VS 代码片段到当前行下方的 console.log 选择

问题描述 投票:0回答:4

这就是我想要实现的目标(在编辑器中选择t):

片段之前:

var t = 'Foobar';

片段后:

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

我怎样才能做到这一点? 这是我尝试做的:

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

但这只是用片段替换选定的文本。我认为我可以在这里使用 TM_CURRENT_LINE 但我不知道如何处理该行中的剩余文本。

你对此有什么想法吗?也许片段是不可能的?如果可以的话,怎样才能达到想要的效果呢?

谢谢你。

javascript visual-studio-code vscode-extensions
4个回答
9
投票

扩展(在1个按键绑定中执行多个命令)。

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

附注如果您在

snippetWithDescription
的开头添加另一个命令:
"editor.action.addSelectionToNextFindMatch",
,您甚至可以省略选择部分。只需将光标放在单词旁边并按热键即可。


0
投票

我来到这个问题是为了寻找安装宏扩展之外的解决方案。不过,您可以使用片段来完成只要光标位于 var 声明行的末尾。该片段将使用正则表达式:

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

捕获组

(.+?)
保存您的变量名称并放置在
$1
中。我已经测试了它(这是一件好事,因为需要进行大量编辑才能获得有效的正则表达式)。您可能希望在设置中设置一个键绑定来触发代码片段(但也可以输入代码片段前缀):

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

不幸的是,就我而言,我正在尝试更改当前行,因此似乎我可能需要一个宏来选择该行以便将其替换。


0
投票

这对我有用:

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

来自 https://medium.com/@copperfox777/how-to-console-log-variable-under-the-cursor-in-visual-studio-code-ba25feadb00a


0
投票

基于 Alex 的出色回答,我可以通过将以下内容添加到 keybindings.json 来完成工作,而无需使用 VS Code 扩展:

{
    "key": "ctrl+shift+l",
    "command": "runCommands",
    "when": "editorTextFocus",
    "args": {
        "commands": [
            "editor.action.clipboardCopyAction",
            "editor.action.insertLineAfter",
            {
                "command": "editor.action.insertSnippet",
                "when": "editorTextFocus",
                "args": {
                    "snippet": "console.log(\"$CLIPBOARD\", $CLIPBOARD)$0"
                }
            }
        ]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.