带有日期和时间作为自定义变量的 Sublime Text 3 片段

Sublime Text 3 snippets with date and time as custom variables

我正在尝试使用自定义环境变量在 sublime text 3 中制作自定义片段。

我基本上想在我的代码片段中包含今天的日期,但没有官方支持此环境变量。

我已经尝试了很多堆栈溢出的解决方案,但都无法完成。他们中的大多数已经过时了。

请帮帮我。

您不能使用 Sublime Text 代码段完全做到这一点。

我建议您看一下 Package Control.[=21= 上 InsertDate plugin 的文档中非正式称为 Snippet Macro 的内容]

InsertDate 插件的作者 FichteFoll 建议创建一个宏来插入代码段,然后自动移动代码段字段以插入日期。下面是来自插件页面的 FichteFoll 示例宏。您可以复制并粘贴它并将其保存在您的 User 文件夹中作为 DateSnippet.sublime-macro

[
    { "command": "insert_snippet", "args": {"contents": "Date: \nTime: \nSomething else: [=10=]"} },
    { "command": "insert_date", "args": {"format": "%x"} },
    { "command": "next_field" },
    { "command": "insert_date", "args": {"format": "%X"} },
    { "command": "next_field" }
]

insert_date 命令明确要求安装 InsertDate 插件。使用 Package Control 安装它或使用像下面我出于类似原因编写的轻量级插件,可以使用 insert_todays_date 命令调用(参见 如何设置或查找 Sublime Text 插件的命令名称 ).

import sublime, sublime_plugin, time
class InsertTodaysDateCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # The date/time field codes for strftime() are at this url:
        # https://docs.python.org/3/library/time.html#time.strftime
        date_today = time.strftime("%Y-%m-%d")
        for sel in self.view.sel():
            self.view.insert(edit, sel.begin(), date_today)

对于 运行 您可以从 Sublime Text 菜单 Tools --> Macros 调用的宏,为其创建一个 命令面板 条目,或者只添加一个像这样的键绑定:

{ "keys": ["ctrl+shift+y"], "command": "run_macro_file", "args": {"file": "res://Packages/User/DateSnippet.sublime-macro"} },