vimrc 代码在文件顶部插入当前文件的路径?

vimrc code to insert path of current file at top of file?

我想在该文件的顶部添加(或更新,如果存在)我正在处理的当前文件的路径。

例如,如果我将 File: 放在我正在 vim (neovim) 中编辑的文件的顶部附近,我想自动更新该行我正在编辑的文件的路径和文件名;例如

File: /mnt/Vancouver/this_file.sh

如果有帮助,我的 .vimrc 文件中有以下内容,每当我保存该缓冲区时,它会自动在文件顶部附近的 Last modified: 行(如果存在)之后添加日期. (光标位置也会自动恢复,通过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: \).*/' .
          \ 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

如果文件的第一行以File:

开头,则以下函数添加完整文件路径(%:p
autocmd! insertleave * call PutPath()                                     
function! PutPath()                                                      
    let file=expand("%:p")                                               
    silent! execute '1s@^File:$@& '.file                                 
endfunction         

退出插入模式时自动执行替换 (autocmd insertleave),File: 后不能有尾随空格。