LaTeX Common Packages and Tips
The previous chapters already used quite a few packages; this part wraps them up systematically: a package cheat sheet, custom commands, code typesetting, multi-file projects, latexmk, and debugging know-how.
Mastering this "toolbox" content takes you from being able to write LaTeX to being able to manage LaTeX projects.
Common Packages Cheat Sheet
Packages are loaded with \usepackage[options]{package-name}, all placed in the preamble.
| Package | Purpose | Appearing in This Series |
|---|---|---|
| geometry | Page Margins and Paper | LaTeX Document Structure and Typesetting |
| fancyhdr | Headers and Footers | LaTeX Document Structure and Typesetting |
| amsmath / amssymb | Math formula enhancement / extended symbols | LaTeX Math Formulas Basics, LaTeX Math Formulas Advanced |
| graphicx | Figure | LaTeX Figures and Tables |
| booktabs / multirow | Three-line table / vertical merged cells | LaTeX Figures and Tables |
| enumitem | List customization | LaTeX Text Formatting and Lists |
| xcolor | Color definitions | This section introduces |
| listings | Code Typesetting | This section introduces |
| hyperref | Hyperlinks and Bookmarks | LaTeX Cross-referencing and Bibliography Management |
| biblatex | References (modern approach) | LaTeX Cross-referencing and Bibliography Management |
| float | Forced figure/table placement [H] | LaTeX Figures and Tables |
When the local environment reports "File 'xxx.sty' not found", install it with tlmgr install xxx (TeX Live); MiKTeX downloads it automatically. Overleaf bundles almost all packages, so this is no concern.
Custom Commands: \newcommand
When the same content is written three or more times, it is time to define a command. \newcommand{\cmdname}[number of arguments]{definition}.
Example: Three Kinds of Custom Commands
% no arguments: shorten a long command
\
newcommand
{
\R}{\mathbb{R}
}
% afterwards $\R$ means $\mathbb{R}$
% one argument: wrap a fixed format
\
newcommand
{
\email}[1]{\texttt{#1}
}
% #1 stands for the first argument
% optional argument with default: [number of args][default value]
\
newcommand
{
\vecn}[2][n]{x_1, \dots, x_#1
}
% usage: $\vecn{...}$ yields x_1, ..., x_n
% $\vecn[5]{...}$ yields x_1, ..., x_5
\begin
{
document}
Functions defined on $\R$, vectors $\vecn$ and $\vecn[5]$,
contact email \email{service@runoob.com}.
\end{document
}
| Command | Purpose | Note |
|---|---|---|
| \newcommand | Defining a New Command | The command name must not conflict with an existing command |
| \renewcommand | Redefining an Existing Command | Used when modifying default styles; change basic commands with caution |
| \newenvironment | Defining a New Environment | Same syntax, provide the start and end code |
Let us also learn the syntax for custom environments:
Example: A Custom "Note" Environment
\
newenvironment
{
note
}
% environment name
{
\par\medskip\noindent\textbf{Note:}\itshape
}
% start code
{
\par\medskip
}
% end code
\begin
{
note}
The content here automatically starts with "Note:" and is typeset in italics.
\end{note
}
Code Typesetting: The listings Package
To paste code in technical documents, use the listings package: language highlighting, line numbers, and borders are all automatic.
Example: A Code Block with Highlighting and Line Numbers
\
documentclass
{
ctexart}
\usepackage{listings
}
% code typesetting 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 border
}
\begin
{
document}
\begin{lstlisting}[language=Python, caption=计算斐波那契数列]
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
}

lstlisting is a "verbatim environment": its content is not interpreted by LaTeX at all, and & and % need no escaping. caption is also auto-numbered (Listing 1). Common language names are Python, C, Java, HTML, SQL, bash, etc.; if no language is specified, it is colored as plain text.
listings' support for UTF-8 Chinese depends on the compiler: Chinese comments are fine under XeLaTeX, but garbled under old engines (latex/pdfLaTeX). For Chinese documents, always compile with XeLaTeX.
Multi-File Projects: \input and \include
Once a document exceeds a few hundred lines, split files - main.tex holds only 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 (file name without .tex)
\
input
{
chapters/method
}
% method
\
input
{
chapters/experiment
}
% experiment
\
input
{
chapters/conclusion
}
% conclusion
\bibliographystyle
{
plain}
\bibliography{refs}
\end{document
}
The two commands look similar but have a clear division of labor.
| Comparison Item | \input{file} | \include{file} |
|---|---|---|
| Nestable | Yes (child files can \input again) | No |
| Forces a page break | No page break | Forces \clearpage before each file |
| Works with includeonly | Not supported | Supported; compiles only specified sections (a great speed-up) |
| Suitable Granularity | Any fragment (macro definitions, figures, cover) | Chapter-level large content |
Common pitfall: \include forces a page break, so using it to assemble "several subsections on the same page" causes mysterious page breaks - always use \input for small fragments.
latexmk: One-Command Compilation
The four-pass compilation pipeline from Part 9 is tedious to type manually; latexmk does it all automatically.
$ latexmk -xelatex main.tex # XeLaTeX 引擎编译,自动跑满所有遍数
$ latexmk -xelatex -c main.tex # 清理中间文件(保留 PDF)
$ latexmk -xelatex -C main.tex # 连 PDF 一起清理
latexmk automatically decides: it runs bibtex if there is a .bib, and recompiles until all numbering is stable if the table of contents or references change. Configuring the "build command" to latexmk in the editor is the best practice for a local environment.
Debugging Mindset
LaTeX error messages start with an exclamation mark and include a line number; the format is fixed, and reading the first few lines is enough.
! Undefined control sequence.
l.42 \secton{方法}
l.42 points to the error line - in this example line 42 misspelled \section as \secton. Fix this one spot and the chain of cascading errors often disappears together.
| Error Message | Meaning | Handling |
|---|---|---|
| Undefined control sequence | Command not found: spelling error or missing package | Check spelling against the line number; confirm the package is loaded |
| Missing $ inserted | Math command used in text mode | Put _ ^ \alpha etc. inside $ |
| File 'xxx' not found | File or package not found | Check the path; tlmgr install xxx |
| Runaway argument | Environment not closed (missing \end) | Add \end{...} against the line number |
| LaTeX Error: Environment xxx undefined | Used an undefined environment | Check environment spelling and package |
| ! Emergency stop | Compilation aborts entirely | Scroll up in the log to find the first error |
| Reference undefined (warning) | The reference shows ?? | Compile once more |
Always fix only the first error in the log - later errors are usually a chain reaction from the first. Fix it and recompile; this is far more reliable than changing ten places at once.
Summary
| Requirements | Solution |
|---|---|
| Reduce Repetitive Typing | \newcommand to define commands and environments |
| Paste code | listings + \lstset global style |
| Split large documents | \input (fragments) / \include (chapter-level) |
| One-command compilation | latexmk -xelatex |
| Debugging | Read the line number of the first ! error in the log |