select 文本和新行中 console.log 的热键

Hotkey to select text and console.log in new line

我无意中发现了这段代码,效果很好:https://gist.github.com/harthur/2951063

问题是当我 运行 快捷方式片段时它会破坏语法。它输入 console.log() 内联,从而破坏语法。

例如我想控制台记录变量hello

var hello = 'World';

好吧,上面链接的代码片段会将其变成:

var console.log(hello) = 'World';

这不是我想要的行为。我想要的是:

var hello = 'World';
console.log(hello);

现在,这看起来像是一个多命令,开箱即用我认为 ST3 不支持键绑定中的多命令。我已经研究了插件命令链,但没有成功地让它输出我想要的方式。有人知道解决方案吗?

如果您继续使用 Chain of Command,您可以将键绑定定义为一系列命令。 如果您不知道执行了哪些命令,请打开控制台 ctrl+` 并写入 sublime.log_commands(True) 以显示所有已执行的命令。

那么如何记录你的行为:

  1. 复制当前选择的变量
  2. 转到行尾
  3. 在下一行插入控制台日志片段
  4. 粘贴复制的变量
{
    "keys": ["super+shift+l"],
    "command": "chain",
    "args": {
        "commands": [
            ["copy"],
            ["move_to", {"to": "eol"}],
            ["move_to", {"to": "eol"}],
            ["insert_snippet", {"contents": "\nconsole.log(\" = \" + );[=10=]"}],
            ["paste"]
        ]
    },
    "context":
    [
        { "key": "selector", "operator": "equal", "operand": "source.js" },
        { "key": "selection_empty", "operator": "equal", "operand": false }
    ]
},

另一种方法是编写一个插件以在当前行下方创建一个日志命令。插件具有支持多个光标且不更改剪贴板的优点。按 Tools >>> New Plugin... 并写入:

import itertools
import sublime_plugin

class LogVariableCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        for sel in view.sel():
            if sel.empty():
                continue
            content = view.substr(sel)
            line = view.line(sel)

            # retrieve the current indent
            indent = "".join(itertools.takewhile(lambda c: c.isspace(),
                                                 view.substr(line)))

            view.insert(edit, line.end(),
                        "\n{0}console.log(\"{1} = \" + {1})"
                        .format(indent, content))

要分配键绑定,请使用:

{
    "keys": ["super+shift+l"],
    "command": "log_variable"
}