4

As per other questions, most of us know that if we want to enter paste mode we can toggle :set paste and :set nopaste.

And for auto-indenting we can :set autoindent.

However, I was thinking today, I only ever paste when I am at the beginning of a line and otherwise always want auto-indenting. I can set up hot keys to toggle the two quickly, but is there some way perhaps to tell vim in settings to be in paste mode when at the beginning of a line and to otherwise be in auto-indent mode to avoid the need to manually toggle?

  • 2
    The unimpaired plugin has a different (but IMO better) solution. See Drew Neil's analysis for the rationale, as well as his copy and paste series. – lcd047 Jun 21 '15 at 3:45
  • 1
    Better than "paste": "put". Unless you are really desperate (tiny vim via ssh without any possibility of X-forwarding), use the * and/or + registers: "*p, "+p. – romainl Jun 21 '15 at 8:24
3

This can be done with an auto command ("autocmd"). There's the CursorMoved event which is triggered every time the cursor is moved. CursorMovedI does the same, but for insert mode.

augroup autopaste
    autocmd!
    autocmd CursorMoved,CursorMovedI * let &paste = col('.') == 1
augroup end

Or, only on blank lines:

augroup autopaste
    autocmd!
    autocmd CursorMoved,CursorMovedI * let &paste = getline('.') == ''
augroup end

Also see :help autocmd.txt and Learn Vimscript the Hard Way (it has more chapters on autocmds, so be sure to look further than just this page).


As mentioned in the comments, this may not be the best way to do this. Usually pasting directly from the clipboard is more convenient. This can be done fairly easily with these mappings:

" Interface with system clipboard
noremap <Leader>y "*y
noremap <Leader>p "*p
noremap <Leader>Y "+y
noremap <Leader>P "+p

See How can I copy text to the system clipboard from Vim? for more information on how to interface with the system's clipboard.

| improve this answer | |
  • Great thanks, going to try this out and then mark this as accepted if it works. – coderintherye Jun 25 '15 at 23:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.