6

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?

Alejandro Babio
  • 5,189
  • 17
  • 28
Sasgorilla
  • 2,403
  • 2
  • 29
  • 56

2 Answers2

9

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>

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Thanks @Kent -- I accepted the other answer, since it precisely answers my question, but I'm using your mapping in my .vimrc :) – Sasgorilla May 16 '16 at 17:10
  • Due to my settings I also wanted to `:set paste` before creating a new line, so my version became: `nnoremap &ma?":set paste\\o\:set nopaste\":"\" ` – SergioAraujo Apr 03 '19 at 11:41
7

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>
bgoldst
  • 34,190
  • 6
  • 38
  • 64