首页 > 解决方案 > vimrc 代码在文件顶部插入当前文件的路径?

问题描述

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

例如,如果我放置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: \).*/\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

标签: vimneovim

解决方案


如果文件%:p的第一行以File:

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

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


推荐阅读