【问题标题】:Sublime Text 3 Plugin changing run to on_pre_saveSublime Text 3 插件将运行更改为 on_pre_save
【发布时间】:2016-09-08 17:56:59
【问题描述】:

我一直在开发 Sublime Text 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)

然后你只需要运行:

view.run_command('replace')

它将应用编码标准(我计划实施更多但现在我会坚持这些)我希望它在保存时运行。

我尝试将 run(self, edit) 更改为 on_pre_save(self, edit) 但它不起作用。我没有收到任何语法错误,但它不起作用。

谁能告诉我如何让它在保存时运行而不是运行命令?

【问题讨论】:

    标签: python plugins sublimetext3


    【解决方案1】:

    我想到的解决方案是创建一个 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')
    

    希望这段代码对某人有所帮助!

    【讨论】:

      【解决方案2】:

      在 ST3 上,获取 Edit 对象的唯一方法是运行 TextCommand。 (在docs 中,但不是很清楚)。但是,幸运的是,您可以以几乎相同的方式运行该命令。

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

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

      【讨论】:

      • 在看到这个大声笑之前,我真的只是想通了这一点。我已经编写了一个运行命令的 TabsToSpaces/SpacesToTabs 插件。然后我把 2 和 2 放在一起。
      猜你喜欢
      • 2013-12-26
      • 2014-02-13
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 2016-10-02
      相关资源
      最近更新 更多