Commit ab7472adec

ab7472adecc0eb3fca721f8959a144f7605cc709

parent: 1d52f06a76

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-14 04:22 UTC

Writing statistics; word count and spell-check skips on iOS

The Mac modeline's word count is a menu with the file's words, characters
and reading time (230 words a minute, rounded up), and the selection's when
there is one. On iOS, More ▸ Word Count shows the same for the selection or
the file.

UITextView can't leave ranges out of its spell checking, so with spell-check
on the iOS editor checks with UITextChecker itself over what
SpellCheck.skipped leaves (SpellCheck.checkable), during restyling: misspelt
words get a dotted red underline, the word at the caret waits until the caret
leaves it, and the edit menu offers guesses and Learn Spelling.

Closes #78

Layout: unified · split

Sources/OrgCore/Semantic/TextStats.swift +12
@@ -97,6 +97,18 @@ public enum TextStats {
9797 }
9898
9999 /// `count-words-region`: lines (a partial last line counts), words and characters.
100 /// Minutes to read `words` at 230 words a minute, rounded up.
101 public static func readingMinutes(words: Int) -> Int {
102 (words + 229) / 230
103 }
104
105 /// Words, characters and reading time, as the word count shows them.
106 public static func summary(words: Int, characters: Int) -> String {
107 let minutes = readingMinutes(words: words)
108 return "\(words.formatted()) \(words == 1 ? "word" : "words"), \(characters.formatted()) \(characters == 1 ? "character" : "characters"), "
109 + "about \(minutes) \(minutes == 1 ? "minute" : "minutes") to read"
110 }
111
100112 public static func region(_ text: some StringProtocol) -> (lines: Int, words: Int, characters: Int) {
101113 var lines = 0
102114 var characters = 0
Sources/OrgPresentation/SpellCheck.swift +13
@@ -41,4 +41,17 @@ public enum SpellCheck {
4141 }
4242 return ranges
4343 }
44
45 /// The parts of `range` outside every `skipped` range, in order: what a spell checker of
46 /// the app's own checks.
47 public static func checkable(_ range: Range<Int>, skipped: [Range<Int>]) -> [Range<Int>] {
48 var out: [Range<Int>] = []
49 var start = range.lowerBound
50 for skip in skipped.filter({ $0.overlaps(range) }).sorted(by: { $0.lowerBound < $1.lowerBound }) {
51 if skip.lowerBound > start { out.append(start..<skip.lowerBound) }
52 start = max(start, skip.upperBound)
53 }
54 if start < range.upperBound { out.append(start..<range.upperBound) }
55 return out
56 }
4457}
Sources/Orgstar/ModeLine.swift +15 −3
@@ -14,6 +14,7 @@ struct ModeLine: View {
1414 let perform: (String) -> Void
1515 @Environment(\.orgTheme) private var theme
1616 @State private var words: Int?
17 @State private var characters = 0
1718 @State private var crlf = false
1819 @State private var branch: String?
1920
@@ -70,8 +71,18 @@ struct ModeLine: View {
7071 Text("\(position.line):\(position.column)")
7172 .help("Line \(position.line), column \(position.column)")
7273 if let words {
73 Text("\(words.formatted()) \(words == 1 ? "word" : "words")")
74 .help("Words in the file (count-words)")
74 Menu {
75 Text(TextStats.summary(words: words, characters: characters))
76 if selection.length > 0, let region = region(text, selection) {
77 Text("Selection: " + TextStats.summary(words: region.words, characters: region.characters))
78 }
79 } label: {
80 Text("\(words.formatted()) \(words == 1 ? "word" : "words")")
81 }
82 .menuStyle(.borderlessButton)
83 .menuIndicator(.hidden)
84 .fixedSize()
85 .help("Words in the file (count-words); click for characters and reading time")
7586 }
7687 ForEach(encodingNotes, id: \.self) { note in
7788 Text(note).foregroundStyle(.orange)
@@ -103,7 +114,8 @@ struct ModeLine: View {
103114 words = nil
104115 return
105116 }
106 (words, crlf) = await Task.detached(priority: .utility) { (TextStats.words(in: text), text.contains("\r\n")) }.value
117 let counts = await Task.detached(priority: .utility) { (TextStats.region(text), text.contains("\r\n")) }.value
118 (words, characters, crlf) = (counts.0.words, counts.0.characters, counts.1)
107119 }
108120 }
109121
Sources/OrgstarMobile/EditorScreen.swift +11
@@ -122,6 +122,7 @@ struct EditorScreen: View {
122122 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
123123 Menu("More", systemImage: "ellipsis.circle") {
124124 Button("Commands", systemImage: "command") { sheet = .palette }
125 Button("Word Count", systemImage: "textformat.123") { message = wordCount() }
125126 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
126127 Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
127128 Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
@@ -592,6 +593,16 @@ extension EditorScreen {
592593 }
593594
594595 /// `org-table-export` of the table at the caret, as CSV or TSV.
596 /// Words, characters and reading time of the selection, or of the file.
597 private func wordCount() -> String {
598 guard let editor else { return "No file is open" }
599 let text = editor.document.text as NSString
600 let selection = editor.textView.selectedRange
601 let selected = selection.length > 0 && NSMaxRange(selection) <= text.length
602 let counts = TextStats.region(selected ? text.substring(with: selection) : text as String)
603 return (selected ? "Selection: " : "") + TextStats.summary(words: counts.words, characters: counts.characters)
604 }
605
595606 private func exportTable(csv: Bool) {
596607 guard let editor else { return }
597608 let context = editor.editContext()
Sources/OrgstarMobile/MobileEditor+Spelling.swift added +87
@@ -0,0 +1,87 @@
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
Sources/OrgstarMobile/MobileEditor+Styling.swift +1
@@ -216,6 +216,7 @@ extension MobileEditor {
216216 applyShrunk(whole, in: storage)
217217 applyImages(whole, in: storage, revealed: revealed)
218218 applyLatex(whole, in: storage, revealed: revealed)
219 if options.spellCheck { markMisspellings(in: whole, storage: storage) }
219220 storage.endEditing()
220221 }
221222
Sources/OrgstarMobile/MobileEditor.swift +9 −2
@@ -21,7 +21,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
2121 private(set) var textView: UITextView
2222 var options: EditingOptions = .org {
2323 didSet {
24 for view in textViews { view.spellCheckingType = options.spellCheck ? .yes : .no }
24 if options.spellCheck != oldValue.spellCheck { restyleAll() }
2525 if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
2626 restyleAll()
2727 }
@@ -120,6 +120,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
120120 var hideStars = false
121121 /// One paragraph style per indent pair.
122122 var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
123 /// `SpellCheck.skipped` for a revision of the buffer.
124 var spellSkipCache: (revision: Int, ranges: [Range<Int>])?
123125 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
124126 var revealedLine: NSRange?
125127 /// `org-toggle-inline-images`: lines that are only an image link show the image.
@@ -199,7 +201,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
199201 view.smartQuotesType = .no
200202 view.smartDashesType = .no
201203 view.smartInsertDeleteType = .no
202 view.spellCheckingType = options.spellCheck ? .yes : .no
204 // The editor checks spelling itself, outside code, links and keywords.
205 view.spellCheckingType = .no
203206 view.keyboardDismissMode = .interactive
204207 view.alwaysBounceVertical = true
205208 view.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
@@ -571,6 +574,10 @@ extension MobileEditor: UITextViewDelegate {
571574
572575 /// Another view's caret moves with edits made in this one; only the focused view's
573576 /// selection drives the display.
577 func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
578 options.spellCheck ? spellingMenu(for: range, in: textView, suggested: suggestedActions) : nil
579 }
580
574581 func textViewDidChangeSelection(_ textView: UITextView) {
575582 if textView.isFirstResponder { focus(textView) }
576583 guard textView === self.textView else { return }
Tests/OrgCoreTests/TextStatsTests.swift +11
@@ -77,3 +77,14 @@ struct TextStatsTests {
7777 #expect(TextStats.position(in: text, at: 0) == (1, 0))
7878 }
7979}
80
81struct ReadingTimeTests {
82 @Test func minutesAtTwoHundredThirtyWords() {
83 #expect(TextStats.readingMinutes(words: 0) == 0)
84 #expect(TextStats.readingMinutes(words: 1) == 1)
85 #expect(TextStats.readingMinutes(words: 230) == 1)
86 #expect(TextStats.readingMinutes(words: 231) == 2)
87 #expect(TextStats.summary(words: 1234, characters: 6789) == "\(1234.formatted()) words, \(6789.formatted()) characters, about 6 minutes to read")
88 #expect(TextStats.summary(words: 1, characters: 4) == "1 word, 4 characters, about 1 minute to read")
89 }
90}
Tests/OrgPresentationTests/SpellCheckTests.swift +6
@@ -36,4 +36,10 @@ struct SpellCheckTests {
3636 """ + "\n"
3737 #expect(checked(text) == ["Headng", "wurd", "Prose", "wurds", "itemm", "quotd"])
3838 }
39
40 @Test func checkableRangesLeaveOutTheSkipped() {
41 #expect(SpellCheck.checkable(0..<20, skipped: [2..<5, 4..<8, 15..<30]) == [0..<2, 8..<15])
42 #expect(SpellCheck.checkable(10..<20, skipped: []) == [10..<20])
43 #expect(SpellCheck.checkable(10..<20, skipped: [0..<25]).isEmpty)
44 }
3945}
docs/manual/guide/02-the-editor.org +3 −3
@@ -194,13 +194,13 @@ The line under the editor shows, from the left:
194194| Running clock | a clock is running | elapsed time and the clocked heading; click for Clock Out, Cancel Clock and Go to Clocked Entry |
195195| Selection counts | text is selected | lines, words and characters in the selection, as =count-words-region= |
196196| Line and column | always | =LINE:COLUMN= of the caret (the end of the selection) |
197| Word count | always | words in the whole file, as =count-words= |
197| Word count | always | words in the whole file, as =count-words=; click for the characters and reading time of the file and the selection |
198198| Encoding notes | the file differs from UTF-8 with LF | =Read-only=, =BOM= and =CRLF=, in orange |
199199| Git branch | the file is in a Git repository | the checked-out branch, or the first 7 characters of the commit when detached |
200200
201201Lines count from 1. Columns count from 0, as Emacs's =column-number-mode= does: a tab advances to the next multiple of 8, and wide characters such as CJK count as two columns. Hover over an item for a description.
202202
203The word count follows edits after a pause. The Git branch is read from the repository's =HEAD= file without running =git=, and checked again every 5 seconds; worktrees and submodules are followed.
203The word count follows edits after a pause. Reading time is at 230 words a minute, rounded up. The Git branch is read from the repository's =HEAD= file without running =git=, and checked again every 5 seconds; worktrees and submodules are followed.
204204
205205The running clock is covered in [[file:06-dates-and-clocking.org][Dates and clocking]]; the evil states in [[file:03-keys.org][Keys and commands]].
206206
@@ -290,7 +290,7 @@ Misspelt words are underlined, using the macOS spelling dictionary. In org files
290290
291291orgstar never corrects spelling on its own; automatic spelling correction, text replacement and smart quotes and dashes are off.
292292
293On iOS, spell checking follows =spell-check= in the synced =config.toml=, and is off by default.
293On iOS, spell checking follows =spell-check= in the synced =config.toml=, and is off by default. It leaves out the same text as on the Mac: misspelt words get a dotted red underline, and selecting one, or tapping it to show the edit menu, offers guesses and Learn Spelling. The word being typed is checked once the caret leaves it.
294294
295295* Wrapping and filling
296296
docs/manual/guide/14-ios.org +1 −1
@@ -46,7 +46,7 @@ Tap a file in Folders, Search or the agenda to read it.
4646
4747Tap Edit in the reader. The title shows the buffer name, with =•= while there are unsaved changes. The tab bar is hidden while you edit.
4848
49The editor folds headings, drawers and blocks (tap a fold's =…= to open it, and an open drawer's first line to fold it), styles text with the theme from the configuration folder (see Themes and display below), and runs the same Org commands as the Mac. Autocorrection, smart quotes and smart dashes are off; spell checking follows =spell-check= in =config.toml= and is off by default.
49The editor folds headings, drawers and blocks (tap a fold's =…= to open it, and an open drawer's first line to fold it), styles text with the theme from the configuration folder (see Themes and display below), and runs the same Org commands as the Mac. Autocorrection, smart quotes and smart dashes are off; spell checking follows =spell-check= in =config.toml= and is off by default; it leaves out code, links, dates, tags and keywords, as on the Mac. More ▸ Word Count shows the words, characters and reading time of the selection, or of the file.
5050
5151The toolbar has:
5252