Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS Code snippet to console.log selection beneath current line

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.

like image 951
squidy06 Avatar asked Jun 29 '17 13:06

squidy06


People also ask

How do I create a shortcut for console log?

Pressing CTRL + SHIFT + L will output the console snippet. Also, if you already have text selected it will be put inside the log statement.


1 Answers

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.

like image 146
Alex Avatar answered Sep 29 '22 03:09

Alex