agents/config.yaml
name: latex-rescue
description: Diagnose and fix LaTeX compilation errors
type: skill
skill_file: latex-rescue/SKILL.md
platforms:
claude_code: {}
openai:
model: gpt-4.1
auto_activate:
- triggers:
- "fix.*latex"
- "latex.*wont compile"
- "pdflatex.*error"
- "compilation.*failed"
- "编译报错"
- "帮我修.*latex"
- "/latex-rescue"
file_patterns:
- "*.tex"
references/debug-workflow.md
# Debug Workflow for Stubborn LaTeX Errors
## First 5 Minutes: Triage Checklist
Before diving into any fix, run these checks — they resolve 30-40% of cases instantly:
1. **Which engine?** Check for `fontspec` or `polyglossia` → must use XeLaTeX/LuaLaTeX, not pdflatex
```bash
grep -rl 'fontspec\|polyglossia' *.tex # → use xelatex
```
2. **Stale auxiliary files?** Delete `.aux`, `.bbl`, `.blg`, `.log`, `.toc`, `.lof`, `.lot` and recompile. Many "undefined" errors are just stale caches.
3. **How many errors total?** `grep -c '^!' build.log` — if 50+, focus on the FIRST 3 only; the rest are cascading
4. **Encoding issues?** `file -I *.tex` (macOS) or `file -i *.tex` (Linux) — should be UTF-8. If not, convert with `iconv`
5. **Missing files?** `grep -c 'File.*not found' build.log` — missing `.sty`, `.cls`, `.bib`, or images cause cascading failures
6. **BibTeX backend mismatch?** If `.bcf` exists → project uses biber. If `.aux` has `\citation` → project uses bibtex. Running the wrong backend causes "undefined citation" errors.
## When to Use
Activate this workflow when:
- An error persists after 2 fix attempts
- Fixing one error introduces new errors
- Errors cascade in unpredictable ways
- You're unsure of the root cause
## Principle: Binary Search Debugging
For large `.tex` files with unclear error sources:
### Step 1: Isolate the Problem Region
Comment out the latter half of the document and recompile:
```latex
% After \begin{document}
...first half...
\iffalse
...second half (temporarily disabled)...
\fi
```
If the error disappears, the problem is in the second half.
If the error persists, the problem is in the first half.
Binary search down to the problematic section, then paragraph, then line.
### Step 2: Minimal Reproducing Example (MRE)
Once you've found the problematic region, create a minimal test file:
```latex
\documentclass{article}
% Copy ONLY the packages actually needed
\usepackage{...}
\begin{document}
% Copy ONLY the problematic content
...
\end{document}
```
If the MRE compiles, the issue is interaction with other content.
If the MRE fails, the issue is in the isolated content itself.
### Step 3: Package Elimination
Systematically comment out packages to find conflicts:
```latex
% Comment each, one at a time:
% \usepackage{foo}
% \usepackage{bar}
```
Recompile after each removal. If the error disappears, you've found the conflicting package.
## Stubborn Error Types
### Endless "Missing } inserted" Chain
**Symptom**: First error at line 50 says "Missing }", then every subsequent line also reports errors.
**Root cause**: The first error triggers parser state corruption. **Fix ONLY the first error**, ignore all subsequent errors from the same compilation run.
**Workflow**:
1. Fix ONLY the first error in the .log
2. Recompile
3. Check if new errors appear
4. Repeat
### "Runaway argument" Errors
**Symptom**: `! Runaway argument? ... Paragraph ended before \foo was complete.`
**Cause**: A fragile command in a moving argument (like `\caption` or `\section`).
**Fix**:
```latex
% Before (fragile command in moving argument)
\caption{Results for \footnote{Details} testing}
% After (protected)
\caption{Results for \protect\footnote{Details} testing}
% Alternative: use optional argument for short form
\caption[Short form]{Long form with \protect\footnote{Details}}
```
Note: If the command is also invalid outside math mode (e.g., `\alpha`), add `$...$` as well — that is a separate error from the fragile-command issue.
### `Emergency stop` After Many Errors
**Symptom**: `! Emergency stop.` after many other errors.
**Fix**: Fix the first 3-5 errors in the log. The "emergency stop" is a symptom, not the cause. When LaTeX hits too many errors, it gives up.
## Project-Specific Issues
### main.tex compiles but individual .tex files don't
**Symptom**: `! LaTeX Error: Missing \begin{document}.` when compiling `sections/intro.tex` directly.
**Cause**: `\include`d files don't have preambles. They only work within `main.tex`.
**Fix**: Always compile the main document (`main.tex`), never individual included files.
### File encoding issues
**Symptom**: Strange characters or `! Package inputenc Error: Unicode character ...` appearing.
**Fix**:
1. Check file encoding: `file -I file.tex` (macOS) or `file -i file.tex` (Linux)
2. If not UTF-8, convert: `iconv -f GB2312 -t UTF-8 file.tex > file_utf8.tex && mv file_utf8.tex file.tex`
3. Verify `\usepackage[utf8]{inputenc}` is in preamble
### pdflatex vs xelatex vs lualatex
**Symptom**: Compilation works with xelatex but not pdflatex (or vice versa).
**Key differences**:
- `pdflatex`: requires fontenc/inputenc, no system fonts
- `xelatex`/`lualatex`: use fontspec, can access system fonts, native UTF-8
**If the user has fontspec** in their document: use `xelatex` or `lualatex`. Don't try to make it work with pdflatex.
**Determine which engine to use**:
```bash
grep -rl 'fontspec\|polyglossia' *.tex # → use xelatex/lualatex
grep -rl 'fontenc\|inputenc' *.tex # → likely pdflatex
```
## When to Escalate to User
Escalate to the user when:
- The error requires domain knowledge (which experiment is described, what the figure should show)
- There are 3+ possible fixes and they have different semantic meanings
- You need to know the intended document structure
- The error involves specialized package (e.g. `tikz`, `pgfplots`, `circuitikz`) with their own syntax
When escalating, provide:
1. What you found
2. Where it is (file:line)
3. What might fix it (with your best guess first)
4. What you need from the user to proceed
## Common Error Chains
One real error often cascades into many reported errors. Recognizing these chains avoids fixing phantom errors.
### Chain 1: Missing `$` → cascading "Missing } inserted"
```
! Missing $ inserted
(l.42) x_i is important
! Missing } inserted
(l.42) x_i is important
! Extra }, or forgotten $
(l.43) The result shows...
```
**Fix**: Only fix line 42 (`x_i` → `$x_i$`). The errors on line 43+ are phantom.
### Chain 2: Undefined control sequence → everything after breaks
```
! Undefined control sequence
(l.10) \textbff{bold text}
! Missing } inserted
(l.10) \textbff{bold text}
! Paragraph ended before \textbf was complete
(l.11) Next sentence here...
```
**Fix**: Only fix `\textbff` → `\textbf`. All subsequent errors clear.
### Chain 3: Missing `}` in preamble → entire document fails
```
! Missing } inserted
(l.5) \usepackage[utf8]{inputenc
! Emergency stop
```
**Fix**: Add the missing `}`. One character fix, all errors disappear.
### Chain 4: Wrong engine → font errors everywhere
```
! Font \TU/cmr/m/n/10 not found
(l.1) \documentclass{article}
! ... (20+ more font errors)
```
**Fix**: The document uses `fontspec` but was compiled with `pdflatex`. Switch to `xelatex`.
### Chain 5: Stale `.aux` → undefined references + missing labels
```
LaTeX Warning: Reference `fig:arch' on page 3 undefined
LaTeX Warning: Reference `tab:results' on page 5 undefined
LaTeX Warning: Citation `smith2023' on page 6 undefined
```
**Fix**: Delete `.aux`, `.bbl`, `.blg`, recompile twice. If using bibtex, run `bibtex` between the two compilations.
### How to Recognize a Chain
If you see 10+ errors, check:
1. Is the first error a "Missing $", "Missing }", or "Undefined control sequence"? → Fix only that one.
2. Do all errors start at the same line? → It's a chain from that line.
3. Are all errors about fonts? → Wrong engine.
4. Are all errors "undefined reference" or "undefined citation"? → Stale aux files.references/error-catalog.md
# LaTeX Error Catalog
## Error Message Quick-Map
Look up the log message here to jump to the right section:
| Log Message Substring | Category | Section Below |
|---|---|---|
| `Undefined control sequence` | Typo or missing package | Command Typos / Package → Command Mapping |
| `Missing $ inserted` | Math mode | Math Mode Errors |
| `Missing } inserted` / `Extra }` | Braces | Bracket/Brace Errors |
| `begin{...} ended by \end{...}` | Environment mismatch | Environment Errors |
| `Environment ... undefined` | Missing package | Environment → Package Mapping |
| `Missing \endcsname inserted` | Broken label/key | Syntax Errors |
| `Runaway argument` | Fragile command in moving arg | Syntax Errors |
| `Paragraph ended before ... was complete` | Missing brace or fragile cmd | Syntax Errors |
| `Illegal parameter number` | Wrong `\newcommand` definition | Syntax Errors |
| `Option clash` | Package loaded twice with diff options | Package Errors |
| `Command already defined` | Package conflict | Package Errors |
| `File ... not found` | Missing package or file | Package Errors |
| `LaTeX Warning: Citation ... undefined` | Missing .bib entry | Citation Errors |
| `LaTeX Warning: Reference ... undefined` | Missing \label | Reference Errors |
| `Cannot determine size of graphic` | Missing image file | Float Errors |
| `Too many }'s` / `Too few }'s` | Brace mismatch | Bracket/Brace Errors |
| `Misplaced \hline` | Table formatting | Table Errors |
| `Extra alignment tab` | Too many `&` in table row | Table Errors |
| `Unicode char not set up` | Special character encoding | Encoding Errors |
| `Font ... not found` | Missing font package | Font Errors |
## Typo Corrections (auto-fix)
### Command Typos
| Wrong | Correct |
|-------|---------|
| `\beginn{` | `\begin{` |
| `\endd{` | `\end{` |
| `\hlin` | `\hline` |
| `\usepacakge` | `\usepackage` |
| `\usepackge` | `\usepackage` |
| `\documentclas` | `\documentclass` |
| `\bibiographystyle` | `\bibliographystyle` |
| `\bibliographystye` | `\bibliographystyle` |
| `\textbfseries` | `\textbf` |
| `\labl` | `\label` |
| `\capton` | `\caption` |
| `\incluegraphics` | `\includegraphics` |
| `\centeringg` | `\centering` |
| `\documnetclass` | `\documentclass` |
| `\begn{document}` | `\begin{document}` |
| `\end{docment}` | `\end{document}` |
| `\seciton{` | `\section{` |
| `\subsectoin{` | `\subsection{` |
| `\subsubsectoin{` | `\subsubsection{` |
| `\figur{` | `\figure` (but `figure` is an env — use `\begin{figure}`) |
| `\refrences` | `\section*{References}` (not a standard command) |
| `\biblography` | `\bibliography` |
| `\bibilography` | `\bibliography` |
| `\citep{` without natbib | `\cite{` (or add `\usepackage{natbib}`) |
### Environment-Name Typos
These appear inside `\begin{...}` or `\end{...}`. Fix the environment name:
| Wrong | Correct | Note |
|-------|---------|------|
| `\tabel` | `\begin{table}` | `table` is an environment, not a command |
| `\tabl` | `\begin{table}` | Same |
| `\fig` | `\begin{figure}` | `figure` is an environment, not a command |
| `\figre` | `\begin{figure}` | Same |
| `\tabluar` | `\begin{tabular}` | Same |
| `\algin` | `\begin{align}` | Same |
| `\itemz` | `\begin{itemize}` | Same |
### Context-Dependent Typos
| Wrong | Correct | Note |
|-------|---------|------|
| `\refrence` | `\ref` | Misspelled `\ref`; not `\bibliography` |
## Math Mode Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `Missing $ inserted` | `\alpha`, `x_i`, `x^2` in text | Wrap in `$...$` |
| Empty math mode | `$ $` or unmatched `$` | Remove space or add missing `$` |
| Double superscript | `x^a^b` | Change to `x^{ab}` or `{x^a}^b`. Ask user. |
| `\left` without `\right` | `\left( x+y` | Add `\right)` or `\right.` |
## Bracket/Brace Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `Missing } inserted` | Open `{` without close | Count pairs, add missing `}` |
| `Too many }'s` | Extra `}` | Remove extra |
| Mismatched type | `\textbf[text}` | Replace `[` with `{` |
## Environment Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| Environment undefined | Typo in `\begin{foo}` | Correct typo (see table above) |
| Begin/end mismatch | `\begin{figure}`...`\end{table}` | Match `\end` to `\begin` |
| Missing `\begin{document}` | Content before doc starts | Move content after `\begin{document}` |
| Wrong nesting | `A → B → end A → end B` | Reorder ends (LIFO) |
## Citation and Reference
| Error | Pattern | Fix |
|-------|---------|-----|
| Citation undefined | `\cite{key}` not in .bib | Check .bib, suggest similar keys |
| Reference undefined | `\ref{label}` has no `\label` | Check for missing/wrong label, add if needed |
| Missing bibliography | No `\bibliography{...}` | Add `\bibliographystyle` + `\bibliography` |
## Package Issues
| Error | Pattern | Fix |
|-------|---------|-----|
| `Option clash` | Same package loaded twice with different options | Remove duplicate, merge options |
| `Command already defined` | Two packages define same command | Check load order in `package-conflicts.md` |
| `File not found` | `\usepackage{foo}` where foo.sty missing | Install package or flag missing dep |
| `Package X Error` | Package-specific error | Read error message for package-specific guidance |
## Table/Array Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `Extra alignment tab` | Too many `&` for column count | Reduce `&` or add columns |
| `Misplaced \noalign` | `\hline` in wrong position | Check table structure |
| `Illegal unit of measure` | Bad column width spec | Check `p{...}`, `m{...}` arguments |
## Float and Figure Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `Float too large` | Figure/table exceeds page | Reduce size with `[width=\textwidth]` |
| `Unknown graphics extension` | Missing file extension | Add .png/.pdf/.jpg extension |
| `Cannot determine size` | Graphics file not found/corrupt | Check file path exists |
## Overfull/Underfull Warnings
| Warning | Meaning | Action |
|---------|---------|--------|
| `Overfull \hbox` | Text exceeds line width | Reword or add hyphenation: `\-` |
| `Underfull \hbox` | Too much stretch in line | Usually ignore unless very bad |
| `Overfull \vbox` | Content exceeds page height | Reduce content or adjust margins |
## Encoding Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `Unicode char not set up` | Special character in source | Add `\usepackage[utf8]{inputenc}` or escape char |
| `Invalid UTF-8 byte` | File encoding mismatch | Ensure file is UTF-8, not GB2312 |
| `Package babel Error: Unknown option` | Wrong language/option for babel | Check babel documentation for supported options; ensure correct language name |
## Auxiliary File Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `File ended while scanning use of \@writefile` | Corrupted `.aux` file | Delete all `.aux`, `.toc`, `.lof`, `.lot` files and recompile |
| `I'm not what you think you are` | Stale `.aux` from different document class | Delete `.aux` file and recompile twice |
## Spacing Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `There's no line here to end` | `\\` outside tabular/array or at start of paragraph | Remove `\\` or use `\par` instead |
| `Missing \endgroup inserted` | Misplaced `\\` in moving argument | Use `\protect\\` or restructure |
## Font Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `Font ... not found` | Missing font package | Install font or use `\usepackage{lmodern}` |
| `Command \texttildelow unavailable` | Wrong font encoding | Use `\usepackage[T1]{fontenc}` |
| `Some font shapes were not available` | Missing bold/italic variant | Substitution warning, usually harmless. Flag if important. |
| `Corrupted NFSS tables` | Multiple fontenc calls | Only one `\usepackage[...]{fontenc}` allowed |
## Cross-Reference Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `Reference 'X' on page Y undefined` | `\ref{label}` without `\label{label}` | Add `\label{label}` after `\caption{}` or section |
| `Label 'X' multiply defined` | Duplicate `\label{label}` | Rename one of them |
| `\cref format for label type X undefined` | cleveref doesn't know label type | Define with `\crefname{}{}{}` |
## Counter Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `No counter 'X' defined` | `\setcounter` with unknown counter | Check counter name (typo?) |
| `Counter too large` | Too many numbered items | Reset counter or switch to letters |
## Document Structure Errors
| Error | Pattern | Fix |
|-------|---------|-----|
| `\maketitle undefined` or `\title undefined` | Document class doesn't define maketitle | Check if using `standalone` or minimal class |
| `Cannot determine size of graphic` | Missing or corrupt image file | Check file path and format |
| `No \title given` | Missing `\title{}` in preamble | Add `\title{...}` or ignore if intentional |
## Escalation
If an error is not in this catalog:
1. Read 20 lines around the error line
2. Understand the semantic intent
3. Apply minimal fix
4. If fails → consult `debug-workflow.md`
## Common Error Chains
One real error often causes 5-50 phantom errors. Recognize these to avoid wasting time:
| First (real) error | Phantom errors it causes | Fix only |
|---|---|---|
| `Missing $ inserted` on line N | `Missing } inserted` on N+1, N+2, ... | Line N: wrap in `$...$` |
| `Undefined control sequence \textbff` | `Missing }`, `Paragraph ended before` | Line: `\textbff` → `\textbf` |
| Missing `}` in preamble | `Emergency stop` + all content fails | Add the `}` |
| Wrong engine (fontspec + pdflatex) | 20+ `Font not found` errors | Switch to `xelatex` |
| Stale `.aux` | `Reference undefined` × many | Delete `.aux`, recompile twice |
| `\hline` outside tabular | `Misplaced \noalign` + `Extra alignment tab` | Move `\hline` inside table env |
**Rule**: If 10+ errors appear, fix ONLY the first one, then recompile. The rest usually vanish.
## Package → Command Mapping
When `Undefined control sequence \X` appears and it's not a typo, the command likely comes from a missing package:
| Command | Package | Notes |
|---------|---------|-------|
| `\hl{}` | `soul` | Highlight text |
| `\ul{}` | `soul` | Underline text |
| `\st{}` | `soul` | Strikethrough text |
| `\cmark` / `\xmark` | `pifont` + custom def | Use `\ding{51}` / `\ding{55}` |
| `\checkmark` | `amssymb` | Already loaded in most math papers |
| `\mathbb{}` | `amssymb` | Blackboard bold (R, N, Z) |
| `\bm{}` | `bm` | Bold math |
| `\cref{}` | `cleveref` | Smart cross-references |
| `\autoref{}` | `hyperref` | Auto-typed references |
| `\subcaption{}` | `subcaption` | Sub-figure captions |
| `\subfloat{}` | `subfig` | Alternative sub-figure (older) |
| `\algorithmic` | `algorithmic` | Pseudocode |
| `\SetAlgoLined` | `algorithm2e` | Alternative pseudocode |
| `\cellcolor{}` | `colortbl` + `xcolor` | Table cell coloring |
| `\rowcolor{}` | `colortbl` + `xcolor` | Table row coloring |
| `\diagbox{}` | `diagbox` | Diagonal cell headers |
| `\multirow{}` | `multirow` | Multi-row table cells |
| `\thead{}` | `makecell` | Table header formatting |
| `\lstinline` | `listings` | Inline code |
| `\mintinline` | `minted` | Inline code with highlighting |
| `\tcb{}` | `tcolorbox` | Colored boxes |
| `\tikz` | `tikz` | Drawings |
| `\pgfplotscreateplotcyclelist` | `pgfplots` | Plot cycle lists |
| `\printbibliography` | `biblatex` | Bibliography (replaces \bibliography) |
| `\printacronym` | `glossaries` | Acronym list |
| `\si{}` / `\SI{}` | `siunitx` | Units and numbers |
| `\num{}` | `siunitx` | Formatted numbers |
## Environment → Package Mapping
When `Environment foo undefined` appears:
| Environment | Package |
|-------------|---------|
| `algorithm` | `algorithm` (float wrapper) |
| `algorithmic` | `algorithmic` (pseudocode body) |
| `align` | `amsmath` |
| `gather` | `amsmath` |
| `multline` | `amsmath` |
| `cases` | `amsmath` |
| `subfigure` | `subcaption` or `subfig` |
| `subtable` | `subcaption` |
| `lstlisting` | `listings` |
| `minted` | `minted` (+ Python Pygments) |
| `tcolorbox` | `tcolorbox` |
| `tikzpicture` | `tikz` |
| `tabularx` | `tabularx` |
| `longtable` | `longtable` |
| `booktabs` | Not an env — it provides `\toprule`, `\midrule`, `\bottomrule` |
| `figure*` | Built-in (two-column float, no package needed) |
| `table*` | Built-in (two-column float, no package needed) |
| `split` | `amsmath` (single equation split across lines) |
| `aligned` | `amsmath` (like align but used inside equation) |
| `bmatrix` | `amsmath` (bracketed matrix) |
| `pmatrix` | `amsmath` (parenthesized matrix) |
| `Vmatrix` | `amsmath` (double-bar matrix) |
| `theorem` | `amsthm` (requires `\newtheorem{theorem}{Theorem}` if class doesn't provide it) |
| `proof` | `amsthm` |
| `remark` | `amsthm` (requires `\newtheorem{remark}{Remark}`) |references/package-conflicts.md
# Package Conflicts
## Known Conflicts
| Package A | Package B | Conflict | Resolution |
|-----------|-----------|----------|------------|
| `hyperref` | `glossaries` | Load order matters | Load `hyperref` last (or use `\usepackage[implicit]{glossaries}` before hyperref) |
| `hyperref` | `algorithm2e` | Hyperref patches conflict with algo refs | Load `hyperref` last |
| `subfigure` | `subcaption` | Both define sub-figure commands | Use ONLY `subcaption` (modern replacement) |
| `cite` | `natbib` | Both modify `\cite` | Use `natbib` (more features); remove `cite` |
| `algorithmic` | `algorithm2e` | Both define algorithm environments | Choose one; prefer `algorithm2e` |
| `amsmath` | `mathtools` | `mathtools` superset of `amsmath` | Use `mathtools` (auto-loads `amsmath`); remove explicit `amsmath` |
| `fancyhdr` | `titlesec` | Heading style conflicts | Accept minor incompatibilities or use `scrlayer-scrpage` |
| `listings` | `minted` | Both for code listing | Choose one; `minted` for syntax coloring, `listings` for simpler |
| `pdfx` | Various | PDF/A compliance changes everything | Accept limitations or drop PDF/A requirement |
| `xcolor` | `color` | Both define color commands | Use `xcolor` only (it supersedes `color`) |
| `ulem` | `soul` | Both for underlining/striking | Choose one based on whether you need UTF-8 support |
| `natbib` | `biblatex` | Both modify citation system | Cannot coexist; choose one (`biblatex` is modern, `natbib` is traditional) |
| `todonotes` | `xcolor` | Option clash on color model | Load `xcolor` before `todonotes`, or pass options via `\PassOptionsToPackage` |
| `cleveref` | `varioref` | Both augment `\ref` | Compatible; load `varioref` first, `cleveref` after |
## No-Conflict Pairs (commonly confused)
These pairs are sometimes assumed to conflict but actually work together:
| Package A | Package B | Note |
|-----------|-----------|------|
| `microtype` | `fontspec` | No conflict; both work with modern engines (XeLaTeX/LuaLaTeX) |
| `csquotes` | `babel` | No conflict; `csquotes` complements `babel` |
## General Rules
1. **Load `hyperref` late** — it patches many commands and must come after packages that define cross-references. Exceptions: `cleveref` must come AFTER `hyperref`, and `glossaries` with `[implicit]` option may come before. So the typical late order is `...glossaries[implicit]...hyperref...cleveref`.
2. **Load font/encoding packages in order**: `inputenc` → `fontenc` → `lmodern` (or other font package). This is standard recommended practice, not a conflict.
3. **One of each function**: don't load multiple packages that do the same thing (e.g. two float-handling packages).
4. **Check the .log for warnings**: packages print warnings about conflicts. Grep for `Package.*Warning` in the log.
5. **Use `\PassOptionsToPackage`** to resolve option clashes without changing package load order.
## Canonical Preamble Load Order
Follow this order to prevent 80%+ of package conflicts:
```latex
% 1. Document class
\documentclass[...]{...}
% 2. Global options (before any package)
\PassOptionsToPackage{option}{package} % if needed
% 3. Encoding and fonts (pdflatex only; skip for XeLaTeX/LuaLaTeX)
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
% 4. Language
\usepackage[english]{babel}
% 5. Math
\usepackage{mathtools} % auto-loads amsmath
% 6. Tables and figures
\usepackage{booktabs}
\usepackage{graphicx}
\usepackage{subcaption} % not subfigure
% 7. Algorithms
\usepackage{algorithm2e} % or algorithmic — not both
% 8. Other domain packages
\usepackage{siunitx}
\usepackage{listings} % or minted — not both
% 9. Typography and layout
\usepackage{microtype}
\usepackage{xcolor} % not color
% 10. Cross-referencing (hyperref BEFORE cleveref)
\usepackage{hyperref}
\usepackage{cleveref}
% 11. Bibliography (choose ONE system)
% Option A: natbib + bibtex
\usepackage{natbib}
% Option B: biblatex + biber
% \usepackage[backend=biber,style=numeric]{biblatex}
```
## Conflict Detection Workflow
When encountering a `Command already defined` or `Option clash` error:
1. **Find both sources**: grep the .log for which package defined the command first
2. **Check this catalog** for known conflicts and resolutions
3. **Determine which one to keep**:
- If one is deprecated → remove it
- If one is a superset of the other → keep superset
- If they serve different purposes → reorder (usually load more specific one later)
4. **Test**: after resolution, compile twice and check for new issues
## Common Issue: Font Encoding Loop
```
! LaTeX Error: Command \texttildelow unavailable in encoding OT1.
```
**Cause**: Loading `fontenc` without specifying T1 encoding.
**Fix**: Change to `\usepackage[T1]{fontenc}` or accept OT1 limitations.
## Common Issue: natbib vs cite
```
! LaTeX Error: Command \cite already defined.
```
**Cause**: Both `cite` and `natbib` loaded.
**Fix**: Remove `\usepackage{cite}`. `natbib` provides numeric citations via `\setcitestyle{numbers}`.
## Common Issue: biblatex vs natbib
```
! LaTeX Error: Command \cite already defined.
```
**Cause**: Both `biblatex` and `natbib` loaded — these are incompatible.
**Fix**: Choose one. `biblatex` is the modern system (uses `biber` backend); `natbib` is traditional (uses `bibtex`). Remove the other completely, including the corresponding backend call.
## Common Issue: pdfx with other packages
**Cause**: `pdfx` enforces PDF/A compliance and is very strict about metadata.
**Fix**: Follow `pdfx` requirements strictly, or if PDF/A is not required, remove `pdfx` and use `hyperref` directly.SKILL.md
---
name: latex-rescue
description: Diagnose and fix LaTeX compilation errors. Handles undefined control sequences, missing brackets, math mode violations, package conflicts, undefined references, and environment mismatches.
version: 1.2.0
triggers:
- "fix my LaTeX errors"
- "论文编译报错"
- "latex won't compile"
- "pdflatex error"
- "compilation failed"
- "帮我修 LaTeX"
- "/latex-rescue"
---
## Role
You are a LaTeX debugging expert with deep knowledge of TeX error messages, common failure patterns, and systematic debugging methodology. You have access to comprehensive reference catalogs of known errors and their fixes.
## When to Activate
Activate this skill when the user:
- Mentions LaTeX compilation failure
- Shows a LaTeX error message or log excerpt
- Says their paper won't compile
- Invokes you with `/latex-rescue`
## Workflow
### Phase 1: Quick Entry (Pasted Error Message)
If the user pastes an error message directly instead of pointing to a project directory:
1. Extract the error type from the message
2. Identify the offending file/line if present
3. Ask the user to point you to the project directory for context
4. Proceed to Phase 2
### Phase 2: Gather Information
1. **Identify the main `.tex` file.** If the project has `main.tex`, use that. Otherwise scan for `.tex` files containing `\documentclass`. If ambiguous, ask the user.
2. **Detect the LaTeX engine.** Check the preamble for engine-specific packages:
- `\usepackage{fontspec}` or `\usepackage{polyglossia}` → use `xelatex` or `lualatex`
- `\usepackage[utf8]{inputenc}` + `\usepackage[T1]{fontenc}` → likely `pdflatex`
- When in doubt, try `pdflatex` first (most common in CS academia)
3. **Run first compilation** to capture the current state:
```bash
pdflatex -interaction=nonstopmode -file-line-error main.tex 2>&1 | tee build.log
```
(Replace `pdflatex` with `xelatex` or `lualatex` if detected in step 2.)
4. If the project uses a bibliography backend, run that too:
```bash
# For bibtex (traditional):
bibtex main 2>&1 | tee -a build.log
# For biber (biblatex projects):
biber main 2>&1 | tee -a build.log
```
Detect which backend: if preamble has `\usepackage{biblatex}`, use `biber`; if it has `\bibliographystyle{...}`, use `bibtex`.
### Phase 3: Parse and Classify Errors
Read `build.log` (or the `.log` file). Extract every error. For each error, record:
- **File** and **line number**
- **Error type** (see classification below)
- **The offending source line**
- **10 lines of surrounding context** (read from source)
Classify each error into one of these categories:
| Category | Pattern | Auto-fix? |
|----------|---------|-----------|
| `typo` | `\beginn{`, `\endd{`, `\hlin`, `\usepacakge` | Yes — correct known typos |
| `missing-bracket` | `Missing } inserted`, `Missing $ inserted` | Yes — match pairs |
| `math-mode` | `Missing $`, `Please use \mathaccent` | Yes — wrap in math mode |
| `undefined-cs` | `Undefined control sequence` | Conditional — check if typo first |
| `environment` | `\begin{foo} ended with \end{bar}` | Yes — align begin/end |
| `package-conflict` | `Option clash`, `Command already defined` | No — consult references |
| `undefined-ref` | `Reference undefined`, `Citation undefined` | No — flag for user review |
| `hbox-overfull` | `Overfull \hbox`, `Underfull \hbox` | No — flag as warning |
| `file-not-found` | `File not found` | No — check paths |
| `syntax` | `Runaway argument`, `Paragraph ended before` | Conditional — contextual fix |
### Phase 4: Fix Strategy
Apply fixes in this order — easy wins first, then escalate.
#### 4.1 Direct Fixes (no LLM needed)
Fix these immediately without consulting an LLM:
**Typo corrections** — map known misspellings to their correct forms:
```
\beginn{ → \begin{
\endd{ → \end{
\hlin → \hline
\usepacakge → \usepackage
\usepackge → \usepackage
\documentclas → \documentclass
\bibiographystyle → \bibliographystyle
\bibliographystye → \bibliographystyle
\textbfseries → \textbf
```
**Deprecated command → modern equivalent** (these compile but produce warnings or have wrong scoping):
```
\bfseries{...} → \textbf{...} (only when used as a command with argument; {\bfseries text} is valid declaration syntax)
\it{...} → \textit{...} (same: \it is a valid but deprecated declaration; \textit{} is the modern command form)
```
**Environment-name typos** — misspelled names inside `\begin{...}` / `\end{...}`:
```
\begin{tabel} → \begin{table}
\begin{tabl} → \begin{table}
\begin{fig} → \begin{figure}
\begin{figre} → \begin{figure}
\begin{algin} → \begin{align}
\begin{itemz} → \begin{itemize}
```
**Other command typos**:
```
\refrence → \ref (misspelled \ref; not \bibliography)
\labl → \label
\capton → \caption
```
**Missing closing brackets/braces** — count open/close pairs:
```
{ but no } → add }
[ but no ] → add ]
( but no ) → add )
```
**Missing `$` around math** — wrap standalone math symbols in `$...$`:
```
\alpha without $ → $\alpha$
x_i without $ → $x_i$
\mathbf{X} without $ → $\mathbf{X}$
```
**Environment mismatch** — align `\end{}` with previous `\begin{}`:
```
\begin{table}
...
\end{table*} → \end{table}
```
#### 4.2 Common Error-Specific Fixes
For errors with known fix patterns, consult `references/error-catalog.md`. This catalog contains common LaTeX errors with specific fix instructions. Always check the catalog before attempting a generic fix.
Key patterns to know without searching:
**`Undefined control sequence \X`** — check in this order:
1. Is it a known typo? Apply typo correction.
2. Is the user missing `\usepackage{...}`? If the command is from a known package (e.g. `\hl{}` needs `\usepackage{soul}`), suggest adding it.
3. Is it a custom command? Check if it's defined elsewhere in the project (grep for `\newcommand{\X}`).
**`Missing \begin{document}`** — the preamble has content that's not allowed before `\begin{document}`. Typically:
- A `\maketitle` or `\section{}` before `\begin{document}`
- Text outside any command in the preamble
Fix: flag the offending line and suggest moving it after `\begin{document}`.
**`Environment foo undefined`** — the environment `foo` doesn't exist. Usually:
- Missing `\usepackage` that defines it (e.g. `{algorithm}` needs `\usepackage{algorithm}`)
- Typo in the name
- Fix: look up `foo` in the Environment → Package Mapping table in `references/error-catalog.md` to find which package provides it.
#### 4.3 Complex Fixes (use LLM judgment)
For errors not covered by the catalog:
1. Read 20 lines of context around the error
2. Identify the semantic intent (what was the user trying to do?)
3. Apply the minimal fix to satisfy both syntax and intent
4. If unsure between multiple fixes, apply the simplest one and verify
### Phase 5: Verify
After each batch of fixes, run a **full compile cycle** to ensure cross-references and citations resolve:
```bash
# If project uses BibTeX:
pdflatex -interaction=nonstopmode -file-line-error main.tex && \
bibtex main && \
pdflatex -interaction=nonstopmode -file-line-error main.tex && \
pdflatex -interaction=nonstopmode -file-line-error main.tex
# If project uses no bibliography, run twice for cross-references:
pdflatex -interaction=nonstopmode -file-line-error main.tex && \
pdflatex -interaction=nonstopmode -file-line-error main.tex
```
**Alternative**: If `latexmk` is installed, it handles multi-pass automatically:
```bash
latexmk -pdf -interaction=nonstopmode main.tex
```
**Checking results**:
- Extract errors: `grep '^!' build.log | head -20` (more reliable than `tail` for multi-file projects)
- Count warnings: `grep -c 'Warning' build.log`
- Check for undefined references: `grep 'undefined' build.log`
**Decision**:
- If **clean**: report all fixes applied, show final status
- If **fewer errors**: continue fixing remaining errors (max 3 fix cycles total)
- If **same number of errors**: the fix didn't work. **Do NOT re-apply the same fix.** Consult `references/debug-workflow.md` for escalation strategies.
- If **more errors**: the fix introduced regressions. **Roll back the fix** and try a different approach.
- If **3 fix cycles completed** without clean compile: escalate to user with a summary of remaining errors and suggested next steps.
**Common false positives after a single-pass compile**:
- `Reference 'X' undefined` — usually resolves after a second `pdflatex` run
- `Citation 'X' undefined` — run `bibtex` then recompile twice
- `Label multiply defined` — this is a real error, not a false positive
### Phase 6: Report
After resolution, report:
```
=== LaTeX Rescue Summary ===
Fixed:
- sections/intro.tex:14 \beginn{table} → \begin{table}
- sections/method.tex:8 missing $ around \alpha
- tables/results.tex:3 environment mismatch: table/table*
Warnings (not fixed):
- main.tex:247 Overfull hbox (badness 7431)
- refs.bib:32 Missing year in smith2023
Compilation: ✓ clean / 0 errors / 3 warnings
```
## Guardrails
**NEVER modify:**
- Content inside `\cite{}`, `\ref{}`, `\label{}`, `\eqref{}`
- Mathematical content inside display math environments (`equation`, `align`, `gather`, `multline`, etc.)
- `\author{}`, `\title{}`, `\date{}` metadata
- BibTeX entry keys or content (`@article{...}` blocks)
- Comment lines (`% ...`)
- Content inside `\verb|...|`, `\verb+...+`, `\lstinline|...|`, or `\begin{verbatim}` blocks
- File paths inside `\includegraphics{}`, `\include{}`, `\input{}`, `\bibliography{}`
**ALWAYS:**
- Make the minimal change to fix the error
- Keep a mental diff of what you changed (to report and to roll back)
- Recompile after every fix batch to verify
- Prefer 1-line fixes over multi-line rewrites
**WHEN IN DOUBT:**
- Flag the error for user review rather than guessing
- For `undefined-ref` errors, do NOT invent reference keys. Tell the user which refs are missing.
- NEVER delete blocks of content to eliminate errors. If a block is problematic, comment it out with `% [RESCUE-REMOVED: reason]` and flag it.
- NEVER edit `.sty`, `.cls`, or `.bst` files shipped with the template. Only edit user `.tex` files.
**AFTER FIXING:**
- If the user needs to polish the text after fixing errors, suggest `/latex-polish`
- If the user needs to reformat for a different venue, suggest `/latex-fmt`
## Advanced Scenarios
### Multi-file Projects
Projects using `\include{...}` or `\input{...}`:
- Compilation errors report the file and line where the error actually occurs
- When fixing, edit the included file, not `main.tex`
- If an included file has a preamble-like content, flag it
### BibTeX/Biber Issues
For citation errors:
- `Citation X undefined` — check if X exists in `.bib` file. If not, search for similar keys (fuzzy match).
- `Missing year in X` — the bib entry has no year field
- `Warning -- empty journal in X` — entry metadata incomplete
- Run `bibtex main` or `biber main` after changing .bib, then recompile twice
### Two-Column vs One-Column
Switching column layout often breaks floats:
- `table*` → `table` (or vice versa) depending on document class
- Check preamble for `\documentclass[twocolumn]{...}`
### Overleaf Projects
Overleaf users cannot run local compilation commands. Adapt the workflow:
1. **Ask the user to paste the error message** from the Overleaf log (click "Logs and output files")
2. **Diagnose from the error message alone** — classify the error using Phase 3 rules
3. **Apply fixes to the `.tex` files** — the user can copy changes back to Overleaf
4. **Do NOT run `pdflatex` locally** — trust the Overleaf log instead
5. **Overleaf-specific quirks**:
- Overleaf auto-creates `{filename}.blg` and `{filename}.bbl` — `bibtex`/`biber` errors appear there
- Overleaf caches old files — if a fix doesn't take effect, advise clearing cache (Menu → Clear cached files)
- Overleaf uses `latexmk` internally — a single recompile usually resolves cross-references
## Reference Files
When you encounter a specific error class, read the corresponding reference:
- **`references/error-catalog.md`** — catalog of common LaTeX errors with fixes
- **`references/package-conflicts.md`** — known package incompatibilities and workarounds
- **`references/debug-workflow.md`** — systematic debugging for stubborn compilation chains