Sources/OrgPresentation/SpellCheck.swift
43 lines · 2215 bytes
1import Foundation
2import OrgCore
3
4/// Where spell checking stays off: the faces spell-fu skips in Org (code, links, dates, tags,
5/// keywords, meta lines, properties, LaTeX, src and example blocks).
6public enum SpellCheck {
7 public static func skipped(_ tree: OrgTree) -> [Range<Int>] {
8 let ns = tree.text as NSString
9 func line(_ p: Int) -> Range<Int> {
10 let r = ns.lineRange(for: NSRange(location: p, length: 0))
11 return r.location..<(r.location + r.length)
12 }
13 let whole: Set<SyntaxKind> = [.code, .verbatim, .link, .timestamp, .footnoteReference, .statisticsCookie, .target, .radioTarget,
14 .macro, .inlineSourceBlock, .latexFragment, .entity, .latexEnvironment, .keyword, .affiliatedKeyword,
15 .planning, .clock, .propertyDrawer, .fixedWidth, .tableFormula, .horizontalRule]
16 let tokens: Set<SyntaxKind> = [.stars, .todoKeyword, .priority, .tags, .bullet, .checkbox]
17 var ranges: [Range<Int>] = []
18 for node in tree.root.descendants() {
19 if whole.contains(node.kind) {
20 ranges.append(node.range)
21 continue
22 }
23 switch node.kind {
24 case .block, .dynamicBlock, .drawer:
25 let first = line(node.range.lowerBound)
26 let name = ns.substring(with: NSRange(location: first.lowerBound, length: first.count)).trimmingCharacters(in: .whitespaces).lowercased()
27 if node.kind == .block, ["src", "example", "export", "comment"].contains(where: { name.hasPrefix("#+begin_\($0)") }) {
28 ranges.append(node.range)
29 } else {
30 ranges.append(first)
31 var end = node.range.upperBound
32 while end > node.range.lowerBound, ns.character(at: end - 1) == 10 { end -= 1 }
33 ranges.append(line(max(node.range.lowerBound, end - 1)))
34 }
35 case .heading, .item:
36 ranges += node.tokens.filter { tokens.contains($0.kind) }.map(\.range)
37 default:
38 break
39 }
40 }
41 return ranges
42 }
43}