ejoubaud
ejoubaud

Reputation: 5241

VIM: execute autocommand on enew

I want to automatically set the paste mode on when I open a new file (an empty file that doesn't exist).

autocmd BufNewFile * :set paste

in the vimrc does the trick with vim newfile or :e newfile, but not with :enew.

How can I run an autocommand on :enew?

Upvotes: 2

Views: 177

Answers (2)

ejoubaud
ejoubaud

Reputation: 5241

To answer the question, the following will run an autocommand on :enew:

autocmd BufCreate * if '' == expand("<afile>") | set paste | endif

You can replace BufCreate with BufAdd or BufNew, it will work all the same. The important part is the if '' == expand("<afile>") that will only execute the command if it the new buffer has no name.

NB:

For the specific use-case of pasting text in new buffer, auto-switching to paste mode is not a great solution though, I wouldn't recommend using this.

As the paste is maintained even when you switch buffer. You'd need additional autocommands to unset the paste mode when you switch buffer/window (autocmd WinEnter * set nopaste will work for windows, but for some reason autocmd BufEnter * set nopaste doesn't help when switching buffer).

To ease pasting stuff in new buffers (or otherwise), I'd recommend either:

  • typing "*p or "+p in normal mode, as to use vim's native mechanism to paste from the clipboard registers, as suggested by @dartNNN (assuming you're on your local machine)
  • using one of the plugins recommended in @peter-rincker's answer

Upvotes: 0

Peter Rincker
Peter Rincker

Reputation: 45177

set paste will have many side effects, e.g. disable indention. I would imagine the requested behavior would become annoying quickly.

Alternatives:

  • Use 'pastetoggle' setting to setup a key to toggle 'paste',
  • unimpaired.vim's yo mappings which put Vim in insert mode with 'paste' set and disables 'paste' upon leaving insert mode
  • vim-bracketed-paste enables transparent pasting into Vim for certain terminals.

For more help see:

:h 'paste'
:h 'pastetoggle'

Upvotes: 2

Related Questions