Skip to content

Instantly share code, notes, and snippets.

@maio
Created August 17, 2011 21:03
Show Gist options
  • Save maio/1152626 to your computer and use it in GitHub Desktop.
Save maio/1152626 to your computer and use it in GitHub Desktop.
Detect correct indentation for pasted text. Helps when moving code around.
nmap P :call <SID>pasteAbove()<CR>
nmap p :call <SID>pasteBelow()<CR>
fun! s:pasteAbove()
let indentDiff = s:detectIndentDiff("O")
exe "norm! P"
call s:fixPasteIndent(indentDiff)
endfun
fun! s:pasteBelow()
let indentDiff = s:detectIndentDiff("o")
exe "norm! p"
call s:fixPasteIndent(indentDiff)
endfun
fun! s:detectIndentDiff( key )
exe "norm! " . a:key . "some text"
let indent = s:getIndent(getline('.')) - s:getIndent(getreg())
exe "norm! u"
return indent
endfun
fun! s:getIndent(string)
return match(a:string, "\\S") / &sw
endfun
fun! s:fixPasteIndent( indentDiff )
if a:indentDiff == 0
return
endif
let direction = a:indentDiff > 0 ? ">" : "<"
exe "norm! `[v`]" . abs(a:indentDiff) . direction
endfun
@maio
Copy link
Author

maio commented Aug 19, 2011

or one can use these binds to do the same :)

nmap p ]p
nmap P [p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment