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

merged merged by cmc on 2026-10-14 04:22 UTC · krz/orgstar:writing-stats into main

11 files changed, +169 −9

Layout: unified · split

Sources/OrgCore/Semantic/TextStats.swift +12
@@ -97,6 +97,18 @@ public enum TextStats {
97 } 97 }
98 98
99 /// `count-words-region`: lines (a partial last line counts), words and characters. 99 /// `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
100 public static func region(_ text: some StringProtocol) -> (lines: Int, words: Int, characters: Int) { 112 public static func region(_ text: some StringProtocol) -> (lines: Int, words: Int, characters: Int) {
101 var lines = 0 113 var lines = 0
102 var characters = 0 114 var characters = 0
Sources/OrgPresentation/SpellCheck.swift +13
@@ -41,4 +41,17 @@ public enum SpellCheck {
41 } 41 }
42 return ranges 42 return ranges
43 } 43 }
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 }
44} 57}
Sources/Orgstar/ModeLine.swift +15 −3
@@ -14,6 +14,7 @@ struct ModeLine: View {
14 let perform: (String) -> Void 14 let perform: (String) -> Void
15 @Environment(\.orgTheme) private var theme 15 @Environment(\.orgTheme) private var theme
16 @State private var words: Int? 16 @State private var words: Int?
17 @State private var characters = 0
17 @State private var crlf = false 18 @State private var crlf = false
18 @State private var branch: String? 19 @State private var branch: String?
19 20
@@ -70,8 +71,18 @@ struct ModeLine: View {
70 Text("\(position.line):\(position.column)") 71 Text("\(position.line):\(position.column)")
71 .help("Line \(position.line), column \(position.column)") 72 .help("Line \(position.line), column \(position.column)")
72 if let words { 73 if let words {
73 Text("\(words.formatted()) \(words == 1 ? "word" : "words")") 74 Menu {
74 .help("Words in the file (count-words)") 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")
75 } 86 }
76 ForEach(encodingNotes, id: \.self) { note in 87 ForEach(encodingNotes, id: \.self) { note in
77 Text(note).foregroundStyle(.orange) 88 Text(note).foregroundStyle(.orange)
@@ -103,7 +114,8 @@ struct ModeLine: View {
103 words = nil 114 words = nil
104 return 115 return
105 } 116 }
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)
107 } 119 }
108 } 120 }
109 121
Sources/OrgstarMobile/EditorScreen.swift +11
@@ -122,6 +122,7 @@ struct EditorScreen: View {
122 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") } 122 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
123 Menu("More", systemImage: "ellipsis.circle") { 123 Menu("More", systemImage: "ellipsis.circle") {
124 Button("Commands", systemImage: "command") { sheet = .palette } 124 Button("Commands", systemImage: "command") { sheet = .palette }
125 Button("Word Count", systemImage: "textformat.123") { message = wordCount() }
125 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") } 126 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
126 Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") } 127 Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
127 Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") } 128 Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
@@ -592,6 +593,16 @@ extension EditorScreen {
592 } 593 }
593 594
594 /// `org-table-export` of the table at the caret, as CSV or TSV. 595 /// `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
595 private func exportTable(csv: Bool) { 606 private func exportTable(csv: Bool) {
596 guard let editor else { return } 607 guard let editor else { return }
597 let context = editor.editContext() 608 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 {
216 applyShrunk(whole, in: storage) 216 applyShrunk(whole, in: storage)
217 applyImages(whole, in: storage, revealed: revealed) 217 applyImages(whole, in: storage, revealed: revealed)
218 applyLatex(whole, in: storage, revealed: revealed) 218 applyLatex(whole, in: storage, revealed: revealed)
219 if options.spellCheck { markMisspellings(in: whole, storage: storage) }
219 storage.endEditing() 220 storage.endEditing()
220 } 221 }
221 222
Sources/OrgstarMobile/MobileEditor.swift +9 −2
@@ -21,7 +21,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
21 private(set) var textView: UITextView 21 private(set) var textView: UITextView
22 var options: EditingOptions = .org { 22 var options: EditingOptions = .org {
23 didSet { 23 didSet {
24 for view in textViews { view.spellCheckingType = options.spellCheck ? .yes : .no } 24 if options.spellCheck != oldValue.spellCheck { restyleAll() }
25 if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities { 25 if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
26 restyleAll() 26 restyleAll()
27 } 27 }
@@ -120,6 +120,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
120 var hideStars = false 120 var hideStars = false
121 /// One paragraph style per indent pair. 121 /// One paragraph style per indent pair.
122 var paragraphStyles: [[Int]: NSParagraphStyle] = [:] 122 var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
123 /// `SpellCheck.skipped` for a revision of the buffer.
124 var spellSkipCache: (revision: Int, ranges: [Range<Int>])?
123 /// The line last revealed while markup is hidden, to hide again when the caret leaves. 125 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
124 var revealedLine: NSRange? 126 var revealedLine: NSRange?
125 /// `org-toggle-inline-images`: lines that are only an image link show the image. 127 /// `org-toggle-inline-images`: lines that are only an image link show the image.
@@ -199,7 +201,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
199 view.smartQuotesType = .no 201 view.smartQuotesType = .no
200 view.smartDashesType = .no 202 view.smartDashesType = .no
201 view.smartInsertDeleteType = .no 203 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
203 view.keyboardDismissMode = .interactive 206 view.keyboardDismissMode = .interactive
204 view.alwaysBounceVertical = true 207 view.alwaysBounceVertical = true
205 view.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8) 208 view.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
@@ -571,6 +574,10 @@ extension MobileEditor: UITextViewDelegate {
571 574
572 /// Another view's caret moves with edits made in this one; only the focused view's 575 /// Another view's caret moves with edits made in this one; only the focused view's
573 /// selection drives the display. 576 /// 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
574 func textViewDidChangeSelection(_ textView: UITextView) { 581 func textViewDidChangeSelection(_ textView: UITextView) {
575 if textView.isFirstResponder { focus(textView) } 582 if textView.isFirstResponder { focus(textView) }
576 guard textView === self.textView else { return } 583 guard textView === self.textView else { return }
Tests/OrgCoreTests/TextStatsTests.swift +11
@@ -77,3 +77,14 @@ struct TextStatsTests {
77 #expect(TextStats.position(in: text, at: 0) == (1, 0)) 77 #expect(TextStats.position(in: text, at: 0) == (1, 0))
78 } 78 }
79} 79}
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 {
36 """ + "\n" 36 """ + "\n"
37 #expect(checked(text) == ["Headng", "wurd", "Prose", "wurds", "itemm", "quotd"]) 37 #expect(checked(text) == ["Headng", "wurd", "Prose", "wurds", "itemm", "quotd"])
38 } 38 }
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 }
39} 45}
docs/manual/guide/02-the-editor.org +3 −3
@@ -194,13 +194,13 @@ The line under the editor shows, from the left:
194| Running clock | a clock is running | elapsed time and the clocked heading; click for Clock Out, Cancel Clock and Go to Clocked Entry | 194| Running clock | a clock is running | elapsed time and the clocked heading; click for Clock Out, Cancel Clock and Go to Clocked Entry |
195| Selection counts | text is selected | lines, words and characters in the selection, as =count-words-region= | 195| Selection counts | text is selected | lines, words and characters in the selection, as =count-words-region= |
196| Line and column | always | =LINE:COLUMN= of the caret (the end of the selection) | 196| 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 |
198| Encoding notes | the file differs from UTF-8 with LF | =Read-only=, =BOM= and =CRLF=, in orange | 198| Encoding notes | the file differs from UTF-8 with LF | =Read-only=, =BOM= and =CRLF=, in orange |
199| Git branch | the file is in a Git repository | the checked-out branch, or the first 7 characters of the commit when detached | 199| Git branch | the file is in a Git repository | the checked-out branch, or the first 7 characters of the commit when detached |
200 200
201Lines 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. 201Lines 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.
202 202
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.
204 204
205The 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]]. 205The 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]].
206 206
@@ -290,7 +290,7 @@ Misspelt words are underlined, using the macOS spelling dictionary. In org files
290 290
291orgstar never corrects spelling on its own; automatic spelling correction, text replacement and smart quotes and dashes are off. 291orgstar never corrects spelling on its own; automatic spelling correction, text replacement and smart quotes and dashes are off.
292 292
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.
294 294
295* Wrapping and filling 295* Wrapping and filling
296 296
docs/manual/guide/14-ios.org +1 −1
@@ -46,7 +46,7 @@ Tap a file in Folders, Search or the agenda to read it.
46 46
47Tap Edit in the reader. The title shows the buffer name, with =•= while there are unsaved changes. The tab bar is hidden while you edit. 47Tap Edit in the reader. The title shows the buffer name, with =•= while there are unsaved changes. The tab bar is hidden while you edit.
48 48
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.
50 50
51The toolbar has: 51The toolbar has:
52 52