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

# LaTeX Common Errors & Troubleshooting

> Fix LaTeX errors quickly with our comprehensive troubleshooting guide. Solutions for the most common LaTeX compilation errors and warnings.

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

Don't panic! LaTeX errors can look scary, but most are easy to fix once you understand them. This guide covers the most common errors with clear solutions.

<Info>
  **Quick tip**: LaTeX error messages show the line number where the error occurred. Look for `l.123` in the error message to find line 123 in your document.
</Info>

## Understanding LaTeX Error Messages

LaTeX errors follow this pattern:

```
! LaTeX Error: [Error description]

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              
                                                  
l.123 \textbf{This is the problematic line
```

Key parts:

* `!` indicates an error (not a warning)
* Error description tells you what went wrong
* `l.123` shows the line number
* The line content helps locate the issue

## Most Common Errors

### 1. Missing \$ inserted

**Error message:**

```
! Missing $ inserted.
<inserted text> 
                $
l.42 The value of x_1 is important
```

**Cause**: Math symbols used outside math mode

**Solutions:**

<LatexSource filename="wrong.tex" source={"The value of x_1 is important       % Wrong\nThe equation x^2 + y^2 = r^2 holds  % Wrong"} />

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

<LatexSource filename="correct.tex" source={"The value of $x_1$ is important       % Correct\nThe equation $x^2 + y^2 = r^2$ holds % Correct"} />

<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_basics_errors">
  <LatexPreview src="/images/rendered/learn-latex-basics-errors-02/page-1.svg" alt="Compiled PDF page 1 from correct.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>

<Tip>
  Common math symbols that need math mode: `_`, `^`, `\alpha`, `\sum`, etc.
</Tip>

### 2. Undefined control sequence

**Error message:**

```
! Undefined control sequence.
l.15 \textcolor
      {red}{This text}
```

**Cause**: Using a command that doesn't exist or missing package

**Solutions:**

<LatexSource filename="solution1.tex" source={"% Add required package\n\\usepackage{xcolor}  % For \\textcolor\n\\usepackage{amsmath} % For \\text\n\\usepackage{graphicx} % For \\includegraphics"} />

<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="solution2.tex" source={"% Check spelling\n\\texbf{bold}    % Wrong (missing 't')\n\\textbf{bold}   % Correct\n\n\\begin{centre}  % Wrong spelling\n\\begin{center}  % Correct"} />

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

### 3. Missing \begin{document}

**Error message:**

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

**Cause**: Content before `\begin{document}` or missing the command entirely

**Solution:**

<LatexSource filename="wrong.tex" source={"\\documentclass{article}\n\\title{My Document}\n\nThis is my text  % Wrong - content before \\begin{document}\n\n\\begin{document}\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>

<LatexSource filename="correct.tex" source={"\\documentclass{article}\n\\title{My Document}\n\n\\begin{document}\nThis is my text  % Correct - content after \\begin{document}\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-basics-errors-06/page-1.svg" alt="Compiled PDF page 1 from correct.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### 4. File not found

**Error message:**

```
! LaTeX Error: File `mycustom.sty' not found.
```

**Cause**: Missing package, image, or bibliography file

**Solutions:**

1. Install missing package:
   ```bash theme={null}
   tlmgr install packagename  # TeX Live
   # or use your TeX distribution's package manager
   ```

2. Check file paths:
   ```latex theme={null}
   \includegraphics{images/photo.png}  % Make sure path is correct
   \bibliography{references}           % Check references.bib exists
   ```

3. Use correct file extensions:
   ```latex theme={null}
   \usepackage{mycustom}     % Looks for mycustom.sty
   \input{chapter1}          % Looks for chapter1.tex
   ```

### 5. Missing } inserted

**Error message:**

```
! Missing } inserted.
<inserted text> 
                }
l.33 \textbf{Bold text
```

**Cause**: Unmatched braces

**Solution:**

<LatexSource filename="wrong.tex" source={"\\textbf{Bold text         % Missing closing brace\n\\textit{Italic {nested}   % Missing closing brace\n$x^{2+3$                  % Missing closing brace"} />

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

<LatexSource filename="correct.tex" source={"\\textbf{Bold text}        % Correct\n\\textit{Italic {nested}}  % Correct\n$x^{2+3}$                 % Correct"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-basics-errors-08/page-1.svg" alt="Compiled PDF page 1 from correct.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>

<Tip>
  Use a text editor with brace matching to catch these errors early.
</Tip>

### 6. Environment undefined

**Error message:**

```
! LaTeX Error: Environment equation* undefined.
```

**Cause**: Using an environment that doesn't exist or missing package

**Solution:**

<LatexSource filename="example.tex" source={"% For equation* environment\n\\usepackage{amsmath}\n\n% Check spelling\n\\begin{ennumerate}  % Wrong\n\\begin{enumerate}   % Correct"} />

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

### 7. Runaway argument

**Error message:**

```
Runaway argument?
{This is a very long...
! Paragraph ended before \textbf was complete.
```

**Cause**: Missing closing brace or bracket spanning paragraphs

**Solution:**

<LatexSource filename="wrong.tex" source={"\\textbf{This is bold\n\nThis is a new paragraph}  % Error - can't span paragraphs"} />

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

<LatexSource filename="correct.tex" source={"\\textbf{This is bold}\n\nThis is a new paragraph   % Correct - close before paragraph"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-basics-errors-11/page-1.svg" alt="Compiled PDF page 1 from correct.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>

### 8. Overfull/Underfull hbox

**Warning message:**

```
Overfull \hbox (15.0pt too wide) in paragraph at lines 42--45
```

**Cause**: Text doesn't fit properly in the line

**Solutions:**

1. Let LaTeX hyphenate:
   ```latex theme={null}
   \usepackage[english]{babel}
   ```

2. Force hyphenation:
   ```latex theme={null}
   super\-cali\-fragi\-listic
   ```

3. Rewrite the sentence

4. Allow stretchy spacing:
   ```latex theme={null}
   \sloppy  % For whole document
   {\sloppy This problematic paragraph}  % For specific text
   ```

### 9. Table/Figure positioning problems

**Issue**: Tables or figures appear in wrong locations

**Solutions:**

<LatexSource filename="positioning.tex" source={"% Use positioning options\n\\begin{figure}[htbp]  % here, top, bottom, page\n\\centering\n\\includegraphics{image}\n\\caption{My figure}\n\\end{figure}\n\n% Force position (not recommended)\n\\usepackage{float}\n\\begin{figure}[H]  % Exactly Here"} />

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

### 10. Bibliography not showing

**Issue**: References not appearing

**Solution sequence:**

```bash theme={null}
pdflatex document.tex
bibtex document       # or biber document
pdflatex document.tex
pdflatex document.tex
```

## Error Categories

### Math Mode Errors

<Warning>
  **Common math mode mistakes:**

  * Text in math: Use `\text{...}` from amsmath
  * Wrong delimiter size: Use `\left(` and `\right)`
  * Display math in wrong place: Can't use `$$` in some environments
</Warning>

<LatexSource filename="math-fixes.tex" source={"% Text in math mode\n$x = 2 when y = 3$        % Wrong\n$x = 2 \\text{ when } y = 3$  % Correct\n\n% Delimiter sizing\n$(\\frac{a}{b})$           % Small parentheses\n$\\left(\\frac{a}{b}\\right)$    % Auto-sized parentheses\n\n% Display math\n\\begin{center}\n$$x = y$$                 % Wrong in center environment\n\\end{center}\n\n\\begin{center}\n$x = y$                   % Correct\n\\end{center}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-basics-errors-13/page-1.svg" alt="Compiled PDF page 1 from math-fixes.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>

### Package Conflicts

Some packages don't work well together:

<LatexSource filename="example.tex" source={"% Common conflicts\n\\usepackage{subfigure}  % Old, conflicts with many\n\\usepackage{subfig}     % Use this instead\n\n\\usepackage{pdfpages}   % Load after graphicx\n\\usepackage{hyperref}   % Usually load last"} />

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

### Font Errors

<LatexSource filename="example.tex" source={"% Font not found\n\\usepackage{times}      % Deprecated\n\\usepackage{mathptmx}   % Use this instead\n\n% Font size errors\n\\fontsize{50}           % Wrong - missing unit\n\\fontsize{50pt}{60pt}\\selectfont  % Correct"} />

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

## Debugging Strategies

### 1. Binary Search Method

Comment out half your document to isolate errors:

<LatexSource filename="example.tex" source={"\\begin{document}\nFirst part...\n%{\nSecond part...  % This part is now commented\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>

### 2. Minimal Working Example (MWE)

Create a minimal file that reproduces the error:

<LatexSource filename="example.tex" source={"\\documentclass{article}\n\\usepackage{[only needed packages]}\n\\begin{document}\n[Minimal code that causes error]\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>

### 3. Check the Log File

Look for:

* First error (fix this first)
* Line numbers
* Package warnings
* Overfull/underfull boxes

### 4. Common Quick Fixes

<CardGroup cols={2}>
  <Card title="Clear auxiliary files" icon="trash">
    Delete `.aux`, `.log`, `.toc` files and recompile
  </Card>

  <Card title="Update packages" icon="download">
    Keep your TeX distribution updated
  </Card>

  <Card title="Check encoding" icon="file-code">
    Save files as UTF-8
  </Card>

  <Card title="Simplify first" icon="compress">
    Remove packages/commands until it works
  </Card>
</CardGroup>

## Prevention Tips

<Tip>
  **Best practices to avoid errors:**

  1. Compile frequently (after every few lines when learning)
  2. Use a good editor with syntax highlighting
  3. Keep backups before major changes
  4. Organize long documents into multiple files
  5. Comment your code for complex parts
  6. Use version control (Git)
</Tip>

## Platform-Specific Issues

### Windows

* Path issues: Use forward slashes `/` or double backslashes `\\`
* Font issues: Install fonts system-wide
* Encoding: Save as UTF-8, not ANSI

### macOS

* Missing fonts: Install MacTeX fully
* Path issues: Don't use spaces in filenames
* Preview issues: Use external PDF viewer

### Linux

* Permission issues: Check file permissions
* Missing packages: Use distribution package manager
* Font issues: Update font cache

## Getting Help

When asking for help online, include:

1. Minimal Working Example (MWE)
2. Complete error message
3. TeX distribution and version
4. What you've already tried

### Help Resources

<CardGroup cols={2}>
  <Card title="TeX StackExchange" icon="stack-overflow" href="https://tex.stackexchange.com">
    Q\&A community for TeX/LaTeX
  </Card>

  <Card title="LaTeX Community" icon="users" href="https://latex.org/forum/">
    Official LaTeX forum
  </Card>

  <Card title="Reddit r/LaTeX" icon="reddit" href="https://reddit.com/r/latex">
    Reddit community
  </Card>

  <Card title="CTAN" icon="box" href="https://ctan.org">
    Package documentation
  </Card>
</CardGroup>

## Quick Reference Card

| Error                      | Quick Fix                     |
| -------------------------- | ----------------------------- |
| Missing \$                 | Wrap math in `$...$`          |
| Undefined control sequence | Check spelling or add package |
| Missing }                  | Match all opening braces      |
| File not found             | Check path and filename       |
| Overfull hbox              | Add hyphenation or rewrite    |
| Figure in wrong place      | Use `[htbp]` positioning      |
| Bibliography missing       | Run BibTeX/Biber              |
| Package unknown            | Install with package manager  |

***

<Info>
  **Remember**: Every LaTeX user encounters errors. They're not a sign of failure but an opportunity to learn. The more errors you fix, the better you become at LaTeX!
</Info>

Still stuck? Create a Minimal Working Example (MWE) - a small, self-contained document that reproduces your error - and ask for help in the community forums. Happy TeXing!

## You've Completed the Basics!

Congratulations on finishing the LaTeX basics! Here's where to go next:

<CardGroup cols={2}>
  <Card title="Mathematics" icon="square-root-variable" href="/learn/latex/mathematics/basics">
    Learn to write beautiful equations and formulas
  </Card>

  <Card title="Tables & Figures" icon="table" href="/learn/latex/tables/creating-tables">
    Add professional tables and images to your documents
  </Card>

  <Card title="Bibliography" icon="book" href="/learn/latex/bibliography-citations">
    Manage citations and references like a pro
  </Card>

  <Card title="Templates" icon="file-code" href="/templates/article">
    Start with ready-made professional templates
  </Card>
</CardGroup>
