VS code snippet to select console.log under current line

This is what I would like to achieve ( t is selected in the editor):

Before the snippet:

var t = 'Foobar';

      

After the snippet:

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

      

How can i do this? Here's what I tried to do:

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

      

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

Do you have any ideas for this? Maybe this is not possible with a snippet? If so, how can I achieve the desired effect?

Thank.

+5


source to share


2 answers


Extenders macros (execution of several commands in 1 keyboard shortcut).

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"
}

      

PS you can even omit part of the selection if you add snippetWithDescription

one more command to the beginning : "editor.action.addSelectionToNextFindMatch",

Just place the cursor next to the word and press the hotkey.

+4


source


I came to this question looking for a solution other than installing a macro extension. You can do this with a snippet even though the cursor is at the end of your var declaration line. The snippet will use a regular expression:

"log_selection": {
    "prefix": "cls",
    "body": [
        "",
        "console.log('${TM_CURRENT_LINE/var (.+?) =.*$/$1', $1/});"
    ],
    "description": "Logs selected text"
}

      

Capture Group (.+?)

Contains the name of your variable and is placed in $1

. I checked this (which is good because it took a lot of edits to get the regex to work). You might want to customize the key bindings in your preferences to trigger the snippet (but it also works by typing the snippet prefix):



    "key": "alt+c alt+l",   // some key combo
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus && !editorHasSelection",
    "args": {
        "langId": "js",   // ?? optional?
        "name": "log_selection"  // your snippet name
    }

      

Unfortunately, in my case, I am trying to change the current line, so I might need a macro to select the line to replace it.

0


source







All Articles