> ## Documentation Index
> Fetch the complete documentation index at: https://resources.latex-cloud-studio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Fixing LaTeX Compilation Errors

> Fix LaTeX compilation errors fast. Learn to identify, debug, and resolve common errors with practical solutions and prevention tips.

export const RenderedOutput = ({title = "Rendered output", ctaHref, ctaLabel = "Open LaTeX Cloud Studio", children}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const trackEditorCta = () => {
    const target = new URL(ctaHref, window.location.href);
    globalThis.posthog?.capture?.("docs_app_cta_clicked", {
      source_page: window.location.pathname,
      source_section: "rendered_output",
      cta_variant: "first_compiled_example",
      target_url: target.toString(),
      target_utm_source: target.searchParams.get("utm_source"),
      target_utm_medium: target.searchParams.get("utm_medium"),
      target_utm_campaign: target.searchParams.get("utm_campaign"),
      target_utm_content: target.searchParams.get("utm_content")
    }, {
      transport: "sendBeacon",
      send_instantly: true
    });
  };
  return <details className="rendered-output" onToggle={event => setIsExpanded(event.currentTarget.open)}>
      <summary className="rendered-output__summary">
        <span className="rendered-output__title">{title}</span>
        <span className="rendered-output__hint" aria-hidden="true">View compiled result</span>
      </summary>
      {isExpanded && <div className="rendered-output__content">
          {children}
          {ctaHref && <aside className="rendered-output__cta" aria-label="Continue in the LaTeX editor">
              <span>
                <strong>Ready to use this syntax?</strong>
                Continue in the browser editor when you want to adapt the example in a real project.
              </span>
              <a href={ctaHref} onClick={trackEditorCta}>{ctaLabel}<span aria-hidden="true"> →</span></a>
            </aside>}
        </div>}
    </details>;
};

export const LatexSource = ({filename, source}) => {
  const [copyStatus, setCopyStatus] = useState("Copy");
  const copySource = async () => {
    try {
      await navigator.clipboard.writeText(source);
      setCopyStatus("Copied");
    } catch {
      setCopyStatus("Select and copy");
    }
  };
  return <figure className="latex-source">
      <figcaption className="latex-source__header">
        <span className="latex-source__filename">{filename}</span>
        <button type="button" className="latex-source__copy" onClick={copySource} aria-live="polite">
          {copyStatus}
        </button>
      </figcaption>
      <pre className="latex-source__pre" aria-label={`LaTeX source: ${filename}`} tabIndex="0">
        <code className="language-latex">{source}</code>
      </pre>
    </figure>;
};

export const LatexPreview = ({src, alt, caption, width, height}) => {
  const minZoom = 1;
  const maxZoom = 3;
  const zoomStep = 0.5;
  const measureSvgContent = async (assetSrc, pageWidth, pageHeight) => {
    const cacheKey = "__latexCloudSvgContentBoxCache";
    const contentBoxCache = globalThis[cacheKey] ?? new Map();
    globalThis[cacheKey] = contentBoxCache;
    if (contentBoxCache.has(assetSrc)) return contentBoxCache.get(assetSrc);
    const measurement = (async () => {
      const assetUrl = new URL(assetSrc, window.location.href);
      if (assetUrl.origin !== window.location.origin) {
        throw new Error("Rendered output must use a same-origin SVG asset.");
      }
      const response = await fetch(assetUrl, {
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error(`Rendered output request failed with ${response.status}.`);
      const source = await response.text();
      const documentNode = new DOMParser().parseFromString(source, "image/svg+xml");
      if (documentNode.querySelector("parsererror")) throw new Error("Rendered output is not valid SVG.");
      const sourceSvg = documentNode.documentElement;
      sourceSvg.querySelectorAll("script, foreignObject").forEach(node => node.remove());
      [sourceSvg, ...sourceSvg.querySelectorAll("*")].forEach(node => {
        [...node.attributes].forEach(attribute => {
          if ((/^on/i).test(attribute.name)) node.removeAttribute(attribute.name);
          if ((attribute.name === "href" || attribute.name === "xlink:href") && !attribute.value.startsWith("#")) {
            node.removeAttribute(attribute.name);
          }
        });
      });
      const measurementHost = document.createElement("div");
      measurementHost.className = "latex-preview__measurement-host";
      const measuredSvg = document.importNode(sourceSvg, true);
      measuredSvg.setAttribute("aria-hidden", "true");
      measurementHost.appendChild(measuredSvg);
      document.body.appendChild(measurementHost);
      try {
        const measuredElements = [...measuredSvg.children].filter(node => !["defs", "desc", "metadata", "style", "title"].includes(node.tagName.toLowerCase()));
        const elementBounds = measuredElements.map(node => node.getBBox()).filter(box => [box.x, box.y, box.width, box.height].every(Number.isFinite) && box.width > 0 && box.height > 0);
        if (elementBounds.length === 0) {
          throw new Error("Rendered output has no measurable visible content.");
        }
        const sortedBounds = [...elementBounds].sort((left, right) => left.y - right.y);
        const clusterGap = pageHeight * 0.045;
        const clusters = [];
        sortedBounds.forEach(box => {
          const current = clusters[clusters.length - 1];
          if (!current || box.y - current.bottom > clusterGap) {
            clusters.push({
              boxes: [box],
              bottom: box.y + box.height
            });
            return;
          }
          current.boxes.push(box);
          current.bottom = Math.max(current.bottom, box.y + box.height);
        });
        const contentClusters = clusters.filter(cluster => {
          const clusterBox = cluster.boxes.reduce((combined, box) => {
            const right = Math.max(combined.x + combined.width, box.x + box.width);
            const bottom = Math.max(combined.y + combined.height, box.y + box.height);
            const x = Math.min(combined.x, box.x);
            const y = Math.min(combined.y, box.y);
            return {
              x,
              y,
              width: right - x,
              height: bottom - y
            };
          });
          const centerY = clusterBox.y + clusterBox.height / 2;
          const isMarginFurniture = cluster.boxes.length <= 2 && clusterBox.width < pageWidth * 0.2 && clusterBox.height < pageHeight * 0.04 && (centerY < pageHeight * 0.08 || centerY > pageHeight * 0.8);
          return !isMarginFurniture;
        });
        const visibleBounds = (contentClusters.length > 0 ? contentClusters : clusters).flatMap(cluster => cluster.boxes);
        const bounds = visibleBounds.reduce((combined, box) => {
          const right = Math.max(combined.x + combined.width, box.x + box.width);
          const bottom = Math.max(combined.y + combined.height, box.y + box.height);
          const x = Math.min(combined.x, box.x);
          const y = Math.min(combined.y, box.y);
          return {
            x,
            y,
            width: right - x,
            height: bottom - y
          };
        });
        const clampValue = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, value));
        const padding = Math.max(8, Math.min(pageWidth, pageHeight) * 0.025);
        const x = clampValue(bounds.x - padding, 0, pageWidth);
        const y = clampValue(bounds.y - padding, 0, pageHeight);
        const right = clampValue(bounds.x + bounds.width + padding, 0, pageWidth);
        const bottom = clampValue(bounds.y + bounds.height + padding, 0, pageHeight);
        return {
          x,
          y,
          width: right - x,
          height: bottom - y
        };
      } finally {
        measurementHost.remove();
      }
    })();
    contentBoxCache.set(assetSrc, measurement);
    measurement.catch(() => contentBoxCache.delete(assetSrc));
    return measurement;
  };
  const renderPreviewAsset = ({contentBox: assetContentBox, loading}) => {
    if (!assetContentBox) {
      return <img className="latex-preview__asset" src={src} alt={alt} width={width} height={height} loading={loading} draggable="false" />;
    }
    return <svg className="latex-preview__asset" viewBox={`${assetContentBox.x} ${assetContentBox.y} ${assetContentBox.width} ${assetContentBox.height}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label={alt}>
        <image href={src} x="0" y="0" width={width} height={height} />
      </svg>;
  };
  const [isOpen, setIsOpen] = useState(false);
  const [frameMode, setFrameMode] = useState("content");
  const [viewMode, setViewMode] = useState("fit");
  const [zoom, setZoom] = useState(minZoom);
  const [contentBox, setContentBox] = useState(null);
  const [measurementStatus, setMeasurementStatus] = useState("loading");
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const viewportRef = useRef(null);
  const previousFocusRef = useRef(null);
  const dragRef = useRef(null);
  useEffect(() => {
    let isCurrent = true;
    setMeasurementStatus("loading");
    measureSvgContent(src, width, height).then(box => {
      if (!isCurrent) return;
      setContentBox(box);
      setMeasurementStatus("ready");
    }).catch(() => {
      if (!isCurrent) return;
      setContentBox(null);
      setFrameMode("page");
      setMeasurementStatus("error");
    });
    return () => {
      isCurrent = false;
    };
  }, [height, src, width]);
  const closeViewer = useCallback(() => {
    setIsOpen(false);
  }, []);
  const openViewer = () => {
    previousFocusRef.current = document.activeElement;
    setFrameMode(contentBox ? "content" : "page");
    setViewMode("fit");
    setZoom(minZoom);
    setIsOpen(true);
  };
  const applyZoom = useCallback(nextZoom => {
    const boundedZoom = Math.min(maxZoom, Math.max(minZoom, nextZoom));
    setViewMode("custom");
    setZoom(boundedZoom);
  }, []);
  const zoomIn = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom + zoomStep : zoom + zoomStep);
  }, [applyZoom, viewMode, zoom]);
  const zoomOut = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom : zoom - zoomStep);
  }, [applyZoom, viewMode, zoom]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();
    return () => {
      document.body.style.overflow = previousOverflow;
      previousFocusRef.current?.focus?.();
    };
  }, [isOpen]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const handleKeyDown = event => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeViewer();
        return;
      }
      if ((event.key === "+" || event.key === "=") && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomIn();
        return;
      }
      if (event.key === "-" && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomOut();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')];
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeViewer, isOpen, zoomIn, zoomOut]);
  const startDrag = event => {
    if (event.button !== 0 || !viewportRef.current) return;
    const viewport = viewportRef.current;
    dragRef.current = {
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      scrollLeft: viewport.scrollLeft,
      scrollTop: viewport.scrollTop
    };
    viewport.setPointerCapture(event.pointerId);
    viewport.dataset.dragging = "true";
  };
  const continueDrag = event => {
    const drag = dragRef.current;
    const viewport = viewportRef.current;
    if (!drag || !viewport || drag.pointerId !== event.pointerId) return;
    viewport.scrollLeft = drag.scrollLeft - (event.clientX - drag.x);
    viewport.scrollTop = drag.scrollTop - (event.clientY - drag.y);
  };
  const stopDrag = event => {
    const viewport = viewportRef.current;
    if (viewport?.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
    if (viewport) delete viewport.dataset.dragging;
    dragRef.current = null;
  };
  const activeContentBox = frameMode === "content" ? contentBox : null;
  const activeWidth = activeContentBox?.width ?? width;
  const activeHeight = activeContentBox?.height ?? height;
  const activeRatio = activeWidth / activeHeight;
  const inlineContentBox = measurementStatus === "ready" ? contentBox : null;
  const inlineWidth = inlineContentBox?.width ?? width;
  const inlineHeight = inlineContentBox?.height ?? height;
  const inlineGeometry = {
    aspectRatio: `${inlineWidth} / ${inlineHeight}`,
    maxWidth: `${30 * inlineWidth / inlineHeight}rem`
  };
  const imageStyle = viewMode === "fit" ? {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: "100%",
    maxWidth: `${Math.max(16, activeRatio * 78)}dvh`
  } : {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: `${zoom * 100}%`,
    maxWidth: "none"
  };
  const zoomLabel = viewMode === "fit" ? frameMode === "content" ? "Fit content" : "Full page" : `${Math.round(zoom * 100)}%`;
  return <figure className="latex-preview">
      <button type="button" className="latex-preview__trigger" onClick={openViewer} aria-haspopup="dialog" aria-label={`Open zoomable preview: ${alt}`}>
        <span className="latex-preview__page" style={inlineGeometry}>
          {measurementStatus === "loading" ? <span className="latex-preview__loading" role="status">Preparing compiled output…</span> : renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: inlineContentBox,
    loading: "lazy"
  })}
        </span>
        <span className="latex-preview__trigger-label" aria-hidden="true">
          <span className="latex-preview__trigger-icon">⌕</span>
          Open viewer
        </span>
      </button>
      <figcaption className="latex-preview__caption">
        <span>
          {caption}
          {measurementStatus === "error" && <span className="latex-preview__status" role="status"> Content fit is unavailable; the complete vector page is shown.</span>}
        </span>
        <a href={src} target="_blank" rel="noreferrer" className="latex-preview__source-link">Open SVG</a>
      </figcaption>

      {isOpen && <div className="latex-preview__backdrop" onMouseDown={event => {
    if (event.target === event.currentTarget) closeViewer();
  }}>
          <section ref={dialogRef} className="latex-preview__dialog" role="dialog" aria-modal="true" aria-label={`Rendered LaTeX viewer: ${alt}`}>
            <header className="latex-preview__toolbar">
              <div className="latex-preview__identity">
                <span className="latex-preview__eyebrow">Compiled LaTeX</span>
                <span className="latex-preview__filename">{alt}</span>
              </div>
              <div className="latex-preview__controls" aria-label="Preview controls">
                <button type="button" className={frameMode === "content" && viewMode === "fit" ? "is-active" : undefined} disabled={!contentBox} onClick={() => {
    setFrameMode("content");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Fit content
                </button>
                <button type="button" className={frameMode === "page" && viewMode === "fit" ? "is-active" : undefined} onClick={() => {
    setFrameMode("page");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Full page
                </button>
                <span className="latex-preview__zoom-group">
                  <button type="button" onClick={zoomOut} disabled={viewMode === "fit" || zoom <= minZoom} aria-label="Zoom out">−</button>
                  <output aria-live="polite" aria-label="Current zoom">{zoomLabel}</output>
                  <button type="button" onClick={zoomIn} disabled={viewMode !== "fit" && zoom >= maxZoom} aria-label="Zoom in">+</button>
                </span>
                <a href={src} target="_blank" rel="noreferrer">Open SVG</a>
                <button ref={closeButtonRef} type="button" className="latex-preview__close" onClick={closeViewer} aria-label="Close rendered LaTeX viewer">
                  Close
                </button>
              </div>
            </header>
            <div ref={viewportRef} className="latex-preview__viewport" data-view-mode={viewMode} onPointerDown={startDrag} onPointerMove={continueDrag} onPointerUp={stopDrag} onPointerCancel={stopDrag}>
              <span className="latex-preview__dialog-page" style={imageStyle}>
                {renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: activeContentBox
  })}
              </span>
            </div>
            <footer className="latex-preview__viewer-note">
              Compiler-generated vector output · Use +/− to zoom · Drag to pan · Esc to close
            </footer>
          </section>
        </div>}
    </figure>;
};

Learn to diagnose and fix LaTeX compilation errors efficiently. This comprehensive guide covers error types, debugging strategies, common problems with solutions, and preventive measures to keep your documents compiling smoothly.

<Info>
  **Prerequisites**: Basic LaTeX knowledge\
  **Time to complete**: 30-35 minutes\
  **Difficulty**: Intermediate to Advanced\
  **What you'll learn**: Error types, debugging tools, common fixes, and prevention strategies
</Info>

## Understanding LaTeX Errors

### Error Message Structure

<CodeGroup>
  ```bash error-anatomy.log theme={null}
  ! LaTeX Error: File `missing-package.sty' not found.
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  Type of error and description

  See the LaTeX manual or LaTeX Companion for explanation.
  Type  H <return>  for immediate help.
   ...                                              
                                                    
  l.5 \usepackage{missing-package}
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  Line number and problematic code

  ? 
  ^ Prompt for user action (press Enter to continue)
  ```

  ```bash error-components.txt theme={null}
  Components of an error message:
  1. ! - Error indicator
  2. Error type - LaTeX Error, TeX capacity exceeded, etc.
  3. Description - What went wrong
  4. Line number (l.XX) - Where it occurred
  4. Context - Code causing the error
  5. Help prompt - Type H for more info
  ```
</CodeGroup>

### Error Categories

<Tabs>
  <Tab title="LaTeX Errors">
    **Structural/syntax errors**

    * Missing braces `{}`
    * Unclosed environments
    * Undefined commands
    * Missing packages
    * Invalid options
  </Tab>

  <Tab title="TeX Errors">
    **Low-level system errors**

    * Memory exceeded
    * Dimension too large
    * Missing characters
    * Font issues
    * File I/O problems
  </Tab>

  <Tab title="Package Errors">
    **Package-specific issues**

    * Incompatible packages
    * Missing dependencies
    * Option conflicts
    * Version mismatches
  </Tab>

  <Tab title="Warnings">
    **Non-fatal issues**

    * Overfull/underfull boxes
    * Font substitutions
    * Multiply defined labels
    * Citation undefined
  </Tab>
</Tabs>

## Common Errors and Solutions

### Missing Package Errors

<LatexSource filename="missing-package-fix.tex" source={"% Error: File `tikz.sty' not found\n\n% Solution 1: Install missing package\n% - TeX Live: tlmgr install pgf\n% - MiKTeX: Use package manager\n% - Manual: Download from CTAN\n\n% Solution 2: Check package name\n\\usepackage{tikz}     % Correct\n\\usepackage{TikZ}     % Wrong - case sensitive\n\\usepackage{tikz-cd}  % Different package\n\n% Solution 3: Update distribution\n% Run: tlmgr update --all\n\n% Solution 4: Check TEXMF path\n% Ensure custom packages are in path"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
  </Info>
</RenderedOutput>

<LatexSource filename="undefined-control-sequence.tex" source={"% Error: Undefined control sequence\n\n% Problem 1: Typo in command\n\\textbf{Bold text}    % Correct\n\\textbold{Bold text}  % Wrong - undefined\n\n% Problem 2: Missing package\n\\SI{10}{\\meter}       % Error without siunitx\n\\usepackage{siunitx}  % Add this first\n\n% Problem 3: Wrong order\n\\alpha                % Error in text mode\n$\\alpha$              % Correct - math mode\n\n% Problem 4: Custom command not defined\n\\mycommand{text}      % Error if not defined\n\\newcommand{\\mycommand}[1]{#1}  % Define first"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `Undefined control sequence.`.
  </Warning>
</RenderedOutput>

### Environment Errors

<LatexSource filename="environment-mismatch.tex" source={"% Error: \\begin{itemize} ended by \\end{enumerate}\n\n% Wrong:\n\\begin{itemize}\n\\item First item\n\\item Second item\n\\end{enumerate}  % Mismatched\n\n% Correct:\n\\begin{itemize}\n\\item First item\n\\item Second item\n\\end{itemize}\n\n% Common mismatches:\n% - equation/align\n% - table/tabular\n% - figure/center\n% - document/article\n\n% Prevention: Use editor matching\n% Most editors highlight matching begin/end"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `\begin{itemize} on input line 7 ended`.
  </Warning>
</RenderedOutput>

<LatexSource filename="missing-begin-end.tex" source={"% Error: Missing \\begin{document}\n\n% Structure required:\n\\documentclass{article}\n% Preamble here\n\\begin{document}  % Required!\nContent here\n\\end{document}\n\n% Error: No \\end{} to match \\begin{equation}\n\\begin{equation}\nE = mc^2\n% Missing \\end{equation}\n\n% Debugging tip: Count begin/end pairs\ngrep -c \"\\\\\\\\begin{\" file.tex\ngrep -c \"\\\\\\\\end{\" file.tex\n# Should be equal"} />

<RenderedOutput title="Rendered output" ctaHref="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=rendered_output&utm_campaign=docs_open_app&utm_content=learn_latex_how_to_fixing_compilation_errors">
  <LatexPreview src="/images/rendered/learn-latex-how-to-fixing-compilation-errors-04/page-1.svg" alt="Compiled PDF page 1 from missing-begin-end.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Math Mode Errors

<LatexSource filename="math-mode-issues.tex" source={"% Error: Missing $ inserted\n\n% Problem: Math symbols in text mode\nThe variable α represents...  % Error\nThe variable $\\alpha$ represents...  % Correct\n\n% Problem: Text in math mode\n$the value of x = 5$  % Wrong\n$\\text{the value of } x = 5$  % Better\nThe value of $x = 5$  % Best\n\n% Problem: Display math syntax\n$$E = mc^2$$  % Deprecated\n\\[E = mc^2\\]  % Correct\n\n% Problem: Nested math modes\n$the formula $x^2$ is$  % Error\n$\\text{the formula } x^2 \\text{ is}$  % Correct"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `Unicode character α (U+03B1)`.
  </Warning>
</RenderedOutput>

<LatexSource filename="math-delimiter-errors.tex" source={"% Error: Missing delimiter\n\n% Mismatched delimiters\n$\\left( x + y \\right]$  % Wrong bracket types\n$\\left( x + y \\right)$  % Correct\n\n% Missing \\right\n$\\left( \\frac{a}{b} $  % Error\n$\\left( \\frac{a}{b} \\right)$  % Correct\n\n% Size mismatch\n\\left( x \\right.  % OK - invisible right\n\\left. x \\right)  % OK - invisible left\n\n% Multi-line issues\n\\begin{align}\n\\left( x + y  % Error - can't break\n\\right)\n\\end{align}\n\n% Solution for multi-line\n\\begin{align}\n\\Bigl( x &+ y \\\\\n      &+ z \\Bigr)\n\\end{align}"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `Missing \right. inserted.`.
  </Warning>
</RenderedOutput>

### Table and Figure Errors

<LatexSource filename="table-errors.tex" source={"% Error: Misplaced \\noalign\n\n% Problem: Commands outside table\n\\begin{tabular}{cc}\n\\hline  % OK\nContent & More \\\\\n\\hline  % OK\n\\caption{Table}  % Error - not allowed\n\\end{tabular}\n\n% Solution: Use table environment\n\\begin{table}\n\\caption{Table}  % Correct placement\n\\begin{tabular}{cc}\n\\hline\nContent & More \\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n% Error: Illegal character in array arg\n\\begin{tabular}{l|c|r}  % Vertical lines ok\n\\begin{tabular}{lcr|}   % Error - trailing |\n\\begin{tabular}{|lcr}   % OK - leading |"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `\caption outside float.`.
  </Warning>
</RenderedOutput>

<LatexSource filename="figure-placement-errors.tex" source={"% Error: Not in outer par mode\n\n% Problem: Figure in wrong place\n\\begin{itemize}\n\\item Some text\n\\begin{figure}[h]  % Error - can't nest\n\\includegraphics{image}\n\\end{figure}\n\\end{itemize}\n\n% Solution 1: Move outside list\n\\begin{itemize}\n\\item Some text\n\\end{itemize}\n\n\\begin{figure}[h]\n\\includegraphics{image}\n\\end{figure}\n\n% Solution 2: Use different approach\n\\begin{itemize}\n\\item Some text with image:\\\\\n\\includegraphics[width=0.5\\textwidth]{image}\n\\end{itemize}"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `Undefined control sequence.`.
  </Warning>
</RenderedOutput>

### Reference and Citation Errors

<LatexSource filename="reference-errors.tex" source={"% Warning: Reference `fig:missing' undefined\n\n% Problem: Label doesn't exist\nSee Figure~\\ref{fig:missing}  % Warning\n\n% Solutions:\n% 1. Add the label\n\\begin{figure}\n\\includegraphics{image}\n\\caption{Caption}\n\\label{fig:missing}  % Add this\n\\end{figure}\n\n% 2. Check label spelling\n\\label{fig:myimage}\n\\ref{fig:myImage}  % Case sensitive!\n\n% 3. Compile twice\n% First run: Collect labels\n% Second run: Resolve references\n\n% Prevention: Systematic naming\n\\label{fig:intro:example}\n\\label{tab:results:summary}\n\\label{eq:theory:main}"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `Undefined control sequence.`.
  </Warning>
</RenderedOutput>

<LatexSource filename="citation-errors.tex" source={"% Warning: Citation `smith2020' undefined\n\n% Problem 1: Missing bib entry\n\\cite{smith2020}  % Not in .bib file\n\n% Solution: Add to bibliography\n@article{smith2020,\n  author = {Smith, John},\n  title = {Article Title},\n  journal = {Journal Name},\n  year = {2020}\n}\n\n% Problem 2: Wrong bibliography file\n\\bibliography{refs}     % Looking for refs.bib\n\\bibliography{references}  % Actual file: references.bib\n\n% Problem 3: Compilation order\npdflatex main\nbibtex main      % Run this!\npdflatex main\npdflatex main\n\n% Problem 4: Backend mismatch\n\\usepackage{biblatex}  % Uses biber\n% Run: biber main (not bibtex)"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `Can be used only in preamble.`.
  </Warning>
</RenderedOutput>

## Debugging Strategies

### Log File Analysis

<CodeGroup>
  ```bash reading-log-files.sh theme={null}
  # Understanding log files

  # 1. Find first error
  grep -n "^!" main.log | head -1

  # 2. Extract error context
  sed -n '/^!/,/^$/p' main.log

  # 3. Count warnings
  grep -c "Warning:" main.log

  # 4. Find undefined references
  grep "undefined" main.log

  # 5. Check overfull boxes
  grep "Overfull" main.log | wc -l
  ```

  ```latex debug-mode.tex theme={null}
  % Enable detailed debugging

  % Show all warnings
  \errorcontextlines=10000

  % Track undefined references
  \usepackage{refcheck}

  % Show keys for labels
  \usepackage{showkeys}

  % Draft mode for faster debugging
  \documentclass[draft]{article}

  % Visual debugging
  \overfullrule=5pt  % Show overfull boxes
  \showboxdepth=10   % More detail in log
  \showboxbreadth=10

  % Trace package loading
  \listfiles  % Lists all loaded files
  ```
</CodeGroup>

<RenderedOutput title="Expected effect">
  <Info>
    This code group documents a multi-step workflow across LaTeX and another file or command language. The blocks work together in a project, so there is no single standalone LaTeX page that would honestly represent the whole group.
  </Info>
</RenderedOutput>

### Minimal Working Example (MWE)

<CodeGroup>
  ```latex create-mwe.tex theme={null}
  % Step 1: Start with problematic document
  % Step 2: Remove content until error disappears
  % Step 3: Add back until error returns

  % MWE template
  \documentclass{article}
  \usepackage{minimal-packages-only}

  \begin{document}
  % Minimal content that reproduces error
  Only include what's necessary to show the problem
  \end{document}

  % Good MWE example for table error:
  \documentclass{article}
  \usepackage{booktabs}
  \begin{document}
  \begin{tabular}{cc}
  \toprule
  A & B \\
  \bottomrule
  \end{tabular}
  \end{document}
  ```

  ```bash binary-search-debug.sh theme={null}
  #!/bin/bash
  # Binary search for errors in large documents

  # 1. Comment out half the document
  # 2. If error persists, problem in first half
  # 3. If error gone, problem in second half
  # 4. Repeat until found

  # Automated approach
  cat > debug-wrapper.tex << 'EOF'
  \documentclass{article}
  \begin{document}
  \input{test-content}
  \end{document}
  EOF

  # Test sections individually
  for file in chapters/*.tex; do
      echo "Testing $file..."
      cp "$file" test-content.tex
      if ! pdflatex -interaction=nonstopmode debug-wrapper.tex > /dev/null 2>&1; then
          echo "Error found in $file"
      fi
  done
  ```
</CodeGroup>

<RenderedOutput title="Expected effect">
  <Info>
    This code group documents a multi-step workflow across LaTeX and another file or command language. The blocks work together in a project, so there is no single standalone LaTeX page that would honestly represent the whole group.
  </Info>
</RenderedOutput>

## Error Prevention

### Best Practices

<Tip>
  **Prevent errors before they happen**:

  1. **Regular compilation** - Compile frequently to catch errors early
  2. **Version control** - Track changes and revert if needed
  3. **Modular structure** - Isolate problems to specific files
  4. **Consistent style** - Use templates and conventions
  5. **Package management** - Keep packages updated
  6. **Editor features** - Use syntax highlighting and checking
  7. **Comments** - Document complex code
  8. **Backup** - Always have working versions
</Tip>

### Pre-compilation Checks

<CodeGroup>
  ```latex pre-checks.tex theme={null}
  % Add checks to document preamble

  % Check for required packages
  \RequirePackage{iftex}
  \ifPDFTeX
      \PackageInfo{mydoc}{Using PDFLaTeX}
  \else
      \PackageError{mydoc}{Requires PDFLaTeX}{Please compile with pdflatex}
  \fi

  % Version checks
  \NeedsTeXFormat{LaTeX2e}[2020/01/01]

  % Compatibility checks
  \@ifpackageloaded{hyperref}{}{
      \PackageWarning{mydoc}{hyperref recommended}
  }

  % Custom sanity checks
  \newcommand{\checksetup}{%
      \@ifundefined{mycommand}{
          \PackageError{mydoc}{Setup incomplete}{Run \string\setupmydoc first}
      }{}
  }
  ```

  ```bash validation-script.sh theme={null}
  #!/bin/bash
  # Pre-compilation validation

  echo "LaTeX Document Validator"

  # Check file exists
  if [ ! -f "$1" ]; then
      echo "Error: File $1 not found"
      exit 1
  fi

  # Check syntax
  echo "Checking syntax..."
  lacheck "$1"

  # Check style
  echo "Checking style..."
  chktex "$1"

  # Check references
  echo "Checking references..."
  grep -n "ref{" "$1" | grep -v "label{" | grep -v "pageref{" | grep -v "autoref{" | grep -v "cref{"

  # Check for common issues
  echo "Checking common issues..."
  grep -n "\$\$" "$1" && echo "Warning: Found deprecated \$\$ math"
  grep -n "\\def\\" "$1" && echo "Warning: Found \\def (use \\newcommand)"

  echo "Validation complete"
  ```
</CodeGroup>

<RenderedOutput title="Expected effect">
  <Info>
    This code group documents a multi-step workflow across LaTeX and another file or command language. The blocks work together in a project, so there is no single standalone LaTeX page that would honestly represent the whole group.
  </Info>
</RenderedOutput>

## Advanced Debugging

### Memory and Capacity Errors

<LatexSource filename="capacity-exceeded.tex" source={"% Error: TeX capacity exceeded\n\n% Problem: Too many labels/refs\n% Solution: Increase memory\n% Edit texmf.cnf or set environment:\n% export extra_mem_top=10000000\n\n% Problem: Dimension too large\n\\vspace{100000pt}  % Error\n\\vspace{100cm}     % OK if fits on page\n\n% Problem: Too deeply nested\n% Solution: Restructure document\n% Avoid >6 levels of nesting\n\n% Problem: Hash size exceeded\n% Too many commands/labels\n% Solution: Clean auxiliary files\n% rm *.aux *.toc *.lof *.lot"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `Dimension too large.`.
  </Warning>
</RenderedOutput>

<LatexSource filename="infinite-loops.tex" source={"% Detecting infinite loops\n\n% Problem: Recursive macro\n\\newcommand{\\recur}{\\recur}  % Infinite loop\n\\recur  % Crashes\n\n% Solution: Add termination\n\\newcounter{depth}\n\\newcommand{\\saferecur}{%\n    \\stepcounter{depth}%\n    \\ifnum\\value{depth}<10\n        \\saferecur\n    \\fi\n}\n\n% Problem: Circular references\n\\label{a} See \\ref{b}\n\\label{b} See \\ref{a}\n% Not infinite but confusing\n\n% Debug with traces\n\\tracingmacros=1\n\\tracingcommands=1\n% Check log file"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

### Package Conflicts

<LatexSource filename="package-conflicts.tex" source={"% Common package conflicts and solutions\n\n% hyperref - load last (with exceptions)\n\\usepackage{graphics}\n\\usepackage{color}\n\\usepackage{hyperref}  % Almost always last\n\\usepackage{cleveref}  % After hyperref\n\n% inputenc vs fontenc order\n\\usepackage[utf8]{inputenc}  % First\n\\usepackage[T1]{fontenc}     % Second\n\n% babel conflicts\n\\usepackage[english]{babel}\n\\usepackage{csquotes}  % After babel\n\n% Math font conflicts\n% Don't use multiple math font packages\n% \\usepackage{mathptmx}\n% \\usepackage{fourier}  % Conflict!\n\n% Caption and subcaption\n\\usepackage{caption}\n\\usepackage{subcaption}  % Must be after caption\n% Don't use with subfigure/subfig"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
  </Info>
</RenderedOutput>

<LatexSource filename="conflict-resolution.tex" source={"% Resolving conflicts\n\n% Option 1: Change load order\n% Try different orders until working\n\n% Option 2: Compatibility options\n\\usepackage[compatibility=false]{caption}\n\n% Option 3: Alternative packages\n% Instead of subfigure (deprecated)\n\\usepackage{subcaption}  % Modern alternative\n\n% Option 4: Manual patches\n\\usepackage{etoolbox}\n\\AtBeginDocument{%\n    % Fix specific conflicts\n}\n\n% Option 5: Minimal example\n% Isolate conflict with MWE\n% Report to package maintainer"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Error Recovery

### Corrupted Files

<CodeGroup>
  ```bash file-recovery.sh theme={null}
  #!/bin/bash
  # Recover from corrupted auxiliary files

  # Clean all generated files
  clean_latex() {
      local base="${1%.tex}"
      rm -f "$base".{aux,log,out,toc,lof,lot,bbl,blg,nav,snm,vrb}
      rm -f "$base".{synctex.gz,fdb_latexmk,fls}
  }

  # Usage
  clean_latex main.tex

  # Rebuild from scratch
  pdflatex main.tex
  bibtex main
  pdflatex main.tex
  pdflatex main.tex
  ```

  ```latex emergency-compilation.tex theme={null}
  % Emergency compilation techniques

  % Skip problematic sections
  \includeonly{chapters/working-chapter}

  % Disable problematic packages
  \PassOptionsToPackage{draft}{graphicx}

  % Continue despite errors
  % pdflatex -interaction=nonstopmode main.tex

  % Create placeholder commands
  \providecommand{\missingcmd}[1]{[MISSING: #1]}

  % Temporary fixes
  \usepackage{silence}
  \WarningsOff[hyperref]
  \ErrorsOff[some-package]
  ```
</CodeGroup>

<RenderedOutput title="Expected effect">
  <Info>
    This code group documents a multi-step workflow across LaTeX and another file or command language. The blocks work together in a project, so there is no single standalone LaTeX page that would honestly represent the whole group.
  </Info>
</RenderedOutput>

## Troubleshooting Workflow

### Systematic Approach

```mermaid theme={null}
graph TD
    A[Compilation Error] --> B{First Error?}
    B -->|Yes| C[Read Error Message]
    B -->|No| D[Fix First Error First]
    C --> E{Understand Error?}
    E -->|Yes| F[Apply Fix]
    E -->|No| G[Create MWE]
    G --> H[Search/Ask for Help]
    F --> I{Fixed?}
    I -->|Yes| J[Compile Again]
    I -->|No| G
    J --> K{More Errors?}
    K -->|Yes| B
    K -->|No| L[Success!]
```

### Quick Reference

<Warning>
  **Common fixes cheat sheet**:

  | Error                      | Quick Fix                    |
  | -------------------------- | ---------------------------- |
  | Undefined control sequence | Check spelling, load package |
  | Missing \$ inserted        | Add \$ around math           |
  | File not found             | Check name, install package  |
  | Missing \begin{document}   | Add document structure       |
  | Undefined reference        | Compile twice, check label   |
  | Dimension too large        | Reduce size value            |
  | Missing } inserted         | Balance braces               |
  | Environment undefined      | Load required package        |
</Warning>

## Complete Debugging Example

<LatexSource filename="debug-session.tex" source={"% Document with multiple errors\n\\documentclass{article}\n\\usepackage{amsmath}\n% Missing graphicx package\n\n\\begin{document}\n\n\\title{Debugging Example}\n\\autor{John Doe}  % Typo: should be \\author\n\\maketitle\n\n\\section{Introduction}\nThis document has several errors. The equation α = β needs math mode.  % Missing $\n\n\\begin{figure}[h]\n\\includegraphics{nonexistent}  % Missing package and file\n\\caption{Test}\n\\label{fig:test\n\\end{figure}  % Missing }\n\nSee Figure \\ref{fig:tset}.  % Typo in label\n\n\\begin{equaton}  % Typo: should be equation\nx^2 + y^2 = z^2\n\\end{equation}  % Mismatch\n\n\\end{document}"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `Undefined control sequence.`.
  </Warning>
</RenderedOutput>

<LatexSource filename="debug-fixed.tex" source={"% Fixed version\n\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{graphicx}  % Added missing package\n\n\\begin{document}\n\n\\title{Debugging Example}\n\\author{John Doe}  % Fixed typo\n\\maketitle\n\n\\section{Introduction}\nThis document has several errors. The equation $\\alpha = \\beta$ needs math mode.  % Added $\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{example-image}  % Fixed path\n\\caption{Test}\n\\label{fig:test}  % Added missing }\n\\end{figure}\n\nSee Figure \\ref{fig:test}.  % Fixed typo\n\n\\begin{equation}  % Fixed typo\nx^2 + y^2 = z^2\n\\end{equation}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-fixing-compilation-errors-16/page-1.svg" alt="Compiled PDF page 1 from debug-fixed.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

## Next Steps

Continue mastering LaTeX:

<CardGroup cols={2}>
  <Card title="Large Documents" icon="file-code" href="/learn/latex/how-to/large-documents">
    Debug multi-file projects
  </Card>

  <Card title="Templates" icon="copy" href="/learn/latex/how-to/using-templates">
    Create error-free templates
  </Card>

  <Card title="Collaboration" icon="users" href="/learn/latex/how-to/collaboration-workflow">
    Team debugging strategies
  </Card>

  <Card title="Package Docs" icon="book" href="/learn/reference/packages">
    Understand package errors
  </Card>
</CardGroup>

### Troubleshooting Center

* [Troubleshooting hub](/learn/latex/troubleshooting)
* [Missing packages](/learn/latex/troubleshooting/missing-packages)
* [Bibliography build errors](/learn/latex/troubleshooting/bibliography-build-errors)
* [Image and path errors](/learn/latex/troubleshooting/image-and-path-errors)
* [Compiler and engine errors](/learn/latex/troubleshooting/compiler-and-engine-errors)
* [Float and placement issues](/learn/latex/troubleshooting/float-and-placement-issues)

***

<Info>
  **Remember**: Most LaTeX errors have simple solutions. Read error messages carefully, fix the first error first, and when in doubt, create a minimal example that reproduces the problem. The LaTeX community is helpful - don't hesitate to ask for help with a good MWE.
</Info>

## Start in LaTeX Cloud Studio

<CardGroup cols={2}>
  <Card title="Open in LaTeX Cloud Studio" icon="cloud" href="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=card&utm_campaign=docs_open_app&utm_content=fixing_compilation_errors_open_app">
    Write, compile, and iterate directly in your browser.
  </Card>

  <Card title="Start from Article Template" icon="file-text" href="/templates/article">
    Use a ready-made template, then adapt it to your content.
  </Card>
</CardGroup>
