I need to check the file type I have opened in Vim to do one thing or another inside a function.
This is what my vimrc
looks like:
function! MyFunction()
autocmd filetype typescript <C-V>%
autocmd filetype go <C-V>%
endfunction
nnoremap <Leadar>f :call MyFunction()<CR>
Next to <C-V>%
will be more instructions, but for now this is what I'm testing.
My function has to detect the file I have openend, according to its type do one thing or another. I'm doing this inside a function because in the near future I will move this to a separete plugin, but for now it is my vimrc
file.
Another thing I've tried already and I know it works is this
autocmd filetype typescript nnoremap <Leader>f <C-V>% DoTypescriptThings
autocmd filetype go nnoremap <Leader>f <C-V>% DoGolangThings
If I move this lines outside of a function body I works. But this way I couldn't change the <Leader> KEY
easily if I make this a plugin. That's why I moved it to a function.
How can I make my function detect my types so my function works?
If I can understand clearly, you actually want to pull out the filetype checking from auto-command so that remapping the main key (<LEADER>f
) becomes easy.
You can do this by using &filetype
.
Your function will look something like this:
function! MyFunction()
if &filetype ==# 'typescript'
autocmd filetype typescript <C-V>%
" Now you dont need autocmds here to be precise;
" But you may consider some other autocmd-events in future
" Until then a simple :execute or :execute "normal!..." should be sufficient instead
elseif &filetype ==# 'go'
autocmd filetype go <C-V>%
endif
endfunction
nnoremap <Leadar>f :call MyFunction()<CR>
Now considering the fact that autocmd also does the same thing (checking filetype and applying a mapping) so I guess your main motivation is not to use autocmd but to be able to remap main key (<LEADER>f
) easily.
So in conclusion, I would suggest to not use autocmd here and go with a function definition only so that one key can rule your function call. (Of course, unless you decide to use some other autocmd-events too)