Skip to content

Instantly share code, notes, and snippets.

@AndrewRadev
Created March 3, 2012 15:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewRadev/1966581 to your computer and use it in GitHub Desktop.
Save AndrewRadev/1966581 to your computer and use it in GitHub Desktop.
Paste and use the current line's indentation as base
" Using the `,p` mapping would paste text below the current line, using the line's indentation.
" The `,P` mapping does the same, except pasting above the current line.
"
" This could be useful for indent-based languages. For example:
"
" foo = (bar) ->
" console.log bar
"
" baz = (qux) ->
" console.log qux
" some_callback ->
" console.log this
"
" Marking and deleting the "foo" function, we'd like to paste it somewhere within the "baz"
" function.
"
" Pasting with `,p` with the cursor on "console.log qux" would result in:
"
" baz = (qux) ->
" console.log qux
" foo = (bar) ->
" console.log bar
" some_callback ->
" console.log this
"
" Pasting with `,P` with the cursor on "console.log this" would result in:
"
" baz = (qux) ->
" console.log qux
" some_callback ->
" foo = (bar) ->
" console.log bar
" console.log this
"
nnoremap ,p @=<SID>Paste('p', v:register)<cr>
nnoremap ,P @=<SID>Paste('P', v:register)<cr>
function! s:Paste(paste_key, register)
let whitespace_pattern = '^\(\s*\).*$'
let pasted_text = getreg(a:register)
let register_type = getregtype(a:register)
let local_whitespace = substitute(getline('.'), whitespace_pattern, '\1', '')
let pasted_whitespace = substitute(pasted_text, whitespace_pattern, '\1', '')
let formatted_lines = []
for line in split(pasted_text, "\n")
let line = substitute(line, '^'.pasted_whitespace, local_whitespace, '')
call add(formatted_lines, line)
endfor
call setreg(a:register, join(formatted_lines, "\n"), register_type)
exe 'normal! "'.a:register.a:paste_key
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment