You would like to add an automatically updated timestamp in your text files.
You can do that by adding 6 lines of code to your
The following command will call the function
LastMod() whenever a buffer of
file is written.
autocmd BufWritePre,FileWritePre *.html call LastMod()
The following function will find all files containing 'Last modified:' and replace them with the current date and time.
fun LastMod() exe "%g/Last modified: /s/Last modified: .*/Last modified: " . strftime("%Y-%m-%d %T") endfun
The biggest problem with this function is that using the
will move the cursor to the beginning of the line. This will
even happen when nothing gets replaced. This is extremely annoying.
This can be fixed by remembering the current column and setting the cursor back to that after the command. Remembering the cursor position is easy.
let save_cursor = getpos(".")
And restoring it is not much harder.
call setpos('.', save_cursor)
. "/e" to the and of the regex to catch errors. Without the
e flag an error
will happen when there is no line matching the regex.
With all these changes the code now looks like this:
fun LastMod() let save_cursor = getpos(".") exe "%s/Last modified: .*/Last modified: " . strftime("%Y-%b-%d %X") . "/e" call setpos('.', save_cursor) endfun