> ## 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 Package Management

> Learn to find, install, and manage LaTeX packages. Understand CTAN, package documentation, troubleshooting conflicts, and best practices.

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

Master LaTeX package management to extend your documents with powerful features. This guide covers package discovery, installation, usage, and troubleshooting.

<Info>
  **Good news**: LaTeX Cloud Studio includes all major packages pre-installed. You can focus on using packages rather than installing them!
</Info>

## Understanding LaTeX Packages

### What Are Packages?

Packages extend LaTeX's core functionality by providing:

* Additional commands and environments
* New document classes
* Enhanced formatting options
* Specialized symbols and fonts
* Integration with external tools

<LatexSource filename="package-basics.tex" source={"% Loading packages in the preamble\n\\documentclass{article}\n\n% Essential packages\n\\usepackage[utf8]{inputenc}    % Input encoding\n\\usepackage[T1]{fontenc}       % Font encoding\n\\usepackage[english]{babel}    % Language support\n\\usepackage{graphicx}          % Graphics inclusion\n\\usepackage{amsmath}           % Enhanced mathematics\n\n% Packages with options\n\\usepackage[margin=1in]{geometry}     % Page layout\n\\usepackage[style=authoryear]{biblatex}  % Bibliography\n\\usepackage[table,xcdraw]{xcolor}     % Colors\n\n\\begin{document}\n% Package commands now available\n\\includegraphics{image.png}    % From graphicx\n\\textcolor{blue}{Blue text}    % From xcolor\n\\begin{align}                  % From amsmath\n  E &= mc^2\n\\end{align}\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>

### Package Categories

<CardGroup cols={2}>
  <Card title="Core Extensions" icon="gear">
    **amsmath, amssymb, graphicx, geometry**
    Essential packages that most documents need
  </Card>

  <Card title="Specialized Tools" icon="wrench">
    **tikz, minted, algorithm2e, chemfig**
    Domain-specific packages for specialized content
  </Card>

  <Card title="Formatting & Style" icon="paintbrush">
    **fancyhdr, titlesec, enumitem, booktabs**
    Packages that enhance document appearance
  </Card>

  <Card title="Language & Fonts" icon="font">
    **babel, fontspec, polyglossia, microtype**
    Internationalization and typography
  </Card>
</CardGroup>

## Finding Packages

### CTAN: The Comprehensive TeX Archive Network

<LatexSource filename="finding-packages.tex" source={"% CTAN is the central repository for LaTeX packages\n% Visit: https://ctan.org\n\n% Common search strategies:\n% 1. Browse by topic: https://ctan.org/topics\n% 2. Search by name: https://ctan.org/search\n% 3. Browse alphabetically: https://ctan.org/pkg\n\n% Popular package categories:\n% - Graphics: tikz, pgfplots, graphicx\n% - Mathematics: amsmath, mathtools, physics\n% - Tables: booktabs, array, longtable\n% - Bibliography: biblatex, natbib\n% - Code: listings, minted, algorithm2e\n% - Fonts: fontspec, lmodern, libertine"} />

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

### Package Documentation

Every package should include documentation. Here's how to access it:

<CodeGroup>
  ```bash package-documentation.bash theme={null}
  # Command line (if you have LaTeX installed locally)
  texdoc packagename          # Opens package documentation
  texdoc graphicx            # Example: graphicx documentation
  texdoc amsmath             # Example: amsmath documentation

  # Alternative methods:
  # 1. CTAN package page: https://ctan.org/pkg/packagename
  # 2. Google: "latex packagename documentation"
  # 3. LaTeX package galleries and guides
  ```
</CodeGroup>

### Popular Package Collections

<LatexSource filename="popular-packages.tex" source={"% Essential mathematics\n\\usepackage{amsmath}      % Enhanced math environments\n\\usepackage{amssymb}      % Additional math symbols\n\\usepackage{mathtools}    % Extensions to amsmath\n\n% Graphics and figures\n\\usepackage{graphicx}     % Include graphics\n\\usepackage{tikz}         % Create graphics programmatically\n\\usepackage{pgfplots}     % Create plots and charts\n\n% Tables and arrays\n\\usepackage{booktabs}     % Professional table formatting\n\\usepackage{array}        % Enhanced column types\n\\usepackage{longtable}    % Multi-page tables\n\n% Text formatting\n\\usepackage{microtype}    % Improved typography\n\\usepackage{enumitem}     % Customizable lists\n\\usepackage{fancyhdr}     % Custom headers/footers\n\n% Colors and styling\n\\usepackage{xcolor}       % Color support\n\\usepackage{listings}     % Code listings\n\\usepackage{hyperref}     % Hyperlinks and PDF features\n\n% Bibliography and citations\n\\usepackage{biblatex}     % Modern bibliography (recommended)\n\\usepackage{natbib}       % Traditional bibliography"} />

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

## Package Installation

### LaTeX Cloud Studio (Pre-installed)

<Info>
  **LaTeX Cloud Studio advantage**: All major packages are pre-installed and ready to use. Simply add `\usepackage{packagename}` to your document.
</Info>

<LatexSource filename="cloud-studio-packages.tex" source={"% These packages work immediately in LaTeX Cloud Studio:\n\\usepackage{amsmath}      ✓ Mathematics\n\\usepackage{graphicx}     ✓ Graphics\n\\usepackage{tikz}         ✓ Drawings\n\\usepackage{booktabs}     ✓ Tables\n\\usepackage{listings}     ✓ Code\n\\usepackage{biblatex}     ✓ Bibliography\n\\usepackage{hyperref}     ✓ Links\n\\usepackage{xcolor}       ✓ Colors\n\\usepackage{geometry}     ✓ Page layout\n\\usepackage{fancyhdr}     ✓ Headers/footers\n% And hundreds more..."} />

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

### Local Installation (For Reference)

<CodeGroup>
  ```bash local-installation.bash theme={null}
  # TeX Live (Linux/macOS/Windows)
  sudo apt-get install texlive-full    # Ubuntu/Debian
  brew install --cask mactex           # macOS
  # Windows: Download from https://tug.org/texlive/

  # MiKTeX (Windows/macOS/Linux)
  # Download from https://miktex.org/
  # Automatically installs packages on first use

  # Manual package installation (if needed)
  # 1. Download package from CTAN
  # 2. Extract to appropriate directory
  # 3. Run texhash to update database
  # 4. Update package database if required
  ```
</CodeGroup>

## Package Usage Patterns

### Loading Order Matters

<LatexSource filename="package-order.tex" source={"\\documentclass{article}\n\n% 1. Input/Output encoding (first)\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\n% 2. Language and fonts\n\\usepackage[english]{babel}\n\\usepackage{lmodern}\n\n% 3. Page layout\n\\usepackage[margin=1in]{geometry}\n\n% 4. Mathematics (early for widespread use)\n\\usepackage{amsmath,amssymb}\n\n% 5. Graphics and colors\n\\usepackage{graphicx}\n\\usepackage{xcolor}\n\n% 6. Tables and lists\n\\usepackage{booktabs}\n\\usepackage{enumitem}\n\n% 7. Bibliography (before hyperref)\n\\usepackage[backend=biber]{biblatex}\n\n% 8. Hyperref (near the end)\n\\usepackage{hyperref}\n\n% 9. Packages that must load after hyperref\n\\usepackage{cleveref}\n\n\\begin{document}\n% Content here\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code performs setup or defines reusable behavior without producing visible page content on its own. It must be used inside a complete document to have a rendered result.
  </Info>
</RenderedOutput>

### Package Options

<LatexSource filename="package-options.tex" source={"% Packages often accept options to modify behavior\n\n% Geometry with specific margins\n\\usepackage[\n  top=1in,\n  bottom=1in,\n  left=1.5in,\n  right=1in,\n  headheight=15pt\n]{geometry}\n\n% Babel with multiple languages\n\\usepackage[english,spanish,french]{babel}\n\n% Biblatex with style and backend\n\\usepackage[\n  backend=biber,\n  style=authoryear,\n  sorting=nyt,\n  maxcitenames=2\n]{biblatex}\n\n% Hyperref with link colors\n\\usepackage[\n  colorlinks=true,\n  linkcolor=blue,\n  citecolor=green,\n  urlcolor=red\n]{hyperref}\n\n% Listings with default language\n\\usepackage[language=Python]{listings}\n\n% Multiple options for xcolor\n\\usepackage[table,xcdraw,dvipsnames]{xcolor}"} />

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

### Conditional Package Loading

<LatexSource filename="conditional-loading.tex" source={"% Check if package is available\n\\IfPackageExists{microtype}{\n  \\usepackage{microtype}\n  \\newcommand{\\hasmicrotype}{true}\n}{\n  \\newcommand{\\hasmicrotype}{false}\n}\n\n% Load different packages based on compiler\n\\usepackage{iftex}\n\\ifPDFTeX\n  \\usepackage[utf8]{inputenc}\n  \\usepackage[T1]{fontenc}\n\\else\n  \\usepackage{fontspec}\n\\fi\n\n% Version-specific loading\n\\@ifpackagelater{tikz}{2020/12/27}{\n  % TikZ version 3.1.8 or later\n  \\usetikzlibrary{new-features}\n}{\n  % Older TikZ version\n  \\usetikzlibrary{legacy-features}\n}\n\n% Global options vs package options\n\\documentclass[12pt]{article}  % Global option affects all packages\n\\usepackage{geometry}          % Inherits 12pt if relevant\n\n% Override global options\n\\usepackage[10pt]{package}     % This package uses 10pt regardless"} />

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

## Package Conflicts and Compatibility

### Common Conflicts

<Warning>
  **Known package conflicts:**

  1. **hyperref conflicts**: Load hyperref late, but before cleveref
  2. **Font conflicts**: Don't mix incompatible font packages
  3. **Math conflicts**: amsmath and mathtools can conflict with some packages
  4. **Table conflicts**: Some table packages don't work together
  5. **Encoding conflicts**: inputenc and fontspec are mutually exclusive
</Warning>

<LatexSource filename="handling-conflicts.tex" source={"% Conflict: subfigure vs subcaption\n% DON'T DO THIS:\n% \\usepackage{subfigure}    % Obsolete\n% \\usepackage{subcaption}   % Modern\n% DO THIS:\n\\usepackage{subcaption}     % Use only the modern package\n\n% Conflict: times vs newtx\n% DON'T DO THIS:\n% \\usepackage{times}        % Obsolete\n% \\usepackage{newtxtext}    % Modern replacement\n% DO THIS:\n\\usepackage{newtxtext,newtxmath}  % Complete modern replacement\n\n% Conflict: hyperref positioning\n% WRONG ORDER:\n% \\usepackage{cleveref}\n% \\usepackage{hyperref}\n% CORRECT ORDER:\n\\usepackage{hyperref}\n\\usepackage{cleveref}\n\n% Resolving font encoding conflicts\n\\usepackage{iftex}\n\\ifPDFTeX\n  \\usepackage[utf8]{inputenc}  % For pdflatex\n  \\usepackage[T1]{fontenc}\n\\else\n  \\usepackage{fontspec}        % For xelatex/lualatex\n\\fi"} />

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

<LatexSource filename="debugging-packages.tex" source={"% Method 1: Minimal example\n\\documentclass{article}\n\\usepackage{problematic-package}\n\\begin{document}\nTest content\n\\end{document}\n\n% Method 2: Load packages incrementally\n\\documentclass{article}\n% \\usepackage{package1}     % Comment out packages one by one\n% \\usepackage{package2}     % to identify conflicts\n% \\usepackage{package3}\n\\usepackage{package4}       % Until you find the problematic combination\n\n% Method 3: Check package versions\n\\listfiles                  % Add this before \\begin{document}\n% This will list all loaded packages and versions in the log\n\n% Method 4: Verbose error reporting\n\\errorcontextlines=999      % Show more context in error messages\n\\tracingmacros=1           % Trace macro expansions (very verbose!)"} />

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

## Essential Package Categories

### Mathematics and Science

<LatexSource filename="math-science-packages.tex" source={"% Core mathematics\n\\usepackage{amsmath}        % Essential math environments\n\\usepackage{amssymb}        % Additional symbols\n\\usepackage{mathtools}      % Enhanced amsmath\n\n% Advanced mathematics\n\\usepackage{physics}        % Physics notation\n\\usepackage{siunitx}        % SI units\n\\usepackage{tensor}         % Tensor notation\n\\usepackage{cancel}         % Cancel terms in equations\n\n% Chemistry\n\\usepackage{mhchem}         % Chemical formulas\n\\usepackage{chemfig}        % Chemical structures\n\\usepackage{chemmacros}     % Chemical macros\n\n% Algorithm typesetting\n\\usepackage{algorithm}      % Algorithm floats\n\\usepackage{algpseudocode}  % Pseudocode\n\\usepackage{algorithm2e}    % Alternative algorithm package"} />

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

### Graphics and Visualization

<LatexSource filename="graphics-packages.tex" source={"% Basic graphics\n\\usepackage{graphicx}       % Include images\n\\usepackage{rotating}       % Rotate content\n\\usepackage{wrapfig}        % Wrap text around figures\n\n% Advanced graphics\n\\usepackage{tikz}           % Programmatic graphics\n\\usepackage{pgfplots}       % Data plotting\n\\usepackage{circuitikz}     % Circuit diagrams\n\n% Subfigures\n\\usepackage{subcaption}     % Modern subfigures\n\\usepackage{subfig}         % Alternative (less recommended)\n\n% Figure positioning\n\\usepackage{float}          % Enhanced float control\n\\usepackage{placeins}       % Float barriers"} />

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

### Text and Document Formatting

<LatexSource filename="formatting-packages.tex" source={"% Typography\n\\usepackage{microtype}      % Improved typography\n\\usepackage{setspace}       % Line spacing control\n\\usepackage{parskip}        % Paragraph spacing\n\n% Page layout\n\\usepackage{geometry}       % Page dimensions\n\\usepackage{fancyhdr}       % Headers and footers\n\\usepackage{titlesec}       % Section title formatting\n\n% Lists and itemization\n\\usepackage{enumitem}       % Customizable lists\n\\usepackage{mdwlist}        % Compact lists\n\n% Tables\n\\usepackage{booktabs}       % Professional tables\n\\usepackage{array}          % Enhanced column types\n\\usepackage{tabularx}       % Auto-width tables\n\\usepackage{longtable}      % Multi-page tables\n\\usepackage{ltxtable}       % Combination of longtable and tabularx"} />

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

### Code and Verbatim

<LatexSource filename="code-packages.tex" source={"% Code listings\n\\usepackage{listings}       % Basic code listings\n\\usepackage{minted}         % Advanced syntax highlighting (requires pygments)\n\\usepackage{fancyvrb}       % Enhanced verbatim\n\n% Listings configuration\n\\lstset{\n  language=Python,\n  basicstyle=\\ttfamily\\small,\n  keywordstyle=\\color{blue},\n  commentstyle=\\color{green},\n  stringstyle=\\color{red},\n  numbers=left,\n  numberstyle=\\tiny,\n  breaklines=true\n}\n\n% Minted configuration\n\\setminted{\n  fontsize=\\small,\n  linenos=true,\n  breaklines=true,\n  frame=lines\n}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code depends on minted's external syntax-highlighting process. The documentation renderer deliberately disables shell escape, so the secure preview pipeline explains the effect instead of executing an external process.
  </Info>
</RenderedOutput>

## Advanced Package Management

### Creating Your Own Packages

<LatexSource filename="custom-package.sty" source={"% mypackage.sty - Custom package file\n\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{mypackage}[2024/01/01 My Custom Package]\n\n% Package options\n\\newif\\if@myoption\n\\@myoptionfalse\n\\DeclareOption{myoption}{\\@myoptiontrue}\n\\ProcessOptions\\relax\n\n% Required packages\n\\RequirePackage{amsmath}\n\\RequirePackage{xcolor}\n\n% Custom commands\n\\newcommand{\\highlight}[1]{\\textcolor{yellow}{#1}}\n\\newcommand{\\important}[1]{\\textbf{\\textcolor{red}{#1}}}\n\n% Custom environments\n\\newenvironment{myenv}{%\n  \\begin{center}\\color{blue}\\bfseries\n}{%\n  \\end{center}\n}\n\n% Conditional code based on options\n\\if@myoption\n  \\newcommand{\\optionalcommand}{This appears with myoption}\n\\else\n  \\newcommand{\\optionalcommand}{This appears without myoption}\n\\fi"} />

<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="using-custom-package.tex" source={"% Using the custom package\n\\documentclass{article}\n\\usepackage[myoption]{mypackage}  % Load with option\n\n\\begin{document}\n\\highlight{Highlighted text}\n\\important{Important text}\n\n\\begin{myenv}\nContent in custom environment\n\\end{myenv}\n\n\\optionalcommand\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>

### Package Version Control

<LatexSource filename="version-control.tex" source={"% Require specific package version\n\\usepackage{l3packages}\n\\ExplSyntaxOn\n\\msg_new:nnn { mypackage } { version-too-old }\n  { Package~'#1'~is~too~old.~Required:~#2,~Found:~#3 }\n\n% Check if package version is sufficient\n\\@ifpackagelater{tikz}{2020/12/27}{\n  % Version is 3.1.8 or later\n}{\n  \\msg_error:nnn { mypackage } { version-too-old } { tikz } { 3.1.8 } { \\@ifpackageloaded{tikz}{\\csname ver@tikz.sty\\endcsname}{not loaded} }\n}\n\\ExplSyntaxOff\n\n% Alternative simple version check\n\\@ifpackagelater{amsmath}{2017/09/02}{}{\n  \\PackageError{mydocument}{amsmath package too old}{}\n}"} />

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

## Best Practices

<Tip>
  **Package management best practices:**

  1. **Document requirements**: List all required packages in comments
  2. **Use stable packages**: Prefer well-established packages over experimental ones
  3. **Read documentation**: Always check package documentation before use
  4. **Test compatibility**: Test package combinations in minimal examples
  5. **Version control**: Document package versions for reproducible builds
  6. **Minimal loading**: Only load packages you actually use
  7. **Load order**: Follow standard loading order to avoid conflicts
  8. **Keep updated**: Use recent package versions when possible
</Tip>

### Package Documentation Template

<LatexSource filename="package-documentation.tex" source={"% Document header with package requirements\n%\n% Required packages:\n% - amsmath (core LaTeX distribution)\n% - graphicx (core LaTeX distribution)\n% - tikz (CTAN: tikz)\n% - booktabs (CTAN: booktabs)\n% - biblatex with biber backend\n%\n% Optional packages:\n% - microtype (improved typography)\n% - hyperref (PDF links and bookmarks)\n%\n% Compilation: pdflatex -> biber -> pdflatex -> pdflatex\n%\n\n\\documentclass{article}\n\n% Package loading with version comments\n\\usepackage{amsmath}        % v2.17 or later\n\\usepackage{graphicx}       % v1.1 or later\n\\usepackage{tikz}           % v3.1.8 or later for advanced features\n\\usepackage{booktabs}       % v1.6 or later\n\\usepackage[backend=biber]{biblatex}  % v3.16 or later\n\n% Document content\n\\begin{document}\nContent requiring the above packages...\n\\end{document}"} />

<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_package_management">
  <LatexPreview src="/images/rendered/learn-latex-package-management-17/page-1.svg" alt="Compiled PDF page 1 from package-documentation.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

## Troubleshooting Guide

### Common Error Messages

<Warning>
  **Fixing common package errors:**

  1. **"Package not found"**: Check spelling and availability
  2. **"Option clash"**: Package loaded twice with different options
  3. **"Command already defined"**: Two packages define the same command
  4. **"Missing number"**: Syntax error in package options
  5. **"Unknown option"**: Option not supported by package version
  6. **"File not found"**: Missing package files or dependencies
</Warning>

<LatexSource filename="troubleshooting.tex" source={"% Error: Package not found\n% Solution: Check package name spelling\n\\usepackage{graphicx}  % Correct\n% \\usepackage{graphics}  % Common misspelling\n\n% Error: Option clash\n% Problem:\n% \\usepackage[utf8]{inputenc}\n% \\usepackage[latin1]{inputenc}  % Conflict!\n% Solution: Use global options or load once\n\\PassOptionsToPackage{utf8}{inputenc}\n\\usepackage{inputenc}\n\n% Error: Command redefinition\n% Problem: Two packages define \\example\n% Solution: Rename one command\n\\usepackage{package1}\n\\let\\exampleoriginal\\example\n\\usepackage{package2}  % Redefines \\example\n\\let\\examplenew\\example\n\\let\\example\\exampleoriginal  % Restore original\n\n% Error: Unknown option\n% Check package documentation for valid options\n\\usepackage[colorlinks=true]{hyperref}  % Valid option\n% \\usepackage[invalidoption]{hyperref}   % Would cause error"} />

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

## Quick Reference

### Essential Package Loading Order

<LatexSource filename="example.tex" source={"% 1. Input/Output\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\n% 2. Language\n\\usepackage[english]{babel}\n\n% 3. Layout\n\\usepackage{geometry}\n\n% 4. Math\n\\usepackage{amsmath,amssymb}\n\n% 5. Graphics\n\\usepackage{graphicx}\n\n% 6. Colors\n\\usepackage{xcolor}\n\n% 7. Bibliography\n\\usepackage{biblatex}\n\n% 8. Hyperref (late)\n\\usepackage{hyperref}\n\n% 9. After hyperref\n\\usepackage{cleveref}"} />

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

### Package Categories Quick List

| Category         | Essential Packages                  |
| ---------------- | ----------------------------------- |
| **Math**         | `amsmath`, `amssymb`, `mathtools`   |
| **Graphics**     | `graphicx`, `tikz`, `subcaption`    |
| **Tables**       | `booktabs`, `array`, `longtable`    |
| **Bibliography** | `biblatex`, `natbib`                |
| **Typography**   | `microtype`, `setspace`, `enumitem` |
| **Layout**       | `geometry`, `fancyhdr`, `titlesec`  |
| **Code**         | `listings`, `minted`, `fancyvrb`    |
| **PDF**          | `hyperref`, `cleveref`, `bookmark`  |

***

<Info>
  **Next**: Learn about [Enhanced cross-linking](/learn/latex/cross-referencing) to improve navigation between related topics in your documentation.
</Info>
