29

I want to create a snippet that will add a file comment, but I want the snippet to create the DateTime automatically. Can a sublime snippet do that?

<snippet>
    <content><![CDATA[
/**
 * Author:      $1
 * DateTime:    $2
 * Description: $3
 */

]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>/header</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.css,source.js,source.php</scope>
</snippet>
Matt York
  • 15,981
  • 7
  • 47
  • 51
aisensiy
  • 1,460
  • 3
  • 26
  • 42

7 Answers7

100

Tools > New Plugin

Paste this:

import datetime, getpass
import sublime, sublime_plugin
class AddDateCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("insert_snippet", { "contents": "%s" %  datetime.date.today().strftime("%d %B %Y (%A)") } )

class AddTimeCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("insert_snippet", { "contents": "%s" %  datetime.datetime.now().strftime("%H:%M") } )

Save it as ~/Library/Application Support/Sublime Text 2/Packages/User/add_date.py

Then, in Preferences > Key Bindings - User , add:

{"keys": ["ctrl+shift+,"], "command": "add_date" },
{"keys": ["ctrl+shift+."], "command": "add_time" },

You can customize the argument passed to strftime to your liking.

nachocab
  • 13,328
  • 21
  • 91
  • 149
  • 3
    @aisensiy you might want to change the accepted answer – nachocab Nov 21 '14 at 14:07
  • 2
    @aisensiy: this REALLY should be the accepted answer man. You need to change that! Thanks @nachocab! – Gus Dec 18 '14 at 15:43
  • 5
    Note that this is a macro and doesn't answer @aisensiy's question. They want a snippet that has today's date. As opposed to a macro that generates a snippet without todays date. – TheMightyLlama Oct 01 '16 at 18:22
  • Note that plugin files must be saved directly under User, not a subdirectory, unlike snippets and themes. – twhb Jan 10 '19 at 21:21
  • This isn't working for me on Sublime Text 3, anyone having the same problem and know a way around it? Positive that I made the changes exactly as listed and saved the files to the right spots. Maybe the syntax changed. – rer Mar 29 '19 at 15:06
13

Nachocab, that was a GREAT answer - and helped me VERY much. I created a slightly different version for myself

~/Library/Application Support/Sublime Text 2/Packages/User/datetimestamp.py:

import datetime, getpass
import sublime, sublime_plugin

class AddDateTimeStampCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("insert_snippet", { "contents": "%s" %  datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") } )

class AddDateStampCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("insert_snippet", { "contents": "%s" %  datetime.datetime.now().strftime("%Y-%m-%d") } )

class AddTimeStampCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("insert_snippet", { "contents": "%s" %  datetime.datetime.now().strftime("%H:%M:%S") } )

Preferences > Key Bindings - User:

{"keys": ["super+alt+ctrl+d"], "command": "add_date_time_stamp" },
{"keys": ["super+alt+d"], "command": "add_date_stamp" },
{"keys": ["super+alt+t"], "command": "add_time_stamp" }

I wouldn't have been able to do this without your help! I scoured google for about an hour now and finally was graced by your answer! Thank's so much!

Jeremy Iglehart
  • 4,281
  • 5
  • 25
  • 38
5

You might want to check the InsertDate package: https://github.com/FichteFoll/InsertDate

In the readme you can find an example of how you can use macros to insert timestamps into snippets.

FichteFoll
  • 663
  • 1
  • 6
  • 12
4

I just implement this function (on sublime3) by a simple plugin and the metadata file (.tmPreference file), but I don't know whether this is efficient. There is the way,

1. create a .tmPreference file, put some variables you want to use in snippets. There is an example, you can save the cotent in Packages/User/Default.tmPreference

<plist version="1.0">
<dict>
    <key>name</key>
    <string>Global</string>
    <key>scope</key>
    <string />
    <key>settings</key>
    <dict>
        <key>shellVariables</key>
        <array>
            <dict>
                <key>name</key>
                <string>TM_YEAR</string>
                <key>value</key>
                <string>2019</string>
            </dict>
            <dict>
                <key>name</key>
                <string>TM_DATE</string>
                <key>value</key>
                <string>2019-06-15</string>
            </dict>
            <dict>
                <key>name</key>
                <string>TM_TIME</string>
                <key>value</key>
                <string>22:51:16</string>
            </dict>
        </array>
    </dict>
</dict>
</plist>

2. create a plugin, which will update the shell variables in .tmPreference file when the plugin loaded.

import sublime, sublime_plugin
import time
from xml.etree import ElementTree as ET

# everytime when plugin loaded, it will update the .tmPreferences file.
def plugin_loaded():
    # res = sublime.load_resource('Packages/User/Default.tmPreferences')
    # root = ET.fromstring(res)
    meta_info = sublime.packages_path() + '\\User\\Default.tmPreferences'
    tree = ET.parse(meta_info)
    eles = tree.getroot().find('dict').find('dict').find('array').findall('dict')

    y = time.strftime("%Y", time.localtime())
    d = time.strftime("%Y-%m-%d", time.localtime())
    t = time.strftime("%H:%M:%S", time.localtime())

    for ele in eles:
        kvs = ele.getchildren()
        if kvs[1].text == 'TM_YEAR':
            if kvs[3].text != y:
                kvs[3].text = y
                continue
        elif kvs[1].text == 'TM_DATE':
            if kvs[3].text != d:
                kvs[3].text = d
                continue
        elif kvs[1].text == 'TM_TIME':
            if kvs[3].text != t:
                kvs[3].text = t
                continue

    tree.write(meta_info)

3. use the shell variable you defined in .tmPreference file.

<snippet>
    <content><![CDATA[
/**
  ******************************************************************************
  * \brief      ${1:}
  * \file       $TM_FILENAME
  * \date       $TM_DATE
  * \details    
  ******************************************************************************
  */

${0:}

/****************************** Copy right $TM_YEAR *******************************/
        ]]></content>
    <!-- Optional: Tab trigger to activate the snippet -->
    <tabTrigger>cfc</tabTrigger>
    <!-- Optional: Scope the tab trigger will be active in -->
    <scope>source.c, source.c++</scope>
    <!-- Optional: Description to show in the menu -->
    <description>c file comment</description>
</snippet>
Doerthous
  • 323
  • 1
  • 11
  • this looks like the correct answer in particular to what OP asked. albeit looks like something for Sublime 2 rather than 3 – qodeninja Aug 31 '19 at 21:48
  • yes, i'm working on sblime3. before i got this solution, i was trying to search answers in stackoverflow, and found this post. so I just post my solution here. – Doerthous Sep 02 '19 at 05:03
  • erratum: code is looking for meta_info = sublime.packages_path() + '\\User\\Default.tmPreferences' but you have the file as Default.tmPreferences – Captain Lepton Mar 23 '21 at 11:09
2

You can use the SMART Snippets plugin for Sublime Text 2.

With SMART Snippets, You can now use Python to dynamically create snippets

I did some research for another question and I am pretty sure this plugin could solve your question.

Community
  • 1
  • 1
Niels van Reijmersdal
  • 2,038
  • 1
  • 20
  • 36
0

It solved in https://github.com/ngocjr7/sublime-snippet-timestamp

Copy all file to Packages/User directory of sublime text.

Configure sublime-snippet file as you want ( cpp_template.sublime-snippet for c++ and py_template.sublime-snippet for python)

Now you can create a simple snippet and the date will be updated every time you press command + s. command + s still has the function to save files.

Explaination

Because snippet doesnot support dynamic variable, I use static variable DATE define in Default.tmPreferences and update this variable when we want to create snippet.

I use a plugin (command) updatetm to update DATE in Default.tmPreferences.

I want the date and time to be updated automatically or at least passive. So I added a function that called updatetm command for keystrockes command + s. To do this, I use another plugin is chain.py to call multiple command on a keymap (both updatetm command and the default command (save). Keymap defined in Default (OSX).sublime-snippet file.

Ngoc Bui
  • 15
  • 5
-4

This post on the official ST forum answers your question and provides a close alternative.

In summary, no, you cannot currently insert datetime from a ST snippet.

Matt York
  • 15,981
  • 7
  • 47
  • 51