Sources/OrgCore/Commands/Refile.swift

150 lines · 6283 bytes

  1import Foundation
  2
  3// Refiling, ported from org-refile.el and org.el (Org 9.8.7) with `org-log-refile` nil,
  4// `org-reverse-note-order` nil and `org-refile-keep` nil.
  5
  6extension EmacsBuffer {
  7    /// `org-copy-subtree` called from Lisp: the subtree at point, with the blank lines after it.
  8    func copySubtree() throws -> String {
  9        try saveExcursion {
 10            let begin = try backToHeading()
 11            skipForward(Self.whitespace)
 12            endOfSubtree(toHeading: true)
 13            return point > begin ? substring(begin, point) : ""
 14        }
 15    }
 16
 17    /// `org-map-region`.
 18    func mapRegion(_ begin: Int, _ end: Int, _ body: () throws -> Void) rethrows {
 19        try saveExcursion {
 20            let end = marker(end)
 21            defer { release(end) }
 22            point = begin
 23            if let heading = searchHeadingForward(), point < end.position {
 24                point = heading
 25                try body()
 26            }
 27            while true {
 28                outlineNextHeading()
 29                guard point < end.position, !eobp else { break }
 30                try body()
 31            }
 32        }
 33    }
 34
 35    /// `org-paste-subtree` with a numeric level; `limit` ends the buffer there, as narrowing does.
 36    func pasteSubtree(level: Int, tree: String, limit: Int? = nil) throws {
 37        let oldLevel = tree.range(of: "(?m)^\\*+ ", options: .regularExpression).map { tree[$0].count - 1 } ?? -1
 38        let shift = oldLevel == -1 || oldLevel == level ? 0 : level - oldLevel
 39        if !(bolp && atHeading) {
 40            endOfLine()
 41            point = min(nextHeadingStart(after: point) ?? length, limit ?? length)
 42            if !bolp { insert("\n") }
 43        }
 44        var begin = point
 45        insert(tree)
 46        if !tree.hasSuffix("\n") { insert("\n") }
 47        let end = marker(point)
 48        defer { release(end) }
 49        point = begin
 50        skipForward(Self.whitespace)
 51        begin = point
 52        var remaining = shift
 53        while remaining != 0 {
 54            try mapRegion(begin, end.position) { try changeLevel(by: remaining > 0 ? 1 : -1) }
 55            remaining += remaining > 0 ? -1 : 1
 56        }
 57        point = begin
 58    }
 59
 60    /// Inserts a refiled subtree as the last child of the heading at `target`, or at the end of
 61    /// the buffer as a top-level entry when `target` is nil.
 62    func refileInsert(_ tree: String, under target: Int?) throws {
 63        try saveExcursion {
 64            let level: Int
 65            if let target {
 66                point = target
 67                level = outlineLevel + 1
 68                let sibling = saveExcursion { nextSibling() }
 69                if let sibling { point = sibling } else { endOfSubtree(toHeading: true) }
 70            } else {
 71                level = 1
 72                point = length
 73            }
 74            if !bolp { insert("\n") }
 75            try pasteSubtree(level: level, tree: tree)
 76            alignTags(onLineAt: point)
 77        }
 78    }
 79
 80    /// Range of the subtree at point with the blank lines after it, as org-refile deletes it.
 81    func subtreeRange() throws -> Range<Int> {
 82        try saveExcursion {
 83            let begin = try backToHeading()
 84            let end = endOfSubtree(toHeading: true)
 85            return begin..<end
 86        }
 87    }
 88
 89    /// `org-refile` to a heading in this buffer, or to its end when `target` is nil; with
 90    /// `keep`, `org-copy`, which leaves the subtree where it was.
 91    func refileWithinBuffer(to target: Int?, keep: Bool = false) throws {
 92        let subtree = try subtreeRange()
 93        if let target, subtree.contains(target) {
 94            throw UserError(message: "Cannot refile to position inside the tree or region")
 95        }
 96        let tree = try copySubtree()
 97        let origin = marker(point, advances: true)
 98        defer { release(origin) }
 99        try refileInsert(tree, under: target)
100        point = origin.position
101        if keep { return }
102        let range = try subtreeRange()
103        deleteRegion(range.lowerBound, range.upperBound)
104    }
105}
106
107/// C-c C-w within one file: moves the subtree at the caret under the heading starting at the
108/// answer's offset, or to the end of the file for an empty answer. With `keep`, C-c M-w
109/// copies it there.
110public struct RefileWithinFile: OrgCommand {
111    public let keep: Bool
112    public init(keep: Bool = false) { self.keep = keep }
113    public var id: String { keep ? "org.refile.local-copy" : "org.refile.local" }
114    public var title: String { keep ? "Copy Within File" : "Refile Within File" }
115    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
116
117    public func run(in context: EditContext) -> CommandStep {
118        guard let answer = context.answers["refile"] else {
119            return .prompt(Prompt(key: "refile", message: "Refile to:"))
120        }
121        return commitBuffer(context) { try $0.refileWithinBuffer(to: Int(answer), keep: keep) }
122    }
123}
124
125/// Refiling into another file: the edit to the source and the target's new text.
126public enum Refile {
127    public struct Result: Sendable, Equatable {
128        public let source: EditResult
129        public let target: TextEdit
130    }
131
132    /// With `keep`, the source's edit leaves its text as it is.
133    public static func toOtherFile(source context: EditContext, target text: String, under heading: Int?, keep: Bool = false) -> Result? {
134        let target = EmacsBuffer(text, point: 0, settings: context.tree.settings, options: context.options)
135        var tree = ""
136        let step = commitBuffer(context) { buffer in
137            tree = try buffer.copySubtree()
138            try target.refileInsert(tree, under: heading)
139            if keep { return }
140            let range = try buffer.subtreeRange()
141            buffer.deleteRegion(range.lowerBound, range.upperBound)
142        }
143        guard case .commit(let source) = step else { return nil }
144        let edit = commitBuffer(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [0..<0])) { buffer in
145            buffer.replace(0..<buffer.length, with: target.string)
146        }
147        guard case .commit(let result) = edit else { return nil }
148        return Result(source: source, target: result.edits.first ?? TextEdit(range: 0..<0, replacement: ""))
149    }
150}