Sources/OrgCore/Replace/StructuralRename.swift
209 lines · 12416 bytes
22 symbols in this file
1import Foundation
2
3/// Rename Tag: a tag renamed in heading tag lists, realigned as `org-set-tags` leaves them, and
4/// in `#+TAGS` and `#+FILETAGS` lines; never in other text. A name already there merges.
5public enum TagRename {
6 /// Characters a tag can hold (`org-tag-re`).
7 public static func isValidName(_ name: String) -> Bool {
8 !name.isEmpty && name.allSatisfy { $0.isLetter || $0.isNumber || "_@#%".contains($0) }
9 }
10
11 public static func changes(in text: String, tree: OrgTree, from old: String, to new: String, options: EditingOptions, skipping: [Range<Int>] = []) -> [ProposedChange] {
12 let ns = text as NSString
13 let lines = LineStarts(ns)
14 var edits: [(edit: TextEdit, shown: TextEdit)] = []
15 for node in tree.root.descendants() {
16 switch node.kind {
17 case .heading:
18 guard let token = node.tokens.first(where: { $0.kind == .tags }) else { continue }
19 let tags = token.text.split(separator: ":").map(String.init)
20 guard tags.contains(old) else { continue }
21 var renamed: [String] = []
22 for tag in tags.map({ $0 == old ? new : $0 }) where !renamed.contains(tag) { renamed.append(tag) }
23 let content = lines.content(ofLine: lines.line(of: node.range.lowerBound))
24 let line = ns.substring(with: NSRange(content))
25 let buffer = EmacsBuffer(line, point: 0, settings: tree.settings, options: options)
26 guard (try? SetTags.set(renamed, in: buffer)) != nil else { continue }
27 if let edit = LineStarts.edit(lineStart: content.lowerBound, from: line, to: buffer.string) {
28 edits.append((edit, TextEdit(range: token.range, replacement: renamed.isEmpty ? "" : ":" + renamed.joined(separator: ":") + ":")))
29 }
30 case .keyword:
31 guard let (key, content, line) = keywordLine(node, lines) else { continue }
32 let value = key.value
33 let renamed: String? = switch key.name {
34 case "TAGS": renamedTagsValue(String(line[value]), from: old, to: new)
35 case "FILETAGS": renamedFileTagsValue(String(line[value]), from: old, to: new)
36 default: nil
37 }
38 guard let renamed else { continue }
39 let newLine = String(line[..<value.lowerBound]) + renamed
40 if let edit = LineStarts.edit(lineStart: content.lowerBound, from: line, to: newLine) { edits.append((edit, lines.wholeWords(edit))) }
41 default:
42 break
43 }
44 }
45 return edits.filter { !EncryptedText.overlaps($0.edit.range, skipping) }.enumerated().map { lines.change(id: $0.offset, $0.element.edit, shown: $0.element.shown) }
46 }
47
48 /// Lines of `org-tag-alist` in `#+TAGS` syntax with `old` renamed; nil when none names it.
49 public static func renamedTagAlist(_ alist: String, from old: String, to new: String) -> String? {
50 renamedLines(alist) { renamedTagsValue($0, from: old, to: new) }
51 }
52
53 /// A `#+TAGS` value with the tag `old` renamed, keeping its fast-selection key, or removed
54 /// when `new` is there already; nil when it doesn't name `old`.
55 static func renamedTagsValue(_ value: String, from old: String, to new: String) -> String? {
56 let name = "[\\p{L}\\p{N}_@#%"
57 func token(_ tag: String) -> String { "(?<!\(name)(])" + NSRegularExpression.escapedPattern(for: tag) + "(?!\(name)])" }
58 return renamedValue(value, old: token(old), new: token(new), key: "(?:\\([^)]*\\))?", separators: "\\s", replacement: new)
59 }
60
61 /// A `#+FILETAGS` value (`:a:b:` or `a b`) with `old` renamed, or removed when `new` is
62 /// there already; nil when it doesn't name `old`.
63 static func renamedFileTagsValue(_ value: String, from old: String, to new: String) -> String? {
64 func token(_ tag: String) -> String { "(?<![^\\s:])" + NSRegularExpression.escapedPattern(for: tag) + "(?![^\\s:])" }
65 return renamedValue(value, old: token(old), new: token(new), key: "", separators: "[\\s:]", replacement: new)
66 }
67}
68
69/// Rename TODO Keyword: a keyword renamed where it is a keyword, in heading keyword position
70/// and in `#+TODO`, `#+SEQ_TODO` and `#+TYP_TODO` lines, with the heading's tags realigned;
71/// never in other text. A name already there merges; a rename across done and not-done states
72/// is refused.
73public enum KeywordRename {
74 /// A keyword is a word without parentheses or a bar, which `#+TODO` syntax gives meaning.
75 public static func isValidName(_ name: String) -> Bool {
76 !name.isEmpty && name != "|" && !name.contains { $0.isWhitespace || $0 == "(" || $0 == ")" }
77 }
78
79 /// Whether `old` and `new` are both keywords under `settings`, one a done state and the
80 /// other not.
81 public static func crossesStates(_ settings: OrgSettings, from old: String, to new: String) -> Bool {
82 let names = settings.todoKeywordNames
83 return names.contains(old) && names.contains(new) && settings.isDone(old) != settings.isDone(new)
84 }
85
86 /// Where a file's keyword is defined.
87 public enum Source: Sendable, Equatable {
88 /// The file's own `#+TODO` lines.
89 case file
90 /// A `#+SETUPFILE` it names.
91 case setupFile
92 /// No TODO lines: the keywords for files without them (`org-todo-keywords`).
93 case defaults
94 /// It isn't a keyword in the file.
95 case none
96 }
97
98 public static func source(of keyword: String, in tree: OrgTree) -> Source {
99 let keys: Set<String> = ["TODO", "SEQ_TODO", "TYP_TODO"]
100 func names(_ value: Substring) -> [String] { SettingsScanner.todoSequence(value, kind: .sequence).map { ($0.active + $0.done).map(\.name) } ?? [] }
101 let text = tree.text as NSString
102 let lines = LineStarts(text)
103 for node in tree.root.descendants() where node.kind == .keyword {
104 guard let (key, _, line) = keywordLine(node, lines), keys.contains(key.name) else { continue }
105 if names(line[key.value]).contains(keyword) { return .file }
106 }
107 for (key, value) in SetupFile.keywords(tree.settings.setupKeywords) where keys.contains(key) && names(value).contains(keyword) {
108 return .setupFile
109 }
110 return tree.settings.todoKeywordNames.contains(keyword) ? .defaults : .none
111 }
112
113 /// The changes renaming `old` to `new` in `text`: the TODO keyword lines, and with
114 /// `headings` the headings' keywords.
115 public static func changes(in text: String, tree: OrgTree, from old: String, to new: String, headings: Bool, options: EditingOptions, skipping: [Range<Int>] = []) -> [ProposedChange] {
116 let ns = text as NSString
117 let lines = LineStarts(ns)
118 var edits: [(edit: TextEdit, shown: TextEdit)] = []
119 for node in tree.root.descendants() {
120 switch node.kind {
121 case .heading where headings:
122 guard let token = node.tokens.first(where: { $0.kind == .todoKeyword }), token.text == old else { continue }
123 let content = lines.content(ofLine: lines.line(of: node.range.lowerBound))
124 let line = ns.substring(with: NSRange(content))
125 let at = NSRange(location: token.range.lowerBound - content.lowerBound, length: token.range.count)
126 var buffer = LineBuffer((line as NSString).replacingCharacters(in: at, with: new), caret: nil)
127 // `org-todo` realigns the tags after the keyword changed the title's width.
128 if node.tokens.contains(where: { $0.kind == .tags }) { alignTags(&buffer, options: options) }
129 if let edit = LineStarts.edit(lineStart: content.lowerBound, from: line, to: buffer.string) {
130 edits.append((edit, TextEdit(range: token.range, replacement: new)))
131 }
132 case .keyword:
133 guard let (key, content, line) = keywordLine(node, lines), ["TODO", "SEQ_TODO", "TYP_TODO"].contains(key.name),
134 let renamed = renamedTodoValue(String(line[key.value]), from: old, to: new) else { continue }
135 let newLine = String(line[..<key.value.lowerBound]) + renamed
136 if let edit = LineStarts.edit(lineStart: content.lowerBound, from: line, to: newLine) { edits.append((edit, lines.wholeWords(edit))) }
137 default:
138 break
139 }
140 }
141 return edits.filter { !EncryptedText.overlaps($0.edit.range, skipping) }.enumerated().map { lines.change(id: $0.offset, $0.element.edit, shown: $0.element.shown) }
142 }
143
144 /// `org-todo-keywords` in `#+TODO` syntax, a sequence a line, with `old` renamed; nil when
145 /// none names it.
146 public static func renamedTodoKeywords(_ lines: String, from old: String, to new: String) -> String? {
147 renamedLines(lines) { renamedTodoValue($0, from: old, to: new) }
148 }
149
150 /// A `#+TODO` value with the keyword `old` renamed, keeping its key and logging flags, or
151 /// removed when `new` is there already; nil when it doesn't name `old`.
152 static func renamedTodoValue(_ value: String, from old: String, to new: String) -> String? {
153 func token(_ name: String) -> String { "(?<!\\S)" + NSRegularExpression.escapedPattern(for: name) + "(?=\\(|\\s|$)" }
154 return renamedValue(value, old: token(old), new: token(new), key: "(?:\\([^)]*\\))?", separators: "\\s", replacement: new)
155 }
156}
157
158/// A keyword line's name, upper-cased, and where its value starts in the line.
159struct KeywordLine {
160 let name: String
161 let value: Range<String.Index>
162}
163
164/// The keyword node's line, its range in the text, and its name and value.
165func keywordLine(_ node: SyntaxNode, _ lines: LineStarts) -> (KeywordLine, Range<Int>, String)? {
166 let content = lines.content(ofLine: lines.line(of: node.range.lowerBound))
167 let line = lines.text.substring(with: NSRange(content))
168 guard let match = line.firstMatch(of: /^[ \t]*#\+([^:\s]+):/) else { return nil }
169 return (KeywordLine(name: match.1.uppercased(), value: match.range.upperBound..<line.endIndex), content, line)
170}
171
172/// `value` with the token `old` (a pattern) and its `key` suffix renamed to `replacement`, or,
173/// when the token `new` is in it too, removed with the separators on one side of it. Nil when
174/// `old` isn't in it.
175private func renamedValue(_ value: String, old: String, new: String, key: String, separators: String, replacement: String) -> String? {
176 guard let oldRegex = try? NSRegularExpression(pattern: old), let newRegex = try? NSRegularExpression(pattern: new) else { return nil }
177 let ns = value as NSString
178 let whole = NSRange(location: 0, length: ns.length)
179 guard oldRegex.firstMatch(in: value, range: whole) != nil else { return nil }
180 if newRegex.firstMatch(in: value, range: whole) == nil {
181 return oldRegex.stringByReplacingMatches(in: value, range: whole, withTemplate: NSRegularExpression.escapedTemplate(for: replacement))
182 }
183 // Merging: the separators after the token go with it, else those before it.
184 guard let withKey = try? NSRegularExpression(pattern: "(" + old + key + ")(" + separators + "+)?") else { return nil }
185 var result = value
186 while let match = withKey.firstMatch(in: result, range: NSRange(location: 0, length: (result as NSString).length)) {
187 var range = match.range
188 if match.range(at: 2).location == NSNotFound {
189 let text = result as NSString
190 var start = range.location
191 while start > 0, let scalar = Unicode.Scalar(text.character(at: start - 1)),
192 String(scalar).range(of: "^" + separators + "$", options: .regularExpression) != nil { start -= 1 }
193 range = NSRange(location: start, length: NSMaxRange(range) - start)
194 }
195 result = (result as NSString).replacingCharacters(in: range, with: "")
196 }
197 return result
198}
199
200/// `text`'s lines, each through `rename`; nil when it renamed none.
201private func renamedLines(_ text: String, _ rename: (String) -> String?) -> String? {
202 var changed = false
203 let lines = text.components(separatedBy: "\n").map { line -> String in
204 guard let renamed = rename(line) else { return line }
205 changed = true
206 return renamed
207 }
208 return changed ? lines.joined(separator: "\n") : nil
209}