开发者

VS 2008 Code Snippet Indentation

In VS 2008, there are XML code snippets that seem to be pretty awesome :) However, it seems that the snippets we creat开发者_StackOverflow社区ed do not indent properly. For example if we have the following code:

{
   ...
   { 
   ...
       {
          InsertSnippet here.

We get something like:

{
   ...
   { 
   ...
       {
          FirstLineofSnippet
SecondLineOfSnippet
ThirdLineOfSnippet

Is there any way to make it so that all lines keep the same indentation?


This usually indicates that the code you are inserting is semantically incorrect - at the time of insert, not when you filled in the snippet values.

To prevent this you can use default values in your snippet to make the snipped syntactivaly correct. E.g. to declare an argument list for a function:

<Literal Editable="true">
    <ID>methodArguments</ID>
    <ToolTip>methodArguments</ToolTip>
    <Default>params object[] args</Default>
    <Function>
    </Function>
</Literal>

The <Default> Element provides the declaration. So using this in a snippet declaring a funciton will lead to this:

public void FunctionName(params object[] args) { }

And it then lets you replace params object[] args with whatever argument declarations you need.


paste the first line without indentation, then select the block and tab until you get the whole block to the indentation you want. AFAIK what you see is the standard behavior and it happens because the location you paste from wasn't indented as far as you wanted.


My unit test snippet appears to be indenting correctly. It may be due to the fact that the code is wrapped in a CDATA block. VisualStudio also tends to auto-format the block as soon as it is added to the code. Does your snippet have as many open braces as closing ones? If the two match up, and the snippet is inserted in a valid/compilable location, it should auto-format.


It seems that Visual Studio does an auto-format on the inserted lines. My snippet wasn't correctly formatted (i.e. indented) either, neither by snippet insertion, nor by manual format (Ctrl-K-F). It contained "delegate{...}", maybe the formatter cannot handle this.


Try swithing from Insert spaces to Keep tabs in Tools > Options > TextEditor > C# > Tabs, it worked for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜