如何检查 Vim 缓冲区是否可修改?

How can I check if a Vim buffer is modifiable?

我找到了Vim快捷键nmap <enter> o<esc>nmap <enter> O<esc>,用回车键插入一个空行,非常有用。但是,它们对插件造成严重破坏;例如,ag.vim,它用要跳转到的文件名填充 quickfix 列表。在此 window 中按回车键(应跳转到文件)会出现错误 E21: Cannot make changes; modifiable is off

为了避免在 quickfix 缓冲区中应用映射,我可以这样做:

" insert blank lines with <enter>
function! NewlineWithEnter()
  if &buftype ==# 'quickfix'
    execute "normal! \<CR>"
  else
    execute "normal! O\<esc>"
  endif
endfunction
nnoremap <CR> :call NewlineWithEnter()<CR>

这行得通,但我真正想要的是避免在任何不可修改的缓冲区中进行映射,而不仅仅是在 quickfix window 中。例如,映射在位置列表中也没有意义(并且可能会破坏使用它的其他一些插件)。我如何检查我是否在可修改的缓冲区中?

使用'modifiable':

" insert blank lines with <enter>
function! NewlineWithEnter()
    if !&modifiable
        execute "normal! \<CR>"
    else
        execute "normal! O\<esc>"
    endif
endfunction
nnoremap <CR> :call NewlineWithEnter()<CR>

您可以检查映射中的选项 modifiable (ma)。

但是您不必创建函数并在映射中调用它。 <expr> 映射是为这些用例设计的:

nnoremap <expr> <Enter> &ma?"O\<esc>":"\<cr>"

(上面那行没测试过,但我觉得应该可以)

有关 <expr> mapping 的详细信息,请执行 :h <expr>