自定义' console.log'插件Sublime Text 3

时间:2017-08-31 14:06:24

标签: python plugins sublimetext3

我做了很多JavaScript项目,我错过了PHPStorm的一个很棒的功能。现在我不太了解Python。希望你能帮助我。

这就是我想要的:

'test'.log => console.log('test');
test.log => console.log(test);

使用单个tabtrigger .log

我想在.log之前检索任何内容。然后我会改变它。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

您可以创建一个插件来检索.log之前的文本并将其替换为视图:

import re

import sublime
import sublime_plugin


class PostSnippetLogCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        for sel in view.sel():
            pos = sel.b
            text_before = view.substr(sublime.Region(view.line(pos).a, pos))

            # match the text before in reversed order
            m = re.match(r"gol\.(\S*)", text_before[::-1])
            if not m:
                continue
            # retrieve the text before .log and reestablish the correct order
            text_content = m.group(1)[::-1]
            # create the replacements text and region
            replace_text = "console.log({});".format(text_content)
            replace_reg = sublime.Region(pos - len(m.group(0)), pos)
            # replace the text
            view.replace(edit, replace_reg, replace_text)

然后添加此键绑定以在javascript文档中以.log作为前缀时触发该命令。

{
    "keys": ["tab"],
    "command": "post_snippet_log",
    "context":
    [
        { "key": "selector", "operand": "source.js" },
        { "key": "preceding_text", "operator": "regex_contains", "operand": "\\.log$" },
    ],
},