我有一个回调设置,在保存缓冲区后自动格式化代码(取决于文件类型)。对于非常长的文件,我希望避免这种行为。当文件长度超过N行时,是否有可能使:w的行为与:noa w相同?
发布于 2018-02-15 22:14:18
您的需求的直接实现可以通过映射:w来实现。通过使用:help map-expr,您可以动态地对条件(此处:缓冲区中的行数)做出反应:
:nnoremap <expr> :w ':' . (line('$') >= 1000 ? 'noa ' : '') . 'w'请注意,有更健壮的方法可以覆盖内置的Ex命令。(例如cmdalias.vim - Create aliases for Vim commands。)
推荐的替代方案
映射的优点是您可以直接看到它的效果(尽管您必须记住:noautocmd在这里有什么效果),并且您可以轻松地影响/覆盖它。
但是,它不能与直接调用:update的映射或插件一起工作。我更喜欢修改回调设置。你可能会有类似这样的东西
:autocmd BufWritePost <buffer> call AutoFormat()我将引入一个布尔型标志来保护它:
:autocmd BufWritePost <buffer> if exists('b:AutoFormat') && b:AutoFormat | call AutoFormat() | endif然后设置一个钩子来初始化它:
:autocmd BufWritePre <buffer> if ! exists('b:AutoFormat') | let b:AutoFormat = (line('$') < 1000) | endif这样,您可以查看是否启用了自动格式化(甚至可以将b:AutoFormat放入状态行中),并且可以通过操作标志来调整行为:
: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.https://stackoverflow.com/questions/48806151
复制相似问题