Question

I would like to make Vim insert a timestamp each time I make a new line. From Best way to insert timestamp in Vim? I can see there's a way of inserting a timestamp on keypress:

nmap <F3> a<C-R>=strftime("%Y-%m-%d %a %I:%M %p")<CR><Esc>
imap <F3> <C-R>=strftime("%Y-%m-%d %a %I:%M %p")<CR>

Likely I could just map Enter to this, instead of F3; however, this is a kludge (for instance, I could press CtrlM). Is there a way to trigger an action on newline in Vim?

No correct solution

OTHER TIPS

<CR>, <Enter>, and <C-M> are all synonyms in Vim. Therefore, it's sufficient to define this mapping:

:imap <buffer> <CR> <CR><C-R>=strftime("%Y-%m-%d %a %I:%M %p ")<CR>

I chose a buffer-local mapping because you probably only want this for certain filetypes. You can define that for certain filetypes by prepending :autocmd Filetype <filetype> ..., and put that into your ~/.vimrc. But that get's unwieldy as you add mappings and other settings for various filetypes. Better put the commands into ~/.vim/ftplugin/<filetype>_mappings.vim. (This requires that you have :filetype plugin on.)

This still won't cover pasted text. I doubt you'd really want that (it's better to prepend the timestamps afterwards), but you can look into the (recently added) TextChanged event to implement that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top