Sources/OrgApp/EmacsImportSnippets.swift
102 lines · 5296 bytes
6 symbols in this file
1import Foundation
2import OrgCore
3
4/// yasnippet's org-mode snippets, from `snippets/org-mode/` beside the configuration read.
5extension EmacsImport {
6 /// One yasnippet file: `# key:`, `# name:` and the body after `# --`. A file without that
7 /// line is all body, keyed by its name, as yasnippet reads it.
8 public struct Yasnippet: Sendable, Equatable {
9 public var key: String
10 public var name: String
11 public var body: String
12 /// Why it can't be used without Emacs, or nil.
13 public var lisp: String?
14 }
15
16 public static func yasnippet(_ text: String, fileName: String) -> Yasnippet {
17 var key: String?
18 var name: String?
19 var type: String?
20 var body = text
21 let lines = text.components(separatedBy: "\n")
22 if let separator = lines.firstIndex(where: { $0.range(of: "^#[ \\t]*--[ \\t]*$", options: .regularExpression) != nil }) {
23 for line in lines[..<separator] {
24 guard line.hasPrefix("#"), let colon = line.firstIndex(of: ":") else { continue }
25 let field = line[line.index(after: line.startIndex)..<colon].trimmingCharacters(in: .whitespaces)
26 let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
27 switch field {
28 case "key": key = value
29 case "name": name = value
30 case "type": type = value
31 default: break
32 }
33 }
34 body = lines[(separator + 1)...].joined(separator: "\n")
35 }
36 let trigger = key ?? fileName
37 var lisp: String?
38 if type == "command" {
39 lisp = "a command snippet, which is Emacs Lisp"
40 } else if body.range(of: "(?<!\\\\)`", options: .regularExpression) != nil {
41 lisp = "has Emacs Lisp in backquotes"
42 } else if body.contains("$(") {
43 lisp = "has an Emacs Lisp transformation"
44 }
45 return Yasnippet(key: trigger, name: name ?? trigger, body: body, lisp: lisp)
46 }
47
48 /// The `[[snippet]]` table for `snippet`.
49 static func snippetTable(_ snippet: Yasnippet) -> String {
50 var out = "[[snippet]]\ntrigger = \(UserConfig.format(.string(snippet.key)))\n"
51 if snippet.name != snippet.key { out += "description = \(UserConfig.format(.string(snippet.name)))\n" }
52 // A literal multi-line string keeps the body as it is, unless it holds the delimiter.
53 if snippet.body.contains("'''") || snippet.body.contains("\r") {
54 out += "body = \(UserConfig.format(.string(snippet.body)))\n"
55 } else {
56 out += "body = '''\n\(snippet.body)'''\n"
57 }
58 return out
59 }
60
61 /// Where yasnippet keeps org-mode snippets for a configuration in `folders`.
62 static func snippetFolders(_ folders: [URL]) -> [URL] {
63 var seen: Set<String> = []
64 return folders.map { $0.appendingPathComponent("snippets/org-mode") }
65 .filter { seen.insert($0.standardizedFileURL.path).inserted && FileManager.default.fileExists(atPath: $0.path) }
66 }
67
68 /// Reads the snippets in `folders` into items; those with Emacs Lisp are listed as not
69 /// imported.
70 mutating func addSnippets(from folders: [URL]) {
71 var next = (items.map(\.id) + unsupported.map(\.id) + unreadable.map(\.id)).max() ?? 0
72 func id() -> Int { next += 1; return next }
73 var triggers: Set<String> = []
74 for folder in folders {
75 let files = ((try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isRegularFileKey])) ?? [])
76 .filter { !$0.lastPathComponent.hasPrefix(".") && (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true }
77 .sorted { $0.lastPathComponent < $1.lastPathComponent }
78 for file in files {
79 let source = "snippets/org-mode/" + file.lastPathComponent
80 guard let text = try? String(contentsOf: file, encoding: .utf8) else {
81 problems.append("Can't read \(file.path)")
82 continue
83 }
84 let snippet = Self.yasnippet(text, fileName: file.lastPathComponent)
85 if let reason = snippet.lisp {
86 unsupported.append(Note(id: id(), name: "snippet \(snippet.key)", reason: reason, source: source))
87 snippetsSkipped += 1
88 continue
89 }
90 let parsed = try? Snippets.parse(Self.snippetTable(snippet))
91 guard let parsed, parsed.problems.isEmpty else {
92 let problem = parsed?.problems.first.map { $0.replacingOccurrences(of: "^line [0-9]+: ", with: "", options: .regularExpression) }
93 unsupported.append(Note(id: id(), name: "snippet \(snippet.key)", reason: problem ?? "not readable", source: source))
94 snippetsSkipped += 1
95 continue
96 }
97 guard triggers.insert(snippet.key).inserted else { continue }
98 items.append(Item(id: id(), name: snippet.key, summary: snippet.name, source: source, change: .snippet(trigger: snippet.key, toml: Self.snippetTable(snippet))))
99 }
100 }
101 }
102}