要确定响应按键时发生的情况,请使用View > Show Console 或相关键打开 Sublime 控制台,然后输入 sublime.log_commands(True) 以打开命令日志记录,然后执行操作。
在这样做的过程中,你可以看到这样的情况:
.rule {|}
当你按下Enter时,触发的命令是:
command: run_macro_file {"file": "res://Packages/Default/Add Line in Braces.sublime-macro"}
据此,您可以确定密钥绑定到run_macro_file,并且执行此操作的是宏。如果你查看默认的键绑定,键绑定是:
{ "keys": ["enter"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Add Line in Braces.sublime-macro"}, "context":
[
{ "key": "setting.auto_indent", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
{ "key": "preceding_text", "operator": "regex_contains", "operand": "\\{$", "match_all": true },
{ "key": "following_text", "operator": "regex_contains", "operand": "^\\}", "match_all": true }
]
},
也就是说,如果您在打开auto_indent 时按Enter,则选择为空,并且光标位于两个大括号{} 的中间,运行宏,它采取插入多行的步骤。
简单地说,您可以通过关闭auto_indent 来阻止这种情况发生。但是,一般来说这不是一个可行的解决方案,因此您需要在您的 User 包中创建一个键绑定,在相同的情况下不会这样做,而只是执行 enter 会做的事情:
{ "keys": ["enter"], "command": "insert", "args": {"characters": "\n"}, "context":
[
{ "key": "selector", "operator": "equal", "operand": "source.css" },
{ "key": "setting.auto_indent", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
{ "key": "preceding_text", "operator": "regex_contains", "operand": "\\{$", "match_all": true },
{ "key": "following_text", "operator": "regex_contains", "operand": "^\\}", "match_all": true }
]
},
这与上面的绑定相同,但现在 command 只插入一行,并且它还通过 selector 中的 source.css 匹配将自身限制为 CSS 文件。
有了这个,当你在这种情况下按下键时,css 如下所示:
.rule{
|}
编辑
insert 命令的 characters 参数中的文本可以设置为您想要输入的任何文本,因此您可以将其设置为例如"\n\t" 或"\n "(换行符和两个空格)以便在新行上有一点缩进。
为了达到如下效果,需要稍微不同的命令:
.rule {
| }
此处光标前后有空格,因此无法使用insert 命令,因为光标总是在插入的最后一个字符之后结束。
执行此操作的一种方法是创建一个类似于此键的默认绑定已经发生的宏,但另一种方法是insert_snippet 命令。这可以插入一个 sn-p 文件,但它也需要一个参数 contents 直接告诉它 sn-p 内容。
考虑到这一点,上面的键绑定可以表示为:
{ "keys": ["enter"], "command": "insert_snippet", "args": {"contents": "\n\t$0\t"}, "context":
[
{ "key": "selector", "operator": "equal", "operand": "source.css" },
{ "key": "setting.auto_indent", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
{ "key": "preceding_text", "operator": "regex_contains", "operand": "\\{$", "match_all": true },
{ "key": "following_text", "operator": "regex_contains", "operand": "^\\}", "match_all": true }
]
},
insert_snippet展开sn-p文本(包括任何字段,如果提供的话),然后将光标放在$0,如果没有提供则默认到插入内容的末尾。
插入\t 字符会插入一个制表符,除非打开translate_tabs_to_spaces,否则它将是一个物理制表符,在这种情况下,插入将用与tab_size 相同数量的空格替换\t当前设置为。
如果需要,您当然也可以使用特定数量的空格字符。