I would like the :Toc command to call :Voom in R markdown files and :VimtexTocOpen in latex files.

First try:

au BufRead,BufNewFile *.Rmd command! Toc Voom
au BufRead,BufNewFile *.tex command! Toc VimtexTocOpen

It works as expected as long as I edit only one file type. If I edit first a markdown file in one buffer, then a latex file in another buffer. Then the :Toc command fails in the markdown buffer because it calls VimtexTocOpen.

Second try:

au FileType rmd command! Toc Voom
au FileType tex command! Toc VimtexTocOpen

It sets the :Toc command correctly in markdown files. Then sets it correctly in latex files. But when i go back to edit the markdown file, the command VimtexTocOpen is called and fails.

Third try:

au FileType rmd setlocal command! Toc Voom
au FileType tex setlocal command! Toc VimtexTocOpen

But this returns the error

Error detected while processing FileType Autocommands for "rmd":
E518: Unknown option: command!
E518: Unknown option: command!
Press ENTER or type command to continue

First you need to create your command as local to a buffer, :h :command-buffer tells us that is what the argument -buffer is for.

Then I think it's better to use ftplugins (:h ftplugin) to do this kind of things rather and a Filetype autocommand which just duplicate a built-in mechanism.

So you could create ~/.vim/after/ftplugin/rmd.vim and put that in it:

command! -buffer Toc Voom

And in ~/.vim/after/ftplugin/tex.vim you can put:

command! -buffer Toc VimtexTocOpen

This way :Toc will be available only in the buffers with the right filetype and the behavior will be different depending on the filetype.

Now if you really want to go the autocommand way, you really should use an augroup like this (see why here) and the -buffer argument is still needed:

augroup Toc
    autocmd Filetype rmd   command! -buffer Toc Voom
    autocmd Filetype tex   command! -buffer Toc VimtexTocOpen
augroup END
  • Thanks for providing 2 solutions. The augroup is quicker to set up on a new machine because you can put it in the .vimrc. Unless I miss something about transferring a vim configuration including ~/.vim/after/ftplugin/ to another machine. Granted, Latex files are generally not the kind of file you edit on a server. Jun 25 '20 at 7:18
  • 1
    It depends how you send your configuration on a new machine. For example my dotfiles contain my vim directory so when I set up a new machine a simple git clone and source set-dotfiles.sh and I'm good to go, it's not longer because I have split my configuration. But yes it depends how you do it.
    – statox
    Jun 25 '20 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.