首页 > 解决方案 > 在 Sublime Text 的 Python 3 中使用 f 字符串完成引号

问题描述

当我在 Sublime Text 3 (3176) 中输入引号时,它会自动以右引号完成。

例如我输入"我得到"<cursor>"

这很棒,我现在一直期待它。但是,如果我输入 f 字符串到 Python 中,f"我会得到f"<cursor>而不是f"<cursor>". 无论如何,这不是一个大问题,但它不像我认为的那样流畅。

我认为如果光标左侧有一个字符,则自动完成规则不会添加额外的引号,因为这通常是在您尝试输入右引号时。

有没有办法修改规则,如果左边的字符是“f”,它会输入右引号?当您真正尝试以“f”结尾的字符串结束时,为了避免出现奇怪的用例,可能需要and检查“f”左侧的左括号、空格或等号是否存在print(f"string"foo = f"string"和的高用例foo =f"string"

标签: pythonpython-3.xautocompletesublimetext3

解决方案


是的,这是可能的。只需将以下内容添加到您的用户键盘映射文件(首选项菜单 - > 键绑定。用户键盘映射是右侧的那个):

// Auto-pair quotes even after string modifiers.
// Copied over from the default bindings with modifications to `preceding_text`
// and an added selector condition.
{ "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": "regex_contains", "operand": "(?i)\\b[bfru]+$", "match_all": true },
        { "key": "selector", "operator": "equal", "operand": "source.python" },
        { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.double - punctuation.definition.string.end", "match_all": true }
    ]
},
{ "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": "regex_contains", "operand": "(?i)\\b[bfru]+$", "match_all": true },
        { "key": "selector", "operator": "equal", "operand": "source.python" },
        { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.single - punctuation.definition.string.end", "match_all": true }
    ]
},

这将在未来的 ST 版本中默认提供。

它使用范围选择器来确定插入符号是否已经在字符串中,因此用f字符结束字符串的情况不成问题。


推荐阅读