Blob31
Blob31

Reputation: 71

Visual Studio Code Snippet Refactoring

I created the following simple Snippet

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Observable Property</Title>
      <Description>Generates an Observable property based on type and Name</Description>
      <Shortcut>nosp</Shortcut>
    </Header>

    <Snippet>
      <Declarations>
        <Literal>
          <ID>PropertyName</ID>
          <ToolTip>Defines the Property Name</ToolTip>
          <Default>Name</Default>
        </Literal>
        <Literal>
          <ID>PropertyType</ID>
          <Type>Type</Type>
          <ToolTip>Defines the Property Type</ToolTip>
          <Default>String</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
        public $PropertyType$ $PropertyName$
        {
            get { return Get<$PropertyType$>("$PropertyName$"); }
            set
            {
                Set("$PropertyName$", value);
            }
        }               
        ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

And its working as expected to create for example

    public VirtualKeyCode Key
    {
        get { return Get<VirtualKeyCode>("Key"); }
        set
        {
            Set("Key", value);
        }
    }

Is it possible to change all $PropertyType$ locations when one of them is changed after the initial insertion of the snippet for example during refactoring ?

Upvotes: 2

Views: 737

Answers (1)

Jeroen Mostert
Jeroen Mostert

Reputation: 28809

No. A snippet is just a quick way to produce text. VS loses all knowledge and context about it once it's inserted. You could, of course, simply insert the snippet anew with the correct type, but there's no way for any refactoring to know the code came from a snippet.

If you're feeling particularly ambitious, you could take a crack at writing a Roslyn extension that tracks which code parts come from snippet variables, and make a snippet-aware refactoring that changes all variable instances. Even so this couldn't work across sessions unless you make snippets tag code with a comment (// snippet: Observable Property), or (if you're feeling really ambitious) you actively match code against snippets whether or not they originally came from snippets, and operate on the matched trees. While powerful, it could lead to surprises if someone is really trying to change only part of the code.

...so the short answer is no.

Upvotes: 2

Related Questions