Skip to main content

common-packages-tips

Common Packages and Tips

The previous chapters have already used quite a few packages; this chapter provides a systematic wrap-up: package quick reference, custom commands, code listings, multi-file projects, latexmk, and troubleshooting mindset. Mastering these "toolbox" topics evolves you from someone who can write LaTeX to someone who can manage LaTeX projects.

Common Package Quick Reference

Packages are loaded with \usepackage[options]{package-name}, all placed in the preamble.

PackagePurposeAppeared In
geometryPage margins and paperLaTeX Document Structure and Layout
fancyhdrHeaders and footersLaTeX Document Structure and Layout
amsmath / amssymbMath formula enhancement / extended symbolsLaTeX Math Formula Basics, LaTeX Advanced Math Formulas
graphicxGraphicsLaTeX Figures and Tables
booktabs / multirowThree-line tables / vertical cell mergingLaTeX Figures and Tables
enumitemList customizationLaTeX Text Formatting and Lists
xcolorColor definitionsIntroduced in this chapter
listingsCode listingsIntroduced in this chapter
hyperrefHyperlinks and bookmarksLaTeX Cross-references and Bibliography Management
biblatexBibliography (modern solution)LaTeX Cross-references and Bibliography Management
floatForced figure/table positioning [H]LaTeX Figures and Tables

When the local environment prompts File 'xxx.sty' not found, install it with tlmgr install xxx (TeX Live); MiKTeX will download automatically. Overleaf comes with almost all packages, so no such trouble.

Custom Commands: \newcommand

When you write the same content more than three times, it is time to define a command. \newcommand{command-name}[arg-count][definition].

Example: Three Types of Custom Commands

% No argument: shorten a long command
\newcommand{\R}{\mathbb{R}} % Writing $\R$ now produces $\mathbb{R}$

% One argument: encapsulate a fixed format
\newcommand{\email}[1]{\texttt{#1}} % #1 denotes the first argument

% Optional argument with default value: [arg-count][default]
\newcommand{\vecn}[2][n]{x_1, \dots, x_{#1}}
% Usage: $\vecn$ produces $x_1,\dots,x_n$
% $\vecn[5]$ produces $x_1,\dots,x_5$

\begin{document}
A function defined on $\R$, vectors $\vecn$ and $\vecn[5]$.
Contact email \email{uniresearch@email.uniplore.com}.
\end{document}

A function defined on R\mathbb{R}, vectors x1,,xnx_1, \dots, x_n and x1,,x5x_1, \dots, x_5.

Contact email: uniresearch@email.uniplore.com.

CommandPurposeNote
\newcommandDefine a new commandCommand name must not conflict with existing commands
\renewcommandRedefine an existing commandUse when customizing default styles; modify basic commands with care
\newenvironmentDefine a new environmentSame syntax; provide start and end code

Get to know the syntax for custom environments as well:

Example: Custom "Note" Environment

\newenvironment{note}
{\par\medskip\noindent\textbf{Note:}\itshape} % Start code
{\par\medskip} % End code

\begin{note}
This content will automatically start with "Note:" and be set in italics.
\end{note}

Note: This content will automatically start with "Note:" and be set in italics.

Code Listings: The listings Package

For posting code in technical documents, use the listings package. Language highlighting, line numbers, and borders are all automatic.

Example: Code Block with Highlighting and Line Numbers

\documentclass{ctexart}
\usepackage{listings} % Code listing package
\usepackage{xcolor} % Color support

\lstset{ % Global code style settings
basicstyle=\ttfamily\small, % Monospace font, slightly smaller size
keywordstyle=\color{blue}, % Keywords blue
commentstyle=\color{gray}, % Comments gray
stringstyle=\color{purple}, % Strings purple
numbers=left, % Line numbers on the left
numberstyle=\tiny\color{gray},
showstringspaces=false, % Do not show space markers inside strings
frame=single % Single-line frame
}

\begin{document}

\begin{lstlisting}[language=Python, caption=Computing the Fibonacci Sequence]
# Compute the n-th Fibonacci number (Chinese comment test)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)

print(fib(10)) # Output 55
\end{lstlisting}

\end{document}

Listing 1: Computing the Fibonacci Sequence

# Compute the n-th Fibonacci number (Chinese comment test)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)

print(fib(10)) # Output 55

lstlisting is a "verbatim environment": internal content is not interpreted by LaTeX at all; &, %, etc. do not need escaping. caption is also automatically numbered (Listing 1). Common language names include Python, C, Java, HTML, SQL, bash, etc.; without specifying language, plain text coloring is used.

UTF-8 Chinese support in listings depends on the compiler: Chinese comments work fine under XeLaTeX; older engines (latex/pdfLaTeX) will produce garbled text. For Chinese documents, always use XeLaTeX for compilation.

Multi-file Projects: \input and \include

Once a document exceeds a few hundred lines, it should be split into files—main.tex serves as the skeleton, and content is divided and conquered.

Example: main.tex Skeleton

\documentclass{ctexart}
\usepackage{amsmath, graphicx, booktabs, hyperref}

\begin{document}

\input{chapters/intro} % Introduction (filename without .tex)
\input{chapters/method} % Method
\input{chapters/result} % Experiments
\input{chapters/conclusion}% Conclusion

\bibliographystyle{plain}
\bibliography{refs}

\end{document}

The two commands look similar but have clear behavioral differences:

Comparison\input{file}\include{file}
Can be nestedYes (sub-files can further use input)No
Forces page breakNoEach file starts with a forced \clearpage
Works with \includeonlyNoYes; compiles only specified chapters (great for speed)
Suitable granularityArbitrary snippets (macros, figures, covers)Chapter-level large blocks

Common pitfall: \include forces a page break. Using it to stitch "several subsections on the same page" will cause mysterious page breaks—always use \input for small snippets.

latexmk: One-click Compilation

The four-step compilation pipeline from Chapter 9 is painful to type manually; latexmk automates it.

$ latexmk -xelatex main.tex # XeLaTeX engine, automatically runs all passes
$ latexmk -xelatex -C main.tex # Clean intermediate files together
$ latexmk -xelatex -c main.tex # Keep PDF, clean auxiliary files

latexmk automatically decides: if there is bibtex or changes in table-of-contents references, it compiles more times until all numbers stabilize. In the editor, configure the "build command" as latexmk -xelatex main.tex.

Troubleshooting Mindset

LaTeX error messages start with an exclamation mark and include a line number. The format is fixed; reading the first few lines is enough.

! Undefined control sequence.

l.42 \section{Method}

l.42 points to the offending line—in this example, line 42 misspelled \section as \secton. Fix this one place, and a chain of follow-up errors often disappears together.

Error MessageMeaningHandling
Undefined control sequenceCommand does not exist: spelling error or missing packageCheck spelling against the line number; confirm package is loaded
Missing $ insertedMath command appears in text modePut \alpha etc. inside $ $
File xxx not foundFile or package not foundCheck path; tlmgr install xxx
Runaway argumentEnvironment not closed (missing \end)Add \end{...} at the indicated line
LaTeX Error: Environment xxx undefinedUsed an undefined environmentCheck environment spelling and package
! Emergency stopCompilation completely stoppedScroll up in the log to find the first error
Reference undefined (warning)Reference is ??Compile again

Always fix only the first error in the log—the later errors are mostly chain reactions of the first. Recompile after fixing, which is much more reliable than changing ten places at once.

Summary

NeedSolution
Reduce repeated inputDefine commands and environments with \newcommand
Post codelistings + \lstset global styles
Split large documents\input (snippets) / \include (chapters)
One-click compilationlatexmk -xelatex
TroubleshootingRead the line number of the first ! error