Sources/OrgCore/Markdown/MarkdownSpans.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgCore/Markdown/MarkdownSpans.swift

394 lines · 16014 bytes

19 symbols in this file
  1import Foundation
  2
  3extension Markdown {
  4    /// What a range of a Markdown line is, for highlighting.
  5    public struct Span: Sendable, Equatable {
  6        public enum Kind: Sendable, Equatable {
  7            case heading(level: Int)
  8            case code, bold, italic, strikeThrough
  9            /// Emphasis and code delimiters, list bullets and block quote markers.
 10            case marker
 11            case link
 12            /// A link's brackets and destination.
 13            case linkMarkup
 14            case comment, rule, table, quote, checkbox
 15        }
 16
 17        public let kind: Kind
 18        public let range: Range<Int>
 19
 20        public init(_ kind: Kind, _ range: Range<Int>) {
 21            self.kind = kind
 22            self.range = range
 23        }
 24    }
 25
 26    static let backslash: UInt16 = 92
 27    static let lessThan: UInt16 = 60
 28    static let greaterThan: UInt16 = 62
 29    static let openBracket: UInt16 = 91
 30    static let closeBracket: UInt16 = 93
 31    static let openParen: UInt16 = 40
 32    static let closeParen: UInt16 = 41
 33    static let bang: UInt16 = 33
 34    static let star: UInt16 = 42
 35    static let underscore: UInt16 = 95
 36    static let dash: UInt16 = 45
 37    static let plus: UInt16 = 43
 38    static let pipe: UInt16 = 124
 39    static let colon: UInt16 = 58
 40
 41    /// Spans of the Markdown line from `start` to `end` (its newline excluded), which is
 42    /// outside front matter and fences. Outer spans come before the spans inside them.
 43    public static func lineSpans(_ u: [UInt16], _ start: Int, _ end: Int) -> [Span] {
 44        var spans: [Span] = []
 45        lineSpans(u, start, end, into: &spans)
 46        return spans.sorted { $0.range.lowerBound != $1.range.lowerBound ? $0.range.lowerBound < $1.range.lowerBound : $0.range.upperBound > $1.range.upperBound }
 47    }
 48
 49    static func lineSpans(_ u: [UInt16], _ start: Int, _ end: Int, into spans: inout [Span]) {
 50        if let heading = atxHeading(u, start, end) {
 51            spans.append(Span(.heading(level: heading.level), start..<end))
 52            inline(u, heading.title, line: start..<end, into: &spans)
 53            return
 54        }
 55        if isThematicBreak(u, start, end) {
 56            spans.append(Span(.rule, start..<end))
 57            return
 58        }
 59        var i = start
 60        // Block quote markers, nested or not.
 61        var quoted = false
 62        while true {
 63            var j = i
 64            var indent = 0
 65            while j < end, u[j] == space, indent < 3 { j += 1; indent += 1 }
 66            guard j < end, u[j] == greaterThan else { break }
 67            spans.append(Span(.marker, j..<(j + 1)))
 68            i = j + 1
 69            if i < end, u[i] == space || u[i] == tab { i += 1 }
 70            quoted = true
 71        }
 72        if quoted, i < end { spans.append(Span(.quote, i..<end)) }
 73        // A list item's bullet or number, and a task's box.
 74        var j = i
 75        while j < end, u[j] == space || u[j] == tab { j += 1 }
 76        if let marker = listMarker(u, j, end) {
 77            spans.append(Span(.marker, j..<marker))
 78            var k = marker
 79            while k < end, u[k] == space || u[k] == tab { k += 1 }
 80            if k + 2 < end, u[k] == openBracket, u[k + 2] == closeBracket, [space, 120, 88].contains(u[k + 1]), k + 3 == end || isBlank(u[k + 3]) {
 81                spans.append(Span(.checkbox, k..<(k + 3)))
 82                k += 3
 83            }
 84            i = k
 85        } else if j < end, u[j] == pipe {
 86            spans.append(Span(.table, j..<trimmedEnd(u, j, end)))
 87        } else if let definition = linkDefinition(u, j, end) {
 88            spans.append(Span(.linkMarkup, j..<definition.lowerBound))
 89            spans.append(Span(.link, definition))
 90            return
 91        }
 92        inline(u, i..<end, line: start..<end, into: &spans)
 93    }
 94
 95    /// Three or more `-`, `*` or `_`, the same one, with only spaces between.
 96    static func isThematicBreak(_ u: [UInt16], _ start: Int, _ end: Int) -> Bool {
 97        var i = start
 98        var indent = 0
 99        while i < end, u[i] == space, indent < 3 { i += 1; indent += 1 }
100        guard i < end, [dash, star, underscore].contains(u[i]) else { return false }
101        let char = u[i]
102        var count = 0
103        while i < end {
104            if u[i] == char { count += 1 } else if !isBlank(u[i]) { return false }
105            i += 1
106        }
107        return count >= 3
108    }
109
110    /// The end of a list marker at `i`: `-`, `*` or `+`, or up to nine digits and `.` or `)`,
111    /// followed by a space, a tab or the end of the line.
112    static func listMarker(_ u: [UInt16], _ i: Int, _ end: Int) -> Int? {
113        guard i < end else { return nil }
114        var j = i
115        if u[i] == dash || u[i] == star || u[i] == plus {
116            j += 1
117        } else {
118            while j < end, j - i < 9, u[j] >= 48, u[j] <= 57 { j += 1 }
119            guard j > i, j < end, u[j] == 46 || u[j] == closeParen else { return nil }
120            j += 1
121        }
122        return j == end || u[j] == space || u[j] == tab ? j : nil
123    }
124
125    /// `[label]: destination`: the destination's range.
126    static func linkDefinition(_ u: [UInt16], _ i: Int, _ end: Int) -> Range<Int>? {
127        guard i < end, u[i] == openBracket else { return nil }
128        var j = i + 1
129        while j < end, u[j] != closeBracket { j += 1 }
130        guard j > i + 1, j + 1 < end, u[j + 1] == colon else { return nil }
131        var k = j + 2
132        while k < end, isBlank(u[k]) { k += 1 }
133        var e = k
134        while e < end, !isBlank(u[e]) { e += 1 }
135        return e > k ? k..<e : nil
136    }
137
138    // MARK: - Inline
139
140    /// Code spans, comments, autolinks and links first, as they hide what's inside them from
141    /// emphasis; then bare URLs and emphasis in the text between.
142    static func inline(_ u: [UInt16], _ range: Range<Int>, line: Range<Int>, into spans: inout [Span]) {
143        let upper = range.upperBound
144        var plain: [Range<Int>] = []
145        var segment = range.lowerBound
146        var i = range.lowerBound
147        func take(_ end: Int) {
148            plain.append(segment..<i)
149            i = end
150            segment = end
151        }
152        while i < upper {
153            let c = u[i]
154            if c == backslash {
155                i += 2
156                continue
157            }
158            if c == backtick {
159                var runEnd = i
160                while runEnd < upper, u[runEnd] == backtick { runEnd += 1 }
161                if let close = backtickRun(u, from: runEnd, to: upper, count: runEnd - i) {
162                    let end = close + runEnd - i
163                    spans.append(Span(.code, i..<end))
164                    spans.append(Span(.marker, i..<runEnd))
165                    spans.append(Span(.marker, close..<end))
166                    take(end)
167                } else {
168                    i = runEnd
169                }
170                continue
171            }
172            if c == lessThan {
173                if starts(u, i, upper, "<!--"), let close = find(u, from: i + 4, to: upper, "-->") {
174                    spans.append(Span(.comment, i..<(close + 3)))
175                    take(close + 3)
176                    continue
177                }
178                if let close = autolink(u, i, upper) {
179                    spans.append(Span(.linkMarkup, i..<(i + 1)))
180                    spans.append(Span(.link, (i + 1)..<close))
181                    spans.append(Span(.linkMarkup, close..<(close + 1)))
182                    take(close + 1)
183                    continue
184                }
185            }
186            if c == openBracket || (c == bang && i + 1 < upper && u[i + 1] == openBracket) {
187                let open = c == bang ? i + 1 : i
188                if let link = link(u, open, upper) {
189                    spans.append(Span(.linkMarkup, i..<(open + 1)))
190                    spans.append(Span(.link, (open + 1)..<link.textEnd))
191                    spans.append(Span(.linkMarkup, link.textEnd..<link.end))
192                    plain.append(segment..<i)
193                    inline(u, (open + 1)..<link.textEnd, line: line, into: &spans)
194                    i = link.end
195                    segment = link.end
196                    continue
197                }
198            }
199            i += 1
200        }
201        plain.append(segment..<upper)
202        for part in plain where !part.isEmpty {
203            var from = part.lowerBound
204            for url in bareURLs(u, part) {
205                spans.append(Span(.link, url))
206                emphasis(u, from..<url.lowerBound, line: line, into: &spans)
207                from = url.upperBound
208            }
209            emphasis(u, from..<part.upperBound, line: line, into: &spans)
210        }
211    }
212
213    static func starts(_ u: [UInt16], _ i: Int, _ upper: Int, _ prefix: String) -> Bool {
214        let p = Array(prefix.utf16)
215        return i + p.count <= upper && Array(u[i..<(i + p.count)]) == p
216    }
217
218    static func find(_ u: [UInt16], from: Int, to upper: Int, _ needle: String) -> Int? {
219        var i = from
220        while i < upper {
221            if starts(u, i, upper, needle) { return i }
222            i += 1
223        }
224        return nil
225    }
226
227    /// The start of the next run of exactly `count` backticks.
228    static func backtickRun(_ u: [UInt16], from: Int, to upper: Int, count: Int) -> Int? {
229        var i = from
230        while i < upper {
231            guard u[i] == backtick else {
232                i += 1
233                continue
234            }
235            var e = i
236            while e < upper, u[e] == backtick { e += 1 }
237            if e - i == count { return i }
238            i = e
239        }
240        return nil
241    }
242
243    /// `<scheme:…>` or `<name@host>`: the offset of the closing `>`.
244    static func autolink(_ u: [UInt16], _ i: Int, _ upper: Int) -> Int? {
245        var j = i + 1
246        var sawScheme = false
247        var sawAt = false
248        while j < upper, u[j] != greaterThan {
249            let c = u[j]
250            if c == space || c == tab || c == lessThan { return nil }
251            if c == colon, j > i + 2 { sawScheme = true }
252            if c == 64 { sawAt = true }
253            j += 1
254        }
255        guard j < upper, j > i + 1, sawScheme || sawAt else { return nil }
256        let first = u[i + 1]
257        guard (first >= 65 && first <= 90) || (first >= 97 && first <= 122) || (first >= 48 && first <= 57) else { return nil }
258        return j
259    }
260
261    /// `[text](destination)` or `[text][label]` from the `[` at `open`: the `]` closing the
262    /// text, and the end of the link.
263    static func link(_ u: [UInt16], _ open: Int, _ upper: Int) -> (textEnd: Int, end: Int)? {
264        var depth = 0
265        var j = open
266        while j < upper {
267            let c = u[j]
268            if c == backslash {
269                j += 2
270                continue
271            }
272            if c == openBracket { depth += 1 }
273            if c == closeBracket {
274                depth -= 1
275                if depth == 0 { break }
276            }
277            j += 1
278        }
279        guard j < upper, j + 1 < upper else { return nil }
280        let textEnd = j
281        if u[j + 1] == openParen {
282            var parens = 0
283            var k = j + 1
284            while k < upper {
285                let c = u[k]
286                if c == backslash {
287                    k += 2
288                    continue
289                }
290                if c == openParen { parens += 1 }
291                if c == closeParen {
292                    parens -= 1
293                    if parens == 0 { return (textEnd, k + 1) }
294                }
295                k += 1
296            }
297            return nil
298        }
299        if u[j + 1] == openBracket {
300            var k = j + 2
301            while k < upper, u[k] != closeBracket, u[k] != openBracket { k += 1 }
302            return k < upper && u[k] == closeBracket ? (textEnd, k + 1) : nil
303        }
304        return nil
305    }
306
307    /// `http://` and `https://` URLs, without trailing punctuation.
308    static func bareURLs(_ u: [UInt16], _ range: Range<Int>) -> [Range<Int>] {
309        var urls: [Range<Int>] = []
310        var i = range.lowerBound
311        while i < range.upperBound {
312            guard u[i] == 104, starts(u, i, range.upperBound, "http://") || starts(u, i, range.upperBound, "https://"),
313                  i == range.lowerBound || !isWordCharacter(u[i - 1]) else {
314                i += 1
315                continue
316            }
317            var e = i
318            while e < range.upperBound, !isBlank(u[e]), u[e] != lessThan { e += 1 }
319            while e > i, [46, 44, 58, 59, 33, 63, 39, 34, closeParen, star, underscore].contains(u[e - 1]) { e -= 1 }
320            if e > i + 8 { urls.append(i..<e) }
321            i = max(e, i + 1)
322        }
323        return urls
324    }
325
326    static func isWordCharacter(_ c: UInt16) -> Bool {
327        (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c > 127
328    }
329
330    static func isPunctuation(_ c: UInt16) -> Bool {
331        (c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126)
332    }
333
334    struct Delimiter {
335        var position: Int
336        let char: UInt16
337        var count: Int
338        let canOpen: Bool
339        let canClose: Bool
340    }
341
342    /// `**bold**`, `__bold__`, `*italic*`, `_italic_` and `~~strike~~`, matched as
343    /// CommonMark's delimiter runs are, within `range`. Characters outside `line` count as
344    /// whitespace.
345    static func emphasis(_ u: [UInt16], _ range: Range<Int>, line: Range<Int>, into spans: inout [Span]) {
346        guard !range.isEmpty else { return }
347        var delimiters: [Delimiter] = []
348        var i = range.lowerBound
349        while i < range.upperBound {
350            let c = u[i]
351            if c == backslash {
352                i += 2
353                continue
354            }
355            guard c == star || c == underscore || c == tilde else {
356                i += 1
357                continue
358            }
359            var e = i
360            while e < range.upperBound, u[e] == c { e += 1 }
361            let before: UInt16 = i > line.lowerBound ? u[i - 1] : space
362            let after: UInt16 = e < line.upperBound ? u[e] : space
363            let left = !isBlank(after) && (!isPunctuation(after) || isBlank(before) || isPunctuation(before))
364            let right = !isBlank(before) && (!isPunctuation(before) || isBlank(after) || isPunctuation(after))
365            let canOpen = c == underscore ? left && (!right || isPunctuation(before)) : left
366            let canClose = c == underscore ? right && (!left || isPunctuation(after)) : right
367            if c != tilde || e - i <= 2 {
368                delimiters.append(Delimiter(position: i, char: c, count: e - i, canOpen: canOpen, canClose: canClose))
369            }
370            i = e
371        }
372        guard delimiters.count > 1 else { return }
373        for closer in delimiters.indices where delimiters[closer].canClose {
374            while delimiters[closer].count > 0 {
375                guard let opener = delimiters[..<closer].lastIndex(where: {
376                    $0.count > 0 && $0.canOpen && $0.char == delimiters[closer].char
377                        && ($0.char != tilde || $0.count == delimiters[closer].count)
378                }) else { break }
379                let char = delimiters[closer].char
380                let use = char == tilde ? delimiters[closer].count : (delimiters[opener].count >= 2 && delimiters[closer].count >= 2 ? 2 : 1)
381                let openEnd = delimiters[opener].position + delimiters[opener].count
382                let closeStart = delimiters[closer].position
383                let kind: Span.Kind = char == tilde ? .strikeThrough : use == 2 ? .bold : .italic
384                spans.append(Span(kind, (openEnd - use)..<(closeStart + use)))
385                spans.append(Span(.marker, (openEnd - use)..<openEnd))
386                spans.append(Span(.marker, closeStart..<(closeStart + use)))
387                delimiters[opener].count -= use
388                delimiters[closer].count -= use
389                delimiters[closer].position += use
390                for between in (opener + 1)..<closer { delimiters[between].count = 0 }
391            }
392        }
393    }
394}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form