以下是编写 Sublime Text 2 插件的资源:
- Sublime Text 2 API 参考 http://www.sublimetext.com/docs/2/api_reference.html
- Sublime Text 2 插件示例 http://www.sublimetext.com/docs/plugin-examples
- 如何运行 Sublime Text 2 命令 https://stackoverflow.com/questions/19532204/in-sublime-why-is-def-run-working-in-one-case-and-not-another-case-and-how-can/19533899#19533899
- 设置 Sublime Text 2 自定义键盘快捷键 https://superuser.com/questions/492021/setting-up-sublime-text-2-custom-keyboard-shortcuts
例子:你可以写一个类似的插件,并给它绑定一个热键,即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)