Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Clearly/PreviewView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,14 @@ struct PreviewView: NSViewRepresentable {
object: nil
)

loadHTML(in: webView, context: context)
// Only render up front when the window opens in Preview. When it opens
// in Edit, lastContentKey stays nil and updateNSView renders on the first
// switch to Preview. Rendering a hidden preview here made documents that
// are slow to render block window creation even in Edit mode.
webView.isHidden = mode != .preview
if mode == .preview {
loadHTML(in: webView, context: context)
}
return webView
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,29 +198,52 @@ public enum MarkdownRenderer {
return (html, [])
}

var protectedHTML = html
// Build the output in one forward pass. Mutating the string in place
// (replaceSubrange per match) copies the whole document for every
// match, which hangs on large files with many code/math regions.
let nsHTML = html as NSString
let matches = codeRegex.matches(in: html, range: NSRange(location: 0, length: nsHTML.length))
guard !matches.isEmpty else { return (html, []) }

var protectedHTML = ""
var segments: [String] = []
let matches = codeRegex.matches(in: html, range: NSRange(html.startIndex..., in: html)).reversed()
segments.reserveCapacity(matches.count)
var cursor = 0

for match in matches {
guard let range = Range(match.range, in: protectedHTML) else { continue }
let segment = String(protectedHTML[range])
let token = "__CLEARLY_PROTECTED_CODE_\(segments.count)__"
segments.append(segment)
protectedHTML.replaceSubrange(range, with: token)
protectedHTML += nsHTML.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
protectedHTML += "__CLEARLY_PROTECTED_CODE_\(segments.count)__"
segments.append(nsHTML.substring(with: match.range))
cursor = NSMaxRange(match.range)
}
protectedHTML += nsHTML.substring(from: cursor)

return (protectedHTML, segments)
}

private static let protectedSegmentTokenRegex = try? NSRegularExpression(
pattern: #"__CLEARLY_PROTECTED_CODE_(\d+)__"#
)

private static func restoreProtectedSegments(in html: String, segments: [String]) -> String {
var restored = html
for (index, segment) in segments.enumerated() {
restored = restored.replacingOccurrences(
of: "__CLEARLY_PROTECTED_CODE_\(index)__",
with: segment
)
// Single pass over the document. Calling replacingOccurrences once per
// segment rescans the entire document for each one (O(segments × length)).
guard !segments.isEmpty, let tokenRegex = protectedSegmentTokenRegex else { return html }

let nsHTML = html as NSString
var restored = ""
var cursor = 0

for match in tokenRegex.matches(in: html, range: NSRange(location: 0, length: nsHTML.length)) {
guard let index = Int(nsHTML.substring(with: match.range(at: 1))),
segments.indices.contains(index) else { continue }
restored += nsHTML.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
restored += segments[index]
cursor = NSMaxRange(match.range)
}

guard cursor > 0 else { return html }
restored += nsHTML.substring(from: cursor)
return restored
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import XCTest
@testable import ClearlyCore

/// Code and math regions are swapped out for placeholder tokens while the
/// inline post-processors run, then restored. These tests cover documents with
/// many such regions, which used to make rendering scale with
/// (regions × document length) and hang the preview on large files.
final class MarkdownProtectedRegionTests: XCTestCase {
func testManyCodeSpansRoundTripUnchanged() {
let count = 2_000
let markdown = (0..<count)
.map { "Line \($0) has `code_\($0)` and ==mark \($0)== in it." }
.joined(separator: "\n\n")

let html = MarkdownRenderer.renderHTML(markdown)

XCTAssertFalse(html.contains("__CLEARLY_PROTECTED_CODE_"), "placeholder token leaked into output")
for i in [0, 1, 9, 10, 11, 99, 100, 101, 999, 1_000, count - 1] {
XCTAssertTrue(html.contains("<code>code_\(i)</code>"), "missing code span \(i)")
XCTAssertTrue(html.contains("<mark>mark \(i)</mark>"), "missing highlight \(i)")
}
}

func testHighlightSyntaxInsideCodeIsNotTransformed() {
let html = MarkdownRenderer.renderHTML("Outside ==yes== and inside `==no==` code.")
XCTAssertTrue(html.contains("<mark>yes</mark>"), html)
XCTAssertTrue(html.contains("<code>==no==</code>"), html)
}

func testLargeDocumentWithManyRegionsRendersQuickly() {
// ~5 MB of prose with ~1,000 code spans. Before the single-pass
// restore this took far longer than the generous bound below.
let paragraph = String(repeating: "نص عربي طويل للاختبار ", count: 220)
let markdown = (0..<1_000)
.map { "\(paragraph) `c\($0)`" }
.joined(separator: "\n\n")

let start = Date()
let html = MarkdownRenderer.renderHTML(markdown)
let elapsed = Date().timeIntervalSince(start)

XCTAssertTrue(html.contains("<code>c999</code>"))
XCTAssertLessThan(elapsed, 20, "rendering took \(elapsed)s")
}
}