Resolving The Underscore Dilemma: Best Practices For Including Underscores In Latex Documents
Handling Underscores in LaTeX
The underscore character (_) plays an important role in LaTeX. It’s used in file specifications, package names, citations, equations, markup, and more. However, underscores can easily cause problems—leading to frustrating compilation failures or inexplicable output issues. To prevent such problems, LaTeX users must handle underscores carefully within documents. This article explores the common pitfalls and provides a comprehensive guide to resolving the underscore dilemma through best practices.
The Core Issue with Underscores
Background on why underscores can cause problems
In LaTeX, the underscore is a special character reserved for predefined commands and internal typesetting tasks. As such, LaTeX treats underscores differently than regular letters or numbers. Using underscores improperly — without escaping or accounting for their special meaning — disrupts many behind-the-scenes LaTeX processes. The precise way each process uses underscores varies. But core issues caused by underscores relate to how LaTeX:
- Parses commands
- Handles specifications
- Formats output
In terms of command parsing, underscores signal a control sequence named with multiple words. The command \under_score, for instance, comprises two words joined by an underscore. LaTeX would fail to parse this properly if the underscore was not escaped. For specifications, underscores represent spaces. So filepath like my_file.tex would point to a nonexistent “my file.tex” instead of “my_file.tex” if not properly handled. Lastly for output, underscores toggle underlined text when used in the \underline command. Accidental underscores could thus add spurious underlining.
Common errors and issues that arise
These core issues manifest in multitudes of errors — ranging from inscrutable to obvious. On the subtle end, a document may compile but produce inconsistent hyphenation, inaccurate citations, missing graphics, or other discrepancies. More blatantly, compiling outright fails with “undefined control sequence” or “file not found” errors. Across outcomes, nearly all underscore-related problems trace back to unescaped underscores disrupting command parsing, file paths specifications, or text formatting.
Common scenarios that trigger underscore errors include:
- Using underscores in file names or paths without escapes
- Forgetting to load special underscore-heavy packages like ulem and underscore
- Violating package rules for underscore usage in markup, equations, etc
- Assuming citation packages properly handle underscores in bibliographies
Such cases produce a menagerie of bizarre output problems and compilation failures. One infamous example includes equations with phantom underlining due to unescaped underscores. Files mysteriously not compiling also frequently arises. As do unfinished citations or missing files when underscores lack proper escapes in paths. Explicit “undefined control sequence” notifications generally signal underscore-related issues too. While the exact manifestation varies — the underlying underscore causes relate to LaTeX parsing, specification processing, or formatting.
Escaping Underscores
Using the backslash to escape underscores
Escaping underscores with the LaTeX backslash (\) provides the most basic method for preventing issues. The backslash denotes that the following underscore does not carry special meaning. It should simply render as a literal character instead of changing behavior or signaling LaTeX commands.
To escape underscores, simply prepend them with a backslash like \_. For example, to use an underscore in regular text, the passage:
My file is named my\_\_file.tex
Would render properly as:
My file is named my__file.tex
Without the added backslashes, LaTeX would interpret the underscores here as a command and space — causing compile or output errors.
When escaping is necessary or recommended
In general, escaping underscores is necessary in any situation where LaTeX could mistake underscores as signals for changing behavior. This includes cases like:
- Using underscores in file paths and names
- Employing underscores in regular text
- Writing out example LaTeX commands containing underscores
- Listing package names with underscores
- Passing underscores to arguments in formatted commands
In tricky cases involving heavy underscore use, escaping generally causes no harm even when possibly unnecessary. As such, liberal backslash escaping for underscores poses little downside besides minor visual clutter. When in doubt, add the escapes.
Example LaTeX code with escaped underscores
As a case study for employing liberal backslash escaping, consider the following contrived LaTeX document. It loads the fictional my_fancy_package, references my_file.tex, and describes commands like \set_undergraduate_style in text:
\documentclass{article} \usepackage{my\_\_fancy\_\_package} \begin{document} Here is an example file path: \textbackslash my\_\_file.tex We also use the \textbackslash set\_\_undergraduate\_\_style command. \end{document}
This document compiles without issue and avoids nearly all underscore pitfalls by prepending liberal backslash escapes.
Packages for Underscore Support
Beyond manual backslash escaping, several LaTeX packages provide more advanced underscore handing and compatibility.
The ulem package for underlining
The popular ulem package overrides LaTeX’s default \underline command to improve compatibility with underscores. Without ulem, \underline awkwardly toggles underlining on and off with each underscore occurrence. This leads to issues like:
\underline{under_score} => under_score
With ulem’s underscore-aware underlining, the output appears correctly as:
under_score
By installing ulem with \usepackage{ulem}, LaTeX ignores underscores when applying underlines. This prevents spurious formatting issues.
The underscore package
The aptly named underscore package further extends compatibility specifically for underscore support. The package essentially handles low-level LaTeX escapes automatically to prevent common issues. For example, with underscore loaded, a path like:
my_file.tex
Just works without manual escaping. The package handles necessary formatting adjustments internally. This helps cut down on visual backslash clutter.
Beyond automatic escaping, underscore also tweaks font handling to improve underscore display. Loading the package with \usepackage{underscore} activates its underscope compatibility enhancements.
Configuring packages for underscore compatibility
Alongside ulem and underscore, underscore-heavy packages may provide special configuration checks during loading. For example, the fancyvrb package for verbatim text offers a ShowEscapeErrors option to help debug backslash issues:
\usepackage[ShowEscapeErrors]{fancyvrb}
Other packages provide compatability checks specifically for underscore support. Consulting package documentation to enable such underscores options reduces potential issues.
Use Cases for Underscores
With basic escapes and compatability packages handled, underscores can appear safely in many LaTeX contexts. Common use case include filenames, bibliographies, equations, markup, and general text.
Underscores in file names and paths
Using underscores to separate words or dates in LaTeX file names poses few issues with proper handling. Just ensure to escape all underscores when actually referencing the files. Either manually add backslash escapes or load underscore to automatically handle it:
\documentclass{article} \usepackage{underscore} \usepackage{my_custom_2022_styles} \begin{document} Lots of underscores here in \textbackslash my\_\_custom\_\_2022\_\_styles! \end{document}
Underscores in bibliographies and citations
Leading citation packages allow underscores without issue in references when properly declared. For BibTeX, simply wrap theBibfile names with braces like {my_refs.bib} to avoid problems:
\documentclass{article} \usepackage{natbib} \bibliographystyle{plainnat} \bibliography{my_refs} \begin{document} \nocite{*} \bibliography{my_refs} \end{document}
Alternatively, for biblatex references, declare underscores in the biblatex options:
\usepackage[check=underscore]{biblatex}
Underscores in text, equations, and markup
With compatibility packages like ulem and underscore loaded, using underscores in regular text, equations, formatting markup, and code samples avoids nearly all issues:
\usepackage{underscore,ulem} ... \underline{Sample with_underscores} looks good! $math\_with\_underscores$ also works. {\ttfamily Utilities\_2022\_Edition} even handles monospace.
The packages handle necessary escaping and formatting adjustments automatically.
Best Practices Summary
In summary, carefully handling underscores by escaping properly, loading compatability packages, and following other best practices resolves nearly all underscode dilemmas in LaTeX.
Top recommendations for resolving underscores
- Escape underscores with preceding backslashes when possible
- Use ulem and underscore packages for compatibility
- Check package documentation for underscore support
- Wrap BibTeX file references with braces
- Enable biblatex underscore checking
When to use escapes, packages, or alternatives
As rule of thumb:
- First try manually escaping underscores
- Fallback to compatibility packages like underscore and ulem for more advanced handling
- Only avoid underscores completely if other solutions fail
Ensuring compatibility and robust usage
Following underscore best practices helps ensure maximum compatibility and resilience against perplexing compilation errors or formatting issues. Pay special attention to escapes and compatibility packages when using underscores heavily throughout a document’s text, filepaths, equations, markup, citations, and other contexts. With care, underscores can be wielding seamlessly—avoiding nearly all frustrations end dilemmas.