3

is there a way that sublime text automatically updates the date in a comment block on a file when I edit and save it?

like:

/**
 * @author yada yada
 * @date 2015-01-08
 */

to:

/**
 * @author yada yada
 * @date 2015-01-19
 */
hntrmr
  • 81
  • 9

2 Answers2

5

ok, got it. it's a mix of

Preferences > Key Bindings- User

[
    {"keys": ["ctrl+s"], "command": "date_and_save" }
]

add_date.py

'''
Autodate header
@date <>
'''
from datetime import datetime
import sublime, sublime_plugin

class AddDateCommand(sublime_plugin.TextCommand):
    def run(self, args):
        content = self.view.substr(sublime.Region(0, self.view.size()))
        begin = content.find('@date <',0,100)
        if begin == -1:
            return
        end = content.find("\n", begin)
        target_region = sublime.Region(begin, end)
        self.view.sel().clear()
        self.view.sel().add(target_region)

        self.view.run_command(
        "insert_snippet",
        { "contents": "@date <%s>" % datetime.now().strftime("%Y-%m-%d %H:%M:%S") } )

class DateAndSaveCommand(sublime_plugin.WindowCommand):
    def run(self):
        self.window.run_command("add_date")
        self.window.run_command("save")

\o/

Flint
  • 1,651
  • 1
  • 19
  • 29
hntrmr
  • 81
  • 9
  • you are using ctrl+s key binding, in this case files will not save. – Sinac Nov 07 '17 at 09:50
  • Limiting the replacement of `date` occurrence to a range of N first characters makes it safer. You probably don't want an other occurrence of `date` to be replaced in the code. An even better approach would be to indicate how much lines to scan. You might also want the hour of the file's revision. The C-s keybinding works fine. – Flint Nov 30 '17 at 04:05
0

Awesome stuff! Small addition to the above solution:

Instead of

end = begin + 19

This line will make it more dynamical, because it will get rid of everything until the end of the line.

end = content.find("\n", begin)

Helps with versioning up, for example, where the line-length can vary.