Sasgorilla
Sasgorilla

Reputation: 3130

How can I check if a Vim buffer is modifiable?

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?

Upvotes: 6

Views: 1923

Answers (2)

Kent
Kent

Reputation: 195209

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>

Upvotes: 9

bgoldst
bgoldst

Reputation: 35324

Use '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>

Upvotes: 7

Related Questions