Index

I keep diaries on different subjects. When I add a new entry I start by inserting a timestamp at the top of the entry. I used to do it ‘manually’ –by copying the current date and pasting in into Vim–, and yesterday I decided to write a vim function to automate that.

There’s nothing especially hard about that, but it took me a while before I figured out how to insert the timestamp at the current cursor position. It didn’t look like there was any built-in Vim function to do it, and most solution I found online seems overly complicated.

It turns out that all I needed was an execute statetement like this: execute ":normal itext to insert", this will insert the string “text to insert” at the current cursor position.

I this added to my vimrc:

function s:InsertISODate()
    let timestamp = strftime('%Y-%m-%d')
    execute ":normal i" . timestamp
    echo 'New time: ' . timestamp
endfunction

function s:InsertISODatetime()
    let timestamp = strftime('%Y-%m-%d %H:%M:%S')
    execute ":normal i" . timestamp
    echo 'New time: ' . timestamp
endfunction

command Today	call s:InsertISODate()
command Now     call s:InsertISODatetime()