mhartington
mhartington

Reputation: 7025

Vim remaps only work if inside of a function

I'm attempting to enable navigation based on displayed lines in VIM with set wrap linebreak enabled.

I have this function, which will toggle line wrapping with <Leader-W>

noremap <silent> <Leader>w :call ToggleWrap()<CR>
function ToggleWrap()
  if &wrap
    echo "Wrap OFF"
    setlocal nowrap
    set virtualedit=all
    silent! nunmap <buffer> <Up>
    silent! nunmap <buffer> <Down>
    silent! nunmap <buffer> <Home>
    silent! nunmap <buffer> <End>
    silent! iunmap <buffer> <Up>
    silent! iunmap <buffer> <Down>
    silent! iunmap <buffer> <Home>
    silent! iunmap <buffer> <End>
  else
    echo "Wrap ON"
    setlocal wrap linebreak nolist
    set virtualedit=
    setlocal display+=lastline
    noremap  <buffer> <silent> <Up>   gk
    noremap  <buffer> <silent> <Down> gj
    noremap  <buffer> <silent> <Home> g<Home>
    noremap  <buffer> <silent> <End>  g<End>
    inoremap <buffer> <silent> <Up>   <C-o>gk
    inoremap <buffer> <silent> <Down> <C-o>gj
    inoremap <buffer> <silent> <Home> <C-o>g<Home>
    inoremap <buffer> <silent> <End>  <C-o>g<End>
  endif
endfunction  

This works perfectly. But I want to have wrap and linebreak enabled all the time and have this navigation mappings work. So I removed the function and left this.

    set wrap linebreak nolist
    set virtualedit=
    set display+=lastline
    noremap  <buffer> <silent> <Up>   gk
    noremap  <buffer> <silent> <Down> gj
    noremap  <buffer> <silent> <Home> g<Home>
    noremap  <buffer> <silent> <End>  g<End>
    inoremap <buffer> <silent> <Up>   <C-o>gk
    inoremap <buffer> <silent> <Down> <C-o>gj
    inoremap <buffer> <silent> <Home> <C-o>g<Home>
    inoremap <buffer> <silent> <End>  <C-o>g<End>

Normal mode works fine, but insert mode does not. Any reason why this isn't working outside of the function?

Upvotes: 0

Views: 46

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172510

There are two possibilities:

  1. A plugin may override the insert mode mappings; check with :verbose imap <Up>.
  2. Your mappings will only work in the first buffer; for global configuration, drop the <buffer> from the :map commands (like you switched :setlocal to :set).

Upvotes: 1

Related Questions