Sources/OrgApp/MacroFile.swift

c2d503b97e80b560fda12d61ecc99864f2a18a25
orgstar/Sources/OrgApp/MacroFile.swift

41 lines · 1870 bytes

 1import Foundation
 2import OrgCore
 3
 4/// `macros.toml` in the configuration folder: keyboard macros by name, in a `[macros]` table of
 5/// key sequences in the keymap's notation.
 6public enum MacroFile {
 7    public static var url: URL { UserConfig.file(NamedMacros.fileName) }
 8
 9    static let header = """
10        # Keyboard macros named with Name Last Macro (C-x C-k n in the Emacs preset). Each runs as
11        # the command macro.named.<name>, which keymap.toml can bind. Keys are in keymap.toml's
12        # notation; a prompt's answer is the keys typed into it, then RET.
13
14        """
15
16    /// Reads the file into `store`, and has `store` write macros named from now on into it.
17    /// The problems found; a missing file is none.
18    @discardableResult
19    public static func load(into store: NamedMacros = .shared, from url: URL = url) -> [String] {
20        store.setSaver { name, keys in try save(name, keys, to: url) }
21        guard let text = try? String(contentsOf: url, encoding: .utf8) else {
22            store.replace([:])
23            return []
24        }
25        var problems: [String] = []
26        do {
27            store.replace(try NamedMacros.parse(text, problems: &problems))
28        } catch {
29            problems.append("\(error)")
30        }
31        return problems
32    }
33
34    /// Writes `name` into the file, keeping what else it holds.
35    public static func save(_ name: String, _ keys: [KeyChord], to url: URL = url) throws {
36        let text = (try? String(contentsOf: url, encoding: .utf8)) ?? header
37        let updated = UserConfig.setting(text, section: NamedMacros.table, key: name, to: .string(KeySequence.format(keys)))
38        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
39        try updated.write(to: url.resolvingSymlinksInPath(), atomically: true, encoding: .utf8)
40    }
41}
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