Search code examples
visual-studio-codevscode-snippets

VS Code snippet interprets variable as string


I'm writing a snippet in VS Code using variable transforms. I want to replace a pattern that occurs in some text (in this case text copied on the clipboard) with a variable that inserts the name of the file without extensions (for example: CurrentFileNameWithoutExtensions). What happens is the pattern gets replaced with the variable name as a string, and not the value of the variable.

Here's the snippet:

"${CLIPBOARD/pattern/$TM_FILENAME_BASE/}"

The output is: "pattern" becomes "$TM_FILENAME_BASE".
The correct output would be: "pattern" becomes "CurrentFileNameWithoutExtensions".

A possible solution to this could be outputting all the clipboard text before the pattern, then the variable, and finally all the clipboard text after the pattern. How would this be done?

Example clipboard text:

Text that is before pattern in clipboard.
pattern
Text that is after pattern in clipboard.

The snippet could capture all text until the pattern and output it:

Text that is before pattern in clipboard.

Then it would output the variable $TM_FILENAME_BASE:

CurrentFileNameWithoutExtensions

Finally it would output the text after the pattern:

Text that is after pattern in clipboard.

The output would look like this put together:

Text that is before pattern in clipboard.
CurrentFileNameWithoutExtensions
Text that is after pattern in clipboard.

Solution

  • If there is always a matching pattern, then this works:

    "pattern": {
        "prefix": "_pt",
        "body": [
          "${CLIPBOARD/(.*[\r\n]*)((pattern)([\r\n]*))(.*)/$1/}$TM_FILENAME_BASE${CLIPBOARD/(.*[\r\n]*)((pattern)([\r\n]*))(.*)/$4$5/}"
    
        ],
        "description": "clipboard pattern"
    }
    

    This handles any number of newlines as in

    first text
    pattern
    second text
    

    or

    first text
    
    pattern
    
    
    second text
    

    or

    first textpatternsecond text
    

    See regex101 demo

    Of course, as rioV8 points out, if pattern also matches in the text somewhere in addition to the middle that is a problem.