Skip to content

Instantly share code, notes, and snippets.

@t9md
Created October 24, 2010 13:08
Show Gist options
  • Save t9md/643524 to your computer and use it in GitHub Desktop.
Save t9md/643524 to your computer and use it in GitHub Desktop.
Copy and Move text easily in vim
fun! MoveSelectedText(direction) range
if a:direction == 'j'
let cmd = a:firstline . ",". a:lastline . "move " . (a:lastline + 1)
elseif a:direction == 'k'
let cmd = a:firstline. ",". a:lastline . "move " . (a:firstline - 2)
elseif a:direction == 'l'
let cmd = "normal gv>>"
elseif a:direction == 'h'
let cmd = "normal gv<<"
endif
execute cmd
normal gv
endfun
fun! CopySelectedText(mode, ...) range
let pos = getpos('.')
let cmd = a:firstline . ",". a:lastline . "copy " . a:lastline
execute cmd
let follow = a:0 > 0 ? a:1 : 0
if follow != 1
if a:mode ==# 'v'
normal `[V`]
elseif a:mode ==# 'n'
let pos[1] = line('.')
call setpos('.', pos)
endif
else
if a:mode ==# 'v'
normal gv
elseif a:mode ==# 'n'
call setpos('.', pos)
endif
endif
endfun
" select text then try!
vnoremap <C-j> :call MoveSelectedText('j')<CR>
vnoremap <C-k> :call MoveSelectedText('k')<CR>
vnoremap <C-h> :call MoveSelectedText('h')<CR>
vnoremap <C-l> :call MoveSelectedText('l')<CR>
" duplicate lines, default behavior is 'follow' selection to newly duplicated
" text.
vnoremap <D-d> :call CopySelectedText('v')<CR>
nnoremap <D-d> :call CopySelectedText('n')<CR>
" If you dont like default behavior, set second arg to '1'.
" Then selection range remain unchanged after copy.
" vnoremap <D-d> :call CopySelectedText('v', 1)<CR>
" nnoremap <D-d> :call CopySelectedText('n', 1)<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment