How do I get the current filetype in a vimscript, say in .vimrc or a regular plugin script? The line
echo &filetype
returns an empty string.
In a function:
let current_filetype = &filetype
On the command line:
:echo &filetype
&filetype
is empty when there's no filetype (obviously). If you try to use it when there's no buffer loaded you'll just get nothing.
edit
&filetype
is only useful when you need to know the current filetype in a function executed at runtime when you are editing a buffer.
&filetype
is only set when a buffer has been determined to be of some filetype. When it is executed, a script (vimrc, ftplugin, whatever) doesn't go through what it would go when it is edited: no filetype checking, no &filetype
.
An example would be a function that displays the current file in a different external app depending on its filetype. Using &filetype
in any other context doesn't make sense because it will be empty.
You need to consider the timing of your plugin. When your plugin script is sourced during the startup of Vim, no buffer has yet been loaded, so &filetype
is empty. Therefore, something like this
let s:formatprgvarname = "g:formatprg_".&filetype
does not work! (For a filetype plugin (in ~/.vim/ftplugin/
), this is different; those are sourced only when the filetype has been detected. But as I understand you want a general-purpose plugin that considers the current filetype.)
Instead, do away with the script-local variable s:formatprgvarname
and resolve &filetype
at the point of action; i.e. when your autoformat functionality is triggered (by mapping or custom command). If you have no such trigger, you can hook into the FileType
event and set a (preferably buffer-local) variable then:
autocmd FileType * let b:formatprgvarname = "g:formatprg_".&filetype
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With