I do a lot of typesetting, and a lot of my work in vim which means that I do a lot of compiling and displaying latex. Normally, I would either use a multiplexer like Screen or Tmux (I actually prefer Screen) to switch back and forth between the source code and compiling; plain old quitting vim to compile; or compiling within vim using something external commands. Although all of them work, they take a lot of keystrokes and are a hassle, and when you have to compile hundreds of times a day, the time adds up. So let’s make it better!
What I want
I want either a command or a key map that will compile my current file and display it.
How I did it
By creating a custom command that compiles the current document using pdflatex, displays it using evince (or your favorite pdf viewer), makes sure that all the output is piped to /dev/null, and then redraws the screen. This will create a user-defined command,
:Latex, that will compile and display your document.
command Latex execute "silent !pdflatex % > /dev/null && evince %:r.pdf > /dev/null 2>&1 &" | redraw!
You want this to be in your
~/.vimrc so that it will autoload.
The first keyword
silent will prevent vim from displaying the “Press ENTER to continue” screen that is usually displayed whenever external commands are executed.
The first step uses pdlatex to compile the current file, denoted by
% and pipes standrard output to
The second step uses a logical
&& so that the command will short-circuit if compilation failed, and then uses evince (or your favorite pdf viewer) to open the file. Note that we use
%:r to get just the filename of the current document and then append
/dev/null and additionally pipe
stdout to prevent errors from getting displayed. The command ends with a bitwise
& so that the pdf viewer runs in the background
Finally the bitwise
| is used to execute multiple commands, after which we redraw the screen. This is necessary to prevent artifacts from showing in the buffer.
Adding a key map (Optional)
:Latex every time you want to compile is also too much, you can additionally map a key to execute it for you.
:map <F2> :Latex <CR>
This will map F2 to execute the Latex command (
More VIM configuration
My entire vim configuration file (along with other common dotfiles) is on GitHub.