VS Code snippet to console.log selection beneath c

2019-05-13 21:03发布

问题:

This is what I'd like to achieve (t is selected in editor):

Before snippet:

var t = 'Foobar';

After snippet:

var t = 'Foobar';
console.log('t', t);

How can I do that? Here is what I tried to do:

"log_selection": {
    "prefix": "cls",
    "body": [
        "console.log('$TM_SELECTED_TEXT', $TM_SELECTED_TEXT);"
    ],
    "description": "Logs selected text"
}

But this just replace selected text with snippet. I think that I could use TM_CURRENT_LINE here but I have no idea what to do with remaining text in the line.

Do you have any idea for this? Maybe it's impossible with snippet? If so, how can I achieve desired effect?

Thank you.

回答1:

Extension macros (executing multiple commands in 1 keybinding).

settings.json:

"macros": {
    "snippetWithDescription": [
        "editor.action.clipboardCopyAction",
        "editor.action.insertLineAfter",
        {
            "command": "editor.action.insertSnippet",
                "when": "editorTextFocus",
                "args": {
                    "snippet": "console.log('$CLIPBOARD', $CLIPBOARD)$0"
                }
        }
    ]
}

keybindings.json:

{
    "key": "ctrl+shift+;",
    "command": "macros.snippetWithDescription"
}

P.S. you can even omit the selection part if you add another command at the beginning of snippetWithDescription: "editor.action.addSelectionToNextFindMatch",. Just place cursor beside the word and hit hotkey.