如何使用SublimeText2或SublimeText3在新行的字符串内自动添加增加的数字?

问题描述 投票:0回答:1

我正在研究某些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个回答
1
投票

一个插件可以做这种事情。基本上,我们希望的是在行的开头包含n*=的情况下覆盖[[enter的常规行为,其中*是数字。为此,我们需要实现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中给出的说明。

这是它的动态效果:-

enter image description here注意事项是:-

    [它不尊重您请求的[ips]部分,因为我认为这会使插件变得不必要地复杂。
  1. 它只是看当前行,请参见n=之间的数字并为下一行相应地增加它。因此,是否存在这样的行并不明智。
  • 希望这符合您的要求。
  • © www.soinside.com 2019 - 2024. All rights reserved.