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

# Managing Large Documents in LaTeX

> Master multi-file LaTeX projects. Learn document structuring, file organization, cross-referencing, and compilation strategies for books, theses, and reports.

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

Learn professional techniques for managing large LaTeX documents like books, theses, and technical reports. This guide covers file organization, modular document structure, efficient compilation, and team collaboration strategies.

<Info>
  **Prerequisites**: Basic LaTeX knowledge, understanding of document classes\
  **Time to complete**: 35-40 minutes\
  **Difficulty**: Advanced\
  **What you'll learn**: Project structure, input/include commands, subfiles, cross-referencing, and build optimization
</Info>

## Why Split Large Documents?

### Benefits of Modular Structure

<CardGroup cols={2}>
  <Card title="Faster Compilation" icon="rocket">
    Compile only changed sections during development
  </Card>

  <Card title="Better Organization" icon="folder-tree">
    Logical file structure mirrors document structure
  </Card>

  <Card title="Team Collaboration" icon="users">
    Multiple authors can work on different sections
  </Card>

  <Card title="Version Control" icon="code-branch">
    Track changes at the chapter/section level
  </Card>
</CardGroup>

### When to Split Documents

<Tip>
  **Consider splitting when**:

  * Document exceeds 50 pages
  * Multiple authors collaborate
  * Chapters have distinct topics
  * Compilation takes over 30 seconds
  * You need different formatting per section
  * Managing bibliography becomes complex
</Tip>

## Project Structure

### Standard Directory Layout

```
my-thesis/
├── main.tex                 # Master document
├── preamble/
│   ├── packages.tex        # Package imports
│   ├── settings.tex        # Document settings
│   ├── commands.tex        # Custom commands
│   └── environments.tex    # Custom environments
├── frontmatter/
│   ├── titlepage.tex       # Title page
│   ├── abstract.tex        # Abstract
│   ├── dedication.tex      # Dedication
│   └── acknowledgments.tex # Acknowledgments
├── chapters/
│   ├── introduction.tex    # Chapter 1
│   ├── literature.tex      # Chapter 2
│   ├── methodology.tex     # Chapter 3
│   ├── results.tex         # Chapter 4
│   └── conclusion.tex      # Chapter 5
├── appendices/
│   ├── appendix-a.tex      # Appendix A
│   └── appendix-b.tex      # Appendix B
├── backmatter/
│   ├── bibliography.bib    # References
│   └── index.tex           # Index entries
├── figures/                # All images
│   ├── chapter1/
│   ├── chapter2/
│   └── shared/
├── tables/                 # Complex tables
└── build/                  # Build artifacts
```

### Master Document Setup

<LatexSource filename="main.tex" source={"\\documentclass[12pt, twoside, openright]{book}\n\n% Load preamble components\n\\input{preamble/packages}\n\\input{preamble/settings}\n\\input{preamble/commands}\n\\input{preamble/environments}\n\n% Document metadata\n\\title{Your Document Title}\n\\author{Your Name}\n\\date{\\today}\n\n\\begin{document}\n\n% Front matter\n\\frontmatter\n\\input{frontmatter/titlepage}\n\\input{frontmatter/dedication}\n\\input{frontmatter/acknowledgments}\n\\input{frontmatter/abstract}\n\\tableofcontents\n\\listoffigures\n\\listoftables\n\n% Main matter\n\\mainmatter\n\\input{chapters/introduction}\n\\input{chapters/literature}\n\\input{chapters/methodology}\n\\input{chapters/results}\n\\input{chapters/conclusion}\n\n% Appendices\n\\appendix\n\\input{appendices/appendix-a}\n\\input{appendices/appendix-b}\n\n% Back matter\n\\backmatter\n\\printbibliography[heading=bibintoc]\n\\printindex\n\n\\end{document}"} />

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

<LatexSource filename="example.tex" source={"% Essential packages for large documents\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{lmodern}\n\n% Page layout\n\\usepackage[\n    top=1in,\n    bottom=1in,\n    left=1.5in,\n    right=1in,\n    headheight=14pt\n]{geometry}\n\n% Graphics and colors\n\\usepackage{graphicx}\n\\usepackage{xcolor}\n\\usepackage{tikz}\n\n% Tables and lists\n\\usepackage{booktabs}\n\\usepackage{longtable}\n\\usepackage{array}\n\\usepackage{enumitem}\n\n% Mathematics\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\n% References and links\n\\usepackage{hyperref}\n\\usepackage{cleveref}\n\\usepackage[nameinlink]{cleveref}\n\n% Bibliography\n\\usepackage[\n    backend=biber,\n    style=authoryear,\n    sorting=nyt\n]{biblatex}\n\\addbibresource{backmatter/bibliography.bib}\n\n% Index\n\\usepackage{imakeidx}\n\\makeindex[intoc]\n\n% Headers and footers\n\\usepackage{fancyhdr}\n\\usepackage{emptypage}\n\n% Code listings\n\\usepackage{listings}\n\\usepackage{minted}\n\n% Subfigures\n\\usepackage{subcaption}\n\n% Todo notes\n\\usepackage[disable]{todonotes} % Enable during writing"} />

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

## Input vs Include

### Understanding the Differences

<Tabs>
  <Tab title="\input">
    <LatexSource filename="example.tex" source={"% Direct text insertion\n\\input{filename} % No .tex extension needed\n\n% Characteristics:\n% - No page break before/after\n% - Can be nested\n% - Good for preamble files\n% - Compiles every time\n\n% Example usage:\n\\input{preamble/packages}\n\\input{chapters/section1}"} />

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

  <Tab title="\include">
    <LatexSource filename="example.tex" source={"% Chapter-level inclusion\n\\include{filename} % No .tex extension\n\n% Characteristics:\n% - Starts new page before\n% - Clears page after\n% - Cannot be nested\n% - Works with \\includeonly\n% - Creates .aux file\n\n% Example usage:\n\\include{chapters/introduction}\n\\include{chapters/methodology}"} />

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

  <Tab title="\includeonly">
    <LatexSource filename="example.tex" source={"% Selective compilation\n\\includeonly{\n    chapters/introduction,\n    chapters/results\n}\n\n% Only compiles listed files\n% Preserves numbering/references\n% Massive time savings\n% Perfect for focused editing"} />

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

### Practical Examples

<LatexSource filename="efficient-workflow.tex" source={"% During writing - compile only current chapter\n\\includeonly{chapters/methodology}\n\n\\begin{document}\n% ... front matter ...\n\n\\include{chapters/introduction}    % Skipped\n\\include{chapters/literature}      % Skipped\n\\include{chapters/methodology}     % Compiled\n\\include{chapters/results}         % Skipped\n\\include{chapters/conclusion}      % Skipped"} />

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

<LatexSource filename="nested-structure.tex" source={"% chapters/methodology.tex\n\\chapter{Methodology}\n\\label{ch:methodology}\n\n\\section{Overview}\nThis chapter describes our research methodology.\n\n% Include section files\n\\input{chapters/methodology/data-collection}\n\\input{chapters/methodology/analysis}\n\\input{chapters/methodology/validation}\n\n\\section{Summary}\nThe methodology ensures reliable results..."} />

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

## The Subfiles Package

### Independent Compilation

<LatexSource filename="main-subfiles.tex" source={"\\documentclass{book}\n\\usepackage{subfiles}\n% ... other packages ...\n\n\\begin{document}\n\n\\subfile{chapters/introduction}\n\\subfile{chapters/literature}\n\\subfile{chapters/methodology}\n\n\\end{document}"} />

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

<LatexSource filename="example.tex" source={"\\documentclass[../main.tex]{subfiles}\n\\begin{document}\n\n\\chapter{Introduction}\n\\label{ch:intro}\n\nThis thesis investigates...\n\n% Can be compiled independently!\n% Run: pdflatex introduction.tex\n\n\\section{Background}\nThe research background...\n\n\\section{Objectives}\nOur main objectives are...\n\n\\end{document}"} />

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

<LatexSource filename="standalone-chapter.tex" source={"% Alternative: standalone package\n\\documentclass{standalone}\n\\usepackage{import}\n\n% Stand-alone compilable\n\\begin{document}\n\\import{../}{preamble}\n\n\\chapter{Standalone Chapter}\nContent here...\n\n\\end{document}"} />

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

### Subfiles Best Practices

<Tip>
  **Subfiles workflow tips**:

  1. Each chapter can be compiled separately
  2. Graphics paths are relative to main file
  3. Bibliography works in both modes
  4. Perfect for author collaboration
  5. Faster development cycles
</Tip>

## Cross-referencing

### Managing References Across Files

<LatexSource filename="smart-referencing.tex" source={"% Enable smart referencing\n\\usepackage{xr} % Cross-references to external documents\n\\usepackage{xr-hyper} % With hyperref support\n\\usepackage{cleveref}\n\n% Reference another document\n\\externaldocument[ext:]{external-doc}\n\n% In chapters/introduction.tex\n\\chapter{Introduction}\n\\label{ch:intro}\n\n\\section{Motivation}\n\\label{sec:intro:motivation}\n\nAs discussed in \\cref{ch:methodology}, our approach...\n\n% In chapters/methodology.tex\n\\chapter{Methodology}\n\\label{ch:methodology}\n\nBuilding on \\cref{sec:intro:motivation}, we develop...\n\n% Cleveref automatically handles:\n% \"Chapter 3\" vs \"Section 1.2\" vs \"Figure 4.5\""} />

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

<LatexSource filename="reference-organization.tex" source={"% Systematic labeling convention\n\\label{type:chapter:section:subsection}\n\n% Examples:\n\\label{ch:intro}                    % Chapter\n\\label{sec:intro:background}        % Section\n\\label{subsec:intro:background:history} % Subsection\n\\label{fig:results:accuracy}        % Figure\n\\label{tab:data:summary}           % Table\n\\label{eq:methodology:formula}      % Equation\n\\label{alg:analysis:process}        % Algorithm\n\\label{thm:theory:main}            % Theorem\n\\label{def:terms:important}         % Definition\n\n% Easy to find and maintain\n% Avoids naming conflicts\n% Self-documenting"} />

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

<LatexSource filename="multi-file-refs.tex" source={"% Create a references file\n% refs/labels.tex\n\\newcommand{\\introduction}{\\cref{ch:intro}}\n\\newcommand{\\methodology}{\\cref{ch:methodology}}\n\\newcommand{\\maintheorem}{\\cref{thm:main}}\n\\newcommand{\\resultsfigure}{\\cref{fig:results:main}}\n\n% Use semantic references\nAs shown in \\resultsfigure, our method outperforms...\nThe proof follows from \\maintheorem...\n\n% Benefits:\n% - Central management\n% - Easy to update\n% - Semantic naming\n% - Find/replace friendly"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="reference-checking.tex" source={"% Check for undefined references\n\\usepackage{refcheck}\n\n% Shows unused labels\n\\usepackage{showlabels}\n\n% During development only:\n\\usepackage[notref,notcite]{showkeys}\n\n% Custom warning for missing refs\n\\makeatletter\n\\def\\@refundefined#1{%\n  \\textbf{[REF: #1??]}%\n  \\@latex@warning{Reference `#1' undefined}%\n}\n\\makeatother"} />

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

## Compilation Strategies

### Build Systems

<Tabs>
  <Tab title="Makefile">
    ```makefile theme={null}
    # Makefile for large LaTeX projects
    MAIN = main
    CHAPTERS = $(wildcard chapters/*.tex)
    FIGURES = $(wildcard figures/**/*.pdf)
    BIBTEX = biber

    # Default target
    all: $(MAIN).pdf

    # Main compilation
    $(MAIN).pdf: $(MAIN).tex $(CHAPTERS) $(FIGURES)
    	pdflatex $(MAIN)
    	$(BIBTEX) $(MAIN)
    	pdflatex $(MAIN)
    	pdflatex $(MAIN)

    # Quick build (no bibliography)
    quick: 
    	pdflatex $(MAIN)

    # Clean auxiliary files
    clean:
    	rm -f *.aux *.log *.out *.toc *.lof *.lot
    	rm -f *.bbl *.blg *.bcf *.run.xml
    	rm -f chapters/*.aux

    # Clean everything
    distclean: clean
    	rm -f $(MAIN).pdf

    # Watch for changes
    watch:
    	latexmk -pdf -pvc $(MAIN)

    .PHONY: all quick clean distclean watch
    ```
  </Tab>

  <Tab title="latexmk">
    ```perl theme={null}
    # .latexmkrc configuration
    $pdf_mode = 1;        # Use pdflatex
    $bibtex_use = 2;      # Use biber
    $out_dir = 'build';   # Output directory

    # Custom dependencies
    add_cus_dep('glo', 'gls', 0, 'run_makeglossaries');
    add_cus_dep('acn', 'acr', 0, 'run_makeglossaries');

    sub run_makeglossaries {
      if ( $silent ) {
        system "makeglossaries -q '$_[0]'";
      } else {
        system "makeglossaries '$_[0]'";
      };
    }

    # Continuous preview
    $preview_continuous_mode = 1;
    $pdf_previewer = 'open -a Skim';

    # Clean extensions
    $clean_ext = 'synctex.gz acn acr alg aux bbl bcf blg brf fdb_latexmk glg glo gls idx ilg ind ist lof log lot out run.xml toc';
    ```
  </Tab>

  <Tab title="VS Code Tasks">
    ```json theme={null}
    // .vscode/tasks.json
    {
      "version": "2.0.0",
      "tasks": [
        {
          "label": "Build LaTeX",
          "type": "shell",
          "command": "latexmk",
          "args": [
            "-pdf",
            "-synctex=1",
            "-interaction=nonstopmode",
            "-file-line-error",
            "main.tex"
          ],
          "group": {
            "kind": "build",
            "isDefault": true
          }
        },
        {
          "label": "Quick Compile",
          "type": "shell",
          "command": "pdflatex",
          "args": ["main.tex"],
          "problemMatcher": []
        },
        {
          "label": "Clean Auxiliary",
          "type": "shell",
          "command": "latexmk",
          "args": ["-c"],
          "problemMatcher": []
        }
      ]
    }
    ```
  </Tab>
</Tabs>

### Compilation Optimization

<LatexSource filename="draft-mode.tex" source={"% Fast draft compilation\n\\documentclass[draft]{book}\n% Images shown as boxes\n% Overfull boxes marked\n% Much faster compilation\n\n% Conditional draft mode\n\\usepackage{ifdraft}\n\\ifdraft{\n  \\usepackage[disable]{todonotes}\n  \\overfullrule=5pt\n}{\n  \\usepackage{todonotes}\n  \\overfullrule=0pt\n}\n\n% Skip expensive operations\n\\ifdraft{\n  \\renewcommand{\\includegraphics}[2][]{%\n    \\fbox{#2}% Just show filename\n  }\n}{}"} />

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

<LatexSource filename="externalization.tex" source={"% Externalize TikZ pictures\n\\usepackage{tikz}\n\\usetikzlibrary{external}\n\\tikzexternalize[prefix=tikz/]\n\n% Compile once, reuse many times\n\\begin{tikzpicture}\n  % Complex diagram\n  % Only recompiled if changed\n\\end{tikzpicture}\n\n% Externalize other content\n\\usepackage{standalone}\n\\usepackage{docmute}\n\n% In main.tex:\n\\input{figures/complex-diagram}\n% Can also compile standalone"} />

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

## Version Control

### Git Best Practices

<CodeGroup>
  ```bash .gitignore theme={null}
  # LaTeX auxiliary files
  *.aux
  *.lof
  *.log
  *.lot
  *.fls
  *.out
  *.toc
  *.fmt
  *.fot
  *.cb
  *.cb2
  .*.lb

  # Bibliography auxiliary
  *.bbl
  *.bcf
  *.blg
  *-blx.aux
  *-blx.bib
  *.run.xml

  # Build artifacts
  build/
  *.pdf
  !figures/*.pdf
  !templates/*.pdf

  # Editor files
  .vscode/
  *.swp
  *.swo
  *~
  .DS_Store

  # Temporary files
  *.tmp
  *.bak
  *.backup
  ```

  ```bash git-workflow.sh theme={null}
  # Meaningful commits for documents
  git add chapters/methodology.tex
  git commit -m "Add data analysis section to methodology"

  git add figures/chapter3/*.pdf
  git commit -m "Add experimental results figures"

  git add preamble/commands.tex
  git commit -m "Define custom theorem environments"

  # Tag milestones
  git tag -a v1.0-draft -m "First complete draft"
  git tag -a v2.0-submission -m "Journal submission version"

  # Branch for major revisions
  git checkout -b revision-reviewer-1
  git checkout -b conference-version
  ```
</CodeGroup>

### Collaboration Strategies

<Tip>
  **Team collaboration tips**:

  1. **One sentence per line** - Easier diffs
  2. **Semantic linebreaks** - Break at clauses
  3. **Chapter ownership** - Assign primary authors
  4. **Regular integration** - Daily merges
  5. **Automated builds** - CI/CD for PDFs
</Tip>

## Managing Bibliography

### Modular Bibliography

<CodeGroup>
  ```latex bibliography-setup.tex theme={null}
  % Split bibliography by chapter
  \usepackage[refsection=chapter]{biblatex}
  \addbibresource{references/intro.bib}
  \addbibresource{references/theory.bib}
  \addbibresource{references/experiments.bib}

  % Print chapter bibliographies
  \printbibliography[heading=subbibintoc]

  % Or global bibliography
  \printbibliography[heading=bibintoc]

  % Bibliography categories
  \DeclareBibliographyCategory{own}
  \addtocategory{own}{myarticle2020,mybook2021}

  \printbibliography[
    category=own,
    title={Own Publications}
  ]
  ```

  ```bibtex references/management.bib theme={null}
  % Organize by topic
  % references/machine-learning.bib
  @article{lecun2015deep,
    title={Deep learning},
    author={LeCun, Yann and Bengio, Yoshua and Hinton, Geoffrey},
    journal={Nature},
    volume={521},
    number={7553},
    pages={436--444},
    year={2015}
  }

  % references/statistics.bib
  @book{hastie2009elements,
    title={The elements of statistical learning},
    author={Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome},
    year={2009},
    publisher={Springer}
  }
  ```
</CodeGroup>

<RenderedOutput title="Expected effect">
  <Info>
    This code group documents a multi-step workflow across LaTeX and another file or command language. The blocks work together in a project, so there is no single standalone LaTeX page that would honestly represent the whole group.
  </Info>
</RenderedOutput>

## Multi-format Output

### Conditional Formatting

<LatexSource filename="conditional-output.tex" source={"% Different formats from same source\n\\usepackage{ifthen}\n\\newboolean{printversion}\n\\setboolean{printversion}{true} % or false\n\n% Conditional content\n\\ifthenelse{\\boolean{printversion}}{\n  % Print version\n  \\usepackage[colorlinks=false]{hyperref}\n  \\geometry{twoside}\n}{\n  % Digital version\n  \\usepackage[colorlinks=true]{hyperref}\n  \\geometry{oneside}\n}\n\n% Format-specific content\n\\newcommand{\\printonly}[1]{%\n  \\ifthenelse{\\boolean{printversion}}{#1}{}%\n}\n\\newcommand{\\digitalonly}[1]{%\n  \\ifthenelse{\\boolean{printversion}}{}{#1}%\n}\n\n% Usage\n\\digitalonly{\\href{https://example.com}{Click here for details}}\n\\printonly{See \\url{https://example.com} for details}"} />

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

## Troubleshooting Large Documents

### Common Issues

<Warning>
  **Large document problems and solutions**:

  1. **Undefined references**
     ```latex theme={null}
     % Run LaTeX multiple times
     pdflatex main && pdflatex main && pdflatex main
     ```

  2. **Memory errors**
     ```bash theme={null}
     # Increase memory limits
     export extra_mem_top=2000000
     export extra_mem_bot=2000000
     ```

  3. **Slow compilation**
     * Use `\includeonly` during writing
     * Enable draft mode
     * Externalize graphics

  4. **File not found**
     ```latex theme={null}
     % Check paths
     \input{./chapters/intro} % Explicit path
     \graphicspath{{./figures/}{./images/}}
     ```

  5. **Conflicting packages**
     * Load hyperref last
     * Check package documentation
     * Use compatibility options
</Warning>

## Complete Example Project

<CodeGroup>
  ```latex complete-thesis-structure.tex theme={null}
  % main.tex - Complete thesis example
  \documentclass[
      12pt,
      a4paper,
      twoside,
      openright,
      english,
      bibliography=totoc,
      listof=totoc
  ]{scrbook}

  % ====== PREAMBLE SETUP ======
  \input{preamble/packages}
  \input{preamble/settings}
  \input{preamble/commands}

  % Conditional compilation
  \includeonly{
      chapters/introduction,
      chapters/methodology,
      chapters/results
  }

  % ====== DOCUMENT INFO ======
  \title{Advanced Research in LaTeX Document Management}
  \author{Your Name}
  \date{\today}

  \begin{document}

  % ====== FRONT MATTER ======
  \frontmatter
  \input{frontmatter/titlepage}
  \input{frontmatter/declaration}
  \input{frontmatter/abstract}
  \input{frontmatter/acknowledgments}

  \tableofcontents
  \listoffigures
  \listoftables
  \input{frontmatter/abbreviations}

  % ====== MAIN MATTER ======
  \mainmatter
  \include{chapters/introduction}
  \include{chapters/literature}
  \include{chapters/theory}
  \include{chapters/methodology}
  \include{chapters/implementation}
  \include{chapters/results}
  \include{chapters/discussion}
  \include{chapters/conclusion}

  % ====== APPENDICES ======
  \appendix
  \include{appendices/code}
  \include{appendices/data}
  \include{appendices/proofs}

  % ====== BACK MATTER ======
  \backmatter
  \printbibliography[heading=bibintoc]
  \include{backmatter/glossary}
  \printindex

  \end{document}
  ```

  ```bash project-setup.sh theme={null}
  #!/bin/bash
  # Setup script for large LaTeX project

  # Create directory structure
  mkdir -p {preamble,frontmatter,chapters,appendices,backmatter}
  mkdir -p {figures,tables,build}
  mkdir -p figures/{chapter1,chapter2,shared}

  # Create preamble files
  touch preamble/{packages,settings,commands,environments}.tex

  # Create chapter files
  for i in {1..8}; do
      touch chapters/chapter$i.tex
  done

  # Create front/back matter
  touch frontmatter/{titlepage,abstract,acknowledgments}.tex
  touch backmatter/bibliography.bib

  # Create Makefile
  cat > Makefile << 'EOF'
  MAIN = main
  LATEX = pdflatex
  BIBTEX = biber
  BUILDDIR = build

  all: $(MAIN).pdf

  $(MAIN).pdf: $(MAIN).tex
  	$(LATEX) -output-directory=$(BUILDDIR) $(MAIN)
  	cd $(BUILDDIR) && $(BIBTEX) $(MAIN)
  	$(LATEX) -output-directory=$(BUILDDIR) $(MAIN)
  	$(LATEX) -output-directory=$(BUILDDIR) $(MAIN)
  	cp $(BUILDDIR)/$(MAIN).pdf .

  clean:
  	rm -rf $(BUILDDIR)/*

  .PHONY: all clean
  EOF

  echo "Project structure created!"
  ```
</CodeGroup>

<RenderedOutput title="Expected effect">
  <Info>
    This code group documents a multi-step workflow across LaTeX and another file or command language. The blocks work together in a project, so there is no single standalone LaTeX page that would honestly represent the whole group.
  </Info>
</RenderedOutput>

## Best Practices Summary

<Tip>
  ✅ **Large document checklist**:

  * [ ] Logical file structure
  * [ ] Consistent naming convention
  * [ ] Modular preamble
  * [ ] Smart cross-referencing
  * [ ] Version control setup
  * [ ] Build automation
  * [ ] Backup strategy
  * [ ] Collaboration guidelines
  * [ ] Documentation/README
  * [ ] Regular integration builds
</Tip>

## Next Steps

Continue mastering advanced LaTeX:

<CardGroup cols={2}>
  <Card title="Collaboration Workflow" icon="users" href="/learn/latex/how-to/collaboration-workflow">
    Team collaboration strategies
  </Card>

  <Card title="Using Templates" icon="clone" href="/learn/latex/how-to/using-templates">
    Create and use document templates
  </Card>

  <Card title="Fixing Errors" icon="bug" href="/learn/latex/how-to/fixing-compilation-errors">
    Troubleshoot compilation issues
  </Card>

  <Card title="Book Publishing" icon="book" href="/learn/latex/how-to/book-publishing">
    Professional book creation
  </Card>

  <Card title="Knowledge Base Docs" icon="book-open" href="/product/knowledge-base?utm_source=resources&utm_medium=internal_card&utm_campaign=research_workflow&utm_content=large_documents">
    Keep the core papers and source PDFs for a large project inside the same workspace as the document tree.
  </Card>

  <Card title="AI Research Agent Docs" icon="magnifying-glass" href="/product/ai-research-agent?utm_source=resources&utm_medium=internal_card&utm_campaign=research_workflow&utm_content=large_documents">
    Use accepted-source expansion and literature follow-up work when a chapter needs stronger evidence.
  </Card>
</CardGroup>

### Large Document Structure Toolkit

* [Sections and chapters](/learn/latex/document-structure/sections-and-chapters)
* [Table of contents](/learn/latex/document-structure/table-of-contents)
* [Glossaries and acronyms](/learn/latex/document-structure/glossaries)
* [Indexes](/learn/latex/document-structure/indexes)
* [Hyperlinks](/learn/latex/document-structure/hyperlinks)
* [Multi-file projects](/learn/latex/document-structure/multi-file-projects)
* [filecontents package](/learn/latex/document-structure/filecontents-package)
* [BibLaTeX guide](/learn/latex/bibliography/biblatex-guide)

***

<Info>
  **Pro tip**: Start with a well-organized structure from the beginning. It's much harder to reorganize a monolithic document later. Use version control from day one and establish clear naming conventions for your team.
</Info>
