Scripting find & replace operations in Sublime Tex

2019-05-16 17:24发布

问题:

Often I find myself doing repetitive file & replace operations in a file. Most often that comes down to fixed find and replace operations; deleting some lines, changing some strings that are always the same and so on.

In Vim that is a no-brainer,

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

copied verbatim.

How could a function like this be defined in Sublime Text editor, if it can be done at all, and then called to act upon the currently opened file?

回答1:

Here are resources to write Sublime Text 2 plugins:

  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

Example: you can write a similar plugin and bind a hot key to it, that is, batch_edit command. Then you can open a file and execute the command via that hot key. By the way, in this script, I didn't consider the file encoding. You can get the file encoding via 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)