Search code examples
vimduplicationautocmd

autocmd function always executed twice


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?


Solution

  • 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