首页 编程 正文
288

vim钩子的应用示例

  • yiqingpeng
  • 2018-09-08
  • 0
  •  
钩子位置:~/.vimrc

钩子命令:
autocmd <events> <filename_pattern> :command
查看更多events,在vim中键入指令:help Cmd-event

钩子示例:
a、单行钩子代码例子
autocmd BufWritePost,FileWritePost *.txt :execute....
autocmd BufReadPost, FileReadPost *.pl,*.pm :silent %!indent  (自动缩进)
autocmd FileWritePost /etc/php.ini :execute '! cp % /home/yqp/php.ini.bk;httpd restart' (%仅代表的是文件名,如果要完整路径的话,需要借助expand())

b、多行钩子代码例子
function! MyHook()
" todo
endfunction

function! AutoSave()
if &modified && g:autosave_on_focus_change
write
echo "Autosaved file while you were absent" 
endif
endfunction

autocmd BufWritePost *.txt :call MyHook()
autocmd FocusLost *.doc :call AutoSave()

引用当前文件名:%
引用当前文件相对路径:expand('%')
引用当前文件绝对路径:expand('%:p')
引用当前文件相对目录:expand("%:h")
引用当前文件绝对目录:expand("%:p:h")
比如自动创建路径::call mkdir(expand("%:h"), "p")

vi脚本语法:https://www.ibm.com/developerworks/linux/library/l-vim-script-1/index.html

调用shell脚本示例:
autocmd BufWritePost,FileWritePost /etc/httpd/conf.d/http.conf :execute '! ~/lookup.sh ' . expand("%:p")
#expand("%:p")返回当前文件的完整路径。此钩子可以用来自动备份http.conf文件.
这种钩子会在vim中显示出执行结果,如果需要让此钩子静静地在后台执行,可以加上silent指令,如下:
autocmd BufWritePost,FileWritePost /etc/httpd/conf.d/http.conf :silent! execute '! ~/lookup.sh ' . expand("%:p")
自动重启php-fpm服务:
autocmd BufWritePost,FileWritePost /etc/php.ini :silent! execute '!pgrep ^php-fpm$|xargs kill&&php-fpm
'
自动重启mysql服务:
autocmd BufWritePost,FileWritePost /etc/my.cnf.d/server.cnf :silent! execute '!systemctl restart mariadb'

正在加载评论...