Vim: disable autocmd BufRead (modeline)

梦想的初衷 提交于 2020-12-13 03:34:03

问题


From this answer I executed:

:set modeline | doautocmd BufRead

Since then, I cannot disable the BufRead.

I can open a file and unset the modeline:

:set nomodeline
:e!
:wq

But when I reopen the same file, its modeline is again auto executed.

I tried noautocmd - autocmd-remove:

:noautocmd w BufRead
:noautocmd BufRead
:exe "au! BufRead *"
:au! BufRead

Note I want to disable all auto executed because of BufRead, not just a single event set by it like here explained: https://stackoverflow.com/a/40173033/9391770


回答1:


In the linked question, the BufRead event only got creatively reused for :doautocmd (any event would do) so that modelines are re-executed without reloading the buffer. Now you're asking for the opposite - preventing modelines from loading.

The corresponding options are 'modeline' and 'modelines' - if the former is off or the latter is set to 0, modelines are ignored.

Your given mapping looks fine to me; it can be simplified a bit; you don't need to spell out <space> (only <bar>), and the : can be dropped except at the front, where it is used for the transition from normal mode to command-line mode. A prepended <C-u> will clear any count (should you accidentally supply some).

:nnoremap <leader>mdl :<C-u>set modelines=5<bar>set modeline<bar>edit <bar>set modelines=0<bar>set nomodeline<CR>

Simplification with plugin

The anwolib plugin has a nifty :With {setlocal-args} Do {cmd} command; if you just target the (buffer-local) 'modeline' option for toggling (which at least for me is sufficient), the whole mapping can be written as

:nnoremap <leader>mdl :<C-u>With modeline Do edit<CR>

This is so crisp and understandable that you barely need a mapping any longer!

Security impact of modelines

Modelines can only change Vim options - some are even forbidden to change because those could be exploited; it is not possible to execute arbitrary Vim commands through them. Though some attacks can be imagined (especially if you have some plugins or customizations which act on changed buffer options), modelines in general are safe. So unless you're paranoid about security or work in an environment with stringent security requirements, you usually don't need to take such precautions. Of course, if you don't personally use modelines at all, turning them off reduces the attack surface. But at least for me, the effort to recognize that modelines would be handy to execute and then toggle the setting and reload the buffer would be worse than the minimal risk that they pose.



来源:https://stackoverflow.com/questions/64368210/vim-disable-autocmd-bufread-modeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!