Sublime Text 3 snippets with date and time as custom variables

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:
        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"} },

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top