Question

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?

Was it helpful?

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

OTHER TIPS

@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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top