Commit be996c163c

be996c163c7399849cca3987b604bf1f64a98962

parent: 754eac2f33

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 22:09 UTC

Markdown and Obsidian to org converter and import planning

Ref #161

Layout: unified · split

Changed files (8)
Sources/OrgApp/MarkdownImport.swift added +481 · view
@@ -0,0 +1,481 @@
1import Foundation
2import OrgCore
3
4/// File ▸ Import ▸ Markdown Files… and Obsidian Vault…: converts Markdown files to new org
5/// files in one of the person's folders, leaving the sources alone.
6///
7/// A chosen file becomes `name.org` in the destination; a chosen folder or vault becomes a new
8/// folder of the same name holding its notes at the same relative paths. Names already taken
9/// get ` 2`, ` 3`… Files a note links to or embeds are copied: a folder's into the new folder
10/// at the same relative path, a loose file's into `attachments` in the destination. Links
11/// between notes become `file:` links to the converted files.
12public enum MarkdownImport {
13 public enum Kind: Sendable {
14 case markdown, obsidian
15 }
16
17 public struct Problem: Sendable, Hashable {
18 public enum Reason: Sendable, Hashable {
19 case converted(MarkdownImportIssue)
20 /// Not UTF-8 or unreadable.
21 case unreadable
22 /// An Obsidian canvas or base, which has no org equivalent.
23 case notConverted
24 }
25
26 /// The source file, relative to what was chosen.
27 public let file: String
28 public let reason: Reason
29 }
30
31 /// What an import will write, for the preview, and the text to write.
32 public struct Plan: Sendable {
33 public let kind: Kind
34 public let destination: URL
35 public fileprivate(set) var notes = 0
36 public fileprivate(set) var headings = 0
37 public fileprivate(set) var links = 0
38 public fileprivate(set) var attachments = 0
39 public fileprivate(set) var problems: [Problem] = []
40 /// Names chosen instead of the source's because the destination has that name.
41 public fileprivate(set) var renamed: [(from: String, to: String)] = []
42
43 struct Top {
44 var name: String
45 let natural: String
46 let folder: Bool
47 /// `attachments`, which may already exist and is shared by loose files.
48 let shared: Bool
49 }
50
51 enum Content {
52 case text(String)
53 case copy(URL)
54 }
55
56 struct Output {
57 let top: Int
58 /// The path inside the top folder; empty for a loose file.
59 var inner: String
60 let content: Content
61 }
62
63 fileprivate var tops: [Top] = []
64 fileprivate var outputs: [Output] = []
65 }
66
67 // MARK: - Planning
68
69 /// A note or attachment in the sources, by where it ends up.
70 fileprivate struct SourceFile {
71 let url: URL
72 /// The chosen item's index.
73 let top: Int
74 /// Path below the chosen folder; the file name for a loose file.
75 let relative: String
76 let note: Bool
77 }
78
79 static let noteExtensions: Set<String> = ["md", "markdown"]
80
81 /// Reads `sources` (files, folders or a vault) and converts every note, choosing names
82 /// that are free in `destination`. Reads files, so call it off the main actor.
83 public static func plan(_ kind: Kind, sources: [URL], into destination: URL) throws -> Plan {
84 var plan = Plan(kind: kind, destination: destination)
85 let manager = FileManager.default
86 var takenTop = Set<String>()
87 var files: [SourceFile] = []
88 for source in sources {
89 var isFolder: ObjCBool = false
90 guard manager.fileExists(atPath: source.path, isDirectory: &isFolder) else { continue }
91 if isFolder.boolValue {
92 let natural = source.lastPathComponent
93 let name = freeName(natural, in: destination, taken: takenTop)
94 takenTop.insert(name.lowercased())
95 if name != natural { plan.renamed.append((natural, name)) }
96 plan.tops.append(Plan.Top(name: name, natural: natural, folder: true, shared: false))
97 let top = plan.tops.count - 1
98 for relative in folderFiles(source) {
99 let url = source.appendingPathComponent(relative)
100 let ext = url.pathExtension.lowercased()
101 if ext == "canvas" || ext == "base" {
102 plan.problems.append(Problem(file: natural + "/" + relative, reason: .notConverted))
103 }
104 files.append(SourceFile(url: url, top: top, relative: relative, note: noteExtensions.contains(ext)))
105 }
106 } else if noteExtensions.contains(source.pathExtension.lowercased()) {
107 let natural = source.deletingPathExtension().lastPathComponent + ".org"
108 let name = freeName(natural, in: destination, taken: takenTop)
109 takenTop.insert(name.lowercased())
110 if name != natural { plan.renamed.append((source.lastPathComponent, name)) }
111 plan.tops.append(Plan.Top(name: name, natural: natural, folder: false, shared: false))
112 files.append(SourceFile(url: source, top: plan.tops.count - 1, relative: source.lastPathComponent, note: true))
113 }
114 }
115
116 // Where each note goes, relative to the destination.
117 var outputPath: [URL: String] = [:]
118 var takenInner: [Int: Set<String>] = [:]
119 for file in files where file.note {
120 let top = plan.tops[file.top]
121 if top.folder {
122 let natural = (file.relative as NSString).deletingPathExtension + ".org"
123 var inner = natural
124 var n = 2
125 while takenInner[file.top, default: []].contains(inner.lowercased()) {
126 inner = (natural as NSString).deletingPathExtension + " \(n).org"
127 n += 1
128 }
129 takenInner[file.top, default: []].insert(inner.lowercased())
130 outputPath[file.url.standardizedFileURL] = top.name + "/" + inner
131 } else {
132 outputPath[file.url.standardizedFileURL] = top.name
133 }
134 }
135
136 let collector = Collector()
137 let index = VaultIndex(files: files.filter { plan.tops[$0.top].folder })
138 plan.tops.append(Plan.Top(name: "attachments", natural: "attachments", folder: true, shared: true))
139 let attachmentsTop = plan.tops.count - 1
140
141 // Parse every note first, so links can name headings in other notes.
142 var parsed: [URL: MarkdownToOrg.Parsed] = [:]
143 var texts: [(file: SourceFile, parsed: MarkdownToOrg.Parsed)] = []
144 for file in files where file.note {
145 let label = display(file, plan)
146 guard let data = try? Data(contentsOf: file.url), let text = String(data: data, encoding: .utf8) else {
147 plan.problems.append(Problem(file: label, reason: .unreadable))
148 continue
149 }
150 let result = MarkdownToOrg.parse(text, obsidian: kind == .obsidian)
151 parsed[file.url.standardizedFileURL] = result
152 texts.append((file, result))
153 }
154
155 for (file, note) in texts {
156 let url = file.url.standardizedFileURL
157 guard let own = outputPath[url] else { continue }
158 let ownFolder = (own as NSString).deletingLastPathComponent
159 let label = display(file, plan)
160 let folderTop = plan.tops[file.top].folder ? file.top : nil
161 let context = LinkContext(note: url, own: own, ownFolder: ownFolder, folderTop: folderTop, topName: plan.tops[file.top].name,
162 attachmentsTop: plan.tops[attachmentsTop].name, destination: destination,
163 outputPath: outputPath, parsed: parsed, index: index, collector: collector, obsidian: kind == .obsidian)
164 let targets = MarkdownTargets(link: { destination, image in context.link(destination, image: image) },
165 wikilink: { target, fragment, embed in context.wikilink(target, fragment: fragment, embed: embed) })
166 let title = kind == .obsidian ? url.deletingPathExtension().lastPathComponent : nil
167 let result = MarkdownToOrg.render(note, title: title, targets: targets)
168 plan.notes += 1
169 plan.headings += result.headings
170 plan.links += result.links
171 plan.problems += (result.issues + collector.take()).map { Problem(file: label, reason: .converted($0)) }
172 let inner = plan.tops[file.top].folder ? String(own.dropFirst(plan.tops[file.top].name.count + 1)) : ""
173 plan.outputs.append(Plan.Output(top: file.top, inner: inner, content: .text(result.text)))
174 }
175
176 // Attachments: a folder's at the same path inside the new folder, a loose note's in
177 // `attachments` under a free name.
178 var takenAttachments = Set<String>()
179 for (source, place) in collector.attachments.sorted(by: { $0.key.path < $1.key.path }) {
180 switch place {
181 case .inFolder(let top, let relative):
182 plan.outputs.append(Plan.Output(top: top, inner: relative, content: .copy(source)))
183 case .loose(let name):
184 takenAttachments.insert(name.lowercased())
185 plan.outputs.append(Plan.Output(top: attachmentsTop, inner: name, content: .copy(source)))
186 }
187 plan.attachments += 1
188 }
189 if takenAttachments.isEmpty { plan.tops[attachmentsTop].name = "" }
190 plan.problems = plan.problems.reduce(into: []) { if !$0.contains($1) { $0.append($1) } }
191 return plan
192 }
193
194 private static func display(_ file: SourceFile, _ plan: Plan) -> String {
195 plan.tops[file.top].folder ? plan.tops[file.top].natural + "/" + file.relative : file.relative
196 }
197
198 /// Files below `folder`, relative to it, leaving out hidden files and folders
199 /// (`.obsidian`, `.trash`, `.git`).
200 static func folderFiles(_ folder: URL) -> [String] {
201 let manager = FileManager.default
202 guard let enumerator = manager.enumerator(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) else { return [] }
203 let base = folder.standardizedFileURL.resolvingSymlinksInPath().path
204 var out: [String] = []
205 for case let url as URL in enumerator {
206 guard (try? url.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true else { continue }
207 let path = url.standardizedFileURL.resolvingSymlinksInPath().path
208 guard path.hasPrefix(base + "/") else { continue }
209 out.append(String(path.dropFirst(base.count + 1)))
210 }
211 return out.sorted()
212 }
213
214 /// `natural`, or `name 2.ext`, `name 3.ext`… when that name is in `folder` or `taken`
215 /// (lowercased).
216 static func freeName(_ natural: String, in folder: URL, taken: Set<String>) -> String {
217 let ext = (natural as NSString).pathExtension
218 let stem = (natural as NSString).deletingPathExtension
219 var name = natural
220 var n = 2
221 while taken.contains(name.lowercased()) || FileManager.default.fileExists(atPath: folder.appendingPathComponent(name).path) {
222 name = stem + " \(n)" + (ext.isEmpty ? "" : "." + ext)
223 n += 1
224 }
225 return name
226 }
227
228 /// `path` relative to the folder `from`, both relative to the same folder.
229 static func relative(_ path: String, from folder: String) -> String {
230 let target = path.split(separator: "/").map(String.init)
231 let base = folder.split(separator: "/").map(String.init)
232 var common = 0
233 while common < min(target.count - 1, base.count), target[common] == base[common] { common += 1 }
234 return (Array(repeating: "..", count: base.count - common) + target[common...]).joined(separator: "/")
235 }
236
237 // MARK: - Links
238
239 enum Placement: Sendable {
240 case inFolder(top: Int, relative: String)
241 case loose(name: String)
242 }
243
244 /// Attachments links ask for, gathered while notes render.
245 final class Collector: @unchecked Sendable {
246 private let lock = NSLock()
247 private(set) var attachments: [URL: Placement] = [:]
248 private var looseNames = Set<String>()
249 private var issues: [MarkdownImportIssue] = []
250
251 func add(_ issue: MarkdownImportIssue) {
252 lock.withLock { issues.append(issue) }
253 }
254
255 func take() -> [MarkdownImportIssue] {
256 lock.withLock {
257 defer { issues = [] }
258 return issues
259 }
260 }
261
262 /// Where `source` is copied, choosing a free name in `attachments` for a loose note's.
263 func place(_ source: URL, inFolder: (top: Int, relative: String)?, attachments folder: URL?) -> Placement {
264 lock.withLock {
265 if let placed = attachments[source] { return placed }
266 let placement: Placement
267 if let inFolder {
268 placement = .inFolder(top: inFolder.top, relative: inFolder.relative)
269 } else {
270 let name = MarkdownImport.freeName(source.lastPathComponent, in: folder ?? source, taken: looseNames)
271 looseNames.insert(name.lowercased())
272 placement = .loose(name: name)
273 }
274 attachments[source] = placement
275 return placement
276 }
277 }
278 }
279
280 /// A folder's files by name, for wikilinks, which name a note or file anywhere in the vault.
281 struct VaultIndex: Sendable {
282 /// Lowercased names (notes without their extension) to the files with them.
283 let byName: [String: [(url: URL, top: Int, relative: String)]]
284 let byPath: [String: (url: URL, top: Int, relative: String)]
285 let byURL: [URL: (top: Int, relative: String)]
286
287 fileprivate init(files: [SourceFile]) {
288 var byName: [String: [(url: URL, top: Int, relative: String)]] = [:]
289 var byPath: [String: (url: URL, top: Int, relative: String)] = [:]
290 var byURL: [URL: (top: Int, relative: String)] = [:]
291 for file in files {
292 let entry = (file.url.standardizedFileURL, file.top, file.relative)
293 byURL[file.url.standardizedFileURL] = (file.top, file.relative)
294 let key = (file.note ? (file.relative as NSString).deletingPathExtension : file.relative).lowercased()
295 byPath["\(file.top)/" + key] = entry
296 byName[(key as NSString).lastPathComponent, default: []].append(entry)
297 }
298 for key in byName.keys { byName[key]?.sort { $0.relative.count < $1.relative.count } }
299 self.byName = byName
300 self.byPath = byPath
301 self.byURL = byURL
302 }
303 }
304
305 /// Resolves one note's links.
306 struct LinkContext: Sendable {
307 let note: URL
308 /// The note's output path, relative to the destination.
309 let own: String
310 let ownFolder: String
311 /// The note's chosen folder, when it's in one.
312 let folderTop: Int?
313 let topName: String
314 let attachmentsTop: String
315 let destination: URL
316 let outputPath: [URL: String]
317 let parsed: [URL: MarkdownToOrg.Parsed]
318 let index: VaultIndex
319 let collector: Collector
320 let obsidian: Bool
321
322 /// The org path for a note at `target` with `fragment`, relative to this note.
323 func notePath(_ target: URL, fragment: String?, original: String) -> String? {
324 guard let output = outputPath[target] else { return nil }
325 let same = target == note
326 var search = ""
327 if let fragment, !fragment.isEmpty {
328 let part = fragment.split(separator: "#").last.map(String.init) ?? fragment
329 if part.hasPrefix("^") {
330 if parsed[target]?.blockIDs.contains(String(part.dropFirst())) == true {
331 search = String(part.dropFirst())
332 } else {
333 collector.add(.missingHeading(original))
334 }
335 } else if let title = MarkdownToOrg.heading(part, in: parsed[target]?.headings ?? []) {
336 search = "*" + title
337 } else {
338 collector.add(.missingHeading(original))
339 }
340 }
341 if same, !search.isEmpty { return search }
342 let path = "file:" + MarkdownImport.relative(output, from: ownFolder)
343 return search.isEmpty ? path : path + "::" + search
344 }
345
346 /// The org path for a file copied as an attachment.
347 func attachmentPath(_ url: URL) -> String {
348 let inFolder: (top: Int, relative: String)?
349 if let folderTop, let found = index.byURL[url], found.top == folderTop {
350 inFolder = (folderTop, found.relative)
351 } else {
352 inFolder = nil
353 }
354 let placement = collector.place(url, inFolder: inFolder, attachments: destination.appendingPathComponent(attachmentsTop))
355 switch placement {
356 case .inFolder(_, let relative): return "file:" + MarkdownImport.relative(topName + "/" + relative, from: ownFolder)
357 case .loose(let name): return "file:" + MarkdownImport.relative(attachmentsTop + "/" + name, from: ownFolder)
358 }
359 }
360
361 func link(_ destination: String, image: Bool) -> String? {
362 if destination.hasPrefix("#") {
363 return notePath(note, fragment: String(destination.dropFirst()), original: destination) ?? destination
364 }
365 if let colon = destination.firstIndex(of: ":"), destination[..<colon].count >= 2,
366 destination[..<colon].allSatisfy({ $0.isLetter || $0.isNumber || "+.-".contains($0) }) { return nil }
367 var path = destination
368 var fragment: String?
369 if let hash = path.firstIndex(of: "#") {
370 fragment = String(path[path.index(after: hash)...])
371 path = String(path[..<hash])
372 }
373 path = path.removingPercentEncoding ?? path
374 let folder = note.deletingLastPathComponent()
375 var candidates = [path.hasPrefix("/") ? URL(fileURLWithPath: path) : folder.appendingPathComponent(path)]
376 if obsidian, let folderTop {
377 if let entry = index.byPath["\(folderTop)/" + ((path as NSString).pathExtension.lowercased() == "md" ? (path as NSString).deletingPathExtension : path).lowercased()] {
378 candidates.append(entry.url)
379 }
380 if let entry = index.byName[((path as NSString).pathExtension.lowercased() == "md" ? (path as NSString).deletingPathExtension : path).lowercased()]?.first {
381 candidates.append(entry.url)
382 }
383 }
384 for candidate in candidates.map(\.standardizedFileURL) {
385 if outputPath[candidate] != nil { return notePath(candidate, fragment: fragment, original: destination) }
386 var isFolder: ObjCBool = false
387 if FileManager.default.fileExists(atPath: candidate.path, isDirectory: &isFolder), !isFolder.boolValue {
388 if MarkdownImport.noteExtensions.contains(candidate.pathExtension.lowercased()) { break }
389 return attachmentPath(candidate)
390 }
391 }
392 collector.add(.unresolvedLink(destination))
393 return nil
394 }
395
396 func wikilink(_ target: String, fragment: String?, embed: Bool) -> (path: String, image: Bool)? {
397 let original = target + (fragment.map { "#" + $0 } ?? "")
398 if target.isEmpty {
399 guard let path = notePath(note, fragment: fragment, original: original) else { return nil }
400 return (path, false)
401 }
402 var key = target.lowercased()
403 if (key as NSString).pathExtension == "md" { key = (key as NSString).deletingPathExtension }
404 let entry: (url: URL, top: Int, relative: String)?
405 if key.contains("/") {
406 entry = folderTop.flatMap { index.byPath["\($0)/" + key] } ?? index.byName[(key as NSString).lastPathComponent]?.first { $0.relative.lowercased().hasSuffix(key) }
407 } else {
408 entry = index.byName[key]?.first
409 }
410 guard let entry else {
411 // Obsidian links to notes that don't exist yet; the link goes where one would be.
412 collector.add(.unresolvedLink(original))
413 let ext = (key as NSString).pathExtension
414 guard ext.isEmpty else { return nil }
415 return ("file:" + MarkdownImport.relative((folderTop == nil ? "" : topName + "/") + target + ".org", from: ownFolder), false)
416 }
417 if outputPath[entry.url] != nil {
418 guard let path = notePath(entry.url, fragment: fragment, original: original) else { return nil }
419 return (path, false)
420 }
421 return (attachmentPath(entry.url), MarkdownToOrg.imageExtensions.contains(entry.url.pathExtension.lowercased()))
422 }
423 }
424
425 // MARK: - Writing
426
427 public struct Written: Sendable {
428 /// Every file written, notes and attachments.
429 public var paths: [String] = []
430 /// Names taken since the preview, and what was used instead.
431 public var renamed: [(from: String, to: String)] = []
432 }
433
434 /// Writes `plan`'s files. Nothing existing is replaced: a name taken since the plan was
435 /// made gets another free name. Each file appears whole or not at all.
436 public static func write(_ plan: Plan) throws -> Written {
437 let manager = FileManager.default
438 var written = Written()
439 var tops = plan.tops
440 for (k, top) in tops.enumerated() where top.folder && !top.name.isEmpty {
441 if top.shared {
442 try manager.createDirectory(at: plan.destination.appendingPathComponent(top.name), withIntermediateDirectories: true)
443 continue
444 }
445 var name = top.name
446 while true {
447 do {
448 try manager.createDirectory(at: plan.destination.appendingPathComponent(name), withIntermediateDirectories: false)
449 break
450 } catch CocoaError.fileWriteFileExists {
451 name = freeName(top.natural, in: plan.destination, taken: Set(tops.map { $0.name.lowercased() }))
452 }
453 }
454 if name != top.name { written.renamed.append((top.name, name)) }
455 tops[k].name = name
456 }
457 for output in plan.outputs {
458 let top = tops[output.top]
459 guard !top.name.isEmpty else { continue }
460 var url = top.folder ? plan.destination.appendingPathComponent(top.name).appendingPathComponent(output.inner) : plan.destination.appendingPathComponent(top.name)
461 try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
462 let temporary = url.deletingLastPathComponent().appendingPathComponent(".\(url.lastPathComponent).\(UUID().uuidString).tmp")
463 switch output.content {
464 case .text(let text): try Data(text.utf8).write(to: temporary, options: .withoutOverwriting)
465 case .copy(let source): try manager.copyItem(at: source, to: temporary)
466 }
467 while renamex_np(temporary.path, url.path, UInt32(RENAME_EXCL)) != 0 {
468 guard errno == EEXIST else {
469 let code = errno
470 try? manager.removeItem(at: temporary)
471 throw NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: [NSFilePathErrorKey: url.path])
472 }
473 let taken = url.lastPathComponent
474 url = url.deletingLastPathComponent().appendingPathComponent(freeName(taken, in: url.deletingLastPathComponent(), taken: []))
475 written.renamed.append((taken, url.lastPathComponent))
476 }
477 written.paths.append(url.path)
478 }
479 return written
480 }
481}
Sources/OrgCore/MarkdownImport/MarkdownBlocks.swift added +573 · view
@@ -0,0 +1,573 @@
1import Foundation
2
3/// A Markdown document's blocks, as `MarkdownBlocks.parse` reads them: CommonMark's block
4/// structure plus GFM tables, task items and footnotes, and Obsidian's callouts and `%%`
5/// comments when `obsidian` is set.
6indirect enum MarkdownBlock: Equatable, Sendable {
7 /// An ATX or setext heading; `text` is the raw inline text.
8 case heading(level: Int, text: String)
9 /// Raw lines, inline markup unconverted.
10 case paragraph([String])
11 /// A fenced block (`lang` from its info string) or an indented one (`fenced` false).
12 case code(lang: String, lines: [String], fenced: Bool)
13 /// `$$ … $$` on lines of their own.
14 case math([String])
15 /// `%% … %%` (Obsidian) or `<!-- … -->` on lines of their own.
16 case comment([String])
17 case html([String])
18 case quote([MarkdownBlock])
19 /// `> [!type] title`; `type` lowercased.
20 case callout(type: String, title: String, blocks: [MarkdownBlock])
21 case list(ordered: Bool, start: Int, items: [MarkdownItem])
22 case table(header: [String], rows: [[String]])
23 case rule
24}
25
26struct MarkdownItem: Equatable, Sendable {
27 /// The character between a task item's brackets, `nil` for a plain item.
28 var task: Character?
29 var blocks: [MarkdownBlock]
30}
31
32/// What a parse found besides blocks: footnote definitions and link reference definitions.
33struct MarkdownDefinitions {
34 var footnotes: [(label: String, blocks: [MarkdownBlock])] = []
35 /// Lowercased, whitespace-collapsed label to destination.
36 var links: [String: String] = [:]
37}
38
39struct MarkdownBlocks {
40 let obsidian: Bool
41 var definitions = MarkdownDefinitions()
42
43 init(obsidian: Bool) { self.obsidian = obsidian }
44
45 static func parse(_ text: String, obsidian: Bool) -> (blocks: [MarkdownBlock], definitions: MarkdownDefinitions) {
46 var parser = MarkdownBlocks(obsidian: obsidian)
47 let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
48 .split(separator: "\n", omittingEmptySubsequences: false).map { expandTabs(String($0)) }
49 let blocks = parser.blocks(lines)
50 return (blocks, parser.definitions)
51 }
52
53 /// Tabs to spaces at four-column stops, in the leading whitespace only.
54 static func expandTabs(_ line: String) -> String {
55 guard line.contains("\t") else { return line }
56 var out = ""
57 var column = 0
58 var leading = true
59 for char in line {
60 if leading, char == "\t" {
61 let width = 4 - column % 4
62 out += String(repeating: " ", count: width)
63 column += width
64 } else {
65 if char != " " { leading = false }
66 out.append(char)
67 column += 1
68 }
69 }
70 return out
71 }
72
73 // MARK: - Line tests
74
75 static func indent(_ line: String) -> Int { line.prefix { $0 == " " }.count }
76 static func isBlank(_ line: String) -> Bool { line.allSatisfy { $0 == " " } }
77
78 static func fence(_ line: String) -> (char: Character, count: Int, indent: Int, info: String)? {
79 let indent = indent(line)
80 guard indent <= 3 else { return nil }
81 let rest = line.dropFirst(indent)
82 guard let char = rest.first, char == "`" || char == "~" else { return nil }
83 let count = rest.prefix { $0 == char }.count
84 guard count >= 3 else { return nil }
85 let info = rest.dropFirst(count).trimmingCharacters(in: .whitespaces)
86 if char == "`", info.contains("`") { return nil }
87 return (char, count, indent, info)
88 }
89
90 static func atxHeading(_ line: String) -> (level: Int, text: String)? {
91 let indent = indent(line)
92 guard indent <= 3 else { return nil }
93 let rest = line.dropFirst(indent)
94 let level = rest.prefix { $0 == "#" }.count
95 guard (1...6).contains(level) else { return nil }
96 let after = rest.dropFirst(level)
97 guard after.isEmpty || after.first == " " else { return nil }
98 var text = after.trimmingCharacters(in: .whitespaces)
99 // A closing sequence of #s preceded by a space.
100 if let closing = text.lastIndex(where: { $0 != "#" }) {
101 let tail = text[text.index(after: closing)...]
102 if !tail.isEmpty, text[closing] == " " { text = String(text[...closing]).trimmingCharacters(in: .whitespaces) }
103 } else {
104 text = ""
105 }
106 return (level, text)
107 }
108
109 static func isRule(_ line: String) -> Bool {
110 guard indent(line) <= 3 else { return false }
111 let chars = line.filter { $0 != " " }
112 guard chars.count >= 3, let first = chars.first, "-*_".contains(first) else { return false }
113 return chars.allSatisfy { $0 == first }
114 }
115
116 static func setextLevel(_ line: String) -> Int? {
117 guard indent(line) <= 3 else { return nil }
118 let trimmed = line.trimmingCharacters(in: .whitespaces)
119 guard let first = trimmed.first, first == "=" || first == "-", trimmed.allSatisfy({ $0 == first }) else { return nil }
120 return first == "=" ? 1 : 2
121 }
122
123 struct ListMarker {
124 var ordered: Bool
125 /// `-`, `+`, `*`, `.` or `)`.
126 var delimiter: Character
127 var start: Int
128 var indent: Int
129 /// Columns from the line's start to the item's content.
130 var contentIndent: Int
131 var empty: Bool
132 }
133
134 static func listMarker(_ line: String) -> ListMarker? {
135 let indent = indent(line)
136 let rest = Array(line.dropFirst(indent))
137 guard let first = rest.first else { return nil }
138 var width: Int
139 var marker: ListMarker
140 if "-+*".contains(first) {
141 width = 1
142 marker = ListMarker(ordered: false, delimiter: first, start: 1, indent: indent, contentIndent: 0, empty: false)
143 } else {
144 let digits = rest.prefix { $0.isASCII && $0.isNumber }
145 guard (1...9).contains(digits.count), digits.count < rest.count else { return nil }
146 let delimiter = rest[digits.count]
147 guard delimiter == "." || delimiter == ")" else { return nil }
148 width = digits.count + 1
149 marker = ListMarker(ordered: true, delimiter: delimiter, start: Int(String(digits)) ?? 1, indent: indent, contentIndent: 0, empty: false)
150 }
151 let after = rest.dropFirst(width)
152 if after.isEmpty {
153 marker.empty = true
154 marker.contentIndent = indent + width + 1
155 return marker
156 }
157 guard after.first == " " else { return nil }
158 let spaces = after.prefix { $0 == " " }.count
159 if spaces == after.count {
160 marker.empty = true
161 marker.contentIndent = indent + width + 1
162 } else {
163 marker.contentIndent = indent + width + (spaces > 4 ? 1 : spaces)
164 }
165 return marker
166 }
167
168 static func isQuote(_ line: String) -> Bool {
169 indent(line) <= 3 && line.drop { $0 == " " }.first == ">"
170 }
171
172 static func stripQuote(_ line: String) -> String {
173 var rest = line.drop { $0 == " " }.dropFirst()
174 if rest.first == " " { rest = rest.dropFirst() }
175 return String(rest)
176 }
177
178 static func tableCells(_ line: String) -> [String] {
179 var text = line.trimmingCharacters(in: .whitespaces)
180 if text.hasPrefix("|") { text.removeFirst() }
181 if text.hasSuffix("|"), !text.hasSuffix("\\|") { text.removeLast() }
182 var cells: [String] = []
183 var current = ""
184 var inCode = false
185 var escaped = false
186 for char in text {
187 if escaped {
188 if char == "|" {
189 current.append("\u{1}")
190 } else {
191 current.append("\\")
192 current.append(char)
193 }
194 escaped = false
195 continue
196 }
197 switch char {
198 case "\\": escaped = true
199 case "`":
200 inCode.toggle()
201 current.append(char)
202 case "|" where !inCode:
203 cells.append(current.trimmingCharacters(in: .whitespaces))
204 current = ""
205 default: current.append(char)
206 }
207 }
208 if escaped { current.append("\\") }
209 cells.append(current.trimmingCharacters(in: .whitespaces))
210 return cells
211 }
212
213 static func isDelimiterRow(_ line: String) -> Bool {
214 guard line.contains("-") else { return false }
215 let cells = tableCells(line)
216 return !cells.isEmpty && cells.allSatisfy { cell in
217 var body = Substring(cell)
218 if body.hasPrefix(":") { body = body.dropFirst() }
219 if body.hasSuffix(":") { body = body.dropLast() }
220 return !body.isEmpty && body.allSatisfy { $0 == "-" }
221 }
222 }
223
224 static func tableStarts(_ lines: [String], at i: Int) -> Bool {
225 i + 1 < lines.count && indent(lines[i]) <= 3 && lines[i].contains("|") && isDelimiterRow(lines[i + 1])
226 && tableCells(lines[i]).count == tableCells(lines[i + 1]).count
227 }
228
229 static let htmlBlockTags: Set<String> = [
230 "address", "article", "aside", "blockquote", "center", "details", "dialog", "div", "dl", "fieldset", "figcaption", "figure",
231 "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "iframe", "li", "main", "nav", "ol", "p", "pre",
232 "section", "summary", "table", "tbody", "td", "th", "thead", "tr", "ul", "video", "audio", "picture", "script", "style", "br", "img"
233 ]
234
235 static func htmlBlockStart(_ line: String) -> Bool {
236 guard indent(line) <= 3 else { return false }
237 let rest = line.drop { $0 == " " }
238 guard rest.hasPrefix("<") else { return false }
239 if rest.hasPrefix("<!--") { return true }
240 let name = rest.dropFirst().drop { $0 == "/" }.prefix { $0.isLetter || $0.isNumber || $0 == "-" }.lowercased()
241 guard !name.isEmpty else { return false }
242 if htmlBlockTags.contains(name) { return true }
243 // Any other tag alone on its line.
244 let trimmed = rest.trimmingCharacters(in: .whitespaces)
245 return trimmed.hasSuffix(">") && !trimmed.dropFirst().contains("<")
246 }
247
248 static func footnoteDefinition(_ line: String) -> (label: String, rest: String)? {
249 guard indent(line) <= 3 else { return nil }
250 let rest = line.drop { $0 == " " }
251 guard rest.hasPrefix("[^"), let close = rest.firstIndex(of: "]") else { return nil }
252 let label = rest[rest.index(rest.startIndex, offsetBy: 2)..<close]
253 let after = rest[rest.index(after: close)...]
254 guard !label.isEmpty, !label.contains(" "), after.hasPrefix(":") else { return nil }
255 return (String(label), after.dropFirst().trimmingCharacters(in: .whitespaces))
256 }
257
258 static func linkDefinition(_ line: String) -> (label: String, destination: String)? {
259 guard indent(line) <= 3 else { return nil }
260 let rest = line.drop { $0 == " " }
261 guard rest.hasPrefix("["), !rest.hasPrefix("[^"), let close = rest.firstIndex(of: "]") else { return nil }
262 let label = rest[rest.index(after: rest.startIndex)..<close]
263 let after = rest[rest.index(after: close)...]
264 guard !label.trimmingCharacters(in: .whitespaces).isEmpty, after.hasPrefix(":") else { return nil }
265 let body = after.dropFirst().trimmingCharacters(in: .whitespaces)
266 guard !body.isEmpty else { return nil }
267 var destination: String
268 var remainder: Substring
269 if body.hasPrefix("<"), let end = body.firstIndex(of: ">") {
270 destination = String(body[body.index(after: body.startIndex)..<end])
271 remainder = body[body.index(after: end)...]
272 } else {
273 destination = String(body.prefix { $0 != " " })
274 remainder = body.dropFirst(destination.count)
275 }
276 let title = remainder.trimmingCharacters(in: .whitespaces)
277 guard title.isEmpty || title.first == "\"" || title.first == "'" || title.first == "(" else { return nil }
278 if destination.isEmpty { destination = "" }
279 return (normalizeLabel(String(label)), destination)
280 }
281
282 static func normalizeLabel(_ label: String) -> String {
283 label.lowercased().split(whereSeparator: { $0 == " " || $0 == "\n" }).joined(separator: " ")
284 }
285
286 /// Whether `line` starts a block that ends a paragraph above it.
287 func interruptsParagraph(_ lines: [String], at i: Int) -> Bool {
288 let line = lines[i]
289 if Self.atxHeading(line) != nil || Self.fence(line) != nil || Self.isQuote(line) || Self.isRule(line) || Self.htmlBlockStart(line) {
290 return true
291 }
292 if let marker = Self.listMarker(line), !marker.empty, marker.indent <= 3, !marker.ordered || marker.start == 1 { return true }
293 if Self.tableStarts(lines, at: i) { return true }
294 if line.trimmingCharacters(in: .whitespaces).hasPrefix("$$") { return true }
295 return false
296 }
297
298 // MARK: - Blocks
299
300 mutating func blocks(_ lines: [String]) -> [MarkdownBlock] {
301 var out: [MarkdownBlock] = []
302 var i = 0
303 while i < lines.count {
304 let line = lines[i]
305 if Self.isBlank(line) {
306 i += 1
307 continue
308 }
309 if let fence = Self.fence(line) {
310 var body: [String] = []
311 i += 1
312 while i < lines.count {
313 if let close = Self.fence(lines[i]), close.char == fence.char, close.count >= fence.count, close.info.isEmpty { break }
314 let content = lines[i]
315 body.append(String(content.dropFirst(min(fence.indent, Self.indent(content)))))
316 i += 1
317 }
318 i += 1
319 let lang = fence.info.split(separator: " ").first.map { String($0).trimmingCharacters(in: CharacterSet(charactersIn: "{}.")) } ?? ""
320 out.append(.code(lang: lang, lines: body, fenced: true))
321 continue
322 }
323 let trimmed = line.trimmingCharacters(in: .whitespaces)
324 if trimmed.hasPrefix("$$") {
325 var body: [String] = []
326 var first = String(trimmed.dropFirst(2))
327 if first.hasSuffix("$$"), first.count >= 2 {
328 first.removeLast(2)
329 out.append(.math([first.trimmingCharacters(in: .whitespaces)].filter { !$0.isEmpty }))
330 i += 1
331 continue
332 }
333 if !first.trimmingCharacters(in: .whitespaces).isEmpty { body.append(first) }
334 i += 1
335 while i < lines.count {
336 let current = lines[i].trimmingCharacters(in: .whitespaces)
337 if current.hasSuffix("$$") {
338 let last = String(current.dropLast(2))
339 if !last.trimmingCharacters(in: .whitespaces).isEmpty { body.append(last) }
340 break
341 }
342 body.append(lines[i])
343 i += 1
344 }
345 i += 1
346 out.append(.math(body))
347 continue
348 }
349 if obsidian, trimmed.hasPrefix("%%") {
350 var body: [String] = []
351 var first = String(trimmed.dropFirst(2))
352 if first.hasSuffix("%%") {
353 first.removeLast(2)
354 out.append(.comment([first.trimmingCharacters(in: .whitespaces)]))
355 i += 1
356 continue
357 }
358 if !first.isEmpty { body.append(first) }
359 i += 1
360 while i < lines.count {
361 let current = lines[i].trimmingCharacters(in: .whitespaces)
362 if current.hasSuffix("%%") {
363 let last = String(current.dropLast(2))
364 if !last.isEmpty { body.append(last) }
365 break
366 }
367 body.append(lines[i])
368 i += 1
369 }
370 i += 1
371 out.append(.comment(body))
372 continue
373 }
374 if trimmed.hasPrefix("<!--") {
375 var body: [String] = []
376 while i < lines.count {
377 body.append(lines[i])
378 i += 1
379 if body.last!.contains("-->") { break }
380 }
381 var text = body.joined(separator: "\n").trimmingCharacters(in: .whitespaces)
382 if text.hasSuffix("-->"), text.hasPrefix("<!--") {
383 text = String(text.dropFirst(4).dropLast(3))
384 out.append(.comment(text.split(separator: "\n", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
385 .drop { $0.isEmpty }.reversed().drop { $0.isEmpty }.reversed()))
386 } else {
387 out.append(.html(body))
388 }
389 continue
390 }
391 if let heading = Self.atxHeading(line) {
392 out.append(.heading(level: heading.level, text: heading.text))
393 i += 1
394 continue
395 }
396 if Self.isRule(line) {
397 out.append(.rule)
398 i += 1
399 continue
400 }
401 if Self.isQuote(line) {
402 var inner: [String] = []
403 while i < lines.count {
404 let current = lines[i]
405 if Self.isQuote(current) {
406 inner.append(Self.stripQuote(current))
407 } else if !Self.isBlank(current), let last = inner.last, !Self.isBlank(last), !interruptsParagraph(lines, at: i) {
408 inner.append(current)
409 } else {
410 break
411 }
412 i += 1
413 }
414 out.append(quote(inner))
415 continue
416 }
417 if let marker = Self.listMarker(line), marker.indent <= 3 {
418 out.append(list(lines, at: &i, first: marker))
419 continue
420 }
421 if Self.htmlBlockStart(line) {
422 var body: [String] = []
423 while i < lines.count, !Self.isBlank(lines[i]) {
424 body.append(lines[i])
425 i += 1
426 }
427 out.append(.html(body))
428 continue
429 }
430 if Self.indent(line) >= 4 {
431 var body: [String] = []
432 while i < lines.count, Self.isBlank(lines[i]) || Self.indent(lines[i]) >= 4 {
433 body.append(String(lines[i].dropFirst(min(4, Self.indent(lines[i])))))
434 i += 1
435 }
436 while body.last.map(Self.isBlank) == true { body.removeLast() }
437 out.append(.code(lang: "", lines: body, fenced: false))
438 continue
439 }
440 if let footnote = Self.footnoteDefinition(line) {
441 var inner = [footnote.rest]
442 i += 1
443 while i < lines.count {
444 let current = lines[i]
445 if Self.isBlank(current) {
446 if i + 1 < lines.count, Self.indent(lines[i + 1]) >= 4 {
447 inner.append("")
448 i += 1
449 continue
450 }
451 break
452 }
453 if Self.indent(current) >= 4 {
454 inner.append(String(current.dropFirst(4)))
455 } else if Self.footnoteDefinition(current) == nil, !interruptsParagraph(lines, at: i) {
456 inner.append(current)
457 } else {
458 break
459 }
460 i += 1
461 }
462 definitions.footnotes.append((footnote.label, blocks(inner)))
463 continue
464 }
465 if Self.tableStarts(lines, at: i) {
466 let header = Self.tableCells(line)
467 var rows: [[String]] = []
468 i += 2
469 while i < lines.count, !Self.isBlank(lines[i]), lines[i].contains("|") || !interruptsParagraph(lines, at: i) {
470 if interruptsParagraph(lines, at: i), !lines[i].contains("|") { break }
471 var cells = Self.tableCells(lines[i])
472 if cells.count < header.count { cells += Array(repeating: "", count: header.count - cells.count) }
473 rows.append(Array(cells.prefix(header.count)))
474 i += 1
475 }
476 out.append(.table(header: header, rows: rows))
477 continue
478 }
479 // A paragraph, after any link reference definitions at its start.
480 var paragraph: [String] = []
481 while i < lines.count, !Self.isBlank(lines[i]) {
482 if paragraph.isEmpty, let definition = Self.linkDefinition(lines[i]) {
483 if definitions.links[definition.label] == nil { definitions.links[definition.label] = definition.destination }
484 i += 1
485 continue
486 }
487 if !paragraph.isEmpty {
488 if let level = Self.setextLevel(lines[i]) {
489 out.append(.heading(level: level, text: paragraph.map { $0.trimmingCharacters(in: .whitespaces) }.joined(separator: " ")))
490 paragraph = []
491 i += 1
492 break
493 }
494 if interruptsParagraph(lines, at: i) { break }
495 } else if Self.footnoteDefinition(lines[i]) != nil {
496 break
497 }
498 paragraph.append(String(lines[i].drop { $0 == " " }))
499 i += 1
500 }
501 if !paragraph.isEmpty { out.append(.paragraph(paragraph)) }
502 }
503 return out
504 }
505
506 private mutating func quote(_ inner: [String]) -> MarkdownBlock {
507 if obsidian, let first = inner.first?.trimmingCharacters(in: .whitespaces), first.hasPrefix("[!"), let close = first.firstIndex(of: "]") {
508 let type = first[first.index(first.startIndex, offsetBy: 2)..<close]
509 if !type.isEmpty, type.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" }) {
510 var title = first[first.index(after: close)...]
511 if title.first == "+" || title.first == "-" { title = title.dropFirst() }
512 return .callout(type: type.lowercased(), title: title.trimmingCharacters(in: .whitespaces), blocks: blocks(Array(inner.dropFirst())))
513 }
514 }
515 return .quote(blocks(inner))
516 }
517
518 /// A list starting at `i` with `first`'s marker; its items continue while lines are
519 /// indented to an item's content, or start another item with the same kind of marker.
520 private mutating func list(_ lines: [String], at i: inout Int, first: ListMarker) -> MarkdownBlock {
521 var items: [MarkdownItem] = []
522 var marker = first
523 while true {
524 let line = lines[i]
525 var content: [String] = [marker.empty ? "" : String(line.dropFirst(marker.contentIndent))]
526 i += 1
527 while i < lines.count {
528 let current = lines[i]
529 if Self.isBlank(current) {
530 // A blank line continues the item when an indented line follows.
531 var j = i
532 while j < lines.count, Self.isBlank(lines[j]) { j += 1 }
533 if j < lines.count, Self.indent(lines[j]) >= marker.contentIndent {
534 content += Array(repeating: "", count: j - i)
535 i = j
536 continue
537 }
538 break
539 }
540 if Self.indent(current) >= marker.contentIndent {
541 content.append(String(current.dropFirst(marker.contentIndent)))
542 i += 1
543 continue
544 }
545 if Self.listMarker(current) != nil || interruptsParagraph(lines, at: i) { break }
546 // A lazy continuation line of the item's paragraph.
547 if let last = content.last, !Self.isBlank(last), Self.fence(content.first ?? "") == nil {
548 content.append(String(current.drop { $0 == " " }))
549 i += 1
550 continue
551 }
552 break
553 }
554 var task: Character?
555 if let head = content.first {
556 let chars = Array(head)
557 if chars.count >= 3, chars[0] == "[", chars[2] == "]", chars.count == 3 || chars[3] == " " {
558 task = chars[1]
559 content[0] = String(head.dropFirst(min(4, chars.count)))
560 }
561 }
562 items.append(MarkdownItem(task: task, blocks: blocks(content)))
563 // A blank line between items is allowed.
564 var j = i
565 while j < lines.count, Self.isBlank(lines[j]) { j += 1 }
566 guard j < lines.count, let next = Self.listMarker(lines[j]), next.ordered == first.ordered, next.delimiter == first.delimiter,
567 next.indent <= 3, next.indent < first.contentIndent else { break }
568 i = j
569 marker = next
570 }
571 return .list(ordered: first.ordered, start: first.start, items: items)
572 }
573}
Sources/OrgCore/MarkdownImport/MarkdownFrontMatter.swift added +122 · view
@@ -0,0 +1,122 @@
1import Foundation
2
3/// YAML front matter between `---` lines at the top of a Markdown file. Reads the subset notes
4/// use: `key: value`, quoted strings, `[a, b]` and `- item` lists, and `|` and `>` blocks.
5/// Nested maps are kept as `nested`.
6enum MarkdownFrontMatter {
7 enum Value: Equatable, Sendable {
8 case scalar(String)
9 case list([String])
10 case nested
11 }
12
13 /// The entries and the text after the front matter; no entries and the whole text when
14 /// there is none.
15 static func split(_ text: String) -> (entries: [(key: String, value: Value)], body: String) {
16 guard text.hasPrefix("---") else { return ([], text) }
17 let lines = text.split(separator: "\n", omittingEmptySubsequences: false).map { $0.hasSuffix("\r") ? $0.dropLast() : $0 }
18 guard lines.first?.trimmingCharacters(in: .whitespaces) == "---",
19 let end = lines.dropFirst().firstIndex(where: { $0 == "---" || $0 == "..." }) else { return ([], text) }
20 let body = lines[(end + 1)...].joined(separator: "\n")
21 return (parse(lines[1..<end].map(String.init)), body)
22 }
23
24 static func parse(_ lines: [String]) -> [(key: String, value: Value)] {
25 var entries: [(key: String, value: Value)] = []
26 var i = 0
27 while i < lines.count {
28 let line = lines[i]
29 i += 1
30 guard !line.hasPrefix(" "), !line.hasPrefix("#"), let colon = keyColon(line) else { continue }
31 let key = unquote(String(line[..<colon]).trimmingCharacters(in: .whitespaces))
32 let rest = stripComment(String(line[line.index(after: colon)...])).trimmingCharacters(in: .whitespaces)
33 var nested: [String] = []
34 while i < lines.count, lines[i].hasPrefix(" ") || lines[i].hasPrefix("-") || lines[i].trimmingCharacters(in: .whitespaces).isEmpty {
35 nested.append(lines[i])
36 i += 1
37 }
38 while nested.last?.trimmingCharacters(in: .whitespaces).isEmpty == true { nested.removeLast() }
39 if rest == "|" || rest == ">" || rest.hasPrefix("|") || rest.hasPrefix(">") {
40 let indent = nested.compactMap { $0.trimmingCharacters(in: .whitespaces).isEmpty ? nil : $0.prefix { $0 == " " }.count }.min() ?? 0
41 let body = nested.map { String($0.dropFirst(min(indent, $0.prefix { $0 == " " }.count))) }
42 entries.append((key, .scalar(body.joined(separator: rest.hasPrefix("|") ? "\n" : " "))))
43 } else if !rest.isEmpty {
44 if rest.hasPrefix("["), rest.hasSuffix("]") {
45 entries.append((key, .list(flowItems(String(rest.dropFirst().dropLast())))))
46 } else if rest.hasPrefix("{") {
47 entries.append((key, .nested))
48 } else {
49 entries.append((key, .scalar(unquote(rest))))
50 }
51 } else if nested.isEmpty {
52 entries.append((key, .scalar("")))
53 } else if nested.allSatisfy({ $0.trimmingCharacters(in: .whitespaces).hasPrefix("-") || $0.trimmingCharacters(in: .whitespaces).isEmpty }) {
54 let items = nested.compactMap { line -> String? in
55 let item = line.trimmingCharacters(in: .whitespaces)
56 guard item.hasPrefix("-") else { return nil }
57 return unquote(stripComment(String(item.dropFirst())).trimmingCharacters(in: .whitespaces))
58 }
59 entries.append((key, .list(items.filter { !$0.isEmpty })))
60 } else {
61 entries.append((key, .nested))
62 }
63 }
64 return entries
65 }
66
67 /// The colon ending a key: the first one outside quotes followed by a space or the end.
68 private static func keyColon(_ line: String) -> String.Index? {
69 var quote: Character?
70 var index = line.startIndex
71 while index < line.endIndex {
72 let char = line[index]
73 if let open = quote {
74 if char == open { quote = nil }
75 } else if char == "\"" || char == "'" {
76 quote = char
77 } else if char == ":" {
78 let next = line.index(after: index)
79 if next == line.endIndex || line[next] == " " { return index }
80 }
81 index = line.index(after: index)
82 }
83 return nil
84 }
85
86 private static func stripComment(_ value: String) -> String {
87 guard !value.trimmingCharacters(in: .whitespaces).hasPrefix("\""), !value.trimmingCharacters(in: .whitespaces).hasPrefix("'"),
88 let range = value.range(of: " #") else { return value }
89 return String(value[..<range.lowerBound])
90 }
91
92 static func unquote(_ value: String) -> String {
93 if value.count >= 2, let first = value.first, first == "\"" || first == "'", value.last == first {
94 let inner = String(value.dropFirst().dropLast())
95 return first == "'" ? inner.replacingOccurrences(of: "''", with: "'")
96 : inner.replacingOccurrences(of: "\\\"", with: "\"").replacingOccurrences(of: "\\\\", with: "\\")
97 }
98 return value
99 }
100
101 private static func flowItems(_ text: String) -> [String] {
102 var items: [String] = []
103 var current = ""
104 var quote: Character?
105 for char in text {
106 if let open = quote {
107 current.append(char)
108 if char == open { quote = nil }
109 } else if char == "\"" || char == "'" {
110 quote = char
111 current.append(char)
112 } else if char == "," {
113 items.append(current)
114 current = ""
115 } else {
116 current.append(char)
117 }
118 }
119 items.append(current)
120 return items.map { unquote($0.trimmingCharacters(in: .whitespaces)) }.filter { !$0.isEmpty }
121 }
122}
Sources/OrgCore/MarkdownImport/MarkdownInline.swift added +431 · view
@@ -0,0 +1,431 @@
1import Foundation
2
3/// Converts Markdown inline text to org: emphasis, code, links, images, footnote references,
4/// math and entities; with `obsidian`, also wikilinks, embeds, highlights and `#tags`.
5final class MarkdownInline {
6 let obsidian: Bool
7 let definitions: [String: String]
8 let targets: MarkdownTargets
9 /// Links written, wikilinks and embeds included.
10 var links = 0
11 /// `#tags` found since the last `takeTags`.
12 private(set) var tags: [String] = []
13 var issues: [MarkdownImportIssue] = []
14
15 init(obsidian: Bool, definitions: [String: String], targets: MarkdownTargets) {
16 self.obsidian = obsidian
17 self.definitions = definitions
18 self.targets = targets
19 }
20
21 func takeTags() -> [String] {
22 defer { tags = [] }
23 return tags
24 }
25
26 func convert(_ text: String) -> String {
27 convert(Array(text)[...])
28 }
29
30 private func convert(_ chars: ArraySlice<Character>) -> String {
31 var out = ""
32 var i = chars.startIndex
33 let end = chars.endIndex
34 func at(_ k: Int) -> Character? { k >= chars.startIndex && k < end ? chars[k] : nil }
35 while i < end {
36 let c = chars[i]
37 switch c {
38 case "\\":
39 if let next = at(i + 1), next.isASCII, next.isPunctuation || next.isSymbol {
40 out.append(next)
41 i += 2
42 continue
43 }
44 case "`":
45 let run = runLength(chars, i, "`")
46 if let close = findRun(chars, from: i + run, "`", run) {
47 var body = String(chars[(i + run)..<close]).replacingOccurrences(of: "\n", with: " ")
48 if body.count >= 2, body.first == " ", body.last == " ", body.contains(where: { $0 != " " }) { body = String(body.dropFirst().dropLast()) }
49 out += code(body)
50 i = close + run
51 continue
52 }
53 out += String(repeating: "`", count: run)
54 i += run
55 continue
56 case "$":
57 if let math = math(chars, i) {
58 out += math.text
59 i = math.end
60 continue
61 }
62 case "!":
63 if obsidian, at(i + 1) == "[", at(i + 2) == "[", let close = findClose(chars, from: i + 3, "]]") {
64 out += wikilink(String(chars[(i + 3)..<close]), embed: true)
65 i = close + 2
66 continue
67 }
68 if at(i + 1) == "[", let link = link(chars, i + 1) {
69 out += image(destination: link.destination, alt: link.text)
70 i = link.end
71 continue
72 }
73 case "^":
74 if at(i + 1) == "[", let close = matchingBracket(chars, i + 1) {
75 out += "[fn:: " + convert(chars[(i + 2)..<close]) + "]"
76 i = close + 1
77 continue
78 }
79 case "[":
80 if obsidian, at(i + 1) == "[", let close = findClose(chars, from: i + 2, "]]") {
81 out += wikilink(String(chars[(i + 2)..<close]), embed: false)
82 i = close + 2
83 continue
84 }
85 if at(i + 1) == "^", let close = chars[i...].firstIndex(of: "]"), close > i + 2,
86 !chars[(i + 2)..<close].contains(where: { $0 == " " || $0 == "\n" }) {
87 out += "[fn:" + MarkdownToOrg.footnoteLabel(String(chars[(i + 2)..<close])) + "]"
88 i = close + 1
89 continue
90 }
91 if let link = link(chars, i) {
92 out += linkText(destination: link.destination, text: link.text)
93 i = link.end
94 continue
95 }
96 case "<":
97 if let close = chars[i...].firstIndex(of: ">") {
98 let inner = String(chars[(i + 1)..<close])
99 if !inner.contains(" "), !inner.contains("\n"), let colon = inner.firstIndex(of: ":"),
100 inner[..<colon].allSatisfy({ $0.isLetter || $0.isNumber || "+.-".contains($0) }), inner.distance(from: inner.startIndex, to: colon) >= 2 {
101 links += 1
102 out += "[[" + MarkdownToOrg.escapeLinkPath(inner) + "]]"
103 i = close + 1
104 continue
105 }
106 if !inner.contains(" "), inner.contains("@"), inner.contains(".") {
107 links += 1
108 out += "[[mailto:" + inner + "]]"
109 i = close + 1
110 continue
111 }
112 if let first = inner.first, first.isLetter || first == "/" || first == "!" {
113 out += "@@html:<" + inner + ">@@"
114 i = close + 1
115 continue
116 }
117 }
118 case "&":
119 if let entity = entity(chars, i) {
120 out += entity.text
121 i = entity.end
122 continue
123 }
124 case "*", "_":
125 if let emphasis = emphasis(chars, i, c, previous: at(i - 1)) {
126 out += emphasis.text
127 i = emphasis.end
128 continue
129 }
130 let run = runLength(chars, i, c)
131 out += String(repeating: c, count: run)
132 i += run
133 continue
134 case "~":
135 if at(i + 1) == "~", at(i + 2).map({ !$0.isWhitespace }) == true, let close = findDelimiter(chars, from: i + 2, "~", 2) {
136 out += "+" + convert(chars[(i + 2)..<close]) + "+"
137 i = close + 2
138 continue
139 }
140 case "=":
141 if obsidian, at(i + 1) == "=", at(i + 2).map({ !$0.isWhitespace }) == true, let close = findDelimiter(chars, from: i + 2, "=", 2) {
142 out += "*" + convert(chars[(i + 2)..<close]) + "*"
143 i = close + 2
144 continue
145 }
146 case "#":
147 if obsidian, at(i - 1).map({ $0.isWhitespace || $0 == "(" }) ?? true {
148 var j = i + 1
149 while let next = at(j), next.isLetter || next.isNumber || next == "_" || next == "-" || next == "/" { j += 1 }
150 let tag = String(chars[(i + 1)..<j])
151 if !tag.isEmpty, tag.contains(where: { !$0.isNumber }) {
152 tags.append(MarkdownToOrg.tag(tag))
153 out += "#" + tag
154 i = j
155 continue
156 }
157 }
158 default:
159 break
160 }
161 out.append(c)
162 i += 1
163 }
164 return out
165 }
166
167 // MARK: - Pieces
168
169 private func code(_ body: String) -> String {
170 if !body.contains("~") { return "~" + body + "~" }
171 if !body.contains("=") { return "=" + body + "=" }
172 return "~" + body + "~"
173 }
174
175 private func runLength(_ chars: ArraySlice<Character>, _ i: Int, _ c: Character) -> Int {
176 var j = i
177 while j < chars.endIndex, chars[j] == c { j += 1 }
178 return j - i
179 }
180
181 /// A run of exactly `count` `c`s at or after `from`.
182 private func findRun(_ chars: ArraySlice<Character>, from: Int, _ c: Character, _ count: Int) -> Int? {
183 var j = from
184 while j < chars.endIndex {
185 if chars[j] == c {
186 let run = runLength(chars, j, c)
187 if run == count { return j }
188 j += run
189 } else {
190 j += 1
191 }
192 }
193 return nil
194 }
195
196 private func findClose(_ chars: ArraySlice<Character>, from: Int, _ close: String) -> Int? {
197 let pattern = Array(close)
198 var j = from
199 while j + pattern.count <= chars.endIndex {
200 if chars[j] == "\n" { return nil }
201 if Array(chars[j..<(j + pattern.count)]) == pattern { return j }
202 j += 1
203 }
204 return nil
205 }
206
207 /// The `]` matching the `[` at `open`, skipping code spans and escapes.
208 private func matchingBracket(_ chars: ArraySlice<Character>, _ open: Int) -> Int? {
209 var depth = 0
210 var j = open
211 while j < chars.endIndex {
212 switch chars[j] {
213 case "\\": j += 1
214 case "`":
215 let run = runLength(chars, j, "`")
216 if let close = findRun(chars, from: j + run, "`", run) { j = close + run - 1 } else { j += run - 1 }
217 case "[": depth += 1
218 case "]":
219 depth -= 1
220 if depth == 0 { return j }
221 default: break
222 }
223 j += 1
224 }
225 return nil
226 }
227
228 /// A closing delimiter run of `count` `c`s after a non-space, skipping code spans.
229 private func findDelimiter(_ chars: ArraySlice<Character>, from: Int, _ c: Character, _ count: Int) -> Int? {
230 var j = from
231 while j < chars.endIndex {
232 let char = chars[j]
233 if char == "\\" {
234 j += 2
235 continue
236 }
237 if char == "`" {
238 let run = runLength(chars, j, "`")
239 if let close = findRun(chars, from: j + run, "`", run) { j = close + run } else { j += run }
240 continue
241 }
242 if char == "[", let close = matchingBracket(chars, j) {
243 // Links and their destinations are skipped whole.
244 j = close + 1
245 if j < chars.endIndex, chars[j] == "(", let paren = destinationEnd(chars, j) { j = paren + 1 }
246 continue
247 }
248 if char == c {
249 let run = runLength(chars, j, c)
250 let before = chars[j - 1]
251 let after = j + run < chars.endIndex ? chars[j + run] : nil
252 if run == count, j > from, !before.isWhitespace, c != "_" || !(after.map { $0.isLetter || $0.isNumber } ?? false) { return j }
253 j += run
254 continue
255 }
256 j += 1
257 }
258 return nil
259 }
260
261 private func emphasis(_ chars: ArraySlice<Character>, _ i: Int, _ c: Character, previous: Character?) -> (text: String, end: Int)? {
262 let run = runLength(chars, i, c)
263 guard (1...3).contains(run), i + run < chars.endIndex, !chars[i + run].isWhitespace else { return nil }
264 if c == "_", let previous, previous.isLetter || previous.isNumber { return nil }
265 guard let close = findDelimiter(chars, from: i + run, c, run) else { return nil }
266 let body = convert(chars[(i + run)..<close])
267 guard !body.isEmpty else { return nil }
268 switch run {
269 case 1: return ("/" + body + "/", close + 1)
270 case 2: return ("*" + body + "*", close + 2)
271 default: return ("*/" + body + "/*", close + 3)
272 }
273 }
274
275 private func math(_ chars: ArraySlice<Character>, _ i: Int) -> (text: String, end: Int)? {
276 var j = i + 1
277 if j < chars.endIndex, chars[j] == "$" {
278 j += 1
279 while j + 1 < chars.endIndex {
280 if chars[j] == "$", chars[j + 1] == "$" { return ("\\[" + String(chars[(i + 2)..<j]) + "\\]", j + 2) }
281 j += 1
282 }
283 return nil
284 }
285 guard j < chars.endIndex, !chars[j].isWhitespace, !chars[j].isNumber || obsidian else { return nil }
286 while j < chars.endIndex {
287 if chars[j] == "\n", j + 1 < chars.endIndex, chars[j + 1] == "\n" { return nil }
288 if chars[j] == "\\" {
289 j += 2
290 continue
291 }
292 if chars[j] == "$" {
293 let after = j + 1 < chars.endIndex ? chars[j + 1] : nil
294 if !chars[j - 1].isWhitespace, !(after?.isNumber ?? false) { return ("\\(" + String(chars[(i + 1)..<j]) + "\\)", j + 1) }
295 return nil
296 }
297 j += 1
298 }
299 return nil
300 }
301
302 private static let entities: [String: String] = ["amp": "&", "lt": "<", "gt": ">", "quot": "\"", "apos": "'", "nbsp": "\u{a0}", "copy": "©", "mdash": "—", "ndash": "–", "hellip": "…"]
303
304 private func entity(_ chars: ArraySlice<Character>, _ i: Int) -> (text: String, end: Int)? {
305 guard let semicolon = chars[i...].prefix(12).firstIndex(of: ";") else { return nil }
306 let name = String(chars[(i + 1)..<semicolon])
307 if let value = Self.entities[name] { return (value, semicolon + 1) }
308 if name.hasPrefix("#") {
309 let digits = name.dropFirst()
310 let value = digits.lowercased().hasPrefix("x") ? UInt32(digits.dropFirst(), radix: 16) : UInt32(digits)
311 if let value, let scalar = Unicode.Scalar(value) { return (String(Character(scalar)), semicolon + 1) }
312 }
313 return nil
314 }
315
316 /// The end of a `(destination "title")` starting at `open`, parentheses balanced.
317 private func destinationEnd(_ chars: ArraySlice<Character>, _ open: Int) -> Int? {
318 var depth = 0
319 var j = open
320 var angle = false
321 while j < chars.endIndex {
322 let char = chars[j]
323 if char == "\\" {
324 j += 2
325 continue
326 }
327 if char == "<", j == open + 1 { angle = true }
328 if angle, char == ">" { angle = false }
329 if !angle {
330 if char == "(" { depth += 1 }
331 if char == ")" {
332 depth -= 1
333 if depth == 0 { return j }
334 }
335 }
336 if char == "\n", j + 1 < chars.endIndex, chars[j + 1] == "\n" { return nil }
337 j += 1
338 }
339 return nil
340 }
341
342 /// `[text](destination)`, `[text][label]`, `[label][]` or `[label]` with a definition.
343 private func link(_ chars: ArraySlice<Character>, _ open: Int) -> (text: ArraySlice<Character>, destination: String, end: Int)? {
344 guard let close = matchingBracket(chars, open) else { return nil }
345 let text = chars[(open + 1)..<close]
346 let after = close + 1
347 if after < chars.endIndex, chars[after] == "(", let end = destinationEnd(chars, after) {
348 var inside = String(chars[(after + 1)..<end]).trimmingCharacters(in: .whitespacesAndNewlines)
349 var destination: String
350 if inside.hasPrefix("<"), let angle = inside.firstIndex(of: ">") {
351 destination = String(inside[inside.index(after: inside.startIndex)..<angle])
352 } else {
353 if let space = inside.firstIndex(where: { $0 == " " || $0 == "\n" }) {
354 let title = inside[space...].trimmingCharacters(in: .whitespacesAndNewlines)
355 if title.first == "\"" || title.first == "'" || title.first == "(" { inside = String(inside[..<space]) }
356 }
357 destination = inside
358 }
359 destination = destination.replacingOccurrences(of: "\\(", with: "(").replacingOccurrences(of: "\\)", with: ")")
360 return (text, destination, end + 1)
361 }
362 if after < chars.endIndex, chars[after] == "[", let labelClose = chars[after...].firstIndex(of: "]") {
363 var label = String(chars[(after + 1)..<labelClose])
364 if label.isEmpty { label = String(text) }
365 if let destination = definitions[MarkdownBlocks.normalizeLabel(label)] { return (text, destination, labelClose + 1) }
366 return nil
367 }
368 if let destination = definitions[MarkdownBlocks.normalizeLabel(String(text))] { return (text, destination, after) }
369 return nil
370 }
371
372 private static func isURL(_ destination: String) -> Bool {
373 guard let colon = destination.firstIndex(of: ":") else { return false }
374 let scheme = destination[..<colon]
375 return scheme.count >= 2 && scheme.allSatisfy { $0.isLetter || $0.isNumber || "+.-".contains($0) }
376 }
377
378 private func path(for destination: String, image: Bool) -> String {
379 if let resolved = targets.link(destination, image) { return resolved }
380 if Self.isURL(destination) { return destination }
381 let decoded = destination.removingPercentEncoding ?? destination
382 return decoded.hasPrefix("#") ? decoded : "file:" + decoded
383 }
384
385 private func linkText(destination: String, text: ArraySlice<Character>) -> String {
386 links += 1
387 var description = convert(text).replacingOccurrences(of: "\n", with: " ")
388 // An image as the description is written as its path, which org shows as the image.
389 if description.hasPrefix("[["), description.hasSuffix("]]"), description.components(separatedBy: "[[").count == 2, !description.contains("][") {
390 description = String(description.dropFirst(2).dropLast(2))
391 }
392 let target = path(for: destination, image: false)
393 let path = target.hasPrefix("#") ? "*" + target.dropFirst() : target
394 if description.isEmpty || description == destination { return "[[" + MarkdownToOrg.escapeLinkPath(path) + "]]" }
395 return "[[" + MarkdownToOrg.escapeLinkPath(path) + "][" + description.replacingOccurrences(of: "]]", with: "] ]") + "]]"
396 }
397
398 private func image(destination: String, alt: ArraySlice<Character>) -> String {
399 links += 1
400 return "[[" + MarkdownToOrg.escapeLinkPath(path(for: destination, image: true)) + "]]"
401 }
402
403 /// `target#heading|alias`, `target#^block` or `target|300` for an embedded image.
404 private func wikilink(_ body: String, embed: Bool) -> String {
405 var target = body
406 var alias: String?
407 if let bar = body.firstIndex(of: "|") {
408 target = String(body[..<bar])
409 alias = String(body[body.index(after: bar)...]).trimmingCharacters(in: .whitespaces)
410 }
411 var fragment: String?
412 if let hash = target.firstIndex(of: "#") {
413 fragment = String(target[target.index(after: hash)...])
414 target = String(target[..<hash])
415 }
416 target = target.trimmingCharacters(in: .whitespaces)
417 guard let resolved = targets.wikilink(target, fragment, embed) else {
418 issues.append(.unresolvedLink(body))
419 return alias ?? body
420 }
421 links += 1
422 if embed, resolved.image { return "[[" + MarkdownToOrg.escapeLinkPath(resolved.path) + "]]" }
423 var description = alias.flatMap { $0.allSatisfy(\.isNumber) || $0.isEmpty ? nil : $0 }
424 if description == nil {
425 let name = target.isEmpty ? "" : (target as NSString).lastPathComponent
426 let heading = fragment.map { $0.split(separator: "#").last.map(String.init) ?? $0 }?.trimmingCharacters(in: CharacterSet(charactersIn: "^"))
427 description = [name, heading].compactMap { $0?.isEmpty == false ? $0 : nil }.joined(separator: " > ")
428 }
429 return "[[" + MarkdownToOrg.escapeLinkPath(resolved.path) + "][" + (description ?? target) + "]]"
430 }
431}
Sources/OrgCore/MarkdownImport/MarkdownToOrg.swift added +487 · view
@@ -0,0 +1,487 @@
1import Foundation
2
3/// How links to other files are written; the importer knows where each file ends up.
4public struct MarkdownTargets: Sendable {
5 /// A Markdown link or image destination as written → the org link path, or `nil` to
6 /// write it as it is (`file:` added to a relative path).
7 public var link: @Sendable (_ destination: String, _ image: Bool) -> String?
8 /// An Obsidian wikilink or embed: the target as written (empty for the same note) and the
9 /// part after `#` → the org link path and whether it's an image; `nil` when it can't be
10 /// found, which writes the link's text.
11 public var wikilink: @Sendable (_ target: String, _ fragment: String?, _ embed: Bool) -> (path: String, image: Bool)?
12
13 public init(link: @escaping @Sendable (String, Bool) -> String?,
14 wikilink: @escaping @Sendable (String, String?, Bool) -> (path: String, image: Bool)?) {
15 self.link = link
16 self.wikilink = wikilink
17 }
18
19 /// Wikilinks to `target.org` beside the file; other links as written.
20 public static let none = MarkdownTargets(link: { _, _ in nil }, wikilink: { target, _, _ in
21 guard !target.isEmpty else { return nil }
22 let ext = (target as NSString).pathExtension.lowercased()
23 if ext.isEmpty || ext == "md" { return ("file:" + (ext.isEmpty ? target : (target as NSString).deletingPathExtension) + ".org", false) }
24 return ("file:" + target, MarkdownToOrg.imageExtensions.contains(ext))
25 })
26}
27
28/// Something in a Markdown file that wasn't converted, or was converted with a loss.
29public enum MarkdownImportIssue: Hashable, Sendable {
30 /// A wikilink or embed whose target isn't in the vault.
31 case unresolvedLink(String)
32 /// A link to a heading or block that isn't in the target file; the link goes to the file.
33 case missingHeading(String)
34 /// A front matter key with a nested map as its value.
35 case frontMatter(String)
36 /// A Tasks plugin recurrence (`🔁`), kept as text.
37 case recurrence
38 /// A task status other than space, `x` and `/`; the item is an open checkbox.
39 case taskStatus(String)
40 /// A heading inside a list or quote, written as a bold line.
41 case nestedHeading(String)
42 /// An attachment that couldn't be read.
43 case attachment(String)
44}
45
46/// Converts a Markdown file (CommonMark with GFM tables, task lists, strikethrough and
47/// footnotes, and YAML front matter) to an org file; with `obsidian`, Obsidian's wikilinks,
48/// embeds, callouts, `#tags`, highlights, comments, block IDs and Tasks plugin dates too.
49///
50/// Front matter: `title` → `#+title:`, `date` → `#+date:`, `tags` → `#+filetags:`,
51/// `aliases` → `ROAM_ALIASES`, and every other key → a property in a property drawer at the
52/// top of the file.
53public enum MarkdownToOrg {
54 public struct Parsed: Sendable {
55 let blocks: [MarkdownBlock]
56 let footnotes: [(label: String, blocks: [MarkdownBlock])]
57 let links: [String: String]
58 let frontMatter: [(key: String, value: MarkdownFrontMatter.Value)]
59 let obsidian: Bool
60 /// Each top-level heading's text as written and as an org title, for links to it.
61 public let headings: [(source: String, title: String)]
62 /// Obsidian block IDs (`^id`) in the file.
63 public let blockIDs: Set<String>
64 }
65
66 public struct Result: Sendable {
67 public var text: String
68 public var headings: Int
69 public var links: Int
70 public var issues: [MarkdownImportIssue]
71 }
72
73 public static func parse(_ markdown: String, obsidian: Bool) -> Parsed {
74 let (frontMatter, body) = MarkdownFrontMatter.split(markdown)
75 let (blocks, definitions) = MarkdownBlocks.parse(body, obsidian: obsidian)
76 let inline = MarkdownInline(obsidian: obsidian, definitions: definitions.links, targets: .none)
77 var headings: [(source: String, title: String)] = []
78 var ids = Set<String>()
79 func collectIDs(_ blocks: [MarkdownBlock]) {
80 for block in blocks {
81 switch block {
82 case .paragraph(let lines): if let id = blockID(lines.last ?? "")?.id { ids.insert(id) }
83 case .list(_, _, let items): items.forEach { collectIDs($0.blocks) }
84 case .quote(let inner), .callout(_, _, let inner): collectIDs(inner)
85 default: break
86 }
87 }
88 }
89 for block in blocks {
90 if case .heading(_, let text) = block {
91 headings.append((text, headingTitle(text, inline: inline).title))
92 }
93 }
94 if obsidian { collectIDs(blocks) }
95 return Parsed(blocks: blocks, footnotes: definitions.footnotes, links: definitions.links, frontMatter: frontMatter,
96 obsidian: obsidian, headings: headings, blockIDs: ids)
97 }
98
99 /// `parsed` as an org file. `title` is the fallback for `#+title:` when the front matter
100 /// has none.
101 public static func render(_ parsed: Parsed, title: String? = nil, targets: MarkdownTargets = .none) -> Result {
102 var renderer = Renderer(parsed: parsed, inline: MarkdownInline(obsidian: parsed.obsidian, definitions: parsed.links, targets: targets))
103 return renderer.document(title: title)
104 }
105
106 public static func convert(_ markdown: String, obsidian: Bool = false, title: String? = nil, targets: MarkdownTargets = .none) -> Result {
107 render(parse(markdown, obsidian: obsidian), title: title, targets: targets)
108 }
109
110 /// The org title of the heading `fragment` names (its text, or GitHub's anchor for it).
111 public static func heading(_ fragment: String, in headings: [(source: String, title: String)]) -> String? {
112 let wanted = squash(fragment.removingPercentEncoding ?? fragment)
113 guard !wanted.isEmpty else { return nil }
114 return headings.first { squash($0.source) == wanted }?.title ?? headings.first { squash($0.title) == wanted }?.title
115 }
116
117 private static func squash(_ text: String) -> String {
118 String(text.lowercased().filter { $0.isLetter || $0.isNumber })
119 }
120
121 // MARK: - Shared pieces
122
123 static func escapeLinkPath(_ path: String) -> String {
124 path.replacingOccurrences(of: "[", with: "\\[").replacingOccurrences(of: "]", with: "\\]")
125 }
126
127 static func footnoteLabel(_ label: String) -> String {
128 String(label.map { $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" ? $0 : "_" })
129 }
130
131 /// An org tag for an Obsidian or front matter tag: characters org doesn't allow become `_`.
132 static func tag(_ tag: String) -> String {
133 String(tag.drop { $0 == "#" }.map { $0.isLetter || $0.isNumber || "_@#%".contains($0) ? $0 : "_" })
134 }
135
136 /// A trailing Obsidian block ID (` ^id`).
137 static func blockID(_ line: String) -> (id: String, rest: String)? {
138 guard let caret = line.range(of: " ^", options: .backwards) ?? (line.hasPrefix("^") ? line.startIndex..<line.index(after: line.startIndex) : nil) else { return nil }
139 let id = line[caret.upperBound...].trimmingCharacters(in: .whitespaces)
140 guard !id.isEmpty, id.allSatisfy({ ($0.isASCII && ($0.isLetter || $0.isNumber)) || $0 == "-" }) else { return nil }
141 return (id, String(line[..<caret.lowerBound]))
142 }
143
144 /// A heading's org title and the `#tags` at its end.
145 static func headingTitle(_ text: String, inline: MarkdownInline) -> (title: String, tags: [String]) {
146 var words = text.split(separator: " ", omittingEmptySubsequences: false).map(String.init)
147 var trailing: [String] = []
148 if inline.obsidian {
149 while let last = words.last, last.hasPrefix("#"), last.count > 1, last.dropFirst().contains(where: { !$0.isNumber }),
150 last.dropFirst().allSatisfy({ $0.isLetter || $0.isNumber || "_-/".contains($0) }) {
151 trailing.insert(tag(last), at: 0)
152 words.removeLast()
153 }
154 }
155 _ = inline.takeTags()
156 let title = inline.convert(words.joined(separator: " ").trimmingCharacters(in: .whitespaces))
157 return (title, trailing + inline.takeTags().filter { !trailing.contains($0) })
158 }
159
160 public static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "bmp", "tif", "tiff", "heic", "avif"]
161
162 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
163
164 /// `<2024-01-05 Fri>` for `2024-01-05`, with `[` `]` when not active.
165 static func timestamp(_ date: String, active: Bool) -> String? {
166 let parts = date.split(separator: "-").compactMap { Int($0) }
167 guard parts.count == 3, date.count == 10 else { return nil }
168 var calendar = Calendar(identifier: .gregorian)
169 calendar.timeZone = TimeZone(identifier: "UTC")!
170 guard let day = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2])) else { return nil }
171 let name = weekdays[calendar.component(.weekday, from: day) - 1]
172 return (active ? "<" : "[") + date + " " + name + (active ? ">" : "]")
173 }
174
175 // MARK: - Rendering
176
177 struct Renderer {
178 let parsed: Parsed
179 let inline: MarkdownInline
180 var lines: [String] = []
181 var headings = 0
182 var issues: [MarkdownImportIssue] = []
183 /// Output line of each heading, and the tags found in its section.
184 var headingLines: [(line: Int, tags: [String])] = []
185 var fileTags: [String] = []
186
187 init(parsed: Parsed, inline: MarkdownInline) {
188 self.parsed = parsed
189 self.inline = inline
190 }
191
192 mutating func document(title fallback: String?) -> Result {
193 var previous: MarkdownBlock?
194 for block in parsed.blocks {
195 defer { previous = block }
196 if !lines.isEmpty {
197 if case .heading = previous {} else { lines.append("") }
198 if Self.listsInARow(previous, block) { lines.append("") }
199 }
200 if case .heading(let level, let text) = block {
201 let heading = MarkdownToOrg.headingTitle(text, inline: inline)
202 headingLines.append((lines.count, heading.tags))
203 lines.append(String(repeating: "*", count: level) + " " + heading.title)
204 headings += 1
205 continue
206 }
207 lines += render(block, indent: "")
208 let tags = inline.takeTags()
209 if headingLines.isEmpty { fileTags += tags } else { headingLines[headingLines.count - 1].tags += tags }
210 }
211 for (label, blocks) in parsed.footnotes {
212 if !lines.isEmpty { lines.append("") }
213 var body = blocks.enumerated().flatMap { index, block in (index > 0 ? [""] : []) + render(block, indent: "") }
214 if body.isEmpty { body = [""] }
215 body[0] = "[fn:" + MarkdownToOrg.footnoteLabel(label) + "] " + body[0].drop { $0 == " " }
216 lines += body
217 let tags = inline.takeTags()
218 if headingLines.isEmpty { fileTags += tags } else { headingLines[headingLines.count - 1].tags += tags }
219 }
220 for (line, tags) in headingLines {
221 let unique = tags.reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } }
222 if !unique.isEmpty { lines[line] += " :" + unique.joined(separator: ":") + ":" }
223 }
224 let header = header(fallback: fallback)
225 var text = header.joined(separator: "\n")
226 if !header.isEmpty, !lines.isEmpty { text += "\n\n" }
227 text += lines.joined(separator: "\n")
228 if !text.isEmpty { text += "\n" }
229 return Result(text: text, headings: headings, links: inline.links, issues: issues + inline.issues)
230 }
231
232 mutating func header(fallback: String?) -> [String] {
233 var drawer: [String] = []
234 var title: String?
235 var date: String?
236 var tags: [String] = []
237 func multi(_ items: [String]) -> String {
238 items.map { $0.contains(" ") || $0.contains("\"") ? "\"" + $0.replacingOccurrences(of: "\"", with: "\\\"") + "\"" : $0 }.joined(separator: " ")
239 }
240 func split(_ value: String) -> [String] {
241 value.split(whereSeparator: { $0 == "," || $0 == " " }).map(String.init)
242 }
243 for (key, value) in parsed.frontMatter {
244 let name = key.lowercased()
245 switch (name, value) {
246 case (_, .nested): issues.append(.frontMatter(key))
247 case ("title", .scalar(let text)): title = text
248 case ("title", .list(let items)): title = items.joined(separator: " ")
249 case ("date", .scalar(let text)): date = text
250 case ("tags", .scalar(let text)), ("tag", .scalar(let text)): tags += split(text).map(MarkdownToOrg.tag)
251 case ("tags", .list(let items)), ("tag", .list(let items)): tags += items.flatMap(split).map(MarkdownToOrg.tag)
252 case ("aliases", .scalar(let text)), ("alias", .scalar(let text)):
253 drawer.append(":ROAM_ALIASES: " + multi(text.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }))
254 case ("aliases", .list(let items)), ("alias", .list(let items)): drawer.append(":ROAM_ALIASES: " + multi(items))
255 case (_, .scalar(let text)):
256 drawer.append(":" + property(key) + ": " + text.replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespaces))
257 case (_, .list(let items)): drawer.append(":" + property(key) + ": " + multi(items))
258 }
259 }
260 tags += fileTags
261 tags = tags.filter { !$0.isEmpty }.reduce(into: []) { if !$0.contains($1) { $0.append($1) } }
262 var out: [String] = []
263 if !drawer.isEmpty { out = [":PROPERTIES:"] + drawer.map { $0.hasSuffix(": ") ? String($0.dropLast()) : $0 } + [":END:"] }
264 if let title = title ?? fallback, !title.isEmpty { out.append("#+title: " + title) }
265 if let date, !date.isEmpty { out.append("#+date: " + date) }
266 if !tags.isEmpty { out.append("#+filetags: :" + tags.joined(separator: ":") + ":") }
267 return out
268 }
269
270 func property(_ key: String) -> String {
271 String(key.map { $0 == " " || $0 == ":" ? "_" : $0 })
272 }
273
274 // MARK: Blocks
275
276 mutating func render(_ block: MarkdownBlock, indent: String) -> [String] {
277 switch block {
278 case .heading(_, let text):
279 // A heading can't be inside a list or quote in org.
280 issues.append(.nestedHeading(text))
281 return paragraph(["**" + text + "**"], indent: indent)
282 case .paragraph(let lines):
283 return paragraph(lines, indent: indent)
284 case .code(let lang, let body, let fenced):
285 let name = lang.lowercased()
286 let example = !fenced || name.isEmpty || ["text", "txt", "plain", "plaintext"].contains(name)
287 let language = String(lang.filter { !$0.isWhitespace })
288 let open = example ? "#+begin_example" : "#+begin_src " + language
289 let close = example ? "#+end_example" : "#+end_src"
290 return [indent + open] + body.map { $0.isEmpty ? "" : indent + escapeCode($0) } + [indent + close]
291 case .math(let body):
292 return [indent + "\\["] + body.map { indent + $0 } + [indent + "\\]"]
293 case .comment(let body):
294 return [indent + "#+begin_comment"] + body.map { $0.isEmpty ? "" : indent + escapeCode($0) } + [indent + "#+end_comment"]
295 case .html(let body):
296 return [indent + "#+begin_export html"] + body.map { $0.isEmpty ? "" : indent + escapeCode($0) } + [indent + "#+end_export"]
297 case .quote(let inner):
298 return [indent + "#+begin_quote"] + blocks(inner, indent: indent) + [indent + "#+end_quote"]
299 case .callout(let type, let title, let inner):
300 var name = type
301 if ["example", "src", "export", "verse", "center", "comment"].contains(name) { name = "callout-" + name }
302 var body: [String] = []
303 if !title.isEmpty { body = paragraph(["**" + title + "**"], indent: indent) }
304 let rest = blocks(inner, indent: indent)
305 if !body.isEmpty, !rest.isEmpty { body.append("") }
306 return [indent + "#+begin_" + name] + body + rest + [indent + "#+end_" + name]
307 case .list(let ordered, let start, let items):
308 return list(ordered: ordered, start: start, items: items, indent: indent)
309 case .table(let header, let rows):
310 return table(header: header, rows: rows, indent: indent)
311 case .rule:
312 return [indent + "-----"]
313 }
314 }
315
316 static func isParagraph(_ block: MarkdownBlock) -> Bool {
317 switch block {
318 case .paragraph, .heading: true
319 default: false
320 }
321 }
322
323 /// Two lists in a row: org would read them as one unless two blank lines part them.
324 static func listsInARow(_ previous: MarkdownBlock?, _ block: MarkdownBlock) -> Bool {
325 if case .list = previous, case .list = block { return true }
326 return false
327 }
328
329 /// Blocks separated by blank lines.
330 mutating func blocks(_ blocks: [MarkdownBlock], indent: String, tight: Bool = false) -> [String] {
331 var out: [String] = []
332 var previous: MarkdownBlock?
333 for block in blocks {
334 let separate: Bool
335 if tight {
336 if case .paragraph = previous, case .paragraph = block { separate = true } else { separate = false }
337 } else {
338 separate = previous != nil
339 }
340 if separate { out.append("") }
341 if Self.listsInARow(previous, block) { out += separate ? [""] : ["", ""] }
342 out += render(block, indent: indent)
343 previous = block
344 }
345 return out
346 }
347
348 /// `,` before lines org would read as a heading or keyword inside a block.
349 func escapeCode(_ line: String) -> String {
350 let lead = line.prefix { $0 == " " }
351 let rest = line.dropFirst(lead.count)
352 let commas = rest.prefix { $0 == "," }
353 let after = rest.dropFirst(commas.count)
354 if (lead.isEmpty && after.hasPrefix("*")) || after.hasPrefix("#+") { return lead + "," + rest }
355 return line
356 }
357
358 mutating func paragraph(_ source: [String], indent: String) -> [String] {
359 var raw = source
360 // Hard line breaks: two trailing spaces or a backslash.
361 for k in raw.indices.dropLast() {
362 if raw[k].hasSuffix(" ") {
363 raw[k] = raw[k].trimmingCharacters(in: .whitespaces) + "\u{2}"
364 } else if raw[k].hasSuffix("\\"), !raw[k].hasSuffix("\\\\") {
365 raw[k] = String(raw[k].dropLast()) + "\u{2}"
366 }
367 }
368 raw[raw.count - 1] = raw[raw.count - 1].trimmingCharacters(in: .whitespaces)
369 var prefix: [String] = []
370 var target = ""
371 if parsed.obsidian, let id = MarkdownToOrg.blockID(raw[raw.count - 1]) {
372 raw[raw.count - 1] = id.rest
373 target = " <<" + id.id + ">>"
374 }
375 if parsed.obsidian, indent.isEmpty {
376 let only = raw.joined(separator: "\n")
377 if only.hasPrefix("![["), only.hasSuffix("]]"), !only.dropFirst(3).contains("[["), let bar = only.lastIndex(of: "|") {
378 let size = only[only.index(after: bar)..<only.index(only.endIndex, offsetBy: -2)]
379 let width = size.split(separator: "x").first.map(String.init) ?? ""
380 if !width.isEmpty, width.allSatisfy(\.isNumber) { prefix.append(indent + "#+attr_org: :width " + width) }
381 }
382 }
383 let joined = raw.joined(separator: "\n")
384 if indent.isEmpty, joined.hasPrefix("!["), joined.hasSuffix(")"), let close = joined.firstIndex(of: "]"), !joined.contains("\n") {
385 let alt = joined[joined.index(joined.startIndex, offsetBy: 2)..<close]
386 if !alt.isEmpty, !alt.contains("]"), joined[joined.index(after: close)] == "(" { prefix.append(indent + "#+attr_html: :alt " + alt) }
387 }
388 let converted = inline.convert(joined).replacingOccurrences(of: "\u{2}", with: " \\\\") + target
389 var out: [String] = []
390 for line in converted.split(separator: "\n", omittingEmptySubsequences: false) {
391 let line = String(line)
392 if out.isEmpty {
393 out.append(Self.startsElement(line, topLevel: indent.isEmpty) ? "\u{200B}" + line : line)
394 } else if Self.startsElement(line, topLevel: indent.isEmpty) {
395 out[out.count - 1] += " " + line
396 } else {
397 out.append(line)
398 }
399 }
400 return prefix + out.map { indent + $0 }
401 }
402
403 /// Whether org would read `line` at the start of a paragraph line as another element.
404 static func startsElement(_ line: String, topLevel: Bool) -> Bool {
405 if topLevel, line.hasPrefix("*"), line.drop(while: { $0 == "*" }).first == " " { return true }
406 let text = line.drop { $0 == " " }
407 if text.hasPrefix("- ") || text.hasPrefix("+ ") || text == "-" || text == "+" || text.hasPrefix("#+") || text.hasPrefix("# ") || text == "#" || text.hasPrefix("|")
408 || text.hasPrefix(": ") || text == ":" || text.hasPrefix("-----") || text.hasPrefix("[fn:") || text.hasPrefix("\\begin{") {
409 return true
410 }
411 if !topLevel, text.hasPrefix("* ") { return true }
412 let digits = text.prefix { $0.isASCII && $0.isNumber }
413 if !digits.isEmpty, let next = text.dropFirst(digits.count).first, next == "." || next == ")" {
414 let after = text.dropFirst(digits.count + 1)
415 return after.isEmpty || after.first == " "
416 }
417 if text.hasPrefix(":"), text.dropFirst().contains(":"), text.hasSuffix(":"), !text.contains(" ") { return true }
418 return false
419 }
420
421 mutating func list(ordered: Bool, start: Int, items: [MarkdownItem], indent: String) -> [String] {
422 var out: [String] = []
423 for (k, item) in items.enumerated() {
424 let bullet = ordered ? "\(start + k)." : "-"
425 var head = indent + bullet + " "
426 if ordered, k == 0, start != 1 { head += "[@\(start)] " }
427 if let task = item.task {
428 switch task {
429 case " ": head += "[ ] "
430 case "x", "X": head += "[X] "
431 case "/": head += "[-] "
432 default:
433 issues.append(.taskStatus(String(task)))
434 head += "[ ] "
435 }
436 }
437 let inner = indent + String(repeating: " ", count: bullet.count + 1)
438 var body = blocks(item.blocks, indent: inner, tight: true)
439 if parsed.obsidian, item.task != nil, let first = body.first { body[0] = taskDates(first) }
440 if let first = body.first, item.blocks.first.map(Self.isParagraph) == true {
441 var text = first.dropFirst(inner.count)
442 if text.first == "\u{200B}" { text = text.dropFirst() }
443 out.append(head + text)
444 out += body.dropFirst()
445 } else {
446 out.append(head.hasSuffix(" ") ? String(head.dropLast()) : head)
447 out += body
448 }
449 }
450 return out
451 }
452
453 /// The Tasks plugin's `📅` due, `⏳` scheduled and `✅` done dates as org keywords and
454 /// timestamps; `🛫` start and `➕` created dates as plain timestamps.
455 mutating func taskDates(_ line: String) -> String {
456 var text = line
457 let marks: [(String, String?, Bool)] = [("📅", "DEADLINE: ", true), ("⏳", "SCHEDULED: ", true), ("✅", "CLOSED: ", false),
458 ("🛫", nil, true), ("➕", nil, false), ("❌", nil, false)]
459 for (mark, keyword, active) in marks {
460 while let range = text.range(of: mark) {
461 let after = text[range.upperBound...].drop { $0 == " " }
462 let date = String(after.prefix(10))
463 guard let stamp = MarkdownToOrg.timestamp(date, active: active) else { break }
464 let end = after.index(after.startIndex, offsetBy: 10)
465 text.replaceSubrange(range.lowerBound..<end, with: (keyword ?? "") + stamp)
466 }
467 }
468 if text.contains("🔁") { issues.append(.recurrence) }
469 return text
470 }
471
472 mutating func table(header: [String], rows: [[String]], indent: String) -> [String] {
473 func cell(_ text: String) -> String {
474 inline.convert(text).replacingOccurrences(of: "\u{1}", with: "\\vert{}")
475 }
476 let all = [header.map(cell)] + rows.map { $0.map(cell) }
477 var widths = Array(repeating: 1, count: header.count)
478 for row in all {
479 for (k, text) in row.enumerated() where k < widths.count { widths[k] = max(widths[k], text.count) }
480 }
481 func line(_ row: [String]) -> String {
482 indent + "| " + row.enumerated().map { k, text in text + String(repeating: " ", count: widths[k] - text.count) }.joined(separator: " | ") + " |"
483 }
484 return [line(all[0]), indent + "|" + widths.map { String(repeating: "-", count: $0 + 2) }.joined(separator: "+") + "|"] + all.dropFirst().map(line)
485 }
486 }
487}
Tests/OrgAppTests/MarkdownImportTests.swift added +230 · view
@@ -0,0 +1,230 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgApp
5
6/// File ▸ Import ▸ Markdown Files… and Obsidian Vault…: names, links, attachments, and the
7/// sources left alone.
8struct MarkdownImportTests {
9 let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("md-import-\(UUID().uuidString)")
10
11 func write(_ files: [String: String], in folder: URL) throws {
12 for (path, text) in files {
13 let url = folder.appendingPathComponent(path)
14 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
15 try Data(text.utf8).write(to: url)
16 }
17 }
18
19 /// Every file below `folder` with its contents and modification date.
20 func snapshot(_ folder: URL) throws -> [String: Data] {
21 var out: [String: Data] = [:]
22 let enumerator = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.contentModificationDateKey])!
23 for case let url as URL in enumerator {
24 let values = try url.resourceValues(forKeys: [.isRegularFileKey, .contentModificationDateKey])
25 let relative = String(url.standardizedFileURL.resolvingSymlinksInPath().path.dropFirst(folder.standardizedFileURL.resolvingSymlinksInPath().path.count))
26 if values.isRegularFile == true {
27 out[relative] = try Data(contentsOf: url) + Data("\(values.contentModificationDate!.timeIntervalSince1970)".utf8)
28 } else {
29 out[relative + "/"] = Data()
30 }
31 }
32 return out
33 }
34
35 func read(_ path: String) throws -> String {
36 try String(contentsOf: scratch.appendingPathComponent("dest").appendingPathComponent(path), encoding: .utf8)
37 }
38
39 /// `file:` links in the org file at `path` whose files don't exist.
40 func brokenLinks(_ path: String) throws -> [String] {
41 let url = scratch.appendingPathComponent("dest").appendingPathComponent(path)
42 let model = DocumentModel(tree: OrgParser.parse(try String(contentsOf: url, encoding: .utf8)))
43 let links = model.links + model.headings.flatMap(\.links)
44 return links.filter { $0.hasPrefix("file:") }.filter { link in
45 let target = String(link.dropFirst(5)).components(separatedBy: "::")[0]
46 return !FileManager.default.fileExists(atPath: url.deletingLastPathComponent().appendingPathComponent(target).path)
47 }
48 }
49
50 static let vault: [String: String] = [
51 "Home.md": """
52 ---
53 tags: [start]
54 aliases: [Index]
55 ---
56 Links: [[Projects/Alpha]], [[Alpha#Goals|goals]], [[Alpha#^key]], [[Missing note]] and [md](Projects/Alpha.md#goals).
57
58 ![[diagram.png]]
59 ![[Alpha]]
60 ![[report.pdf]]
61
62 """,
63 "Projects/Alpha.md": """
64 # Goals #project
65 Ship it. ^key
66
67 - [ ] Write 📅 2026-12-01
68 Back to [[Home]].
69
70 """,
71 "attachments/diagram.png": "png",
72 "attachments/report.pdf": "pdf",
73 "attachments/unused.png": "png",
74 "Board.canvas": "{}",
75 ".obsidian/app.json": "{}"
76 ]
77
78 @Test func vaultBecomesAFolderWithLinksBetweenTheNewFiles() throws {
79 defer { try? FileManager.default.removeItem(at: scratch) }
80 let source = scratch.appendingPathComponent("Vault")
81 let destination = scratch.appendingPathComponent("dest")
82 try write(Self.vault, in: source)
83 try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
84 let before = try snapshot(source)
85
86 let plan = try MarkdownImport.plan(.obsidian, sources: [source], into: destination)
87 #expect(plan.notes == 2)
88 #expect(plan.headings == 1)
89 #expect(plan.attachments == 2)
90 #expect(plan.renamed.isEmpty)
91 #expect(Set(plan.problems) == [
92 MarkdownImport.Problem(file: "Vault/Board.canvas", reason: .notConverted),
93 MarkdownImport.Problem(file: "Vault/Home.md", reason: .converted(.unresolvedLink("Missing note")))
94 ])
95 let written = try MarkdownImport.write(plan)
96 #expect(written.paths.count == 4)
97 #expect(written.renamed.isEmpty)
98
99 let home = try read("Vault/Home.org")
100 #expect(home.hasPrefix(":PROPERTIES:\n:ROAM_ALIASES: Index\n:END:\n#+title: Home\n#+filetags: :start:\n"))
101 #expect(home.contains("[[file:Projects/Alpha.org][Alpha]],"))
102 #expect(home.contains("[[file:Projects/Alpha.org::*Goals][goals]]"))
103 #expect(home.contains("[[file:Projects/Alpha.org::key][Alpha > key]]"))
104 #expect(home.contains("[[file:Missing note.org][Missing note]]"))
105 #expect(home.contains("[[file:Projects/Alpha.org::*Goals][md]]"))
106 #expect(home.contains("[[file:attachments/diagram.png]]"))
107 #expect(home.contains("[[file:attachments/report.pdf][report.pdf]]"))
108 let alpha = try read("Vault/Projects/Alpha.org")
109 #expect(alpha.contains("* Goals :project:"))
110 #expect(alpha.contains("Ship it. <<key>>"))
111 #expect(alpha.contains("[[file:../Home.org][Home]]"))
112 #expect(alpha.contains("DEADLINE: <2026-12-01 Tue>"))
113 #expect(try brokenLinks("Vault/Home.org") == ["file:Missing note.org"])
114 #expect(try brokenLinks("Vault/Projects/Alpha.org").isEmpty)
115 #expect(!FileManager.default.fileExists(atPath: destination.appendingPathComponent("Vault/attachments/unused.png").path))
116 #expect(!FileManager.default.fileExists(atPath: destination.appendingPathComponent("Vault/.obsidian").path))
117 #expect(try snapshot(source) == before)
118 }
119
120 @Test func takenNamesGetFreeOnesAndNothingIsOverwritten() throws {
121 defer { try? FileManager.default.removeItem(at: scratch) }
122 let source = scratch.appendingPathComponent("src")
123 let destination = scratch.appendingPathComponent("dest")
124 try write(["Vault/Note.md": "# Hi\n", "a.md": "A ![p](pic.png)\n", "pic.png": "new", "b.markdown": "B\n"], in: source)
125 try write(["Vault/keep.org": "old vault", "a.org": "old a", "attachments/pic.png": "old pic"], in: destination)
126 let before = try snapshot(source)
127 let existing = try snapshot(destination)
128
129 let plan = try MarkdownImport.plan(.markdown, sources: [source.appendingPathComponent("Vault"), source.appendingPathComponent("a.md"),
130 source.appendingPathComponent("b.markdown")], into: destination)
131 #expect(plan.renamed.map(\.to) == ["Vault 2", "a 2.org"])
132 #expect(plan.renamed.map(\.from) == ["Vault", "a.md"])
133 let written = try MarkdownImport.write(plan)
134 #expect(written.renamed.isEmpty)
135 #expect(try read("Vault 2/Note.org") == "* Hi\n")
136 #expect(try read("a 2.org") == "A [[file:attachments/pic 2.png]]\n")
137 #expect(try read("attachments/pic 2.png") == "new")
138 #expect(try read("b.org") == "B\n")
139 let after = try snapshot(destination)
140 for (path, data) in existing { #expect(after[path] == data, "\(path)") }
141 #expect(try snapshot(source) == before)
142 }
143
144 @Test func aNameTakenAfterThePreviewIsNotOverwritten() throws {
145 defer { try? FileManager.default.removeItem(at: scratch) }
146 let source = scratch.appendingPathComponent("src")
147 let destination = scratch.appendingPathComponent("dest")
148 try write(["Note.md": "new\n", "Folder/x.md": "x\n"], in: source)
149 try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
150 let plan = try MarkdownImport.plan(.markdown, sources: [source.appendingPathComponent("Note.md"), source.appendingPathComponent("Folder")], into: destination)
151 try write(["Note.org": "someone else's", "Folder/y.org": "theirs"], in: destination)
152
153 let written = try MarkdownImport.write(plan)
154 #expect(Set(written.renamed.map(\.to)) == ["Note 2.org", "Folder 2"])
155 #expect(try read("Note.org") == "someone else's")
156 #expect(try read("Note 2.org") == "new\n")
157 #expect(try read("Folder 2/x.org") == "x\n")
158 #expect(!FileManager.default.fileExists(atPath: destination.appendingPathComponent("Folder/x.org").path))
159 let leftovers = try FileManager.default.contentsOfDirectory(atPath: destination.path).filter { $0.hasPrefix(".") }
160 #expect(leftovers.isEmpty)
161 }
162
163 @Test func markdownLinksBetweenChosenFiles() throws {
164 defer { try? FileManager.default.removeItem(at: scratch) }
165 let source = scratch.appendingPathComponent("src")
166 let destination = scratch.appendingPathComponent("dest")
167 try write(["one.md": "# Top\nSee [two](two.md#second-part), [self](#top) and [gone](gone.md).\n", "two.md": "## Second part\n"], in: source)
168 try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
169 let plan = try MarkdownImport.plan(.markdown, sources: [source.appendingPathComponent("one.md"), source.appendingPathComponent("two.md")], into: destination)
170 #expect(plan.problems == [MarkdownImport.Problem(file: "one.md", reason: .converted(.unresolvedLink("gone.md")))])
171 _ = try MarkdownImport.write(plan)
172 #expect(try read("one.org") == "* Top\nSee [[file:two.org::*Second part][two]], [[*Top][self]] and [[file:gone.md][gone]].\n")
173 }
174
175 @Test func unreadableNoteIsReported() throws {
176 defer { try? FileManager.default.removeItem(at: scratch) }
177 let source = scratch.appendingPathComponent("src")
178 try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)
179 try Data([0xff, 0xfe, 0x00, 0xd8]).write(to: source.appendingPathComponent("bad.md"))
180 let plan = try MarkdownImport.plan(.markdown, sources: [source.appendingPathComponent("bad.md")], into: scratch)
181 #expect(plan.notes == 0)
182 #expect(plan.problems == [MarkdownImport.Problem(file: "bad.md", reason: .unreadable)])
183 }
184
185 /// Writes a vault of `count` notes, each linking to the next two and embedding an image.
186 static func writeVault(_ count: Int, to folder: URL) throws {
187 try FileManager.default.createDirectory(at: folder.appendingPathComponent("img"), withIntermediateDirectories: true)
188 for n in 0..<count {
189 let dir = folder.appendingPathComponent("area \(n % 10)")
190 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
191 let text = """
192 ---
193 tags: [t\(n % 7)]
194 ---
195 # Note \(n) #tag\(n % 5)
196 Text with **bold**, a [[Note \((n + 1) % count)]] link and [[Note \((n + 2) % count)#Section]].
197
198 ## Section
199 - [ ] task 📅 2026-12-0\(n % 9 + 1)
200 - item with `code`
201
202 | a | b |
203 |---|---|
204 | \(n) | x |
205
206 ![[pic \(n % 20).png]]
207
208 """
209 try Data(text.utf8).write(to: dir.appendingPathComponent("Note \(n).md"))
210 }
211 for k in 0..<20 { try Data("png".utf8).write(to: folder.appendingPathComponent("img/pic \(k).png")) }
212 }
213
214 @Test func largeVaultConvertsWithEveryLinkResolved() throws {
215 defer { try? FileManager.default.removeItem(at: scratch) }
216 let source = scratch.appendingPathComponent("Big")
217 let destination = scratch.appendingPathComponent("dest")
218 try Self.writeVault(1_000, to: source)
219 try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
220 let plan = try MarkdownImport.plan(.obsidian, sources: [source], into: destination)
221 #expect(plan.notes == 1_000)
222 #expect(plan.headings == 2_000)
223 #expect(plan.links == 3_000)
224 #expect(plan.attachments == 20)
225 #expect(plan.problems.isEmpty)
226 let written = try MarkdownImport.write(plan)
227 #expect(written.paths.count == 1_020)
228 for n in [0, 499, 999] { #expect(try brokenLinks("Big/area \(n % 10)/Note \(n).org").isEmpty) }
229 }
230}
Tests/OrgCoreTests/MarkdownToOrgTests.swift added +234 · view
@@ -0,0 +1,234 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// Markdown to org, one construct at a time; each output is read back with orgstar's parser.
6struct MarkdownToOrgTests {
7 func org(_ markdown: String, obsidian: Bool = false, title: String? = nil) -> (text: String, tree: OrgTree, model: DocumentModel, result: MarkdownToOrg.Result) {
8 let result = MarkdownToOrg.convert(markdown, obsidian: obsidian, title: title)
9 let tree = OrgParser.parse(result.text)
10 return (result.text, tree, DocumentModel(tree: tree), result)
11 }
12
13 func nodes(_ tree: OrgTree, _ kind: SyntaxKind) -> [SyntaxNode] {
14 tree.root.descendants().filter { $0.kind == kind }
15 }
16
17 func tokens(_ tree: OrgTree, _ kind: SyntaxKind) -> [SyntaxToken] {
18 tree.root.descendants().flatMap(\.tokens).filter { $0.kind == kind }
19 }
20
21 @Test func atxAndSetextHeadings() {
22 let out = org("# One\ntext\n## Two ##\nSetext\n======\nUnder\n---\n")
23 #expect(out.model.headings.map(\.level) == [1, 2, 1, 2])
24 #expect(out.model.headings.map(\.title) == ["One", "Two", "Setext", "Under"])
25 #expect(out.result.headings == 4)
26 }
27
28 @Test func emphasisAndCode() {
29 let out = org("Some **bold**, __strong__, *it*, _em_, ***both***, `co~de`, `x` and ~~gone~~.\n")
30 #expect(out.text == "Some *bold*, *strong*, /it/, /em/, */both/*, =co~de=, ~x~ and +gone+.\n")
31 #expect(nodes(out.tree, .bold).count == 3)
32 #expect(nodes(out.tree, .italic).count == 3)
33 #expect(nodes(out.tree, .verbatim).count == 1)
34 #expect(nodes(out.tree, .code).count == 1)
35 #expect(nodes(out.tree, .strikeThrough).count == 1)
36 }
37
38 @Test func intrawordUnderscoreStaysText() {
39 #expect(org("snake_case_name\n").text == "snake_case_name\n")
40 }
41
42 @Test func linksAndImages() {
43 let out = org("""
44 A [site](https://example.com "Title"), <https://auto.example>, <me@example.com>,
45 ![alt text](pics/a%20b.png) and [ref] and [label][ref].
46
47 [ref]: https://ref.example
48
49 """)
50 #expect(out.model.links == ["https://example.com", "https://auto.example", "mailto:me@example.com", "file:pics/a b.png", "https://ref.example", "https://ref.example"])
51 #expect(out.text.contains("[[https://example.com][site]]"))
52 #expect(out.result.links == 6)
53 }
54
55 @Test func imageAloneGetsAltAttribute() {
56 let out = org("![A cat](cat.png)\n")
57 #expect(out.text == "#+attr_html: :alt A cat\n[[file:cat.png]]\n")
58 #expect(nodes(out.tree, .affiliatedKeyword).count + nodes(out.tree, .keyword).count >= 1)
59 }
60
61 @Test func nestedOrderedAndTaskLists() {
62 let out = org("""
63 - one
64 - nested *a*
65 - [ ] open
66 - [x] done
67 - two
68
69 3. three
70 4. four
71
72 """)
73 #expect(out.text == """
74 - one
75 - nested /a/
76 - [ ] open
77 - [X] done
78 - two
79
80
81 3. [@3] three
82 4. four
83
84 """)
85 #expect(nodes(out.tree, .plainList).count == 3)
86 #expect(nodes(out.tree, .item).count == 7)
87 #expect(tokens(out.tree, .checkbox).count == 2)
88 #expect(tokens(out.tree, .counter).count == 1)
89 }
90
91 @Test func listItemWithParagraphsAndCode() {
92 let out = org("1. First\n\n More text.\n\n ```sh\n ls\n ```\n2. Second\n")
93 #expect(out.text == "1. First\n\n More text.\n #+begin_src sh\n ls\n #+end_src\n2. Second\n")
94 #expect(nodes(out.tree, .item).count == 2)
95 #expect(out.model.srcBlocks.map(\.language) == ["sh"])
96 }
97
98 @Test func blockQuote() {
99 let out = org("> quoted *text*\n> more\n>\n> - item\n")
100 #expect(out.text == "#+begin_quote\nquoted /text/\nmore\n\n- item\n#+end_quote\n")
101 #expect(nodes(out.tree, .block).count == 1)
102 }
103
104 @Test func codeFencesBecomeSourceBlocks() {
105 let out = org("```python\n* star\n#+keyword\nprint(1)\n```\n\n```\nplain\n```\n\n indented\n")
106 #expect(out.text == "#+begin_src python\n,* star\n,#+keyword\nprint(1)\n#+end_src\n\n#+begin_example\nplain\n#+end_example\n\n#+begin_example\nindented\n#+end_example\n")
107 #expect(out.model.srcBlocks.count == 1)
108 #expect(out.model.headings.isEmpty)
109 }
110
111 @Test func tablesBecomeOrgTables() {
112 let out = org("| A | B \\| C |\n|:--|--:|\n| `x` | **y** |\n| z |\n")
113 #expect(out.model.tables.count == 1)
114 #expect(out.model.tables[0].rows == [.cells(["A", "B \\vert{} C"]), .rule, .cells(["~x~", "*y*"]), .cells(["z", ""])])
115 }
116
117 @Test func footnotes() {
118 let out = org("Text[^1] and more[^note].\n\n[^1]: First.\n[^note]: Second\n continued.\n")
119 #expect(nodes(out.tree, .footnoteReference).count == 2)
120 #expect(nodes(out.tree, .footnoteDefinition).count == 2)
121 #expect(out.text.hasSuffix("[fn:1] First.\n\n[fn:note] Second\ncontinued.\n"))
122 }
123
124 @Test func frontMatter() {
125 let out = org("""
126 ---
127 title: "A Note"
128 date: 2024-01-05
129 tags: [one, two/three]
130 aliases:
131 - First alias
132 - second
133 status: draft
134 nested:
135 a: 1
136 ---
137 Body.
138
139 """)
140 #expect(out.text == """
141 :PROPERTIES:
142 :ROAM_ALIASES: "First alias" second
143 :status: draft
144 :END:
145 #+title: A Note
146 #+date: 2024-01-05
147 #+filetags: :one:two_three:
148
149 Body.
150
151 """)
152 #expect(out.model.fileTags == ["one", "two_three"])
153 #expect(nodes(out.tree, .propertyDrawer).count == 1)
154 #expect(out.result.issues == [.frontMatter("nested")])
155 }
156
157 @Test func mathRuleHTMLAndComments() {
158 let out = org("$$\nE = mc^2\n$$\n\nInline $x^2$, not $5 or $6.\n\n***\n\n<!-- hidden -->\n\n<div>\n<b>x</b>\n</div>\n")
159 #expect(out.text == "\\[\nE = mc^2\n\\]\n\nInline \\(x^2\\), not $5 or $6.\n\n-----\n\n#+begin_comment\nhidden\n#+end_comment\n\n#+begin_export html\n<div>\n<b>x</b>\n</div>\n#+end_export\n")
160 #expect(nodes(out.tree, .latexFragment).count >= 1)
161 #expect(nodes(out.tree, .horizontalRule).count == 1)
162 }
163
164 @Test func hardBreaksAndEntities() {
165 let out = org("one \ntwo\\\nthree &amp; &#8212;\n")
166 #expect(out.text == "one \\\\\ntwo \\\\\nthree & —\n")
167 #expect(nodes(out.tree, .lineBreak).count == 2)
168 }
169
170 @Test func paragraphLinesThatOrgWouldReadAsElements() {
171 // A continuation line can't start a list or a table in org; it joins the line above.
172 let out = org("Item count:\n2. is not a list\n| not a table\n")
173 #expect(out.text == "Item count: 2. is not a list | not a table\n")
174 #expect(nodes(out.tree, .plainList).isEmpty)
175 #expect(nodes(out.tree, .table).isEmpty)
176 }
177
178 @Test func headingInsideListIsBold() {
179 let out = org("- # Title\n")
180 #expect(out.text == "- *Title*\n")
181 #expect(out.model.headings.isEmpty)
182 }
183
184 // MARK: - Obsidian
185
186 @Test func wikilinksAndEmbeds() {
187 let out = org("See [[Other note]], [[Other note#Part|alias]], [[#Local]] and ![[pic.png|300]].\n", obsidian: true)
188 #expect(out.text == "See [[file:Other note.org][Other note]], [[file:Other note.org][alias]], #Local and [[file:pic.png]].\n")
189 #expect(out.result.issues == [.unresolvedLink("#Local")])
190 }
191
192 @Test func embeddedImageWidth() {
193 let out = org("![[pic.png|300]]\n", obsidian: true)
194 #expect(out.text == "#+attr_org: :width 300\n[[file:pic.png]]\n")
195 }
196
197 @Test func tagsGoToHeadingsAndFile() {
198 let out = org("#inbox note\n\n# Meeting #work #2024\nTalked about #project/alpha.\n", obsidian: true)
199 #expect(out.model.fileTags == ["inbox"])
200 #expect(out.model.headings.first?.localTags == ["work", "project_alpha"])
201 #expect(out.model.headings.first?.title == "Meeting #work #2024")
202 }
203
204 @Test func calloutsBecomeSpecialBlocks() {
205 let out = org("> [!warning]- Careful\n> Inside **it**.\n\n> [!example]\n> e.g.\n", obsidian: true)
206 #expect(out.text == "#+begin_warning\n*Careful*\n\nInside *it*.\n#+end_warning\n\n#+begin_callout-example\ne.g.\n#+end_callout-example\n")
207 #expect(nodes(out.tree, .block).count == 2)
208 }
209
210 @Test func taskDates() {
211 let out = org("- [ ] Pay 📅 2024-01-10 ⏳ 2024-01-08\n- [x] Paid ✅ 2024-01-09\n- [>] Moved\n- [ ] Weekly 🔁 every week\n", obsidian: true)
212 #expect(out.text == "- [ ] Pay DEADLINE: <2024-01-10 Wed> SCHEDULED: <2024-01-08 Mon>\n- [X] Paid CLOSED: [2024-01-09 Tue]\n- [ ] Moved\n- [ ] Weekly 🔁 every week\n")
213 #expect(nodes(out.tree, .timestamp).count == 3)
214 #expect(Set(out.result.issues) == [.taskStatus(">"), .recurrence])
215 }
216
217 @Test func highlightCommentAndBlockID() {
218 let out = org("A ==marked== word.\nLast line ^block-1\n\n%%\nhidden\n%%\n", obsidian: true)
219 #expect(out.text == "A *marked* word.\nLast line <<block-1>>\n\n#+begin_comment\nhidden\n#+end_comment\n")
220 #expect(nodes(out.tree, .target).count == 1)
221 }
222
223 @Test func fileNameIsTheFallbackTitle() {
224 #expect(org("Body\n", obsidian: true, title: "Note").text == "#+title: Note\n\nBody\n")
225 #expect(org("---\ntitle: Own\n---\nBody\n", obsidian: true, title: "Note").text == "#+title: Own\n\nBody\n")
226 }
227
228 @Test func headingFragments() {
229 let headings = MarkdownToOrg.parse("# Some *Heading*\n## Other: part\n", obsidian: false).headings
230 #expect(MarkdownToOrg.heading("some-heading", in: headings) == "Some /Heading/")
231 #expect(MarkdownToOrg.heading("Other: part", in: headings) == "Other: part")
232 #expect(MarkdownToOrg.heading("missing", in: headings) == nil)
233 }
234}
Tests/OrgEditorAppKitTests/MarkdownImportGateTests.swift added +36 · view
@@ -0,0 +1,36 @@
1import Foundation
2import OrgApp
3import Testing
4
5/// Gate for File ▸ Import ▸ Obsidian Vault…: planning and writing a vault of 1,000 notes.
6extension GateTests {
7 @Test func importingAThousandNoteVault() async throws {
8 let scratch = try Self.scratch()
9 defer { try? FileManager.default.removeItem(at: scratch) }
10 let vault = scratch.appendingPathComponent("Vault")
11 let destination = scratch.appendingPathComponent("dest")
12 try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
13 try FileManager.default.createDirectory(at: vault.appendingPathComponent("img"), withIntermediateDirectories: true)
14 for n in 0..<1_000 {
15 let dir = vault.appendingPathComponent("area \(n % 10)")
16 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
17 var text = "---\ntags: [t\(n % 7)]\n---\n# Note \(n) #tag\(n % 5)\n"
18 for p in 0..<10 {
19 text += "Paragraph \(p) with **bold**, *italic*, `code`, [[Note \((n + p + 1) % 1_000)]] and [[Note \((n + 2) % 1_000)#Section]].\n\n"
20 }
21 text += "## Section\n- [ ] task 📅 2026-12-01\n- item\n\n| a | b |\n|---|---|\n| \(n) | x |\n\n![[pic \(n % 20).png]]\n"
22 try Data(text.utf8).write(to: dir.appendingPathComponent("Note \(n).md"))
23 }
24 for k in 0..<20 { try Data("png".utf8).write(to: vault.appendingPathComponent("img/pic \(k).png")) }
25
26 var notes = 0
27 let time = try await ContinuousClock().measure {
28 let plan = try await Task.detached { try MarkdownImport.plan(.obsidian, sources: [vault], into: destination) }.value
29 notes = plan.notes
30 _ = try await Task.detached { try MarkdownImport.write(plan) }.value
31 }
32 print("import 1,000-note vault: \(time)")
33 #expect(notes == 1_000)
34 #expect(time < .seconds(5))
35 }
36}
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