> ## 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 listings vs minted: Code Blocks, Highlighting, and Setup

> Compare listings and minted for LaTeX code blocks. Includes copy-ready setup, minted v3 requirements, inline code, file imports, caching, and fixes.

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

Use `listings` when you need portable code blocks with no external highlighter. Use `minted` when syntax quality matters and the build environment provides the `latexminted` executable and Pygments. On current TeX Live 2024+ installations, `minted` v3 can normally use trusted restricted shell escape without the unsafe global `-shell-escape` flag.

<Info>
  **Quick answer**: choose `listings` for journals, CI systems, or editors where external commands may be unavailable. Choose `minted` for richer Pygments highlighting. TeX Live 2024+ with `minted` v3 usually compiles normally; older TeX Live and some MiKTeX setups require explicit permission for `latexminted`.

  **Related topics**: [Text formatting](/learn/latex/text-formatting) | [Fonts](/learn/latex/fonts) | [Headers & footers](/learn/latex/formatting/headers-footers) | [Errors](/learn/latex/basics/errors)
</Info>

## `listings` vs `minted`

| Requirement                     | `listings`                         | `minted`                                                                           |
| ------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------- |
| Syntax highlighting             | Built-in, configured in LaTeX      | Pygments-based, usually more accurate                                              |
| External executable             | None                               | `latexminted` plus Pygments                                                        |
| Current TeX Live 2024+          | Normal compilation                 | Normally works through trusted restricted shell escape                             |
| Older TeX Live or MiKTeX        | Normal compilation                 | May require `-shell-escape`, `-enable-write18`, or a trusted-command configuration |
| Locked-down CI or journal build | Safest default                     | Use only if the environment supports it or accepts a frozen cache                  |
| Inline code                     | `\lstinline`                       | `\mintinline`                                                                      |
| Import source files             | `\lstinputlisting`                 | `\inputminted`                                                                     |
| Built-in result caching         | No Pygments cache needed           | Enabled by default; frozen cache is available                                      |
| Best fit                        | Portability and predictable builds | High-quality highlighting and themes                                               |

### Choose in 30 seconds

* Choose **`listings`** if the PDF must compile anywhere, the source is untrusted, or the publisher controls the build.
* Choose **`minted`** if highlighting quality matters and you control or have verified the toolchain.
* Choose **`listings`** when you are unsure. You can switch later without changing the surrounding document structure.

## Quick Start

### Minimal `listings` setup

Use this when you want a simple code block and do not want to change your compiler settings.

<LatexSource filename="listings-quickstart.tex" source={"\\documentclass{article}\n\\usepackage{listings}\n\n\\begin{document}\n\n\\begin{lstlisting}[language=Python]\ndef hello():\n    print(\"Hello, world!\")\n\\end{lstlisting}\n\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_formatting_code_listings_minted">
  <LatexPreview src="/images/rendered/learn-latex-formatting-code-listings-minted-01/page-1.svg" alt="Compiled PDF page 1 from listings-quickstart.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Minimal `minted` setup

Use this when you want Pygments syntax highlighting and the build environment provides `minted` v3 and `latexminted`.

<LatexSource filename="minted-quickstart.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\n\\begin{document}\n\n\\begin{minted}{python}\ndef hello():\n    print(\"Hello, world!\")\n\\end{minted}\n\n\\end{document}"} />

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

With an up-to-date TeX Live 2024+ installation, compile normally:

```bash theme={null}
pdflatex file.tex
```

For older TeX Live releases, full shell escape may still be required:

```bash theme={null}
pdflatex -shell-escape file.tex
```

<Warning>
  Full `-shell-escape` allows LaTeX to run arbitrary system commands. Use it only for documents you trust. Prefer current `minted` v3 with the restricted `latexminted` executable, or use `listings` in untrusted and locked-down environments.
</Warning>

### The usual `minted` failure

If `minted` does not compile, the problem is usually one of these:

* `minted`, `latexminted`, or its Python dependencies are not installed
* the TeX distribution does not permit `latexminted` through restricted shell escape
* an older TeX Live or MiKTeX setup needs explicit permission
* the editor, CI runner, or publisher blocks all external commands

If you cannot change the build setup, use `listings` instead.

<Info>
  LaTeX Cloud Studio keeps unrestricted `-shell-escape` disabled for untrusted compilation. Use `listings` for guaranteed portability. `minted` v3 may work through the restricted, trusted `latexminted` path when it is available in the active compiler image.
</Info>

### Cache highlighted code for restricted builds

`minted` caches highlighted output in `_minted` by default. If the final build cannot run `latexminted`, generate the cache in an allowed environment and then enable `frozencache`:

<LatexSource filename="minted-frozen-cache.tex" source={"% Enable this only after the complete cache has been generated.\n\\usepackage[frozencache]{minted}"} />

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

Keep the generated cache with the document. With `frozencache=true`, compilation fails when a required cache entry is missing instead of trying to execute the highlighter. This is useful for publisher and CI workflows, but `listings` remains simpler when cached artifacts are not accepted.

### Inline code

For short snippets inside a paragraph:

<LatexSource filename="inline-code.tex" source={"Use \\lstinline|-shell-escape| with listings examples.\n\nUse \\mintinline{latex}{\\usepackage{minted}} for minted inline code."} />

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

## The listings Package

### Basic Code Formatting

<LatexSource filename="listings-basic.tex" source={"\\documentclass{article}\n\\usepackage{listings}\n\\usepackage{xcolor}\n\n% Basic configuration\n\\lstset{\n  basicstyle=\\ttfamily\\footnotesize,\n  breaklines=true,\n  frame=single,\n  numbers=left,\n  numberstyle=\\tiny,\n  stepnumber=1,\n  showstringspaces=false\n}\n\n\\begin{document}\n\n\\section{Code Examples}\n\n\\begin{lstlisting}[language=Python]\ndef fibonacci(n):\n    \"\"\"Calculate the nth Fibonacci number.\"\"\"\n    if n <= 1:\n        return n\n    return fibonacci(n-1) + fibonacci(n-2)\n\n# Example usage\nfor i in range(10):\n    print(f\"F({i}) = {fibonacci(i)}\")\n\\end{lstlisting}\n\n% Inline code\nThe function \\lstinline|fibonacci(n)| calculates Fibonacci numbers.\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-formatting-code-listings-minted-05/page-1.svg" alt="Compiled PDF page 1 from listings-basic.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

**Expected output:**

<Card title="Expected output" icon="eye">
  A code block with a light gray background and single-line frame border. Line numbers (1-10) appear in the left margin in a subtle gray color. The Python code displays in a monospace font with consistent formatting: the function definition, docstring, conditional logic, and loop are all clearly visible with proper indentation preserved.
</Card>

### Language-Specific Styling

<LatexSource filename="listings-languages.tex" source={"\\documentclass{article}\n\\usepackage{listings}\n\\usepackage{xcolor}\n\n% Python style\n\\lstdefinestyle{pythonstyle}{\n  language=Python,\n  basicstyle=\\ttfamily\\small,\n  keywordstyle=\\color{blue}\\bfseries,\n  stringstyle=\\color{red},\n  commentstyle=\\color{gray}\\itshape,\n  numberstyle=\\tiny\\color{gray},\n  breaklines=true,\n  showstringspaces=false,\n  frame=leftline,\n  framerule=2pt,\n  rulecolor=\\color{blue!30},\n  backgroundcolor=\\color{blue!5}\n}\n\n% Java style\n\\lstdefinestyle{javastyle}{\n  language=Java,\n  basicstyle=\\ttfamily\\small,\n  keywordstyle=\\color{purple}\\bfseries,\n  stringstyle=\\color{orange},\n  commentstyle=\\color{green!60!black}\\itshape,\n  numberstyle=\\tiny\\color{gray},\n  breaklines=true,\n  showstringspaces=false,\n  frame=tb,\n  framerule=1pt\n}\n\n% C++ style\n\\lstdefinestyle{cppstyle}{\n  language=C++,\n  basicstyle=\\ttfamily\\small,\n  keywordstyle=\\color{blue}\\bfseries,\n  stringstyle=\\color{red!80!black},\n  commentstyle=\\color{green!60!black}\\itshape,\n  numberstyle=\\tiny\\color{gray},\n  breaklines=true,\n  showstringspaces=false,\n  frame=single,\n  frameround=tttt\n}\n\n\\begin{document}\n\n\\section{Python Example}\n\\begin{lstlisting}[style=pythonstyle]\nclass DataProcessor:\n    def __init__(self, data):\n        self.data = data\n\n    def process(self):\n        \"\"\"Process the data using advanced algorithms.\"\"\"\n        result = []\n        for item in self.data:\n            if self.validate(item):\n                result.append(self.transform(item))\n        return result\n\\end{lstlisting}\n\n\\section{Java Example}\n\\begin{lstlisting}[style=javastyle]\npublic class Calculator {\n    private double result;\n\n    public Calculator() {\n        this.result = 0.0;\n    }\n\n    public double add(double value) {\n        result += value;\n        return result;\n    }\n\n    public void reset() {\n        result = 0.0;\n    }\n}\n\\end{lstlisting}\n\n\\section{C++ Example}\n\\begin{lstlisting}[style=cppstyle]\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\ntemplate<typename T>\nclass Container {\nprivate:\n    std::vector<T> data;\n\npublic:\n    void add(const T& item) {\n        data.push_back(item);\n    }\n\n    void sort() {\n        std::sort(data.begin(), data.end());\n    }\n};\n\\end{lstlisting}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-formatting-code-listings-minted-06/page-1.svg" alt="Compiled PDF page 1 from listings-languages.tex" caption="Page 1 of 2. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />

  <LatexPreview src="/images/rendered/learn-latex-formatting-code-listings-minted-06/page-2.svg" alt="Compiled PDF page 2 from listings-languages.tex" caption="Page 2 of 2. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

**Expected output:**

<Card title="Expected output" icon="eye">
  **Language-specific syntax highlighting** - Each style applies different colors and formatting:

  * **Python style**: Blue keywords, red strings, gray comments, light blue background with left border
  * **Java style**: Purple keywords, orange strings, green comments, top/bottom frame
  * **C++ style**: Blue keywords, dark red strings, green comments, rounded frame

  The code appears in a monospace font with proper indentation and language-specific keyword coloring.
</Card>

### Custom Language Definitions

<LatexSource filename="listings-custom-language.tex" source={"\\documentclass{article}\n\\usepackage{listings}\n\\usepackage{xcolor}\n\n% Define custom language (LaTeX commands)\n\\lstdefinelanguage{LaTeX}{\n  morekeywords={\n    documentclass, usepackage, begin, end, section, subsection,\n    title, author, maketitle, textbf, textit, emph, label, ref,\n    cite, bibliography, includegraphics, caption\n  },\n  morecomment=[l]{\\%},\n  morestring=[b]\",\n  morestring=[b]',\n  sensitive=true\n}\n\n% Style for LaTeX\n\\lstdefinestyle{latexstyle}{\n  language=LaTeX,\n  basicstyle=\\ttfamily\\small,\n  keywordstyle=\\color{blue}\\bfseries,\n  stringstyle=\\color{red},\n  commentstyle=\\color{green!60!black}\\itshape,\n  breaklines=true,\n  showstringspaces=false,\n  frame=single,\n  backgroundcolor=\\color{yellow!10},\n  escapeinside={(*@}{@*)}  % Allow LaTeX commands inside\n}\n\n% Define SQL language\n\\lstdefinelanguage{SQL}{\n  morekeywords={\n    SELECT, FROM, WHERE, INSERT, UPDATE, DELETE, CREATE, TABLE,\n    INDEX, PRIMARY, KEY, FOREIGN, REFERENCES, JOIN, INNER, LEFT,\n    RIGHT, OUTER, GROUP, BY, ORDER, HAVING, DISTINCT, COUNT, SUM,\n    AVG, MAX, MIN, AND, OR, NOT, NULL, TRUE, FALSE\n  },\n  morecomment=[l]{--},\n  morecomment=[s]{/*}{*/},\n  morestring=[b]\",\n  morestring=[b]',\n  sensitive=false\n}\n\n\\begin{document}\n\n\\section{LaTeX Code Example}\n\\begin{lstlisting}[style=latexstyle]\n\\documentclass{article}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\n\\title{My Document}\n\\author{John Doe}\n\n\\begin{document}\n\\maketitle\n\n\\section{Introduction}\nThis is an example of (*@\\textbf{LaTeX}@*) code formatting.\n\n\\begin{equation}\nE = mc^2\n\\end{equation}\n\n\\end{document}\n\\end{lstlisting}\n\n\\section{SQL Example}\n\\begin{lstlisting}[language=SQL, style=javastyle]\n-- Create a table for user information\nCREATE TABLE users (\n    id INTEGER PRIMARY KEY,\n    username VARCHAR(50) NOT NULL UNIQUE,\n    email VARCHAR(100) NOT NULL,\n    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- Insert sample data\nINSERT INTO users (username, email) VALUES\n    ('john_doe', 'john_doe_mail'),\n    ('jane_smith', 'jane_smith_mail');\n\n-- Query with joins\nSELECT u.username, p.title, p.created_at\nFROM users u\nINNER JOIN posts p ON u.id = p.user_id\nWHERE p.published = TRUE\nORDER BY p.created_at DESC;\n\\end{lstlisting}\n\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>

## The minted Package

### Basic minted Setup

<Warning>
  `minted` v3 uses the `latexminted` executable and Pygments. TeX Live 2024+ normally permits `latexminted` through restricted shell escape; older TeX Live and some MiKTeX configurations need explicit permission. Do not enable unrestricted shell escape for untrusted documents.
</Warning>

<LatexSource filename="minted-basic.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\n% Global minted settings\n\\setminted{\n  fontsize=\\footnotesize,\n  linenos,\n  breaklines,\n  frame=lines,\n  framesep=2mm\n}\n\n\\begin{document}\n\n\\section{Python with minted}\n\n\\begin{minted}{python}\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef mandelbrot(c, max_iter):\n    \"\"\"Calculate the Mandelbrot set value for complex number c.\"\"\"\n    z = 0\n    for n in range(max_iter):\n        if abs(z) > 2:\n            return n\n        z = z*z + c\n    return max_iter\n\n# Generate Mandelbrot set\nwidth, height = 800, 600\nxmin, xmax = -2.0, 1.0\nymin, ymax = -1.5, 1.5\n\nmandelbrot_set = np.zeros((height, width))\nfor i in range(height):\n    for j in range(width):\n        c = complex(xmin + (xmax - xmin) * j / width,\n                   ymin + (ymax - ymin) * i / height)\n        mandelbrot_set[i, j] = mandelbrot(c, 100)\n\nplt.imshow(mandelbrot_set, extent=[xmin, xmax, ymin, ymax],\n           cmap='hot', origin='lower')\nplt.colorbar()\nplt.title('Mandelbrot Set')\nplt.show()\n\\end{minted}\n\n\\end{document}"} />

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

<LatexSource filename="minted-advanced.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\\usepackage{mdframed}\n\\usepackage{xcolor}\n\n% Define custom style\n\\definecolor{codegray}{rgb}{0.95,0.95,0.95}\n\\definecolor{codeframe}{rgb}{0.7,0.7,0.7}\n\n% Custom environment for highlighted code\n\\newenvironment{mintedbox}[1]{%\n  \\begin{mdframed}[\n    linecolor=codeframe,\n    backgroundcolor=codegray,\n    roundcorner=5pt,\n    linewidth=1pt,\n    innertopmargin=10pt,\n    innerbottommargin=10pt,\n    innerleftmargin=10pt,\n    innerrightmargin=10pt\n  ]\n  \\begin{minted}[\n    fontsize=\\small,\n    linenos,\n    breaklines,\n    numbersep=5pt,\n    gobble=2\n  ]{#1}\n}{%\n  \\end{minted}\n  \\end{mdframed}\n}\n\n\\begin{document}\n\n\\section{Styled Code Blocks}\n\n\\begin{mintedbox}{javascript}\n  // Advanced JavaScript example with ES6+ features\n  class APIClient {\n    constructor(baseURL) {\n      this.baseURL = baseURL;\n      this.headers = {\n        'Content-Type': 'application/json',\n        'Accept': 'application/json'\n      };\n    }\n\n    async request(endpoint, options = {}) {\n      const url = `${this.baseURL}${endpoint}`;\n      const config = {\n        ...options,\n        headers: {\n          ...this.headers,\n          ...options.headers\n        }\n      };\n\n      try {\n        const response = await fetch(url, config);\n\n        if (!response.ok) {\n          throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n        }\n\n        return await response.json();\n      } catch (error) {\n        console.error('API request failed:', error);\n        throw error;\n      }\n    }\n\n    // Convenience methods\n    get(endpoint) {\n      return this.request(endpoint, { method: 'GET' });\n    }\n\n    post(endpoint, data) {\n      return this.request(endpoint, {\n        method: 'POST',\n        body: JSON.stringify(data)\n      });\n    }\n  }\n\n  // Usage example\n  const client = new APIClient('https://api.example.com');\n\n  client.get('/users')\n    .then(users => console.log('Users:', users))\n    .catch(error => console.error('Failed to fetch users:', error));\n\\end{mintedbox}\n\n\\section{Rust Example}\n\n\\begin{minted}[\n  bgcolor=codegray,\n  fontsize=\\footnotesize,\n  linenos,\n  breaklines,\n  frame=single,\n  framerule=0.5pt,\n  framesep=3mm\n]{rust}\nuse std::collections::HashMap;\nuse std::fs::File;\nuse std::io::{BufRead, BufReader, Result};\n\n#[derive(Debug, Clone)]\npub struct WordCounter {\n    counts: HashMap<String, usize>,\n    total_words: usize,\n}\n\nimpl WordCounter {\n    pub fn new() -> Self {\n        Self {\n            counts: HashMap::new(),\n            total_words: 0,\n        }\n    }\n\n    pub fn add_word(&mut self, word: &str) {\n        let normalized = word.to_lowercase();\n        *self.counts.entry(normalized).or_insert(0) += 1;\n        self.total_words += 1;\n    }\n\n    pub fn count_from_file(&mut self, filename: &str) -> Result<()> {\n        let file = File::open(filename)?;\n        let reader = BufReader::new(file);\n\n        for line in reader.lines() {\n            let line = line?;\n            for word in line.split_whitespace() {\n                // Remove punctuation\n                let clean_word: String = word\n                    .chars()\n                    .filter(|c| c.is_alphabetic())\n                    .collect();\n\n                if !clean_word.is_empty() {\n                    self.add_word(&clean_word);\n                }\n            }\n        }\n\n        Ok(())\n    }\n\n    pub fn most_frequent(&self, n: usize) -> Vec<(&String, &usize)> {\n        let mut pairs: Vec<_> = self.counts.iter().collect();\n        pairs.sort_by(|a, b| b.1.cmp(a.1));\n        pairs.into_iter().take(n).collect()\n    }\n}\n\\end{minted}\n\n\\end{document}"} />

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

### Highlighting Specific Lines

<LatexSource filename="minted-highlighting.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\\usepackage{xcolor}\n\n% Define highlight colors\n\\definecolor{highlightgray}{rgb}{0.9,0.9,0.9}\n\\definecolor{highlightyellow}{rgb}{1.0,1.0,0.8}\n\n\\begin{document}\n\n\\section{Line Highlighting Examples}\n\n\\subsection{Highlighting Specific Lines}\n\\begin{minted}[\n  linenos,\n  highlightlines={3,7-9},\n  highlightcolor=highlightyellow\n]{python}\ndef binary_search(arr, target):\n    left, right = 0, len(arr) - 1\n\n    while left <= right:  # Main loop condition\n        mid = (left + right) // 2\n\n        if arr[mid] == target:    # Found target\n            return mid            # Return index\n        elif arr[mid] < target:   # Target in right half\n            left = mid + 1\n        else:                     # Target in left half\n            right = mid - 1\n\n    return -1  # Target not found\n\\end{minted}\n\n\\subsection{Multiple Highlight Ranges}\n\\begin{minted}[\n  linenos,\n  highlightlines={1-2,8-10},\n  highlightcolor=highlightgray\n]{cpp}\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nint main() {\n    std::vector<int> numbers = {64, 34, 25, 12, 22, 11, 90};\n\n    std::cout << \"Original array: \";\n    for (int num : numbers) {\n        std::cout << num << \" \";\n    }\n    std::cout << std::endl;\n\n    std::sort(numbers.begin(), numbers.end());\n\n    std::cout << \"Sorted array: \";\n    for (int num : numbers) {\n        std::cout << num << \" \";\n    }\n    std::cout << std::endl;\n\n    return 0;\n}\n\\end{minted}\n\n\\end{document}"} />

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

## Code Listings in Floats

### Floating Code Listings

<LatexSource filename="code-floats.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\\usepackage{caption}\n\\usepackage{float}\n\n% Define new float type for code\n\\newfloat{listing}{tbp}{lol}\n\\floatname{listing}{Listing}\n\n% Caption setup for listings\n\\captionsetup[listing]{position=below}\n\n\\begin{document}\n\n\\section{Algorithm Examples}\n\nListing~\\ref{lst:quicksort} shows an implementation of the quicksort algorithm.\n\n\\begin{listing}[H]\n\\begin{minted}[\n  fontsize=\\footnotesize,\n  linenos,\n  frame=single,\n  framesep=2mm\n]{python}\ndef quicksort(arr):\n    \"\"\"\n    Sorts an array using the quicksort algorithm.\n\n    Args:\n        arr: List of comparable elements\n\n    Returns:\n        Sorted list\n    \"\"\"\n    if len(arr) <= 1:\n        return arr\n\n    pivot = arr[len(arr) // 2]\n    left = [x for x in arr if x < pivot]\n    middle = [x for x in arr if x == pivot]\n    right = [x for x in arr if x > pivot]\n\n    return quicksort(left) + middle + quicksort(right)\n\n# Example usage\nif __name__ == \"__main__\":\n    test_array = [3, 6, 8, 10, 1, 2, 1]\n    print(f\"Original: {test_array}\")\n    print(f\"Sorted: {quicksort(test_array)}\")\n\\end{minted}\n\\caption{Quicksort algorithm implementation in Python}\n\\label{lst:quicksort}\n\\end{listing}\n\nThe algorithm shown in Listing~\\ref{lst:quicksort} has an average time complexity of O(n log n).\n\n\\begin{listing}[t]\n\\begin{minted}[\n  fontsize=\\small,\n  linenos,\n  frame=leftline,\n  framerule=2pt,\n  rulecolor=blue\n]{java}\npublic class BinaryTree<T extends Comparable<T>> {\n    private Node<T> root;\n\n    private static class Node<T> {\n        T data;\n        Node<T> left, right;\n\n        Node(T data) {\n            this.data = data;\n            this.left = this.right = null;\n        }\n    }\n\n    public void insert(T data) {\n        root = insertRec(root, data);\n    }\n\n    private Node<T> insertRec(Node<T> root, T data) {\n        if (root == null) {\n            root = new Node<>(data);\n            return root;\n        }\n\n        if (data.compareTo(root.data) < 0) {\n            root.left = insertRec(root.left, data);\n        } else if (data.compareTo(root.data) > 0) {\n            root.right = insertRec(root.right, data);\n        }\n\n        return root;\n    }\n\n    public boolean search(T data) {\n        return searchRec(root, data);\n    }\n\n    private boolean searchRec(Node<T> root, T data) {\n        if (root == null) {\n            return false;\n        }\n\n        if (data.compareTo(root.data) == 0) {\n            return true;\n        }\n\n        return data.compareTo(root.data) < 0\n            ? searchRec(root.left, data)\n            : searchRec(root.right, data);\n    }\n}\n\\end{minted}\n\\caption{Generic binary search tree implementation in Java}\n\\label{lst:bst}\n\\end{listing}\n\n\\end{document}"} />

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

### Code Listings with Subfigures

<LatexSource filename="code-subfigures.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\\usepackage{subcaption}\n\\usepackage{caption}\n\n\\begin{document}\n\n\\section{Algorithm Comparison}\n\nFigure~\\ref{fig:sorting-algorithms} compares different sorting algorithm implementations.\n\n\\begin{figure}[htbp]\n\\centering\n\n\\begin{subfigure}[t]{0.45\\textwidth}\n\\begin{minted}[\n  fontsize=\\tiny,\n  linenos,\n  frame=single,\n  framesep=1mm\n]{python}\ndef bubble_sort(arr):\n    \"\"\"Bubble sort - O(n²)\"\"\"\n    n = len(arr)\n    for i in range(n):\n        for j in range(0, n - i - 1):\n            if arr[j] > arr[j + 1]:\n                arr[j], arr[j + 1] = arr[j + 1], arr[j]\n    return arr\n\n# Example\nnumbers = [64, 34, 25, 12, 22, 11, 90]\nprint(\"Bubble sort:\", bubble_sort(numbers.copy()))\n\\end{minted}\n\\caption{Bubble sort algorithm}\n\\label{fig:bubble-sort}\n\\end{subfigure}\n\\hfill\n\\begin{subfigure}[t]{0.45\\textwidth}\n\\begin{minted}[\n  fontsize=\\tiny,\n  linenos,\n  frame=single,\n  framesep=1mm\n]{python}\ndef merge_sort(arr):\n    \"\"\"Merge sort - O(n log n)\"\"\"\n    if len(arr) <= 1:\n        return arr\n\n    mid = len(arr) // 2\n    left = merge_sort(arr[:mid])\n    right = merge_sort(arr[mid:])\n\n    return merge(left, right)\n\ndef merge(left, right):\n    result = []\n    i = j = 0\n\n    while i < len(left) and j < len(right):\n        if left[i] <= right[j]:\n            result.append(left[i])\n            i += 1\n        else:\n            result.append(right[j])\n            j += 1\n\n    result.extend(left[i:])\n    result.extend(right[j:])\n    return result\n\n# Example\nnumbers = [64, 34, 25, 12, 22, 11, 90]\nprint(\"Merge sort:\", merge_sort(numbers.copy()))\n\\end{minted}\n\\caption{Merge sort algorithm}\n\\label{fig:merge-sort}\n\\end{subfigure}\n\n\\caption{Comparison of sorting algorithms with different time complexities}\n\\label{fig:sorting-algorithms}\n\\end{figure}\n\n\\end{document}"} />

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

## Inline Code and Escaping

### Inline Code with Special Characters

<LatexSource filename="inline-code.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\\usepackage{listings}\n\n% Configure listings for inline code\n\\lstset{\n  basicstyle=\\ttfamily,\n  breaklines=true\n}\n\n\\begin{document}\n\n\\section{Inline Code Examples}\n\n% Simple inline code\nThe \\lstinline|print()| function outputs text to the console.\n\n% Inline code with special characters\nUse \\lstinline|arr[i] = arr[j]| to swap array elements.\n\n% Different delimiters for special characters\nThe regular expression \\lstinline/[a-zA-Z0-9]+/ matches alphanumeric strings.\n\n% Minted inline code\nThe \\mintinline{python}|lambda x: x**2| function squares its input.\n\n% Inline code with highlighting\nThe key function is \\mintinline[bgcolor=yellow!30]{python}|process_data()|.\n\n\\section{Code with LaTeX Escapes}\n\n\\begin{lstlisting}[language=Python, escapeinside={(*@}{@*)}]\ndef calculate_(*@\\textbf{mean}@*)(values):\n    \"\"\"Calculate the arithmetic (*@\\emph{mean}@*) of a list.\"\"\"\n    if not values:\n        return 0\n    return sum(values) / len(values)  # (*@$\\frac{\\sum x_i}{n}$@*)\n\n# Example: (*@\\textcolor{red}{Important note}@*)\nresult = calculate_mean([1, 2, 3, 4, 5])\nprint(f\"Mean: {result}\")  # Output: (*@\\texttt{Mean: 3.0}@*)\n\\end{lstlisting}\n\n\\end{document}"} />

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

## Performance and Customization

### Custom Color Schemes

<LatexSource filename="custom-colors.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\\usepackage{xcolor}\n\n% Define custom color scheme\n\\definecolor{darkblue}{rgb}{0.0,0.2,0.4}\n\\definecolor{darkgreen}{rgb}{0.0,0.4,0.2}\n\\definecolor{darkred}{rgb}{0.4,0.0,0.2}\n\\definecolor{darkorange}{rgb}{0.8,0.4,0.0}\n\\definecolor{codebg}{rgb}{0.98,0.98,0.98}\n\n% Custom minted style\n\\newminted{python}{\n  bgcolor=codebg,\n  fontsize=\\footnotesize,\n  linenos,\n  numbersep=8pt,\n  frame=leftline,\n  framerule=2pt,\n  rulecolor=darkblue,\n  breaklines,\n  breaksymbolleft=\\raisebox{0.8ex}{\\small\\reflectbox{\\carriagereturn}},\n  breaksymbolindentleft=0pt,\n  breaksymbolsepleft=0pt,\n  breaksymbolright=\\small\\carriagereturn,\n  breaksymbolindentright=0pt,\n  breaksymbolsepright=0pt\n}\n\n% Custom environment\n\\newenvironment{darkcode}\n{%\n  \\begin{tcolorbox}[\n    colback=black!95,\n    coltext=white,\n    colframe=gray!50,\n    arc=2mm,\n    boxrule=0.5pt\n  ]\n  \\begin{minted}[\n    bgcolor={},\n    fontsize=\\small,\n    style=monokai\n  ]{python}\n}{%\n  \\end{minted}\n  \\end{tcolorbox}\n}\n\n\\begin{document}\n\n\\section{Custom Styled Code}\n\n\\begin{pythoncode}\nimport asyncio\nimport aiohttp\nfrom typing import List, Dict, Optional\n\nclass AsyncWebScraper:\n    def __init__(self, max_concurrent: int = 10):\n        self.max_concurrent = max_concurrent\n        self.session: Optional[aiohttp.ClientSession] = None\n\n    async def __aenter__(self):\n        connector = aiohttp.TCPConnector(limit=self.max_concurrent)\n        self.session = aiohttp.ClientSession(connector=connector)\n        return self\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        if self.session:\n            await self.session.close()\n\n    async def fetch_url(self, url: str) -> Dict[str, str]:\n        \"\"\"Fetch content from a single URL.\"\"\"\n        try:\n            async with self.session.get(url) as response:\n                content = await response.text()\n                return {\n                    'url': url,\n                    'status': response.status,\n                    'content': content[:1000],  # First 1000 chars\n                    'headers': dict(response.headers)\n                }\n        except Exception as e:\n            return {\n                'url': url,\n                'error': str(e),\n                'status': None,\n                'content': None\n            }\n\n    async def scrape_urls(self, urls: List[str]) -> List[Dict[str, str]]:\n        \"\"\"Scrape multiple URLs concurrently.\"\"\"\n        tasks = [self.fetch_url(https://mintlify.s3.us-west-1.amazonaws.com/hirox-6fc9e3ca/learn/latex/formatting/url) for url in urls]\n        results = await asyncio.gather(*tasks, return_exceptions=True)\n        return [r for r in results if not isinstance(r, Exception)]\n\n# Usage example\nasync def main():\n    urls = [\n        'https://httpbin.org/json',\n        'https://httpbin.org/xml',\n        'https://httpbin.org/html'\n    ]\n\n    async with AsyncWebScraper(max_concurrent=5) as scraper:\n        results = await scraper.scrape_urls(urls)\n\n    for result in results:\n        print(f\"URL: {result['url']}\")\n        print(f\"Status: {result.get('status', 'Error')}\")\n        print(\"-\" * 50)\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n\\end{pythoncode}\n\n\\end{document}"} />

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

### Code Import from Files

<LatexSource filename="code-import.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\n\\begin{document}\n\n\\section{Importing Code from Files}\n\n% Import entire file\n\\inputminted{python}{example_script.py}\n\n% Import specific lines from file\n\\inputminted[firstline=10,lastline=25]{python}{large_script.py}\n\n% Import with custom styling\n\\inputminted[\n  fontsize=\\footnotesize,\n  linenos,\n  numbersep=5pt,\n  frame=lines,\n  framesep=2mm,\n  bgcolor=gray!10\n]{python}{algorithm.py}\n\n\\section{Code Snippets}\n\n% You can also use external command to include processed code\n\\immediate\\write18{pygmentize -l python -f latex example.py > example_highlighted.tex}\n\\input{example_highlighted.tex}\n\n\\end{document}"} />

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

## Best Practices

<Tip>
  **Code formatting guidelines:**

  1. **Choose appropriate package** - Use `listings` for simple formatting, `minted` for syntax highlighting
  2. **Consistent styling** - Define styles once and reuse throughout document
  3. **Font size** - Use `\footnotesize` or `\small` for better readability
  4. **Line numbers** - Include for longer code blocks, omit for short snippets
  5. **Break long lines** - Enable `breaklines` for better page layout
  6. **Escape special characters** - Use proper delimiters for inline code
</Tip>

### Production-Ready Setup

<LatexSource filename="production-code.tex" source={"\\documentclass{article}\n\\usepackage{minted}\n\\usepackage{tcolorbox}\n\\usepackage{caption}\n\n% Global minted configuration\n\\setminted{\n  fontsize=\\footnotesize,\n  linenos=true,\n  numbersep=8pt,\n  frame=leftline,\n  framerule=1pt,\n  breaklines=true,\n  breaksymbolleft=\\raisebox{0.8ex}{\\small\\reflectbox{\\carriagereturn}},\n  autogobble=true\n}\n\n% Professional code environment\n\\newtcolorbox{codebox}[2][]{\n  colback=blue!5!white,\n  colframe=blue!50!black,\n  title=#2,\n  fonttitle=\\bfseries,\n  #1\n}\n\n% Language-specific environments\n\\newenvironment{pythoncode}[1][]\n{%\n  \\begin{codebox}[#1]{Python Code}\n  \\begin{minted}{python}\n}{%\n  \\end{minted}\n  \\end{codebox}\n}\n\n\\newenvironment{javacode}[1][]\n{%\n  \\begin{codebox}[colback=orange!5!white,colframe=orange!50!black,#1]{Java Code}\n  \\begin{minted}{java}\n}{%\n  \\end{minted}\n  \\end{codebox}\n}\n\n\\begin{document}\n\n\\section{Professional Code Presentation}\n\n\\begin{pythoncode}[title=Data Analysis Pipeline]\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix\n\nclass DataAnalysisPipeline:\n    \"\"\"A complete data analysis pipeline for machine learning.\"\"\"\n\n    def __init__(self, random_state=42):\n        self.random_state = random_state\n        self.scaler = StandardScaler()\n        self.model = RandomForestClassifier(\n            n_estimators=100,\n            random_state=self.random_state\n        )\n        self.is_fitted = False\n\n    def preprocess_data(self, X, y=None, fit_transform=True):\n        \"\"\"Preprocess the input data.\"\"\"\n        if fit_transform:\n            X_scaled = self.scaler.fit_transform(X)\n        else:\n            X_scaled = self.scaler.transform(X)\n\n        return X_scaled\n\n    def train(self, X, y, test_size=0.2):\n        \"\"\"Train the model with the provided data.\"\"\"\n        # Split the data\n        X_train, X_test, y_train, y_test = train_test_split(\n            X, y, test_size=test_size, random_state=self.random_state\n        )\n\n        # Preprocess\n        X_train_scaled = self.preprocess_data(X_train, fit_transform=True)\n        X_test_scaled = self.preprocess_data(X_test, fit_transform=False)\n\n        # Train model\n        self.model.fit(X_train_scaled, y_train)\n        self.is_fitted = True\n\n        # Evaluate\n        train_score = self.model.score(X_train_scaled, y_train)\n        test_score = self.model.score(X_test_scaled, y_test)\n\n        return {\n            'train_score': train_score,\n            'test_score': test_score,\n            'X_test': X_test_scaled,\n            'y_test': y_test\n        }\n\n    def predict(self, X):\n        \"\"\"Make predictions on new data.\"\"\"\n        if not self.is_fitted:\n            raise ValueError(\"Model must be trained before making predictions\")\n\n        X_scaled = self.preprocess_data(X, fit_transform=False)\n        return self.model.predict(X_scaled)\n\n    def feature_importance(self):\n        \"\"\"Get feature importance scores.\"\"\"\n        if not self.is_fitted:\n            raise ValueError(\"Model must be trained first\")\n\n        return self.model.feature_importances_\n\n# Example usage\nif __name__ == \"__main__\":\n    # Load your dataset here\n    # X, y = load_your_data()\n\n    pipeline = DataAnalysisPipeline()\n    results = pipeline.train(X, y)\n\n    print(f\"Training accuracy: {results['train_score']:.3f}\")\n    print(f\"Testing accuracy: {results['test_score']:.3f}\")\n\\end{pythoncode}\n\n\\end{document}"} />

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

## Troubleshooting & FAQ

<Accordion title="minted says latexminted is unavailable or not permitted">
  First confirm that `minted` v3 and `latexminted` are installed and available on `PATH`. TeX Live 2024+ normally permits `latexminted` through restricted shell escape. Older TeX Live or MiKTeX may require an explicit trusted-command configuration or, for trusted documents only, full shell escape. If you cannot change the environment, use `listings` or a complete frozen cache.
</Accordion>

<Accordion title="Do I need Python, Pygments, and latexminted installed?">
  `minted` v3 performs highlighting through `latexminted`, which uses Pygments. A current TeX package manager may install these components together; otherwise install `latexminted` and its dependencies in the Python environment used by the compiler. A document with a complete frozen cache no longer needs Python or Pygments during the final build.
</Accordion>

<Accordion title="minted vs listings – which should I use?">
  Use `listings` for lightweight, dependency-free code blocks; choose `minted` for high-quality syntax highlighting and extensive styling. For journal-ready output, minted is usually preferred.
</Accordion>

<Accordion title="How do I avoid shell-escape for strict environments?">
  Use current `minted` v3 on TeX Live 2024+ through its trusted restricted executable, use a verified frozen cache, or choose `listings`. If a journal or CI service forbids external execution and cached artifacts, `listings` is the portable choice.
</Accordion>

<Accordion title="Colored backgrounds and line highlighting don’t appear">
  Ensure your document isn’t forcing monochrome (e.g., via print mode) and that options like `bgcolor`, `highlightlines`, and `frame` are set on the environment or via `\setminted{...}`.
</Accordion>

## Quick Reference

### Essential Commands

| Package  | Command              | Purpose              | Example                             |      |    |
| -------- | -------------------- | -------------------- | ----------------------------------- | ---- | -- |
| listings | `\lstset{}`          | Global configuration | `\lstset{language=Python}`          |      |    |
| listings | `\begin{lstlisting}` | Code block           | `\begin{lstlisting}[language=Java]` |      |    |
| listings | `\lstinline`         | Inline code          | \`\lstinline                        | code | \` |
| minted   | `\setminted{}`       | Global configuration | `\setminted{fontsize=\small}`       |      |    |
| minted   | `\begin{minted}`     | Code block           | `\begin{minted}{python}`            |      |    |
| minted   | `\mintinline`        | Inline code          | \`\mintinline{python}               | code | \` |

### Common Options

| Option       | Effect                   | Example                  |
| ------------ | ------------------------ | ------------------------ |
| `language`   | Set programming language | `language=Python`        |
| `linenos`    | Show line numbers        | `linenos=true`           |
| `fontsize`   | Set font size            | `fontsize=\footnotesize` |
| `breaklines` | Allow line breaking      | `breaklines=true`        |
| `frame`      | Add frame around code    | `frame=single`           |
| `bgcolor`    | Background color         | `bgcolor=gray!10`        |

### Supported Languages

Both packages support many languages including:

* Python, Java, C++, C, JavaScript, TypeScript
* HTML, CSS, SQL, LaTeX, Bash, PowerShell
* Go, Rust, Swift, Kotlin, Scala, Haskell
* MATLAB, R, Julia, Perl, Ruby, PHP

***

<Info>
  **Next**: Learn about [Headers and footers](/learn/latex/formatting/headers-footers) for page decoration and numbering, or explore [Multiple columns](/learn/latex/formatting/multiple-columns) for layout.
</Info>
