### Parse HWPEQ to AST using unified Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt This snippet demonstrates how to parse HWPEQ markup into an Abstract Syntax Tree (AST) using the unified processor with the `hwpeqParse` plugin. It shows the basic setup and the structure of the resulting AST for a complex equation. Dependencies include `unified` and `unified-hwpeq`. ```typescript import { unified } from 'unified'; import { hwpeqParse } from 'unified-hwpeq'; // Create processor with parse plugin const processor = unified().use(hwpeqParse); // Parse complex equation const ast = processor.parse('1 over 2 + sqrt{x^2 + 1}'); console.log(ast); // Output: // { // type: 'root', // children: [ // { // type: 'fraction', // numerator: { type: 'number', value: '1' }, // denominator: { type: 'number', value: '2' } // }, // { type: 'symbol', value: '+' }, // { // type: 'sqrt', // radicand: { // type: 'group', // children: [ // { type: 'superscript', base: {...}, superscript: {...} }, // ... // ] // } // } // ] // } ``` -------------------------------- ### Convert HWPEQ to LaTeX using unified Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt This snippet shows how to convert HWPEQ equations to LaTeX format using the `unified` processor with both `hwpeqParse` and `hwpeqToLatex` plugins. It includes examples for basic conversion, and advanced usage with display mode and dollar wrapping options. The `processSync` method is used for immediate conversion. ```typescript import { unified } from 'unified'; import { hwpeqParse, hwpeqToLatex } from 'unified-hwpeq'; // Basic conversion const processor = unified() .use(hwpeqParse) .use(hwpeqToLatex); const latex = processor.processSync('1 over 2').toString(); console.log(latex); // '\frac{1}{2}' // With display mode and dollar wrapping const displayProcessor = unified() .use(hwpeqParse) .use(hwpeqToLatex, { displayMode: true, wrap: 'dollar' }); const wrapped = displayProcessor.processSync('sum_{i=1}^n a_i').toString(); console.log(wrapped); // '$$\sum_{i=1}^{n}a_{i}$$' // Complex expressions const complex = processor.processSync( '{-b plusminus sqrt{b^2 - 4ac}} over {2a}' ).toString(); console.log(complex); // '\frac{-b\pm\sqrt{b^{2}-4ac}}{2a}' ``` -------------------------------- ### Direct HWPEQ Parsing Function Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt This snippet provides direct functions (`parse`) from `unified-hwpeq` to parse HWPEQ strings into AST nodes without requiring a full unified processor setup. It illustrates parsing various equation types like fractions, summations, integrals, and matrices. Each call returns a `Root` node representing the parsed expression tree. ```typescript import { parse } from 'unified-hwpeq'; // Simple fraction const ast1 = parse('a over b'); // Summation with limits const ast2 = parse('sum_{i=1}^n a_i'); // Integral expression const ast3 = parse('int_0^inf e^{-x^2} dx'); // Matrix notation const ast4 = parse('bmatrix{1 & 2 # 3 & 4}'); // Each returns a Root node containing the parsed expression tree ``` -------------------------------- ### Convert AST to HWPEQ using unified Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt This snippet illustrates how to convert an Abstract Syntax Tree (AST) back to HWPEQ markup using the `unified` processor with `hwpeqParse` and `hwpeqStringify` plugins. It demonstrates a round-trip conversion scenario and the use of `processSync` for immediate stringification. Dependencies include `unified` and `unified-hwpeq`. ```typescript import { unified } from 'unified'; import { hwpeqParse, hwpeqStringify } from 'unified-hwpeq'; // Round-trip conversion const processor = unified() .use(hwpeqParse) .use(hwpeqStringify); const result = processor.processSync('a over b + c over d').toString(); console.log(result); // 'a over b + c over d' // Direct function usage import { parse, stringify } from 'unified-hwpeq'; const ast = parse('sqrt{x}'); const hwpeq = stringify(ast); console.log(hwpeq); // 'sqrt {x}' ``` -------------------------------- ### Create AST Nodes Programmatically with unified-hwpeq Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt Allows programmatic creation of AST nodes using factory functions, avoiding the need to parse strings. Supports creating various node types like fractions, powers, and expressions, and converting them back to LaTeX. ```typescript import { createRoot, createText, createNumber, createGroup, createFraction, createSqrt, createSuperscript, createSubscript, createSpace, toLatex } from 'unified-hwpeq'; // Build a fraction: a/b const fraction = createFraction( createText('a'), createText('b') ); // Build x^2 const power = createSuperscript( createText('x'), createNumber('2') ); // Build complete expression: sqrt(x^2 + 1) const expr = createRoot([ createSqrt( createGroup([ power, createSpace('normal'), createText('+'), createSpace('normal'), createNumber('1') ]) ) ]); // Convert to LaTeX console.log(toLatex(expr)); // '\sqrt{x^{2} + 1}' ``` -------------------------------- ### Traverse AST with unified-hwpeq Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt Provides functions to parse HWPEQ expressions into an Abstract Syntax Tree (AST) and traverse it using visitor functions. Supports visiting all nodes, specific types, controlling traversal, and finding nodes. ```typescript import { parse, visit, findAll, find } from 'unified-hwpeq'; const ast = parse('a over b + c over d + sqrt{e over f}'); // Visit all nodes visit(ast, (node) => { console.log(node.type); }); // Output: root, fraction, text, text, symbol, fraction, ... // Visit specific node types visit(ast, 'fraction', (node) => { console.log('Found fraction:', node.numerator, '/', node.denominator); }); // Control traversal visit(ast, (node) => { if (node.type === 'group') { return 'skip'; // Skip children of groups } if (node.type === 'fraction') { return false; // Stop traversal } }); // Find all fractions const fractions = findAll(ast, 'fraction'); console.log(`Total fractions: ${fractions.length}`); // Find first match const firstSqrt = find(ast, 'sqrt'); console.log(firstSqrt?.type); // 'sqrt' ``` -------------------------------- ### Direct HWPEQ to LaTeX Conversion Function Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt This snippet demonstrates the direct `toLatex` function from `unified-hwpeq` for converting AST nodes (obtained via `parse`) to LaTeX strings without a `unified` pipeline. It shows single conversions and batch conversions of multiple equations, highlighting the flexibility of this approach. ```typescript import { parse, toLatex } from 'unified-hwpeq'; // Parse and convert in one go const ast = parse('int_0^1 x^2 dx'); const latex = toLatex(ast); console.log(latex); // '\int_{0}^{1}x^{2}dx' // Multiple conversions const equations = [ 'sqrt{x^2 + y^2}', 'lim_{x->0} {sin x} over x', 'hat x + bar y + vec z' ]; for (const hwpeq of equations) { const result = toLatex(parse(hwpeq)); console.log(`${hwpeq} → ${result}`); } // sqrt{x^2 + y^2} → \sqrt{x^{2}+y^{2}} // lim_{x->0} {sin x} over x → \lim_{x\to 0}\frac{\sin x}{x} // hat x + bar y + vec z → \hat{x}+\bar{y}+\vec{z} ``` -------------------------------- ### Inspect and Debug AST with unified-hwpeq Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt Provides tools for inspecting and debugging AST structures generated by unified-hwpeq. Includes functions to pretty-print the AST and retrieve structural statistics. ```typescript import { parse, inspect, getStats } from 'unified-hwpeq'; const ast = parse('sum_{i=1}^n {a_i over i}'); // Pretty print AST structure console.log(inspect(ast)); // Output: // root // sum // group // fraction // subscript // text: "a" // text: "i" // text: "i" // Get statistics const stats = getStats(ast); console.log(stats); // { // totalNodes: 15, // nodeTypes: { // root: 1, // sum: 1, // group: 2, // fraction: 1, // subscript: 2, // text: 8 // }, // depth: 5 // } ``` -------------------------------- ### Error Handling for HWPEQ Parsing Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt Gracefully handle parsing errors and invalid syntax when using the 'unified-hwpeq' library. This includes catching 'ParseError' exceptions, which provide details about the error's position and message. It also demonstrates how to use strict mode with a custom 'Parser' instance to reject unknown commands. ```typescript import { parse, ParseError, Parser } from 'unified-hwpeq'; try { const ast = parse('over'); // Invalid: missing numerator } catch (error) { if (error instanceof ParseError) { console.error(`Parse error at line ${error.position.line}, col ${error.position.column}`); console.error(error.message); console.error('Token:', error.token); } } // Strict mode for unknown commands const strictParser = new Parser({ strict: true }); try { strictParser.parse('unknowncommand{x}'); } catch (error) { console.error('Strict mode rejected unknown command'); } ``` -------------------------------- ### Convert LaTeX to HWPEQ using unified-hwpeq Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt Converts LaTeX mathematical expressions into HWPEQ format. It supports basic conversions, Greek letters, symbols, and matrices. Debugging output is available. ```typescript import { fromLatex } from 'unified-hwpeq'; // Basic conversions console.log(fromLatex('\frac{1}{2}')); // '1 over 2' console.log(fromLatex('\sqrt{x}')); // 'sqrt {x}' console.log(fromLatex('\sqrt[3]{x}')); // '^{3} sqrt {x}' // Greek letters and symbols console.log(fromLatex('\alpha + \beta')); // 'alpha + beta' console.log(fromLatex('x \leq y')); // 'x leq y' console.log(fromLatex('\sum_{i=1}^{n}')); // 'sum_{i=1}^{n}' // Matrices const matrixLatex = '\begin{bmatrix}1 & 2 \\ 3 & 4\end{bmatrix}'; console.log(fromLatex(matrixLatex)); // 'bmatrix{1 & 2 # 3 & 4}' // With debug output const hwpeq = fromLatex('\frac{a}{b}', { debug: true }); // Logs: LaTeX→HWPEQ: \frac{a}{b} → {a} over {b} ``` -------------------------------- ### Type Guards and Utilities for unified-hwpeq AST Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt Safely check node types and access type-specific properties within the unified-hwpeq Abstract Syntax Tree (AST). This includes checking for root, parent, literal, and specific node types like matrices, fractions, and text. It utilizes imported type guard functions from 'unified-hwpeq' and the 'visit' utility for AST traversal. ```typescript import { isParent, isLiteral, isRoot, isText, isFraction, isMatrix, parse, visit } from 'unified-hwpeq'; const ast = parse('matrix{a & b # c & d}'); // Type checking if (isRoot(ast)) { console.log('Root has', ast.children.length, 'children'); } // Check for parent nodes (nodes with children) visit(ast, (node) => { if (isParent(node)) { console.log(`${node.type} has ${node.children.length} children`); } if (isLiteral(node)) { console.log(`${node.type} value: ${node.value}`); } }); // Specific type guards const matrixNode = ast.children[0]; if (isMatrix(matrixNode)) { console.log('Matrix variant:', matrixNode.variant); console.log('Rows:', matrixNode.rows.length); } ``` -------------------------------- ### Parse and Convert Complex HWPEQ Syntax to LaTeX Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt Parse and convert advanced HWPEQ syntax, including matrices with different bracket styles, piecewise functions (cases), accents, decorations, large delimiters, multiple integrals, and Korean text within equations, into LaTeX format. This functionality is achieved using the 'parse' and 'toLatex' functions from 'unified-hwpeq'. ```typescript import { parse, toLatex } from 'unified-hwpeq'; // Matrix with different bracket styles const pmatrix = parse('pmatrix{1 & 2 & 3 # 4 & 5 & 6}'); console.log(toLatex(pmatrix)); // '\begin{pmatrix}1 & 2 & 3 \\ 4 & 5 & 6\end{pmatrix}' // Cases (piecewise functions) const cases = parse('cases{x if x>0 # -x if x<0}'); console.log(toLatex(cases)); // '\begin{cases}x if x>0 \\ -x if x<0\end{cases}' // Accents and decorations const accents = parse('hat x + bar y + vec z + tilde w'); console.log(toLatex(accents)); // '\hat{x}+\bar{y}+\vec{z}+\tilde{w}' // Large delimiters const delim = parse('LEFT( x over y RIGHT)'); console.log(toLatex(delim)); // '\left(x over y\right)' // Multiple integrals const doubleInt = parse('dint_D f(x,y) dx dy'); console.log(toLatex(doubleInt)); // '\iint_{D}f(x,y)dxdy' // Korean text in equations const korean = parse('삼각형~넓이 = {1 over 2} times 밑변 times 높이'); console.log(toLatex(korean)); // '\mathrm{삼각형} \mathrm{넓이}=\frac{1}{2}\times\mathrm{밑변}\times\mathrm{높이}' ``` -------------------------------- ### Transform AST Nodes with unified-hwpeq Source: https://context7.com/jiwonme/unified-hwpeq/llms.txt Enables manipulation of ASTs by mapping, filtering, and replacing nodes. Supports transforming all nodes, specific types, replacing existing nodes, removing nodes, and filtering the AST. ```typescript import { parse, map, mapWhere, replace, remove, filter } from 'unified-hwpeq'; const ast = parse('a over b + x^2'); // Transform all text nodes to uppercase const upperAst = map(ast, (node) => { if (node.type === 'text') { return { ...node, value: node.value.toUpperCase() }; } return node; }); // Transform specific node types const scaled = mapWhere(ast, 'fraction', (frac) => ({ ...frac, data: { scaled: true } })); // Replace fractions with different structure const replaced = replace(ast, 'fraction', (frac) => ({ type: 'text', value: `(${frac.numerator}/${frac.denominator})` })); // Remove all superscripts const noSuperscripts = remove(ast, 'superscript'); // Filter - keep only specific nodes const onlyFractions = filter(ast, (node) => node.type === 'root' || node.type === 'fraction' ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.