sublimetext3 - 如何使用 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=
有没有办法让它发生?
解决方案
插件可以做这种事情。基本上,我们想要的是覆盖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+=)"
}
],
}
我不会详细介绍这个插件的工作原理。完成这项工作所需要做的就是遵循本要点中给出的说明。
这是它的动图:-
- 它不尊重
[ips]
您的请求,因为我认为这会使插件变得不必要地复杂。 - 它只查看当前行,查看
n
&=
& 之间的数字会相应地为下一行增加它。所以这条线是否已经存在并不明智。
希望这能满足您的要求。
推荐阅读
- c++ - 可变参数模板,范围,C++
- linux - 在 Bash/Shell 脚本中使用正则表达式搜索特定字符串
- awk - 为什么访问 awk 数组的不存在元素会创建此元素?
- android - Android - 双击主页按钮作为默认操作
- php - PHP,使用 xpath 获取里面的所有 svg
- wordpress - Disqus iframe 透明度在 Chrome 87 上不起作用
- mysql - MySQL Workbench 错误,用户和权限页面丢失
- javascript - 将表搜索限制为 Javascript ArrayObjects 中的某些动态键值
- dns - 有没有办法使用 okhttp 为每个请求指定不同的 DNS 查找?
- python - 无法在 GCP 虚拟机实例上导入模块