Sources/OrgstarMobile/MobileEditor+Spelling.swift
87 lines · 4622 bytes
1#if os(iOS)
2import OrgPresentation
3import UIKit
4
5extension NSAttributedString.Key {
6 /// A word the editor's spell checker found misspelt.
7 static let orgMisspelled = NSAttributedString.Key("OrgMisspelled")
8}
9
10/// Spell checking outside code, links, dates, tags and keywords, as the Mac's spell checker
11/// is kept out of them (`SpellCheck.skipped`). UITextView can't leave ranges out of its own
12/// checking, so with `spell-check` on the editor checks with UITextChecker itself, marks the
13/// words, and offers guesses in the edit menu.
14extension MobileEditor {
15 /// The first preferred language the checker has, else US English.
16 static let spellLanguage: String = {
17 let available = UITextChecker.availableLanguages
18 for preferred in Locale.preferredLanguages {
19 let id = preferred.replacingOccurrences(of: "-", with: "_")
20 if available.contains(id) { return id }
21 let base = String(id.prefix { $0 != "_" })
22 if let match = available.first(where: { $0 == base || $0.hasPrefix(base + "_") }) { return match }
23 }
24 return "en_US"
25 }()
26
27 static let spellChecker = UITextChecker()
28
29 /// Marks the misspelt words in `range`, leaving out the word being typed at the caret.
30 func markMisspellings(in range: Range<Int>, storage: NSTextStorage) {
31 let string = storage.string
32 let caret = textView.isFirstResponder && textView.selectedRange.length == 0 ? textView.selectedRange.location : nil
33 let skipped = spellSkipped()
34 for part in SpellCheck.checkable(range, skipped: skipped) {
35 var start = part.lowerBound
36 while start < part.upperBound {
37 let found = Self.spellChecker.rangeOfMisspelledWord(
38 in: string, range: NSRange(part), startingAt: start, wrap: false, language: Self.spellLanguage
39 )
40 guard found.location != NSNotFound, found.location >= start else { break }
41 start = NSMaxRange(found)
42 if let caret, caret >= found.location, caret <= NSMaxRange(found) { continue }
43 storage.addAttributes([
44 .underlineStyle: NSUnderlineStyle([.single, .patternDot]).rawValue,
45 .underlineColor: UIColor.systemRed,
46 .orgMisspelled: true,
47 ], range: found)
48 }
49 }
50 }
51
52 /// The skipped ranges for the buffer's current text, kept until it changes.
53 func spellSkipped() -> [Range<Int>] {
54 if let cached = spellSkipCache, cached.revision == document.revision { return cached.ranges }
55 let ranges = SpellCheck.skipped(document.tree)
56 spellSkipCache = (document.revision, ranges)
57 return ranges
58 }
59
60 /// Guesses for the misspelt word at `range`, and Learn Spelling, above the system's actions.
61 func spellingMenu(for range: NSRange, in view: UITextView, suggested: [UIMenuElement]) -> UIMenu? {
62 let storage = view.textStorage
63 let location = range.location < storage.length && storage.attribute(.orgMisspelled, at: range.location, effectiveRange: nil) != nil
64 ? range.location : range.location - 1
65 guard location >= 0, location < storage.length else { return nil }
66 var word = NSRange()
67 guard storage.attribute(.orgMisspelled, at: location, longestEffectiveRange: &word, in: NSRange(location: 0, length: storage.length)) != nil else { return nil }
68 let text = (storage.string as NSString).substring(with: word)
69 let guesses = Self.spellChecker.guesses(forWordRange: word, in: storage.string, language: Self.spellLanguage) ?? []
70 var actions: [UIMenuElement] = guesses.prefix(5).map { guess in
71 UIAction(title: guess) { [weak self, weak view] _ in
72 guard let self, let view,
73 let start = view.position(from: view.beginningOfDocument, offset: word.location),
74 let end = view.position(from: start, offset: word.length),
75 let range = view.textRange(from: start, to: end) else { return }
76 view.replace(range, withText: guess)
77 self.restyle(word.location..<(word.location + (guess as NSString).length))
78 }
79 }
80 actions.append(UIAction(title: "Learn Spelling", image: UIImage(systemName: "book")) { [weak self] _ in
81 UITextChecker.learnWord(text)
82 self?.restyle(word.location..<NSMaxRange(word))
83 })
84 return UIMenu(children: [UIMenu(options: .displayInline, children: actions)] + suggested)
85 }
86}
87#endif