2016-05-12 78 views
0

我一直在研究一個Sublime Text 3插件,它修復了我在工作時的一些編碼標準(我有一個錯誤的缺陷)我現在有一個運行命令控制檯。 Most of the code was originally from this thread.Sublime Text 3插件更改運行到on_pre_save

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),但它不起作用。我沒有得到任何語法錯誤,但它不起作用。

任何人都可以告訴我如何使這個節省運行,而不必運行命令?

回答

3

在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') 
+0

在我看到這個笑之前,我簡直就明白了這一點。我已經編寫了一個運行命令的TabsToSpaces/SpacesToTabs插件。然後我把2和2放在一起。 – Snowdrama

0

我來到解決方案是創建一個運行命令我前面列出的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') 

希望這代碼可以幫助別人!