6

I put together the following pile of awesomeness:

if !exists("g:AsciidocAutoSave")
  let g:AsciidocAutoSave = 0
endif

fun! AsciidocRefresh()
  if g:AsciidocAutoSave == 1
    execute 'write'
    execute 'silent !asciidoc -b html5 -a icons "%"'
  endif
endf

fun! AsciidocFocusLost()
  augroup asciidocFocusLost
    autocmd FocusLost <buffer> call AsciidocRefresh()
  augroup END
endfun

augroup asciidocFileType
  autocmd FileType asciidoc :call AsciidocFocusLost()
augroup END

The only problem is: It saves twice every time vim loses focus when in an asciidoc file.

When I put :autocmd asciidocFileType into the command line, it shows:

---Auto-Commands---
asciidocFileType  FileType
    asciidoc   :call AsciidocFocusLost()
               :call AsciidocFocusLost()

The same with :autocmd asciidocFocusLost and AsciidocRefresh().

Why this duplication?

Profpatsch
  • 4,918
  • 5
  • 27
  • 32

2 Answers2

7

I can't tell you for sure why you got those duplicates (multiple sourcing?), but the canonical way to prevent this is clearing the augroup first:

augroup asciidocFileType
    autocmd!
    autocmd FileType asciidoc :call AsciidocFocusLost()
augroup END

Since you only have one definition, you can also do this in one command:

augroup asciidocFileType
    autocmd! FileType asciidoc :call AsciidocFocusLost()
augroup END
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
  • Thanks. I found the trick with the `!` out in the meantime, making even the augroups unnecessary. But I guess I’m not the only one with a similar problem, so the question isn’t totally unnecessary. – Profpatsch Apr 24 '13 at 16:42
  • 2
    With `!`, the augroups are important; otherwise, you may clear other, same event + pattern autocmds (from other plugins), too! The `:augroup` restricts the clearing to your own group. – Ingo Karkat Apr 25 '13 at 05:59
0

@ingo-karkat's answer is great, but I think I know why you get twice as many autocmds and how to prevent it naturally:

Some distributions of vim / Neovim make sure by default that filetype plugin indent is on. Test it for neovim with env XDG_CONFIG_HOME=/dev/null nvim -c 'filetype' or for vim with env HOME=/dev/null vim -c filetype

If the output is

filetype detection:ON  plugin:ON  indent:ON

Then You don't need to add filetype * on to your vimrc.

Doron Behar
  • 2,606
  • 2
  • 21
  • 24