Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 200
y0mbo Avatar asked Oct 20 '09 17:10

y0mbo


2 Answers

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

like image 149
MincedMeatMole Avatar answered Sep 23 '22 05:09

MincedMeatMole


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 \".

like image 34
BPH Avatar answered Sep 23 '22 05:09

BPH