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?

muru
  • 24,838
  • 8
  • 82
  • 143

1 Answers1

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.

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271