From 8f8cd19af7f36a9f44fdb14af4b7722e6bbf4597 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Sun, 15 Nov 2026 12:27:34 +0100 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20formulas=20inside=20\left=E2=80=A6\r?= =?UTF-8?q?ight=20and=20bracketed=20environments=20repeated=20characters?= =?UTF-8?q?=20(#59)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In `cases`, `pmatrix`, `bmatrix` and anything between \left and \right, "20" was drawn as "200" and "2x" as "2xx"; the limits of a \sum inside delimiters were dropped. Cause (vendored SwiftMath): the step that merges neighbouring characters rewrote the caller's atoms, and makeLeftRight typeset its content twice (once to size the delimiters, once to place it), so the second pass merged again. Same changes as upstream SwiftMath #70 and #75: - typesetting preprocesses a copy of the list, never the caller's atoms; - makeLeftRight typesets its content once and reuses the display. Tests: the engine is now compiled into the test target (MathEngineTests reads what a formula draws; the fonts come from the source tree through MathFontsBundle.overrideURL). Seven of the nine tests fail without the fix. The engine's `backgroundColor` extension moves from every NSView to its own label: with the engine in the test target it shadowed NSTextView's property wherever an optional colour was expected. Co-Authored-By: Claude Fable 5.2 --- QuickMD/CHANGELOG.md | 6 + QuickMD/QuickMD.xcodeproj/project.pbxproj | 60 ++++ QuickMD/QuickMD/SwiftMath/MTBezierPath.swift | 7 +- QuickMD/QuickMD/SwiftMath/MTFont.swift | 14 +- .../SwiftMath/MTTypesetter+Tokenization.swift | 16 +- QuickMD/QuickMD/SwiftMath/MTTypesetter.swift | 20 +- QuickMD/QuickMD/SwiftMath/MathFont.swift | 4 +- QuickMD/QuickMDTests/MathEngineTests.swift | 280 ++++++++++++++++++ 8 files changed, 394 insertions(+), 13 deletions(-) create mode 100644 QuickMD/QuickMDTests/MathEngineTests.swift diff --git a/QuickMD/CHANGELOG.md b/QuickMD/CHANGELOG.md index 891fc1c..2fcdf55 100644 --- a/QuickMD/CHANGELOG.md +++ b/QuickMD/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to QuickMD will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed +- **Formulas inside brackets repeated characters:** in `cases`, `pmatrix`, `bmatrix` and anything between `\left` and `\right`, `20` was drawn as `200` and `2x` as `2xx`. Thanks to @ilmarmors for the report (#59). +- The limits of a sum, product or integral inside `\left…\right` are drawn again. + ## [1.15.0] - 2026-11-11 Edit side by side, separate windows, tables on macOS 27.2, a redrawn icon, and many documents shown more faithfully. diff --git a/QuickMD/QuickMD.xcodeproj/project.pbxproj b/QuickMD/QuickMD.xcodeproj/project.pbxproj index abac600..f75dae3 100644 --- a/QuickMD/QuickMD.xcodeproj/project.pbxproj +++ b/QuickMD/QuickMD.xcodeproj/project.pbxproj @@ -202,6 +202,35 @@ A1B2C3D401000181 /* SourceEditLanding.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000180 /* SourceEditLanding.swift */; }; A1B2C3D401000182 /* SourceEditLandingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000181 /* SourceEditLandingTests.swift */; }; A1B2C3D4010000F0 /* HeadingLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000F0 /* HeadingLayoutTests.swift */; }; + A1B2C3D401000560 /* MathFont.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000001A /* MathFont.swift */; }; + A1B2C3D401000561 /* MathImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000001B /* MathImage.swift */; }; + A1B2C3D401000562 /* MTBezierPath.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000001C /* MTBezierPath.swift */; }; + A1B2C3D401000563 /* MTColor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000001D /* MTColor.swift */; }; + A1B2C3D401000564 /* MTConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000001E /* MTConfig.swift */; }; + A1B2C3D401000565 /* MTFont.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000001F /* MTFont.swift */; }; + A1B2C3D401000566 /* MTFontManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000020 /* MTFontManager.swift */; }; + A1B2C3D401000567 /* MTFontMathTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000021 /* MTFontMathTable.swift */; }; + A1B2C3D401000568 /* MTFontMathTableV2.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000022 /* MTFontMathTableV2.swift */; }; + A1B2C3D401000569 /* MTFontV2.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000023 /* MTFontV2.swift */; }; + A1B2C3D40100056A /* MTLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000024 /* MTLabel.swift */; }; + A1B2C3D40100056B /* MTMathAtomFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000025 /* MTMathAtomFactory.swift */; }; + A1B2C3D40100056C /* MTMathImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000026 /* MTMathImage.swift */; }; + A1B2C3D40100056D /* MTMathList.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000027 /* MTMathList.swift */; }; + A1B2C3D40100056E /* MTMathListBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000028 /* MTMathListBuilder.swift */; }; + A1B2C3D40100056F /* MTMathListDisplay.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000029 /* MTMathListDisplay.swift */; }; + A1B2C3D401000570 /* MTMathListIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000002A /* MTMathListIndex.swift */; }; + A1B2C3D401000571 /* MTMathUILabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000002B /* MTMathUILabel.swift */; }; + A1B2C3D401000572 /* MTTypesetter.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000002C /* MTTypesetter.swift */; }; + A1B2C3D401000573 /* MTTypesetter+Tokenization.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000002D /* MTTypesetter+Tokenization.swift */; }; + A1B2C3D401000574 /* MTUnicode.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000002E /* MTUnicode.swift */; }; + A1B2C3D401000575 /* RWLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000002F /* RWLock.swift */; }; + A1B2C3D401000576 /* MTAtomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000030 /* MTAtomTokenizer.swift */; }; + A1B2C3D401000577 /* MTBreakableElement.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000031 /* MTBreakableElement.swift */; }; + A1B2C3D401000578 /* MTDisplayGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000032 /* MTDisplayGenerator.swift */; }; + A1B2C3D401000579 /* MTDisplayPreRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000033 /* MTDisplayPreRenderer.swift */; }; + A1B2C3D40100057A /* MTElementWidthCalculator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000034 /* MTElementWidthCalculator.swift */; }; + A1B2C3D40100057B /* MTLineFitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000035 /* MTLineFitter.swift */; }; + A1B2C3D401000541 /* MathEngineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000540 /* MathEngineTests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -358,6 +387,7 @@ A1B2C3D40000004D /* FileWatcherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileWatcherTests.swift; sourceTree = ""; }; A1B2C3D400000066 /* ChromeHoverState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChromeHoverState.swift; sourceTree = ""; }; A1B2C3D400000067 /* ChromeHoverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChromeHoverTests.swift; sourceTree = ""; }; + A1B2C3D400000540 /* MathEngineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MathEngineTests.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -401,6 +431,7 @@ A1B2C3D40000006A /* BlockHeightMeasurerTests.swift */, A1B2C3D4000002A1 /* VerticalRhythmTests.swift */, A1B2C3D400000440 /* MathInTextKindsTests.swift */, + A1B2C3D400000540 /* MathEngineTests.swift */, A1B2C3D400000483 /* InlineSyntaxTests.swift */, A1B2C3D400000462 /* ImageRowTests.swift */, A1B2C3D400000465 /* LocalLinkSafetyTests.swift */, @@ -822,6 +853,35 @@ A1B2C3D40100006A /* BlockHeightMeasurerTests.swift in Sources */, A1B2C3D4010002A2 /* VerticalRhythmTests.swift in Sources */, A1B2C3D401000441 /* MathInTextKindsTests.swift in Sources */, + A1B2C3D401000560 /* MathFont.swift in Sources */, + A1B2C3D401000561 /* MathImage.swift in Sources */, + A1B2C3D401000562 /* MTBezierPath.swift in Sources */, + A1B2C3D401000563 /* MTColor.swift in Sources */, + A1B2C3D401000564 /* MTConfig.swift in Sources */, + A1B2C3D401000565 /* MTFont.swift in Sources */, + A1B2C3D401000566 /* MTFontManager.swift in Sources */, + A1B2C3D401000567 /* MTFontMathTable.swift in Sources */, + A1B2C3D401000568 /* MTFontMathTableV2.swift in Sources */, + A1B2C3D401000569 /* MTFontV2.swift in Sources */, + A1B2C3D40100056A /* MTLabel.swift in Sources */, + A1B2C3D40100056B /* MTMathAtomFactory.swift in Sources */, + A1B2C3D40100056C /* MTMathImage.swift in Sources */, + A1B2C3D40100056D /* MTMathList.swift in Sources */, + A1B2C3D40100056E /* MTMathListBuilder.swift in Sources */, + A1B2C3D40100056F /* MTMathListDisplay.swift in Sources */, + A1B2C3D401000570 /* MTMathListIndex.swift in Sources */, + A1B2C3D401000571 /* MTMathUILabel.swift in Sources */, + A1B2C3D401000572 /* MTTypesetter.swift in Sources */, + A1B2C3D401000573 /* MTTypesetter+Tokenization.swift in Sources */, + A1B2C3D401000574 /* MTUnicode.swift in Sources */, + A1B2C3D401000575 /* RWLock.swift in Sources */, + A1B2C3D401000576 /* MTAtomTokenizer.swift in Sources */, + A1B2C3D401000577 /* MTBreakableElement.swift in Sources */, + A1B2C3D401000578 /* MTDisplayGenerator.swift in Sources */, + A1B2C3D401000579 /* MTDisplayPreRenderer.swift in Sources */, + A1B2C3D40100057A /* MTElementWidthCalculator.swift in Sources */, + A1B2C3D40100057B /* MTLineFitter.swift in Sources */, + A1B2C3D401000541 /* MathEngineTests.swift in Sources */, A1B2C3D401000484 /* InlineSyntaxTests.swift in Sources */, A1B2C3D401000462 /* ImageRowTests.swift in Sources */, A1B2C3D401000465 /* LocalLinkSafetyTests.swift in Sources */, diff --git a/QuickMD/QuickMD/SwiftMath/MTBezierPath.swift b/QuickMD/QuickMD/SwiftMath/MTBezierPath.swift index fb5e082..834c8cf 100755 --- a/QuickMD/QuickMD/SwiftMath/MTBezierPath.swift +++ b/QuickMD/QuickMD/SwiftMath/MTBezierPath.swift @@ -17,7 +17,12 @@ extension MTBezierPath { } } -extension MTView { +// QuickMD (#59): upstream declares this on MTView, i.e. on EVERY NSView. A read +// of `textView.backgroundColor` where an optional colour is expected then binds +// to this layer property instead of NSTextView's own (it broke the editor's +// colour tests once the engine was compiled into the test target). The label +// is the only user, so the property lives on the label. +extension MTMathUILabel { var backgroundColor:MTColor? { get { diff --git a/QuickMD/QuickMD/SwiftMath/MTFont.swift b/QuickMD/QuickMD/SwiftMath/MTFont.swift index 36a79eb..b0e2e16 100644 --- a/QuickMD/QuickMD/SwiftMath/MTFont.swift +++ b/QuickMD/QuickMD/SwiftMath/MTFont.swift @@ -46,8 +46,7 @@ public class MTFont { } static var fontBundle:Bundle { - // Uses bundle for class so that this can be access by the unit tests. - Bundle(url: Bundle.main.url(forResource: "mathFonts", withExtension: "bundle")!)! + Bundle(url: MathFontsBundle.url!)! } /** Returns a copy of this font but with a different size. */ @@ -78,3 +77,14 @@ public class MTFont { } } + +/// Where the math fonts live (QuickMD addition, #59). The app reads them from +/// its own bundle. The unit tests have no host app (their main bundle is the +/// test runner), so `MathEngineTests` points `overrideURL` at the folder in the +/// source tree to typeset with the real engine. +enum MathFontsBundle { + static var overrideURL: URL? + static var url: URL? { + overrideURL ?? Bundle.main.url(forResource: "mathFonts", withExtension: "bundle") + } +} diff --git a/QuickMD/QuickMD/SwiftMath/MTTypesetter+Tokenization.swift b/QuickMD/QuickMD/SwiftMath/MTTypesetter+Tokenization.swift index 3911df6..4334e5a 100644 --- a/QuickMD/QuickMD/SwiftMath/MTTypesetter+Tokenization.swift +++ b/QuickMD/QuickMD/SwiftMath/MTTypesetter+Tokenization.swift @@ -33,7 +33,21 @@ extension MTTypesetter { // Phase 0: Preprocess atoms to fuse ordinary characters // This is critical for accents and other structures where multi-character // text like "xyzw" should stay together as a single atom - let preprocessedAtoms = MTTypesetter.preprocessMathList(mathList) + // + // INVARIANT: typesetting never changes its input (upstream SwiftMath #75; + // QuickMD #59). `preprocessMathList` mutates the atoms it is handed (it + // rewrites `type` and `nucleus`, and `MTMathAtom.fuse(with:)` appends the + // next atom's nucleus onto the previous atom while the next atom stays in + // the list). Every internal typeset request funnels through this function, + // and some typeset the same list more than once (delimiter measurement, + // accent re-layout), so preprocessing the caller's atoms made the second + // pass fuse again: "2","x" became "2x", then "2x","x" became "2xx". + // Preprocess a deep copy instead. `MTMathAtom.copy()` is the + // type-dispatched deep copy (sublists included); `finalized` is + // deliberately not used here because it re-applies TeX rules 5 & 6. + let atomsToPreprocess = MTMathList() + atomsToPreprocess.atoms = mathList.atoms.map { $0.copy() } + let preprocessedAtoms = MTTypesetter.preprocessMathList(atomsToPreprocess) // Phase 1: Tokenize atoms into breakable elements let tokenizer = MTAtomTokenizer(font: font, style: style, cramped: cramped, maxWidth: maxWidth) diff --git a/QuickMD/QuickMD/SwiftMath/MTTypesetter.swift b/QuickMD/QuickMD/SwiftMath/MTTypesetter.swift index e1c1c93..87a830e 100644 --- a/QuickMD/QuickMD/SwiftMath/MTTypesetter.swift +++ b/QuickMD/QuickMD/SwiftMath/MTTypesetter.swift @@ -1216,6 +1216,11 @@ class MTTypesetter { let glyphHeight: CGFloat + // Typeset the inner content at most once. The resulting display is reused + // for both the delimiter height calculation and the placement below + // (upstream SwiftMath #70; QuickMD #59). + var innerListDisplay: MTMathListDisplay? = nil + // Check if we have an explicit delimiter height (from \big, \Big, etc.) if let delimiterMultiplier = inner!.delimiterHeight { // delimiterHeight is a multiplier (e.g., 1.2, 1.8, 2.4, 3.0) @@ -1223,7 +1228,7 @@ class MTTypesetter { glyphHeight = styleFont.fontSize * delimiterMultiplier } else { // Calculate height based on inner content (for \left...\right) - let innerListDisplay = MTTypesetter.createLineForMathList(inner!.innerList, font:font, style:style, cramped:cramped, spaced:true, maxWidth:maxWidth) + innerListDisplay = MTTypesetter.createLineForMathList(inner!.innerList, font:font, style:style, cramped:cramped, spaced:true, maxWidth:maxWidth) let axisHeight = styleFont.mathTable!.axisHeight // delta is the max distance from the axis let delta = max(innerListDisplay!.ascent - axisHeight, innerListDisplay!.descent + axisHeight); @@ -1251,12 +1256,13 @@ class MTTypesetter { } // Only include inner content if not using explicit delimiter height - // (explicit height commands like \big produce standalone delimiters) - if inner!.delimiterHeight == nil { - let innerListDisplay = MTTypesetter.createLineForMathList(inner!.innerList, font:font, style:style, cramped:cramped, spaced:true, maxWidth:maxWidth) - innerListDisplay!.position = position; - position.x += innerListDisplay!.width; - innerElements.append(innerListDisplay!) + // (explicit height commands like \big produce standalone delimiters). + // Reuse the display already typeset for the height calculation above so the + // inner list is never typeset twice. + if inner!.delimiterHeight == nil, let innerListDisplay { + innerListDisplay.position = position; + position.x += innerListDisplay.width; + innerElements.append(innerListDisplay) } if inner!.rightBoundary != nil && !inner!.rightBoundary!.nucleus.isEmpty { diff --git a/QuickMD/QuickMD/SwiftMath/MathFont.swift b/QuickMD/QuickMD/SwiftMath/MathFont.swift index 650d8f6..54c8092 100644 --- a/QuickMD/QuickMD/SwiftMath/MathFont.swift +++ b/QuickMD/QuickMD/SwiftMath/MathFont.swift @@ -109,7 +109,7 @@ private class BundleManager { attributes: .concurrent) private func registerCGFont(mathFont: MathFont) throws { - guard let frameworkBundleURL = Bundle.main.url(forResource: "mathFonts", withExtension: "bundle"), + guard let frameworkBundleURL = MathFontsBundle.url, let resourceBundleURL = Bundle(url: frameworkBundleURL)?.path(forResource: mathFont.rawValue, ofType: "otf") else { throw FontError.fontPathNotFound } @@ -136,7 +136,7 @@ private class BundleManager { } private func registerMathTable(mathFont: MathFont) throws { - guard let frameworkBundleURL = Bundle.main.url(forResource: "mathFonts", withExtension: "bundle"), + guard let frameworkBundleURL = MathFontsBundle.url, let mathTablePlist = Bundle(url: frameworkBundleURL)?.url(forResource: mathFont.rawValue, withExtension:"plist") else { throw FontError.fontPathNotFound } diff --git a/QuickMD/QuickMDTests/MathEngineTests.swift b/QuickMD/QuickMDTests/MathEngineTests.swift new file mode 100644 index 0000000..fbb463b --- /dev/null +++ b/QuickMD/QuickMDTests/MathEngineTests.swift @@ -0,0 +1,280 @@ +import XCTest +import AppKit + +/// The vendored SwiftMath engine, typeset for real (#59). +/// +/// Every other test stands a stub in for the engine; these compile its sources +/// into the test target and read what a formula DRAWS: the text of every glyph +/// run in the display tree. They never read sizes or font names, only which +/// characters come out and in which order, so they do not depend on the OS. +/// +/// The rule under test: TYPESETTING NEVER CHANGES ITS INPUT. Until 1.15.0 the +/// step that merges neighbouring characters ("2", "x" → "2x") rewrote the +/// caller's atoms, and `\left…\right` typeset its content twice (once to size +/// the delimiters, once to place it), so the second pass merged again: +/// "2x", "x" → "2xx". Every environment that draws delimiters (`cases`, +/// `pmatrix`, `bmatrix`, …) and every `\left…\right` repeated characters; the +/// measuring pass also used up the limits of a `\sum` inside delimiters. +/// +/// Negative control: with the two engine changes reverted +/// (`MTTypesetter+Tokenization.swift` copies before preprocessing, +/// `makeLeftRight` typesets once) seven of the nine tests fail. The two that +/// pass guard what already held: the inline source path (fixed in 1.15.0) and +/// the public entry, which always typeset a copy. +final class MathEngineTests: XCTestCase { + + // MARK: - Fixtures + + /// No host app: the test runner's main bundle has no fonts, so the engine + /// reads them from the source tree. Restored afterwards (process-wide state). + override class func setUp() { + super.setUp() + MathFontsBundle.overrideURL = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // QuickMDTests + .deletingLastPathComponent() // the project folder + .appendingPathComponent("QuickMD/SwiftMath/mathFonts.bundle") + } + + override class func tearDown() { + MathFontsBundle.overrideURL = nil + super.tearDown() + } + + private var font: MTFont { MathFont.latinModernFont.mtfont(size: 20) } + + private func build(_ latex: String, file: StaticString = #filePath, line: UInt = #line) -> MTMathList? { + var error: NSError? + let list = MTMathListBuilder.build(fromString: latex, error: &error) + XCTAssertNil(error, "\(latex) must parse", file: file, line: line) + XCTAssertNotNil(list, "\(latex) must parse", file: file, line: line) + return list + } + + /// What the formula draws, as the app typesets it (`MathImage` uses this + /// public entry): every glyph run, in drawing-tree order, as plain text. + private func drawn(_ latex: String, style: MTLineStyle = .display, + file: StaticString = #filePath, line: UInt = #line) -> String { + guard let list = build(latex, file: file, line: line), + let display = MTTypesetter.createLineForMathList(list, font: font, style: style) else { + XCTFail("\(latex) must typeset", file: file, line: line) + return "" + } + return Self.text(of: display) + } + + private static func text(of display: MTDisplay?) -> String { + guard let display else { return "" } + if let line = display as? MTCTLineDisplay { return plain(line.attributedString?.string ?? "") } + if let list = display as? MTMathListDisplay { return list.subDisplays.map { text(of: $0) }.joined() } + if let fraction = display as? MTFractionDisplay { return text(of: fraction.numerator) + text(of: fraction.denominator) } + if let radical = display as? MTRadicalDisplay { return text(of: radical.degree) + text(of: radical.radicand) } + if let accent = display as? MTAccentDisplay { return text(of: accent.accentee) } + if let line = display as? MTLineDisplay { return text(of: line.inner) } + if let limits = display as? MTLargeOpLimitsDisplay { + return text(of: limits.nucleus) + text(of: limits.upperLimit) + text(of: limits.lowerLimit) + } + return "" // a single glyph: a delimiter, a big operator, a radical sign + } + + /// The engine draws variables with the mathematical italic letters; map + /// them back so expectations read as the source does. Spaces are dropped: + /// only the characters matter. + private static func plain(_ string: String) -> String { + var result = String.UnicodeScalarView() + for scalar in string.unicodeScalars { + switch scalar.value { + case 0x1D434...0x1D44D: result.append(UnicodeScalar(scalar.value - 0x1D434 + 0x41)!) // 𝐴…𝑍 + case 0x1D44E...0x1D467: result.append(UnicodeScalar(scalar.value - 0x1D44E + 0x61)!) // 𝑎…𝑧 + case 0x210E: result.append("h") // ℎ + case 0x2212: result.append("-") // − + case 0x20, 0xA0: continue + default: result.append(scalar) + } + } + return String(result) + } + + /// Every nucleus in the list, through scripts and nested lists. + private static func nuclei(of list: MTMathList?) -> [String] { + guard let list else { return [] } + var result: [String] = [] + for atom in list.atoms { + result.append(atom.nucleus) + result += nuclei(of: atom.superScript) + nuclei(of: atom.subScript) + if let inner = atom as? MTInner { result += nuclei(of: inner.innerList) } + if let fraction = atom as? MTFraction { result += nuclei(of: fraction.numerator) + nuclei(of: fraction.denominator) } + if let radical = atom as? MTRadical { result += nuclei(of: radical.degree) + nuclei(of: radical.radicand) } + if let accent = atom as? MTAccent { result += nuclei(of: accent.innerList) } + if let over = atom as? MTOverLine { result += nuclei(of: over.innerList) } + if let under = atom as? MTUnderLine { result += nuclei(of: under.innerList) } + if let table = atom as? MTMathTable { + for row in table.cells { for cell in row { result += nuclei(of: cell) } } + } + } + return result + } + + // MARK: - The report (#59) + + /// The reporter's file, case by case. Before the fix: `200`, `122`, + /// `80x0x`, `15x²5x²`. + func testTheReportedFormulasDrawEachCharacterOnce() { + // A. cases, display + XCTAssertEqual(drawn(#"\begin{cases} \frac{20}{x + y} = 12 \\ 80x = 15x^2 \end{cases}"#), + "20x+y=1280x=15x2") + // C. aligned inside \left\{ … \right. + XCTAssertEqual(drawn(#"\left\{\begin{aligned} \frac{20}{x + y} &= 12 \\ 80x &= 15x^2 \end{aligned}\right."#), + "20x+y=1280x=15x2") + // D. matrix (was right: it draws no delimiters) + XCTAssertEqual(drawn(#"\begin{matrix} 20 & 12 \\ 80x & 15x^2 \end{matrix}"#), "201280x15x2") + // E. cases in a line of text (text style) + XCTAssertEqual(drawn(#"\begin{cases} 20 = 12 \\ 80x = 15 \end{cases}"#, style: .text), "20=1280x=15") + // The tokens quoted from the reporter's longer document. + XCTAssertEqual(drawn(#"\begin{cases} x + 2y = 7{,}5 \\ 40(x - y) = 48y^2 \end{cases}"#), + "x+2y=7,540(x-y)=48y2") + } + + /// Case E of the report also ran its two rows together: its picture is + /// exactly what the engine draws when `\ ` arrives in place of the source's + /// `\\`. A formula is an atom decided on the source line (constraints.md + /// "Inline math"), so the row break must reach the engine as written, in + /// every text kind that typesets inline formulas. + @MainActor + func testAnInlineFormulaReachesTheEngineWithItsRowBreak() { + let formula = #"\begin{cases} 20 = 12 \\ 80x = 15 \end{cases}"# + let theme = MarkdownTheme.cached(for: .light) + for markdown in ["E. Inline cases: $\(formula)$", "> quoted $\(formula)$", "# Heading $\(formula)$", + "| a |\n|---|\n| $\(formula)$ |"] { + var asked: [String] = [] + let engine = MathRendering(inlineImage: { latex, _, _ in + asked.append(latex) + return NSImage(size: NSSize(width: 40, height: 30)) + }, displayHeight: { _, _, _ in 40 }) + let blocks = MarkdownBlockParser(theme: theme, fontScale: 1).parse(markdown) + let raw = BlockHeightMeasurer.measure(blocks: blocks, theme: theme, fontScale: 1, + contentWidth: 600, math: nil) + _ = BlockHeightMeasurer.measureMathRows(raw.mathPendingRows, in: raw, blocks: blocks, theme: theme, + fontScale: 1, contentWidth: 600, math: engine) + XCTAssertFalse(asked.isEmpty, markdown) + XCTAssertTrue(asked.allSatisfy { $0 == formula }, "\(markdown): \(asked)") + } + } + + // MARK: - Delimiters never change what is inside + + private static let bodies = [ + "80x", "2x+1", "ab", "12ab", #"\frac{12ab}{cd}"#, #"\sqrt{2xy}"#, "x^{2ab}", #"3y - 40z"#, + #"\text{clip}(x)"#, #"\sin 2x"#, #"\hat{ab} + \vec{cd}"#, #"a_{12n}b"# + ] + + func testLeftRightDrawsItsContentAsWithoutDelimiters() { + let pairs = [(#"\left("#, #"\right)"#), (#"\left["#, #"\right]"#), (#"\left|"#, #"\right|"#), + (#"\left\{"#, #"\right."#), (#"\left."#, #"\right\}"#), (#"\left\langle "#, #"\right\rangle"#)] + for style in [MTLineStyle.display, .text] { + for body in Self.bodies { + let expected = drawn(body, style: style) + XCTAssertFalse(expected.isEmpty, body) + for (open, close) in pairs { + XCTAssertEqual(drawn(open + body + close, style: style), expected, "\(open) \(body) \(close)") + } + } + } + } + + /// Each level used to double the damage: two levels drew `12abababab`. + func testNestedDelimitersDrawTheirContentOnce() { + for body in Self.bodies { + let expected = drawn(body) + XCTAssertEqual(drawn(#"\left(\left("# + body + #"\right)\right)"#), expected, body) + XCTAssertEqual(drawn(#"\left(\left[\left\{"# + body + #"\right\}\right]\right)"#), expected, body) + } + XCTAssertEqual(drawn(#"\left(\left(12ab\right)\right)"#), "12ab") + } + + /// Delimiters in every place a list is typeset from: scripts, fractions, + /// radicals, the rows of an environment. + func testDelimitersInsideOtherStructuresDrawTheirContentOnce() { + XCTAssertEqual(drawn(#"\sqrt{\left(2x\right)^2 + \left(3y\right)^2}"#), "2x2+3y2") + XCTAssertEqual(drawn(#"\frac{\left(2ab\right)}{\left(3cd\right)}"#), "2ab3cd") + XCTAssertEqual(drawn(#"x_{\left(2ab\right)}^{\left[3cd\right]}"#), drawn(#"x_{2ab}^{3cd}"#)) + XCTAssertEqual(drawn(#"\lim_{n \to \infty} \left(1 + \frac{1}{2n}\right)^{2n}"#), + drawn(#"\lim_{n \to \infty} 1 + \frac{1}{2n}^{2n}"#)) + XCTAssertEqual(drawn(#"f(x) = \begin{cases} 2x & \text{if } x > 10 \\ 15x^2 & \text{otherwise} \end{cases}"#), + "f(x)=2xifx>1015x2otherwise") + } + + /// The measuring pass used up a big operator's limits, so the placed pass + /// drew `∑` bare: the bounds vanished inside `\left…\right`. + func testLimitsOfABigOperatorSurviveDelimiters() { + for body in [#"\sum_{i=1}^{n} x_i"#, #"\prod_{k=1}^{12} ab"#, #"\int_{0}^{2\pi} f(x)"#, #"\lim_{n \to 0} 2n"#] { + let expected = drawn(body) + XCTAssertEqual(drawn(#"\left("# + body + #"\right)"#), expected, body) + } + XCTAssertEqual(drawn(#"\left(\sum_{i=1}^{n} x_i\right)"#), "ni=1xi", "the bounds are drawn") + } + + // MARK: - Environments + + /// Every environment that draws delimiters went through the same double + /// pass; a cell draws what the same source draws on its own. + func testEnvironmentCellsDrawTheirSourceOnce() { + let cells = [["20", "12ab"], ["80x", "15x^2"], [#"\frac{2ab}{3cd}"#, "x + 2y"]] + let expected = cells.flatMap { $0 }.map { drawn($0) }.joined() + let rows = cells.map { $0.joined(separator: " & ") }.joined(separator: #" \\ "#) + for environment in ["matrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix", "cases"] { + XCTAssertEqual(drawn("\\begin{\(environment)} \(rows) \\end{\(environment)}"), expected, environment) + XCTAssertEqual(drawn("\\begin{\(environment)} \(rows) \\end{\(environment)}", style: .text), expected, + "\(environment), text style") + } + // Alignment environments, bare and inside delimiters. + for environment in ["aligned", "split"] { + let table = "\\begin{\(environment)} 80x &= 15x^2 \\\\ 12y &= 7ab \\end{\(environment)}" + XCTAssertEqual(drawn(table), "80x=15x212y=7ab", environment) + XCTAssertEqual(drawn(#"\left\{"# + table + #"\right."#), "80x=15x212y=7ab", environment) + XCTAssertEqual(drawn(#"\left("# + table + #"\right)"#), "80x=15x212y=7ab", environment) + } + } + + // MARK: - The invariant + + private static let invariantCases = [ + #"\left(80x\right)"#, #"\left(\left(12ab\right)\right)"#, #"\left(\sum_{i=1}^{n} x_i\right)"#, + #"\begin{cases} \frac{20}{x + y} = 12 \\ 80x = 15x^2 \end{cases}"#, + #"\begin{pmatrix} 20 & 12ab \\ 80x & 15x^2 \end{pmatrix}"#, + #"\begin{aligned} 80x &= 15x^2 \\ 12y &= 7ab \end{aligned}"#, + #"\widehat{abc} + \overrightarrow{AB} + \vec{ab}"#, #"\sqrt[3]{80x} + \frac{80x}{12y}"#, + #"\overline{80x} + \underline{12ab}"#, #"x^{12ab}_{34cd}"#, #"\text{clip}(2xy)"# + ] + + /// The internal entry is the one nested lists go through, and it takes the + /// caller's list as it is. Typesetting it must leave every atom alone, so a + /// second pass over the same list draws the same thing. + func testTypesettingLeavesTheListUnchangedAndCanBeRepeated() { + for latex in Self.invariantCases { + guard let list = build(latex)?.finalized else { continue } + let before = Self.nuclei(of: list) + let first = MTTypesetter.createLineForMathList(list, font: font, style: .display, cramped: false) + XCTAssertEqual(Self.nuclei(of: list), before, "the first pass changed the list: \(latex)") + let second = MTTypesetter.createLineForMathList(list, font: font, style: .display, cramped: false) + XCTAssertEqual(Self.nuclei(of: list), before, "the second pass changed the list: \(latex)") + XCTAssertFalse(Self.text(of: first).isEmpty, latex) + XCTAssertEqual(Self.text(of: second), Self.text(of: first), latex) + XCTAssertEqual(second?.width, first?.width, latex) + XCTAssertEqual(second?.ascent, first?.ascent, latex) + XCTAssertEqual(second?.descent, first?.descent, latex) + } + } + + /// The same through the entry the app uses: one parsed list, typeset for + /// the measurer and again for the view. + func testAParsedListCanBeTypesetAgain() { + for latex in Self.invariantCases { + guard let list = build(latex) else { continue } + let before = Self.nuclei(of: list) + let first = MTTypesetter.createLineForMathList(list, font: font, style: .display) + let second = MTTypesetter.createLineForMathList(list, font: font, style: .text) + XCTAssertEqual(Self.nuclei(of: list), before, latex) + XCTAssertEqual(Self.text(of: second), Self.text(of: first), latex) + } + } +} From 291a2613901ca1b2839b7518e06e2ae0129865ac Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Sun, 15 Nov 2026 12:38:17 +0100 Subject: [PATCH 2/3] fix: math engine - crash on a row break taken as an argument, sign spacing, space widths Found while fixing #59, all in the vendored SwiftMath: - Crash: `b^\\` inside aligned / matrix / cases took the row break as the exponent, advanced the row count twice and the table parser indexed a row it never made (a trap that closed the app). Rows now grow to the row the parser is on (upstream SwiftMath #76). - Signs: TeX rule 5 looks at the previous atom; a style change or a space is not one. `\displaystyle -x`, `\quad -x` and every matrix or cases cell starting with `-` (cells begin with a style) were spaced like a subtraction. A subtraction keeps its spacing. - Spaces: a space command is as wide as it asks for (`\,` 3mu, `\;` 5mu, `\quad` 18mu, `\qquad` 36mu, `\!` -3mu). The tokenizer measured the atom's type, so every one of them was a thin space. Tests: MathEngineTests (crash inputs parse and typeset; widths compared with each other, never with numbers). The sign and space tests fail without the two changes. Co-Authored-By: Claude Fable 5.2 --- QuickMD/CHANGELOG.md | 3 + QuickMD/QuickMD/SwiftMath/MTMathList.swift | 16 ++- .../QuickMD/SwiftMath/MTMathListBuilder.swift | 8 +- QuickMD/QuickMD/SwiftMath/MTTypesetter.swift | 15 ++- .../Tokenization/MTAtomTokenizer.swift | 11 ++- .../MTElementWidthCalculator.swift | 7 ++ QuickMD/QuickMDTests/MathEngineTests.swift | 98 ++++++++++++++++++- 7 files changed, 143 insertions(+), 15 deletions(-) diff --git a/QuickMD/CHANGELOG.md b/QuickMD/CHANGELOG.md index 2fcdf55..f513ec1 100644 --- a/QuickMD/CHANGELOG.md +++ b/QuickMD/CHANGELOG.md @@ -8,8 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Fixed +- **A crash on a malformed formula:** a row break right after `^` or `_` inside `aligned`, `matrix` or `cases` (for example `b^\\`) closed QuickMD. - **Formulas inside brackets repeated characters:** in `cases`, `pmatrix`, `bmatrix` and anything between `\left` and `\right`, `20` was drawn as `200` and `2x` as `2xx`. Thanks to @ilmarmors for the report (#59). - The limits of a sum, product or integral inside `\left…\right` are drawn again. +- A minus or plus sign at the start of a matrix or `cases` cell, or right after `\displaystyle` or a space command, sits against its number instead of being spaced like a subtraction. +- Space commands have their own widths: `\quad`, `\qquad`, `\;` and `\!` were all drawn as narrow as `\,`. ## [1.15.0] - 2026-11-11 diff --git a/QuickMD/QuickMD/SwiftMath/MTMathList.swift b/QuickMD/QuickMD/SwiftMath/MTMathList.swift index 9feb02d..dd149b0 100644 --- a/QuickMD/QuickMD/SwiftMath/MTMathList.swift +++ b/QuickMD/QuickMD/SwiftMath/MTMathList.swift @@ -923,6 +923,11 @@ public class MTMathList : NSObject { let zeroRange = NSMakeRange(0, 0) var prevNode: MTMathAtom? = nil + // TeX's "most recent previous atom" for rules 5 & 6 (QuickMD): style + // changes and spaces are not atoms, so `\displaystyle -x`, `\quad -x` + // and a matrix cell `-1` (cells start with a style) begin with a sign, + // not with a subtraction. + var prevNoad: MTMathAtom? = nil for atom in self.atoms { let newNode = atom.finalized @@ -949,12 +954,12 @@ public class MTMathList : NSObject { switch newNode.type { case .binaryOperator: - if isNotBinaryOperator(prevNode) { + if isNotBinaryOperator(prevNoad) { newNode.type = .unaryOperator } case .relation, .punctuation, .close: - if prevNode != nil && prevNode!.type == .binaryOperator { - prevNode!.type = .unaryOperator + if prevNoad != nil && prevNoad!.type == .binaryOperator { + prevNoad!.type = .unaryOperator } case .number: if prevNode != nil && prevNode!.type == .number && prevNode!.subScript == nil && prevNode!.superScript == nil { @@ -965,9 +970,10 @@ public class MTMathList : NSObject { } finalizedList.add(newNode) prevNode = newNode + if newNode.type != .style && newNode.type != .space { prevNoad = newNode } } - if prevNode != nil && prevNode!.type == .binaryOperator { - prevNode!.type = .unaryOperator + if prevNoad != nil && prevNoad!.type == .binaryOperator { + prevNoad!.type = .unaryOperator } return finalizedList } diff --git a/QuickMD/QuickMD/SwiftMath/MTMathListBuilder.swift b/QuickMD/QuickMD/SwiftMath/MTMathListBuilder.swift index 4083fd9..a40a2fc 100644 --- a/QuickMD/QuickMD/SwiftMath/MTMathListBuilder.swift +++ b/QuickMD/QuickMD/SwiftMath/MTMathListBuilder.swift @@ -1529,7 +1529,13 @@ public struct MTMathListBuilder { currentCol+=1 if currentEnv!.numRows > currentRow { currentRow = currentEnv!.numRows - rows.append([MTMathList]()) + // A row break consumed inside a sub-list (e.g. `x^\\`) can advance + // numRows by more than one per cell, so grow to the row we're on + // rather than by exactly one, or the subscript above traps + // (upstream SwiftMath #76). + while rows.count <= currentRow { + rows.append([MTMathList]()) + } currentCol = 0 } } diff --git a/QuickMD/QuickMD/SwiftMath/MTTypesetter.swift b/QuickMD/QuickMD/SwiftMath/MTTypesetter.swift index 87a830e..b774904 100644 --- a/QuickMD/QuickMD/SwiftMath/MTTypesetter.swift +++ b/QuickMD/QuickMD/SwiftMath/MTTypesetter.swift @@ -502,6 +502,10 @@ class MTTypesetter { // that are not included in TeX and applies Rule 14 to merge ordinary characters. var preprocessed = [MTMathAtom]() // arrayWithCapacity:ml.atoms.count) var prevNode:MTMathAtom! = nil + // TeX's "most recent previous atom" for Rule 5 (QuickMD): style changes + // and spaces are not atoms. `prevNode` stays the immediate neighbour, + // which is what fusing needs. + var prevNoad:MTMathAtom? = nil preprocessed.reserveCapacity(ml!.atoms.count) for atom in ml!.atoms { if atom.type == .variable || atom.type == .number { @@ -520,16 +524,16 @@ class MTTypesetter { // to ordinary when it appears after: Bin, Op, Rel, Open, Punct, or at the beginning // This handles cases like "=-2" where minus should be unary, not binary let shouldConvertToOrdinary: Bool - if prevNode == nil { - // At the beginning of the list - shouldConvertToOrdinary = true - } else { - switch prevNode.type { + if let prevNoad { + switch prevNoad.type { case .binaryOperator, .relation, .open, .punctuation, .largeOperator: shouldConvertToOrdinary = true default: shouldConvertToOrdinary = false } + } else { + // At the beginning of the list + shouldConvertToOrdinary = true } if shouldConvertToOrdinary { @@ -552,6 +556,7 @@ class MTTypesetter { // TODO: add italic correction here or in second pass? prevNode = atom + if atom.type != .style && atom.type != .space { prevNoad = atom } preprocessed.append(atom) } return preprocessed diff --git a/QuickMD/QuickMD/SwiftMath/Tokenization/MTAtomTokenizer.swift b/QuickMD/QuickMD/SwiftMath/Tokenization/MTAtomTokenizer.swift index 1547269..946539b 100644 --- a/QuickMD/QuickMD/SwiftMath/Tokenization/MTAtomTokenizer.swift +++ b/QuickMD/QuickMD/SwiftMath/Tokenization/MTAtomTokenizer.swift @@ -1121,7 +1121,16 @@ class MTAtomTokenizer { private func tokenizeSpace(_ atom: MTMathAtom, prevAtom: MTMathAtom?, atomIndex: Int) -> MTBreakableElement? { // Space atoms typically don't participate in breaking // They are rendered as-is - let width = widthCalculator.measureSpace(atom.type) + // + // QuickMD: a space command is as wide as it asks for (`\,` 3mu, `\;` 5mu, + // `\quad` 18mu, `\qquad` 36mu, `\!` -3mu). Upstream measures the atom's + // TYPE, so every one of them came out as a thin space. + let width: CGFloat + if let space = atom as? MTMathSpace { + width = widthCalculator.measureSpace(mu: space.space) + } else { + width = widthCalculator.measureSpace(atom.type) + } return MTBreakableElement( content: .space(width), diff --git a/QuickMD/QuickMD/SwiftMath/Tokenization/MTElementWidthCalculator.swift b/QuickMD/QuickMD/SwiftMath/Tokenization/MTElementWidthCalculator.swift index 258eb76..f88bd9c 100644 --- a/QuickMD/QuickMD/SwiftMath/Tokenization/MTElementWidthCalculator.swift +++ b/QuickMD/QuickMD/SwiftMath/Tokenization/MTElementWidthCalculator.swift @@ -105,6 +105,13 @@ class MTElementWidthCalculator { } } + /// Width of a space command given in mu (QuickMD), in the same mu as the + /// spacing between atoms. Negative for `\!`. + func measureSpace(mu: CGFloat) -> CGFloat { + guard let mathTable = font.mathTable else { return 0 } + return mathTable.muUnit * mu + } + /// Measure explicit space value func measureExplicitSpace(_ width: CGFloat) -> CGFloat { return width diff --git a/QuickMD/QuickMDTests/MathEngineTests.swift b/QuickMD/QuickMDTests/MathEngineTests.swift index fbb463b..5150738 100644 --- a/QuickMD/QuickMDTests/MathEngineTests.swift +++ b/QuickMD/QuickMDTests/MathEngineTests.swift @@ -18,9 +18,11 @@ import AppKit /// /// Negative control: with the two engine changes reverted /// (`MTTypesetter+Tokenization.swift` copies before preprocessing, -/// `makeLeftRight` typesets once) seven of the nine tests fail. The two that -/// pass guard what already held: the inline source path (fixed in 1.15.0) and -/// the public entry, which always typeset a copy. +/// `makeLeftRight` typesets once) seven of the first nine tests fail. The two +/// that pass guard what already held: the inline source path (fixed in 1.15.0) +/// and the public entry, which always typeset a copy. The "Signs and spaces" +/// tests have their own control: without the previous-atom rule and the +/// per-command space width the sign test and the space test fail. final class MathEngineTests: XCTestCase { // MARK: - Fixtures @@ -235,6 +237,96 @@ final class MathEngineTests: XCTestCase { } } + // MARK: - Signs and spaces (found while fixing #59) + + private func width(_ latex: String, file: StaticString = #filePath, line: UInt = #line) -> CGFloat { + guard let list = build(latex, file: file, line: line), + let display = MTTypesetter.createLineForMathList(list, font: font, style: .display) else { + XCTFail("\(latex) must typeset", file: file, line: line) + return 0 + } + return display.width + } + + /// TeX rule 5: a `-` or `+` with no atom before it is a sign, set tight + /// against what follows. A style change or a space is not an atom, and a + /// matrix or cases cell starts with a style change — so `\displaystyle -x` + /// and every negative matrix entry were spaced like a subtraction (`− 1`). + /// Widths are compared with each other, never with a number. + func testASignAfterAStyleChangeOrASpaceIsSetTight() { + let sign = width("-x") + XCTAssertEqual(width(#"\displaystyle -x"#), sign, accuracy: 0.01) + XCTAssertEqual(width(#"\textstyle -x"#), sign, accuracy: 0.01) + XCTAssertEqual(width(#"\begin{matrix} -x \end{matrix}"#), sign, accuracy: 0.01) + XCTAssertEqual(width(#"\begin{matrix} +x \end{matrix}"#), width("+x"), accuracy: 0.01) + XCTAssertEqual(width(#"\begin{matrix} -1 & 2 \\ 3 & -4 \end{matrix}"#), + width(#"\begin{matrix} {-1} & 2 \\ 3 & {-4} \end{matrix}"#), accuracy: 0.01) + XCTAssertEqual(drawn(#"\begin{cases} -x & x < 0 \\ x & x \ge 0 \end{cases}"#), "-xx<0xx≥0") + // After a space the sign is as tight as a letter would be. + XCTAssertEqual(width(#"\quad -x"#) - sign, width(#"\quad x"#) - width("x"), accuracy: 0.01) + XCTAssertEqual(width(#"x = \, -1"#) - width("x = -1"), width(#"a \, b"#) - width("ab"), accuracy: 0.01) + XCTAssertEqual(width(#"\left( \, -x \right)"#) - width(#"\left( -x \right)"#), + width(#"a \, b"#) - width("ab"), accuracy: 0.01) + } + + /// The other half of the rule: with an atom before it, the operator is a + /// subtraction and keeps its space on both sides — also across a space or + /// a style change, and inside a cell. + func testASubtractionKeepsItsSpacing() { + let operatorSpace = width("a - b") - width("a") - width("-b") + XCTAssertGreaterThan(operatorSpace, 1, "a subtraction is wider than its parts set tight") + XCTAssertEqual(width(#"\displaystyle a - b"#), width("a - b"), accuracy: 0.01) + XCTAssertEqual(width(#"a \, - b"#) - width("a - b"), width(#"a \, b"#) - width("ab"), accuracy: 0.01) + XCTAssertEqual(width(#"a \displaystyle - b"#), width("a - b"), accuracy: 0.01) + XCTAssertEqual(width(#"\begin{matrix} a - b \end{matrix}"#), width("a - b"), accuracy: 0.01) + } + + /// Every space command was drawn as a thin space: `\quad` and `\qquad` + /// separated nothing and `\!` pushed apart. Each is the number of mu it + /// names (`\,` 3, `\>` 4, `\;` 5, `\quad` 18, `\qquad` 36, `\!` −3). + func testSpaceCommandsHaveTheirOwnWidths() { + let tight = width("ab") + func gap(_ command: String) -> CGFloat { width("a \(command) b") - tight } + let thin = gap(#"\,"#) + XCTAssertGreaterThan(thin, 0.5) + XCTAssertEqual(gap(#"\>"#), thin * 4 / 3, accuracy: 0.01) + XCTAssertEqual(gap(#"\;"#), thin * 5 / 3, accuracy: 0.01) + XCTAssertEqual(gap(#"\quad"#), thin * 6, accuracy: 0.01) + XCTAssertEqual(gap(#"\qquad"#), thin * 12, accuracy: 0.01) + XCTAssertEqual(gap(#"\!"#), -thin, accuracy: 0.01) + XCTAssertEqual(gap(#"\quad\quad"#), gap(#"\qquad"#), accuracy: 0.01) + // The same inside a script, a fraction and delimiters: wider than a thin space. + XCTAssertGreaterThan(width(#"x^{a \quad b}"#), width(#"x^{a \, b}"#) + thin) + XCTAssertGreaterThan(width(#"\frac{a \quad b}{c}"#), width(#"\frac{a \, b}{c}"#) + thin) + XCTAssertEqual(width(#"\left(a \quad b\right)"#) - width(#"\left(a \, b\right)"#), thin * 5, accuracy: 0.01) + // Spaces draw nothing. + XCTAssertEqual(drawn(#"a \quad b \qquad c \! d"#), "abcd") + } + + // MARK: - Malformed input must not crash + + /// A dropped exponent right before a row break (`b^\\`) takes the break as + /// its argument; the table parser then indexed a row it never made and + /// trapped, taking the whole app down with the document. Whatever such + /// input parses to, parsing and typesetting it return. + func testARowBreakTakenAsAnArgumentDoesNotCrash() { + let inputs = [ + #"\begin{aligned} a &= b^\\ \\ c &= d \end{aligned}"#, + #"\begin{matrix} a_\\ \\ c \end{matrix}"#, + #"\begin{cases} \overline\\ \\ c \end{cases}"#, + #"\begin{pmatrix} a^\\ \\ b^\\ \\ c \end{pmatrix}"#, + #"\begin{matrix} a^\cr b \end{matrix}"# + ] + for latex in inputs { + var error: NSError? + guard let list = MTMathListBuilder.build(fromString: latex, error: &error) else { continue } + _ = MTTypesetter.createLineForMathList(list, font: font, style: .display) + _ = MTTypesetter.createLineForMathList(list, font: font, style: .text) + } + // The well-formed neighbour still has its two rows. + XCTAssertEqual(drawn(#"\begin{aligned} a &= b^2 \\ c &= d \end{aligned}"#), "a=b2c=d") + } + // MARK: - The invariant private static let invariantCases = [ From 6e3e0396a302ad33f16b9d8616d78f97ec287cf5 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Sun, 15 Nov 2026 12:54:13 +0100 Subject: [PATCH 3/3] release: v1.15.1 (33) Co-Authored-By: Claude Fable 5.2 --- QuickMD/CHANGELOG.md | 4 +++- QuickMD/QuickMD.xcodeproj/project.pbxproj | 8 ++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/QuickMD/CHANGELOG.md b/QuickMD/CHANGELOG.md index f513ec1..b488e81 100644 --- a/QuickMD/CHANGELOG.md +++ b/QuickMD/CHANGELOG.md @@ -5,7 +5,9 @@ All notable changes to QuickMD will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [1.15.1] - 2026-11-15 + +Formulas: no more repeated characters inside brackets, a crash on a malformed formula, signs and spaces as LaTeX sets them. ### Fixed - **A crash on a malformed formula:** a row break right after `^` or `_` inside `aligned`, `matrix` or `cases` (for example `b^\\`) closed QuickMD. diff --git a/QuickMD/QuickMD.xcodeproj/project.pbxproj b/QuickMD/QuickMD.xcodeproj/project.pbxproj index f75dae3..1803afd 100644 --- a/QuickMD/QuickMD.xcodeproj/project.pbxproj +++ b/QuickMD/QuickMD.xcodeproj/project.pbxproj @@ -1081,7 +1081,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 32; + CURRENT_PROJECT_VERSION = 33; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = VJ92852M32; ENABLE_APP_SANDBOX = YES; @@ -1106,7 +1106,7 @@ "$(inherited)", "@executable_path/../Frameworks", ); - MARKETING_VERSION = 1.15.0; + MARKETING_VERSION = 1.15.1; PRODUCT_BUNDLE_IDENTIFIER = pl.falami.studio.QuickMD; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; @@ -1125,7 +1125,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 32; + CURRENT_PROJECT_VERSION = 33; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = VJ92852M32; ENABLE_APP_SANDBOX = YES; @@ -1150,7 +1150,7 @@ "$(inherited)", "@executable_path/../Frameworks", ); - MARKETING_VERSION = 1.15.0; + MARKETING_VERSION = 1.15.1; PRODUCT_BUNDLE_IDENTIFIER = pl.falami.studio.QuickMD; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = "";