如何在 ST3 宏中使用 conditions/context?

How to use conditions/context in ST3 macros?

我正在尝试修改 Ctrl+Enter 宏,以便它在编写换行符之前在行尾附加一个分号,类似于 this question。 基本解决方案非常简单

[
    {"command": "move_to", "args": {"to": "hardeol"}},
    {"command": "insert", "args": {"characters": ";\n"}}
]

,但是,它有两个问题:


1)如果eol处已经有分号,则重复分号。有没有一种方法可以包含类似于键绑定的条件 ( preceding_text == ";" )'

{ "key": "preceding_text", "operator": "regex_match", "operand": ";$" } 

并根据宏 运行 使用两个不同的插入命令之一?


2) 事实上,插件 运行 与语言无关,例如,在 html 中也插入分号。同样,有没有一种方法可以根据范围插入分号?

我找到了一个很好的解决方法。我仍然不知道,是否可以在宏本身中添加这种条件,但可以通过在键绑定中添加条件来替代。

首先,用

创建第二个宏 "Packages/User/Add Line Semicolon.sublime-macro"
[
    {"command": "move_to", "args": {"to": "hardeol"}},
    {"command": "insert", "args": {"characters": ";\n"}}
]

在用户键绑定中添加

{ "keys": ["ctrl+enter"], "command": "run_macro_file", "args": {"file": "res://Packages/User/Add Line Semicolon.sublime-macro"}, "context":
    [
        { "key": "following_text", "operator": "not_regex_contains", "operand": ";$", "match_all": false },
        { "key": "selector", "operator": "equal", "operand": "(source.css, source.scss) - comment", "match_all": false },
    ]
},

这会监听与普通 ctrl+enter 相同的键,但会调用新宏并且仅在满足特定条件时触发。

首先,光标后的文本不能以分号结尾。如果行尾已经有分号,则不会触发此绑定,而是将快捷方式传递给默认绑定。请注意,因为它只检查插入符号后的文本,所以如果您的光标已经在行尾,这将不起作用。

其次,插入符号的位置必须有适当的范围。对于这个例子,我只包含了 css 和 scss 文件,它只在你当前不在评论中时匹配。同样,如果条件失败,快捷方式将传递给默认宏。