Tests/OrgEditorAppKitTests/EditorTests.swift
470 lines · 20867 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, mode: OrgEditor.Mode = .org) {
23 _ = NSApplication.shared
24 editor = OrgEditor(document: document, mode: mode)
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 drawersFoldAtOpenAndToggleWithTab() {
151 let text = "* a\n:PROPERTIES:\n:ID: x\n:END:\nbody\n#+begin_src sh\necho\n#+end_src\n* c\n"
152 let h = Harness(text)
153 #expect(h.visibleLines == ["* a\n", ":PROPERTIES:\n", "body\n", "#+begin_src sh\n", "echo\n", "#+end_src\n", "* c\n"])
154 h.caret(at: h.offset(of: ":PROPERTIES:"))
155 #expect(h.editor.cycleAtCaret())
156 #expect(h.visibleLines.count == 9)
157 h.caret(at: h.offset(of: "#+end_src"))
158 #expect(h.editor.cycleAtCaret())
159 #expect(h.visibleLines == ["* a\n", ":PROPERTIES:\n", ":ID: x\n", ":END:\n", "body\n", "#+begin_src sh\n", "* c\n"])
160 #expect(h.textView.selectedRange().location == h.offset(of: "#+begin_src"))
161 // Heading cycling leaves the block folded.
162 h.caret(at: 1)
163 h.editor.cycleAtCaret()
164 h.editor.cycleAtCaret()
165 #expect(h.visibleLines.contains("#+begin_src sh\n") && !h.visibleLines.contains("echo\n"))
166 #expect(Harness("#+STARTUP: nohidedrawers\n" + text).visibleLines.contains(":ID: x\n"))
167 let folded = Harness(text)
168 folded.editor.reveal(folded.offset(of: ":ID: x") + 1)
169 #expect(folded.visibleLines.contains(":ID: x\n"))
170 }
171
172 @Test func drawerFoldsFollowEdits() {
173 let h = Harness("* a\n:PROPERTIES:\n:ID: x\n:END:\nbody\n* b\n:LOGBOOK:\nl\n:END:\n")
174 h.caret(at: h.offset(of: "body") + 4)
175 h.textView.insertText(" more", replacementRange: h.textView.selectedRange())
176 h.textView.insertNewline(nil)
177 h.caret(at: 2)
178 h.textView.insertText("new ", replacementRange: h.textView.selectedRange())
179 #expect(h.visibleLines == ["* new a\n", ":PROPERTIES:\n", "body more\n", "\n", "* b\n", ":LOGBOOK:\n"])
180 // Renaming the drawer's opening line keeps a drawer, and its fold.
181 h.caret(at: h.offset(of: ":LOGBOOK:") + 1)
182 h.textView.insertText("X", replacementRange: h.textView.selectedRange())
183 #expect(h.visibleLines.last == ":XLOGBOOK:\n")
184 h.checkInSync()
185 }
186
187 @Test func foldsFollowEdits() {
188 let h = Harness(outline)
189 h.caret(at: h.offset(of: "* c") + 1)
190 h.editor.cycleAtCaret()
191 h.caret(at: 0)
192 h.textView.insertText("new ", replacementRange: NSRange(location: 2, length: 0))
193 #expect(h.visibleLines == ["* new a\n", "body\n", "** b\n", "more\n", "* c\n"])
194 h.checkInSync()
195 }
196}
197
198@MainActor
199struct EditingTests {
200 @Test func typingKeepsTheDocumentInSync() {
201 let h = Harness(outline)
202 h.caret(at: h.offset(of: "body") + 4)
203 h.textView.insertText(" *bold*", replacementRange: h.textView.selectedRange())
204 h.textView.insertNewline(nil)
205 h.textView.insertText("* new heading", replacementRange: h.textView.selectedRange())
206 h.textView.deleteBackward(nil)
207 h.checkInSync()
208 #expect(h.editor.document.isDirty)
209 }
210
211 @Test func inputMethodComposition() {
212 let h = Harness("* a\n")
213 h.caret(at: 3)
214 h.textView.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
215 #expect(h.textView.hasMarkedText())
216 h.textView.setMarkedText("かん", selectedRange: NSRange(location: 2, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
217 h.textView.insertText("漢", replacementRange: NSRange(location: NSNotFound, length: 0))
218 #expect(!h.textView.hasMarkedText())
219 #expect(h.string == "* a漢\n")
220 h.checkInSync()
221 }
222
223 @Test func undoKeepsTheDocumentInSync() {
224 let h = Harness(outline)
225 h.caret(at: 3)
226 h.textView.insertText("xyz", replacementRange: h.textView.selectedRange())
227 h.textView.breakUndoCoalescing()
228 h.textView.undoManager?.undo()
229 #expect(h.string == outline)
230 h.checkInSync()
231 }
232
233 @Test func styling() throws {
234 let h = Harness("** b\nbody\n")
235 let storage = try #require(h.textView.textStorage)
236 #expect(storage.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor == .clear)
237 let style = try #require(storage.attribute(.paragraphStyle, at: 6, effectiveRange: nil) as? NSParagraphStyle)
238 #expect(style.firstLineHeadIndent == 3 * h.editor.theme.column)
239 h.caret(at: 0)
240 h.textView.insertText("*", replacementRange: NSRange(location: 0, length: 0))
241 let deeper = try #require(storage.attribute(.paragraphStyle, at: 7, effectiveRange: nil) as? NSParagraphStyle)
242 #expect(deeper.firstLineHeadIndent == 4 * h.editor.theme.column)
243 }
244
245 @Test func accessibilityReadsTheWholeText() {
246 let h = Harness(outline)
247 h.caret(at: 1)
248 h.editor.cycleAtCaret()
249 #expect(h.textView.accessibilityValue() as? String == outline)
250 h.textView.setSelectedRange(NSRange(location: 0, length: 3))
251 #expect(h.textView.accessibilitySelectedText() == "* a")
252 #expect(h.textView.accessibilityLine(for: h.offset(of: "* c")) >= 1)
253 }
254
255 @Test func saveWritesAndClearsDirty() throws {
256 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
257 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
258 defer { try? FileManager.default.removeItem(at: folder) }
259 let file = folder.appendingPathComponent("a.org")
260 try Data(outline.utf8).write(to: file)
261 let h = Harness(outline)
262 h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
263 let saver = Saver(fileSystem: CoordinatedFileSystem(), recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
264 #expect(try h.editor.save(using: saver, to: file) == .saved)
265 #expect(!h.editor.document.isDirty)
266 #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
267 }
268}
269
270@MainActor
271struct BufferTests {
272 @Test func updateMapsCaretAndFoldsAndClearsUndo() {
273 let h = Harness(outline)
274 var changes = 0
275 h.editor.onChange = { changes += 1 }
276 h.caret(at: 1)
277 h.textView.insertText("x", replacementRange: NSRange(location: 4, length: 0))
278 #expect(changes == 1)
279 RunLoop.current.run(until: Date())
280 #expect(h.textView.undoManager?.canUndo == true)
281 h.editor.setFolds(FoldState(folds: [h.offset(of: "** b")]))
282 h.caret(at: h.offset(of: "* c") + 2)
283 h.editor.update { $0 = DocumentState(bytes: Array(("new\n" + outline).utf8)) }
284 #expect(changes == 2)
285 #expect(h.string == "new\n" + outline)
286 #expect(h.caret == h.offset(of: "* c") + 2)
287 #expect(h.editor.foldState.folds == [h.offset(of: "** b")])
288 #expect(h.textView.undoManager?.canUndo != true)
289 h.checkInSync()
290 }
291
292 /// Each buffer's editor reports its own changes: a background buffer's edit saves its
293 /// file, not the shown one's.
294 @Test func backgroundEditorsSaveTheirOwnFiles() async throws {
295 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
296 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
297 defer { try? FileManager.default.removeItem(at: folder) }
298 let a = folder.appendingPathComponent("a.org"), b = folder.appendingPathComponent("b.org")
299 try Data("* A\n".utf8).write(to: a)
300 try Data("* B\n".utf8).write(to: b)
301 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
302 session.autosaveDelay = .milliseconds(10)
303 var harnesses: [String: Harness] = [:]
304 for file in [a, b] {
305 session.open(file.path)
306 let h = Harness(try #require(session.document))
307 let path = file.path
308 h.editor.onChange = { [weak session] in session?.bufferChanged(path) }
309 session.attach(h.editor)
310 harnesses[path] = h
311 }
312 #expect(session.path == b.path)
313 harnesses[a.path]!.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
314 #expect(session.dirtyPaths == [a.path])
315 #expect(!session.isDirty)
316 for _ in 0..<50 where (try? String(contentsOf: a, encoding: .utf8)) != "x* A\n" {
317 try await Task.sleep(for: .milliseconds(20))
318 }
319 #expect(try String(contentsOf: a, encoding: .utf8) == "x* A\n")
320 }
321
322 /// The wiring the app uses: the editor is the session's buffer and reports typing.
323 @Test func sessionSavesWhatIsTyped() async throws {
324 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
325 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
326 defer { try? FileManager.default.removeItem(at: folder) }
327 let file = folder.appendingPathComponent("a.org")
328 try Data(outline.utf8).write(to: file)
329 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
330 session.autosaveDelay = .milliseconds(10)
331 session.open(file.path)
332 let h = Harness(try #require(session.document))
333 h.editor.onChange = { [weak session] in session?.bufferChanged() }
334 session.attach(h.editor)
335 h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
336 #expect(session.isDirty)
337 await session.autosave?.value
338 #expect(!session.isDirty)
339 #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
340
341 try Data(("x" + outline + "end\n").utf8).write(to: file)
342 session.fileChanged(file.path)
343 #expect(h.string == "x" + outline + "end\n")
344 }
345}
346
347@MainActor
348struct RestyleTests {
349 func indent(_ h: Harness, at line: String) -> CGFloat? {
350 let style = h.textView.textStorage?.attribute(.paragraphStyle, at: h.offset(of: line), effectiveRange: nil) as? NSParagraphStyle
351 return style.map { $0.firstLineHeadIndent / h.editor.theme.column }
352 }
353
354 @Test func newHeadingReindentsTheLinesItTakesOver() {
355 let h = Harness("* a\none\ntwo\nthree\n")
356 h.textView.insertText("** b\n", replacementRange: NSRange(location: h.offset(of: "two"), length: 0))
357 #expect(indent(h, at: "one") == 2)
358 #expect(indent(h, at: "three") == 3)
359 h.checkInSync()
360 }
361
362 @Test func joiningAwayAHeadingReindentsItsBody() {
363 let h = Harness("* a\none\n** b\ntwo\nthree\n")
364 h.textView.insertText("", replacementRange: NSRange(location: h.offset(of: "** b") - 1, length: 1))
365 #expect(indent(h, at: "three") == 2)
366 h.checkInSync()
367 }
368
369 @Test func typingASpaceAfterAStarMakesAHeading() {
370 let h = Harness("* a\n*x\nbody\nmore\n")
371 h.textView.insertText(" ", replacementRange: NSRange(location: h.offset(of: "*x") + 1, length: 0))
372 #expect(indent(h, at: "more") == 2)
373 h.checkInSync()
374 }
375}
376
377@MainActor
378struct RestyleFuzzTests {
379 /// After each random edit, the restyled text must equal a fresh editor's full styling. Set
380 /// `ORGSTAR_RESTYLE_EDITS` and `ORGSTAR_FUZZ_SEED` for longer runs.
381 @Test func incrementalRestyleEqualsFullRestyle() throws {
382 let environment = ProcessInfo.processInfo.environment
383 var state = UInt64(environment["ORGSTAR_FUZZ_SEED"] ?? "") ?? 20261006
384 let count = Int(environment["ORGSTAR_RESTYLE_EDITS"] ?? "") ?? 300
385 func next(_ bound: Int) -> Int {
386 state = state &* 6364136223846793005 &+ 1442695040888963407
387 return Int((state >> 33) % UInt64(bound))
388 }
389 let pieces = ["* ", "** ", "*", " ", "\n", "x", "*b*", "TODO ", "- ", "| a |", "#+begin_src\n", "#+end_src\n", ":PROPERTIES:\n", ":END:\n", "[[l][d]]", "<2026-10-04 Sun>"]
390 let h = Harness("* a\nbody *b*\n** b\n- item\nmore\n* c\ntext\n")
391 for n in 0..<count {
392 let length = (h.string as NSString).length
393 let start = next(length + 1)
394 let end = min(length, start + next(4))
395 let replacement = next(3) == 0 ? "" : pieces[next(pieces.count)]
396 h.textView.insertText(replacement, replacementRange: NSRange(location: start, length: end - start))
397 let fresh = Harness(h.string)
398 let same = h.textView.textStorage!.isEqual(to: fresh.textView.textStorage!)
399 #expect(same, "edit \(n): \(start)..<\(end) \(replacement.debugDescription) -> \(h.string.debugDescription)")
400 if !same { break }
401 }
402 h.checkInSync()
403 }
404}
405
406@MainActor
407struct InitialStylingTests {
408 @Test func stylesTheFirstScreenThenTheRest() throws {
409 let line = "* heading *bold*\nbody text\n"
410 let text = String(repeating: line, count: 4_000)
411 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
412 let length = (text as NSString).length
413 #expect(h.editor.styledUpTo >= OrgEditor.firstStyleChunk && h.editor.styledUpTo < length)
414 h.textView.insertText("x", replacementRange: NSRange(location: length - 3, length: 0))
415 h.drainStyling()
416 #expect(h.editor.styledUpTo == length + 1)
417 #expect(h.textView.textStorage!.isEqual(to: Harness(h.string).textView.textStorage!))
418 }
419
420 @Test func editsBeforeTheWatermarkShiftIt() {
421 let text = String(repeating: "line of text\n", count: 5_000)
422 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
423 let before = h.editor.styledUpTo
424 h.textView.insertText("abc", replacementRange: NSRange(location: 0, length: 0))
425 #expect(h.editor.styledUpTo == before + 3)
426 }
427}
428
429struct HangingIndentTests {
430 @Test(arguments: [
431 ("plain", 0), (" indented", 2), ("- item", 2), (" - [X] done", 8), ("12. step", 4),
432 ("* heading-like", 0), (" * starred item", 4), ("-not a bullet", 0), ("\t- tab", 10),
433 ])
434 func columns(line: String, expected: Int) {
435 #expect(OrgEditor.hangingColumns(line) == expected)
436 }
437}
438
439@MainActor
440struct CommandTests {
441 @Test func performEditsThroughTheTextView() {
442 let h = Harness("* a :t:\nbody\n")
443 var messages: [String] = []
444 h.editor.onMessage = { messages.append($0) }
445 h.caret(at: 2)
446 h.editor.perform(PriorityUp())
447 #expect(h.string.hasPrefix("* [#B] a "))
448 #expect(h.caret == 2)
449 h.checkInSync()
450 // Undo groups by event: let the run loop close the first command's group, as a key
451 // press would.
452 RunLoop.current.run(until: Date())
453 h.editor.perform(TodoCycle())
454 #expect(h.string.hasPrefix("* TODO [#B] a "))
455 RunLoop.current.run(until: Date())
456 h.textView.undoManager?.undo()
457 #expect(h.string.hasPrefix("* [#B] a "))
458 h.checkInSync()
459 h.caret(at: h.offset(of: "body"))
460 h.editor.perform(PromoteHeading())
461 #expect(messages == ["Not on a heading"])
462 }
463
464 @Test func readOnlyEditorsRefuseEdits() {
465 let editor = OrgEditor(document: DocumentState(bytes: Array("* a\n".utf8)), editable: false)
466 editor.textView.setSelectedRange(NSRange(location: 2, length: 0))
467 #expect(editor.perform(TodoCycle()) == .failed("read-only"))
468 #expect(editor.document.text == "* a\n")
469 }
470}