vim - 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
解决方案
如果文件%:p
的第一行以File:
autocmd! insertleave * call PutPath()
function! PutPath()
let file=expand("%:p")
silent! execute '1s@^File:$@& '.file
endfunction
退出插入模式 ( autocmd insertleave
) 时会自动执行替换,并且 之后不能有尾随空格File:
。
推荐阅读
- javascript - 微调器仅在表单提交时
- jupyter - JupyterLab 高级设置编辑器中的重复项
- javascript - 如何打印 author.name 和 description(embed) 的内容?
- .net-core - 在构建服务器上升级 VS 后的 .NetCore.App 运行时包问题
- python - 使用 HC-SR04 和 PySimpleGUI 进行距离测量
- c - 为什么这个 C 代码的程序集等同于这样?
- javascript - 如何为相同id的所有元素设置值(相同值)?Javascript
- flask - 我在 Flask 中设置了调试模式,但在 PyCharm 控制台中显示为“关闭”
- ssis - 导入 Excel 文件的 SSIS 2019 包如果不在预期的文件夹中,则会创建一个空文件
- javascript - django 没有读取 javascript 表单数据文件