Visual Studio Code snippet as keyboard shortcut key

前端 未结 2 1819
梦如初夏
梦如初夏 2020-12-24 03:03

I know how to modify and create code snippets and I know how to modify shortcut keys, but how does one bring those 2 together?

2条回答
  •  长情又很酷
    2020-12-24 04:05

    Note that the line below will open a list of snippets defined for the language you are currently using (and you don't want that)

    "args": { "snippet": "'$TM_SELECTED_TEXT'" }
    

    Whereas with the below line the snippet given as argument will be executed right away

    "args": { "name": "your_snippets_name" }
    

    Here's how I defined a snippet for HTML where I wanted to select a text and when pressing CTRL+B the text to become enclosed in tags:

    "make_strong": {
        "prefix": "strong",
        "body": [
            "$TM_SELECTED_TEXT${1:}"
        ],
        "description": "Encloses selected text in  tags"
    }
    

    Note the ${1:} above - what this does is that it places the cursor there. This enables you to press CTRL+B at cursor and then have the cursor placed inside the tags. When selecting a string and pressing CTRL+B, the string will be placed between tabs and the cursor will be placed before the closing tag. Pressing TAB at this point, will put your cursor after the closing tag.

    And added in my keybindings.json the following:

    {
        "key": "ctrl+b",
        "command": "editor.action.insertSnippet",
        "args": { "name": "make_strong" }
    }
    

提交回复
热议问题