Vim Tips Wiki
(Insert TipProposed template + minor manual clean)
Line 57: Line 57:
   
 
==Comments==
 
==Comments==
  +
  +
This should be generalized into a single function to avoid duplication of code.

Revision as of 07:58, 4 October 2010

Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created September 9, 2010 · complexity basic · author jeet · version 7.0

When trying to "squeeze" code between existing code, the "o" and "O" commands are useful to add a blank line below/above the current one and drop into insert mode. However, sometimes it would be nice to have one (or more) extra lines inserted at the same time, so that, for example, there is an extra line between the line you are currently working on and the code above or below.

The following functions and key maps will do this.

" '\o' : open multiple lines below and drop into insert mode [count]\o will
" insert [count] lines below current line, and then drop into insert mode one
" line below the current line (i.e., second line from the top of stack of the
" newly inserted lines).
function! OpenLinesBelow()
  let num_lines = v:count1
  if num_lines < 2
    let num_lines = 2
  endif
  let linesave = line('.')
  let colsave = col('.')
  let new_lines = 2
  while num_lines > new_lines
    put=''
    let new_lines = new_lines + 1
  endwhile
  call cursor(linesave, colsave)
endfunction
nnoremap <Leader>o :<C-u>call OpenLinesBelow()<CR>o<CR>

" '\O' : open multiple lines above and drop into insert mode [count]\O will
" insert [count] lines above current line, and then drop into insert mode one
" line above current line (i.e., second line from the bottom of the stack of
" the newly inserted lines).
function! OpenLinesAbove()
  let num_lines = v:count1
  if (num_lines < 2)
    let num_lines = 2
  endif
  let linesave = line('.')
  let colsave = col('.')
  let new_lines = 1
  while num_lines > new_lines
    put!=''
    let new_lines = new_lines + 1
  endwhile
  call cursor(linesave+num_lines-2, colsave)
endfunction
nnoremap <Leader>O :<C-u>call OpenLinesAbove()<CR>O<ESC>o

Comments

This should be generalized into a single function to avoid duplication of code.