Tests/OrgCoreTests/BlockCommandTests.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Tests/OrgCoreTests/BlockCommandTests.swift history · blame · raw

128 lines · 6970 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct BlockCommandTests {
  6    static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
  7
  8    static let text = """
  9        * Heading
 10        Some text here.
 11          Indented line
 12        * Starred
 13        #+keyword
 14        last
 15        """
 16
 17    @Test(.enabled(if: oracle))
 18    func insertsTemplatesLikeOrg() throws {
 19        let ns = Self.text as NSString
 20        let points = [ns.range(of: "Some").location, ns.range(of: "text").location, ns.range(of: "Indented").location, ns.length]
 21        let regions = [("Some", "here."), ("Indented", "#+keyword"), ("Some", "line\n")]
 22        let types = ["src", "quote", "EXAMPLE", "export html", "verse"]
 23        var cases: [EmacsOracle.Case] = []
 24        var ours: [(String, Int)] = []
 25        for type in types {
 26            for offset in points {
 27                cases.append(EmacsOracle.Case(text: Self.text, point: EmacsOracle.point(offset, in: Self.text), form: "(org-insert-structure-template \(lispString(type)))"))
 28                ours.append(Self.run(type, offset..<offset))
 29            }
 30            for (from, to) in regions {
 31                let start = ns.range(of: from).location
 32                let end = NSMaxRange(ns.range(of: to))
 33                cases.append(EmacsOracle.Case(text: Self.text, point: EmacsOracle.point(end, in: Self.text), form: "(progn (transient-mark-mode 1) (set-mark \(EmacsOracle.point(start, in: Self.text))) (activate-mark) (org-insert-structure-template \(lispString(type))))"))
 34                ours.append(Self.run(type, start..<end))
 35            }
 36        }
 37        for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() {
 38            #expect(mine.0 == theirs.text, "\(cases[i].form)\nours:  \(mine.0.debugDescription)\nemacs: \(theirs.text.debugDescription)")
 39            if mine.0 == theirs.text { #expect(mine.1 == EmacsOracle.offset(theirs.point, in: theirs.text), "\(cases[i].form) caret") }
 40        }
 41    }
 42
 43    static func run(_ type: String, _ selection: Range<Int>) -> (String, Int) {
 44        let key = StructureTemplate.defaults.first { $0.type == type }?.key ?? "\t"
 45        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection], answers: ["template": key, "type": type])
 46        guard case .commit(let result) = InsertStructureTemplate().run(in: context) else { return (text, 0) }
 47        var new = text
 48        for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) }
 49        return (new, result.selection?.first?.lowerBound ?? 0)
 50    }
 51
 52    /// Keys of two letters take a second stroke; Tab picks the one-letter key of the same letter.
 53    @Test func configuredTemplatesTakeTwoStrokes() throws {
 54        var options = EditingOptions.org
 55        options.structureTemplates = StructureTemplate.merged([.init(key: "el", type: "src emacs-lisp"), .init(key: "q", type: "QUOTE")])
 56        func step(_ answers: [String: String]) -> CommandStep {
 57            InsertStructureTemplate().run(in: EditContext(revision: 0, text: "x\n", tree: OrgParser.parse("x\n"), selection: [0..<0], answers: answers, options: options))
 58        }
 59        guard case .prompt(let top) = step([:]) else { Issue.record("no prompt"); return }
 60        #expect(top.fast?.items.contains(.option(key: "e", name: "example, src emacs-lisp")) == true)
 61        #expect(top.fast?.items.contains(.option(key: "q", name: "QUOTE")) == true)
 62        guard case .prompt(let second) = step(["template": "e"]) else { Issue.record("no second prompt"); return }
 63        #expect(second.key == "template2" && second.fast?.items == [.option(key: "\t", name: "example"), .option(key: "l", name: "src emacs-lisp")])
 64        guard case .commit(let result) = step(["template": "e", "template2": "l"]) else { Issue.record("no commit"); return }
 65        #expect(result.edits.reduce("x\n") { $1.apply(to: $0) } == "#+begin_src emacs-lisp\n#+end_src\nx\n")
 66        guard case .commit(let quote) = step(["template": "q"]) else { Issue.record("no commit"); return }
 67        #expect(quote.edits.reduce("x\n") { $1.apply(to: $0) }.hasPrefix("#+BEGIN_QUOTE\n"))
 68    }
 69
 70    /// `org--insert-structure-template-unique-keys`.
 71    @Test(.enabled(if: oracle))
 72    func secondKeysLikeOrg() throws {
 73        let sets = [["e", "el"], ["e", "el", "elisp", "ex"], ["py", "pl", "p"], ["abc", "abd", "ab"]]
 74        for keys in sets {
 75            let ours = InsertStructureTemplate.secondKeys(keys.map { StructureTemplate(key: $0, type: "x") })
 76                .map { zip(keys, $0).map { String($0.first!) + String($1) } }
 77            let form = "(list (mapconcat #'identity (org--insert-structure-template-unique-keys '(\(keys.map { lispString($0) }.joined(separator: " ")))) \"|\"))"
 78            let theirs = try EmacsOracle.evaluate("", form)
 79            #expect(ours?.joined(separator: "|") == theirs.first, "\(keys)")
 80        }
 81    }
 82
 83    static let blocks = """
 84        * Code
 85        #+begin_src python :results output
 86        def f():
 87            return 1
 88        ,* not a heading
 89        ,#+not a keyword
 90        #+end_src
 91        #+begin_example
 92          indented
 93        #+end_example
 94        #+begin_src sh
 95        #+end_src
 96        """
 97
 98    @Test(.enabled(if: oracle))
 99    func editsBlocksLikeOrgEditSpecial() throws {
100        let ns = Self.blocks as NSString
101        let points = [ns.range(of: "def f").location, ns.range(of: "#+begin_example").location, ns.range(of: "#+begin_src sh").location + 3]
102        let added = "* new star\n#+new keyword\nplain"
103        let forms = points.map { point in
104            """
105            (progn (erase-buffer) (insert \(lispString(Self.blocks))) (goto-char \(EmacsOracle.point(point, in: Self.blocks)))
106              (org-edit-special)
107              (let ((content (buffer-string)))
108                (goto-char (point-max)) (insert \(lispString(added)))
109                (org-edit-src-exit)
110                (format "%s|%s" content (buffer-string))))
111            """
112        }
113        let emacs = try EmacsOracle.evaluate("", "(list \(forms.joined(separator: " ")))", prelude: "(setq org-src-preserve-indentation t org-src-window-setup 'current-window)")
114        let tree = OrgParser.parse(Self.blocks)
115        for (point, expected) in zip(points, emacs) {
116            guard let edit = BlockEdit.at(point, text: Self.blocks, tree: tree) else {
117                Issue.record("no block at \(point)")
118                continue
119            }
120            let context = EditContext(revision: 0, text: Self.blocks, tree: tree, selection: [point..<point])
121            var after = Self.blocks
122            if case .commit(let result) = ReplaceBlockLines(edit: edit, content: edit.content + added).run(in: context) {
123                for e in result.edits { after = e.apply(to: after) }
124            }
125            #expect("\(edit.content)|\(after)" == expected, "at \(point)")
126        }
127    }
128}