Question

I am trying to make a keymap that will call latexmk when .tex is available (it would be better if .tex is the currently open and active buffer)

I tried :

:nnoremap <Leader>lw :if filereadable('*.tex')<cr>up!<cr>:!latexmk -pdf<cr>endif<cr>

when trying to make latexmk -pdf run, but unfortunately, its just prompting those line in the window, and doing nothing like:

~
:if filereadable('*.tex')
:  up!
:  :call Tex_RunLaTeX()
:  endif
Press ENTER or type command to continue

kindly help.

(it will be great, as told, if this can be done when .tex is the currently open and active buffer.)

NB: this question and its variant has been asked here several time here eg this and this, hence sorry for the repetation. I have failed to solve my problem with those.

Was it helpful?

Solution

You need to do 3 things:

  • fix your mapping to run the command properly
  • create a mapping local to a specific buffer by using the <buffer> option for nnoremap.
  • load the mappings for just a specific filetype.

First fix the mapping by using executing the command as single ex command by using <bar> and removing :'s & <cr>'s. We also remove the filereadable portion because we just wrote the file.

nnoremap <buffer> :up!<bar>!latexmk -pdf<cr>

or you can use an expressing mapping like FDinoff suggested.

Note the <buffer> option on the mapping. This makes the mapping only available to the current buffer not every buffer.

Now we need to make sure this mapping only works for tex filetypes. This can be done via an autocommand in your .vimrc like so:

autocmd FileType tex nnoremap <buffer> :up!<bar>!latexmk -pdf<cr>

The other way option is by creating a filetype plugin. (see :h ftplugin for more details)

A simple example is do create a file named, ~/.vim/ftplugin/text.vim and place your mappings inside like so:

nnoremap <buffer> :up!<bar>!latexmk -pdf<cr>

I personally lean more towards the ftplugin approach but having a everything in your .vimrc file can be nice.

OTHER TIPS

I feel like this could be done with an autocmd.

The autocmd only loads the mapping when the file is a tex file.

autocmd FileType tex nnoremap <leader>lw :up! \| !latexmk -pdf<CR>

If you want to do this filereadable('*.tex') which just checks to see if a file in the directory is a tex file. You could use the expr mapping from the first link. In the else part of the expression we just put an empty string so the mapping will do nothing.

nnoremap <expr> <leader>lw filereadable('*.txt') ? ':up! \| !latexmk -pdf<CR>' : ''
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top