Sources/OrgPresentation/MarkdownDisplay.swift
179 lines · 8869 bytes
11 symbols in this file
1import Foundation
2import OrgCore
3
4/// A Markdown file's text and structure at one revision, with what the editors build from
5/// them: the outline, and the tree the fold commands work on.
6public final class MarkdownDocument: @unchecked Sendable {
7 public let units: [UInt16]
8 public let structure: Markdown.Structure
9
10 public init(_ text: String) {
11 units = Array(text.utf16)
12 structure = Markdown.structure(units)
13 }
14
15 init(units: [UInt16], structure: Markdown.Structure) {
16 self.units = units
17 self.structure = structure
18 }
19
20 /// The document after `edit`, read again only where the edit needs it.
21 public func applying(_ edit: TextEdit) -> MarkdownDocument {
22 var new = units
23 new.replaceSubrange(edit.range, with: Array(edit.replacement.utf16))
24 return MarkdownDocument(units: new, structure: Markdown.structure(structure, old: units, new: new, after: edit) ?? Markdown.structure(new))
25 }
26
27 public private(set) lazy var outline: [OutlineEntry] = Presentation.markdownOutline(structure, length: units.count)
28
29 /// An org tree whose headings are the Markdown headings, at the same offsets: the text with
30 /// each heading's `#`s as stars and everything else but newlines as spaces. The org fold
31 /// code (cycling, hidden ranges, Doom's fold keys) works on it unchanged.
32 public private(set) lazy var foldTree: OrgTree = {
33 var skeleton = units.map { $0 == 10 ? UInt16(10) : UInt16(32) }
34 for heading in structure.headings {
35 for k in 0..<heading.level { skeleton[heading.start + k] = 42 }
36 }
37 return OrgParser.parse(String(decoding: skeleton, as: UTF16.self))
38 }()
39}
40
41extension Presentation {
42 /// Every Markdown heading in document order: a section runs to the next heading of its
43 /// level or higher.
44 public static func markdownOutline(_ structure: Markdown.Structure, length: Int) -> [OutlineEntry] {
45 let headings = structure.headings
46 var entries: [OutlineEntry] = []
47 var open: [Int] = []
48 for (index, heading) in headings.enumerated() {
49 while let last = open.last, headings[last].level >= heading.level { open.removeLast() }
50 let end = headings[(index + 1)...].first { $0.level <= heading.level }?.start ?? length
51 entries.append(OutlineEntry(start: heading.start, level: heading.level, title: heading.title, end: end, parent: open.last, isTopLevel: open.isEmpty))
52 open.append(index)
53 }
54 return entries
55 }
56
57 /// What folding the Markdown headings at `folds` (whole sections) and `bodyFolds` (their
58 /// text before the first subheading) hides, as `hiddenRanges` does for org headings.
59 public static func markdownHiddenRanges(_ document: MarkdownDocument, folds: Set<Int>, bodyFolds: Set<Int>) -> [Range<Int>] {
60 guard !folds.isEmpty || !bodyFolds.isEmpty else { return [] }
61 let outline = document.outline
62 let headings = document.structure.headings
63 var ranges: [Range<Int>] = []
64 var hiddenUntil = 0
65 for (index, entry) in outline.enumerated() where entry.start >= hiddenUntil {
66 let lineEnd = headings[index].lineEnd
67 if folds.contains(entry.start) {
68 if lineEnd < entry.end { ranges.append(lineEnd..<entry.end) }
69 hiddenUntil = entry.end
70 } else if bodyFolds.contains(entry.start) {
71 let bodyEnd = index + 1 < outline.count && outline[index + 1].parent == index ? outline[index + 1].start : entry.end
72 if lineEnd < bodyEnd { ranges.append(lineEnd..<bodyEnd) }
73 }
74 }
75 return ranges
76 }
77
78 /// The display a file that isn't org opens with: nothing folded, indented or shown inline.
79 public static func textStartupDisplay(options: EditingOptions) -> StartupDisplay {
80 StartupDisplay(folds: FoldState(), wrappers: [], indented: false, hideStars: false, inlineImages: false, alignTables: false, truncated: options.startupTruncated)
81 }
82
83 /// Style runs for the Markdown lines overlapping `range`: front matter and fences as
84 /// blocks, highlighted as YAML, TOML or the fence's language; other lines by their
85 /// markup. Outer runs come before the runs inside them.
86 public static func markdownStyles(_ document: MarkdownDocument, in range: Range<Int>, highlighter: (any CodeHighlighter)? = nil) -> [StyleRun] {
87 let u = document.units
88 let structure = document.structure
89 guard !range.isEmpty, range.lowerBound < u.count else { return [] }
90 var runs: [StyleRun] = []
91 func code(_ language: String?, _ body: Range<Int>) {
92 guard let highlighter, let language, !body.isEmpty else { return }
93 let text = String(decoding: u[body], as: UTF16.self)
94 for run in highlighter.highlights(language: language, code: text) {
95 runs.append(StyleRun(range: (run.range.lowerBound + body.lowerBound)..<(run.range.upperBound + body.lowerBound), role: .syntax(run.category)))
96 }
97 }
98 if let front = structure.frontMatter, front.range.overlaps(range) {
99 runs.append(StyleRun(range: front.opening, role: .blockDelimiter))
100 if !front.body.isEmpty { runs.append(StyleRun(range: front.body, role: .metadata)) }
101 code(front.format.rawValue, front.body)
102 runs.append(StyleRun(range: front.closing, role: .blockDelimiter))
103 }
104 let fences = structure.fences
105 var first = firstIndex(fences) { $0.range.upperBound > range.lowerBound }
106 while first < fences.count, fences[first].range.lowerBound < range.upperBound {
107 let fence = fences[first]
108 runs.append(StyleRun(range: fence.opening, role: .blockDelimiter))
109 if !fence.body.isEmpty { runs.append(StyleRun(range: fence.body, role: .block)) }
110 code(fence.language, fence.body)
111 if let closing = fence.closing { runs.append(StyleRun(range: closing, role: .blockDelimiter)) }
112 first += 1
113 }
114 let blocks = structure.blocks
115 var block = firstIndex(blocks) { $0.upperBound > range.lowerBound }
116 var i = range.lowerBound
117 while i > 0, u[i - 1] != 10 { i -= 1 }
118 let upper = min(range.upperBound, u.count)
119 while i < upper {
120 if block < blocks.count, blocks[block].lowerBound <= i {
121 i = max(i, blocks[block].upperBound)
122 block += 1
123 continue
124 }
125 var end = i
126 while end < u.count, u[end] != 10 { end += 1 }
127 for span in Markdown.lineSpans(u, i, end) { runs.append(StyleRun(range: span.range, role: role(span.kind))) }
128 i = end + 1
129 }
130 return runs
131 }
132
133 /// The first index whose element satisfies `test`, which holds from some index to the end.
134 static func firstIndex<T>(_ items: [T], where test: (T) -> Bool) -> Int {
135 var low = 0
136 var high = items.count
137 while low < high {
138 let mid = (low + high) / 2
139 if test(items[mid]) { high = mid } else { low = mid + 1 }
140 }
141 return low
142 }
143
144 static func role(_ kind: Markdown.Span.Kind) -> StyleRole {
145 switch kind {
146 case .heading(let level): .heading(level: level)
147 case .code: .code
148 case .bold: .bold
149 case .italic, .quote: .italic
150 case .strikeThrough: .strikeThrough
151 case .marker: .markup
152 case .link: .link
153 case .linkMarkup: .linkMarkup
154 case .comment: .comment
155 case .rule: .rule
156 case .table: .table
157 case .checkbox: .cookie
158 }
159 }
160
161 /// The lines an edit to a Markdown file restyles: the edited lines, and every front matter
162 /// or fence that the edit made, unmade or moved the end of.
163 public static func markdownRestyleRange(for edit: TextEdit, oldBlocks: [Range<Int>], new document: MarkdownDocument, newText: NSString) -> Range<Int> {
164 let newEnd = edit.range.lowerBound + edit.replacement.utf16.count
165 let lines = newText.lineRange(for: NSRange(location: edit.range.lowerBound, length: newEnd - edit.range.lowerBound))
166 var lower = lines.location
167 var upper = NSMaxRange(lines)
168 let delta = newEnd - edit.range.upperBound
169 func map(_ offset: Int) -> Int {
170 offset < edit.range.lowerBound ? offset : offset >= edit.range.upperBound ? offset + delta : newEnd
171 }
172 let mapped = Set(oldBlocks.map { map($0.lowerBound)..<map($0.upperBound) })
173 for changed in mapped.symmetricDifference(document.structure.blocks) {
174 lower = min(lower, changed.lowerBound)
175 upper = max(upper, changed.upperBound)
176 }
177 return lower..<min(upper, newText.length)
178 }
179}