I am trying to make a custom snippet in sublime text 3 with custom environment variables.
I essentially want to include today's date in my snippet, but there is no official support for this environment variable.
I have tried many solutions from the stack overflow, but unable to get it done. Most of them are outdated.
Please help me.
You can not do exactly that with a Sublime Text snippet.
I suggest you take a look at what is informally called a Snippet Macro
in the documentation of the InsertDate plugin on Package Control.
The InsertDate plugin's author, FichteFoll, suggests the creation of a macro to insert a snippet and which then automatically moves snippet fields to insert the date. Below is FichteFoll's example macro from the plugin's page. You could copy'n'paste it and save it in your User
folder as DateSnippet.sublime-macro
.
[
{ "command": "insert_snippet", "args": {"contents": "Date: $1\nTime: $2\nSomething else: $0"} },
{ "command": "insert_date", "args": {"format": "%x"} },
{ "command": "next_field" },
{ "command": "insert_date", "args": {"format": "%X"} },
{ "command": "next_field" }
]
The insert_date
command clearly requires the InsertDate plugin to have been installed. Install that using Package Control or use a plugin as lightweight as the one below that I wrote for a similar reason, which can be called with the insert_todays_date
command (see How to set or find the command name of a Sublime Text plugin here).
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)
To run the macro you could call it from the Sublime Text menu Tools --> Macros
, create a Command Palette entry for it, or just add a key binding with something like this:
{ "keys": ["ctrl+shift+y"], "command": "run_macro_file", "args": {"file": "res://Packages/User/DateSnippet.sublime-macro"} },