4

Hello fellow Vim users.

I am trying to execute a command when I write a buffer with :w. But the command should only be executed if I changed the content of the buffer.

I thought somthing like this maybe:

autocmd BufWritePost * if modified | echo 'execute command' | endif

How to I do that?

Edit:

I found the solution

autocmd BufWritePre * if &modified | echo 'execute command' | endif

Apperently I can not write modified without '&' in front it.

DasOhmoff San
  • 865
  • 6
  • 19
  • By the way `echo 'execute command'` will print something but the next echo, something like `bla bla bla written` will come shortly after. The message wont be seen because of that. The commands will still be executed. – DasOhmoff San Oct 29 '17 at 21:53

1 Answers1

2

As you've already found out, you can check the buffer-local 'modified' flag for that. For the syntax, a & needs to be prepended to the option name.

Alternatively, if you use the :update command instead of :write, the buffer will only be persisted (and the autocmd triggered) where there are actual changes; for unchanged buffers, this command is a no-op.

Many users have a mapping similar to this:

nnoremap <C-S>      :<C-U>update<CR>
vnoremap <C-S>      :<C-U>update<CR>gv
inoremap <C-S>      <C-O>:update<CR>
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324