{
  "id": "tex",
  "title": "TeX",
  "lang": "en",
  "source_lang": "en",
  "summary": "TeX is a programmable typesetting system created by Donald Knuth, renowned for mathematical composition, precise layout algorithms, and reproducible document production.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "product",
  "aliases": [
    "TeX typesetting system"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/tex/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/tex/",
      "json": "https://aiwiki.page/zh/tex.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "TeX is a programmable digital typesetting system designed by Donald E. Knuth to produce high-quality books and other documents, especially those containing complex mathematics. It combines a specialized programming language with algorithms for arranging characters, formulas, paragraphs, and pages. Rather than editing the final page directly, an author supplies text and commands that TeX processes into a precisely positioned representation of the document.\n\nFirst developed in 1977 and substantially redesigned in 1982, TeX became foundational infrastructure for mathematical and scientific publishing. Its influence extends beyond its original implementation: document systems such as LaTeX, modern Unicode-aware engines, mathematical notation renderers, and automated publishing workflows all build on or draw from its ideas. TeX is particularly distinguished by paragraph-wide line breaking, sophisticated mathematical layout, portability, and an unusually strong commitment to compatibility.\n\nThe name derives from the Greek letters tau, epsilon, and chi, associated with the Greek word technē, meaning art or craft. It is conventionally pronounced “tech,” with the final consonant resembling the sound in Scottish “loch,” rather than “tecks.” The distinctive lowered E is a typographic logo; the plain-text spelling is “TeX.”"
    },
    {
      "heading": "Origins and historical development",
      "text": "TeX originated in Knuth’s dissatisfaction with the typesetting of a new edition of the second volume of The Art of Computer Programming. Earlier volumes had been produced using established metal-typesetting methods, whereas the replacement production process yielded results that he considered inferior. Advances in digital printing suggested that a computer could specify letterforms and page geometry with much greater precision. Knuth began work in 1977, initially expecting a much shorter project than the undertaking became.\n\nThe original TeX, subsequently known as TeX78, was implemented in the SAIL programming language. Its development combined practical book production with research in typography and algorithms. Knuth investigated historical mathematical printing, the spacing of formulas, and the ways in which expert compositors balanced lines. The project was therefore not merely an attempt to automate typewriter-like output: it sought to encode substantial parts of a professional compositor’s judgment.\n\nA major redesign produced TeX82, the basis of the stable system used thereafter. Knuth rewrote it using WEB, a system that interleaves explanatory prose with program fragments and generates both documentation and compilable code. WEB originally targeted Pascal. This approach became a prominent example of literate programming, in which a program is presented as an explanation intended for human readers as well as an executable artifact.\n\nTeX’s typography was developed alongside METAFONT, Knuth’s system for describing and rasterizing typefaces, and the Computer Modern font family. These components were documented in the five-volume Computers & Typesetting series, published in 1984–1986. The TeXbook explains TeX’s user-facing language and typographic behavior, while TeX: The Program presents the implementation. Together they made both the system’s interface and much of its internal reasoning unusually accessible.\n\nVersion 3, released in 1990, introduced important multilingual capabilities, including eight-bit character support and changes supporting multiple hyphenation patterns. Subsequent version numbers approach \\(\\pi\\), as in 3.1, 3.14, and 3.141. These releases principally correct defects rather than add features. Knuth’s policy separates a fixed reference system from independently named extensions, allowing the original TeX to remain a stable target while other engines evolve."
    },
    {
      "heading": "The language: tokens, expansion, and execution",
      "text": "TeX reads a stream of characters and converts it into tokens. A character token records both a character code and a category code, commonly called a catcode. Category codes determine whether a character acts as a letter, a space, a group delimiter, a mathematical shift, a comment marker, or another syntactic element. Consequently, TeX’s syntax is programmable at a level that differs sharply from most conventional programming languages: changing category codes can change how subsequently read input is interpreted.\n\nIn normal settings, a backslash introduces a control sequence, such as \\par or \\hbox. A control word consists of an escape character followed by letters; a control symbol normally uses a single nonletter after the escape. Spaces following control words are treated specially so that command names can be separated from ordinary text without necessarily producing printed spaces. Braces ordinarily delimit groups, and a percent sign causes the remainder of an input line to be ignored as a comment.\n\nProcessing distinguishes expansion from execution. Expandable commands, including macros and conditionals, can replace themselves with other tokens. Unexpandable commands perform operations such as assigning a dimension, starting a box, selecting a font, or adding material to a list. This distinction explains many behaviors that initially seem surprising: a command can expand without immediately producing typeset material, while another command may require execution before it has any effect.\n\nA macro is defined by specifying the tokens that identify its arguments and the tokens that replace the invocation. For example:\n\n\\def\\term#1{{\\it #1}}\n\nIn a plain TeX environment, \\term{typesetting} expands to a group that selects italic type and processes the supplied argument. Parameters can also be delimited by specified token sequences, allowing macro authors to create specialized input syntaxes. Macros, conditionals, registers, and recursion together make TeX a general-purpose computational system, although its design is optimized for document processing rather than conventional application development.\n\nGrouping normally makes assignments local: a font selection or dimension change inside a group is restored when the group ends. Explicitly global assignments escape this scope. TeX also provides integer, dimension, glue, token-list, and box registers. Because input interpretation, expansion, and assignment interact closely, sophisticated TeX code requires careful control over when tokens are read and expanded. Its token model is unrelated to the statistical tokenization used in natural-language processing."
    },
    {
      "heading": "Boxes, glue, and the construction of pages",
      "text": "TeX represents typeset material through internal lists containing several kinds of nodes. The most familiar explanatory model is “boxes and glue.” A box has a width, a height above its reference baseline, and a depth below that baseline. Individual characters can contribute box-like material, while larger boxes contain entire words, lines, formulas, tables, or pages. This nested geometry lets the same fundamental mechanisms describe both small typographic objects and complete layouts.\n\nHorizontal boxes arrange material side by side; vertical boxes stack material. The primitive commands \\hbox and \\vbox expose these operations directly. A line of ordinary text eventually becomes a horizontal box, and a page consists largely of a vertical list of line boxes and intervening spaces. A box’s baseline matters independently of its visible outline, which is essential when aligning formulas, superscripts, table entries, and neighboring lines.\n\nGlue is adjustable space. It has a natural size and may also have stretch and shrink components. Interword glue allows justified text to reach a specified line width without changing the shapes of letters. Vertical glue controls spaces between paragraphs, headings, or other page elements. TeX also supports different orders of effectively infinite stretch or shrink, conventionally written using units such as fil and fill. These express priorities: flexible space at one order can absorb an adjustment before finite flexibility is used.\n\nKerns and penalties provide additional control. A kern is a specified displacement rather than ordinary stretchable space; it can implement fine adjustments between characters or other objects. A penalty assigns a numerical cost to a possible break. Strongly positive penalties discourage breaks, sufficiently large positive values prohibit them, and sufficiently negative values force them. These mechanisms allow macro packages to express rules such as avoiding a break after a heading or discouraging an isolated line at the top of a page.\n\nThe box model also explains the distinction between a box’s measured dimensions and the visible marks it contains. Material may protrude outside its nominal box, or an object may be deliberately assigned dimensions that conceal part of its physical extent. Such techniques support overlapping symbols and specialized layouts, but they can also create collisions that the automatic layout machinery does not detect. TeX composes according to declared geometry; it does not generally inspect the shapes of printed outlines to infer whether they collide."
    },
    {
      "heading": "Paragraph breaking, hyphenation, and page breaking",
      "text": "TeX’s paragraph composition is one of its most influential technical contributions. Instead of filling one line and irrevocably moving to the next, it evaluates possible line breaks across a paragraph. The Knuth–Plass line-breaking algorithm, developed by Knuth and Michael Plass and described in 1981, uses dynamic programming to select a sequence of breaks with a low overall cost. A slightly loose line may be accepted if it prevents much worse spacing later.\n\nFor each candidate line, the system compares the required adjustment with the available stretch or shrink. In the ordinary finite-glue case, its badness is approximately\n\n\\[b=\\min\\!\\left(10000,\\;100|r|^3\\right),\\]\n\nwhere \\(r\\) is the ratio of required adjustment to available flexibility, subject to TeX’s detailed feasibility rules and integer calculations. The cubic dependence makes severe spacing distortion much more expensive than small adjustments. Badness is not itself the entire optimization objective: TeX combines it with line penalties, breakpoint penalties, and additional demerits.\n\nThe algorithm also considers relationships between neighboring lines. It classifies lines into fitness categories reflecting how tight or loose their spacing is and can penalize abrupt changes. Separate demerits discourage consecutive hyphenated lines and certain hyphenation patterns at a paragraph’s end. The result is a typographic compromise involving several goals rather than a simple rule that every line must have equally sized spaces.\n\nHyphenation supplies additional candidate breakpoints within words. TeX uses compact language-dependent patterns, associated especially with Franklin Liang’s work, rather than relying only on a list of individually stored words. Patterns assign competing numerical values to positions within letter sequences; after combination, the surviving values determine potential breaks. Exceptions and minimum fragment lengths supplement this mechanism. Correct hyphenation therefore depends on the selected patterns and language conventions, not merely on the spelling visible on the page.\n\nPage breaking is a distinct process and should not be confused with paragraph-wide optimization. TeX’s page builder accumulates vertical material and evaluates candidate page breaks using available space, stretchability, penalties, and insertions such as footnotes. When appropriate, it invokes an output routine, a programmable mechanism that assembles or modifies the page before shipping it out. This flexibility permits headers, multicolumn arrangements, and complex publication designs, but ordinary TeX does not globally optimize every page break across an entire book."
    },
    {
      "heading": "Mathematical composition",
      "text": "TeX’s mathematical typesetting rests on a structured representation of formulas rather than the treatment of an equation as an ordinary line of specially chosen characters. Mathematical input is converted into a math list containing objects such as ordinary symbols, operators, binary operators, relations, opening and closing delimiters, punctuation, and inner expressions. These classes influence spacing. For example, the spaces around a relation such as an equals sign differ from those around an ordinary variable or a punctuation mark.\n\nThe familiar input conventions include ^ for superscripts, _ for subscripts, and braces for grouping. In plain TeX, x^{n+1} creates a superscript containing several mathematical objects, whereas x^n+1 superscripts only the next object. The source distinguishes these structures even if an inexperienced reader might initially regard braces as optional punctuation. TeX’s ability to nest these constructions is central to its treatment of advanced notation.\n\nTeX defines display, text, script, and scriptscript styles, together with corresponding cramped variants. Styles control how components are sized and positioned in different contexts. A fraction inside a superscript cannot simply be scaled as a complete picture; its numerator, denominator, spacing, and rules must be recomposed for a more constrained setting. TeX propagates style changes through the mathematical structure to produce such nested expressions.\n\nFractions, radicals, accents, large operators, and extensible delimiters use font metrics and mathematical parameters. A summation operator may place its limits above and below in display style but beside the operator in running text. Parentheses and other delimiters can be selected from larger glyphs or assembled from multiple pieces when the font supplies the necessary components. Vertical alignment uses a mathematical axis, which is related to but distinct from the text baseline.\n\nThe source\n\n$$\n\\int_0^1 x^n\\,dx = {1\\over n+1}\n$$\n\nillustrates plain TeX’s display notation, subscripts and superscripts, a thin mathematical space, and its primitive fraction construction. LaTeX generally presents different higher-level interfaces, including \\frac and dedicated display environments. TeX itself does not verify that the integral is mathematically meaningful or infer the semantic roles of all its symbols. It constructs the requested notation. This distinction becomes important when converting formulas into searchable, accessible, or machine-interpretable mathematical representations."
    },
    {
      "heading": "Fonts, metrics, and character encoding",
      "text": "Original TeX separates font measurement from the rendering of glyph shapes. It reads TeX Font Metric files, conventionally identified by the .tfm extension, to obtain widths, heights, depths, italic corrections, ligature and kerning information, and font parameters. These measurements let the engine determine layout without knowing whether a printer or previewer will eventually render a character from a bitmap or an outline.\n\nThis separation was especially valuable when output devices differed greatly in resolution and technology. A document could be composed using the same measurements and then rendered for a particular printer. The output system still had to locate appropriate glyph representations, but the page-breaking calculations did not inherently depend on a specific raster device. Missing or mismatched font resources could nevertheless cause substituted glyphs or incorrect appearance.\n\nMETAFONT describes letterforms through geometric constructions and generates rasterized fonts for specified device conditions. Computer Modern was developed using this approach and became strongly associated with TeX’s visual identity. Its coordinated text and mathematical fonts gave TeX a comprehensive working type system at a time when digital mathematical font resources were limited. Later workflows increasingly used scalable outline versions of Computer Modern and other font families.\n\nFont encoding is a separate issue from the input encoding of a source file. A source byte or Unicode character must eventually be associated with the desired glyph in the selected font. Classic TeX’s eight-bit character model and the arrangement of glyphs in traditional TeX fonts required encoding-specific macros and font setups. Accented letters assembled from separate components can also behave differently from precomposed glyphs in hyphenation, searching, and text extraction.\n\nModern engines reduce many historical restrictions by supporting Unicode input and OpenType fonts. Nevertheless, Unicode support alone does not settle every typographic question. Complex scripts require shaping, languages need appropriate line-breaking and hyphenation behavior, and mathematical fonts need specialized metrics. OpenType’s MATH table provides information for mathematical layout, including parameters and constructions that go beyond ordinary text shaping. Font choice can therefore change not only appearance but also line lengths, pagination, symbol coverage, and the reliability of extracted text."
    },
    {
      "heading": "Output formats and the document-production pipeline",
      "text": "Traditional TeX produces a Device Independent file, usually called a DVI file. DVI describes pages through operations such as positioning characters, moving horizontally or vertically, and drawing rules. It references fonts but does not ordinarily embed their glyph descriptions. Its compact representation separates the decisions made by the typesetter from the final details of displaying or printing those decisions.\n\nA DVI driver interprets this output for a particular destination. Historically, drivers supported screen previewers, laser printers, and conversion to page-description languages such as PostScript. DVI also permits specials: instructions whose interpretation is delegated to the output driver. Graphics inclusion, color, hyperlinks, and other capabilities could be carried through specials, but their portability depended on agreement between the macro package and the chosen driver.\n\nModern workflows often generate PDF directly. This removes the need for a separate DVI-to-PDF conversion step and permits engines to manage PDF-specific objects, links, font embedding, and other resources. Direct PDF production does not mean that every part of a document is handled by the engine itself. External programs may still prepare illustrations, process bibliographies, create indexes, or convert image formats.\n\nA complete build commonly requires several runs. During one run, the document writes auxiliary information about labels, section numbers, and page positions. A later run reads that information to resolve cross-references. A bibliography processor may consume citation data and produce formatted entries, while an indexing program sorts terms and their page references. Changes to any of these results can alter pagination, requiring further runs before the output stabilizes.\n\nThe pipeline also produces diagnostic information. TeX reports errors, missing characters, and overfull or underfull boxes, and writes a log recording the processing session. An overfull horizontal box indicates that material could not be accommodated within the requested width under the applicable rules; it is not necessarily a fatal error. Build tools distinguish successful execution from typographically satisfactory output. A PDF can be generated even when unresolved references, missing glyphs, or layout problems remain, so the existence of an output file is not by itself evidence of a completed publication build."
    },
    {
      "heading": "Formats, macro packages, and LaTeX",
      "text": "The word TeX can refer narrowly to the typesetting engine or more loosely to the surrounding document-production ecosystem. A crucial intermediate layer is the format: a preloaded collection of macros, register settings, hyphenation data, and other initial state. Format files allow an engine to begin with a substantial working environment without rereading every definition from source for each document.\n\nKnuth’s plain TeX is both a widely used basic format and an exposition of how to build higher-level behavior from TeX primitives. It supplies conventions for font changes, mathematical displays, page layout, and many routine operations. Plain TeX is not the unmodified engine itself: commands familiar to plain TeX users may be macros rather than built-in primitives. This distinction matters when interpreting documentation or moving code between formats.\n\nLaTeX, developed by Leslie Lamport in the early 1980s, adds a document-preparation layer organized around structural markup. Authors specify sections, figures, citations, equations, and other document elements through a coordinated interface. Classes define broad document designs, while packages extend functionality. The widely established LaTeX2e release dates from 1994; later development has continued within that maintained system and through newer programming interfaces.\n\nA minimal LaTeX document illustrates the difference in abstraction:\n\n\\documentclass{article}\n\\begin{document}\n\\section{An example}\nThe relation \\(E=mc^2\\) appears in running text.\n\\end{document}\n\nHere \\documentclass, \\section, and the document environment belong to LaTeX rather than the underlying TeX engine. The engine still performs macro expansion, list construction, mathematical composition, and line breaking, but the author works mainly through a document-oriented interface. A command-line name such as pdflatex consequently identifies a combination: a PDF-capable engine loaded with the LaTeX format.\n\nConTeXt is another substantial macro-based document system, with its own integrated interfaces for layout, typography, and structured publishing. Its development demonstrates that TeX does not imply a single authoring language or package architecture. Formats can differ substantially while sharing underlying layout mechanisms. Conversely, two documents both described informally as “TeX documents” may require different engines, formats, fonts, and support programs to build successfully."
    },
    {
      "heading": "Extended engines and modern implementations",
      "text": "The stability of Knuth’s TeX encouraged extensions to develop under distinct names. An important example is e-TeX, which added facilities such as additional registers, richer expression handling, and improved programming and diagnostic capabilities. These extensions became part of the practical foundation of many later engines. Compatibility remains central, but extended implementations are not simply successive feature releases of Knuth’s fixed reference program.\n\npdfTeX, initiated by Hàn Thế Thành, added direct PDF output and typographic extensions. Its best-known refinements include character protrusion and font expansion, associated with microtypography. Protrusion allows selected characters, especially punctuation, to extend slightly beyond the nominal margin so that the visible text edge appears more even. Font expansion permits controlled adjustments to glyph widths, offering another degree of freedom during line breaking. The effects depend on suitable configuration and font support.\n\nXeTeX, developed by Jonathan Kew, brought Unicode-oriented processing and access to modern system fonts into a TeX engine. It supports advanced font technologies and multilingual composition through shaping infrastructure. In its common PDF workflow, XeTeX produces extended DVI data that a driver converts to PDF. Its user-visible ability to select an OpenType font should therefore be distinguished from the internal route by which the final PDF is produced.\n\nLuaTeX combines a TeX-derived engine with the Lua programming language. It exposes internal structures and processing stages through interfaces and callbacks, allowing behavior to be implemented or modified without relying exclusively on TeX macro expansion. This facilitates advanced font handling, custom node processing, and specialized publishing systems. LuaTeX is an extensible platform rather than merely a Unicode-input version of classic TeX.\n\nEngine choice affects supported primitives, character handling, font loading, output behavior, and package compatibility. A macro package that depends on Lua callbacks cannot generally run unchanged under pdfTeX; one that assumes legacy font encodings may need adaptation for Unicode-oriented engines. Even when source syntax is shared, different fonts and engine settings can change line breaks. Modern TeX practice therefore distinguishes source-level compatibility from identical output and treats the engine, format, package versions, and font resources as separate components of the document environment."
    },
    {
      "heading": "Distribution, scientific publishing, and long-term preservation",
      "text": "TeX is distributed as part of larger collections that include engines, formats, fonts, documentation, and supporting programs. TeX Live is a major cross-platform distribution, while MiKTeX provides another widely used distribution with facilities for package management. These collections turn a typesetting engine into an operational publishing environment. Much of the ecosystem is available as open-source software, but the collection contains components under different licenses rather than a single uniform license.\n\nThe Comprehensive TeX Archive Network, or CTAN, is a central repository for TeX-related software and documentation. The TeX Users Group, founded in 1980, and language-specific or regional groups have supported publications, conferences, development, and user education. This distributed institutional structure helps explain TeX’s longevity: its maintenance and extension do not depend on one commercial product vendor, although individual packages vary in maintenance activity and compatibility guarantees.\n\nTeX-based systems are especially prominent in mathematics, theoretical physics, computer science, and other fields that require extensive notation and cross-referencing. Journals and conference proceedings distribute document classes, and repositories such as arXiv accept TeX-based submissions. Plain-text source works naturally with version control, automated builds, and collaborative editing. These advantages coexist with practical complexity: a project may depend on a large package collection, bibliography databases, graphics, external tools, and publication-specific settings.\n\nReproducibility requires more than preserving the main .tex file. Fonts, included images, class files, package versions, engine behavior, and auxiliary build steps can all affect the result. TeX’s stable core is an important foundation, but it does not guarantee identical output from arbitrarily changing environments. Preserving a complete build environment, or recording its components precisely, addresses a different problem from simply retaining readable source. Source preservation and final-form PDF preservation serve complementary purposes.\n\nAccessibility and document semantics expose another boundary. TeX’s layout model is highly effective at positioning material, but visual placement alone does not identify reading order, heading structure, table relationships, or the meaning of mathematical notation. Producing tagged, accessible PDF requires cooperation among the authoring format, packages, engine, and PDF-generation mechanisms. Similar issues arise when converting documents to HTML: a visually precise page is not automatically a well-structured web document.\n\nDocument compilation also has security implications. TeX can read and write files, and some configurations permit invocation of external commands. Processing untrusted source therefore involves a different risk profile from displaying an inert finished document. Hosted compilation services use restrictions on command execution, filesystem access, and resource consumption, often combined with an application sandbox. These controls address the fact that a TeX document is not only descriptive text but also an executable program."
    }
  ],
  "links": [
    "mathematics",
    "programming-language",
    "typography",
    "algorithm",
    "recursion",
    "tokenization",
    "dynamic-programming",
    "unicode",
    "open-source-software",
    "arxiv",
    "version-control",
    "html"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}