需编写Python插件命令实现,因.sublime-snippet仅支持静态变量如$CURRENT_YEAR,不支持strftime等动态时间格式化,且无时分秒、前导零及时区控制。

怎么用 Sublime 的 insert_snippet 插入动态当前时间
Sublime 本身不支持 snippet 中直接执行 Python 时间函数,但可以通过插件或命令扩展实现。原生 snippet(.sublime-snippet)只能做静态文本替换,$CURRENT_YEAR、$CURRENT_MONTH 等变量仅限于少数预定义字段,且不支持格式化(比如“2024-05-21 14:32”这种完整时间戳)。
真正可行的路径是:写一个 Python 插件命令,调用 view.run_command('insert_snippet', {...}) 或直接 view.insert() 写入格式化后的时间字符串。
- 新建插件文件:
Preferences → Browse Packages → User,在该目录下新建insert_datetime.py - 内容示例(支持 ISO 格式和中文格式双键绑定):
import sublime import sublime_plugin import datetime class InsertDatetimeCommand(sublime_plugin.TextCommand): def run(self, edit, format_type="iso"): now = datetime.datetime.now() formats = { "iso": now.strftime("%Y-%m-%d %H:%M:%S"), "cn": now.strftime("%Y年%m月%d日 %H时%M分%S秒") } text = formats.get(format_type, formats["iso"]) for region in self.view.sel(): self.view.replace(edit, region, text) - 保存后,在
Key Bindings中添加快捷键:[{"keys": ["ctrl+alt+t"], "command": "insert_datetime", "args": {"format_type": "iso"}}, {"keys": ["ctrl+alt+shift+t"], "command": "insert_datetime", "args": {"format_type": "cn"}}]
为什么不能直接在 .sublime-snippet 里用 strftime
因为 .sublime-snippet 是纯 XML 模板,解析器只识别 $TM_SELECTED_TEXT、$SELECTION、$CURRENT_YEAR 这类内置变量,不执行任何代码。试图写 $${import datetime; datetime.now().strftime(...)} 会原样输出,甚至破坏 snippet 解析。
-
$CURRENT_YEAR等变量只在部分版本中可用(Sublime Text 4+),且无时分秒 - 即使加上
$CURRENT_HOUR,也无法拼接成带前导零的09:05(它返回的是9和5) - 所有时间相关变量都不支持时区控制或自定义格式字符串
如何让自定义命令支持光标定位和多光标插入
上面的 InsertDatetimeCommand 已经用了 self.view.sel() 遍历所有选区,天然支持多光标。如果想插入后把光标留在时间末尾(方便继续输入),需额外调用 view.sel().clear() 和 view.sel().add():
- 在
self.view.replace(edit, region, text)后加:new_pos = region.begin() + len(text) view.sel().clear() view.sel().add(sublime.Region(new_pos))
- 注意:如果用户有多个选区,要对每个
region单独计算新位置,否则光标会全部跳到最后一处 - 若希望「没选中时插入在光标处,选中时替换选中内容」,原逻辑已满足——
region就是当前选区,长度为 0 时就是光标点
插件 vs 宏:哪种更适合时间插入场景
宏(.sublime-macro)无法生成动态值,只能回放固定按键,所以不适合时间插入;而插件可调用 Python 标准库,灵活性高,但需要重启或重载插件(Ctrl+Shift+P → Satisfy Dependencies 或手动 Tools → Developer → Reload Plugin)。
- 调试技巧:在插件里加
print(),查看 Sublime 控制台(Ctrl+`)输出 - 常见报错
AttributeError: 'NoneType' object has no attribute 'replace',通常是因为edit对象未正确传入run()方法 - 不要在插件里用
time.sleep()或阻塞操作,会卡住 UI
时间格式逻辑写死在插件里最稳;如果未来要频繁改格式,可以抽成配置项读取 Preferences.sublime-settings,但多数人改一次就不再动了。










