0

I have mapped F10 key to execute different programs (pdflatex, python) depending on the file extension.

autocmd Filetype tex map <F10> :lcd %:p:h<CR> :bel ter pdflatex % <CR>
autocmd Filetype python map <F10> :lcd %:p:h<CR> :bel ter python3 % <CR>

If I open a tex file and then press F10, pdflatex is executed. If I then open a python file in a new tab and press F10, python is executed. But now if I now switch back to the tab having the tex file and press F10, python is executed and not pdflatex. Vim is mapping F10 as per the extension of the last opened file and not the extension of the current file. Can someone please help me resolve the issue. Thank you

1
  • As the answer points out, your issue is related to switching buffers, not tabs.
    – D. Ben Knoble
    Commented Nov 3, 2022 at 13:49

1 Answer 1

2

You have to use buffer-local mappings (see :h :map-local):

autocmd Filetype tex map <buffer> <F10> :lcd %:p:h<CR> :bel ter pdflatex % <CR>
autocmd Filetype python map <buffer> <F10> :lcd %:p:h<CR> :bel ter python3 % <CR>

But these ^ mappings in auto-commands have some unrelated problems:

  • You should wrap autocmd in an autocmd group (see :h augroup)1
  • You should use noremap instead of map to avoid recursive mapping2
  • You should map this only in normal mode (see :nn)3

So a better set of autocommands would be this:

augroup FTMaps
  au!
  autocmd Filetype tex nnoremap <buffer> <F10> :lcd %:p:h<CR> :bel ter pdflatex % <CR>
  autocmd Filetype python nnoremap <buffer> <F10> :lcd %:p:h<CR> :bel ter python3 % <CR>
augroup END

  1. augroup helps you redefining auto-commands easily when you source your $MYVIMRC again.
  2. Otherwise, mapping j to jk, for example, will get vim stuck in forever converting j to jk because j exists in the right-hand-side of the map command.
  3. Because the right-hand-side is usable only in normal mode.
2
  • I would prefer nnoremap instead of noremap here as mapping body only make sense for normal mode.
    – Maxim Kim
    Commented Nov 2, 2022 at 5:47
  • @MaximKim, done.
    – 3N4N
    Commented Nov 2, 2022 at 5:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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