首页 > 解决方案 > 如何使用 SublimeText2 或 SublimeText3 在新行的字符串中自动添加增加的数字?

问题描述

我正在处理一些 mIRC 脚本,该脚本需要在每一行上添加一个前置字符串,如果有的话,后面跟着一个从前一行中包含的数字增加的行号。

例子:

[ips]

[urls]
n0=1:mIRC NewsURL:http://www.mirc.com/news.html
n1=2:mIRC RegisterURL:http://www.mirc.com/register.html
n2=3:mIRC HelpURL:http://www.mirc.com/help.html

所以,如果我在第一行:([ips]不以模式开头n*=)并且我按ENTER,我希望下一行前面加上n0=

但是,如果我在最后一行n2=3:mIRC HelpURL:http://www.mirc.com/help.html(以 pattern 开头n*=)并且按ENTER,我希望下一行前面加上n3=

有没有办法让它发生?

标签: sublimetext3sublimetext2sublimetextsublime-text-plugin

解决方案


插件可以做这种事情。基本上,我们想要的是覆盖entern*=开头包含*数字时的正常行为。为此,我们需要一个自定义EventListener来实现一个on_query_context方法和一个在满足上下文时运行的自定义命令。

import re
import sublime
import sublime_plugin

class MrcScriptEventListener(sublime_plugin.EventListener):
    """ A custom event listener that implements an on_query_context method which checks to see if
        the start of the line if of the form n*= where * = number.  
    """

    def on_query_context(self, view, key, operator, operand, match_all):
        current_pt = view.sel()[0].begin()
        desired = view.substr(view.line(view.sel()[0].begin()))

        if key != "mrc_script":
            return None 

        if operator != sublime.OP_REGEX_MATCH:
            return None

        if operator == sublime.OP_REGEX_MATCH:
            return re.search(operand, desired)

        return None


class MrcScriptCommand(sublime_plugin.TextCommand):
    """ A custom command that is executed when the context set by the MrcScript event listener
        is fulfilled.  
    """

    def run(self, edit):
        current_line = self.view.substr(self.view.line(self.view.sel()[0].begin()))
        match_pattern = r"^(n\d+=)"
        if re.search(match_pattern, current_line):
            num = int(re.match(match_pattern, current_line).groups()[0][1:-1]) + 1
            self.view.run_command("insert", {
                    "characters": "\nn{}=".format(num)
            })
        else:
            return

键绑定如下:-

{
    "keys": ["enter"],
    "command": "mrc_script",
    "context": [
        {
            "key": "mrc_script",
            "operator": "regex_match",
            "operand": "^(n\\d+=)"
        }
    ],
}

我不会详细介绍这个插件的工作原理。完成这项工作所需要做的就是遵循本要点中给出的说明。

这是它的动图:-

在此处输入图像描述 警告是: -

  1. 它不尊重[ips]您的请求,因为我认为这会使插件变得不必要地复杂。
  2. 它只查看当前行,查看n& =& 之间的数字会相应地为下一行增加它。所以这条线是否已经存在并不明智。

希望这能满足您的要求。


推荐阅读