> ## 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.

# Common LaTeX Errors and How to Fix Them

> Fix common LaTeX errors fast, including Missing $ inserted, undefined control sequence, content after \end{document} is ignored, and other compile failures.

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>;
};

Every LaTeX user eventually runs into compile errors. This guide explains common LaTeX error messages, including `Missing $ inserted`, `Undefined control sequence`, and `Content after \end{document} is ignored`, then shows how to fix them with clear examples.

## How to Read LaTeX Error Messages

Before diving into specific errors, let's understand how to read error messages:

```
! Missing $ inserted.
<inserted text>
                $
l.15 The area is x^
                    2 square units.
```

| Part                 | Meaning                               |
| -------------------- | ------------------------------------- |
| `!`                  | Indicates an error                    |
| `Missing $ inserted` | The error description                 |
| `l.15`               | Line number where the error occurred  |
| `x^`                 | The specific text causing the problem |

<Tip>
  **Pro tip:** In LaTeX Cloud Studio, click on error messages to jump directly to the problematic line.
</Tip>

***

## Error 1: Missing \$ inserted

**The most common LaTeX error.** This happens when you use math symbols outside of math mode.

### The Error

```
! Missing $ inserted.
<inserted text>
                $
l.10 The formula x^2 + y^2 = z^
                                2 shows...
```

### Why It Happens

Characters like `^`, `_`, `\sum`, `\int`, and Greek letters (`\alpha`, `\beta`) only work inside math mode.

### The Fix

**Before (Wrong):**

<LatexSource filename="example.tex" source={"The formula x^2 + y^2 = z^2 shows the Pythagorean theorem.\nThe value is approximately \\pi."} />

<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=blog_common_latex_errors_fixes">
  <LatexPreview src="/images/rendered/blog-common-latex-errors-fixes-01/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

**After (Correct):**

<LatexSource filename="example.tex" source={"The formula $x^2 + y^2 = z^2$ shows the Pythagorean theorem.\nThe value is approximately $\\pi$."} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/blog-common-latex-errors-fixes-02/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

### Quick Reference

| Symbol Type        | Requires Math Mode? | Example             |
| ------------------ | ------------------- | ------------------- |
| Superscripts (`^`) | Yes                 | `$x^2$`             |
| Subscripts (`_`)   | Yes                 | `$x_i$`             |
| Greek letters      | Yes                 | `$\alpha$, $\beta$` |
| Math operators     | Yes                 | `$\sum$, $\int$`    |
| Regular text       | No                  | `Hello world`       |

***

## Error 2: Undefined control sequence

This error occurs when LaTeX doesn't recognize a command you've used.

### The Error

```
! Undefined control sequence.
l.12 \begn
          {document}
```

### Why It Happens

* Typo in command name
* Missing package that defines the command
* Using a command in the wrong context

### The Fix

**Common typos:**

<LatexSource filename="example.tex" source={"% Wrong\n\\begn{document}\n\\sectoin{Title}\n\\includ{file}\n\n% Correct\n\\begin{document}\n\\section{Title}\n\\include{file}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt is structurally incomplete and cannot be compiled honestly as a standalone document. It shows document-boundary syntax rather than a visible page result.
  </Info>
</RenderedOutput>

**Missing package:**

<LatexSource filename="example.tex" source={"% Wrong - using \\includegraphics without graphicx\n\\documentclass{article}\n\\begin{document}\n\\includegraphics{image}  % Error!\n\\end{document}\n\n% Correct - add the package\n\\documentclass{article}\n\\usepackage{graphicx}\n\\begin{document}\n\\includegraphics{image}\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Common Commands and Required Packages

| Command                | Required Package |
| ---------------------- | ---------------- |
| `\includegraphics`     | `graphicx`       |
| `\url`, `\href`        | `hyperref`       |
| `\toprule`, `\midrule` | `booktabs`       |
| `\align` environment   | `amsmath`        |
| `\textcolor`           | `xcolor`         |
| `\SI`, `\si`           | `siunitx`        |

***

## Error 3: Missing } inserted

LaTeX expects every `{` to have a matching `}`.

### The Error

```
! Missing } inserted.
<inserted text>
                }
l.8 \textbf{This is bold text
```

### Why It Happens

* Forgot closing brace
* Mismatched braces
* Special character not escaped

### The Fix

**Before (Wrong):**

<LatexSource filename="example.tex" source={"\\textbf{This is bold text\n\n\\section{Introduction\n\n\\textit{Nested \\textbf{formatting} example"} />

<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>

**After (Correct):**

<LatexSource filename="example.tex" source={"\\textbf{This is bold text}\n\n\\section{Introduction}\n\n\\textit{Nested \\textbf{formatting} example}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/blog-common-latex-errors-fixes-06/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

### Finding Mismatched Braces

Count opening and closing braces—they should be equal:

<LatexSource filename="example.tex" source={"% Use editor brace matching (hover over { to find matching })\n\\textbf{This is \\textit{nested} text}\n       ^                            ^\n       |____________________________|"} />

<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>

<Tip>
  **LaTeX Cloud Studio tip:** Enable brace matching in settings to highlight matching pairs.
</Tip>

***

## Error 4: File not found

LaTeX cannot locate a file you're trying to include.

### The Error

```
! LaTeX Error: File `myimage.png' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: png)
```

### Why It Happens

* File doesn't exist
* Wrong file path
* Wrong file name (case-sensitive!)
* File extension issues

### The Fix

**Check file location:**

<LatexSource filename="example.tex" source={"% If your file structure is:\n% project/\n%   main.tex\n%   images/\n%     diagram.png\n\n% Wrong\n\\includegraphics{diagram}\n\n% Correct\n\\includegraphics{images/diagram}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

**Check file name (case-sensitive on Linux/Mac):**

<LatexSource filename="example.tex" source={"% File is named \"Diagram.png\"\n\n% Wrong (on Linux/Mac)\n\\includegraphics{diagram}\n\n% Correct\n\\includegraphics{Diagram}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

**For bibliography files:**

<LatexSource filename="example.tex" source={"% Wrong\n\\bibliography{References}  % But file is references.bib\n\n% Correct\n\\bibliography{references}"} />

<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>

***

## Error 5: Environment undefined

You're trying to use an environment that doesn't exist or isn't loaded.

### The Error

```
! LaTeX Error: Environment align undefined.
```

### Why It Happens

* Misspelled environment name
* Missing package
* Using environment incorrectly

### The Fix

**Misspelled environment:**

<LatexSource filename="example.tex" source={"% Wrong\n\\begin{itemise}\n\\end{itemise}\n\n% Correct\n\\begin{itemize}\n\\end{itemize}"} />

<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>

**Missing package for math environments:**

<LatexSource filename="example.tex" source={"% Wrong - align needs amsmath\n\\documentclass{article}\n\\begin{document}\n\\begin{align}\n    y &= mx + b\n\\end{align}\n\\end{document}\n\n% Correct\n\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\\begin{align}\n    y &= mx + b\n\\end{align}\n\\end{document}"} />

<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>

### Common Environments and Required Packages

| Environment                   | Required Package                |
| ----------------------------- | ------------------------------- |
| `align`, `gather`, `multline` | `amsmath`                       |
| `lstlisting`                  | `listings`                      |
| `minted`                      | `minted`                        |
| `tikzpicture`                 | `tikz`                          |
| `algorithm`                   | `algorithm2e` or `algorithmicx` |

***

## Error 6: Overfull/Underfull hbox

These are warnings (not errors) about line breaking issues.

### The Warning

```
Overfull \hbox (15.2pt too wide) in paragraph at lines 10--12
Underfull \hbox (badness 10000) in paragraph at lines 15--17
```

### Why It Happens

* **Overfull**: Line is too long, extends into margin
* **Underfull**: Line has too much space, looks stretched

### The Fix

**For overfull (too wide):**

<LatexSource filename="example.tex" source={"% Option 1: Allow hyphenation\n\\usepackage[hyphens]{url}\n\n% Option 2: Use sloppypar for problematic paragraphs\n\\begin{sloppypar}\nThis paragraph contains a very long URL or technical term\nthat LaTeX struggles to break properly.\n\\end{sloppypar}\n\n% Option 3: Add manual break hints\nsuper\\-cali\\-fragi\\-listic\n\n% Option 4: For URLs\n\\usepackage{hyperref}\n\\url{https://very-long-url-that-causes-problems.com/path}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/blog-common-latex-errors-fixes-13/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

**For underfull (too sparse):**

<LatexSource filename="example.tex" source={"% Usually happens with \\\\ at paragraph end\n% Wrong\nThis is the end of a paragraph.\\\\\n\n% Correct\nThis is the end of a paragraph."} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/blog-common-latex-errors-fixes-14/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

<Warning>
  **Don't ignore these warnings!** Overfull boxes can cause text to extend beyond page margins, looking unprofessional in printed documents.
</Warning>

***

## Error 7: Missing \begin{document}

LaTeX can't find where your document content starts.

### The Error

```
! LaTeX Error: Missing \begin{document}.
```

### Why It Happens

* Content before `\begin{document}`
* Missing `\begin{document}` entirely
* Encoding issues with invisible characters

### The Fix

**Content in preamble:**

<LatexSource filename="example.tex" source={"% Wrong\n\\documentclass{article}\n\\usepackage{amsmath}\nThis text is in the wrong place!  % Error here\n\\begin{document}\nActual content\n\\end{document}\n\n% Correct\n\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\nThis text is in the right place!\nActual content\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is document setup or preamble code. It changes the behavior of a containing document but does not produce an honest standalone page by itself.
  </Info>
</RenderedOutput>

**Check for invisible characters:**

<LatexSource filename="example.tex" source={"% Sometimes copy-paste introduces hidden characters\n% Delete and retype the line if you suspect this\n\\documentclass{article}  % Delete and retype this line\n\\begin{document}\n\\end{document}"} />

<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 8: Too many }'s

You have more closing braces than opening ones.

### The Error

```
! Too many }'s.
l.15 }
```

### Why It Happens

* Extra closing brace
* Deleted opening brace
* Copy-paste error

### The Fix

**Find and remove the extra brace:**

<LatexSource filename="example.tex" source={"% Wrong\n\\textbf{Some bold text}}\n\n% Correct\n\\textbf{Some bold text}"} />

<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>

**Check for mismatched environments:**

<LatexSource filename="example.tex" source={"% Wrong\n\\begin{itemize}\n    \\item First\n\\end{enumerate}  % Wrong environment!\n\n% Correct\n\\begin{itemize}\n    \\item First\n\\end{itemize}"} />

<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 9: Misplaced alignment tab character &

The `&` character has special meaning in tables and math alignment.

### The Error

```
! Misplaced alignment tab character &.
l.10 Bread & butter
```

### Why It Happens

* Using `&` in regular text (it's reserved for tables)
* Wrong number of `&` in a table row
* `&` outside tabular environment

### The Fix

**In regular text, escape the ampersand:**

<LatexSource filename="example.tex" source={"% Wrong\nBread & butter\nSmith & Jones LLC\n\n% Correct\nBread \\& butter\nSmith \\& Jones LLC"} />

<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>

**In tables, check column count:**

<LatexSource filename="example.tex" source={"% Wrong - 3 columns defined, but 4 values in row\n\\begin{tabular}{|l|c|r|}\n    A & B & C & D \\\\  % Error! Too many &\n\\end{tabular}\n\n% Correct\n\\begin{tabular}{|l|c|r|l|}  % 4 columns\n    A & B & C & D \\\\\n\\end{tabular}"} />

<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 10: Dimension too large

A calculated dimension exceeds LaTeX's maximum.

### The Error

```
! Dimension too large.
l.25 \includegraphics[width=2\textwidth]{image}
```

### Why It Happens

* Image scaled too large
* Infinite or very large calculation
* Negative dimensions

### The Fix

**For images:**

<LatexSource filename="example.tex" source={"% Wrong\n\\includegraphics[width=2\\textwidth]{image}\n\n% Correct\n\\includegraphics[width=\\textwidth]{image}\n\\includegraphics[width=0.8\\textwidth]{image}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

**For spacing:**

<LatexSource filename="example.tex" source={"% Wrong - this creates infinite stretch\n\\hspace{\\fill}text\\hspace{\\fill}\n\n% Correct\n\\hfill text \\hfill"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/blog-common-latex-errors-fixes-22/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

***

## Bonus: General Debugging Tips

### 1. Compile Often

Don't write 50 lines before compiling. Compile after each significant addition to catch errors early.

### 2. Binary Search for Errors

If you have a mysterious error:

<LatexSource filename="example.tex" source={"% Comment out half your document\n\\begin{document}\nFirst half of content\n%{\nSecond half of content\n%}\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt is structurally incomplete and cannot be compiled honestly as a standalone document. It shows document-boundary syntax rather than a visible page result.
  </Info>
</RenderedOutput>

If it compiles, the error is in the second half. Repeat until you find the problematic line.

### 3. Start Fresh

If an error is truly mysterious:

<LatexSource filename="example.tex" source={"% Create minimal example\n\\documentclass{article}\n\\begin{document}\n% Paste suspicious code here\n\\end{document}"} />

<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>

### 4. Check Log File

The `.log` file contains detailed information:

```
This is pdfTeX, Version 3.141592653
...
! Missing $ inserted.
<inserted text>
                $
l.10 x^
      2
```

### 5. Clear Auxiliary Files

Sometimes old `.aux`, `.log`, `.toc` files cause problems:

```bash theme={null}
# Delete auxiliary files and recompile
rm *.aux *.log *.toc *.out
```

## Quick Error Reference Table

| Error Message              | Likely Cause            | Quick Fix                          |
| -------------------------- | ----------------------- | ---------------------------------- |
| Missing \$ inserted        | Math outside math mode  | Add `$...$`                        |
| Undefined control sequence | Typo or missing package | Check spelling, add package        |
| Missing } inserted         | Unclosed brace          | Add missing `}`                    |
| File not found             | Wrong path or name      | Check path, case sensitivity       |
| Environment undefined      | Missing package         | Add required package               |
| Overfull hbox              | Line too wide           | Use `\sloppy` or break text        |
| Missing \begin{document}   | Content in preamble     | Move text after `\begin{document}` |
| Too many }'s               | Extra closing brace     | Remove extra `}`                   |
| Misplaced &                | & in regular text       | Use `\&` to escape                 |
| Dimension too large        | Oversized element       | Reduce size values                 |

***

## Need More Help?

* Check our [LaTeX documentation](/learn/latex/basics/creating-first-document)
* Browse [Stack Exchange TeX](https://tex.stackexchange.com) for specific issues
* Use the [editor and AI assistance guide](/product/editor-and-ai-assistance) for LaTeX Cloud Studio troubleshooting workflows

<Info>
  **LaTeX Cloud Studio advantage:** Our editor highlights errors in real-time and provides AI-powered suggestions to fix common issues automatically.
</Info>
