脚本搜索&替换Sublime Text中的操作

时间:2013-11-14 07:27:22

标签: sublimetext2

我经常发现自己在做重复文件&替换文件中的操作。通常归结为修复查找和替换操作;删除一些行,更改一些总是相同的字符串等等。

在Vim中,这是一个不费脑子的事,

function! Modify_Strength_Files()
    execute':%s/?/-/'
    execute':%s/Ä/-/'
    "--------------------------------------------------------
    execute':%s/Ä/-/'
    execute':%s///g'
    "--------------------------------------------------------
    execute':g/Version\ of\ Light\ Ship/d'
    execute':g/Version\ of\ Data\ for\ Specific\ Regulations/d'
    "--------------------------------------------------------
    " execute':g/LOADING\ CONDITION/d'
    " execute':g/REGULATION:\ A\.562\ IMO\ Resolution/d'

    " This is to reduce multiple blank lines into one.
    execute ':%s/\s\+$//e'
    execute ':%s/\n\{3,}/\r\r/e'
    " ---------------------
endfunction

逐字复制。

如果可以在Sublime Text编辑器中定义这样的函数,如果它可以完成,然后调用以对当前打开的文件进行操作,那该怎么办?

1 个答案:

答案 0 :(得分:8)

以下是编写Sublime Text 2插件的资源:

  1. Sublime Text 2 API Reference
  2. Sublime Text 2 Plugin Examples
  3. How to run Sublime Text 2 commands
  4. Setting up Sublime Text 2 Custom Keyboard Shortcuts
  5. 示例:您可以编写类似的插件并将热键绑定到它,即batch_edit命令。然后,您可以打开文件并通过该热键执行命令。顺便说一句,在这个脚本中,我没有考虑文件编码。您可以通过self.view.encoding()获取文件编码。

    # -*- coding: utf-8 -*-
    
    import sublime, sublime_plugin
    
    import re
    
    class BatchEditCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            self._edit = edit
            self._replace_all(r"\?", "-")
            self._replace_all(u"Ä", "-")
            self._delete_line_with(r"Version of Light Ship")
            self._delete_line_with(r"Version of Data for Specific Regulations")
            self._replace_all(r"(\n\s*\n)+", "\n\n")
    
        def _get_file_content(self):
            return self.view.substr(sublime.Region(0, self.view.size()))
    
        def _update_file(self, doc):
            self.view.replace(self._edit, sublime.Region(0, self.view.size()), doc)
    
        def _replace_all(self, regex, replacement):
            doc = self._get_file_content()
            p = re.compile(regex, re.UNICODE)
            doc = re.sub(p, replacement, doc)
            self._update_file(doc)
    
        def _delete_line_with(self, regex):
            doc = self._get_file_content()
            lines = doc.splitlines()
            result = []
            for line in lines:
                if re.search(regex, line, re.UNICODE):
                    continue
                result.append(line)
            line_ending = {
                "Windows" : "\r\n",
                "Unix"    : "\n",
                "CR"      : "\r"
            }[self.view.line_endings()]
            doc = line_ending.join(result)
            self._update_file(doc)