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