I have a callback setup-ed that auto-formats the code automatically after saving the buffer (depending on the file type). I'd like to avoid this behavior for very long files. Is it possible to make :w
behave the same as :noa w
, when the file is longer than N lines?
A direct implementation of your requirement would be by mapping :w
. Through the use of :help map-expr
, you can dynamically react to conditions (here: the number of lines in the buffer):
:nnoremap <expr> :w ':' . (line('$') >= 1000 ? 'noa ' : '') . 'w'
Note that there are more robust approaches for overriding built-in Ex commands. (For example cmdalias.vim - Create aliases for Vim commands .)
The advantage of the mapping is that you directly see what effect it has (though you have to remember what effects :noautocmd
has here), and you can influence / override it easily.
However, it won't work with mappings or plugins that invoke :update
directly. I would prefer to modify the callback setup instead. You probably have something like
:autocmd BufWritePost <buffer> call AutoFormat()
I would introduce a boolean flag that guards this:
:autocmd BufWritePost <buffer> if exists('b:AutoFormat') && b:AutoFormat | call AutoFormat() | endif
And then setup a hook that initializes it:
:autocmd BufWritePre <buffer> if ! exists('b:AutoFormat') | let b:AutoFormat = (line('$') < 1000) | endif
This way, you see whether auto-formatting is enabled (you can even put b:AutoFormat
into your statusline), and you can tweak the behavior by manipulating the flag:
:let b:AutoFormat = 0 " Turn off auto-formatting even though the buffer is small.
:let b:AutoFormat = 1 " Force auto-formatting even though it's a large buffer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.