【问题标题】:How to automatically add an increased number inside of a string on a new line with SublimeText2 or SublimeText3?如何使用 Sublime Text 2 或 Sublime Text 3 在新行的字符串中自动添加增加的数字?
【发布时间】:2020-07-20 08:47:58
【问题描述】:

我正在编写一些 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(以模式 n*= 开头)并按 ENTER,我希望下一行前面加上 n3=

有没有办法让它发生?

【问题讨论】:

    标签: sublimetext3 sublimetext2 sublimetext sublime-text-plugin


    【解决方案1】:

    插件可以做这种事情。基本上我们想要的是覆盖 enter 的正常行为,当行的开头包含 n*= 时,* 是一个数字。为此,我们需要一个自定义的 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+=)"
            }
        ],
    }
    

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

    这是它的动图:-

    警告是:-

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

    希望这符合您的要求。

    【讨论】:

    • 确实如此!非常感谢您的精彩回答!
    猜你喜欢
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 2019-09-07
    • 2012-08-27
    • 2014-06-15
    • 1970-01-01
    相关资源
    最近更新 更多