'Resize window in vim with a keyboard map

I am trying to set the + and _ keys to increase or decrease the size of a window pane in vim. Here is what I have so far in my .vimrc:

 nnoremap + :res +5
 nnoremap _ :res -5

However it doesn't appear to work. What would be the proper way to map the resize pane in vim? Also, is there a way to press [enter] automatically after entering the command so that it executes automatically?

vim


Solution 1:[1]

The :res commands are fine, but you need to append <CR> (for Carriage Return) to the mappings to actually execute them when you press + or _ . So, your mappings should look like this:

nnoremap + :res +5<CR>
nnoremap _ :res -5<CR>

It should be noted that there are built-in hotkeys in Vim to increase and decrease the window height and width, with the default number being 1:

  • Increase height (by 1): Ctrl-W +
  • Decrease height (by 1): Ctrl-W -
  • Increase width (by 1): Ctrl-W >
  • Decrease width (by 1): Ctrl-W <

To use the above hotkeys with values other than 1, simply prepend the hotkey with the value:

  • Increase height by 5: 5 Ctrl-W +

Solution 2:[2]

Alternative: use a "mode" where normal arrow keys can resize the current window. either map to + or :call ToggleResizeMode()

"
" + toggle remap arrow keys to resize windows
"
nnoremap + :call ToggleResizeMode()<CR>

let s:KeyResizeEnabled = 0

function! ToggleResizeMode()
  if s:KeyResizeEnabled
    call NormalArrowKeys()
    let s:KeyResizeEnabled = 0
  else
    call ResizeArrowKeys()
    let s:KeyResizeEnabled = 1
  endif
endfunction

function! NormalArrowKeys()
  " unmap arrow keys
  echo 'normal arrow keys'
  nunmap <Up>
  nunmap <Down>
  nunmap <Left>
  nunmap <Right>
endfunction

function! ResizeArrowKeys()
  " Remap arrow keys to resize window
  echo 'Resize window with arrow keys'
  nnoremap <Up>    :resize +2<CR>
  nnoremap <Down>  :resize -2<CR>
  nnoremap <Left>  :vertical resize -2<CR>
  nnoremap <Right> :vertical resize +2<CR>
endfunction

Or better: someone already implemented a window submode, there is probably a plugin for it somewhere. https://ddrscott.github.io/blog/2016/making-a-window-submode/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2