autocmd function always executed twice
Asked Answered
L

2

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?

Lyndseylyndsie answered 24/4, 2013 at 15:15 Comment(0)
I
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
Instant answered 24/4, 2013 at 16:8 Comment(2)
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.Lyndseylyndsie
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.Instant
R
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.

Rahr answered 16/3, 2018 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.