Tests/OrgCoreTests/ReplaceTests.swift

0dc8dea033dd64cad6c9b4130124d1c229454342
orgstar/Tests/OrgCoreTests/ReplaceTests.swift

255 lines · 13320 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5/// Replace in Files' matching and case rules, and the structural renames of tags and TODO
  6/// keywords, against Emacs where Org has the behaviour.
  7struct ReplaceTests {
  8    static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
  9
 10    func replaced(_ text: String, _ query: TextReplace, skipping: [Range<Int>] = []) throws -> String {
 11        ProposedChange.apply(try query.changes(in: text, skipping: skipping), to: text)
 12    }
 13
 14    /// An Emacs Lisp string literal.
 15    static func lisp(_ s: String) -> String {
 16        "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
 17    }
 18
 19    @Test func plainText() throws {
 20        let query = TextReplace(pattern: "a.b", replacement: "$1\\1")
 21        #expect(try replaced("a.b axb\n", query) == "$1\\1 axb\n")
 22    }
 23
 24    @Test func regexpWithGroups() throws {
 25        let query = TextReplace(pattern: "(\\w+)@(\\w+)", replacement: "\\2 at $1 (\\&)", isRegexp: true, caseFold: false)
 26        #expect(try replaced("me@home\n", query) == "home at me (me@home)\n")
 27    }
 28
 29    @Test func linesAnchor() throws {
 30        let query = TextReplace(pattern: "^- ", replacement: "+ ", isRegexp: true)
 31        #expect(try replaced("- a\n- b\nx - c\n", query) == "+ a\n+ b\nx - c\n")
 32    }
 33
 34    @Test func caseRules() throws {
 35        // case-fold-search off: only the exact case matches, and nothing is casified.
 36        #expect(try replaced("foo Foo", TextReplace(pattern: "foo", replacement: "bar", caseFold: false)) == "bar Foo")
 37        // An upper-case letter in the pattern turns folding off.
 38        #expect(try replaced("foo Foo", TextReplace(pattern: "Foo", replacement: "bar")) == "foo bar")
 39        // case-replace off: matches fold, the replacement stays as written.
 40        #expect(try replaced("foo Foo FOO", TextReplace(pattern: "foo", replacement: "bar", caseReplace: false)) == "bar bar bar")
 41        // A letter after a backslash isn't upper case for folding.
 42        #expect(TextReplace(pattern: "\\Wfoo", replacement: "", isRegexp: true).foldsCase)
 43        #expect(!TextReplace(pattern: "\\WFoo", replacement: "", isRegexp: true).foldsCase)
 44    }
 45
 46    @Test func invalidPatterns() {
 47        #expect(throws: TextReplace.InvalidPattern.empty) { try TextReplace(pattern: "", replacement: "x").regex() }
 48        #expect(throws: TextReplace.InvalidPattern.invalid) { try TextReplace(pattern: "(", replacement: "x", isRegexp: true).regex() }
 49    }
 50
 51    @Test func changesDescribeTheirLines() throws {
 52        let changes = try TextReplace(pattern: "cat", replacement: "dog").changes(in: "a\nthe cat sat\non a cat\n")
 53        #expect(changes.map(\.line) == [2, 3])
 54        #expect(changes[0].lineText == "the cat sat")
 55        #expect(changes[0].changed == 4..<7)
 56        #expect(changes[1].replacement == "dog")
 57    }
 58
 59    @Test func encryptedEntriesAreSkipped() throws {
 60        let text = """
 61        * Secrets :crypt:
 62        -----BEGIN PGP MESSAGE-----
 63
 64        jA0ECQMCsecret
 65        -----END PGP MESSAGE-----
 66        * Open
 67        secret
 68        ** Child :crypt:
 69        -----BEGIN PGP MESSAGE-----
 70        secret
 71        -----END PGP MESSAGE-----
 72        * Not tagged
 73        -----BEGIN PGP MESSAGE-----
 74        secret
 75        -----END PGP MESSAGE-----
 76
 77        """
 78        let ranges = EncryptedText.ranges(in: text)
 79        #expect(ranges.count == 2)
 80        let changes = try TextReplace(pattern: "secret", replacement: "x").changes(in: text, skipping: ranges)
 81        // The tagged heading's title isn't encrypted.
 82        #expect(changes.map(\.line) == [1, 7, 14])
 83        #expect(EncryptedText.isEncryptedFile("/a/notes.org.gpg"))
 84        #expect(!EncryptedText.isEncryptedFile("/a/notes.org"))
 85    }
 86
 87    /// The same replacements through `perform-replace` with `case-fold-search` and
 88    /// `case-replace` on: (text, Emacs pattern, ICU pattern, replacement, regexp).
 89    static let replaceCases: [(String, String, String, String, Bool)] = [
 90        ("foo Foo FOO fOo\n", "foo", "foo", "bar", false),
 91        ("Foo foo\n", "Foo", "Foo", "bar", false),
 92        ("a A x\n", "a", "a", "bc", false),
 93        ("foo Foo FOO\n", "foo", "foo", "Bar baz", false),
 94        ("1foo 1Foo\n", "1foo", "1foo", "bar", false),
 95        ("Foo bar\nFoo Bar\n", "foo bar", "foo bar", "qux quux", false),
 96        ("foo-bar Foo-Bar FOO-BAR\n", "foo-\\(bar\\)", "foo-(bar)", "x-\\1", true),
 97        ("John Smith\njane doe\n", "\\([a-z]+\\) \\([a-z]+\\)", "([a-z]+) ([a-z]+)", "\\2, \\1", true),
 98        ("* TODO a\n* b\n", "^\\* ", "^\\* ", "- ", true),
 99        ("Émile émile ÉMILE\n", "émile", "émile", "zoé", false),
100    ]
101
102    @Test(.enabled(if: oracle)) func replaceMatchesEmacs() throws {
103        for (text, emacsPattern, pattern, replacement, regexp) in Self.replaceCases {
104            let form = "(progn (goto-char (point-min)) (let ((case-fold-search t) (case-replace t)) (perform-replace \(Self.lisp(emacsPattern)) \(Self.lisp(replacement)) nil \(regexp ? "t" : "nil") nil)) (list (buffer-string)))"
105            let emacs = try EmacsOracle.evaluate(text, form)
106            let ours = try replaced(text, TextReplace(pattern: pattern, replacement: replacement, isRegexp: regexp))
107            #expect([ours] == emacs, "\(emacsPattern) -> \(replacement) in \(text)")
108        }
109    }
110
111    // MARK: - Tags
112
113    static let tagged = """
114    #+TAGS: work(w) home { @office : work errand } urgent
115    #+FILETAGS: :work:notes:
116    * Plan                                                                 :work:
117    ** TODO Call the boss                                           :work:urgent:
118    * A heading whose title is long enough to push its tags past the tag column :work:
119    * Unaligned :home:work:
120    * See [[https://example.com][the site]]                               :work:
121    * Coffee ☕ break :work:
122    * Untagged
123    Body text says work and :work: and is left alone.
124    #+begin_example
125    #+TAGS: work
126    #+end_example
127
128    """
129
130    func renameTag(_ text: String, _ old: String, _ new: String) -> String {
131        let tree = OrgParser.parse(text)
132        return ProposedChange.apply(TagRename.changes(in: text, tree: tree, from: old, to: new, options: .org), to: text)
133    }
134
135    @Test func tagRenameChangesOnlyTags() {
136        let renamed = renameTag(Self.tagged, "work", "office")
137        #expect(renamed.contains("#+TAGS: office(w) home { @office : office errand } urgent\n"))
138        #expect(renamed.contains("#+FILETAGS: :office:notes:\n"))
139        #expect(renamed.contains("Body text says work and :work: and is left alone."))
140        #expect(renamed.contains("#+begin_example\n#+TAGS: work\n"))
141        #expect(renamed.components(separatedBy: ":work:").count == 2)
142        // The list shows whole tag lists and words, not the realigning spaces.
143        let changes = TagRename.changes(in: Self.tagged, tree: OrgParser.parse(Self.tagged), from: "work", to: "office", options: .org)
144        let shown = changes.map { ($0.lineText as NSString).substring(with: NSRange($0.changed)) + " -> " + $0.replacement }
145        #expect(shown[0] == "work(w) home { @office : work -> office(w) home { @office : office")
146        #expect(shown[1] == ":work:notes: -> :office:notes:")
147        #expect(shown[3] == ":work:urgent: -> :office:urgent:")
148    }
149
150    @Test func tagRenameMerges() {
151        let renamed = renameTag(Self.tagged, "work", "home")
152        #expect(renamed.contains("#+TAGS: home { @office : errand } urgent\n"))
153        #expect(renamed.contains("#+FILETAGS: :home:notes:\n"))
154        #expect(renamed.contains("* Unaligned") && renamed.contains(":home:\n* See"))
155        #expect(TagRename.renamedTagAlist("a(a) b\nc", from: "a", to: "c") == "c(a) b\nc")
156        #expect(TagRename.renamedTagAlist("a b c", from: "b", to: "a") == "a c")
157        #expect(TagRename.renamedTagAlist("x y", from: "a", to: "b") == nil)
158        #expect(TagRename.renamedFileTagsValue(" a b", from: "b", to: "a") == " a")
159        #expect(TagRename.renamedFileTagsValue(" :b:a:", from: "b", to: "a") == " :a:")
160    }
161
162    /// Org's `org-set-tags` on every heading with the tag, as Rename Tag aligns them.
163    @Test(.enabled(if: oracle)) func tagRenameAlignsAsOrg() throws {
164        let headings = Self.tagged.components(separatedBy: "\n").filter { $0.hasPrefix("*") }.joined(separator: "\n") + "\n"
165        for (old, new) in [("work", "office"), ("work", "home"), ("work", "a-very-long-tag-name".replacingOccurrences(of: "-", with: "_")), ("urgent", "u")] {
166            let form = """
167            (progn (setq org-tags-column -77) (font-lock-ensure)
168              (org-map-entries (lambda () (let ((tags (org-get-tags nil t)))
169                (when (member \(Self.lisp(old)) tags)
170                  (org-set-tags (delete-dups (mapcar (lambda (tg) (if (equal tg \(Self.lisp(old))) \(Self.lisp(new)) tg)) tags)))))))
171              (list (buffer-string)))
172            """
173            let emacs = try EmacsOracle.evaluate(headings, form)
174            #expect([renameTag(headings, old, new)] == emacs, "\(old) -> \(new)")
175        }
176    }
177
178    // MARK: - TODO keywords
179
180    /// A heading line with its tags ending at column 77, as `org-tags-column` -77 puts them.
181    static func aligned(_ title: String, _ tags: String) -> String {
182        title + String(repeating: " ", count: max(1, 77 - title.count - tags.count)) + tags
183    }
184
185    static let keyworded = """
186    #+TODO: TODO NEXT(n!) | DONE(d)
187    #+TYP_TODO: Fred Sara | FINISHED
188    \(aligned("* NEXT Call the boss", ":work:"))
189    \(aligned("** NEXT A longer title so that the tags move", ":work:urgent:"))
190    * TODO Write
191    NEXT time, NEXT is body text.
192    * DONE Filed
193    \(aligned("* Sara Review", ":team:"))
194
195    """
196
197    func renameKeyword(_ text: String, _ old: String, _ new: String) -> String {
198        let tree = OrgParser.parse(text)
199        return ProposedChange.apply(KeywordRename.changes(in: text, tree: tree, from: old, to: new, headings: true, options: .org), to: text)
200    }
201
202    @Test func keywordRenameChangesOnlyKeywords() {
203        let renamed = renameKeyword(Self.keyworded, "NEXT", "WAITING")
204        #expect(renamed.contains("#+TODO: TODO WAITING(n!) | DONE(d)\n"))
205        #expect(renamed.contains("NEXT time, NEXT is body text."))
206        #expect(renamed.contains("* WAITING Call the boss"))
207        #expect(OrgParser.parse(renamed).settings.todoKeywordNames.contains("WAITING"))
208    }
209
210    @Test func keywordRenameMergesAndRefuses() {
211        let merged = renameKeyword(Self.keyworded, "NEXT", "TODO")
212        #expect(merged.contains("#+TODO: TODO | DONE(d)\n"))
213        #expect(merged.contains("* TODO Call the boss"))
214        let settings = OrgParser.parse(Self.keyworded).settings
215        #expect(KeywordRename.crossesStates(settings, from: "NEXT", to: "DONE"))
216        #expect(KeywordRename.crossesStates(settings, from: "FINISHED", to: "Sara"))
217        #expect(!KeywordRename.crossesStates(settings, from: "NEXT", to: "TODO"))
218        #expect(!KeywordRename.crossesStates(settings, from: "NEXT", to: "LATER"))
219        #expect(!KeywordRename.isValidName("A B") && !KeywordRename.isValidName("A(b)") && !KeywordRename.isValidName("|"))
220        #expect(KeywordRename.renamedTodoKeywords("TODO NEXT | DONE\nA B", from: "NEXT", to: "WAIT") == "TODO WAIT | DONE\nA B")
221    }
222
223    @Test func keywordSources() {
224        let tree = OrgParser.parse(Self.keyworded)
225        #expect(KeywordRename.source(of: "NEXT", in: tree) == .file)
226        #expect(KeywordRename.source(of: "LATER", in: tree) == .none)
227        var defaults = OrgSettings.default.withTodoKeywords("TODO LATER | DONE")!
228        #expect(KeywordRename.source(of: "LATER", in: OrgParser.parse("* LATER x\n", defaults: defaults)) == .defaults)
229        defaults.setupKeywords = "#+TODO: TODO SOON | DONE\n"
230        #expect(KeywordRename.source(of: "SOON", in: OrgParser.parse("* SOON x\n", defaults: defaults)) == .setupFile)
231        // Without headings, only the keyword lines change.
232        let lines = KeywordRename.changes(in: Self.keyworded, tree: tree, from: "NEXT", to: "WAITING", headings: false, options: .org)
233        #expect(lines.map(\.line) == [1])
234    }
235
236    /// After a rename, Org reads the headings with the new keyword, and its tags stay where
237    /// `org-align-tags` puts them.
238    @Test(.enabled(if: oracle)) func keywordRenameParsesInOrg() throws {
239        for (old, new) in [("NEXT", "WAITING"), ("NEXT", "N"), ("Sara", "Alexandra"), ("TODO", "NEXT")] {
240            let renamed = renameKeyword(Self.keyworded, old, new)
241            let form = """
242            (progn (setq org-tags-column -77) (font-lock-ensure)
243              (let ((states (org-map-entries (lambda () (or (org-get-todo-state) "")))))
244                (org-align-tags t)
245                (cons (buffer-string) states)))
246            """
247            let emacs = try EmacsOracle.evaluate(renamed, form)
248            #expect(emacs.first == renamed, "\(old) -> \(new): alignment")
249            let tree = OrgParser.parse(renamed)
250            let ours = tree.root.descendants().filter { $0.kind == .heading }.map { $0.tokens.first { $0.kind == .todoKeyword }?.text ?? "" }
251            #expect(Array(emacs.dropFirst()) == ours, "\(old) -> \(new): keywords")
252            #expect(ours.contains(new))
253        }
254    }
255}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form