Search code examples
vimfile-type

Why check did_load_filetypes in custom filetype files?


From vim wiki:

Custom filetype.vim files should always have the following structure:

if exists("did_load_filetypes")
  finish
endif

augroup filetypedetect
  " au! commands to set the filetype go here
augroup END

I am wondering why is the if...endif part necessary?

I think this basically means that if filetypes are already loaded, then skip loading this script. But in that case what's the point of creating a custom filetype file?


Solution

  • This is just an include guard, to avoid that your custom filetype is accidentally sourced multiple times.

    If all goes well, this indeed looks superfluous, but with all the variations in user configuration, plugin managers, etc., it's better to be safe. And it saves Vim from re-processing the potentially large list of definitions, speeding up startup.

    What happens when this is actually sourced twice?

    If you use :autocmd instead of :autocmd!, all your detections would be defined twice. (Note that an initial :autocmd! cannot be used here to clear all previous definitions, because multiple filetype.vim files are involved, and each only adds to the existing ones.)