Previously, compiling a LaTeX document in Emacs needs repeated pressing the fast key C-c C-c as below:

  1. Press C-c C-c two times to run the LaTeX command.
  2. Press C-c C-c to run the BibTeX command.
  3. Press C-c C-c two times to run the LaTeX command.
  4. Press C-c C-c to run the View command.

Now I switch to latexmk, i.e. press C-c C-c to run the LaTeXMk command, which can automate the process of compiling LaTeX documents, including the calling of BibTeX.

Configuration for latexmk in $HOME/.latexmkrc:

# Use xelatex to generate PDF file.
$pdf_mode = 5;

# Keep final PDF in the project directory.
$out_dir = '.';

# Put auxiliary files in .latex-build.
$aux_dir = '.latex-build';

# Emulate separate auxiliary and output directories.
$emulate_aux = 1;

Here I ask latexmk to place auxiliary files into a hidden subfolder .latex-build specified in the variable $out_dir, while the generated PDF file and synctex file are still in the current directory specified in the variable $out_dir. N.B. Since TeXLive does not support auxiliary directories, $emulate_aux must be set to 1, so that after the PDF file and synctex file are generated in .latex-build, they will be moved to the current directory.

Emacs configuration:

(setq-default TeX-engine 'xetex)
(setq-default TeX-command-default "LaTeXMk")
(with-eval-after-load 'latex
(setf (cadr (assoc "LaTeXMk" TeX-command-list))
      "latexmk %(file-line-error) %`%(extraopts) %S%(mode)%' %t"))

N.B. In the original TeX-command-list, the actually command line for calling latexmk is

 ("LaTeXMk" "latexmk %(latexmk-out) %(file-line-error) %`%(extraopts) %S%(mode)%' %t"
TeX-run-TeX nil (LaTeX-mode docTeX-mode) :help "Run LaTeXMk")

where %(latexmk-out) will be expanded as -pdf when the TeX engine is default and PDF mode is enabled; it will be expanded as -pdf -pdflatex=xelatex, when the TeX engine is xetex. Both of them will ignore the configuration $pdf_mode = 5 in .latexmkrc. Therefore, the option %(latexmk-out) is removed from the latexmk command line in the above Emacs configuration.

Advantages of using latexmk

  1. Press C-c C-c only one time to produce a PDF file from a LaTeX file.
  2. All auxiliary files are generated in a hidden folder.