### Include tex-linebreak2 as a Third-Party Script Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md Load the library using a script tag from a CDN. Methods are then available globally via the `texLinebreak` object. This example shows how to apply line breaking to all `

` elements on the page. ```html

Example text

``` -------------------------------- ### Format text with TexLinebreak and get plaintext output Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md Instantiate TexLinebreak with text and options like lineWidth and measureFn to format the text. The plaintext property provides the formatted output as a string. ```javascript import { TexLinebreak } from "tex-linebreak2"; const text = "Chamæleon animal est quadrupes, macrum & gibbosum, capite galeato, corpore & cauda lacertæ majoris, cervice penè nulla, costis plus minus sedecim, obliquo ductu ventri junctis ut piscibus."; const t = new TexLinebreak(text, { lineWidth: 45, /* A function that measures the width of a string of text. (For monospace text, you should however use the option `preset: "plaintext"`, which will correctly calculate a string's width) */ measureFn: (word) => word.length, /* Spaces should not expand */ glueStretchFactor: 0, /* Spaces should not contract */ glueShrinkFactor: 0, }); /* Get output as plain text */ console.log(t.plaintext); /* Output: Chamæleon animal est quadrupes, macrum & gibbosum, capite galeato, corpore & cauda lacertæ majoris, cervice penè nulla, costis plus minus sedecim, obliquo ductu ventri junctis ut piscibus. */ /* Get output as positioned items */ console.log(t.lines.map((line) => line.positionedItems)); /* Output: [[{ type: 'box', text: 'Chamæleon', xOffset: 0, width: 9 }, { type: 'glue', text: ' ', xOffset: 9, width: 1 }, ... */ ``` -------------------------------- ### Using Tex-Linebreak2 Presets Source: https://context7.com/egilll/tex-linebreak2/llms.txt Demonstrates the usage of 'plaintext', 'html', and combined presets for text line breaking. Ensure correct import of TexLinebreak. ```typescript import { TexLinebreak } from "tex-linebreak2"; // Plaintext preset: uses string-width, breaks only on whitespace, ragged const plain = new TexLinebreak( "A Markdown-style paragraph.\nSingle newlines are collapsed by default.", { preset: "plaintext", lineWidth: 40, } ); console.log(plain.plaintext); ``` ```typescript // HTML preset: collapses all newlines, suitable for DOM content const html = new TexLinebreak( "Text with\nnewlines that\nshould collapse.", { preset: "html", lineWidth: 200, measureFn: (w) => w.length * 9, } ); ``` ```typescript // Combined presets const combined = new TexLinebreak("Some text", { preset: ["html", "raggedAlignment"], // apply both lineWidth: 300, measureFn: (w) => w.length * 9, }); ``` -------------------------------- ### TexLinebreak Constructor Source: https://context7.com/egilll/tex-linebreak2/llms.txt The main entry point for the library. Accepts either a plain string or an array of low-level items (Box | Glue | Penalty), plus an options object. Computes optimal line breakpoints using the Knuth-Plass algorithm and exposes the result through lines, plaintext, plaintextLines, items, and breakpoints. ```APIDOC ## new TexLinebreak(input, options) ### Description Instantiates the TexLinebreak class to perform line breaking on the provided input text. ### Parameters - **input** (string | Array) - The text or array of items to break into lines. - **options** (object) - Configuration options for line breaking. - **lineWidth** (number) - The target width for each line. - **measureFn** (function) - A function to measure the width of a given string (e.g., character count for monospace). - **glueStretchFactor** (number) - Controls how much spaces can stretch. - **glueShrinkFactor** (number) - Controls how much spaces can shrink. ### Request Example ```javascript import { TexLinebreak } from "tex-linebreak2"; const t = new TexLinebreak( "Chamæleon animal est quadrupes, macrum & gibbosum, capite galeato, corpore & cauda lacertæ majoris, cervice penè nulla.", { lineWidth: 45, measureFn: (word) => word.length, glueStretchFactor: 0, glueShrinkFactor: 0, } ); console.log(t.plaintext); ``` ### Response - **lines** (Array) - An array of Line objects, each representing a broken line. - **plaintext** (string) - The entire text broken into lines, separated by newline characters. - **plaintextLines** (Array) - An array of strings, each representing a line of text. - **items** (Array) - The raw items after line breaking. - **breakpoints** (Array) - Indices indicating where lines break. ### Response Example ```javascript // Accessing plaintext console.log(t.plaintext); /* Chamæleon animal est quadrupes, macrum & gibbosum, capite galeato, corpore & cauda lacertæ majoris, cervice penè nulla. */ // Iterating over lines t.lines.forEach((line, i) => { console.log(`Line ${i}: "${line.plaintext}"`); }); // Accessing raw breakpoint indices console.log(t.breakpoints); // e.g. [0, 8, 17, 26] ``` ``` -------------------------------- ### Initialize TexLinebreak Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md Instantiate TexLinebreak with either plain text or arbitrary items, and an optional options object. Arbitrary items can be boxes, glues, or penalties. ```javascript new TexLinebreak("text", {}); ``` ```javascript new TexLinebreak({ type: "box", width: 10 }, {}); ``` -------------------------------- ### Construct Items with box, glue, and penalty Helpers Source: https://context7.com/egilll/tex-linebreak2/llms.txt Utility functions box, glue, and penalty help construct raw item types for custom line breaking. Use MIN_COST to force a break and MAX_COST to prevent one. This is useful for integrating with custom layout engines. ```typescript import { box, glue, penalty, MIN_COST, MAX_COST, TexLinebreak, } from "tex-linebreak2"; // Layout a non-text sequence (e.g., for a graphic layout engine) const items = [ box(30), // word: 30 units wide glue(6, 3, 2), // space: 6 wide, stretch 3, shrink 2 box(50), // word: 50 units wide glue(6, 3, 2), box(20), penalty(0, 0), // optional breakpoint, zero cost glue(6, 3, 2), box(40), // Mandatory paragraph end glue(0, 1e5, 0), penalty(0, MIN_COST), ]; const result = new TexLinebreak(items, { lineWidth: 80 }); result.lines.forEach((line) => { console.log( line.positionedItems .map((i) => `[${i.type} x=${i.xOffset.toFixed(1)} w=${i.adjustedWidth.toFixed(1)}]`) .join(" ") ); }); ``` -------------------------------- ### Initialize TexLinebreak for Plain Text Source: https://context7.com/egilll/tex-linebreak2/llms.txt Instantiate the core TexLinebreak class with a string and options. Use a custom measureFn for monospace fonts or specific width calculations. Set glueStretchFactor and glueShrinkFactor to 0 for fixed-width spacing. ```typescript import { TexLinebreak } from "tex-linebreak2"; // --- Plain text with a monospace measureFn --- const t = new TexLinebreak( "Chamæleon animal est quadrupes, macrum & " + "corpore & cauda lacertæ majoris, cervice penè nulla.", { lineWidth: 45, measureFn: (word) => word.length, // character-count width for monospace glueStretchFactor: 0, // no stretching: fixed-width spaces glueShrinkFactor: 0, } ); // Get the result as a newline-separated string console.log(t.plaintext); /* Chamæleon animal est quadrupes, macrum & gibbosum, capite galeato, corpore & cauda lacertæ majoris, cervice penè nulla. */ // Iterate over individual lines t.lines.forEach((line, i) => { console.log(`Line ${i}: "${line.plaintext}"`); }); // Access positioned items for custom rendering t.lines.forEach((line) => { line.positionedItems.forEach((item) => { if (item.type === "box" && "text" in item) { console.log(` box "${item.text}" at x=${item.xOffset}, w=${item.adjustedWidth}`); } else if (item.type === "glue") { console.log(` space at x=${item.xOffset}, w=${item.adjustedWidth}`); } }); }); // Access raw breakpoint indices console.log(t.breakpoints); // e.g. [0, 8, 17, 26] ``` -------------------------------- ### `box`, `glue`, `penalty` helpers Source: https://context7.com/egilll/tex-linebreak2/llms.txt Utility functions for constructing raw item types used in custom line breaking scenarios. ```APIDOC ## `box`, `glue`, `penalty` — Item constructor helpers ### Description Utility functions to construct the raw item types used by `breakLines` and `TexLinebreak` when supplying custom items. `MIN_COST` forces a break; `MAX_COST` prevents one. ### Functions - **box(width)**: Creates a 'box' item with a given width. - **glue(width, stretch, shrink)**: Creates a 'glue' item with specified width, stretch, and shrink values. - **penalty(cost, lineAfter)**: Creates a 'penalty' item with a cost and a flag indicating if a line break is allowed after it. ### Constants - **MIN_COST**: A constant representing the minimum cost, typically used to force a break. - **MAX_COST**: A constant representing the maximum cost, typically used to prevent a break. ### Request Example ```typescript import { box, glue, penalty, MIN_COST, MAX_COST, TexLinebreak, } from "tex-linebreak2"; // Layout a non-text sequence (e.g., for a graphic layout engine) const items = [ box(30), // word: 30 units wide glue(6, 3, 2), // space: 6 wide, stretch 3, shrink 2 box(50), // word: 50 units wide glue(6, 3, 2), box(20), penalty(0, 0), // optional breakpoint, zero cost glue(6, 3, 2), box(40), // Mandatory paragraph end glue(0, 1e5, 0), penalty(0, MIN_COST), ]; const result = new TexLinebreak(items, { lineWidth: 80 }); result.lines.forEach((line) => { console.log( line.positionedItems .map((i) => `[${i.type} x=${i.xOffset.toFixed(1)} w=${i.adjustedWidth.toFixed(1)}]`) .join(" ") ); }); ``` ``` -------------------------------- ### breakLines(items, options) Source: https://context7.com/egilll/tex-linebreak2/llms.txt The raw implementation of the Knuth-Plass paragraph line-breaking algorithm. Takes an array of Box, Glue, and Penalty items and returns the chosen breakpoint indices plus the internal LineBreakingNode chain. Throws MaxAdjustmentExceededError if maxAdjustmentRatio is set and no valid layout can be found. ```APIDOC ## `breakLines(items, options)` — Low-level Knuth-Plass algorithm ### Description The raw implementation of the Knuth-Plass paragraph line-breaking algorithm. Takes an array of `Box`, `Glue`, and `Penalty` items and returns the chosen breakpoint indices plus the internal `LineBreakingNode` chain. Throws `MaxAdjustmentExceededError` if `maxAdjustmentRatio` is set and no valid layout can be found. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **items** (Array) - Required - An array of items to be laid out. * **options** (TexLinebreakOptions) - Optional - Configuration options for line breaking. ### Request Example ```typescript import { breakLines, Box, Glue, Penalty, MIN_COST, MAX_COST, MaxAdjustmentExceededError, } from "tex-linebreak2"; const items: (Box | Glue | Penalty)[] = [ { type: "box", width: 10 }, { type: "glue", width: 4, stretch: 2, shrink: 1 }, { type: "box", width: 20 }, { type: "glue", width: 4, stretch: 2, shrink: 1 }, { type: "box", width: 15 }, // Paragraph end: infinite glue + forced break { type: "glue", width: 0, stretch: 1e5, shrink: 0 }, { type: "penalty", width: 0, cost: MIN_COST }, ]; try { const { breakpoints, lineBreakingNodes } = breakLines(items, { lineWidth: 40, }); console.log("Breakpoints at item indices:", breakpoints); // e.g. [0, 3, 6] console.log("Total demerits:", lineBreakingNodes.at(-1)?.totalDemerits); } catch (e) { if (e instanceof MaxAdjustmentExceededError) { console.error("Could not lay out paragraph within maxAdjustmentRatio"); } } ``` ### Response #### Success Response (200) - **breakpoints** (Array) - An array of indices representing the breakpoints. - **lineBreakingNodes** (Array) - A chain of nodes representing the line breaking structure. #### Response Example ```json { "breakpoints": [0, 3, 6], "lineBreakingNodes": [ // ... LineBreakingNode objects ] } ``` ### Errors - **MaxAdjustmentExceededError**: Thrown if `maxAdjustmentRatio` is set and no valid layout can be found. ``` -------------------------------- ### Configure TexLinebreak with TexLinebreakOptions Source: https://context7.com/egilll/tex-linebreak2/llms.txt Instantiate `TexLinebreak` with a configuration object to control all aspects of the line-breaking algorithm. Key options include `lineWidth`, `measureFn`, alignment, spacing, hyphenation, and custom break rules. ```typescript import { TexLinebreak } from "tex-linebreak2"; const t = new TexLinebreak("Some long paragraph text here...", { // Required lineWidth: 600, // px, or an array of per-line widths, or a function measureFn: (word) => { // must return width in the same units as lineWidth const canvas = document.createElement("canvas"); return canvas.getContext("2d")!.measureText(word).width; }, // Alignment justify: true, // true = justified (default), false = ragged align: "left", // "left" | "right" | "center" (for non-DOM use) // Spacing tuning glueStretchFactor: 1.2, // spaces can grow to 220% of natural width glueShrinkFactor: 0.2, // spaces can shrink to 80% of natural width renderLineAsUnjustifiedIfAdjustmentRatioExceeds: 2.5, // hard display cap // Hyphenation softHyphenPenalty: 50, // 0–MAX_COST; higher = fewer hyphenations regularHyphenPenalty: 20, // penalty for breaking after an existing hyphen doubleHyphenPenalty: 100, // extra cost for back-to-back hyphenated lines // Advanced lineBreakingAlgorithm: "tex", // "tex" (default) | "greedy" findOptimalWidth: false, // shrink lineWidth to minimize whitespace forceOverflowToBreak: false, // force-break words longer than lineWidth hangingPunctuation: true, // allow punctuation to hang into margin // DOM-specific updateOnWindowResize: true, setElementWidthToMaxLineWidth: false, ignoreFloatingElements: false, // Custom break rules neverBreakInside: /https?:\/\/\S+/g, // don't break inside URLs neverBreakAfter: ["Dr.", "Mr.", "Ms."], }); console.log(t.plaintext); ``` -------------------------------- ### TexLinebreak Initialization Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md The TexLinebreak class can be initialized with either plain text or an array of items, along with an optional options object. ```APIDOC ## TexLinebreak Initialization ### Description Instantiate the `TexLinebreak` class with text content or structured items and configuration options. ### Method `new TexLinebreak(content, options)` ### Parameters #### content - `text` (string) - The text content to be broken into lines. - `items` (Array) - An array of structured items (boxes, glues, penalties) to be broken into lines. See [`TexLinebreak`](src/index.ts) for item structure. #### options - `options` (object) - An optional object for configuring line breaking behavior. See [`TexLinebreakOptions`](src/options.ts) for available options. ### Request Example ```js // Initialize with text new TexLinebreak("This is a sample text to be broken into lines.", {}); // Initialize with structured items new TexLinebreak({ type: "box", width: 10 }, {}); ``` ``` -------------------------------- ### Lay out paragraphs with options using texLinebreakDOM Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md Pass an options object as the second argument to texLinebreakDOM to customize layout, such as alignment. The library listens for window resizing by default. ```javascript import { texLinebreakDOM } from "tex-linebreak2"; texLinebreakDOM(document.querySelectorAll("p"), { align: "left" }); ``` -------------------------------- ### `texLinebreakMonospace(input, options)` Source: https://context7.com/egilll/tex-linebreak2/llms.txt A convenience wrapper for monospace text that pre-applies the 'plaintext' preset for easier line breaking on whitespace. ```APIDOC ## `texLinebreakMonospace(input, options)` ### Description A helper that pre-applies the "plaintext" preset (which sets `measureFn` to `string-width`, disables justification, and only breaks on whitespace) so callers do not need to configure these details manually. ### Parameters - **input** (string) - The text to be line-broken. - **options** (object) - Configuration options for line breaking, such as `lineWidth`. ### Returns An object containing the line-broken text, including `plaintext` and `plaintextLines`. ### Request Example ```typescript import { texLinebreakMonospace } from "tex-linebreak2"; const result = texLinebreakMonospace( "The quick brown fox jumps over the lazy dog and keeps on running far away.", { lineWidth: 40 } ); console.log(result.plaintext); /* The quick brown fox jumps over the lazy dog and keeps on running far away. */ // Each line's plain text result.plaintextLines.forEach((line, i) => { console.log(`[${i}] ${line}`); }); ``` ``` -------------------------------- ### Lay out arbitrary items using TexLinebreak Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md Use TexLinebreak to lay out custom items, including 'box', 'glue', and 'penalty' types, by providing them as an array. This allows for flexible content formatting beyond simple text. ```javascript import { TexLinebreak, MIN_COST } from "tex-linebreak2"; const items = [ { type: "box", width: 10 }, { type: "glue", width: 4, stretch: 2, shrink: 1 }, { type: "box", width: 20 }, { type: "penalty", cost: MIN_COST }, ]; const positionedItems = new TexLinebreak(items, { lineWidth: 45, }).positionedItems; ``` -------------------------------- ### splitTextIntoItems(input, options) Source: https://context7.com/egilll/tex-linebreak2/llms.txt Converts a plain string into the sequence of TextItem objects (boxes, glues, penalties) that the algorithm operates on. Handles Unicode line-breaking rules, soft hyphens, non-breaking spaces, hanging punctuation, and custom patterns. ```APIDOC ## `splitTextIntoItems(input, options)` — Convert text to box/glue/penalty items ### Description Converts a plain string into the sequence of `TextItem` objects (boxes, glues, penalties) that the algorithm operates on. Handles Unicode line-breaking rules (via the `linebreak` package), soft hyphens (`\u00AD`), non-breaking spaces, hanging punctuation, and custom `neverBreakInside` / `neverBreakAfter` patterns. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **input** (string) - Required - The plain text string to convert. * **options** (object) - Optional - Configuration options for text splitting. * **measureFn** (function) - Required - A function that measures the width of a word. * **hangingPunctuation** (boolean) - Optional - Whether to enable hanging punctuation. * **softHyphenPenalty** (number) - Optional - The penalty for breaking at a soft hyphen. * **neverBreakInside** (RegExp) - Optional - A regular expression for patterns that should not be broken inside. * **neverBreakAfter** (Array) - Optional - An array of strings after which breaks should not occur. ### Request Example ```typescript import { splitTextIntoItems } from "tex-linebreak2"; const items = splitTextIntoItems( "Hello, world! This is a test\u00ADstring with a soft\u00ADhyphen.", { measureFn: (word) => word.length, hangingPunctuation: true, softHyphenPenalty: 50, neverBreakInside: /\{.+?\}/g, // never break inside curly braces neverBreakAfter: ["e.g.", "-"], // never break after these strings } ); items.forEach((item) => { if (item.type === "box") { console.log(`box: "${("text" in item && item.text) || ""}" w=${item.width}`); } else if (item.type === "glue") { console.log(`glue: w=${item.width} stretch=${item.stretch} shrink=${item.shrink}`); } else { console.log(`penalty: cost=${item.cost} flagged=${item.flagged}`); } }); ``` ### Response #### Success Response (200) - **items** (Array) - An array of TextItem objects (boxes, glues, penalties). #### Response Example ```json [ { "type": "box", "text": "Hello, ", "width": 7 }, { "type": "glue", "width": 0, "stretch": 1000, "shrink": 100 }, { "type": "box", "text": "world! ", "width": 7 }, // ... other items ] ``` ``` -------------------------------- ### Implement Knuth-Plass Algorithm with breakLines Source: https://context7.com/egilll/tex-linebreak2/llms.txt Use the `breakLines` function for the raw implementation of the Knuth-Plass algorithm. It takes an array of Box, Glue, and Penalty items and returns breakpoint indices. Ensure proper error handling for `MaxAdjustmentExceededError`. ```typescript import { breakLines, Box, Glue, Penalty, MIN_COST, MAX_COST, MaxAdjustmentExceededError, } from "tex-linebreak2"; const items: (Box | Glue | Penalty)[] = [ { type: "box", width: 10 }, { type: "glue", width: 4, stretch: 2, shrink: 1 }, { type: "box", width: 20 }, { type: "glue", width: 4, stretch: 2, shrink: 1 }, { type: "box", width: 15 }, // Paragraph end: infinite glue + forced break { type: "glue", width: 0, stretch: 1e5, shrink: 0 }, { type: "penalty", width: 0, cost: MIN_COST }, ]; try { const { breakpoints, lineBreakingNodes } = breakLines(items, { lineWidth: 40, }); console.log("Breakpoints at item indices:", breakpoints); // e.g. [0, 3, 6] console.log("Total demerits:", lineBreakingNodes.at(-1)?.totalDemerits); } catch (e) { if (e instanceof MaxAdjustmentExceededError) { console.error("Could not lay out paragraph within maxAdjustmentRatio"); } } ``` -------------------------------- ### Lay out paragraphs on a webpage using texLinebreakDOM Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md Use texLinebreakDOM with a CSS selector to format all paragraphs on a webpage. Ensure this is called after fonts have loaded if using third-party webfonts. ```javascript import { texLinebreakDOM } from "tex-linebreak2"; texLinebreakDOM("p"); // Selects all

elements ``` -------------------------------- ### `Line` class Source: https://context7.com/egilll/tex-linebreak2/llms.txt Represents a single line of text after line breaking, providing properties for rendering and layout information. ```APIDOC ## `Line` class ### Description Each element of `TexLinebreak.lines` is a `Line` instance. The most important property is `positionedItems`, which provides the items needed to render one line with their pixel offsets already computed. Also exposes `plaintext`, `adjustmentRatio`, `endsWithSoftHyphen`, and `idealWidth`. ### Properties - **plaintext** (string) - The plain text content of the line. - **idealWidth** (number) - The ideal width of the line before adjustments. - **adjustmentRatio** (number) - The ratio of adjustment applied to the line. - **endsWithSoftHyphen** (boolean) - Indicates if the line ends with a soft hyphen. - **positionedItems** (Array) - An array of items with their computed positions and widths for rendering. ### Request Example ```typescript import { TexLinebreak } from "tex-linebreak2"; const t = new TexLinebreak( "Pack my box with five dozen liquor jugs quickly.", { lineWidth: 25, measureFn: (w) => w.length } ); t.lines.forEach((line, lineIndex) => { console.log(`\n--- Line ${lineIndex} ---`); console.log(` plaintext: "${line.plaintext}"`); console.log(` idealWidth: ${line.idealWidth}`); console.log(` adjustmentRatio: ${line.adjustmentRatio.toFixed(3)}`); console.log(` endsWithHyphen: ${line.endsWithSoftHyphen}`); line.positionedItems.forEach((item) => { if (item.type === "box" && "text" in item) { process.stdout.write(item.text as string); } else if (item.type === "glue") { process.stdout.write(" ".repeat(Math.round(item.adjustedWidth))); } }); console.log(); }); ``` ``` -------------------------------- ### `findOptimalWidth(paragraphObjects, options)` Source: https://context7.com/egilll/tex-linebreak2/llms.txt Shrinks line width iteratively to minimize whitespace, useful for compact layouts like headings or captions. ```APIDOC ## `findOptimalWidth(paragraphObjects, options)` ### Description Iteratively reduces `lineWidth` (via the internal `makeLineWidthSmallerBy` option) to find the most compact layout that does not introduce extra lines. Useful for headings or captions where you want to minimize trailing whitespace. Mutates the options on the passed `TexLinebreak` instances in place. ### Parameters - **paragraphObjects** (Array) - An array of `TexLinebreak` instances to optimize. - **options** (object) - Configuration options, including `makeLineWidthSmallerBy`. ### Request Example ```typescript import { TexLinebreak, findOptimalWidth } from "tex-linebreak2"; const paragraph = new TexLinebreak( "Breaking paragraphs into lines of optimal width.", { lineWidth: 400, measureFn: (w) => w.length * 8, // 8px per character findOptimalWidth: true, // activate inside TexLinebreak automatically } ); // Or call manually across multiple paragraphs: const p1 = new TexLinebreak("First paragraph text.", { lineWidth: 400, measureFn: (w) => w.length * 8 }); const p2 = new TexLinebreak("Second paragraph text.", { lineWidth: 400, measureFn: (w) => w.length * 8 }); findOptimalWidth([p1, p2]); console.log(p1.plaintext); console.log(p2.plaintext); ``` ``` -------------------------------- ### Use texLinebreakMonospace for Monospace Text Source: https://context7.com/egilll/tex-linebreak2/llms.txt This convenience wrapper pre-applies the 'plaintext' preset for monospace text, disabling justification and breaking only on whitespace. It simplifies the process by avoiding manual configuration of these settings. ```typescript import { texLinebreakMonospace } from "tex-linebreak2"; const result = texLinebreakMonospace( "The quick brown fox jumps over the lazy dog and keeps on running far away.", { lineWidth: 40 } ); console.log(result.plaintext); /* The quick brown fox jumps over the lazy dog and keeps on running far away. */ // Each line's plain text result.plaintextLines.forEach((line, i) => { console.log(`[${i}] ${line}`); }); ``` -------------------------------- ### texLinebreakDOM Function Source: https://context7.com/egilll/tex-linebreak2/llms.txt An async function that applies the Knuth-Plass algorithm to one or more HTML elements in a live document. Measures text widths via canvas, inserts `
` elements and CSS `margin-left` adjustments to achieve optimal justification, and registers a window resize listener to reflow on viewport changes. ```APIDOC ## texLinebreakDOM(elements, options?) ### Description Applies line breaking and justification to specified HTML elements directly in the DOM. ### Parameters - **elements** (string | HTMLElement | NodeList | Array) - A CSS selector, a single element, a NodeList, or an array of elements to apply line breaking to. - **options** (object, optional) - Configuration options for DOM line breaking. - **align** (string) - Alignment of the text ('left', 'right', 'center'). - **hangingPunctuation** (boolean) - Allows punctuation to hang into the margin. - **updateOnWindowResize** (boolean) - Automatically reflows text when the window is resized (default: true). - **renderLineAsUnjustifiedIfAdjustmentRatioExceeds** (number) - Threshold for line justification. - **justify** (boolean) - Enables or disables justification (setting to false enables ragged alignment). ### Request Example ```javascript import { texLinebreakDOM } from "tex-linebreak2"; // Apply to all

elements await texLinebreakDOM("p"); // Apply to a specific element with custom options const article = document.querySelector("article"); await texLinebreakDOM(article, { align: "left", hangingPunctuation: true, updateOnWindowResize: true, renderLineAsUnjustifiedIfAdjustmentRatioExceeds: 2, }); // Apply with ragged-right alignment await texLinebreakDOM(document.querySelectorAll(".content p"), { justify: false, }); ``` ### Response This function does not return a value but modifies the DOM directly by inserting `
` elements and applying CSS. ### Related Functions - **resetDOMJustification(element)**: Removes justification applied by `texLinebreakDOM` from a specific element. ``` -------------------------------- ### Access Line Properties with TexLinebreak Class Source: https://context7.com/egilll/tex-linebreak2/llms.txt The TexLinebreak class provides a Line object for each line of text, exposing properties like plaintext, idealWidth, adjustmentRatio, and positionedItems. Use this to access detailed information about each line for rendering. ```typescript import { TexLinebreak } from "tex-linebreak2"; const t = new TexLinebreak( "Pack my box with five dozen liquor jugs quickly.", { lineWidth: 25, measureFn: (w) => w.length } ); t.lines.forEach((line, lineIndex) => { console.log(`\n--- Line ${lineIndex} ---`); console.log(` plaintext: "${line.plaintext}"`); console.log(` idealWidth: ${line.idealWidth}`); console.log(` adjustmentRatio: ${line.adjustmentRatio.toFixed(3)}`); console.log(` endsWithHyphen: ${line.endsWithSoftHyphen}`); line.positionedItems.forEach((item) => { if (item.type === "box" && "text" in item) { process.stdout.write(item.text as string); } else if (item.type === "glue") { process.stdout.write(" ".repeat(Math.round(item.adjustedWidth))); } }); console.log(); }); ``` -------------------------------- ### TexLinebreak Properties Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md The TexLinebreak instance provides several properties to access the results of the line breaking process. ```APIDOC ## TexLinebreak Properties ### Description Access the results of the line breaking algorithm through these properties. ### Properties - `lines` (Array): An array of `Line` objects, each describing a formatted line of text. - `plaintext` (string): The input text formatted as plain text with newline characters. - `items` (Array): The input text represented as an array of boxes, glues, and penalties. - `breakpoints` (Array): An array containing the indices of items that mark the end of a line. ``` -------------------------------- ### Minimize Whitespace with findOptimalWidth Source: https://context7.com/egilll/tex-linebreak2/llms.txt The findOptimalWidth function iteratively reduces lineWidth to find the most compact layout without adding extra lines. This is ideal for headings or captions where trailing whitespace should be minimized. It can be activated automatically within TexLinebreak or called manually. ```typescript import { TexLinebreak, findOptimalWidth } from "tex-linebreak2"; const paragraph = new TexLinebreak( "Breaking paragraphs into lines of optimal width.", { lineWidth: 400, measureFn: (w) => w.length * 8, // 8px per character findOptimalWidth: true, // activate inside TexLinebreak automatically } ); // Or call manually across multiple paragraphs: const p1 = new TexLinebreak("First paragraph text.", { lineWidth: 400, measureFn: (w) => w.length * 8 }); const p2 = new TexLinebreak("Second paragraph text.", { lineWidth: 400, measureFn: (w) => w.length * 8 }); findOptimalWidth([p1, p2]); console.log(p1.plaintext); console.log(p2.plaintext); ``` -------------------------------- ### `resetDOMJustification(element)` Source: https://context7.com/egilll/tex-linebreak2/llms.txt Reverses DOM modifications made by `texLinebreakDOM`, restoring the element to its original state. ```APIDOC ## `resetDOMJustification(element)` ### Description Reverses all DOM mutations made by a prior `texLinebreakDOM` call on the given element: removes inserted `
` tags and wrapper `` elements, re-joins split text nodes via `normalize()`, and resets `whiteSpace` style to its initial value. ### Parameters - **element** (HTMLElement) - The DOM element to reset. ### Request Example ```typescript import { texLinebreakDOM, resetDOMJustification } from "tex-linebreak2"; const el = document.getElementById("article-body")!; // Apply justification await texLinebreakDOM(el, { justify: true }); // Later, undo it (e.g., before removing the element or switching layout) resetDOMJustification(el); // The element is now back to its original state console.log(el.style.whiteSpace); // "" ``` ``` -------------------------------- ### Apply Line Breaking to HTML Elements with texLinebreakDOM Source: https://context7.com/egilll/tex-linebreak2/llms.txt Use texLinebreakDOM to apply Knuth-Plass line breaking to HTML elements. It measures text via canvas and can automatically reflow on window resize. Configure alignment, hyphenation, and justification behavior. ```typescript import { texLinebreakDOM } from "tex-linebreak2"; // Apply to all

elements (CSS selector) await texLinebreakDOM("p"); // Apply to a specific element with custom options const article = document.querySelector("article"); await texLinebreakDOM(article, { align: "left", // "left" | "right" | "center" hangingPunctuation: true, // let punctuation hang into the margin updateOnWindowResize: true, // re-run on resize (default: true) renderLineAsUnjustifiedIfAdjustmentRatioExceeds: 2, }); // Apply to a NodeList with ragged-right alignment await texLinebreakDOM(document.querySelectorAll(".content p"), { justify: false, // triggers the raggedAlignment preset }); // Undo all justification applied to an element import { resetDOMJustification } from "tex-linebreak2"; resetDOMJustification(document.querySelector("#my-paragraph")); ``` -------------------------------- ### Convert Text to Items with splitTextIntoItems Source: https://context7.com/egilll/tex-linebreak2/llms.txt Utilize `splitTextIntoItems` to transform plain text into Box, Glue, and Penalty items. This function handles Unicode line-breaking, soft hyphens, non-breaking spaces, and custom break patterns. ```typescript import { splitTextIntoItems } from "tex-linebreak2"; const items = splitTextIntoItems( "Hello, world! This is a test\u00ADstring with a soft\u00ADhyphen.", { measureFn: (word) => word.length, hangingPunctuation: true, softHyphenPenalty: 50, neverBreakInside: /\{.+?\}/g, // never break inside curly braces neverBreakAfter: ["e.g.", "-"], // never break after these strings } ); items.forEach((item) => { if (item.type === "box") { console.log(`box: "${("text" in item && item.text) || ""}" w=${item.width}`); } else if (item.type === "glue") { console.log(`glue: w=${item.width} stretch=${item.stretch} shrink=${item.shrink}`); } else { console.log(`penalty: cost=${item.cost} flagged=${item.flagged}`); } }); ``` -------------------------------- ### Line Object Source: https://github.com/egilll/tex-linebreak2/blob/master/README.md A Line object represents a single line of text after the breaking process, containing information about its content and layout. ```APIDOC ## Line Object ### Description Represents a single line of output from the text breaking process. ### Properties - `positionedItems` (Array): An array of items (boxes, glues, penalties) relevant for rendering the line, including their positioning information (`xOffset`, `adjustedWidth`). - `plaintext` (string): The plain text representation of the line. ``` -------------------------------- ### Reset DOM Modifications with resetDOMJustification Source: https://context7.com/egilll/tex-linebreak2/llms.txt The resetDOMJustification function reverses DOM mutations made by texLinebreakDOM. It removes inserted
tags and elements, normalizes text nodes, and resets the whiteSpace style. Use this to revert the element to its original state. ```typescript import { texLinebreakDOM, resetDOMJustification } from "tex-linebreak2"; const el = document.getElementById("article-body")!; // Apply justification await texLinebreakDOM(el, { justify: true }); // Later, undo it (e.g., before removing the element or switching layout) resetDOMJustification(el); // The element is now back to its original state console.log(el.style.whiteSpace); // "" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.