VS Code snippet to console.log selection beneath current line

荒凉一梦 提交于 2020-01-22 21:30:06

问题


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.




回答2:


I came to this question looking for a solution other than installing a macro extension. Yours can be done with a snippet though as long as the cursor is at the end of your var declaration line. The snippet would use regex:

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

The capturing group (.+?) holds your variable name and is placed in $1. I've tested it (and a good thing, because it took a lot of edits to get a working regex). You'd probably want to set up a key binding in your settings to trigger the snippet (but it also works 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'm trying to alter the current line so it seems I may need a macro to select the line so that it is replaced.



来源:https://stackoverflow.com/questions/44826623/vs-code-snippet-to-console-log-selection-beneath-current-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!