我试图在 Sublime 中定义一个按键绑定(bind),让它自动配对美元符号“$”,就像它自动配对以下符号一样:
- “
- (
- [
- {
- '
我打开了默认的键盘映射文件并添加了以下代码:
// Auto-pair dollar signs
{ "keys": ["\$"], "command": "insert_snippet", "args": {"contents": "\$$0\$"}, "context":
[
{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
{ "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|\\}|>|$)", "match_all": true },
{ "key": "preceding_text", "operator": "not_regex_contains", "operand": "[\$a-zA-Z0-9_]$", "match_all": true },
{ "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.double", "match_all": true }
]
},
{ "keys": ["\$"], "command": "insert_snippet", "args": {"contents": "\$${0:$SELECTION}\$"}, "context":
[
{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true }
]
},
{ "keys": ["\$"], "command": "move", "args": {"by": "characters", "forward": true}, "context":
[
{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
{ "key": "following_text", "operator": "regex_contains", "operand": "^\$", "match_all": true }
]
},
{ "keys": ["backspace"], "command": "run_macro_file", "args": {"file": "Packages/Default/Delete Left Right.sublime-macro"}, "context":
[
{ "key": "setting.auto_match_enabled", "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 }
]
},
注意转义的美元符号\$。在编辑器中,它们以红色突出显示,当我尝试保存文件时,收到无效转义错误消息。转义美元符号的正确方法是什么?
最佳答案
注意逃生
您将在这里经历两层编程。首先是 Python,然后是 JSON。所以,你的转义美元符号实际上需要转义两次:
"args": {"contents": "\\$$0\\$"}
Sublime Text 读取设置文件后,Python 会去掉第一个转义,留下以下 JSON 表示
"args": {"contents": "\$$0\$"}
然后,一旦 JSON 被解析,你最终会得到
"args": {"contents": "$$0$"}
不要逃避击键
您不需要在 keys
列表中转义 $
。击键是一个字面上的美元符号,因此不需要转义
第一个设置应如下所示:
{ "keys": ["$"], "command": "insert_snippet", "args": {"contents": "\\$$0\\$"}, "context":
[
{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
{ "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|\\}|>|$)", "match_all": true },
{ "key": "preceding_text", "operator": "not_regex_contains", "operand": "[\\$a-zA-Z0-9_]$", "match_all": true },
{ "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.double", "match_all": true }
]
},
关于autocomplete - Sublime Text 2 : trying to escape the dollar sign,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34115090/