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.
| Package | Purpose | Appeared In |
|---|---|---|
| geometry | Page margins and paper | LaTeX Document Structure and Layout |
| fancyhdr | Headers and footers | LaTeX Document Structure and Layout |
| amsmath / amssymb | Math formula enhancement / extended symbols | LaTeX Math Formula Basics, LaTeX Advanced Math Formulas |
| graphicx | Graphics | LaTeX Figures and Tables |
| booktabs / multirow | Three-line tables / vertical cell merging | LaTeX Figures and Tables |
| enumitem | List customization | LaTeX Text Formatting and Lists |
| xcolor | Color definitions | Introduced in this chapter |
| listings | Code listings | Introduced in this chapter |
| hyperref | Hyperlinks and bookmarks | LaTeX Cross-references and Bibliography Management |
| biblatex | Bibliography (modern solution) | LaTeX Cross-references and Bibliography Management |
| float | Forced figure/table positioning [H] | LaTeX Figures and Tables |
When the local environment prompts
File 'xxx.sty' not found, install it withtlmgr 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 , vectors and .
Contact email: uniresearch@email.uniplore.com.
| Command | Purpose | Note |
|---|---|---|
\newcommand | Define a new command | Command name must not conflict with existing commands |
\renewcommand | Redefine an existing command | Use when customizing default styles; modify basic commands with care |
\newenvironment | Define a new environment | Same 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
listingsdepends 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 nested | Yes (sub-files can further use input) | No |
| Forces page break | No | Each file starts with a forced \clearpage |
Works with \includeonly | No | Yes; compiles only specified chapters (great for speed) |
| Suitable granularity | Arbitrary snippets (macros, figures, covers) | Chapter-level large blocks |
Common pitfall:
\includeforces a page break. Using it to stitch "several subsections on the same page" will cause mysterious page breaks—always use\inputfor 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.42points to the offending line—in this example, line 42 misspelled\sectionas\secton. Fix this one place, and a chain of follow-up errors often disappears together.
| Error Message | Meaning | Handling |
|---|---|---|
| Undefined control sequence | Command does not exist: spelling error or missing package | Check spelling against the line number; confirm package is loaded |
| Missing $ inserted | Math command appears in text mode | Put \alpha etc. inside $ $ |
File xxx not found | File or package not found | Check path; tlmgr install xxx |
| Runaway argument | Environment not closed (missing \end) | Add \end{...} at the indicated line |
| LaTeX Error: Environment xxx undefined | Used an undefined environment | Check environment spelling and package |
| ! Emergency stop | Compilation completely stopped | Scroll 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
| Need | Solution |
|---|---|
| Reduce repeated input | Define commands and environments with \newcommand |
| Post code | listings + \lstset global styles |
| Split large documents | \input (snippets) / \include (chapters) |
| One-click compilation | latexmk -xelatex |
| Troubleshooting | Read the line number of the first ! error |