Vim:避免在成功制作后按ENTER


$ ls
Makefile          html-page/        page-generator.m4
Run               includes/

除了Makefile,我还有一个脚本Run,它只有在make完成而没有错误时才执行。我已经在.vimrc文件中用以下内容实现了这一点,如果需要,该文件还会在父目录中查找Makefile

" Before the 'make' quickfix command, run my quickfix pre-commands
autocmd QuickfixCmdPre make call MyQuickfixCmdPre()
" After the 'make' quickfix command, run my quickfix post-commands
autocmd QuickfixCmdPost make call MyQuickfixCmdPost()

function! MyQuickfixCmdPre()
" Save current buffer, but only if it's been modified
update
" (h)ead of (p)ath of % (current buffer), i.e. path of current file
let l:dir = expand('%:p:h')
" Remove final / and smack a /Makefile on the end, glob gives empty if file doesn't exist
while empty(glob(substitute(l:dir, '/$', '', '') . '/Makefile'))
" There's no Makefile here. Are we at the root dir?
if l:dir ==# "/"
" Just use dir of current file then
let l:dir = '.'
break
else
" Try the parent dir. Get (h)ead of dir, i.e. remove rightmost dir name from it
let l:dir = fnamemodify(l:dir, ':h')
endif
endwhile
" Makefile is in this dir, so local-cd (only this window) to the dir
execute "lcd " . l:dir
endfunction
function! MyQuickfixCmdPost()
" Get number of valid quickfix entries, i.e. number of errors reported,
" using filter to check the 'valid' flag
let l:err_count = len(filter(getqflist(), 'v:val.valid'))
if l:err_count ==# 0
" The make succeeded. Execute the Run script expected in the same dir as Makefile
call system('./Run')
redraw!
endif
endfunction

有了这个,在vim中键入:mak后,代码就生成并运行了。。。有两种可能的结果:

  1. 如果在make期间出现错误,vim将在之后用Press ENTER or type command to continue呈现这些错误,这一切都很好
  2. 然而,如果make成功而没有错误,我的Run脚本就会被执行,用于测试我的代码(在本例中是浏览器中显示的html文件(,但当我切换回vim时,我必须按enter来清除vim中的一条消息,我不需要读它,因为它不会告诉我错误。此消息以前是这样的:
"includes/m4includes/subs.m4" 34L, 759B written
:!make  2>&1| tee /var/folders/zk/0bsgbxne3pe5c86jsbgdt27f3333yd/T/vkbxFyd/255
m4 -I includes/m4includes page-generator.m4 >html-page/mypage.html
(1 of 1): m4 -I includes/m4includes page-generator.m4 >html-page/mypage.html
Press ENTER or type command to continue

但在CCD_ 13中引入CCD_

(1 of 1): m4 -I includes/m4includes page-generator.m4 >html-page/mypage.html
Press ENTER or type command to continue

但仍需要按下CCD_ 14。

我们如何避免在成功编译后每次返回vim时都必须按下enter?有什么想法吗?

注意:vim有一个-silent命令行选项,但据我所见,这将使所有Press ENTERs静音,这里的目标是只有在成功的make之后才能避免它们

之后只需添加call feedkeys("<CR>")即可。需要feedkeys()的地方不多(通常normal!或类似的命令会用到(,而且有一些微妙的效果(请仔细查看它所使用的标志(。幸运的是,这是一个有用的地方。

最新更新