我想在该文件的顶部添加(或更新,如果存在)我正在处理的当前文件的路径。
例如,如果我将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
如果文件的第一行以%:p
开头,则以下函数添加完整文件路径(File:
)
autocmd! insertleave * call PutPath()
function! PutPath()
let file=expand("%:p")
silent! execute '1s@^File:$@& '.file
endfunction
离开插入模式(autocmd insertleave
)时自动执行替换,并且在File:
之后必须没有尾随空格。