Tests/OrgEditorAppKitTests/EditorTests.swift
403 lines · 17123 bytes
1import AppKit
2import OrgCore
3import OrgDocument
4import OrgPresentation
5@testable import OrgApp
6import Testing
7@testable import OrgEditorAppKit
8
9/// An editor in an offscreen window, laid out.
10@MainActor
11final class Harness {
12 let editor: OrgEditor
13 let window: NSWindow
14
15 convenience init(_ text: String) {
16 self.init(DocumentState(bytes: Array(text.utf8)))
17 drainStyling()
18 layout()
19 }
20
21 /// The editor as a window would show it first: background styling not yet run.
22 init(_ document: DocumentState, layout: Bool = true) {
23 _ = NSApplication.shared
24 editor = OrgEditor(document: document)
25 window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 800), styleMask: [.titled], backing: .buffered, defer: false)
26 window.contentView = editor.makeScrollView()
27 window.makeFirstResponder(editor.textView)
28 if layout { self.layout() }
29 }
30
31 func drainStyling() {
32 editor.finishStyling()
33 }
34
35 var textView: NSTextView { editor.textView }
36 var string: String { textView.string }
37
38 func layout() {
39 let manager = editor.textLayoutManager
40 manager.ensureLayout(for: manager.documentRange)
41 }
42
43 /// Text of each laid-out paragraph.
44 var visibleLines: [String] {
45 layout()
46 let manager = editor.textLayoutManager
47 var lines: [String] = []
48 manager.enumerateTextLayoutFragments(from: manager.documentRange.location, options: [.ensuresLayout]) { fragment in
49 let content = manager.textContentManager!
50 let start = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location)
51 let end = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.endLocation)
52 lines.append((self.string as NSString).substring(with: NSRange(location: start, length: end - start)))
53 return true
54 }
55 return lines.filter { !$0.isEmpty }
56 }
57
58 func caret(at offset: Int) {
59 textView.setSelectedRange(NSRange(location: offset, length: 0))
60 }
61
62 var caret: Int { textView.selectedRange().location }
63
64 func offset(of line: String) -> Int {
65 (string as NSString).range(of: line).location
66 }
67
68 func checkInSync() {
69 #expect(editor.document.text == string)
70 #expect(editor.document.tree.green == OrgParser.parse(string).green)
71 }
72}
73
74let outline = "* a\nbody\n** b\nmore\n* c\ntext\n"
75
76@MainActor
77struct FoldingTests {
78 @Test func foldingHidesTheSubtree() {
79 let h = Harness(outline)
80 #expect(h.visibleLines == ["* a\n", "body\n", "** b\n", "more\n", "* c\n", "text\n"])
81 h.caret(at: 1)
82 #expect(h.editor.cycleAtCaret())
83 #expect(h.visibleLines == ["* a\n", "* c\n", "text\n"])
84 h.editor.cycleAtCaret()
85 #expect(h.visibleLines == ["* a\n", "body\n", "** b\n", "* c\n", "text\n"])
86 h.editor.cycleAtCaret()
87 #expect(h.visibleLines.count == 6)
88 }
89
90 @Test func globalCycleAndStartup() {
91 let h = Harness(outline)
92 h.editor.run("org.cycle-global")
93 h.editor.run("org.cycle-global")
94 #expect(h.visibleLines == ["* a\n", "** b\n", "* c\n"])
95 h.editor.run("org.cycle-global")
96 #expect(h.visibleLines.count == 6)
97 #expect(Harness("#+STARTUP: overview\n" + outline).visibleLines == ["#+STARTUP: overview\n", "* a\n", "* c\n"])
98 }
99
100 @Test func revealUnfoldsWhatHidesTheTarget() {
101 let h = Harness("#+STARTUP: overview\n" + outline)
102 let target = h.offset(of: "more")
103 h.editor.reveal(target)
104 #expect(h.visibleLines.contains("more\n"))
105 #expect(h.caret == target)
106 }
107
108 @Test func readOnlyAndReloadKeepFolds() {
109 let editor = OrgEditor(document: DocumentState(bytes: Array(outline.utf8)), editable: false)
110 #expect(!editor.textView.isEditable)
111 editor.setFolds(FoldState(folds: [19]))
112 editor.diskChanged(to: Array(("new line\n" + outline).utf8))
113 #expect(editor.document.text == "new line\n" + outline)
114 #expect(editor.foldState.folds == [28])
115 }
116
117 @Test func tabFoldsOnlyOnHeadings() {
118 let h = Harness(outline)
119 h.caret(at: 5)
120 #expect(!h.editor.cycleAtCaret())
121 h.editor.run("org.cycle-global")
122 #expect(h.visibleLines == ["* a\n", "* c\n"])
123 }
124
125 @Test func caretMovesOverFoldedText() {
126 let h = Harness(outline)
127 h.caret(at: 1)
128 h.editor.cycleAtCaret()
129 h.caret(at: 0)
130 h.textView.moveDown(nil)
131 #expect(h.caret >= h.offset(of: "* c") && h.caret < h.offset(of: "text"))
132 h.caret(at: 3)
133 h.textView.moveRight(nil)
134 #expect(h.caret == h.offset(of: "* c"))
135 h.textView.moveLeft(nil)
136 #expect(h.caret == 3)
137 }
138
139 @Test func copyingAcrossAFoldIncludesHiddenText() {
140 let h = Harness(outline)
141 h.caret(at: 1)
142 h.editor.cycleAtCaret()
143 h.textView.setSelectedRange(NSRange(location: 0, length: h.offset(of: "text")))
144 let pasteboard = NSPasteboard(name: NSPasteboard.Name("orgstar-test-\(UUID().uuidString)"))
145 defer { pasteboard.releaseGlobally() }
146 #expect(h.textView.writeSelection(to: pasteboard, types: h.textView.writablePasteboardTypes))
147 #expect(pasteboard.string(forType: .string) == "* a\nbody\n** b\nmore\n* c\n")
148 }
149
150 @Test func foldsFollowEdits() {
151 let h = Harness(outline)
152 h.caret(at: h.offset(of: "* c") + 1)
153 h.editor.cycleAtCaret()
154 h.caret(at: 0)
155 h.textView.insertText("new ", replacementRange: NSRange(location: 2, length: 0))
156 #expect(h.visibleLines == ["* new a\n", "body\n", "** b\n", "more\n", "* c\n"])
157 h.checkInSync()
158 }
159}
160
161@MainActor
162struct EditingTests {
163 @Test func typingKeepsTheDocumentInSync() {
164 let h = Harness(outline)
165 h.caret(at: h.offset(of: "body") + 4)
166 h.textView.insertText(" *bold*", replacementRange: h.textView.selectedRange())
167 h.textView.insertNewline(nil)
168 h.textView.insertText("* new heading", replacementRange: h.textView.selectedRange())
169 h.textView.deleteBackward(nil)
170 h.checkInSync()
171 #expect(h.editor.document.isDirty)
172 }
173
174 @Test func inputMethodComposition() {
175 let h = Harness("* a\n")
176 h.caret(at: 3)
177 h.textView.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
178 #expect(h.textView.hasMarkedText())
179 h.textView.setMarkedText("かん", selectedRange: NSRange(location: 2, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
180 h.textView.insertText("漢", replacementRange: NSRange(location: NSNotFound, length: 0))
181 #expect(!h.textView.hasMarkedText())
182 #expect(h.string == "* a漢\n")
183 h.checkInSync()
184 }
185
186 @Test func undoKeepsTheDocumentInSync() {
187 let h = Harness(outline)
188 h.caret(at: 3)
189 h.textView.insertText("xyz", replacementRange: h.textView.selectedRange())
190 h.textView.breakUndoCoalescing()
191 h.textView.undoManager?.undo()
192 #expect(h.string == outline)
193 h.checkInSync()
194 }
195
196 @Test func styling() throws {
197 let h = Harness("** b\nbody\n")
198 let storage = try #require(h.textView.textStorage)
199 #expect(storage.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor == .clear)
200 let style = try #require(storage.attribute(.paragraphStyle, at: 6, effectiveRange: nil) as? NSParagraphStyle)
201 #expect(style.firstLineHeadIndent == 3 * h.editor.theme.column)
202 h.caret(at: 0)
203 h.textView.insertText("*", replacementRange: NSRange(location: 0, length: 0))
204 let deeper = try #require(storage.attribute(.paragraphStyle, at: 7, effectiveRange: nil) as? NSParagraphStyle)
205 #expect(deeper.firstLineHeadIndent == 4 * h.editor.theme.column)
206 }
207
208 @Test func accessibilityReadsTheWholeText() {
209 let h = Harness(outline)
210 h.caret(at: 1)
211 h.editor.cycleAtCaret()
212 #expect(h.textView.accessibilityValue() as? String == outline)
213 h.textView.setSelectedRange(NSRange(location: 0, length: 3))
214 #expect(h.textView.accessibilitySelectedText() == "* a")
215 #expect(h.textView.accessibilityLine(for: h.offset(of: "* c")) >= 1)
216 }
217
218 @Test func saveWritesAndClearsDirty() throws {
219 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
220 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
221 defer { try? FileManager.default.removeItem(at: folder) }
222 let file = folder.appendingPathComponent("a.org")
223 try Data(outline.utf8).write(to: file)
224 let h = Harness(outline)
225 h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
226 let saver = Saver(fileSystem: CoordinatedFileSystem(), recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
227 #expect(try h.editor.save(using: saver, to: file) == .saved)
228 #expect(!h.editor.document.isDirty)
229 #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
230 }
231}
232
233@MainActor
234struct BufferTests {
235 @Test func updateMapsCaretAndFoldsAndClearsUndo() {
236 let h = Harness(outline)
237 var changes = 0
238 h.editor.onChange = { changes += 1 }
239 h.caret(at: 1)
240 h.textView.insertText("x", replacementRange: NSRange(location: 4, length: 0))
241 #expect(changes == 1)
242 RunLoop.current.run(until: Date())
243 #expect(h.textView.undoManager?.canUndo == true)
244 h.editor.setFolds(FoldState(folds: [h.offset(of: "** b")]))
245 h.caret(at: h.offset(of: "* c") + 2)
246 h.editor.update { $0 = DocumentState(bytes: Array(("new\n" + outline).utf8)) }
247 #expect(changes == 2)
248 #expect(h.string == "new\n" + outline)
249 #expect(h.caret == h.offset(of: "* c") + 2)
250 #expect(h.editor.foldState.folds == [h.offset(of: "** b")])
251 #expect(h.textView.undoManager?.canUndo != true)
252 h.checkInSync()
253 }
254
255 /// The wiring the app uses: the editor is the session's buffer and reports typing.
256 @Test func sessionSavesWhatIsTyped() async throws {
257 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
258 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
259 defer { try? FileManager.default.removeItem(at: folder) }
260 let file = folder.appendingPathComponent("a.org")
261 try Data(outline.utf8).write(to: file)
262 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
263 session.autosaveDelay = .milliseconds(10)
264 session.open(file.path)
265 let h = Harness(try #require(session.document))
266 h.editor.onChange = { [weak session] in session?.bufferChanged() }
267 session.attach(h.editor)
268 h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
269 #expect(session.isDirty)
270 await session.autosave?.value
271 #expect(!session.isDirty)
272 #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
273
274 try Data(("x" + outline + "end\n").utf8).write(to: file)
275 session.fileChanged(file.path)
276 #expect(h.string == "x" + outline + "end\n")
277 }
278}
279
280@MainActor
281struct RestyleTests {
282 func indent(_ h: Harness, at line: String) -> CGFloat? {
283 let style = h.textView.textStorage?.attribute(.paragraphStyle, at: h.offset(of: line), effectiveRange: nil) as? NSParagraphStyle
284 return style.map { $0.firstLineHeadIndent / h.editor.theme.column }
285 }
286
287 @Test func newHeadingReindentsTheLinesItTakesOver() {
288 let h = Harness("* a\none\ntwo\nthree\n")
289 h.textView.insertText("** b\n", replacementRange: NSRange(location: h.offset(of: "two"), length: 0))
290 #expect(indent(h, at: "one") == 2)
291 #expect(indent(h, at: "three") == 3)
292 h.checkInSync()
293 }
294
295 @Test func joiningAwayAHeadingReindentsItsBody() {
296 let h = Harness("* a\none\n** b\ntwo\nthree\n")
297 h.textView.insertText("", replacementRange: NSRange(location: h.offset(of: "** b") - 1, length: 1))
298 #expect(indent(h, at: "three") == 2)
299 h.checkInSync()
300 }
301
302 @Test func typingASpaceAfterAStarMakesAHeading() {
303 let h = Harness("* a\n*x\nbody\nmore\n")
304 h.textView.insertText(" ", replacementRange: NSRange(location: h.offset(of: "*x") + 1, length: 0))
305 #expect(indent(h, at: "more") == 2)
306 h.checkInSync()
307 }
308}
309
310@MainActor
311struct RestyleFuzzTests {
312 /// After each random edit, the restyled text must equal a fresh editor's full styling. Set
313 /// `ORGSTAR_RESTYLE_EDITS` and `ORGSTAR_FUZZ_SEED` for longer runs.
314 @Test func incrementalRestyleEqualsFullRestyle() throws {
315 let environment = ProcessInfo.processInfo.environment
316 var state = UInt64(environment["ORGSTAR_FUZZ_SEED"] ?? "") ?? 20261006
317 let count = Int(environment["ORGSTAR_RESTYLE_EDITS"] ?? "") ?? 300
318 func next(_ bound: Int) -> Int {
319 state = state &* 6364136223846793005 &+ 1442695040888963407
320 return Int((state >> 33) % UInt64(bound))
321 }
322 let pieces = ["* ", "** ", "*", " ", "\n", "x", "*b*", "TODO ", "- ", "| a |", "#+begin_src\n", "#+end_src\n", ":PROPERTIES:\n", ":END:\n", "[[l][d]]", "<2026-10-04 Sun>"]
323 let h = Harness("* a\nbody *b*\n** b\n- item\nmore\n* c\ntext\n")
324 for n in 0..<count {
325 let length = (h.string as NSString).length
326 let start = next(length + 1)
327 let end = min(length, start + next(4))
328 let replacement = next(3) == 0 ? "" : pieces[next(pieces.count)]
329 h.textView.insertText(replacement, replacementRange: NSRange(location: start, length: end - start))
330 let fresh = Harness(h.string)
331 let same = h.textView.textStorage!.isEqual(to: fresh.textView.textStorage!)
332 #expect(same, "edit \(n): \(start)..<\(end) \(replacement.debugDescription) -> \(h.string.debugDescription)")
333 if !same { break }
334 }
335 h.checkInSync()
336 }
337}
338
339@MainActor
340struct InitialStylingTests {
341 @Test func stylesTheFirstScreenThenTheRest() throws {
342 let line = "* heading *bold*\nbody text\n"
343 let text = String(repeating: line, count: 4_000)
344 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
345 let length = (text as NSString).length
346 #expect(h.editor.styledUpTo >= OrgEditor.firstStyleChunk && h.editor.styledUpTo < length)
347 h.textView.insertText("x", replacementRange: NSRange(location: length - 3, length: 0))
348 h.drainStyling()
349 #expect(h.editor.styledUpTo == length + 1)
350 #expect(h.textView.textStorage!.isEqual(to: Harness(h.string).textView.textStorage!))
351 }
352
353 @Test func editsBeforeTheWatermarkShiftIt() {
354 let text = String(repeating: "line of text\n", count: 5_000)
355 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
356 let before = h.editor.styledUpTo
357 h.textView.insertText("abc", replacementRange: NSRange(location: 0, length: 0))
358 #expect(h.editor.styledUpTo == before + 3)
359 }
360}
361
362struct HangingIndentTests {
363 @Test(arguments: [
364 ("plain", 0), (" indented", 2), ("- item", 2), (" - [X] done", 8), ("12. step", 4),
365 ("* heading-like", 0), (" * starred item", 4), ("-not a bullet", 0), ("\t- tab", 10),
366 ])
367 func columns(line: String, expected: Int) {
368 #expect(OrgEditor.hangingColumns(line) == expected)
369 }
370}
371
372@MainActor
373struct CommandTests {
374 @Test func performEditsThroughTheTextView() {
375 let h = Harness("* a :t:\nbody\n")
376 var messages: [String] = []
377 h.editor.onMessage = { messages.append($0) }
378 h.caret(at: 2)
379 h.editor.perform(PriorityUp())
380 #expect(h.string.hasPrefix("* [#B] a "))
381 #expect(h.caret == 2)
382 h.checkInSync()
383 // Undo groups by event: let the run loop close the first command's group, as a key
384 // press would.
385 RunLoop.current.run(until: Date())
386 h.editor.perform(TodoCycle())
387 #expect(h.string.hasPrefix("* TODO [#B] a "))
388 RunLoop.current.run(until: Date())
389 h.textView.undoManager?.undo()
390 #expect(h.string.hasPrefix("* [#B] a "))
391 h.checkInSync()
392 h.caret(at: h.offset(of: "body"))
393 h.editor.perform(PromoteHeading())
394 #expect(messages == ["Not on a heading"])
395 }
396
397 @Test func readOnlyEditorsRefuseEdits() {
398 let editor = OrgEditor(document: DocumentState(bytes: Array("* a\n".utf8)), editable: false)
399 editor.textView.setSelectedRange(NSRange(location: 2, length: 0))
400 #expect(editor.perform(TodoCycle()) == .failed("read-only"))
401 #expect(editor.document.text == "* a\n")
402 }
403}