Hanlon
Hanlon

Reputation: 442

Making commands work only for chosen filetype(s)

I want to map F2 to compiling tex files, and F3 for viewing tex files.

This is what I put in my .vimrc:

if &filetype == "tex"
nnoremap <F2> :Latexmk<cr>
inoremap <F2> <Esc>:Latexmk<cr>a
nnoremap <F3> :LatexView<cr>
inoremap <F3> <Esc>:LatexView<cr>a
endif

These Latex* commands are from LaTeX-Box plugin. I can execute them manually without any problems. Typing :echo &filetype in any *.tex file returns tex.

Upvotes: 2

Views: 186

Answers (2)

romainl
romainl

Reputation: 196556

You have two methods…

  • Create a self-clearing group in your vimrc and add as many autocommands as needed:

    augroup Tex
        autocmd!
        autocmd FileType tex nnoremap <buffer> <F2> :Latexmk<cr>
        autocmd FileType tex nnoremap <buffer> <F3> :LatexView<cr>
        autocmd FileType tex inoremap <buffer> <F2> <Esc>:Latexmk<cr>a
        autocmd FileType tex inoremap <buffer> <F3> <Esc>:LatexView<cr>a
    augroup END
    
  • Use a ftplugin:

    Put the following in after/ftplugin/tex.vim:

    nnoremap <buffer> <F2> :Latexmk<cr>
    nnoremap <buffer> <F3> :LatexView<cr>
    inoremap <buffer> <F2> <Esc>:Latexmk<cr>a
    inoremap <buffer> <F3> <Esc>:LatexView<cr>a
    

The second method is recommended because it is a lot cleaner and less expensive than the first.

Upvotes: 3

Hanlon
Hanlon

Reputation: 442

I replaced the code above with this:

autocmd FileType tex nnoremap <buffer> <F2> :Latexmk<cr>
autocmd FileType tex nnoremap <buffer> <F3> :LatexView<cr>
autocmd FileType tex inoremap <buffer> <F2> <Esc>:Latexmk<cr>a
autocmd FileType tex inoremap <buffer> <F3> <Esc>:LatexView<cr>a

Upvotes: 1

Related Questions