10

It is possible to define custom snippets of code that VS Code can auto complete. These can even use place-holders so that one can fill in the blanks as required.

/* Before */

//=

/* After (for example) */

// [title]
//===============================

What I'm looking for is somewhat the next step up from that, where it can take a selection and replace it with a place-holder that contains that original code (having embedded place-holders is a plus too).

/* Before */
some.code();
where.I = am;
doing = stuff;

/* After (for example) */
some('surrounding code which contains the original code', () => {
  some.code();
  where.I = am;
  doing = stuff;
});

The above is just an example of what I want to achieve - the surrounding code could take any form.

3
  • Great question! You could write a node.js script and hook into selected text. Take a look here: code.visualstudio.com/docs/editor/…. There might be a better way and if you find it let me know! Commented Aug 23, 2023 at 12:29
  • That appears to be the documentation for creating debug configurations, which isn't especially related. Can you give a bit more of a concrete example? Commented Aug 25, 2023 at 7:18
  • Sadly no @Ooker Commented Sep 17, 2023 at 6:10

1 Answer 1

1

You can create snippets to get this kind of behaviour. It would require you to select the text you want to wrap first, and then input some text that represents the refactor. You can include the selection in your snippet body by using the $TM_SELECTED_TEXT variable.

I use the following snippet to quickly wrap and edit a tag in xml. I select text, press g, then tab to autocomplete. Here's the snippet:

"wrap with <g></g>": {
  "scope": "svg, xml",
  "prefix": "g",
  "body": [
     "<g kvg:position=\"$3\"${2: kvg:element=\"$1\"}>",
     "$TM_SELECTED_TEXT",
     "</g>",
  ],
  "description": "<g> wrap",
},

Check out the official documentation for more information on how to create snippets and which variables you can use: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables

Sign up to request clarification or add additional context in comments.

1 Comment

$TM_SELECTED_TEXT works perfectly for my use-case!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.