Search code examples
visual-studio-codecode-snippets

When in snippet mode in VS Code, how can I ONLY move through placeholders using the Tab key without accepting suggestions


Assume I have this sample snippet

  "Sample HTML A snippet": {
    "prefix": "htmla",
    "body": [
      "<a href=\"${1:urlhere}\">${2:Text To Appear}</a>"
    ],
    "description": "Sample HTML A snippet"
  },

When I type "htmla" it is launched

If I happen to type "htmla" again because I want that exact text, and then hit the {Tab} key, I get a snippet within a snippet.

The only way to avoid that is to watch closely if the words I type produce a snippet suggestion and hit {ESC} key to close it.

How to directly move between placeholders using {Tab} key without having the need for that extra step.

i.e. prevent snippet within a snippet?

This is what happens when you type a serious of "htmla{tab}" key

<a href="<a href="<a href="<a href="urlhere">Text To Appear</a>">Text To Appear</a>">Text To Appear</a>">Text To Appear</a>

Solution

  • If the problem is that you're getting quick suggestions while in snippet-mode already, you can take a workaround to just close the suggestions widget opened by the quick-suggestions feature, which you can do by pressing escape. Not ideal, but it'll get you by. Technically, this implies the "give up" solution of just disabling quick-suggestions (see the editor.quickSuggestions setting), but I'll assume that you don't want to do that.

    I can reproduce this behaviour, and it's funny, because at least for the specific case you showed of accepting a snippet suggestion while in snippet mode, from the way that the default { "key": "tab", "command": "insertSnippet", "when": "editorTextFocus && hasSnippetCompletions && !editorTabMovesFocus && !inSnippetMode" }, keybinding is defined, it seems to me like VS Code wants the behaviour you want to be the case. But when I troubleshoot keybindings using the Developer: Toggle Keyboard Shortcuts Troubleshooting command in the command palette, I see that it's actually matching the acceptSelectedSuggestion, when: suggestWidgetHasFocusedSuggestion && suggestWidgetVisible && textInputFocus, source: built-in. keyboard shortcut.

    I suppose you could try to unbind that command and then define a modified version of it where the when clause includes && !inSnippetMode, which would be like this, which you would put into your keybindings.json file (which you can open using the Preferences: Open Keyboard Shortcuts (JSON) command in the command palette):

    { "key": "tab", "command": "-acceptSelectedSuggestion", "when": "suggestWidgetHasFocusedSuggestion && suggestWidgetVisible && textInputFocus" },
    { "key": "tab", "command": "acceptSelectedSuggestion", "when": "suggestWidgetHasFocusedSuggestion && suggestWidgetVisible && textInputFocus && !inSnippetMode" },
    

    I gave that a spin and it seems to work.