### Accent Commands in LaTeX Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/README.md Examples of commands for applying accents to characters in LaTeX. ```LaTeX \hat, \bar, \vec, \tilde, \dot, \ddot ``` -------------------------------- ### Swift: LaTeX Environments Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/GETTING_STARTED.md Examples of using LaTeX environments like 'matrix', 'align', and 'cases' for structured mathematical content. ```swift label.latex = "\\begin{matrix} a & b \\ c & d \\end{matrix}" ``` ```swift label.latex = "\\begin{align} x &= 1 \\ y &= 2 \\end{align}" ``` ```swift label.latex = "\\begin{cases} x & \\text{if } x > 0 \\ -x & \\text{if } x < 0 \\end{cases}" ``` -------------------------------- ### MathFont Usage Examples Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/types.md Demonstrates how to obtain Core Graphics and Core Text font objects from the MathFont enum cases. ```swift let font = MathFont.latinModernFont.cgFont() let ctFont = MathFont.xitsFont.ctFont(withSize: 24) ``` -------------------------------- ### Swift: Simple Arithmetic Example Source: https://github.com/mgriebling/swiftmath/blob/main/README.md A good use case for SwiftMath, showing clean breaks between operators for simple arithmetic sequences. ```swift label.latex = "5+10+15+20+25+30+35+40+45+50" label.preferredMaxLayoutWidth = 150 // ✅ Breaks between operators cleanly ``` -------------------------------- ### MTFontStyle Usage Example Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/types.md Illustrates setting the font style for a math atom to bold or calligraphic. ```swift atom.fontStyle = .bold atom.fontStyle = .caligraphic ``` -------------------------------- ### MTTextAlignment Usage Example Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/types.md Shows how to apply a specific horizontal text alignment to a math label or image. ```swift label.textAlignment = .center ``` -------------------------------- ### Swift: Discriminant Formula Example Source: https://github.com/mgriebling/swiftmath/blob/main/README.md An excellent use case for SwiftMath, demonstrating natural breaking at good points between atoms for the discriminant formula. ```swift label.latex = "\text{Calculer le discriminant }\Delta=b^{2}-4ac\text{ avec }a=1\text{, }b=-1\text{, }c=-5" label.preferredMaxLayoutWidth = 235 // ✅ Breaks naturally at good points between atoms ``` -------------------------------- ### MTMathUILabelMode Usage Example Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/types.md Demonstrates how to set the rendering mode for a math label to control its display size and layout. ```swift label.labelMode = .display // Full-size rendering label.labelMode = .text // Compact inline rendering ``` -------------------------------- ### Basic MTMathUILabel Usage Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathUILabel.md Demonstrates the basic setup for an MTMathUILabel. Import SwiftMath, create an instance, set the LaTeX string, font size, and text color, then add it to a view. ```swift import SwiftMath let label = MTMathUILabel() label.latex = "E = mc^2" label.fontSize = 24 label.textColor = .black view.addSubview(label) ``` -------------------------------- ### Build Fraction Programmatically Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Constructs a fraction using MTMathAtomFactory by programmatically creating MTMathList objects for the numerator and denominator. This example builds the fraction 1/2. ```swift // Build the fraction 1/2 let one = MTMathList() one.add(MTMathAtomFactory.atom(forCharacter: "1")!) let two = MTMathList() two.add(MTMathAtomFactory.atom(forCharacter: "2")!) let fraction = MTMathAtomFactory.fraction(withNumerator: one, denominator: two) ``` -------------------------------- ### Swift: Single Display Equation Example Source: https://github.com/mgriebling/swiftmath/blob/main/README.md An alternative approach for complex expressions in SwiftMath, treating them as a single display equation by setting `preferredMaxLayoutWidth` to 0 to disable breaking. ```swift // Instead of trying to break this: label.latex = "x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}" // Consider it as a single display equation without width constraint label.preferredMaxLayoutWidth = 0 // No breaking ``` -------------------------------- ### Swift: Inline Fractions Example Source: https://github.com/mgriebling/swiftmath/blob/main/README.md An excellent use case for SwiftMath, where fractions remain inline if they fit within the layout width, allowing for natural breaks. ```swift label.latex = "a+\frac{1}{2}+b+\frac{3}{4}+c" label.preferredMaxLayoutWidth = 200 // ✅ Fractions stay inline when they fit! // Breaks: "a + ½ + b" on line 1, "+ ¾ + c" on line 2 ``` -------------------------------- ### Greek Commands in LaTeX Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/README.md Examples of common Greek letter commands used in LaTeX for mathematical notation. ```LaTeX \alpha, \beta, \Gamma, \Delta ``` -------------------------------- ### Swift Code Example for Widow/Orphan Control Problem Source: https://github.com/mgriebling/swiftmath/blob/main/MULTILINE_IMPLEMENTATION_NOTES.md Illustrates a potential issue where a single atom might end up alone on a line, impacting readability. This highlights the need for minimum atoms per line constraints. ```swift // Last line might just be: "+ e" ``` -------------------------------- ### Optimizing Performance with Batch Updates Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/GETTING_STARTED.md Improve performance by batching property updates. This example disables animations, sets multiple label properties, and then re-enables animations. ```swift // Line wrapping is slower - only use when needed label.preferredMaxLayoutWidth = 0 // Disable wrapping if not needed // Batch updates UIView.setAnimationsEnabled(false) label.latex = "..." label.fontSize = 24 label.textColor = .blue UIView.setAnimationsEnabled(true) ``` -------------------------------- ### Create GitHub Pull Request Source: https://github.com/mgriebling/swiftmath/blob/main/CLAUDE.md Example command for creating a GitHub pull request using the GitHub CLI. Ensure the PR body is in a separate file for clean formatting. ```bash gh pr create --repo mgriebling/SwiftMath --base main --head ChrisGVE:dev --title "..." --body-file tmp/pr_body.md ``` -------------------------------- ### macOS MTMathUILabel Setup Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/GETTING_STARTED.md Set up MTMathUILabel for macOS. Note that NSView compatibility is available on macOS 12 and later. ```swift import SwiftMath let label = MTMathUILabel() // NSView compatible on macOS 12+ ``` -------------------------------- ### Greedy Breaking Example in Swift Source: https://github.com/mgriebling/swiftmath/blob/main/MULTILINE_IMPLEMENTATION_NOTES.md Illustrates a potential issue with the greedy breaking algorithm where an immediate break might not be optimal. The algorithm doesn't look ahead to find better break points. ```swift "abc + defgh" ``` -------------------------------- ### Swift: Inline Radicals Example Source: https://github.com/mgriebling/swiftmath/blob/main/README.md An excellent use case for SwiftMath, where radicals remain inline if they fit within the layout width, enabling natural line breaks. ```swift label.latex = "x+\sqrt{2}+y+\sqrt{3}+z" label.preferredMaxLayoutWidth = 150 // ✅ Radicals stay inline when they fit! // Example: "x + √2 + y" on line 1, "+ √3 + z" on line 2 ``` -------------------------------- ### Get Font by Name and Size Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieves a specific mathematical font by its name and desired size. Ensure SwiftMath is imported before use. ```swift import SwiftMath let manager = MTFontManager.fontManager let font = manager.font(withName: "xits-math", size: 24) ``` -------------------------------- ### Basic Typesetting with MTTypesetter Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTTypesetter.md Demonstrates how to create a display line for a given math list, font, and style. Shows how to retrieve and print the dimensions of the typeset line. ```swift import SwiftMath let mathList = MTMathListBuilder.build(fromString: "E = mc^2") let font = MTFontManager.fontManager.defaultFont let display = MTTypesetter.createLineForMathList( mathList, font: font, style: .display ) if let display = display { print("Width: \(display.width)") print("Ascent: \(display.ascent)") print("Descent: \(display.descent)") } ``` -------------------------------- ### Get MTFont Size Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFont.md Retrieves the size of the MTFont in points. This is a read-only property. ```swift public var fontSize: CGFloat { get } ``` ```swift let size = font.fontSize // e.g., 20.0 ``` -------------------------------- ### Initialization Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathList.md Creates an empty math list or a copy of an existing one. ```APIDOC ## Initialization ### init() Creates an empty math list. **Example:** ```swift let mathList = MTMathList() ``` ### init(_:) Creates a copy of another math list. | Parameter | Type | Description | |-----------|------|-------------| | list | MTMathList? | The list to copy, or nil | **Example:** ```swift let copy = MTMathList(originalList) ``` ``` -------------------------------- ### Get Garamond Math Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the Garamond Math font at a specified size. ```swift public func garamondMathFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.garamondMathFont(withSize: 20) ``` -------------------------------- ### Get Euler Math Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the Euler Math font at a specified size. ```swift public func eulerFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.eulerFont(withSize: 20) ``` -------------------------------- ### Get Asana Math Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the Asana Math font at a specified size. ```swift public func asanaFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.asanaFont(withSize: 20) ``` -------------------------------- ### Build and Test Swift Package Source: https://github.com/mgriebling/swiftmath/blob/main/CLAUDE.md Commands for building the Swift package and running tests. Use '--filter' to target specific tests or classes. ```bash swift build ``` ```bash swift test ``` ```bash swift test --filter MTMathListBuilderTests ``` ```bash swift test --filter MTMathListBuilderTests.testBuilder ``` -------------------------------- ### Get KpMath-Sans Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the KpMath-Sans font, a sans-serif variant, at a specified size. ```swift public func kpMathSansFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.kpMathSansFont(withSize: 20) ``` -------------------------------- ### Ensure Matching \end for \begin Environments Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/errors.md Use this snippet to verify that every \begin{...} command has a matching \end{...} command with the same environment name. ```swift // Unclosed environment label.latex = "\\begin{matrix} 1 & 2" // Missing \\end{matrix} // Wrong environment name in \end label.latex = "\\begin{matrix}...\\end{array}" // Names don't match ``` -------------------------------- ### Get KpMath-Light Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the KpMath-Light font, a lighter weight variant, at a specified size. ```swift public func kpMathLightFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.kpMathLightFont(withSize: 22) ``` -------------------------------- ### Greek Alphabet Symbols in LaTeX Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/README.md Examples of Greek alphabet characters available directly as symbols in LaTeX. ```LaTeX \alpha, \beta, \gamma, \Delta, \Omega ``` -------------------------------- ### Inline Equation Rendering with Fractions Source: https://github.com/mgriebling/swiftmath/blob/main/MULTILINE_IMPLEMENTATION_NOTES.md Demonstrates how simple equations with operators and fractions are now rendered inline, staying on one to two lines. This is useful for displaying mathematical content within regular text flow. ```swiftmath a + \frac{1}{2} + \sqrt{3} + b ``` -------------------------------- ### init(frame:) Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathUILabel.md Initializes a new MTMathUILabel with the specified frame. This is the standard initializer for creating a view with a given size and position. ```APIDOC ## init(frame:) ### Description Initializes a new MTMathUILabel with the specified frame. ### Method `init` ### Parameters #### Path Parameters - **frame** (CGRect) - Required - The frame rectangle for the view ``` -------------------------------- ### Get Lete Sans Math Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the Lete Sans Math font at a specified size. ```swift public func leteSansFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.leteSansFont(withSize: 20) ``` -------------------------------- ### Typesetting with Line Wrapping Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTTypesetter.md Illustrates how to create a display for a math list with a specified maximum width, enabling line wrapping for long expressions. Requires a font and style. ```swift let latex = "a + b + c + d + e + f + g + h" let mathList = MTMathListBuilder.build(fromString: latex) let display = MTTypesetter.createDisplayForMathList( mathList, font: font, style: .display, width: 150 // Wrap at 150pt ) ``` -------------------------------- ### Get Libertinus Math Regular Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the Libertinus Math Regular font at a specified size. ```swift public func libertinusRegularFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.libertinusRegularFont(withSize: 20) ``` -------------------------------- ### Get Fira Math Regular Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the Fira Math Regular font at a specified size. ```swift public func firaRegularFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.firaRegularFont(withSize: 20) ``` -------------------------------- ### Ensure Matching \begin and \end Commands Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/errors.md Use this snippet to verify that \end{...} commands correctly match their corresponding \begin{...} commands in name and nesting order. ```swift // Orphan \end label.latex = "\\end{matrix}" // No \\begin // Wrong nesting order label.latex = "\\begin{array}...\\end{matrix}" // Names don't match ``` -------------------------------- ### getInterElementSpaceArrayIndexForType Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTTypesetter.md Gets the index in the spacing matrix for a given atom type, distinguishing between left and right positioning. ```APIDOC ## getInterElementSpaceArrayIndexForType ### Description Gets the spacing matrix index for an atom type (distinguishes left vs right position). ### Method Internal ### Parameters - `_:` (type) - Description - `row:` (type) - Description ### Returns - `Int` - The spacing matrix index. ``` -------------------------------- ### Matrix Environments in LaTeX Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/README.md Environments for creating matrices and arrays with different bracket styles. ```LaTeX matrix, pmatrix, bmatrix, vmatrix ``` -------------------------------- ### Initialize Empty MTMathList Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathList.md Creates an empty math list. Use this when starting a new mathematical expression. ```swift public init() ``` ```swift let mathList = MTMathList() ``` -------------------------------- ### Basic SwiftMath Usage Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/README.md Initialize an MTMathUILabel, set its LaTeX string, and add it to a view to display a rendered equation. ```swift import SwiftMath // Create and render let label = MTMathUILabel() label.latex = "E = mc^2" view.addSubview(label) ``` -------------------------------- ### Get XITS Math Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the XITS Math font, a Times-based serif font, at a specified size. ```swift public func xitsFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.xitsFont(withSize: 24) ``` -------------------------------- ### Get Noto Sans Math Regular Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the Noto Sans Math Regular font at a specified size. ```swift public func notoSansRegularFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.notoSansRegularFont(withSize: 20) ``` -------------------------------- ### SwiftMath Project File Structure Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/README.md Overview of the directory and file organization within the SwiftMath project. This structure separates concerns like font loading, rendering, and tokenization. ```tree SwiftMath/ ├── Sources/SwiftMath/ │ ├── MathBundle/ # Font loading │ │ ├── MathFont.swift │ │ ├── MTFontMathTableV2.swift │ │ ├── MTFontV2.swift │ │ └── MathImage.swift │ ├── MathRender/ # Rendering engine │ │ ├── MTMathUILabel.swift │ │ ├── MTMathList.swift │ │ ├── MTMathListBuilder.swift │ │ ├── MTMathListDisplay.swift │ │ ├── MTMathAtomFactory.swift │ │ ├── MTTypesetter.swift │ │ ├── MTFont.swift │ │ ├── MTFontManager.swift │ │ ├── MTConfig.swift │ │ ├── RWLock.swift │ │ └── Tokenization/ # Line breaking │ │ ├── MTAtomTokenizer.swift │ │ ├── MTDisplayGenerator.swift │ │ └── ... │ └── mathFonts.bundle/ # Bundled fonts │ ├── *.otf # Font files │ └── *.plist # Math metrics └── Tests/ └── SwiftMathTests/ # Unit tests ``` -------------------------------- ### Get TeX Gyre Termes Math Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the TeX Gyre Termes Math font at a specified size. ```swift public func termesFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.termesFont(withSize: 18) ``` -------------------------------- ### Build Equations Programmatically Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/GETTING_STARTED.md Construct a MathList and MTMathAtoms programmatically to create complex equations. Use MTTypesetter to render the MathList. ```swift let mathList = MTMathList() let x = MTMathAtom(type: .variable, value: "x") let exp = MTMathList() exp.add(MTMathAtom(type: .number, value: "2")) x.superScript = exp mathList.add(x) let display = MTTypesetter.createLineForMathList( mathList, font: MTFontManager.fontManager.defaultFont, style: .display ) ``` -------------------------------- ### Get Latin Modern Math Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve the Latin Modern Math font at a specified size. This is the default font. ```swift public func latinModernFont(withSize size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.latinModernFont(withSize: 20) ``` -------------------------------- ### Dynamically Build Quadratic Formula Expression Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathList.md Demonstrates the dynamic construction of a complex mathematical expression, the quadratic formula, using MTMathList and its components like MTFraction and MTRadical. ```swift func buildQuadraticFormula() -> MTMathList { let mathList = MTMathList() // x = mathList.add(MTMathAtom(type: .variable, value: "x")) mathList.add(MTMathAtom(type: .relation, value: "=")) // (-b ± √(b² - 4ac)) / 2a let numerator = MTMathList() // Build numerator: -b ± √(b² - 4ac) numerator.add(MTMathAtom(type: .unaryOperator, value: "−")) numerator.add(MTMathAtom(type: .variable, value: "b")) numerator.add(MTMathAtom(type: .binaryOperator, value: "±")) // √(b² - 4ac) let radical = MTRadical() let radicand = MTMathList() // ... build radicand radical.radicand = radicand numerator.add(radical) // Denominator: 2a let denominator = MTMathList() denominator.add(MTMathAtom(type: .number, value: "2")) denominator.add(MTMathAtom(type: .variable, value: "a")) // Full fraction let fraction = MTFraction() fraction.numerator = numerator fraction.denominator = denominator mathList.add(fraction) return mathList } ``` -------------------------------- ### Get Font by Name and Size Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieve a specific font by its name and desired size. Returns nil if the font cannot be loaded. ```swift public func font(withName name: String, size: CGFloat) -> MTFont? ``` ```swift let font = MTFontManager.fontManager.font(withName: "xits-math", size: 24) ``` -------------------------------- ### Look Up Delimiter Name Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Finds the LaTeX name associated with a given delimiter character. This example looks up the name for the ceiling symbol. ```swift // Find the name for the ceiling symbol if let delimName = MTMathAtomFactory.delimValueToName["⌈"] { print("Delimiter: \\(delimName)") // \lceil } ``` -------------------------------- ### Initialize MTFontManager Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Initializes a new font manager. Direct initialization is not recommended; use the `fontManager` static property instead. ```swift public init() ``` -------------------------------- ### Use Commands Within Appropriate Environments Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/errors.md Use this snippet to ensure commands like \\ (newline) and & (column separator) are used only within their supported environments, such as tables or arrays. ```swift // \\ used outside a table environment label.latex = "a \\ b" // \\ only valid in table/array // & used outside table label.latex = "a & b" // & only valid in table ``` -------------------------------- ### Create Expression with Fraction: 1/2 + x Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathList.md Constructs a mathematical expression involving a fraction '1/2' and addition with 'x'. Demonstrates the use of MTFraction for creating fractional elements. ```swift let mathList = MTMathList() // Build fraction 1/2 let fraction = MTFraction() fraction.numerator = MTMathList() fraction.numerator?.add(MTMathAtom(type: .number, value: "1")) fraction.denominator = MTMathList() fraction.denominator?.add(MTMathAtom(type: .number, value: "2")) mathList.add(fraction) // + mathList.add(MTMathAtom(type: .binaryOperator, value: "+")) // x mathList.add(MTMathAtom(type: .variable, value: "x")) ``` -------------------------------- ### Get All Supported LaTeX Symbol Names Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Retrieves an array of all supported LaTeX symbol names. This can be used to iterate through or count the available mathematical symbols. ```swift let allSymbols = MTMathAtomFactory.supportedLatexSymbolNames print("Total symbols: \(allSymbols.count)") ``` -------------------------------- ### Get Canonical Alias for LaTeX Command Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the canonical name for a given LaTeX command alias. This is useful for normalizing LaTeX commands before processing. ```swift if let canonical = MTMathAtomFactory.aliases["le"] { print(canonical) // "leq" } ``` -------------------------------- ### Build Math List with Detected Style Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/configuration.md Build a math list from a LaTeX string, automatically detecting and returning the rendering style based on delimiters. ```swift // Use detected style let (mathList, style) = MTMathListBuilder.buildWithStyle( fromString: "$$E=mc^2$$" ) ``` -------------------------------- ### Get Default Font Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFontManager.md Retrieves the default mathematical font, which is Latin Modern Math at 20pt. This is useful for general use when a specific font is not required. ```swift public var defaultFont: MTFont? ``` ```swift let defaultFont = MTFontManager.fontManager.defaultFont ``` -------------------------------- ### Initialize MTMathListBuilder Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathListBuilder.md Initializes a builder with a LaTeX string. This is the primary way to create a builder instance. ```swift init(string: String) ``` -------------------------------- ### Get Font Bundle Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFont.md Retrieves the bundle that contains all bundled math fonts and their associated metric files. Use this to locate font resources programmatically. ```swift static var fontBundle: Bundle { get } ``` ```swift let bundle = MTFont.fontBundle let fontPath = bundle.path(forResource: "latinmodern-math", ofType: "otf") ``` -------------------------------- ### buildWithStyle(fromString:) Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathListBuilder.md Parses a LaTeX string and automatically detects the math mode/style (inline or display). ```APIDOC ## buildWithStyle(fromString:) ### Description Parses a LaTeX string with automatic detection of the math mode/style. ### Method `public static func buildWithStyle(fromString string: String) -> (mathList: MTMathList?, style: MTLineStyle)` ### Parameters #### Path Parameters - **string** (String) - Required - The LaTeX string to parse ### Response #### Success Response - **Tuple** - Contains `mathList: MTMathList?` and `style: MTLineStyle` ### Details Detects LaTeX delimiters: - `$...$` or `\(...\)` → inline style (`.text`) - `$$...$$` or `\[...\]` → display style (`.display`) - Environments (`\begin{...}\end{...}`) → display style - No delimiters → display style (default) ### Request Example ```swift let (mathList, style) = MTMathListBuilder.buildWithStyle(fromString: "$$E=mc^2$$") // style will be .display let (mathList2, style2) = MTMathListBuilder.buildWithStyle(fromString: "$E=mc^2$") // style2 will be .text ``` ``` -------------------------------- ### Define and Use Custom LaTeX Commands Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/GETTING_STARTED.md Register custom LaTeX commands like \lcm using MTMathAtomFactory. Then use the custom command within a LaTeX string. ```swift // Define \lcm as a custom operator MTMathAtomFactory.addLatexSymbol( "lcm", value: MTMathAtomFactory.operator(withName: "lcm", limits: false) ) // Now use in LaTeX label.latex = "\text{lcm}(a, b) = 12" ``` -------------------------------- ### Configure UI Label for macOS Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/configuration.md Set content hugging and compression resistance priorities for vertical layout on macOS. ```swift import SwiftMath let label = MTMathUILabel() label.setContentHuggingPriority(.required, for: .vertical) ``` -------------------------------- ### Get Unicode Delimiter from LaTeX Name Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the Unicode character for a given LaTeX delimiter name. Useful for displaying LaTeX-formatted delimiters in a Unicode-supporting environment. ```swift if let delimiter = MTMathAtomFactory.delimiters["lceil"] { print(delimiter) // "⌈" } ``` -------------------------------- ### Matrix Multiplication in LaTeX Source: https://github.com/mgriebling/swiftmath/blob/main/EXAMPLES.md Demonstrates matrix multiplication using LaTeX syntax. Supports various matrix environments like pmatrix, bmatrix, etc. ```LaTeX \begin{pmatrix} a & b\ c & d \end{pmatrix} \begin{pmatrix} \alpha & \beta \\ \gamma & \delta \end{pmatrix} = \begin{pmatrix} a\alpha + b\gamma & a\beta + b \\ delta \\ c\alpha + d\gamma & c\beta + d \\ delta \end{pmatrix} ``` -------------------------------- ### Simple Equation Line Breaking Source: https://github.com/mgriebling/swiftmath/blob/main/MULTILINE_IMPLEMENTATION_NOTES.md Demonstrates basic line breaking for simple equations with operators and variables. Works perfectly by breaking between elements. ```swift "a + b + c + d + e + f" ``` ```swift "x = 1, y = 2, z = 3" ``` ```swift "α + β + γ + δ" ``` -------------------------------- ### Get LaTeX Delimiter Name from Unicode Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the LaTeX command name for a given Unicode delimiter character. This is useful for parsing or converting Unicode back to LaTeX. ```swift if let name = MTMathAtomFactory.delimValueToName["⌈"] { print(name) // "lceil" } ``` -------------------------------- ### Create and Configure MTMathUILabel Source: https://github.com/mgriebling/swiftmath/blob/main/README.md Instantiate an MTMathUILabel and set its LaTeX string to display a mathematical equation. This is the basic usage for UIKit. ```swift import SwiftMath let label = MTMathUILabel() label.latex = "x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}" ``` -------------------------------- ### MTFont Initialization Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFont.md Initializes a new MTFont instance with a specified font name and size. This allows you to load a mathematical font and set its display size. ```APIDOC ## MTFont Initialization ### Description Creates a new font instance from a font name and size. ### Parameters #### Path Parameters - **name** (String) - Required - The name of the font (e.g., "latinmodern-math", "xits-math") - **size** (CGFloat) - Required - The font size in points ### Request Example ```swift let font = MTFont(fontWithName: "latinmodern-math", size: 20) ``` ``` -------------------------------- ### Get MTMathAtomType Description Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/types.md Demonstrates retrieving the custom string representation of an MTMathAtomType enum case using the CustomStringConvertible conformance. Provides a human-readable name for atom types. ```swift print(MTMathAtomType.variable.description) // "Variable" ``` -------------------------------- ### Create Display Tree with Width Constraint Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTTypesetter.md Creates a display tree from a math list with an optional width constraint to enable line wrapping. Set width to 0 for no constraint. ```swift // Create display with 200pt width constraint let display = MTTypesetter.createDisplayForMathList( mathList, font: font, style: .display, width: 200 ) ``` -------------------------------- ### Add Custom LaTeX Symbol Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Defines a new custom LaTeX symbol that can be used within the SwiftMath library. This example shows how to add an 'lcm' operator that does not display limits. ```swift import SwiftMath // Define \lcm command that appears as an operator with no limits MTMathAtomFactory.addLatexSymbol("lcm", value: MTMathAtomFactory.operator(withName: "lcm", limits: false)) // Now this works in LaTeX: let label = MTMathUILabel() label.latex = "\\text{lcm}(a, b)" ``` -------------------------------- ### Round-trip Conversion: LaTeX to Math List and Back Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathListBuilder.md Demonstrates parsing a LaTeX string into an `MTMathList` and then converting that `MTMathList` back into a LaTeX string. ```swift // Parse LaTeX to math list let mathList = MTMathListBuilder.build(fromString: "E = mc^2") // Convert back to LaTeX let latex = MTMathListBuilder.mathListToString(mathList) ``` -------------------------------- ### Configure Fallback Font for Non-Latin Characters Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/configuration.md Set a fallback font for rendering non-Latin characters, such as those in \\text{} commands. This example demonstrates platform-specific system font retrieval for fallback. ```swift let mathFont = MTFont(fontWithName: "latinmodern-math", size: 30) // Set fallback for unsupported characters #if os(iOS) || os(visionOS) let systemFont = UIFont.systemFont(ofSize: 30) mathFont.fallbackFont = CTFontCreateWithName( systemFont.fontName as CFString, 30, nil ) #elseif os(macOS) let systemFont = NSFont.systemFont(ofSize: 30) mathFont.fallbackFont = CTFontCreateWithName( systemFont.fontName as CFString, 30, nil ) #endif label.font = mathFont label.latex = "\\text{Hello 世界 🌍}" ``` -------------------------------- ### SwiftMath Source Code Structure Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/INDEX.md This snippet shows the directory structure of the SwiftMath source code, indicating the location of various components and their corresponding documentation files. ```text Sources/SwiftMath/ ├── MathRender/ │ ├── MTMathUILabel.swift → MTMathUILabel.md │ ├── MTMathListBuilder.swift → MTMathListBuilder.md │ ├── MTMathList.swift → MTMathList.md │ ├── MTTypesetter.swift → MTTypesetter.md │ ├── MTFont.swift → MTFont.md │ ├── MTFontManager.swift → MTFontManager.md │ ├── MTMathAtomFactory.swift → MTMathAtomFactory.md │ └── MTConfig.swift → types.md (type aliases) └── MathBundle/ └── MathFont.swift → types.md (MathFont enum) ``` -------------------------------- ### Dirac Notation in LaTeX Source: https://github.com/mgriebling/swiftmath/blob/main/EXAMPLES.md Implements Dirac notation (bra-ket notation) for quantum mechanics using LaTeX commands. Requires specific commands for bra, ket, and braket. ```LaTeX \bra{\psi} \ket{\phi} = \braket{\psi}{\phi} ``` -------------------------------- ### Get Font Style by Name Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Retrieves an MTFontStyle object based on a given LaTeX style command name. Returns nil if the name does not correspond to a known style command. ```swift static func fontStyleWithName(_ name: String) -> MTFontStyle? ``` ```swift if let style = MTMathAtomFactory.fontStyleWithName("mathbf") { print(style) // .bold } ``` -------------------------------- ### Display and Text Style Fractions with \dfrac and \tfrac Source: https://github.com/mgriebling/swiftmath/blob/main/MISSING_FEATURES.md Use \dfrac to force display-style fractions for larger, more readable output. Use \tfrac to force text-style fractions for smaller, inline fractions. These commands ensure consistent fraction appearance. ```latex \dfrac{1}{2} ``` ```latex \tfrac{a}{b} ``` ```latex y'=-\dfrac{2}{x^{3}} ``` -------------------------------- ### Get Combining Unicode Accent from LaTeX Name Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the combining Unicode character for a given LaTeX accent command. This is used for applying accents to characters in mathematical typesetting. ```swift if let combining = MTMathAtomFactory.accents["hat"] { print("Hat accent: \(combining)") } ``` -------------------------------- ### MTMathAtom Initialization Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathList.md Initializes an MTMathAtom with a specified type and value. This is the fundamental way to create basic mathematical atoms. ```APIDOC ## MTMathAtom Initialization ### Description Creates an atom with specified type and value. ### Signature ```swift public init(type: MTMathAtomType, value: String) ``` ### Parameters - **type** (MTMathAtomType) - The type of the mathematical atom. - **value** (String) - The character(s) to render for the atom. ### Example ```swift let xAtom = MTMathAtom(type: .variable, value: "x") let plusAtom = MTMathAtom(type: .binaryOperator, value: "+") ``` ``` -------------------------------- ### Initialize MTMathAtom Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathList.md Creates a new MTMathAtom with a specified type and value. Use this to create basic mathematical symbols or variables. ```swift public init(type: MTMathAtomType, value: String) ``` ```swift let xAtom = MTMathAtom(type: .variable, value: "x") let plusAtom = MTMathAtom(type: .binaryOperator, value: "+") ``` -------------------------------- ### Configure fallback font for Unicode text Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFont.md Set a fallback font for MTFont to ensure proper rendering of non-Latin characters and symbols. This example demonstrates platform-specific configuration for iOS/visionOS and macOS. ```swift let mathFont = MTFont(fontWithName: "latinmodern-math", size: 30) // Configure fallback for non-Latin characters #if os(iOS) || os(visionOS) let systemFont = UIFont.systemFont(ofSize: 30) mathFont.fallbackFont = CTFontCreateWithName(systemFont.fontName as CFString, 30, nil) #elseif os(macOS) let systemFont = NSFont.systemFont(ofSize: 30) mathFont.fallbackFont = CTFontCreateWithName(systemFont.fontName as CFString, 30, nil) #endif let label = MTMathUILabel() label.font = mathFont label.latex = "\\text{Hello 世界 🌍}" // Renders with fallback for Chinese and emoji ``` -------------------------------- ### Line Wrapping with Mixed Text and Simple Math Source: https://github.com/mgriebling/swiftmath/blob/main/README.md Demonstrates natural line breaking between text and simple mathematical atoms. Set `preferredMaxLayoutWidth`. ```swift label.latex = "\\text{Calculer }\\Delta=b^{2}-4ac\\text{ avec }a=1\\text{, }b=-1" label.preferredMaxLayoutWidth = 200 // Breaks between text and math atoms naturally ``` -------------------------------- ### Enable Line Wrapping Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/configuration.md Enable line wrapping for long LaTeX equations by setting the preferred maximum layout width. This snippet shows basic setup and how to calculate the required size. ```swift let label = MTMathUILabel() label.latex = "a + b + c + d + e + f + g + h" label.preferredMaxLayoutWidth = 200 // Enable wrapping at 200pt // Calculate size with wrapping let size = label.sizeThatFits(CGSize(width: 200, height: .greatestFiniteMagnitude)) label.frame.size = size ``` -------------------------------- ### Create Display Tree for Math List Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTTypesetter.md Creates a display tree from a math list using TeX typesetting rules. Use this for general typesetting without width constraints. ```swift let mathList = MTMathListBuilder.build(fromString: "x^2 + y^2") let display = MTTypesetter.createLineForMathList( mathList, font: MTFontManager.fontManager.defaultFont, style: .display ) ``` -------------------------------- ### Line Wrapping with Fractions Source: https://github.com/mgriebling/swiftmath/blob/main/README.md Shows how fractions stay inline if they fit, breaking to a new line only when necessary. Set `preferredMaxLayoutWidth`. ```swift label.latex = "a+\\frac{1}{2}+b+\\frac{3}{4}+c" label.preferredMaxLayoutWidth = 150 // Fractions stay inline if they fit, break to new line only when needed // Example: "a + ½ + b" stays on one line if it fits ``` -------------------------------- ### Adjusting Font Size Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/GETTING_STARTED.md Modify the font size of an existing label or create a new font with a specific size. This example shows changing the size to 28 and creating a new font at size 32. ```swift // Change font size (keeps typeface) label.fontSize = 28 // Or create new font at size let font = MTFont(fontWithName: "xits-math", size: 32) label.font = font ``` -------------------------------- ### Conditional Cases in LaTeX Source: https://github.com/mgriebling/swiftmath/blob/main/EXAMPLES.md Illustrates how to define piecewise functions or conditional cases using LaTeX. The syntax allows for different expressions based on specified conditions. ```LaTeX f(x) = \begin{cases} \frac{e^x}{2} & x \geq 0 \\ 1 & x < 0 \end{cases} ``` -------------------------------- ### Handle Very Long Text Atoms in Swift Source: https://github.com/mgriebling/swiftmath/blob/main/MULTILINE_IMPLEMENTATION_NOTES.md This example demonstrates rendering a very long text string within a single \text command. Core Text's word boundary breaking is used, with protection for numbers. ```swift "\text{This is an extremely long piece of text within a single text command}" ``` -------------------------------- ### Detect Math Mode (Display vs. Inline) Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/GETTING_STARTED.md Build a MathList with style information from a LaTeX string. Check the style to determine if it's display or text/inline mode. ```swift let (mathList, style) = MTMathListBuilder.buildWithStyle(fromString: latex) if style == .display { print("Display mode") } else { print("Text/inline mode") } ``` -------------------------------- ### Scripted Atom Breaking in Swift Source: https://github.com/mgriebling/swiftmath/blob/main/MULTILINE_IMPLEMENTATION_NOTES.md This code handles breaking lines specifically for scripted atoms, incorporating dynamic line height. It updates the vertical position and the starting index for the next line, ensuring correct spacing for content with scripts. ```swift scriptedAtomBreaking() { // ... existing code ... let lineHeight = calculateCurrentLineHeight() currentPosition.y += lineHeight currentLineStartIndex = displayAtoms.count // ... existing code ... } ``` -------------------------------- ### Initialize MTFont Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTFont.md Creates a new MTFont instance from a font name and size. Use this to load a specific mathematical font for rendering. ```swift convenience init(fontWithName name: String, size: CGFloat) ``` ```swift let font = MTFont(fontWithName: "latinmodern-math", size: 20) ``` -------------------------------- ### Compact \smallmatrix Environment for Inline Use Source: https://github.com/mgriebling/swiftmath/blob/main/MISSING_FEATURES.md The \smallmatrix environment creates compact matrices suitable for inline use, offering a smaller font size and tighter column spacing than regular matrices. It can be used with or without delimiters. ```latex \left( \begin{smallmatrix} a & b \\ c & d \end{smallmatrix} \right) ``` ```latex A = \left( \begin{smallmatrix} 1 & 0 \\ 0 & 1 \end{smallmatrix} \right) ``` ```latex \begin{smallmatrix} x \\ y \end{smallmatrix} ``` -------------------------------- ### Perform Interatom Line Break in Swift Source: https://github.com/mgriebling/swiftmath/blob/main/MULTILINE_IMPLEMENTATION_NOTES.md This function handles interatom line breaks by calculating the line height dynamically. It updates the current position's y-coordinate and sets the starting index for the next line's content. This is part of the dynamic line height implementation. ```swift performInteratomLineBreak() { // ... existing code ... let lineHeight = calculateCurrentLineHeight() currentPosition.y += lineHeight currentLineStartIndex = displayAtoms.count // ... existing code ... } ``` -------------------------------- ### Initialize MTMathList from Another List Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathList.md Creates a copy of an existing math list. Pass nil to create an empty list. ```swift public init(_ list: MTMathList?) ``` ```swift let copy = MTMathList(originalList) ``` -------------------------------- ### Perform Complex Display Line Break in Swift Source: https://github.com/mgriebling/swiftmath/blob/main/MULTILINE_IMPLEMENTATION_NOTES.md This function manages line breaks for complex display elements, incorporating dynamic line height calculation. It ensures proper vertical spacing and updates the line start index for subsequent lines. This is crucial for maintaining layout integrity with varied content. ```swift performLineBreak() { // ... existing code ... let lineHeight = calculateCurrentLineHeight() currentPosition.y += lineHeight currentLineStartIndex = displayAtoms.count // ... existing code ... } ``` -------------------------------- ### sizeThatFits(_:) Source: https://github.com/mgriebling/swiftmath/blob/main/_autodocs/api-reference/MTMathUILabel.md Calculates the size required to render the current equation with an optional width constraint. The width of the proposed size can be finite for line wrapping or infinite for no constraint. ```APIDOC ## sizeThatFits(_:) ### Description Calculates the size required to render the current equation with an optional width constraint. ### Method Signature ```swift public func sizeThatFits(_ size: CGSize) -> CGSize ``` ### Parameters #### Path Parameters - **size** (CGSize) - Required - Proposed size; width can be finite (for line wrapping) or 0/infinity (no constraint) ### Returns - **CGSize** - The minimum size needed to render the equation ### Example ```swift let requiredSize = label.sizeThatFits(CGSize(width: 200, height: .greatestFiniteMagnitude)) label.frame.size = requiredSize ``` ```