Typeset (La)TeX and open pdf with one line command from vi/vim (or Emacs, etc.)

I habitually use vim to edit files, particularly latex code. Ashamedly I only recently realized you could make shell calls without leaving vim just by typing

:![command]

When I’m editing a TeX file I am constantly typesetting my document to a pdf then opening the pdf. Here’s a one-line vi(m) specific bash command to typeset your current document to a pdf then open that pdf using your default pdf viewer.


:!if pdflatex "%"; then open "`echo "%" | sed "s/\(\.[^\.]*\)$/.pdf/g"`"; fi

If you do not have or want to use the open command just replace it with some other viewer like ghostview or xpdf.

Note: Here’s the multi-line version of the exact same thing if you want to save it in a callable bash script:


!/bin/bash
if pdflatex $1; then
  open `echo $1 | sed "s/\(\.[^\.]*\)$/.pdf/g"`
fi

If you save the above in an executable file called openpdflatex then you could still call it from vi or vim with


:!openpdflatex %

Update: Occasionally I include .eps figures so I need to first make a .dvi with the latex command then use dvipdf to convert to pdf. Here’s how I do it in one line from vi(m):


:!if latex %; then if dvipdf `echo % | sed "s/\(\.[^\.]*\)$/.dvi/g"`; then open `echo % | sed "s/\(\.[^\.]*\)$/.pdf/g"`; fi; fi

Tags: , , , , , , ,

Leave a Reply