vim: automatic date/timetamp when opening a specific file?

206 Views Asked by At

I would like help with my vim script. thus far I am able to check for the file name, however, I have been unsuccessful in learning how to give normal mode commands via vim script. here is what I've got:

autocmd VimEnter * if @% == 'diary.md' | :r! | endif

I am trying to give the command :r! to add the date/time on a new line when I open this file.

I appreciate any and all wisdom, thanks~!

2

There are 2 best solutions below

2
SergioAraujo On

From vi.stackexchange.com, a seemingly easy answer:

 autocmd VimEnter dairy.md | 0put=strftime('%c') 

You just have to use the filename, the zero indicates the very beginning of the file. If you want to modificate the timestamp just read the strftime help for that.

1
Rokiora On

huge thanks to @romaini and @SergioAraujo~!

@romaini - your comment helped me learn more about external commands and using the built in :help

@SergioAraujo - your answer was right on the money~! the only issue was that I received the following error with your code:

E116: Invalid Arguments for function strftime(

It was a quick fix though by switching from ("%c") to ('%c') :

autocmd VimEnter diary.md | $put=strftime('%c')

I am unsure why it only works with single quotes

Additionally, you will note I used $put instead of 0put, this is because I wanted to add the timestamp at the end of the file as a way to start a new entry of my diary on this document. Once again thank you for all your help~!