Search code examples
vimneovim

How does Vim declare the filetype for Js or other types


For making my own snippet for js, Vim can't use js as a type to create my snippet.

autocmd FileType js :call Foo()

How do I choose the correct Vim FileType?


Solution

  • As shown in the article linked in the comments, you can do this using an autocmd in your vimrc. However, I find it can be cleaner to instead leverage vim's runtime path structure to set filetype-specific settings.

    TL;DR

    Put your filetype specific commands such as inoremap ,f ()... in ~/.vim/after/ftplugin/javascript.vim. If any of these directories don't exist, create them. You can do similar things for other languages (e.g. put html bindings in ~/.vim/after/ftplugin/html.vim, etc).

    Explanation

    The vim runtime path is just where vim looks for configuration files and related things when it starts up (just like how it reads ~/.vimrc). First it will read some system-wide things from /etc, and then it will read the contents of ~/.vim. The after directory, as the name suggests, will be read after other settings, and though it is probably not necessary to put this type of thing in after, it won't hurt (it makes sure it won't get overwritten by system-wide configuration). Within after is the ftplugin directory, which is where filetype-specific config will go. You could also put an ftplugin directory directly in ~/.vim, and it would do the same thing (except it would get read earlier. The files you put in this directory will work similar to how the autocmd would work. I just prefer to do things this way, because I find it neater than having a bunch of autocmds in my vimrc. For more detailed info about the vim runtime path and how you can use it, check out this video. The whole thing isn't about the runtime path, but it does have a very good explanation in there.

    Of course, you can still use autocmds if you would like to (and I think your only problem there is that your autocmd must say Filetype javascript instead of Filetype js).