Tests/OrgEditorAppKitTests/EditorTests.swift
600 lines · 27550 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 textWidth() throws {
248 let h = Harness("Prose that is long enough to wrap in a narrow text area, past sixty columns of text.\n")
249 let full = try #require(h.textView.textContainer).size.width
250 var spec = ThemeSpec.default
251 spec.textWidth = 40
252 h.editor.themeSpec = spec
253 h.layout()
254 let narrow = try #require(h.textView.textContainer).size.width
255 #expect(narrow < full)
256 #expect(abs(narrow - 40 * h.editor.theme.column - 2 * h.textView.textContainer!.lineFragmentPadding) < 1)
257 // Centred: the same margin either side.
258 #expect(abs(h.textView.textContainerInset.width * 2 + narrow - h.textView.bounds.width) < 1)
259 spec.textWidth = 0
260 h.editor.themeSpec = spec
261 h.layout()
262 #expect(try #require(h.textView.textContainer).size.width == full)
263 }
264
265 @Test func mixedPitch() throws {
266 let text = "**** Heading :tag:\nProse text.\n- item\n| a | b |\n#+begin_src sh\necho\n#+end_src\n"
267 let h = Harness(text)
268 var spec = ThemeSpec.default
269 spec.bodyFont = "system"
270 h.editor.themeSpec = spec
271 h.drainStyling()
272 let storage = try #require(h.textView.textStorage)
273 let ns = text as NSString
274 func fixed(_ needle: String, offset: Int = 0) -> Bool {
275 let font = storage.attribute(.font, at: ns.range(of: needle).location + offset, effectiveRange: nil) as? NSFont
276 return font?.isFixedPitch == true
277 }
278 #expect(!fixed("Prose"))
279 #expect(!fixed("Heading"))
280 #expect(fixed("****"))
281 #expect(fixed(":tag:"))
282 #expect(fixed("- item") && !fixed("item"))
283 #expect(fixed("| a"))
284 #expect(fixed("echo"))
285 // Body indentation is still counted in columns of the fixed-pitch font.
286 let style = try #require(storage.attribute(.paragraphStyle, at: ns.range(of: "Prose").location, effectiveRange: nil) as? NSParagraphStyle)
287 #expect(style.firstLineHeadIndent == 5 * h.editor.theme.column)
288 #expect(h.editor.theme.font.isFixedPitch)
289 }
290
291 @Test func styling() throws {
292 let h = Harness("** b\nbody\n")
293 let storage = try #require(h.textView.textStorage)
294 #expect(storage.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor == .clear)
295 let style = try #require(storage.attribute(.paragraphStyle, at: 6, effectiveRange: nil) as? NSParagraphStyle)
296 #expect(style.firstLineHeadIndent == 3 * h.editor.theme.column)
297 h.caret(at: 0)
298 h.textView.insertText("*", replacementRange: NSRange(location: 0, length: 0))
299 let deeper = try #require(storage.attribute(.paragraphStyle, at: 7, effectiveRange: nil) as? NSParagraphStyle)
300 #expect(deeper.firstLineHeadIndent == 4 * h.editor.theme.column)
301 }
302
303 @Test func accessibilityReadsTheWholeText() {
304 let h = Harness(outline)
305 h.caret(at: 1)
306 h.editor.cycleAtCaret()
307 #expect(h.textView.accessibilityValue() as? String == outline)
308 h.textView.setSelectedRange(NSRange(location: 0, length: 3))
309 #expect(h.textView.accessibilitySelectedText() == "* a")
310 #expect(h.textView.accessibilityLine(for: h.offset(of: "* c")) >= 1)
311 }
312
313 @Test func saveWritesAndClearsDirty() throws {
314 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
315 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
316 defer { try? FileManager.default.removeItem(at: folder) }
317 let file = folder.appendingPathComponent("a.org")
318 try Data(outline.utf8).write(to: file)
319 let h = Harness(outline)
320 h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
321 let saver = Saver(fileSystem: CoordinatedFileSystem(), recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
322 #expect(try h.editor.save(using: saver, to: file) == .saved)
323 #expect(!h.editor.document.isDirty)
324 #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
325 }
326}
327
328@MainActor
329struct BufferTests {
330 @Test func updateMapsCaretAndFoldsAndClearsUndo() {
331 let h = Harness(outline)
332 var changes = 0
333 h.editor.onChange = { changes += 1 }
334 h.caret(at: 1)
335 h.textView.insertText("x", replacementRange: NSRange(location: 4, length: 0))
336 #expect(changes == 1)
337 RunLoop.current.run(until: Date())
338 #expect(h.textView.undoManager?.canUndo == true)
339 h.editor.setFolds(FoldState(folds: [h.offset(of: "** b")]))
340 h.caret(at: h.offset(of: "* c") + 2)
341 h.editor.update { $0 = DocumentState(bytes: Array(("new\n" + outline).utf8)) }
342 #expect(changes == 2)
343 #expect(h.string == "new\n" + outline)
344 #expect(h.caret == h.offset(of: "* c") + 2)
345 #expect(h.editor.foldState.folds == [h.offset(of: "** b")])
346 #expect(h.textView.undoManager?.canUndo != true)
347 h.checkInSync()
348 }
349
350 /// Shorter text, as archiving a subtree leaves it: reloading puts the caret at the new
351 /// end, inside the old range of the fold after the removed subtree.
352 @Test func updateRemovingTextBeforeAFold() {
353 let h = Harness("* a\n* b\n* c\nlong body\n")
354 h.editor.setFolds(FoldState(folds: [h.offset(of: "* c")]))
355 h.caret(at: h.offset(of: "* b"))
356 h.editor.update { $0 = DocumentState(bytes: Array("* a\n* c\nlong body\n".utf8)) }
357 #expect(h.string == "* a\n* c\nlong body\n")
358 #expect(h.caret == h.offset(of: "* c"))
359 #expect(h.editor.foldState.folds == [h.offset(of: "* c")])
360 h.checkInSync()
361 }
362
363 /// Each buffer's editor reports its own changes: a background buffer's edit saves its
364 /// file, not the shown one's.
365 @Test func backgroundEditorsSaveTheirOwnFiles() async throws {
366 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
367 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
368 defer { try? FileManager.default.removeItem(at: folder) }
369 let a = folder.appendingPathComponent("a.org"), b = folder.appendingPathComponent("b.org")
370 try Data("* A\n".utf8).write(to: a)
371 try Data("* B\n".utf8).write(to: b)
372 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
373 session.autosaveDelay = .milliseconds(10)
374 var harnesses: [String: Harness] = [:]
375 for file in [a, b] {
376 session.open(file.path)
377 let h = Harness(try #require(session.document))
378 let path = file.path
379 h.editor.onChange = { [weak session] in session?.bufferChanged(path) }
380 session.attach(h.editor)
381 harnesses[path] = h
382 }
383 #expect(session.path == b.path)
384 harnesses[a.path]!.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
385 #expect(session.dirtyPaths == [a.path])
386 #expect(!session.isDirty)
387 for _ in 0..<50 where (try? String(contentsOf: a, encoding: .utf8)) != "x* A\n" {
388 try await Task.sleep(for: .milliseconds(20))
389 }
390 #expect(try String(contentsOf: a, encoding: .utf8) == "x* A\n")
391 }
392
393 /// The wiring the app uses: the editor is the session's buffer and reports typing.
394 @Test func sessionSavesWhatIsTyped() async throws {
395 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
396 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
397 defer { try? FileManager.default.removeItem(at: folder) }
398 let file = folder.appendingPathComponent("a.org")
399 try Data(outline.utf8).write(to: file)
400 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
401 session.autosaveDelay = .milliseconds(10)
402 session.open(file.path)
403 let h = Harness(try #require(session.document))
404 h.editor.onChange = { [weak session] in session?.bufferChanged() }
405 session.attach(h.editor)
406 h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
407 #expect(session.isDirty)
408 await session.autosave?.value
409 #expect(!session.isDirty)
410 #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
411
412 try Data(("x" + outline + "end\n").utf8).write(to: file)
413 session.fileChanged(file.path)
414 #expect(h.string == "x" + outline + "end\n")
415 }
416}
417
418@MainActor
419struct RestyleTests {
420 func indent(_ h: Harness, at line: String) -> CGFloat? {
421 let style = h.textView.textStorage?.attribute(.paragraphStyle, at: h.offset(of: line), effectiveRange: nil) as? NSParagraphStyle
422 return style.map { $0.firstLineHeadIndent / h.editor.theme.column }
423 }
424
425 @Test func newHeadingReindentsTheLinesItTakesOver() {
426 let h = Harness("* a\none\ntwo\nthree\n")
427 h.textView.insertText("** b\n", replacementRange: NSRange(location: h.offset(of: "two"), length: 0))
428 #expect(indent(h, at: "one") == 2)
429 #expect(indent(h, at: "three") == 3)
430 h.checkInSync()
431 }
432
433 @Test func joiningAwayAHeadingReindentsItsBody() {
434 let h = Harness("* a\none\n** b\ntwo\nthree\n")
435 h.textView.insertText("", replacementRange: NSRange(location: h.offset(of: "** b") - 1, length: 1))
436 #expect(indent(h, at: "three") == 2)
437 h.checkInSync()
438 }
439
440 @Test func typingASpaceAfterAStarMakesAHeading() {
441 let h = Harness("* a\n*x\nbody\nmore\n")
442 h.textView.insertText(" ", replacementRange: NSRange(location: h.offset(of: "*x") + 1, length: 0))
443 #expect(indent(h, at: "more") == 2)
444 h.checkInSync()
445 }
446}
447
448@MainActor
449struct RestyleFuzzTests {
450 /// After each random edit, the restyled text must equal a fresh editor's full styling. Set
451 /// `ORGSTAR_RESTYLE_EDITS` and `ORGSTAR_FUZZ_SEED` for longer runs.
452 @Test func incrementalRestyleEqualsFullRestyle() throws {
453 let environment = ProcessInfo.processInfo.environment
454 var state = UInt64(environment["ORGSTAR_FUZZ_SEED"] ?? "") ?? 20261006
455 let count = Int(environment["ORGSTAR_RESTYLE_EDITS"] ?? "") ?? 300
456 func next(_ bound: Int) -> Int {
457 state = state &* 6364136223846793005 &+ 1442695040888963407
458 return Int((state >> 33) % UInt64(bound))
459 }
460 let pieces = ["* ", "** ", "*", " ", "\n", "x", "*b*", "TODO ", "- ", "| a |", "#+begin_src\n", "#+end_src\n", ":PROPERTIES:\n", ":END:\n", "[[l][d]]", "<2026-10-04 Sun>"]
461 let h = Harness("* a\nbody *b*\n** b\n- item\nmore\n* c\ntext\n")
462 for n in 0..<count {
463 let length = (h.string as NSString).length
464 let start = next(length + 1)
465 let end = min(length, start + next(4))
466 let replacement = next(3) == 0 ? "" : pieces[next(pieces.count)]
467 h.textView.insertText(replacement, replacementRange: NSRange(location: start, length: end - start))
468 let fresh = Harness(h.string)
469 let same = h.textView.textStorage!.isEqual(to: fresh.textView.textStorage!)
470 #expect(same, "edit \(n): \(start)..<\(end) \(replacement.debugDescription) -> \(h.string.debugDescription)")
471 if !same { break }
472 }
473 h.checkInSync()
474 }
475}
476
477@MainActor
478struct SourceHighlightTests {
479 struct Overlapping: CodeHighlighter {
480 func highlights(language: String, code: String) -> [(range: Range<Int>, category: SyntaxCategory)] {
481 [(5..<7, .string), (0..<7, .keyword), (2..<4, .comment)]
482 }
483 }
484
485 /// Later runs win over earlier ones, wherever they start.
486 @Test func laterHighlighterRunsWin() throws {
487 let text = "* a\n#+begin_src sh\necho hi\n#+end_src\n"
488 let editor = OrgEditor(document: DocumentState(bytes: Array(text.utf8)), highlighter: Overlapping())
489 editor.finishStyling()
490 let storage = try #require(editor.textView.textStorage)
491 let code = (text as NSString).range(of: "echo").location
492 func color(_ offset: Int) -> NSColor? { storage.attribute(.foregroundColor, at: code + offset, effectiveRange: nil) as? NSColor }
493 #expect(color(0) == color(5) && color(0) == color(4))
494 #expect(color(2) != color(0) && color(2) == color(3))
495 }
496}
497
498@MainActor
499struct InitialStylingTests {
500 @Test func stylesTheFirstScreenThenTheRest() throws {
501 let line = "* heading *bold*\nbody text\n"
502 let text = String(repeating: line, count: 4_000)
503 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
504 let length = (text as NSString).length
505 #expect(h.editor.styledUpTo >= OrgEditor.firstStyleChunk && h.editor.styledUpTo < length)
506 h.textView.insertText("x", replacementRange: NSRange(location: length - 3, length: 0))
507 h.drainStyling()
508 #expect(h.editor.styledUpTo == length + 1)
509 #expect(h.textView.textStorage!.isEqual(to: Harness(h.string).textView.textStorage!))
510 }
511
512 @Test func openingLeavesTextPastTheFirstChunkUnstyled() throws {
513 let text = String(repeating: "** heading *bold*\nbody text\n", count: 4_000)
514 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
515 let storage = try #require(h.textView.textStorage)
516 var unstyled = NSRange()
517 _ = storage.attributes(at: h.editor.styledUpTo, longestEffectiveRange: &unstyled, in: NSRange(location: 0, length: storage.length))
518 #expect(unstyled == NSRange(location: h.editor.styledUpTo, length: storage.length - h.editor.styledUpTo))
519 }
520
521 /// `#+STARTUP` display options hold in the first chunk before any background pass, and in
522 /// the rest after them.
523 @Test(arguments: [
524 "#+STARTUP: noindent\n", "#+STARTUP: noindent hidestars\n", "#+STARTUP: indent\n", "#+STARTUP: latexpreview\nInline $x^2$ here.\n",
525 "#+STARTUP: shrink\n| <3> | b |\n| long cell | c |\n", "",
526 ]) func startupDisplayAppliesToEveryChunk(head: String) throws {
527 let text = head + String(repeating: "** heading *bold*\nbody text\n", count: 4_000) + "Last $y^2$ line\n"
528 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
529 let storage = try #require(h.textView.textStorage)
530 let length = storage.length
531 // Without the preview boxes, which are made anew by each styling.
532 func styled() -> NSAttributedString {
533 let copy = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: NSRange(location: 0, length: h.editor.styledUpTo)))
534 copy.removeAttribute(.orgLatex, range: NSRange(location: 0, length: copy.length))
535 return copy
536 }
537 func check() {
538 let before = styled()
539 h.editor.restyleOutsideEditing(0..<h.editor.styledUpTo)
540 #expect(styled().isEqual(to: before))
541 }
542 #expect(h.editor.styledUpTo < length)
543 check()
544 h.drainStyling()
545 #expect(h.editor.styledUpTo == length)
546 check()
547
548 let ns = text as NSString
549 for needle in ["$x^2$", "$y^2$"] where head.contains("latexpreview") {
550 #expect(storage.attribute(.orgLatex, at: ns.range(of: needle).location, effectiveRange: nil) != nil)
551 }
552 for needle in [ns.range(of: "** heading"), ns.range(of: "** heading", options: .backwards)] {
553 let stars = storage.attribute(.foregroundColor, at: needle.location, effectiveRange: nil) as? NSColor
554 #expect((stars == .clear) == !head.contains("noindent\n"))
555 let body = storage.attribute(.paragraphStyle, at: NSMaxRange(ns.lineRange(for: needle)), effectiveRange: nil) as? NSParagraphStyle
556 #expect((body?.firstLineHeadIndent == 0) == head.contains("noindent"))
557 }
558 }
559
560 @Test func editsBeforeTheWatermarkShiftIt() {
561 let text = String(repeating: "line of text\n", count: 5_000)
562 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
563 let before = h.editor.styledUpTo
564 h.textView.insertText("abc", replacementRange: NSRange(location: 0, length: 0))
565 #expect(h.editor.styledUpTo == before + 3)
566 }
567}
568
569@MainActor
570struct CommandTests {
571 @Test func performEditsThroughTheTextView() {
572 let h = Harness("* a :t:\nbody\n")
573 var messages: [String] = []
574 h.editor.onMessage = { messages.append($0) }
575 h.caret(at: 2)
576 h.editor.perform(PriorityUp())
577 #expect(h.string.hasPrefix("* [#B] a "))
578 #expect(h.caret == 2)
579 h.checkInSync()
580 // Undo groups by event: let the run loop close the first command's group, as a key
581 // press would.
582 RunLoop.current.run(until: Date())
583 h.editor.perform(TodoCycle())
584 #expect(h.string.hasPrefix("* TODO [#B] a "))
585 RunLoop.current.run(until: Date())
586 h.textView.undoManager?.undo()
587 #expect(h.string.hasPrefix("* [#B] a "))
588 h.checkInSync()
589 h.caret(at: h.offset(of: "body"))
590 h.editor.perform(PromoteHeading())
591 #expect(messages == ["Not on a heading"])
592 }
593
594 @Test func readOnlyEditorsRefuseEdits() {
595 let editor = OrgEditor(document: DocumentState(bytes: Array("* a\n".utf8)), editable: false)
596 editor.textView.setSelectedRange(NSRange(location: 2, length: 0))
597 #expect(editor.perform(TodoCycle()) == .failed("read-only"))
598 #expect(editor.document.text == "* a\n")
599 }
600}