### Build Example App with xcodebuild Source: https://github.com/kostub/iosmath/blob/master/README.md Command to build the example app using xcodebuild. This command specifies the project, scheme, SDK, and destination for the build process. ```bash xcodebuild build -project SwiftMathExample.xcodeproj \ -scheme SwiftMathExample \ -sdk iphonesimulator \ -destination 'platform=iOS Simulator,name=iPhone 16' ``` -------------------------------- ### Code Examples Source: https://github.com/kostub/iosmath/blob/master/_autodocs/MANIFEST.txt Over 40 standalone code examples are provided in both Swift and Objective-C, covering a wide range of use cases from basic rendering to advanced features like custom command registration and display tree manipulation. ```APIDOC ## Code Examples The documentation includes a comprehensive set of code examples to demonstrate the usage of the iosmath library's features. Examples are provided in both Swift and Objective-C. ### Example Categories: - Basic LaTeX rendering - Error handling scenarios - Font selection and sizing customization - Color customization - Programmatic construction of math atoms - Inspection and modification of display trees - Registration of custom LaTeX commands - Creation of matrices and tables - Direct parser usage - Symbol lookup functionality ### Language Coverage: - **Swift**: Primary, idiomatic usage examples. - **Objective-C**: Fallback examples for compatibility. ### Quantity: - Over 40 standalone examples are included, with approximately one example per 100 words of documentation. ``` -------------------------------- ### Example: Creating MTMathAtom Instances Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathList.md Demonstrates how to create MTMathAtom instances for a variable and a binary operator. ```swift let x = MTMathAtom(type: .variable, value: "x") let plus = MTMathAtom(type: .binaryOperator, value: "+") ``` -------------------------------- ### Navigate to Next Index Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListIndex.md Use the 'next' method to get the subsequent index at the same level. ```objc - (MTMathListIndex *) next; ``` -------------------------------- ### Swift Example: Building MTMathList Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListBuilder.md Demonstrates how to use MTMathListBuilder.buildFromString in Swift to parse a LaTeX string and iterate through the resulting MTMathList atoms. ```Swift if let list = MTMathListBuilder.buildFromString(#"x^2 + y^2 = z^2"#) { for atom in list.atoms { print("Atom type: \(atom.type), nucleus: \(atom.nucleus)") } } ``` -------------------------------- ### Check if at Beginning of Line Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListIndex.md Use 'isAtBeginningOfLine' to determine if the innermost sub-index is at the start of its list. ```swift if idx.isAtBeginningOfLine { print("At the start of a sub-list") } ``` -------------------------------- ### Build Math Programmatically Source: https://github.com/kostub/iosmath/blob/master/_autodocs/README.md Construct a mathematical expression programmatically using MTMathList and MTMathAtom. This example builds the expression (a+b)^2. ```swift // Construct: (a+b)^2 let base = MTMathListBuilder.buildFromString("a+b")! let inner = MTInner() inner.innerList = base inner.leftBoundary = MTMathAtomFactory.boundaryAtom(forDelimiter: "(") inner.rightBoundary = MTMathAtomFactory.boundaryAtom(forDelimiter: ")") let power = MTMathAtom(type: .number, value: "2") power.superScript = MTMathListBuilder.buildFromString("2")! power.nucleus = "" let list = MTMathList() list.add(inner) list.add(power) label.mathList = list ``` -------------------------------- ### Swift Error Handling Example Source: https://github.com/kostub/iosmath/blob/master/_autodocs/MANIFEST.txt Demonstrates how to catch parse errors in Swift. Ensure the MTParseError domain is used for error handling. ```swift do { try mathLabel.setLatex("invalid LaTeX") } catch let error as NSError { guard error.domain == MTParseErrorDomain else { return } print("Error: \(error.localizedDescription)\nCode: \(error.code)") } ``` -------------------------------- ### Create and Union MTMathListRange Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListIndex.md Demonstrates creating an MTMathListRange from a start index and length, and performing a union operation with another range. ```swift let range = MTMathListRange.makeRange(startIdx, length: 3) let unionRange = range.unionRange(otherRange) ``` -------------------------------- ### Swift Example: Handling Parse Errors Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListBuilder.md Shows how to use the error-handling variant of buildFromString in Swift. It captures potential parsing errors and prints the error description and code. ```Swift var error: NSError? let list = MTMathListBuilder.buildFromString(#"\\frac{1}{x"#, error: &error) if let error = error { print("Parse failed: \(error.localizedDescription)") print("Error code: \(error.code)") } ``` -------------------------------- ### Objective-C Error Handling Example Source: https://github.com/kostub/iosmath/blob/master/_autodocs/MANIFEST.txt Demonstrates how to catch parse errors in Objective-C. Ensure the MTParseError domain is used for error handling. ```objectivec NSError *error; [mathLabel setLatex:@"invalid LaTeX" error:&error]; if (error) { if ([error.domain isEqualToString:MTParseErrorDomain]) { NSLog(@"Error: %@\nCode: %ld", error.localizedDescription, (long)error.code); } } ``` -------------------------------- ### Initialize Empty MTMathList Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathList.md Creates an empty math list. Use this initializer when starting with a new math list. ```Objective-C - (instancetype) init NS_DESIGNATED_INITIALIZER; ``` -------------------------------- ### Get Placeholder Fraction Atom Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Returns a fraction atom with placeholder numerator and denominator. ```objc + (MTFraction*) placeholderFraction; ``` -------------------------------- ### Using Font Name Constants Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTFontManager.md Load different bundled fonts using their predefined constants. This example demonstrates loading two distinct fonts with specified sizes. ```swift let font1 = MTFontManager.fontManager.font(withName: MTFontNameLatinModern, size: 20) let font2 = MTFontManager.fontManager.font(withName: MTFontNameSTIXTwo, size: 28) ``` -------------------------------- ### Set Content Insets Source: https://github.com/kostub/iosmath/blob/master/README.md Add padding between the rendered equation and the label's bounds. This example adds 10pt left padding and 20pt right padding. ```swift // Add 10 pt of space on the left and 20 pt on the right. label.contentInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 20) ``` -------------------------------- ### Accessing the MTFontManager Singleton Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTFontManager.md Get the shared instance of MTFontManager to access its methods. This is the standard way to interact with the font manager. ```swift let manager = MTFontManager.fontManager let font = manager.font(withName: MTFontNameTermes, size: 20) ``` -------------------------------- ### Quick Start: Render LaTeX Equation Source: https://github.com/kostub/iosmath/blob/master/_autodocs/README.md Use MTMathUILabel to display a LaTeX math equation in your iOS/macOS view. Import the iosMath framework and set the latex property of the label. ```swift import iosMath let label = MTMathUILabel() label.latex = #"x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}" view.addSubview(label) ``` -------------------------------- ### mathList Property Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathUILabel.md Sets or gets the MTMathList model to be rendered by the label. Setting this property clears any previously set LaTeX string. ```APIDOC ## mathList Property ### Description Represents the math model (`MTMathList`) to be rendered. Setting this property will clear any existing `latex` string. ### Property `mathList` (MTMathList*) ### Details - **Type**: `MTMathList*` (nullable) - **Default**: `nil` - **Description**: The math model to render. Setting this clears any previously set `latex`. ### Returns If `latex` has been set and parses successfully, returns the parsed `MTMathList`. Otherwise returns the directly-set `mathList`. ### Example ```swift // Build math programmatically without LaTeX let num = MTMathListBuilder.build(from: "1")! let denom = MTMathListBuilder.build(from: "2")! let frac = MTMathAtomFactory.fraction(numerator: num, denominator: denom) let list = MTMathList() list.add(frac) label.mathList = list ``` ``` -------------------------------- ### Set Content Insets (Objective-C) Source: https://github.com/kostub/iosmath/blob/master/README.md Add padding between the rendered equation and the label's bounds using Objective-C. This example adds 10pt left padding and 20pt right padding. ```objective-c label.contentInsets = UIEdgeInsetsMake(0, 10, 0, 20); ``` -------------------------------- ### Get Text Style from Name (Objective-C) Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Converts a text command name (e.g., 'textbf') into an MTTextStyle value. Returns NSNotFound if the name is not recognized. ```Objective-C + (MTTextStyle) textStyleWithName:(NSString*) name; ``` -------------------------------- ### Calculate Label Size Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathUILabel.md Use sizeThatFits to determine the minimum size required to render the math content, accounting for content insets. Pass a maximum width and infinity for height to get the natural height. ```swift let size = label.sizeThatFits(CGSize(width: 300, height: .infinity)) print("Label needs \(size.width) x \(size.height) points") ``` -------------------------------- ### SwiftUI Usage with MathView Wrapper Source: https://github.com/kostub/iosmath/blob/master/README.md Example of using the MathView SwiftUI wrapper to display a mathematical formula. The frame modifier is used to control the view's size. ```swift MathView(latex: #"e^{i\pi} + 1 = 0"#) .frame(height: 50) ``` -------------------------------- ### Build with Swift Package Manager Source: https://github.com/kostub/iosmath/blob/master/CLAUDE.md Use these commands to build the project using Swift Package Manager. ```bash swift build swift test ``` -------------------------------- ### Get Placeholder Atom Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Returns a placeholder square atom, useful for editor implementations. ```objc + (MTMathAtom*) placeholder; ``` -------------------------------- ### Rendering Pipeline Overview Source: https://github.com/kostub/iosmath/blob/master/_autodocs/INDEX.md Illustrates the step-by-step process of rendering a LaTeX string into a visual equation within the iosMath framework. ```text LaTeX String ↓ [MTMathListBuilder.build] ↓ MTMathList (atom tree) ↓ [MTTypesetter.layoutToWidth] (internal) ↓ MTMathListDisplay (positioned glyphs) ↓ [draw:] method → CoreText → CoreGraphics ↓ Rendered Equation in UIView/NSView ``` -------------------------------- ### Get String Representation of MTMathAtom Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathList.md Retrieves a string representation of the MTMathAtom for debugging purposes. ```objc @property (nonatomic, readonly) NSString *stringValue; ``` -------------------------------- ### Create Math Atoms using Factory Source: https://github.com/kostub/iosmath/blob/master/README.md Demonstrates creating various math atoms like multiplication, fraction, square root, and Greek letters using the MTMathAtomFactory. ```swift let times = MTMathAtomFactory.times() // × let frac = MTMathAtomFactory.fraction(numerator: num, denominator: denom) let sqrt = MTMathAtomFactory.placeholderSquareRoot() let alpha = MTMathAtomFactory.atom(forLatexSymbol: "alpha") ``` -------------------------------- ### Programmatically Create a Fraction Source: https://github.com/kostub/iosmath/blob/master/_autodocs/README.md Build a fraction (e.g., 1/2) using MTMathAtomFactory and MTMathListBuilder without relying on LaTeX syntax. This allows for dynamic construction of mathematical expressions. ```swift // Create a fraction 1/2 let num = MTMathListBuilder.buildFromString("1")! denom = MTMathListBuilder.buildFromString("2")! let frac = MTMathAtomFactory.fraction(numerator: num, denominator: denom) let list = MTMathList() list.add(frac) label.mathList = list ``` -------------------------------- ### Get Placeholder Square Root Atom Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Returns a square root atom with a placeholder radicand. ```objc + (MTRadical *)placeholderSquareRoot; ``` -------------------------------- ### Get Final Sub-Index Type Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListIndex.md Retrieve the sub-index type of the innermost level using 'finalSubIndexType'. ```objc - (MTMathListSubIndexType) finalSubIndexType; ``` -------------------------------- ### Public Methods Overview Source: https://github.com/kostub/iosmath/blob/master/_autodocs/MANIFEST.txt The iosmath library exposes over 90 public methods, including initialization methods, property accessors, class methods, instance methods, and factory methods. All are fully documented with parameters, return types, and explanations. ```APIDOC ## Public Methods The iosmath library provides a rich set of public methods for rendering and manipulating mathematical expressions. All methods are thoroughly documented, ensuring clarity on their purpose, parameters, and return values. ### Initialization Methods All initialization methods are documented, detailing the parameters required to create instances of various classes. ### Property Accessors Documentation includes type tables for all property accessors, explaining the data types and expected values. ### Class and Instance Methods Class and instance methods are fully described, including their parameters, return types, and the operations they perform. ### Factory Methods Factory methods are explained, providing insights into how they are used to create and configure mathematical objects. ``` -------------------------------- ### MTFontManager textCTFontForStyle:size: Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTFontManager.md Get a CoreText font reference for rendering text-mode math content. ```APIDOC ## Get Text CoreText Font ### Description Provides a CoreText font reference (`CTFontRef`) suitable for rendering standard text within math expressions (e.g., using `\text{}`). The font is selected based on the specified text style and size. ### Method Class Method ### Endpoint `+ (CTFontRef) textCTFontForStyle:(MTTextStyle) style size:(CGFloat) size CF_RETURNS_RETAINED;` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **style** (`MTTextStyle`) - Required - The text style to apply (e.g., `kMTTextStyleRoman`, `kMTTextStyleBold`). - **size** (`CGFloat`) - Required - The font size in points. ### Request Example ```swift let ctFont = MTFontManager.textCTFontForStyle(.bold, size: 16) // Remember to release the returned CTFontRef: CFRelease(ctFont) ``` ### Response #### Success Response - **Returns** (`CTFontRef`) - A CoreText font reference. The caller is responsible for releasing this reference using `CFRelease`. ``` -------------------------------- ### initWithString: Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListBuilder.md Initializes a new MTMathListBuilder instance with a given LaTeX string. This is the designated initializer and should be used to create builders for parsing. ```APIDOC ## initWithString: (Initializer) ### Description Initializes a new `MTMathListBuilder` instance with the provided LaTeX string. This is the designated initializer for creating a builder to parse LaTeX. ### Method - (instancetype) initWithString:(NSString *)str NS_DESIGNATED_INITIALIZER ### Parameters #### Path Parameters - **str** (`NSString*`) - The LaTeX string to parse. ### Returns A new `MTMathListBuilder` initialized with the given string. ### Notes - Do not reuse a builder after calling `build`. Create a new builder for each string to parse. The builder holds parsing state that is not reset between calls. ### Example ```swift let builder = MTMathListBuilder(string: #"\alpha + \beta"#) if let list = builder.build() { // Use the list } ``` ``` -------------------------------- ### Get Placeholder N-th Root Atom Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Returns an n-th root atom with a placeholder radicand and degree. ```objc + (MTRadical*) placeholderRadical; ``` -------------------------------- ### Build Fraction Programmatically Source: https://github.com/kostub/iosmath/blob/master/README.md Constructs a fraction (1/2) programmatically using MTMathListBuilder and MTMathAtomFactory, without parsing LaTeX. The resulting math list is then assigned to an MTMathUILabel. ```swift import iosMath // Build a fraction 1/2 without parsing LaTeX. let num = MTMathListBuilder.build(from: "1")! let denom = MTMathListBuilder.build(from: "2")! let frac = MTMathAtomFactory.fraction(numerator: num, denominator: denom) let mathList = MTMathList() mathList.add(frac) let label = MTMathUILabel() label.mathList = mathList ``` -------------------------------- ### Configuration Options Source: https://github.com/kostub/iosmath/blob/master/_autodocs/MANIFEST.txt Seven configuration options are available to customize the appearance and behavior of math rendering, including label mode, font, font size, text color, alignment, insets, and inline error display. ```APIDOC ## Configuration Options Developers can customize the appearance and behavior of the math rendering component using the following configuration options: - **labelMode**: Controls whether the label operates in 'Display' or 'Text' mode. - **font**: Allows selection from 8 bundled fonts, with details provided for each. - **fontSize**: Sets the desired font size for the mathematical expressions. - **textColor**: Configures the text color, with platform-aware adjustments. - **textAlignment**: Specifies text alignment, supporting Left, Center, and Right options. - **contentInsets**: Adjusts the content insets for the math view. - **displayErrorInline**: A boolean option to control whether errors are displayed inline. ``` -------------------------------- ### Get MTFont Size Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTFont.md Retrieves the current font size in points for an MTFont instance. This property is read-only. ```swift let size = label.font.fontSize print("Current size: \(size) points") ``` -------------------------------- ### iosMath Rendering Pipeline Source: https://github.com/kostub/iosmath/blob/master/ALGORITHM.md Illustrates the flow from a LaTeX string to the final rendered display in iosMath. It highlights the key stages and transformations involved in typesetting. ```plaintext LaTeX string ──► MTMathListBuilder ──► MTMathList (of MTMathAtoms) │ ▼ MTMathList.finalized (Rules 5, 6, 14 pre-bake) │ ▼ MTTypesetter.preprocessMathList (Rule 14 merge + Number→Ord, Variable→Ord, Unary→Ord) │ ▼ MTTypesetter.createDisplayAtoms (Rules 1–4, 7–13, 15–18, 20, 22; two-pass merged into one) │ ▼ MTMathListDisplay (tree of MTDisplays) │ ▼ MTDisplay.draw: (CoreText / CGContext) ``` -------------------------------- ### Get Accent Name Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the accent name for a given MTAccent atom. Returns nil if the accent is not recognized. ```objc + (nullable NSString*) accentName:(MTAccent*) accent; ``` -------------------------------- ### Navigate to Previous Index Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListIndex.md Use the 'previous' method to get the preceding index in the list. Returns nil if at the beginning. ```swift if let prevIdx = idx.previous { print("Previous index: \(prevIdx.atomIndex)") } ``` -------------------------------- ### MTMathUILabel Initialization Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathUILabel.md Initializes a new MTMathUILabel instance with default settings. This is the primary way to create a math label for rendering. ```APIDOC ## MTMathUILabel Initialization ### Description Initializes a new `MTMathUILabel` instance configured with default settings. ### Method `init` ### Returns A new `MTMathUILabel` instance. ### Example ```swift import iosMath let label = MTMathUILabel() label.latex = #"x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}"# view.addSubview(label) ``` ``` -------------------------------- ### Checking for Parse Errors Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListBuilder.md Example of how to check if an NSError object has the MTParseError domain and extract the specific parse error code. ```swift if error?.domain == MTParseError { let parseCode = MTParseErrors(rawValue: error!.code) } ``` -------------------------------- ### Get All Supported LaTeX Symbol Names Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Use `supportedLatexSymbolNames` to retrieve an array of all LaTeX symbol names that the factory recognizes. ```Objective-C + (NSArray*) supportedLatexSymbolNames; ``` -------------------------------- ### Get String Representation of MTMathList Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathList.md Returns a string representation of the math list, primarily for debugging purposes. This is not a LaTeX representation. ```Objective-C @property (nonatomic, readonly) NSString *stringValue; ``` -------------------------------- ### Run macOS Tests with Xcode Source: https://github.com/kostub/iosmath/blob/master/CLAUDE.md Execute macOS tests using xcodebuild. ```bash xcodebuild test -project MacOSMath.xcodeproj -scheme MacOSMath -sdk macosx ``` -------------------------------- ### Import iosMath in Objective-C Source: https://github.com/kostub/iosmath/blob/master/_autodocs/INDEX.md Import the iosMath library using the module syntax for Objective-C projects. This enables the use of C-style APIs. ```objectivec @import iosMath; ``` -------------------------------- ### tableWithEnvironment:rows:error: Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Creates a table or matrix structure with specified rows and an optional environment. ```APIDOC ## tableWithEnvironment:rows:error: ### Description Creates a table or matrix structure with specified rows and an optional environment. ### Method `+ (nullable MTMathAtom*) tableWithEnvironment:(nullable NSString*) env rows:(NSArray*>*) rows error:(NSError**) error` ### Parameters #### Path Parameters - **env** (`NSString*`) - Optional - Environment name (e.g., "matrix", "pmatrix", "bmatrix"). If `nil`, builds a plain table. - **rows** (`NSArray*>*`) - Required - 2D array of `MTMathList` objects, each representing a cell. - **error** (`NSError**`) - Optional - Output parameter for errors. ### Response #### Success Response - **Returns:** An `MTMathAtom` (typically `MTMathTable` or `MTInner` with delimiters), or `nil` on error. ### Request Example ```swift let cell11 = MTMathListBuilder.buildFromString("a")! let cell12 = MTMathListBuilder.buildFromString("b")! let cell21 = MTMathListBuilder.buildFromString("c")! let cell22 = MTMathListBuilder.buildFromString("d")! var error: NSError? let matrix = MTMathAtomFactory.tableWithEnvironment("pmatrix", rows: [[cell11, cell12], [cell21, cell22]], error: &error) ``` ``` -------------------------------- ### Initialization Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathList.md Initializes an MTMathList object. Use `init` for an empty list, `mathListWithAtoms:` for a variadic list, or `mathListWithAtomsArray:` for a list from an array. ```APIDOC ## Initialization ### `init` Creates an empty math list. ### `mathListWithAtoms:(MTMathAtom*) firstAtom, ...` Creates a list from a variadic list of atoms, terminated with `nil`. ### `mathListWithAtomsArray:(NSArray*) atoms` Creates a list from an array of atoms. ``` -------------------------------- ### build Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListBuilder.md Attempts to parse the LaTeX string provided during initialization into an MTMathList. Returns nil if parsing fails. ```APIDOC ## build ### Description Attempts to parse the LaTeX string that the builder was initialized with into an `MTMathList`. If parsing is successful, it returns the `MTMathList`; otherwise, it returns `nil`. ### Method - (nullable MTMathList *) build; ### Returns An `MTMathList` if parsing succeeds, or `nil` if parsing fails. ### Errors If parsing fails, the error is available in the `error` property. ### Example ```swift let builder = MTMathListBuilder(string: latex) if let list = builder.build() { // Success } else if let error = builder.error { print("Parse error: \(error.localizedDescription)") } ``` ``` -------------------------------- ### fraction(numeratorString:denominatorString:) Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Creates a fraction by parsing the numerator and denominator from simple strings. ```APIDOC ## fraction(numeratorString:denominatorString:) ### Description Creates a fraction by parsing the numerator and denominator from simple strings. ### Method `+ (MTFraction*) fractionWithNumeratorStr:(NSString*) numStr denominatorStr:(NSString*) denomStr` ### Parameters #### Path Parameters - **numStr** (`NSString*`) - Required - The string representation of the numerator. - **denomStr** (`NSString*`) - Required - The string representation of the denominator. ### Response #### Success Response - **Returns:** A fraction with numerator and denominator parsed from simple strings. ### Request Example ```swift let frac = MTMathAtomFactory.fraction(numeratorString: "1", denominatorString: "2") ``` ``` -------------------------------- ### latex Property Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathUILabel.md Sets or gets the LaTeX string to be rendered by the label. Setting this property clears any previously set math list. ```APIDOC ## latex Property ### Description Represents the LaTeX string to be rendered. Setting this property will clear any existing `mathList`. ### Property `latex` (NSString*) ### Details - **Type**: `NSString*` (nullable) - **Default**: `nil` - **Description**: The LaTeX string to render. Setting this clears any previously set `mathList`. ### Returns If `latex` has not been set, returns the LaTeX serialization of the current `mathList`. If no list exists, returns `nil`. ### Errors When set to an invalid LaTeX string, the error is captured in the `error` property and displayed inline (unless `displayErrorInline` is `false`). ### Example ```swift label.latex = #"\alpha + \beta = \gamma"# ``` ``` -------------------------------- ### Get Font Name from Style (Objective-C) Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Converts an MTFontStyle value back into its corresponding LaTeX font command name (e.g., 'mathbf'). ```Objective-C + (NSString*) fontNameForStyle:(MTFontStyle) fontStyle; ``` -------------------------------- ### Initialize MTMathListBuilder with a String Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListBuilder.md Initializes a new MTMathListBuilder with a given LaTeX string. Do not reuse a builder after calling build; create a new one for each string. ```Objective-C - (instancetype) initWithString:(NSString *)str NS_DESIGNATED_INITIALIZER; ``` ```swift let builder = MTMathListBuilder(string: #"\alpha + \beta"#) if let list = builder.build() { // Use the list } ``` -------------------------------- ### Simple UIKit/AppKit Usage with MTMathUILabel (Objective-C) Source: https://github.com/kostub/iosmath/blob/master/README.md Objective-C equivalent for creating an MTMathUILabel, setting its latex property, and adding it as a subview. ```objective-c @import iosMath; MTMathUILabel *label = [[MTMathUILabel alloc] init]; label.latex = @"x = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}"; [self.view addSubview:label]; ``` -------------------------------- ### Get Stack Command Specification Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the MTMathStackCommandSpec for a given LaTeX command. This spec describes the command's structure and argument roles. ```objc + (nullable MTMathStackCommandSpec*) stackCommandSpec:(NSString*)command; ``` -------------------------------- ### Get Command Name for Text Style (Objective-C) Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the canonical LaTeX command name for a given MTTextStyle (e.g., 'textbf' for bold text). ```Objective-C + (NSString*) commandNameForTextStyle:(MTTextStyle) style; ``` -------------------------------- ### stackAtom(forCommand:) Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Creates a math stack atom for specified LaTeX commands like over/under arrows and braces. ```APIDOC ## stackAtom(forCommand:) ### Description Creates a pre-configured `MTMathStack` atom for a given LaTeX command. The command should be provided without the leading backslash. ### Method Signature ```objc + (nullable MTMathStack*) stackAtomForCommand:(NSString*)command NS_SWIFT_NAME(stackAtom(forCommand:)); ``` ### Parameters #### Path Parameters * **command** (`NSString*`) - Required - LaTeX command name without backslash. ### Response #### Success Response A pre-configured `MTMathStack` atom with static (extensible) constructions set, or `nil` if the command is unknown. The caller must set the `innerList` property. ### Supported Commands - Over arrows: `overrightarrow`, `overleftarrow`, `overleftrightarrow` - Under arrows: `underrightarrow`, `underleftarrow`, `underleftrightarrow` - Braces: `overbrace`, `underbrace` ### Example ```swift if let arrow = MTMathAtomFactory.stackAtom(forCommand: "overrightarrow") { arrow.innerList = baseList } ``` ``` -------------------------------- ### Run iOS Tests with Xcode Source: https://github.com/kostub/iosmath/blob/master/CLAUDE.md Execute iOS tests using xcodebuild for a specific simulator. ```bash xcodebuild test -project iosMath.xcodeproj -scheme iosMath -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 16' ``` -------------------------------- ### Get Delimiter Name from Boundary Atom (Objective-C) Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the delimiter name associated with an MTMathAtom. Returns nil if the atom is not a recognized boundary atom. ```Objective-C + (nullable NSString*) delimiterNameForBoundaryAtom:(MTMathAtom*) boundary; ``` -------------------------------- ### Handling Style Changes in MTTypesetter Source: https://github.com/kostub/iosmath/blob/master/ALGORITHM.md This code demonstrates how iosMath processes style change atoms by updating the current style and re-creating the style font. ```objc MTMathStyle* style = (MTMathStyle*) atom; self.style = style.style; continue; ``` -------------------------------- ### Create MTMathAtom from LaTeX Symbol Name Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Use `atomForLatexSymbolName:` to get an MTMathAtom for a given LaTeX command name. Returns nil if the symbol is not recognized. ```Objective-C + (nullable MTMathAtom*) atomForLatexSymbolName:(NSString*) symbolName NS_SWIFT_NAME(atom(forLatexSymbol:)); ``` ```swift let alpha = MTMathAtomFactory.atom(forLatexSymbol: "alpha") let integral = MTMathAtomFactory.atom(forLatexSymbol: "int") ``` -------------------------------- ### Get Parent Level Index Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListIndex.md Retrieves the parent MTMathListIndex by removing the current index's outermost sub-index. Useful for navigating up the index hierarchy. ```swift if let parentIdx = idx.levelDown { print("Parent level index: \(parentIdx.atomIndex)") } ``` -------------------------------- ### Getting the Default MTFont Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTFontManager.md Retrieve the default MTFont, which is Latin Modern Math at 20pt. This is useful for setting a standard font for labels or text views. ```swift let defaultFont = MTFontManager.fontManager.defaultFont() label.font = defaultFont ``` -------------------------------- ### buildFromString:error: Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListBuilder.md Parses a LaTeX string into an MTMathList and provides detailed error information on failure. ```APIDOC ## buildFromString:error: ### Description Parses a LaTeX string into an `MTMathList` and provides detailed error information if parsing fails. This method is useful for debugging parse errors. ### Method `+ (nullable MTMathList *) buildFromString:(NSString *)str error:(NSError * _Nullable * _Nullable)error;` ### Parameters #### Path Parameters - **str** (`NSString*`) - The LaTeX string to parse. - **error** (`NSError**`) - Output parameter. On return, if parsing failed, contains an `NSError` with code from `MTParseErrors` enum. ### Returns An `MTMathList` if parsing succeeds, or `nil` if parsing fails. On failure, the error parameter is populated. ### Errors Populates `error` with one of the `MTParseErrors` codes: - `MTParseErrorMismatchBraces` — braces do not match - `MTParseErrorInvalidCommand` — unrecognized command - `MTParseErrorCharacterNotFound` — expected character missing - `MTParseErrorMissingDelimiter` — `\left` or `\right` lacks a delimiter - `MTParseErrorInvalidDelimiter` — invalid delimiter after `\left`/`\right` - `MTParseErrorMissingRight` — no `\right` for `\left` - `MTParseErrorMissingLeft` — no `\left` for `\right` - `MTParseErrorInvalidEnv` — unrecognized environment name - `MTParseErrorMissingEnv` — command only valid inside an environment - `MTParseErrorMissingBegin` — no `\begin` for `\end` - `MTParseErrorMissingEnd` — no `\end` for `\begin` - `MTParseErrorInvalidNumColumns` — column count mismatch - `MTParseErrorNestingTooDeep` — nesting depth exceeds 150 levels - `MTParseErrorInvalidLimits` — incorrect limit control - `MTParseErrorInternalError` — programming error in the parser ### Request Example ```swift var error: NSError? let list = MTMathListBuilder.buildFromString(#"\\frac{1}{x"#, error: &error) if let error = error { print("Parse failed: \(error.localizedDescription)") print("Error code: \(error.code)") } ``` ``` -------------------------------- ### MTMathUILabel Source: https://github.com/kostub/iosmath/blob/master/_autodocs/MANIFEST.txt The main rendering view class for displaying mathematical expressions. It provides properties for controlling the appearance and content of the label, along with initialization and usage examples. ```APIDOC ## Class MTMathUILabel ### Description This class is the primary view for rendering mathematical expressions using LaTeX or MathML. It exposes properties to customize font, color, alignment, and more, facilitating easy integration into iOS applications. ### Properties - **latex** (string) - The LaTeX string to be rendered. - **mathList** (MTMathList) - The internal MathList representation of the expression. - **error** (string) - Displays any parsing errors. - **font** (MTFont) - The font used for rendering. - **fontSize** (CGFloat) - The size of the font. - **textColor** (UIColor) - The color of the text. - **contentInsets** (UIEdgeInsets) - Padding around the content. - **labelMode** (MTLabelMode) - Determines how the label renders (e.g., display or inline). - **textAlignment** (NSTextAlignment) - The horizontal alignment of the text. - **displayList** (MTDisplayList) - The internal display list for rendering. ### Initialization - `init()` - Initializes a new instance of MTMathUILabel. ### Usage Examples Provides examples for setting LaTeX strings, customizing appearance, and handling errors. ``` -------------------------------- ### Import iosMath in Swift Source: https://github.com/kostub/iosmath/blob/master/_autodocs/INDEX.md Import the iosMath library to use its functionalities in your Swift project. This allows access to Swift-renamed APIs. ```swift import iosMath ``` -------------------------------- ### Set LaTeX String Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathUILabel.md Assigns a LaTeX string to the label for rendering. This will clear any previously set mathList. ```swift label.latex = #"\alpha + \beta = \gamma"# ``` -------------------------------- ### MTMathListRange Class Definition Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListIndex.md Defines a range within an MTMathList using MTMathListIndex for the start position and an NSUInteger for the length. Includes factory methods and range manipulation. ```objc @interface MTMathListRange : NSObject + (MTMathListRange *) makeRange:(MTMathListIndex *)start length:(NSUInteger)length; + (MTMathListRange *) makeRangeForRange:(NSRange)range; + (MTMathListRange *) makeRange:(MTMathListIndex *)start; + (MTMathListRange *) makeRangeForIndex:(NSUInteger)start; @property (nonatomic, readonly) MTMathListIndex *start; @property (nonatomic, readonly) NSUInteger length; - (nullable MTMathListRange *) subIndexRange; - (nullable MTMathListRange *) unionRange:(MTMathListRange *)range; + (nullable MTMathListRange *) unionRanges:(NSArray *)ranges; @end ``` -------------------------------- ### Get Font Style from Name (Objective-C) Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Converts a font command name (e.g., 'mathbf') into an MTFontStyle value. Returns NSNotFound if the font name is not recognized. ```Objective-C + (MTFontStyle) fontStyleWithName:(NSString*) fontName; ``` -------------------------------- ### Get Stack Command for Atom Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Retrieves the LaTeX command name for a given MTMathStack atom. Returns nil if the atom does not match a canonical stack command. ```objc + (nullable NSString*) stackCommandForStack:(MTMathStack*)stack NS_SWIFT_NAME(stackCommand(for:)); ``` -------------------------------- ### fraction(numerator:denominator:) Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Creates an M TFraction atom with a specified numerator and denominator, including a rule. ```APIDOC ## fraction(numerator:denominator:) ### Description Creates an M TFraction atom with a specified numerator and denominator, including a rule. ### Method `+ (MTFraction*) fractionWithNumerator:(MTMathList*) num denominator:(MTMathList*) denom` ### Parameters #### Path Parameters - **num** (`MTMathList*`) - Required - The numerator. - **denom** (`MTMathList*`) - Required - The denominator. ### Response #### Success Response - **Returns:** An `MTFraction` atom with the given numerator and denominator, with a rule. ### Request Example ```swift let numList = MTMathListBuilder.buildFromString("1")! let denomList = MTMathListBuilder.buildFromString("2")! let fraction = MTMathAtomFactory.fraction(numerator: numList, denominator: denomList) ``` ``` -------------------------------- ### Navigation Methods Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListIndex.md Provides methods to navigate to the previous or next index within the mathematical list structure. ```APIDOC ## Navigation Methods ### previous ```objc - (nullable MTMathListIndex *) previous; ``` **Returns:** The previous index if one exists, or `nil` if at the beginning of the current level. **Example:** ```swift if let prevIdx = idx.previous { print("Previous index: \(prevIdx.atomIndex)") } ``` ### next ```objc - (MTMathListIndex *) next; ``` **Returns:** The next index at the same level. ``` -------------------------------- ### Get LaTeX Symbol Name from MTMathAtom Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Use `latexSymbolNameForAtom:` to retrieve the canonical LaTeX command name for a given MTMathAtom. This method may not return aliases. ```Objective-C + (nullable NSString*) latexSymbolNameForAtom:(MTMathAtom*) atom NS_SWIFT_NAME(latexSymbolName(for:)); ``` ```swift if let atom = MTMathAtomFactory.atom(forLatexSymbol: "alpha") { let name = MTMathAtomFactory.latexSymbolName(for: atom) print(name) // Output: "alpha" } ``` -------------------------------- ### Create MTTable or MTInner with Environment and Rows Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Constructs a table or matrix structure. Specify an environment name like 'pmatrix' for bracketed matrices or nil for a plain table. Rows are provided as a 2D array of MTMathList cells. Handles errors via an NSError pointer. ```Objective-C + (nullable MTMathAtom*) tableWithEnvironment:(nullable NSString*) env rows:(NSArray*>*) rows error:(NSError**) error; ``` ```swift let cell11 = MTMathListBuilder.buildFromString("a")! let cell12 = MTMathListBuilder.buildFromString("b")! let cell21 = MTMathListBuilder.buildFromString("c")! let cell22 = MTMathListBuilder.buildFromString("d")! var error: NSError? let matrix = MTMathAtomFactory.tableWithEnvironment("pmatrix", rows: [[cell11, cell12], [cell21, cell22]], error: &error) ``` -------------------------------- ### Getting a CoreText Font Reference Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTFontManager.md Obtain a CoreText font reference (CTFontRef) for rendering text-mode content. Remember to release the returned CFTypeRef using defer. ```swift let ctFont = MTFontManager.textCTFontForStyle(.bold, size: 16) defer { CFRelease(ctFont) } // Use ctFont with CoreText... ``` -------------------------------- ### Run a Single iOS Test Class Source: https://github.com/kostub/iosmath/blob/master/CLAUDE.md Execute a specific test class within the iOS project using xcodebuild. ```bash xcodebuild test -project iosMath.xcodeproj -scheme iosMath -sdk iphonesimulator \ -destination 'platform=iOS Simulator,name=iPhone 16' \ -only-testing:iosMathTests/MTMathListBuilderTest ``` -------------------------------- ### Create MTMathAtom Instance Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathList.md Creates a new MTMathAtom with a specified type and value. ```objc + (instancetype) atomWithType:(MTMathAtomType) type value:(NSString*) value; ``` -------------------------------- ### Initialize MTMathList from Variadic Atoms Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathList.md Creates a math list from a variadic list of MTMathAtom objects, terminated with nil. Useful for creating lists with a known set of initial atoms. ```Objective-C + (instancetype) mathListWithAtoms:(MTMathAtom*) firstAtom, ... NS_REQUIRES_NIL_TERMINATION; ``` -------------------------------- ### sizeThatFits Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathUILabel.md Calculates the minimum size required to render the math content, including content insets. ```APIDOC ## sizeThatFits ### Description Calculates the minimum size needed to render the current math, including `contentInsets`. ### Method Signature `func sizeThatFits(_: CGSize) -> CGSize` ### Parameters * `constrainedSize` (CGSize) - The maximum size the label can be. ### Returns (CGSize) - The minimum size required to display the math content. ### Example ```swift let size = label.sizeThatFits(CGSize(width: 300, height: .infinity)) print("Label needs \(size.width) x \(size.height) points") ``` ``` -------------------------------- ### Get Inherited Display Class for Base Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Determines the math class to inherit for display purposes for the base of an \overset or \underset command. Returns kMTMathAtomOrdinary if the base is not a single Bin/Rel atom. ```objc + (MTMathAtomType) inheritedDisplayClassForBase:(MTMathList*)base; ``` -------------------------------- ### MTMathAtomFactory Source: https://github.com/kostub/iosmath/blob/master/_autodocs/MANIFEST.txt A factory class providing over 25 static methods for creating and manipulating `MTMathAtom` objects. It handles atom creation, symbol lookup, and conversion for various mathematical elements. ```APIDOC ## Class MTMathAtomFactory ### Description This factory class offers a comprehensive set of over 25 static methods for creating and managing `MTMathAtom` objects. It simplifies the process of generating atoms from various sources, including placeholders and character-based inputs, and handles symbol registration and conversion. ### Atom Creation - Methods for creating atoms, including placeholder atoms and character-based atoms. ### Symbol Handling - Utilities for symbol lookup and registration within the math rendering system. ### Command Handling - Support for creating atoms from large operators, accents, and stack commands. ### Delimiter and Style Conversion - Functionality for handling delimiters and converting between font and text styles. ``` -------------------------------- ### Placeholder Atoms Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Methods to create placeholder math atoms for various mathematical structures. ```APIDOC ## placeholder ### Description Returns a placeholder square atom, useful for editors. ### Method `+ (MTMathAtom*) placeholder;` ### Returns - `MTMathAtom*`: A placeholder square atom. ``` ```APIDOC ## placeholderFraction ### Description Returns a fraction with placeholder numerator and denominator. ### Method `+ (MTFraction*) placeholderFraction;` ### Returns - `MTFraction*`: A fraction with placeholder numerator and denominator. ``` ```APIDOC ## placeholderSquareRoot ### Description Returns a square root with a placeholder radicand. ### Method `+ (MTRadical *)placeholderSquareRoot;` ### Returns - `MTRadical*`: A square root with a placeholder radicand. ``` ```APIDOC ## placeholderRadical ### Description Returns an n-th root with a placeholder radicand and degree. ### Method `+ (MTRadical*) placeholderRadical;` ### Returns - `MTRadical*`: An n-th root with a placeholder radicand and degree. ``` -------------------------------- ### Create Stack Atom for Command Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathAtomFactory.md Creates a pre-configured MTMathStack atom for a given LaTeX command. The command name should not include the leading backslash. The caller must set the innerList for the returned atom. ```objc + (nullable MTMathStack*) stackAtomForCommand:(NSString*)command NS_SWIFT_NAME(stackAtom(forCommand:)); ``` ```swift if let arrow = MTMathAtomFactory.stackAtom(forCommand: "overrightarrow") { arrow.innerList = baseList } ``` -------------------------------- ### MTMathAtom Methods Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathList.md Methods available for an MTMathAtom instance. ```APIDOC ## MTMathAtom Methods ### scriptsAllowed ```objc - (bool) scriptsAllowed; ``` **Returns:** `true` if this atom can have superscripts or subscripts. Returns `false` for atom types at or after `kMTMathAtomBoundary` (e.g., boundary atoms, spacing atoms). ### stringValue ```objc @property (nonatomic, readonly) NSString *stringValue; ``` A string representation for debugging. ### finalized ```objc - (instancetype) finalized; ``` Returns a finalized copy with merged and reclassified atoms (TeX preprocessing). ``` -------------------------------- ### Set MathList Programmatically Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathUILabel.md Builds and assigns an MTMathList object to the label for rendering, allowing programmatic construction of equations without LaTeX. ```swift // Build math programmatically without LaTeX let num = MTMathListBuilder.build(from: "1")! let denom = MTMathListBuilder.build(from: "2")! let frac = MTMathAtomFactory.fraction(numerator: num, denominator: denom) let list = MTMathList() list.add(frac) label.mathList = list ``` -------------------------------- ### Iterating Over Sub-Displays in MTMathListDisplay Source: https://github.com/kostub/iosmath/blob/master/_autodocs/api-reference/MTMathListDisplay.md Demonstrates how to iterate over the sub-displays of an MTMathListDisplay object. This is useful for inspecting the individual components of a rendered mathematical expression. ```swift if let display = label.displayList { // Iterate over sub-displays for subDisplay in display.subDisplays ?? [] { print("Sub-display type: \(type(of: subDisplay))") } } ```