Search code examples
visual-studio-coderefactoringautomated-refactoring

Is there a way I can define a custom refactoring in Visual Studio Code?


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.


Solution

  • 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