> ## 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 Counters and Numbering

> Complete guide to LaTeX counters and custom numbering systems. Learn to create, modify, and customize automatic numbering for any document element.

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

LaTeX counters control all automatic numbering in your document. This guide covers how to create custom counters, modify existing ones, and implement sophisticated numbering schemes for any document element.

<Info>
  **Key concept**: LaTeX uses counters to track numbers for sections, figures, tables, equations, and more. Understanding counters lets you create custom numbering schemes and control how elements are numbered throughout your document.

  **Related topics**: [Page numbering](/learn/latex/formatting/page-numbering) | [Cross-referencing](/learn/latex/cross-referencing) | [Document structure](/components/document-structure)
</Info>

## Understanding LaTeX Counters

### Built-in Counters

LaTeX provides many predefined counters:

| Counter      | Purpose            | Example               |
| ------------ | ------------------ | --------------------- |
| `page`       | Page numbers       | 1, 2, 3...            |
| `chapter`    | Chapter numbers    | 1, 2, 3...            |
| `section`    | Section numbers    | 1.1, 1.2, 2.1...      |
| `subsection` | Subsection numbers | 1.1.1, 1.1.2...       |
| `figure`     | Figure numbers     | Figure 1, Figure 2... |
| `table`      | Table numbers      | Table 1, Table 2...   |
| `equation`   | Equation numbers   | (1), (2), (3)...      |
| `footnote`   | Footnote numbers   | ¹, ², ³...            |

<LatexSource filename="viewing-counters.tex" source={"\\documentclass{article}\n\\begin{document}\n\n% Display current counter values\nCurrent page: \\thepage\n\nCurrent section: \\thesection\n\nCurrent figure: \\thefigure\n\nCurrent table: \\thetable\n\n% Show counter values in different formats\nPage (arabic): \\arabic{page}\n\nSection (roman): \\roman{section}\n\nChapter (Roman): \\Roman{chapter}\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>

### Counter Operations

<LatexSource filename="counter-operations.tex" source={"\\documentclass{article}\n\\begin{document}\n\n% View current value\nCurrent page counter: \\thepage\n\n% Set counter to specific value\n\\setcounter{page}{5}\nNew page value: \\thepage\n\n% Add to counter\n\\addtocounter{page}{3}\nAfter adding 3: \\thepage\n\n% Step counter (increment by 1)\n\\stepcounter{page}\nAfter stepping: \\thepage\n\n% Reset counter to zero\n\\setcounter{page}{0}\nAfter reset: \\thepage\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_counters_numbering">
  <LatexPreview src="/images/rendered/learn-latex-formatting-counters-numbering-02/page-1.svg" alt="Compiled PDF page 1 from counter-operations.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Creating Custom Counters

### Basic Counter Creation

<LatexSource filename="custom-counters.tex" source={"\\documentclass{article}\n\n% Create new counters\n\\newcounter{example}\n\\newcounter{problem}\n\\newcounter{solution}\n\n% Create counter that resets with another\n\\newcounter{subproblem}[problem]\n\n\\begin{document}\n\n% Use custom counters\n\\stepcounter{example}\nExample \\theexample: This is the first example.\n\n\\stepcounter{example}\nExample \\theexample: This is the second example.\n\n\\stepcounter{problem}\nProblem \\theproblem: Solve this equation.\n\n\\stepcounter{subproblem}\nSubproblem \\theproblem.\\thesubproblem: First part.\n\n\\stepcounter{subproblem}\nSubproblem \\theproblem.\\thesubproblem: Second part.\n\n\\stepcounter{problem}\nProblem \\theproblem: New problem resets subproblem.\n\n\\stepcounter{subproblem}\nSubproblem \\theproblem.\\thesubproblem: Starts at 1 again.\n\n\\end{document}"} />

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

### Counter Display Formats

<LatexSource filename="counter-formats.tex" source={"\\documentclass{article}\n\n\\newcounter{demo}\n\n% Redefine how counter is displayed\n\\renewcommand{\\thedemo}{\\Roman{demo}}\n\n\\begin{document}\n\n% Default arabic format\n\\stepcounter{demo}\nDemo \\thedemo\n\n% Change to alphabetic\n\\renewcommand{\\thedemo}{\\Alph{demo}}\n\\stepcounter{demo}\nDemo \\thedemo\n\n% Change to roman numerals\n\\renewcommand{\\thedemo}{\\roman{demo}}\n\\stepcounter{demo}\nDemo \\thedemo\n\n% Custom format with prefix/suffix\n\\renewcommand{\\thedemo}{Example-\\arabic{demo}}\n\\stepcounter{demo}\nDemo \\thedemo\n\n% Complex format combining counters\n\\newcounter{chapter}\n\\newcounter{section}[chapter]\n\\renewcommand{\\thesection}{\\thechapter.\\arabic{section}}\n\n\\setcounter{chapter}{3}\n\\stepcounter{section}\nSection \\thesection\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>

## Advanced Counter Techniques

### Conditional Counter Reset

<LatexSource filename="conditional-reset.tex" source={"\\documentclass{article}\n\\usepackage{ifthen}\n\n\\newcounter{task}\n\\newcounter{step}\n\n% Custom reset behavior\n\\newcommand{\\newtask}{%\n  \\stepcounter{task}%\n  \\setcounter{step}{0}%\n  \\textbf{Task \\thetask:}%\n}\n\n\\newcommand{\\newstep}{%\n  \\stepcounter{step}%\n  \\ifthenelse{\\value{step}=1}%\n    {Step \\thestep:}%\n    {Step \\thestep:}%\n}\n\n\\begin{document}\n\n\\newtask\n\\newstep First step of first task.\n\\newstep Second step of first task.\n\n\\newtask\n\\newstep First step of second task.\n\\newstep Second step of second task.\n\\newstep Third step of second task.\n\n\\end{document}"} />

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

### Counter Dependencies

<LatexSource filename="counter-dependencies.tex" source={"\\documentclass{book}\n\n% Create hierarchical counters\n\\newcounter{exercise}[chapter]\n\\newcounter{question}[exercise]\n\\newcounter{part}[question]\n\n% Define display formats\n\\renewcommand{\\theexercise}{\\thechapter.\\arabic{exercise}}\n\\renewcommand{\\thequestion}{\\theexercise.\\arabic{question}}\n\\renewcommand{\\thepart}{\\thequestion(\\alph{part})}\n\n% Commands for easy use\n\\newcommand{\\exercise}{%\n  \\stepcounter{exercise}%\n  \\setcounter{question}{0}%\n  \\textbf{Exercise \\theexercise}%\n}\n\n\\newcommand{\\question}{%\n  \\stepcounter{question}%\n  \\setcounter{part}{0}%\n  \\par\\textbf{Question \\thequestion:}%\n}\n\n\\newcommand{\\part}{%\n  \\stepcounter{part}%\n  \\par(\\thepart)%\n}\n\n\\begin{document}\n\n\\chapter{Linear Algebra}\n\n\\exercise\n\\question What is a vector?\n\\part Define vector space.\n\\part Give three examples.\n\n\\question How do you add vectors?\n\\part Component-wise addition.\n\\part Geometric interpretation.\n\n\\exercise\n\\question What is a matrix?\n\n\\chapter{Calculus}\n\n\\exercise\n\\question What is a derivative?\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>

## Custom Numbering Environments

### Creating Numbered Environments

<LatexSource filename="numbered-environments.tex" source={"\\documentclass{article}\n\n% Create counter for custom environment\n\\newcounter{theorem}[section]\n\\newcounter{lemma}[section]\n\\newcounter{corollary}[section]\n\n% Define display format\n\\renewcommand{\\thetheorem}{\\thesection.\\arabic{theorem}}\n\\renewcommand{\\thelemma}{\\thesection.\\arabic{lemma}}\n\\renewcommand{\\thecorollary}{\\thesection.\\arabic{corollary}}\n\n% Create environments\n\\newenvironment{theorem}[1][]\n{%\n  \\stepcounter{theorem}%\n  \\textbf{Theorem \\thetheorem}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{.} \\itshape%\n}\n{%\n  \\par\\medskip%\n}\n\n\\newenvironment{lemma}[1][]\n{%\n  \\stepcounter{lemma}%\n  \\textbf{Lemma \\thelemma}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{.} \\itshape%\n}\n{%\n  \\par\\medskip%\n}\n\n\\begin{document}\n\n\\section{Basic Theory}\n\n\\begin{theorem}[Fundamental Theorem]\nThis is an important theorem in the first section.\n\\end{theorem}\n\n\\begin{lemma}\nA supporting lemma for the theorem.\n\\end{lemma}\n\n\\begin{theorem}\nAnother theorem in the same section.\n\\end{theorem}\n\n\\section{Advanced Topics}\n\n\\begin{theorem}\nNew section resets the counter.\n\\end{theorem}\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>

### Shared Counter Systems

<LatexSource filename="shared-counters.tex" source={"\\documentclass{article}\n\n% Create shared counter for all theorem-like environments\n\\newcounter{theorem}[section]\n\n% All environments share the same counter\n\\newenvironment{theorem}[1][]\n{%\n  \\stepcounter{theorem}%\n  \\textbf{Theorem \\thesection.\\arabic{theorem}}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{.} \\itshape%\n}{\\par\\medskip}\n\n\\newenvironment{lemma}[1][]\n{%\n  \\stepcounter{theorem}%\n  \\textbf{Lemma \\thesection.\\arabic{theorem}}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{.} \\itshape%\n}{\\par\\medskip}\n\n\\newenvironment{corollary}[1][]\n{%\n  \\stepcounter{theorem}%\n  \\textbf{Corollary \\thesection.\\arabic{theorem}}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{.} \\itshape%\n}{\\par\\medskip}\n\n\\begin{document}\n\n\\section{Mathematical Results}\n\n\\begin{theorem}\nFirst result.\n\\end{theorem}\n\n\\begin{lemma}\nSupporting lemma numbered consecutively.\n\\end{lemma}\n\n\\begin{corollary}\nFollows from the theorem.\n\\end{corollary}\n\n\\begin{theorem}\nFourth result in the sequence.\n\\end{theorem}\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>

## List Numbering Customization

### Custom List Counters

<LatexSource filename="custom-list-numbering.tex" source={"\\documentclass{article}\n\\usepackage{enumitem}\n\n% Create custom counter for special lists\n\\newcounter{priority}\n\\renewcommand{\\thepriority}{P-\\arabic{priority}}\n\n% Define custom list\n\\newlist{prioritylist}{enumerate}{1}\n\\setlist[prioritylist]{%\n  label=\\stepcounter{priority}\\thepriority:,\n  ref=\\thepriority\n}\n\n\\begin{document}\n\n\\section{Project Tasks}\n\n\\begin{prioritylist}\n\\item High importance task\n\\item Medium importance task\n\\item Low importance task\n\\end{prioritylist}\n\n\\section{Requirements}\n\n\\begin{prioritylist}[resume]\n\\item Continue numbering from previous list\n\\item Another requirement\n\\end{prioritylist}\n\n% Reset counter for new project\n\\setcounter{priority}{0}\n\n\\section{New Project}\n\n\\begin{prioritylist}\n\\item First task of new project\n\\item Second task of new project\n\\end{prioritylist}\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>

### Multi-Level Custom Numbering

<LatexSource filename="multilevel-numbering.tex" source={"\\documentclass{article}\n\\usepackage{enumitem}\n\n% Create counters for hierarchical numbering\n\\newcounter{requirement}\n\\newcounter{subrequirement}[requirement]\n\\newcounter{detail}[subrequirement]\n\n% Define display formats\n\\renewcommand{\\therequirement}{R\\arabic{requirement}}\n\\renewcommand{\\thesubrequirement}{\\therequirement.\\arabic{subrequirement}}\n\\renewcommand{\\thedetail}{\\thesubrequirement.\\alph{detail}}\n\n% Custom environments\n\\newenvironment{requirements}\n{\\begin{enumerate}[label=\\stepcounter{requirement}\\therequirement:]}\n{\\end{enumerate}}\n\n\\newenvironment{subrequirements}\n{\\begin{enumerate}[label=\\stepcounter{subrequirement}\\thesubrequirement:]}\n{\\end{enumerate}}\n\n\\newenvironment{details}\n{\\begin{enumerate}[label=\\stepcounter{detail}\\thedetail)]}\n{\\end{enumerate}}\n\n\\begin{document}\n\n\\section{System Requirements}\n\n\\begin{requirements}\n\\item User Authentication\n  \\begin{subrequirements}\n  \\item Login functionality\n    \\begin{details}\n    \\item Username validation\n    \\item Password encryption\n    \\item Session management\n    \\end{details}\n  \\item Registration process\n    \\begin{details}\n    \\item Email verification\n    \\item Data validation\n    \\end{details}\n  \\end{subrequirements}\n\n\\item Data Management\n  \\begin{subrequirements}\n  \\item Database design\n  \\item Backup procedures\n  \\end{subrequirements}\n\\end{requirements}\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>

## Cross-Counter References

### Referencing Custom Counters

<LatexSource filename="counter-references.tex" source={"\\documentclass{article}\n\n\\newcounter{definition}[section]\n\\renewcommand{\\thedefinition}{\\thesection.\\arabic{definition}}\n\n\\newenvironment{definition}[1][]\n{%\n  \\stepcounter{definition}%\n  \\textbf{Definition \\thedefinition}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{.} \\itshape%\n}\n{\\par\\medskip}\n\n\\begin{document}\n\n\\section{Basic Concepts}\n\n\\begin{definition}[Vector Space]\\label{def:vector-space}\nA vector space is a collection of objects called vectors.\n\\end{definition}\n\n\\begin{definition}[Linear Independence]\\label{def:linear-independence}\nVectors are linearly independent if no vector can be written as a linear combination of the others.\n\\end{definition}\n\n\\section{Applications}\n\nIn Definition~\\ref{def:vector-space}, we established the concept of vector spaces. Building on Definition~\\ref{def:linear-independence}, we can now discuss bases.\n\nThe relationship between Definition~\\ref{def:vector-space} and Definition~\\ref{def:linear-independence} is fundamental to linear algebra.\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>

### Counter-Based Indexing

<LatexSource filename="counter-indexing.tex" source={"\\documentclass{article}\n\n% Create index counter system\n\\newcounter{item}\n\\newcounter{subitem}[item]\n\n\\renewcommand{\\theitem}{\\arabic{item}}\n\\renewcommand{\\thesubitem}{\\theitem.\\arabic{subitem}}\n\n% Commands for index entries\n\\newcommand{\\indexitem}[2]{%\n  \\stepcounter{item}%\n  \\setcounter{subitem}{0}%\n  \\textbf{\\theitem. #1} \\dotfill #2\\par%\n}\n\n\\newcommand{\\indexsubitem}[2]{%\n  \\stepcounter{subitem}%\n  \\quad\\textbf{\\thesubitem} #1 \\dotfill #2\\par%\n}\n\n\\begin{document}\n\n\\section{Index}\n\n\\indexitem{Introduction}{Page 1}\n\\indexsubitem{Overview}{Page 1}\n\\indexsubitem{Scope}{Page 2}\n\\indexsubitem{Methodology}{Page 3}\n\n\\indexitem{Theory}{Page 5}\n\\indexsubitem{Basic Concepts}{Page 5}\n\\indexsubitem{Advanced Topics}{Page 8}\n\n\\indexitem{Applications}{Page 12}\n\\indexsubitem{Example 1}{Page 12}\n\\indexsubitem{Example 2}{Page 15}\n\\indexsubitem{Case Studies}{Page 18}\n\n\\end{document}"} />

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

## Specialized Numbering Systems

### Legal Document Numbering

<LatexSource filename="legal-numbering.tex" source={"\\documentclass{article}\n\n% Legal document counter system\n\\newcounter{article}\n\\newcounter{section}[article]\n\\newcounter{subsection}[section]\n\\newcounter{paragraph}[subsection]\n\n% Custom display formats\n\\renewcommand{\\thearticle}{\\Roman{article}}\n\\renewcommand{\\thesection}{\\arabic{section}}\n\\renewcommand{\\thesubsection}{\\alph{subsection}}\n\\renewcommand{\\theparagraph}{\\roman{paragraph}}\n\n% Commands for legal structure\n\\newcommand{\\legalArticle}[1]{%\n  \\stepcounter{article}%\n  \\setcounter{section}{0}%\n  \\textbf{ARTICLE \\thearticle}\\par%\n  \\textbf{#1}\\par\\medskip%\n}\n\n\\newcommand{\\legalSection}[1]{%\n  \\stepcounter{section}%\n  \\setcounter{subsection}{0}%\n  \\textbf{Section \\thearticle.\\thesection.} #1\\par%\n}\n\n\\newcommand{\\legalSubsection}[1]{%\n  \\stepcounter{subsection}%\n  \\setcounter{paragraph}{0}%\n  \\textbf{(\\thesubsection)} #1\\par%\n}\n\n\\newcommand{\\legalParagraph}[1]{%\n  \\stepcounter{paragraph}%\n  \\textbf{(\\theparagraph)} #1\\par%\n}\n\n\\begin{document}\n\n\\legalArticle{GENERAL PROVISIONS}\n\n\\legalSection{Definitions}\n\\legalSubsection{In this document, unless the context otherwise requires:}\n\\legalParagraph{\"Company\" means the organization defined herein;}\n\\legalParagraph{\"Agreement\" refers to this contract;}\n\\legalParagraph{\"Party\" means any signatory to this agreement.}\n\n\\legalSection{Scope of Application}\n\\legalSubsection{This agreement applies to all parties involved.}\n\n\\legalArticle{TERMS AND CONDITIONS}\n\n\\legalSection{Obligations}\n\\legalSubsection{Each party shall:}\n\\legalParagraph{Fulfill their contractual obligations;}\n\\legalParagraph{Maintain confidentiality;}\n\\legalParagraph{Report any violations.}\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>

### Scientific Paper Numbering

<LatexSource filename="scientific-numbering.tex" source={"\\documentclass{article}\n\n% Scientific numbering system\n\\newcounter{hypothesis}\n\\newcounter{experiment}\n\\newcounter{observation}[experiment]\n\\newcounter{conclusion}\n\n\\renewcommand{\\thehypothesis}{H\\arabic{hypothesis}}\n\\renewcommand{\\theexperiment}{E\\arabic{experiment}}\n\\renewcommand{\\theobservation}{\\theexperiment.\\arabic{observation}}\n\\renewcommand{\\theconclusion}{C\\arabic{conclusion}}\n\n% Scientific environments\n\\newenvironment{hypothesis}[1][]\n{%\n  \\stepcounter{hypothesis}%\n  \\textbf{Hypothesis \\thehypothesis}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{:} \\itshape%\n}{\\par\\medskip}\n\n\\newenvironment{experiment}[1][]\n{%\n  \\stepcounter{experiment}%\n  \\setcounter{observation}{0}%\n  \\textbf{Experiment \\theexperiment}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{:}%\n}{\\par\\medskip}\n\n\\newenvironment{observation}[1][]\n{%\n  \\stepcounter{observation}%\n  \\textbf{Observation \\theobservation}%\n  \\ifthenelse{\\equal{#1}{}}{}{ (#1)}%\n  \\textbf{:} \\itshape%\n}{\\par\\medskip}\n\n\\begin{document}\n\n\\section{Research Methodology}\n\n\\begin{hypothesis}[Primary]\nIncreased temperature will accelerate the reaction rate.\n\\end{hypothesis}\n\n\\begin{hypothesis}[Secondary]\nPressure changes will have minimal effect on the reaction.\n\\end{hypothesis}\n\n\\begin{experiment}[Temperature Study]\nConduct reaction at various temperatures.\n\n\\begin{observation}[25°C]\nReaction completed in 60 minutes.\n\\end{observation}\n\n\\begin{observation}[50°C]\nReaction completed in 30 minutes.\n\\end{observation}\n\n\\begin{observation}[75°C]\nReaction completed in 15 minutes.\n\\end{observation}\n\\end{experiment}\n\n\\begin{experiment}[Pressure Study]\nConduct reaction at various pressures.\n\n\\begin{observation}[1 atm]\nReaction rate unchanged from baseline.\n\\end{observation}\n\n\\begin{observation}[2 atm]\nMinimal change in reaction rate.\n\\end{observation}\n\\end{experiment}\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>

## Best Practices

<Tip>
  **Counter management guidelines:**

  1. **Plan your numbering scheme** - Design consistent hierarchy before implementation
  2. **Use descriptive counter names** - `problem` is better than `prob` or `p`
  3. **Reset appropriately** - Child counters should reset when parent increments
  4. **Document your system** - Comment complex counter relationships
  5. **Test thoroughly** - Check numbering across document sections
  6. **Consider references** - Ensure counter formats work well with `\ref{}`
</Tip>

### Professional Counter Setup

<LatexSource filename="professional-counters.tex" source={"\\documentclass{report}\n\n% Professional counter hierarchy\n\\newcounter{requirement}[chapter]\n\\newcounter{subrequirement}[requirement]\n\\newcounter{specification}[chapter]\n\\newcounter{testcase}[specification]\n\n% Clear numbering formats\n\\renewcommand{\\therequirement}{\\thechapter.\\arabic{requirement}}\n\\renewcommand{\\thesubrequirement}{\\therequirement.\\arabic{subrequirement}}\n\\renewcommand{\\thespecification}{\\thechapter.\\arabic{specification}}\n\\renewcommand{\\thetestcase}{\\thespecification.\\arabic{testcase}}\n\n% Consistent formatting commands\n\\newcommand{\\Requirement}[1]{%\n  \\stepcounter{requirement}%\n  \\setcounter{subrequirement}{0}%\n  \\paragraph{Requirement \\therequirement:} #1%\n}\n\n\\newcommand{\\SubRequirement}[1]{%\n  \\stepcounter{subrequirement}%\n  \\subparagraph{Requirement \\thesubrequirement:} #1%\n}\n\n\\newcommand{\\Specification}[1]{%\n  \\stepcounter{specification}%\n  \\setcounter{testcase}{0}%\n  \\paragraph{Specification \\thespecification:} #1%\n}\n\n\\newcommand{\\TestCase}[1]{%\n  \\stepcounter{testcase}%\n  \\subparagraph{Test Case \\thetestcase:} #1%\n}\n\n\\begin{document}\n\n\\chapter{User Interface Requirements}\n\n\\Requirement{The system shall provide a user-friendly interface.}\n\\SubRequirement{All buttons shall be clearly labeled.}\n\\SubRequirement{Navigation shall be intuitive.}\n\n\\Requirement{The interface shall be responsive.}\n\\SubRequirement{Layout shall adapt to screen size.}\n\n\\Specification{Login form implementation}\n\\TestCase{Valid credentials acceptance}\n\\TestCase{Invalid credentials rejection}\n\n\\Specification{Menu navigation implementation}\n\\TestCase{Menu accessibility}\n\\TestCase{Submenu functionality}\n\n\\chapter{Performance Requirements}\n\n\\Requirement{Response times shall be minimal.}\n\\SubRequirement{Page loads under 2 seconds.}\n\\SubRequirement{Database queries under 1 second.}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-formatting-counters-numbering-15/page-1.svg" alt="Compiled PDF page 1 from professional-counters.tex" caption="Page 1 of 2. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />

  <LatexPreview src="/images/rendered/learn-latex-formatting-counters-numbering-15/page-2.svg" alt="Compiled PDF page 2 from professional-counters.tex" caption="Page 2 of 2. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Troubleshooting Counters

### Common Counter Issues

<LatexSource filename="counter-troubleshooting.tex" source={"\\documentclass{article}\n\n% Problem: Counter not resetting properly\n% Solution: Ensure proper counter dependency\n\n\\newcounter{main}\n\\newcounter{sub}[main]  % Correctly reset sub when main increments\n\n% Problem: Wrong display format\n% Solution: Check \\renewcommand{\\thecounter}\n\n\\renewcommand{\\themain}{\\arabic{main}}  % Correct format\n\\renewcommand{\\thesub}{\\themain.\\arabic{sub}}\n\n% Problem: Counter value not updating\n% Solution: Use \\stepcounter or \\addtocounter\n\n\\newcommand{\\newmain}{%\n  \\stepcounter{main}%  % Correct: increments counter\n  % \\setcounter{main}{\\value{main}+1}  % Wrong: doesn't work\n}\n\n% Problem: References showing wrong number\n% Solution: Ensure counter is stepped before labeling\n\n\\newcommand{\\labeleditem}[1]{%\n  \\stepcounter{main}%  % Step BEFORE label\n  \\label{#1}%\n  Item \\themain%\n}\n\n\\begin{document}\n\n\\newmain\nMain item \\themain\n\n\\stepcounter{sub}\nSub item \\thesub\n\n\\newmain\nNext main item (sub resets): \\themain, \\thesub\n\n\\labeleditem{item:first}\nThis can be referenced as \\ref{item:first}.\n\n\\end{document}"} />

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

## Quick Reference

### Essential Counter Commands

| Command                      | Purpose                      | Example                  |
| ---------------------------- | ---------------------------- | ------------------------ |
| `\newcounter{name}`          | Create new counter           | `\newcounter{example}`   |
| `\newcounter{name}[parent]`  | Create with reset dependency | `\newcounter{sub}[main]` |
| `\setcounter{name}{value}`   | Set counter to value         | `\setcounter{page}{1}`   |
| `\addtocounter{name}{value}` | Add to counter               | `\addtocounter{page}{5}` |
| `\stepcounter{name}`         | Increment by 1               | `\stepcounter{section}`  |
| `\value{name}`               | Get counter value            | `\value{page}`           |
| `\thename`                   | Display counter              | `\thepage`               |

### Counter Display Formats

| Format             | Command            | Output Example    |
| ------------------ | ------------------ | ----------------- |
| Arabic             | `\arabic{counter}` | 1, 2, 3, 4...     |
| Roman (lower)      | `\roman{counter}`  | i, ii, iii, iv... |
| Roman (upper)      | `\Roman{counter}`  | I, II, III, IV... |
| Alphabetic (lower) | `\alph{counter}`   | a, b, c, d...     |
| Alphabetic (upper) | `\Alph{counter}`   | A, B, C, D...     |

***

<Info>
  **Next**: Learn about [Advanced code listings and minted](/learn/latex/formatting/code-listings-minted) for displaying source code, or explore [Headers and footers](/learn/latex/formatting/headers-footers) for additional content placement.
</Info>
