Sources/OrgCore/Parser/Inline.swift

53903567a65c44ccdf4ba4ff6ffa6d04721efea1
orgstar/Sources/OrgCore/Parser/Inline.swift

376 lines · 14402 bytes

  1/// Characters allowed before an emphasis opener, besides whitespace and the start of the run.
  2private let emphasisPre: Set<Character> = ["-", "(", "{", "'", "\""]
  3
  4/// Characters allowed after an emphasis closer, besides whitespace and the end of the run.
  5private let emphasisPost: Set<Character> = ["-", ".", ",", ":", "!", "?", ";", "'", "\"", ")", "}", "\\", "["]
  6
  7private let emphasisKinds: [Character: SyntaxKind] = [
  8    "*": .bold, "/": .italic, "_": .underline, "+": .strikeThrough, "=": .verbatim, "~": .code,
  9]
 10
 11private let angleLinkSchemes: Set<String> = [
 12    "http", "https", "mailto", "file", "id", "doi", "ftp", "news", "shell", "elisp", "info", "help", "attachment",
 13]
 14
 15private let plainLinkPrefixes = ["https://", "http://", "mailto:", "file:"]
 16
 17/// "\r\n" is a single Character, so both forms count.
 18func isNewline(_ c: Character) -> Bool {
 19    c == "\n" || c == "\r\n"
 20}
 21
 22enum InlineMatch {
 23    case emphasis(SyntaxKind, open: Int, close: Int)
 24    case link(path: Range<Int>, description: Range<Int>?, whole: Range<Int>)
 25    case object(SyntaxKind, Range<Int>)
 26
 27    var end: Int {
 28        switch self {
 29        case .emphasis(_, _, let close): close + 1
 30        case .link(_, _, let whole): whole.upperBound
 31        case .object(_, let range): range.upperBound
 32        }
 33    }
 34}
 35
 36/// Turns a run of text into text, newline and object tokens. Every character ends up in
 37/// exactly one token.
 38struct InlineScanner {
 39    let chars: [Character]
 40
 41    func scan(_ range: Range<Int>, into b: inout GreenBuilder, inLink: Bool = false) {
 42        var textStart = range.lowerBound
 43        var i = range.lowerBound
 44        while i < range.upperBound {
 45            if let match = match(at: i, in: range, inLink: inLink) {
 46                emitText(textStart..<i, into: &b)
 47                emit(match, into: &b, inLink: inLink)
 48                i = match.end
 49                textStart = i
 50            } else {
 51                i += 1
 52            }
 53        }
 54        emitText(textStart..<range.upperBound, into: &b)
 55    }
 56
 57    func emitText(_ range: Range<Int>, into b: inout GreenBuilder) {
 58        var start = range.lowerBound
 59        for k in range where isNewline(chars[k]) {
 60            if start < k { b.token(.text, string(start..<k)) }
 61            b.token(.newline, String(chars[k]))
 62            start = k + 1
 63        }
 64        if start < range.upperBound { b.token(.text, string(start..<range.upperBound)) }
 65    }
 66
 67    func emit(_ match: InlineMatch, into b: inout GreenBuilder, inLink: Bool) {
 68        switch match {
 69        case .emphasis(let kind, let open, let close):
 70            b.start(kind)
 71            b.token(.marker, string(open..<(open + 1)))
 72            if kind == .verbatim || kind == .code {
 73                emitText((open + 1)..<close, into: &b)
 74            } else {
 75                scan((open + 1)..<close, into: &b, inLink: inLink)
 76            }
 77            b.token(.marker, string(close..<(close + 1)))
 78            b.finish()
 79        case .link(let path, let description, let whole):
 80            b.start(.link)
 81            b.token(.marker, string(whole.lowerBound..<path.lowerBound))
 82            b.token(.linkPath, string(path))
 83            if let description {
 84                b.token(.marker, string(path.upperBound..<description.lowerBound))
 85                b.start(.linkDescription)
 86                scan(description, into: &b, inLink: true)
 87                b.finish()
 88                b.token(.marker, string(description.upperBound..<whole.upperBound))
 89            } else {
 90                b.token(.marker, string(path.upperBound..<whole.upperBound))
 91            }
 92            b.finish()
 93        case .object(let kind, let range):
 94            b.start(kind)
 95            emitText(range, into: &b)
 96            b.finish()
 97        }
 98    }
 99
100    func string(_ range: Range<Int>) -> String {
101        String(chars[range])
102    }
103
104    func hasPrefix(_ s: String, at i: Int, _ limit: Int) -> Bool {
105        var j = i
106        for c in s {
107            guard j < limit, chars[j] == c else { return false }
108            j += 1
109        }
110        return true
111    }
112
113    // MARK: - Recognizers
114
115    func match(at i: Int, in range: Range<Int>, inLink: Bool) -> InlineMatch? {
116        let limit = range.upperBound
117        let previous: Character? = i > range.lowerBound ? chars[i - 1] : nil
118        let afterWord = previous.map { $0.isLetter || $0.isNumber } ?? false
119
120        switch chars[i] {
121        case "[":
122            if !inLink, let link = bracketLink(i, limit) { return link }
123            if let end = footnoteReference(i, limit) { return .object(.footnoteReference, i..<end) }
124            if let end = scanTimestamp(chars, at: i, limit: limit)?.end { return .object(.timestamp, i..<end) }
125            if let end = statisticsCookie(i, limit) { return .object(.statisticsCookie, i..<end) }
126        case "<":
127            if let end = scanTimestamp(chars, at: i, limit: limit)?.end { return .object(.timestamp, i..<end) }
128            if let end = target(i, limit) { return .object(.target, i..<end) }
129            if !inLink, let end = angleLink(i, limit) { return .object(.link, i..<end) }
130        case "{":
131            if let end = macro(i, limit) { return .object(.macro, i..<end) }
132        case "\\":
133            if let end = lineBreak(i, limit) { return .object(.lineBreak, i..<end) }
134            if let end = latexFragment(i, limit) { return .object(.latexFragment, i..<end) }
135        case "^":
136            if afterWord, let end = superscript(i, limit) { return .object(.superscript, i..<end) }
137        case "s":
138            if !afterWord, let end = inlineSourceBlock(i, limit) { return .object(.inlineSourceBlock, i..<end) }
139        default:
140            break
141        }
142
143        if !inLink, !afterWord, let end = plainLink(i, limit) { return .object(.link, i..<end) }
144
145        if let kind = emphasisKinds[chars[i]],
146           previous.map({ $0.isWhitespace || emphasisPre.contains($0) }) ?? true,
147           let close = emphasisClose(i, limit) {
148            return .emphasis(kind, open: i, close: close)
149        }
150        return nil
151    }
152
153    /// org's emphasis rules: the body neither starts nor ends with whitespace, spans at most
154    /// one line break, and the closer is followed by whitespace, punctuation or the end.
155    func emphasisClose(_ i: Int, _ limit: Int) -> Int? {
156        let marker = chars[i]
157        guard i + 1 < limit, !chars[i + 1].isWhitespace else { return nil }
158        var newlines = 0
159        var j = i + 1
160        while j < limit {
161            if isNewline(chars[j]) {
162                newlines += 1
163                if newlines > 1 { return nil }
164            } else if chars[j] == marker, j > i + 1, !chars[j - 1].isWhitespace {
165                if j + 1 == limit || chars[j + 1].isWhitespace || emphasisPost.contains(chars[j + 1]) { return j }
166            }
167            j += 1
168        }
169        return nil
170    }
171
172    /// `[[path]]` or `[[path][description]]`.
173    func bracketLink(_ i: Int, _ limit: Int) -> InlineMatch? {
174        guard i + 1 < limit, chars[i + 1] == "[" else { return nil }
175        var j = i + 2
176        while j < limit, chars[j] != "]" {
177            if chars[j] == "[" || isNewline(chars[j]) { return nil }
178            if chars[j] == "\\", j + 1 < limit { j += 1 }
179            j += 1
180        }
181        guard j > i + 2, j + 1 < limit else { return nil }
182        let path = (i + 2)..<j
183        if chars[j + 1] == "]" { return .link(path: path, description: nil, whole: i..<(j + 2)) }
184        guard chars[j + 1] == "[" else { return nil }
185        let descriptionStart = j + 2
186        var depth = 0
187        var k = descriptionStart
188        while k < limit {
189            if chars[k] == "[" {
190                depth += 1
191            } else if chars[k] == "]" {
192                if depth == 0 { break }
193                depth -= 1
194            }
195            k += 1
196        }
197        guard k > descriptionStart, k + 1 < limit, chars[k + 1] == "]" else { return nil }
198        return .link(path: path, description: descriptionStart..<k, whole: i..<(k + 2))
199    }
200
201    /// `[fn:label]`, `[fn:label:definition]` or `[fn::definition]`.
202    func footnoteReference(_ i: Int, _ limit: Int) -> Int? {
203        guard hasPrefix("[fn:", at: i, limit) else { return nil }
204        var j = i + 4
205        while j < limit, chars[j].isLetter || chars[j].isNumber || chars[j] == "_" || chars[j] == "-" { j += 1 }
206        guard j < limit else { return nil }
207        if chars[j] == "]" { return j > i + 4 ? j + 1 : nil }
208        guard chars[j] == ":" else { return nil }
209        var depth = 0
210        j += 1
211        while j < limit {
212            if chars[j] == "[" {
213                depth += 1
214            } else if chars[j] == "]" {
215                if depth == 0 { return j + 1 }
216                depth -= 1
217            }
218            j += 1
219        }
220        return nil
221    }
222
223    /// `[1/3]`, `[/]`, `[50%]` or `[%]`.
224    func statisticsCookie(_ i: Int, _ limit: Int) -> Int? {
225        var j = i + 1
226        while j < limit, chars[j].isASCII, chars[j].isNumber { j += 1 }
227        guard j < limit else { return nil }
228        if chars[j] == "%" {
229            j += 1
230        } else if chars[j] == "/" {
231            j += 1
232            while j < limit, chars[j].isASCII, chars[j].isNumber { j += 1 }
233        } else {
234            return nil
235        }
236        guard j < limit, chars[j] == "]" else { return nil }
237        return j + 1
238    }
239
240    /// `<<target>>`.
241    func target(_ i: Int, _ limit: Int) -> Int? {
242        guard hasPrefix("<<", at: i, limit), i + 2 < limit, chars[i + 2] != "<" else { return nil }
243        let start = i + 2
244        var j = start
245        while j < limit, chars[j] != ">" {
246            if chars[j] == "<" || isNewline(chars[j]) { return nil }
247            j += 1
248        }
249        guard j > start, j + 1 < limit, chars[j + 1] == ">",
250              !chars[start].isWhitespace, !chars[j - 1].isWhitespace else { return nil }
251        return j + 2
252    }
253
254    /// `<scheme:path>` for a known scheme.
255    func angleLink(_ i: Int, _ limit: Int) -> Int? {
256        var j = i + 1
257        while j < limit, chars[j].isLetter { j += 1 }
258        guard j < limit, chars[j] == ":", angleLinkSchemes.contains(string((i + 1)..<j).lowercased()) else { return nil }
259        j += 1
260        let bodyStart = j
261        while j < limit, chars[j] != ">" {
262            if chars[j] == "<" || isNewline(chars[j]) { return nil }
263            j += 1
264        }
265        guard j < limit, j > bodyStart else { return nil }
266        return j + 1
267    }
268
269    /// A bare URL. Trailing sentence punctuation stays outside the link.
270    func plainLink(_ i: Int, _ limit: Int) -> Int? {
271        guard "hmf".contains(chars[i]),
272              let prefix = plainLinkPrefixes.first(where: { hasPrefix($0, at: i, limit) }) else { return nil }
273        let bodyStart = i + prefix.count
274        var j = bodyStart
275        while j < limit, !chars[j].isWhitespace, !"()<>[]\"".contains(chars[j]) { j += 1 }
276        while j > bodyStart, ".,;:!?'".contains(chars[j - 1]) { j -= 1 }
277        return j > bodyStart ? j : nil
278    }
279
280    /// `{{{name}}}` or `{{{name(arguments)}}}`.
281    func macro(_ i: Int, _ limit: Int) -> Int? {
282        guard hasPrefix("{{{", at: i, limit) else { return nil }
283        var j = i + 3
284        guard j < limit, chars[j].isLetter else { return nil }
285        while j < limit, chars[j].isLetter || chars[j].isNumber || chars[j] == "-" || chars[j] == "_" { j += 1 }
286        if j < limit, chars[j] == "(" {
287            var k = j + 1
288            while k < limit, !hasPrefix(")}}}", at: k, limit) {
289                if isNewline(chars[k]) { return nil }
290                k += 1
291            }
292            return k < limit ? k + 4 : nil
293        }
294        return hasPrefix("}}}", at: j, limit) ? j + 3 : nil
295    }
296
297    /// `\\` at the end of a line, before optional trailing blanks. The newline stays outside.
298    func lineBreak(_ i: Int, _ limit: Int) -> Int? {
299        guard hasPrefix("\\\\", at: i, limit) else { return nil }
300        var j = i + 2
301        while j < limit, chars[j] == " " || chars[j] == "\t" { j += 1 }
302        guard j == limit || isNewline(chars[j]) else { return nil }
303        return j
304    }
305
306    /// `\(...\)` or `\[...\]`.
307    func latexFragment(_ i: Int, _ limit: Int) -> Int? {
308        guard i + 1 < limit else { return nil }
309        let closer: String
310        switch chars[i + 1] {
311        case "(": closer = "\\)"
312        case "[": closer = "\\]"
313        default: return nil
314        }
315        var j = i + 2
316        while j < limit {
317            if hasPrefix(closer, at: j, limit) { return j + 2 }
318            j += 1
319        }
320        return nil
321    }
322
323    /// `^word` or `^{group}` after a letter or digit.
324    func superscript(_ i: Int, _ limit: Int) -> Int? {
325        var j = i + 1
326        guard j < limit else { return nil }
327        if chars[j] == "{" {
328            j += 1
329            while j < limit, chars[j] != "}" {
330                if isNewline(chars[j]) { return nil }
331                j += 1
332            }
333            return j < limit ? j + 1 : nil
334        }
335        let start = j
336        while j < limit, chars[j].isLetter || chars[j].isNumber { j += 1 }
337        return j > start ? j : nil
338    }
339
340    /// `src_lang{body}` or `src_lang[headers]{body}`, on one line, with balanced braces.
341    func inlineSourceBlock(_ i: Int, _ limit: Int) -> Int? {
342        guard hasPrefix("src_", at: i, limit) else { return nil }
343        var j = i + 4
344        let languageStart = j
345        while j < limit, !chars[j].isWhitespace, chars[j] != "[", chars[j] != "{" { j += 1 }
346        guard j > languageStart, j < limit else { return nil }
347        if chars[j] == "[" {
348            while j < limit, chars[j] != "]" {
349                if isNewline(chars[j]) { return nil }
350                j += 1
351            }
352            guard j < limit else { return nil }
353            j += 1
354        }
355        guard j < limit, chars[j] == "{" else { return nil }
356        var depth = 0
357        while j < limit {
358            if isNewline(chars[j]) { return nil }
359            if chars[j] == "{" {
360                depth += 1
361            } else if chars[j] == "}" {
362                depth -= 1
363                if depth == 0 { return j + 1 }
364            }
365            j += 1
366        }
367        return nil
368    }
369}
370
371extension Parser {
372    mutating func inline(_ text: Substring) {
373        let chars = Array(text)
374        InlineScanner(chars: chars).scan(0..<chars.count, into: &builder)
375    }
376}
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