Search code examples
phpvisual-studio-codecode-snippets

VSCode Snippet trigger with text before?


I want to create a snippet in VSCode that display the PHP arrow. When I press the key "²" then TAB I want the PHP arrow "->".

Here is my snippet code

"PHP arrow": {
    "prefix": "²",
    "body": "->$0",
    "description": "PHP Arrow ->"
},

It works fine when there is nothing around the "²" char but when I write some code like

$this²

the snippet is not triggered

What can I do ?

Thank you and have a nice day :)

PS: The ² char is oem_7 in VSCode


Solution

  • I don't know what keystrokes you are using to insert the superscript ². But if you are trying to use it as a snippet at the end of a word try making a keybinding instead.

    VSCode has no way of knowing whether that ² is intended to be part of a word or not.

    Try this in your keybindings.json - not in a snippet file:

    {
      "key": "2",
      "command": "editor.action.insertSnippet",
      "when": "resourceExtname == .php",
      "args": {
        "snippet": "->$0"
      }
    }
    

    Typing $this2 yields $this->:

    php snippet demo

    Obviously you will have to replace the 2 key above with whatever you want to use. Now you can use the snippet as part of a word or at the end of a word without any necessary word boundary.