This will be a pretty straightforward how-to guide on how to implement timestamping in Emacs. This will insert the time directly into the document, under the cursor, so if you want something fancier than unfortunately the GNU Emacs Documentation will have to hold you over.
The Command
The command to actually insert the time into the document is this:
(insert (current-time-string))
The Keybind
Now, if it doesn't exactly sound like your cup of tea to have to copy-and-paste that Lisp command every time you want to insert the timestamp, open up your .emacs file (or wherever you store your Emacs configuration file. If you don't have one, you can just create a file called ".emacs" in your home directory).
Insert this line:
(global-set-key (kbd "C-c C-c") (lambda () (interactive) (insert (current-time-string)))
This tells Emacs that whenever you press Control-C, Control-C, it should insert the default time string (which looks like:
Fri Jul 1 10:57:35 2016
Note the (lambda (interactive()). This is only required because global-set-key expects interactive commands.
Modifying the Time
Obviously, having a string that long doesn't work for everybody. Maybe you don't want the day of the week to show, or you only care about the year, etc. Luckily, Emacs comes with a command called format-time-string which allows us to control what kind of format the date will be output as. So, let's change up that (current-time-string)!
(global-set-key (kbd "C-c C-c") (lambda () (interactive) (insert (format-time-string "%I:%M:%S%p"))))
This will give you just the 12-hour time (i.e "10:57:35pm"). To see a list of all the options you can use with format-time-string, either run man strftime (on linux) or go to The GNU Documentation on the function.
Only in Certain Modes
Now, in my case, I only want time-stamping to be enabled when I'm in Markdown Mode. The code (still using the 12-hour time format) would be this:
(add-hook 'markdown-mode-hook (global-set-key (kbd "C-c C-c") (lambda () (interactive) (insert (format-time-string "%I:%M:%S%p")))))
There are a ton of hooks out of the box, and even more in the thousands of MELPA packages, so you can modify 'markdown-mode-hook to be anything.
No comments:
Post a Comment