nathom / filetype.nvim

A faster version of filetype.vim
560 stars 35 forks source link

Create filetypedetect augroup in filetype.vim #54

Closed gpanders closed 2 years ago

gpanders commented 2 years ago

Like the plugin file, filetype.vim is automatically sourced by Neovim, but it is done much sooner than plugin files (it is sourced immediately after the user's init file). It turns out that this ordering matters for autocommand definitions: autocommands cannot specify any kind of priority, so they run in the order they are defined. The builtin filetype.vim creates the filetypedetect autocommands early on, which means users (and plugins) can use the buffer's filetype in their own BufRead autocommands.

However, when the filetypedetect autocommand is created in the plugin file, any BufRead autocommands defined before that file is sourced are not able to read the buffer's filetype.

For example, consider a "restore cursor position" autocommand defined in ~/.config/nvim/plugin/restore_cursor.vim:

augroup restore_cursor
  au!
  au BufRead * if &ft !~# 'commit' | exe 'silent! normal! g`"' | endif
augroup END

With the status quo, this will not work, because &ft is empty. This happens because this BufRead autocommand is defined before filetype.nvim's filetypedetect autocommand. Thus, when the autocommand executes, filetype detection has not yet run. However, if the filetypedetect autocommand is moved to filetype.vim (as this PR does), the filetypedetect autocommand runs before any other BufRead autocommands, so &filetype will be defined.

Move the filetypedetect autocommand into filetype.vim to ensure it's created as soon as possible. This also is more consistent with the builtin filetype.vim and ensures there are fewer "gotchas" when using filetype.nvim.

NOTE: This will only work on Neovim 0.6 or later, which includes changes to 'runtimepath' that ensure this plugin's filetype.vim is sourced before the builtin one. However, 0.6 will be released later today.