Reputation: 38
I have a function in my .vimrc that automatically updates the file I'm currently editing with the timestamp (Modified) of the last 'save' (:w).
I would like to also update the Filename and Filepath. I have an autocmd that updates the filename (through expand("%"). As for the Filepath, from what I read in the documentation, using expand("%:p:h") should permit me to insert the path (excluding the filename), but it does not work.
Anybody can tell me how insert the Filepath in my header ?
Example of file header that I wish to update:
Modified: November 13 2016
Filename: myfile
Filepath: /home/me/path/tomyfile/
Code I have at the moment :
autocmd BufWritePre * call UpdHeader()
function! UpdHeader()
" update path <<<<<< DOES NOT WORK >>>>>>>
silent! execute "1," . 10 . "g/Filepath:.*/s//Filepath: " .expand("%:p:h")
" update filename <<WORKS>>
silent! execute "1," . 10 . "g/Filename:.*/s//Filename: " . expand("%")
" update last mod date <<WORKS>>
silent! execute "1," . 10 . "g/Modified:.*/s//Modified: " . strftime("%d %B %Y%t%t%T (%z)%tBy : ") . $USER
...
endf
thx! M
Upvotes: 2
Views: 403
Reputation: 172598
You need to perform proper escaping on the filepath, as you use /
both as a separator in :substitute
, and the (Unix-style) replacement path also has /
separators in it. :substitute
would have alerted your via E488: Trailing characters
, but you've :silent!
it.
A quick fix would be switching of :substitute
separators, hoping that #
will never appear in a file path:
silent! execute "1," . 10 . "g/Filepath:.*/s##Filepath: " .expand("%:p:h")
Better do proper escaping:
silent! execute "1," . 10 . "g/Filepath:.*/s//Filepath: " .escape(expand("%:p:h"), '/\'. (&magic ? '&~' : ''))
Alternatively, you can replace with an expression:
silent! execute "1," . 10 . "g/Filepath:.*/s//\\='Filepath: ' .expand('%:p:h')"
Your filename expansion would benefit from that as well.
Upvotes: 1