Sublime Text 3插件将运行更改为

2024-06-02 05:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在致力于一个崇高的文本3插件,修复了我在工作中的一些编码标准(我有一个坏习惯丢失),我目前有一个命令运行在控制台这个工作。Most of the code was originally from this thread.

import sublime, sublime_plugin

class ReplaceCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        #for each selected region
        region = sublime.Region(0, self.view.size())
        #if there is slected text
        if not region.empty():
            #get the selected region
            s = self.view.substr(region)

            #perform the replacements
            s = s.replace('){', ') {')
            s = s.replace('}else', '} else')
            s = s.replace('else{', 'else {')

            #send the updated string back to the selection
            self.view.replace(edit, region, s)

然后你只需要跑:

^{pr2}$

它将应用编码标准(还有更多的我计划实现,但现在我将坚持这些),我希望这个运行在save上。在

我试着把run(self,edit)改为on_pre_save(self,edit),但是不起作用。我没有发现任何语法错误,但它就是不起作用。在

有谁能告诉我如何在save上运行而不必运行命令吗?在


Tags: therun命令selfviewifsaveedit
2条回答

我的解决方案是创建一个on_pre_save()函数,该函数运行我前面列出的命令:

import sublime, sublime_plugin
class ReplaceCodeStandardsCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        #for each selected region
        region = sublime.Region(0, self.view.size())
        #if there is slected text
        if not region.empty():
            #get the selected region
            s = self.view.substr(region)

            #perform the replacements
            s = s.replace('){', ') {')
            s = s.replace('}else', '} else')
            s = s.replace('else{', 'else {')

            #send the updated string back to the selection
            self.view.replace(edit, region, s)

class ReplaceCodeStandardsOnSave(sublime_plugin.EventListener):
    # Run ST's 'unexpand_tabs' command when saving a file
    def on_pre_save(self, view):
        if view.settings().get('update_code_standard_on_save') == 1:
            view.window().run_command('replace_code_standards')

希望这段代码能帮助别人!在

在ST3上,获得Edit对象的唯一方法是运行TextCommand。(在docs中,但它们不是很清楚)。但是,幸运的是,您可以像以前一样运行命令。在

事件处理程序,如on_pre_save,只能在^{}上定义。向on_pre_save()事件传递了一个视图对象,因此您只需要添加类似这样的内容,这将启动您已经编写的命令。在

class ReplaceEventListener(sublime_plugin.EventListener):
    def on_pre_save(self, view):
        view.run_command('replace')

相关问题 更多 >