y0mbo
y0mbo

Reputation: 4602

Replace text in a Visual Studio Code Snippet Literal

Is it possible to replace text in a Visual Studio Snippet literal after the enter key is pressed and the snippet exits its edit mode?

For example, given a snippet like this:

 public void $name$
 {
   $end$
 }

If I were to enter $name$ as:

 My function name

is it possible to have Visual Studio change it to:

 My_function_name

or

 MyFunctionName

Upvotes: 7

Views: 6432

Answers (3)

chantey
chantey

Reputation: 5837

In my case the goal was to replace a single instance of the word Authoring with Baker:

${TM_FILENAME_BASE/(Authoring)/Baker/}

Upvotes: 2

BPH
BPH

Reputation: 536

It's great. I used it to wrap things in a function with quotes. If a selection has quotes it can remove the quotes. In the snippet part, it seems to break down into:

TM_SELECTED_TEXT - this is the input
[ ' '] - regex find
_ - regex replace
gi - global flag for regex

So what I wanted is change: "User logged in" into: <%= gettext("User logged in") %> For this in the snippet I used:

"body": ["<%= gettext(\"${TM_SELECTED_TEXT/['\"']//gi}\") %>"],

Note: you need to escape the quotein the regular expression, therefore: " becomes \".

Upvotes: 1

MincedMeatMole
MincedMeatMole

Reputation: 571

After many years there is an answer, for anyone still coming across this question:

"Replace Whitespaces": {
    "prefix": "wrap2",
    "body": [
        "${TM_SELECTED_TEXT/[' ']/_/gi}",
    ],
    "description": "Replace all whitespaces of highlighted Text with underscores"
},

Add this to your user snippets. Or alternativly you can add a keyboard shortcut like this:

{
    "key": "ctrl+shift+y",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
        "snippet": "${TM_SELECTED_TEXT/[' ']/_/gi}"            
    }
},

Hope this helps anyone coming across this in the future

Upvotes: 11

Related Questions