Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a Vim buffer is modifiable?

Tags:

vim

macvim

viml

I find the Vim shortcuts nmap <enter> o<esc> or nmap <enter> O<esc>, which insert a blank line with the enter key, very useful. However, they wreak havoc with plugins; for instance, ag.vim, which populates the quickfix list with filenames to jump to. Pressing enter in this window (which should jump to the file) gives me the error E21: Cannot make changes; modifiable is off.

To avoid applying the mapping in the quickfix buffer, I can do this:

" 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>

This works, but what I really want is to avoid the mapping in any nonmodifiable buffer, not just in the quickfix window. For instance, the mapping makes no sense in the location list either (and may break some other plugin that uses it). How can I check to see if I'm in a modifiable buffer?

like image 323
Sasgorilla Avatar asked May 13 '16 13:05

Sasgorilla


1 Answers

you can check the option modifiable (ma) in your mapping.

However you don't have to create a function and call it in your mapping. The <expr> mapping is designed for those use cases:

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

(The above line was not tested, but I think it should go.)

For detailed information about <expr> mapping, do :h <expr>

like image 89
Kent Avatar answered Sep 23 '22 10:09

Kent