2

I want to add (or update, if present) the path to the current file I am working on, at the top of that file.

For example, if I place File: near the top of the file I that I am editing in vim (neovim), I want to automatically update that line with the path and filename of the file that I am editing; e.g.

File: /mnt/Vancouver/this_file.sh

If it helps, I have the following in my .vimrc file that automatically adds the date after the Last modified: line (if present) near the top of my file, anytime I save that buffer. (The cursor position is also automatically restored, via keepjumps.)

" http://vim.wikia.com/wiki/Insert_current_date_or_time 
" If buffer modified, update any 'Last modified: ' in the first 30 lines.
" 'Last modified: ' can have up to 10 characters before (they are retained).
" Restores cursor and window position using save_cursor variable.

function! LastModified()
  if &modified
    let save_cursor = getpos(".")
    let n = min([30, line("$")])
    keepjumps exe '1,' . n . 's/^\(^Last modified: \).*/\1' .
          \ strftime('%Y-%m-%d') . '/e'
    call histdel('search', -1)
    call setpos('.', save_cursor)
  endif
endfun
autocmd BufWritePre * call LastModified()

" TEST:
" Last updated: 
" (indented line below: should not update)
"  Last modified: 
" Last modified: 2018-11-21
Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37
  • 1
    Hi, this question is very similar to yours, https://unix.stackexchange.com/questions/57555/how-do-i-insert-the-current-filename-into-the-contents-in-vim/57557. Perhaps the answers provided are sufficient for your effort. – Patrick Bacon Apr 04 '19 at 19:24
  • @PatrickBacon: thank you for the link, and @Sergio for the answer. Here is a manual solution. The `%` register represents file path/name, so I added this to my ~/.vimrc: `nmap p "%p` – Victoria Stuart Apr 09 '19 at 16:05

1 Answers1

3

The following function adds the full file path (%:p) if the first line of the file starts with File:

autocmd! insertleave * call PutPath()                                     
function! PutPath()                                                      
    let file=expand("%:p")                                               
    silent! execute '1s@^File:$@& '.file                                 
endfunction         

The substitution is performed automatically when leaving insert mode (autocmd insertleave) and there must be no trailing spaces after File:.

builder-7000
  • 7,131
  • 3
  • 19
  • 43