Sources/OrgApp/RefileTargets.swift

19641366e5de9103a7d88bf80436ab2aebc03cf5
orgstar/Sources/OrgApp/RefileTargets.swift

154 lines · 8668 bytes

  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import OrgIndex
  5import OrgPresentation
  6
  7extension RefileSettings {
  8    /// For an answer that isn't a target, `parent/child` with `parent` one: the target and the
  9    /// new heading's title, as `org-refile-get-location` splits it.
 10    public static func newNode(_ answer: String, in targets: [RefileTarget]) -> (parent: RefileTarget, child: String)? {
 11        guard let m = answer.firstMatch(of: /^(.*)\/([^\/]+)$/) else { return nil }
 12        let parent = String(m.1).replacingOccurrences(of: "/$", with: "", options: .regularExpression)
 13        let child = String(m.2).trimmingCharacters(in: .whitespaces)
 14        guard !child.isEmpty, let target = targets.first(where: { $0.label == parent }) else { return nil }
 15        return (target, child)
 16    }
 17}
 18
 19extension WorkspaceModel {
 20    /// The refile targets, as `org-refile-get-targets` lists them for `settings`: entry by
 21    /// entry, file by file, in buffer order, with a file's own target first when the outline
 22    /// path starts with the file. `openPath` is the file refiled from, read from `document`.
 23    public func refileTargets(openPath: String?, document: DocumentState?, settings: RefileSettings = OrgPreferences.refileSettings()) -> [RefileTarget] {
 24        var targets: [RefileTarget] = []
 25        var seen: Set<String> = []
 26        func add(_ target: RefileTarget) {
 27            if seen.insert("\(target.path)\u{0}\(target.start ?? -1)\u{0}\(target.label)").inserted { targets.append(target) }
 28        }
 29        let orgFiles = files.filter { $0.kind == .org }
 30        let relative = Dictionary(orgFiles.map { ($0.path, $0.relativePath) }, uniquingKeysWith: { a, _ in a })
 31        // Closed files' headings, from the index, for the targets that go by level.
 32        let levels = settings.targets.compactMap { target -> Int? in
 33            switch target.spec {
 34            case .all: Int.max
 35            case .level(let n), .maxLevel(let n): n
 36            default: nil
 37            }
 38        }
 39        let indexed = levels.isEmpty ? [] : (try? index.outline(maxLevel: min(levels.max()!, 1000))) ?? []
 40        let indexedByPath = Dictionary(grouping: indexed, by: \.location.path)
 41        for entry in settings.targets {
 42            let paths: [String]
 43            switch entry.files {
 44            case .current: paths = openPath.map { [$0] } ?? []
 45            case .workspace: paths = orgFiles.map(\.path)
 46            case .agendaFiles:
 47                let list = OrgPreferences.agendaFiles()
 48                if list.isEmpty {
 49                    let subfolders = OrgPreferences.agendaSubfolders()
 50                    paths = orgFiles.filter { !$0.name.hasPrefix(".") && (subfolders || !$0.relativePath.contains("/")) }.map(\.path).sorted()
 51                } else {
 52                    paths = AgendaFiles.resolve(list, base: rootPaths.first)
 53                }
 54            case .paths(let list):
 55                let base = openPath.map { ($0 as NSString).deletingLastPathComponent } ?? rootPaths.first
 56                paths = list.map { entry in
 57                    let path = OrgPaths.expandingTilde(entry)
 58                    return ((path.hasPrefix("/") || base == nil ? path : (base! as NSString).appendingPathComponent(path)) as NSString).standardizingPath
 59                }
 60            }
 61            for path in paths {
 62                let name = relative[path] ?? (path as NSString).lastPathComponent
 63                // The headings: from the buffer, the index, or the file's text.
 64                var text: String?
 65                var hash: String
 66                var headings: [(start: Int, level: Int, path: [String])] = []
 67                if path == openPath, let document {
 68                    text = document.text
 69                    hash = FileRecord.hash(document.mergeBase)
 70                } else if let level = Self.level(entry.spec), let records = indexedByPath[path] {
 71                    hash = records.first?.location.contentHash ?? ""
 72                    headings = records.filter { level($0.level) }.map { ($0.location.start, $0.level, $0.outlinePath) }
 73                } else {
 74                    guard let data = FileManager.default.contents(atPath: path) else { continue }
 75                    let state = DocumentState(bytes: [UInt8](data))
 76                    text = state.text
 77                    hash = FileRecord.hash(state.mergeBase)
 78                }
 79                if let text {
 80                    headings = Self.headings(text, spec: entry.spec)
 81                }
 82                let base: String? = switch settings.outlinePath {
 83                case .file, .bufferName: name
 84                case .fullFilePath: path
 85                case .title: text.flatMap { Self.fileTitle($0) } ?? Self.diskTitle(path) ?? name
 86                case .none, .full: nil
 87                }
 88                // Targets in other files name the file after them, but not with paths that start with it.
 89                let elsewhere = path != openPath && [.none, .full, .bufferName].contains(settings.outlinePath)
 90                let suffix = elsewhere ? " (\((path as NSString).lastPathComponent))" : ""
 91                if let base, settings.outlinePath != .none, settings.outlinePath != .full {
 92                    add(RefileTarget(label: base + suffix, path: path, start: nil, title: "", level: 0, contentHash: hash))
 93                }
 94                for heading in headings {
 95                    let escaped = heading.path.map { $0.replacingOccurrences(of: "/", with: "\\/") }
 96                    var label = settings.outlinePath == .none ? heading.path.last ?? "" : ((base.map { [$0] } ?? []) + escaped).joined(separator: "/")
 97                    label += suffix
 98                    add(RefileTarget(label: label, path: path, start: heading.start, title: heading.path.last ?? "", level: heading.level, contentHash: hash))
 99                }
100            }
101        }
102        return targets
103    }
104
105    /// The test a level-based spec makes of a heading's level; nil for the others.
106    static func level(_ spec: RefileSettings.Spec) -> ((Int) -> Bool)? {
107        switch spec {
108        case .all: { _ in true }
109        case .level(let n): { $0 == n }
110        case .maxLevel(let n): { $0 <= n }
111        default: nil
112        }
113    }
114
115    /// The headings `spec` finds in `text`, as `org-refile-get-targets` searches: each match
116    /// of its regexp (case-sensitive) on a heading line gives that heading.
117    static func headings(_ text: String, spec: RefileSettings.Spec) -> [(start: Int, level: Int, path: [String])] {
118        let outline = Presentation.outline(OrgParser.parse(text))
119        var paths: [[String]] = []
120        for entry in outline { paths.append((entry.parent.map { paths[$0] } ?? []) + [entry.title]) }
121        let byStart = Dictionary(outline.indices.map { (outline[$0].start, $0) }, uniquingKeysWith: { a, _ in a })
122        guard let regex = try? NSRegularExpression(pattern: EmacsRegex.translate(RefileSettings.regexp(spec)), options: .anchorsMatchLines) else { return [] }
123        let ns = text as NSString
124        var found: [(Int, Int, [String])] = []
125        var at = 0
126        while at <= ns.length, let m = regex.firstMatch(in: text, options: [.withoutAnchoringBounds, .withTransparentBounds], range: NSRange(location: at, length: ns.length - at)) {
127            let end = NSMaxRange(m.range)
128            let line = ns.lineRange(for: NSRange(location: min(end, max(0, ns.length - 1)), length: 0))
129            let lineStart = end == ns.length && end > 0 && ns.character(at: end - 1) == 10 ? end : line.location
130            if let index = byStart[lineStart] {
131                found.append((lineStart, outline[index].level, paths[index]))
132                var lineEnd = NSMaxRange(line)
133                if lineEnd > line.location, ns.character(at: lineEnd - 1) == 10 { lineEnd -= 1 }
134                at = max(lineEnd, end, at + 1)
135            } else {
136                at = max(end, at + 1)
137            }
138        }
139        return found
140    }
141
142    /// `org-get-title`: the `#+TITLE` lines joined.
143    static func fileTitle(_ text: String) -> String? {
144        let titles = text.components(separatedBy: "\n").compactMap { line -> String? in
145            guard let r = line.range(of: "^#\\+(?i:title):[ \\t]*", options: .regularExpression) else { return nil }
146            return String(line[r.upperBound...]).trimmingCharacters(in: .whitespaces)
147        }
148        return titles.isEmpty ? nil : titles.joined(separator: " ")
149    }
150
151    static func diskTitle(_ path: String) -> String? {
152        FileManager.default.contents(atPath: path).flatMap { String(data: $0, encoding: .utf8) }.flatMap { fileTitle($0) }
153    }
154}
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