Sources/OrgCore/MarkdownImport/MarkdownToOrg.swift
485 lines · 26303 bytes
35 symbols in this file
MarkdownTargetsMarkdownImportIssueMarkdownToOrgParsedResultparsecollectIDsrenderconvertheadingsquashescapeLinkPathfootnoteLabeltagblockIDheadingTitletimestampRendererdocumentheadermultisplitpropertyrenderisParagraphlistsInARowblocksescapeCodeparagraphstartsElementlisttaskDatestablecellline
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}
43
44/// Converts a Markdown file (CommonMark with GFM tables, task lists, strikethrough and
45/// footnotes, and YAML front matter) to an org file; with `obsidian`, Obsidian's wikilinks,
46/// embeds, callouts, `#tags`, highlights, comments, block IDs and Tasks plugin dates too.
47///
48/// Front matter: `title` → `#+title:`, `date` → `#+date:`, `tags` → `#+filetags:`,
49/// `aliases` → `ROAM_ALIASES`, and every other key → a property in a property drawer at the
50/// top of the file.
51public enum MarkdownToOrg {
52 public struct Parsed: Sendable {
53 let blocks: [MarkdownBlock]
54 let footnotes: [(label: String, blocks: [MarkdownBlock])]
55 let links: [String: String]
56 let frontMatter: [(key: String, value: MarkdownFrontMatter.Value)]
57 let obsidian: Bool
58 /// Each top-level heading's text as written and as an org title, for links to it.
59 public let headings: [(source: String, title: String)]
60 /// Obsidian block IDs (`^id`) in the file.
61 public let blockIDs: Set<String>
62 }
63
64 public struct Result: Sendable {
65 public var text: String
66 public var headings: Int
67 public var links: Int
68 public var issues: [MarkdownImportIssue]
69 }
70
71 public static func parse(_ markdown: String, obsidian: Bool) -> Parsed {
72 let (frontMatter, body) = MarkdownFrontMatter.split(markdown)
73 let (blocks, definitions) = MarkdownBlocks.parse(body, obsidian: obsidian)
74 let inline = MarkdownInline(obsidian: obsidian, definitions: definitions.links, targets: .none)
75 var headings: [(source: String, title: String)] = []
76 var ids = Set<String>()
77 func collectIDs(_ blocks: [MarkdownBlock]) {
78 for block in blocks {
79 switch block {
80 case .paragraph(let lines): if let id = blockID(lines.last ?? "")?.id { ids.insert(id) }
81 case .list(_, _, let items): items.forEach { collectIDs($0.blocks) }
82 case .quote(let inner), .callout(_, _, let inner): collectIDs(inner)
83 default: break
84 }
85 }
86 }
87 for block in blocks {
88 if case .heading(_, let text) = block {
89 headings.append((text, headingTitle(text, inline: inline).title))
90 }
91 }
92 if obsidian { collectIDs(blocks) }
93 return Parsed(blocks: blocks, footnotes: definitions.footnotes, links: definitions.links, frontMatter: frontMatter,
94 obsidian: obsidian, headings: headings, blockIDs: ids)
95 }
96
97 /// `parsed` as an org file. `title` is the fallback for `#+title:` when the front matter
98 /// has none.
99 public static func render(_ parsed: Parsed, title: String? = nil, targets: MarkdownTargets = .none) -> Result {
100 var renderer = Renderer(parsed: parsed, inline: MarkdownInline(obsidian: parsed.obsidian, definitions: parsed.links, targets: targets))
101 return renderer.document(title: title)
102 }
103
104 public static func convert(_ markdown: String, obsidian: Bool = false, title: String? = nil, targets: MarkdownTargets = .none) -> Result {
105 render(parse(markdown, obsidian: obsidian), title: title, targets: targets)
106 }
107
108 /// The org title of the heading `fragment` names (its text, or GitHub's anchor for it).
109 public static func heading(_ fragment: String, in headings: [(source: String, title: String)]) -> String? {
110 let wanted = squash(fragment.removingPercentEncoding ?? fragment)
111 guard !wanted.isEmpty else { return nil }
112 return headings.first { squash($0.source) == wanted }?.title ?? headings.first { squash($0.title) == wanted }?.title
113 }
114
115 private static func squash(_ text: String) -> String {
116 String(text.lowercased().filter { $0.isLetter || $0.isNumber })
117 }
118
119 // MARK: - Shared pieces
120
121 static func escapeLinkPath(_ path: String) -> String {
122 path.replacingOccurrences(of: "[", with: "\\[").replacingOccurrences(of: "]", with: "\\]")
123 }
124
125 static func footnoteLabel(_ label: String) -> String {
126 String(label.map { $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" ? $0 : "_" })
127 }
128
129 /// An org tag for an Obsidian or front matter tag: characters org doesn't allow become `_`.
130 static func tag(_ tag: String) -> String {
131 String(tag.drop { $0 == "#" }.map { $0.isLetter || $0.isNumber || "_@#%".contains($0) ? $0 : "_" })
132 }
133
134 /// A trailing Obsidian block ID (` ^id`).
135 static func blockID(_ line: String) -> (id: String, rest: String)? {
136 guard let caret = line.range(of: " ^", options: .backwards) ?? (line.hasPrefix("^") ? line.startIndex..<line.index(after: line.startIndex) : nil) else { return nil }
137 let id = line[caret.upperBound...].trimmingCharacters(in: .whitespaces)
138 guard !id.isEmpty, id.allSatisfy({ ($0.isASCII && ($0.isLetter || $0.isNumber)) || $0 == "-" }) else { return nil }
139 return (id, String(line[..<caret.lowerBound]))
140 }
141
142 /// A heading's org title and the `#tags` at its end.
143 static func headingTitle(_ text: String, inline: MarkdownInline) -> (title: String, tags: [String]) {
144 var words = text.split(separator: " ", omittingEmptySubsequences: false).map(String.init)
145 var trailing: [String] = []
146 if inline.obsidian {
147 while let last = words.last, last.hasPrefix("#"), last.count > 1, last.dropFirst().contains(where: { !$0.isNumber }),
148 last.dropFirst().allSatisfy({ $0.isLetter || $0.isNumber || "_-/".contains($0) }) {
149 trailing.insert(tag(last), at: 0)
150 words.removeLast()
151 }
152 }
153 _ = inline.takeTags()
154 let title = inline.convert(words.joined(separator: " ").trimmingCharacters(in: .whitespaces))
155 return (title, trailing + inline.takeTags().filter { !trailing.contains($0) })
156 }
157
158 public static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "bmp", "tif", "tiff", "heic", "avif"]
159
160 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
161
162 /// `<2024-01-05 Fri>` for `2024-01-05`, with `[` `]` when not active.
163 static func timestamp(_ date: String, active: Bool) -> String? {
164 let parts = date.split(separator: "-").compactMap { Int($0) }
165 guard parts.count == 3, date.count == 10 else { return nil }
166 var calendar = Calendar(identifier: .gregorian)
167 calendar.timeZone = TimeZone(identifier: "UTC")!
168 guard let day = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2])) else { return nil }
169 let name = weekdays[calendar.component(.weekday, from: day) - 1]
170 return (active ? "<" : "[") + date + " " + name + (active ? ">" : "]")
171 }
172
173 // MARK: - Rendering
174
175 struct Renderer {
176 let parsed: Parsed
177 let inline: MarkdownInline
178 var lines: [String] = []
179 var headings = 0
180 var issues: [MarkdownImportIssue] = []
181 /// Output line of each heading, and the tags found in its section.
182 var headingLines: [(line: Int, tags: [String])] = []
183 var fileTags: [String] = []
184
185 init(parsed: Parsed, inline: MarkdownInline) {
186 self.parsed = parsed
187 self.inline = inline
188 }
189
190 mutating func document(title fallback: String?) -> Result {
191 var previous: MarkdownBlock?
192 for block in parsed.blocks {
193 defer { previous = block }
194 if !lines.isEmpty {
195 if case .heading = previous {} else { lines.append("") }
196 if Self.listsInARow(previous, block) { lines.append("") }
197 }
198 if case .heading(let level, let text) = block {
199 let heading = MarkdownToOrg.headingTitle(text, inline: inline)
200 headingLines.append((lines.count, heading.tags))
201 lines.append(String(repeating: "*", count: level) + " " + heading.title)
202 headings += 1
203 continue
204 }
205 lines += render(block, indent: "")
206 let tags = inline.takeTags()
207 if headingLines.isEmpty { fileTags += tags } else { headingLines[headingLines.count - 1].tags += tags }
208 }
209 for (label, blocks) in parsed.footnotes {
210 if !lines.isEmpty { lines.append("") }
211 var body = blocks.enumerated().flatMap { index, block in (index > 0 ? [""] : []) + render(block, indent: "") }
212 if body.isEmpty { body = [""] }
213 body[0] = "[fn:" + MarkdownToOrg.footnoteLabel(label) + "] " + body[0].drop { $0 == " " }
214 lines += body
215 let tags = inline.takeTags()
216 if headingLines.isEmpty { fileTags += tags } else { headingLines[headingLines.count - 1].tags += tags }
217 }
218 for (line, tags) in headingLines {
219 let unique = tags.reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } }
220 if !unique.isEmpty { lines[line] += " :" + unique.joined(separator: ":") + ":" }
221 }
222 let header = header(fallback: fallback)
223 var text = header.joined(separator: "\n")
224 if !header.isEmpty, !lines.isEmpty { text += "\n\n" }
225 text += lines.joined(separator: "\n")
226 if !text.isEmpty { text += "\n" }
227 return Result(text: text, headings: headings, links: inline.links, issues: issues + inline.issues)
228 }
229
230 mutating func header(fallback: String?) -> [String] {
231 var drawer: [String] = []
232 var title: String?
233 var date: String?
234 var tags: [String] = []
235 func multi(_ items: [String]) -> String {
236 items.map { $0.contains(" ") || $0.contains("\"") ? "\"" + $0.replacingOccurrences(of: "\"", with: "\\\"") + "\"" : $0 }.joined(separator: " ")
237 }
238 func split(_ value: String) -> [String] {
239 value.split(whereSeparator: { $0 == "," || $0 == " " }).map(String.init)
240 }
241 for (key, value) in parsed.frontMatter {
242 let name = key.lowercased()
243 switch (name, value) {
244 case (_, .nested): issues.append(.frontMatter(key))
245 case ("title", .scalar(let text)): title = text
246 case ("title", .list(let items)): title = items.joined(separator: " ")
247 case ("date", .scalar(let text)): date = text
248 case ("tags", .scalar(let text)), ("tag", .scalar(let text)): tags += split(text).map(MarkdownToOrg.tag)
249 case ("tags", .list(let items)), ("tag", .list(let items)): tags += items.flatMap(split).map(MarkdownToOrg.tag)
250 case ("aliases", .scalar(let text)), ("alias", .scalar(let text)):
251 drawer.append(":ROAM_ALIASES: " + multi(text.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }))
252 case ("aliases", .list(let items)), ("alias", .list(let items)): drawer.append(":ROAM_ALIASES: " + multi(items))
253 case (_, .scalar(let text)):
254 drawer.append(":" + property(key) + ": " + text.replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespaces))
255 case (_, .list(let items)): drawer.append(":" + property(key) + ": " + multi(items))
256 }
257 }
258 tags += fileTags
259 tags = tags.filter { !$0.isEmpty }.reduce(into: []) { if !$0.contains($1) { $0.append($1) } }
260 var out: [String] = []
261 if !drawer.isEmpty { out = [":PROPERTIES:"] + drawer.map { $0.hasSuffix(": ") ? String($0.dropLast()) : $0 } + [":END:"] }
262 if let title = title ?? fallback, !title.isEmpty { out.append("#+title: " + title) }
263 if let date, !date.isEmpty { out.append("#+date: " + date) }
264 if !tags.isEmpty { out.append("#+filetags: :" + tags.joined(separator: ":") + ":") }
265 return out
266 }
267
268 func property(_ key: String) -> String {
269 String(key.map { $0 == " " || $0 == ":" ? "_" : $0 })
270 }
271
272 // MARK: Blocks
273
274 mutating func render(_ block: MarkdownBlock, indent: String) -> [String] {
275 switch block {
276 case .heading(_, let text):
277 // A heading can't be inside a list or quote in org.
278 issues.append(.nestedHeading(text))
279 return paragraph(["**" + text + "**"], indent: indent)
280 case .paragraph(let lines):
281 return paragraph(lines, indent: indent)
282 case .code(let lang, let body, let fenced):
283 let name = lang.lowercased()
284 let example = !fenced || name.isEmpty || ["text", "txt", "plain", "plaintext"].contains(name)
285 let language = String(lang.filter { !$0.isWhitespace })
286 let open = example ? "#+begin_example" : "#+begin_src " + language
287 let close = example ? "#+end_example" : "#+end_src"
288 return [indent + open] + body.map { $0.isEmpty ? "" : indent + escapeCode($0) } + [indent + close]
289 case .math(let body):
290 return [indent + "\\["] + body.map { indent + $0 } + [indent + "\\]"]
291 case .comment(let body):
292 return [indent + "#+begin_comment"] + body.map { $0.isEmpty ? "" : indent + escapeCode($0) } + [indent + "#+end_comment"]
293 case .html(let body):
294 return [indent + "#+begin_export html"] + body.map { $0.isEmpty ? "" : indent + escapeCode($0) } + [indent + "#+end_export"]
295 case .quote(let inner):
296 return [indent + "#+begin_quote"] + blocks(inner, indent: indent) + [indent + "#+end_quote"]
297 case .callout(let type, let title, let inner):
298 var name = type
299 if ["example", "src", "export", "verse", "center", "comment"].contains(name) { name = "callout-" + name }
300 var body: [String] = []
301 if !title.isEmpty { body = paragraph(["**" + title + "**"], indent: indent) }
302 let rest = blocks(inner, indent: indent)
303 if !body.isEmpty, !rest.isEmpty { body.append("") }
304 return [indent + "#+begin_" + name] + body + rest + [indent + "#+end_" + name]
305 case .list(let ordered, let start, let items):
306 return list(ordered: ordered, start: start, items: items, indent: indent)
307 case .table(let header, let rows):
308 return table(header: header, rows: rows, indent: indent)
309 case .rule:
310 return [indent + "-----"]
311 }
312 }
313
314 static func isParagraph(_ block: MarkdownBlock) -> Bool {
315 switch block {
316 case .paragraph, .heading: true
317 default: false
318 }
319 }
320
321 /// Two lists in a row: org would read them as one unless two blank lines part them.
322 static func listsInARow(_ previous: MarkdownBlock?, _ block: MarkdownBlock) -> Bool {
323 if case .list = previous, case .list = block { return true }
324 return false
325 }
326
327 /// Blocks separated by blank lines.
328 mutating func blocks(_ blocks: [MarkdownBlock], indent: String, tight: Bool = false) -> [String] {
329 var out: [String] = []
330 var previous: MarkdownBlock?
331 for block in blocks {
332 let separate: Bool
333 if tight {
334 if case .paragraph = previous, case .paragraph = block { separate = true } else { separate = false }
335 } else {
336 separate = previous != nil
337 }
338 if separate { out.append("") }
339 if Self.listsInARow(previous, block) { out += separate ? [""] : ["", ""] }
340 out += render(block, indent: indent)
341 previous = block
342 }
343 return out
344 }
345
346 /// `,` before lines org would read as a heading or keyword inside a block.
347 func escapeCode(_ line: String) -> String {
348 let lead = line.prefix { $0 == " " }
349 let rest = line.dropFirst(lead.count)
350 let commas = rest.prefix { $0 == "," }
351 let after = rest.dropFirst(commas.count)
352 if (lead.isEmpty && after.hasPrefix("*")) || after.hasPrefix("#+") { return lead + "," + rest }
353 return line
354 }
355
356 mutating func paragraph(_ source: [String], indent: String) -> [String] {
357 var raw = source
358 // Hard line breaks: two trailing spaces or a backslash.
359 for k in raw.indices.dropLast() {
360 if raw[k].hasSuffix(" ") {
361 raw[k] = raw[k].trimmingCharacters(in: .whitespaces) + "\u{2}"
362 } else if raw[k].hasSuffix("\\"), !raw[k].hasSuffix("\\\\") {
363 raw[k] = String(raw[k].dropLast()) + "\u{2}"
364 }
365 }
366 raw[raw.count - 1] = raw[raw.count - 1].trimmingCharacters(in: .whitespaces)
367 var prefix: [String] = []
368 var target = ""
369 if parsed.obsidian, let id = MarkdownToOrg.blockID(raw[raw.count - 1]) {
370 raw[raw.count - 1] = id.rest
371 target = " <<" + id.id + ">>"
372 }
373 if parsed.obsidian, indent.isEmpty {
374 let only = raw.joined(separator: "\n")
375 if only.hasPrefix("![["), only.hasSuffix("]]"), !only.dropFirst(3).contains("[["), let bar = only.lastIndex(of: "|") {
376 let size = only[only.index(after: bar)..<only.index(only.endIndex, offsetBy: -2)]
377 let width = size.split(separator: "x").first.map(String.init) ?? ""
378 if !width.isEmpty, width.allSatisfy(\.isNumber) { prefix.append(indent + "#+attr_org: :width " + width) }
379 }
380 }
381 let joined = raw.joined(separator: "\n")
382 if indent.isEmpty, joined.hasPrefix("!["), joined.hasSuffix(")"), let close = joined.firstIndex(of: "]"), !joined.contains("\n") {
383 let alt = joined[joined.index(joined.startIndex, offsetBy: 2)..<close]
384 if !alt.isEmpty, !alt.contains("]"), joined[joined.index(after: close)] == "(" { prefix.append(indent + "#+attr_html: :alt " + alt) }
385 }
386 let converted = inline.convert(joined).replacingOccurrences(of: "\u{2}", with: " \\\\") + target
387 var out: [String] = []
388 for line in converted.split(separator: "\n", omittingEmptySubsequences: false) {
389 let line = String(line)
390 if out.isEmpty {
391 out.append(Self.startsElement(line, topLevel: indent.isEmpty) ? "\u{200B}" + line : line)
392 } else if Self.startsElement(line, topLevel: indent.isEmpty) {
393 out[out.count - 1] += " " + line
394 } else {
395 out.append(line)
396 }
397 }
398 return prefix + out.map { indent + $0 }
399 }
400
401 /// Whether org would read `line` at the start of a paragraph line as another element.
402 static func startsElement(_ line: String, topLevel: Bool) -> Bool {
403 if topLevel, line.hasPrefix("*"), line.drop(while: { $0 == "*" }).first == " " { return true }
404 let text = line.drop { $0 == " " }
405 if text.hasPrefix("- ") || text.hasPrefix("+ ") || text == "-" || text == "+" || text.hasPrefix("#+") || text.hasPrefix("# ") || text == "#" || text.hasPrefix("|")
406 || text.hasPrefix(": ") || text == ":" || text.hasPrefix("-----") || text.hasPrefix("[fn:") || text.hasPrefix("\\begin{") {
407 return true
408 }
409 if !topLevel, text.hasPrefix("* ") { return true }
410 let digits = text.prefix { $0.isASCII && $0.isNumber }
411 if !digits.isEmpty, let next = text.dropFirst(digits.count).first, next == "." || next == ")" {
412 let after = text.dropFirst(digits.count + 1)
413 return after.isEmpty || after.first == " "
414 }
415 if text.hasPrefix(":"), text.dropFirst().contains(":"), text.hasSuffix(":"), !text.contains(" ") { return true }
416 return false
417 }
418
419 mutating func list(ordered: Bool, start: Int, items: [MarkdownItem], indent: String) -> [String] {
420 var out: [String] = []
421 for (k, item) in items.enumerated() {
422 let bullet = ordered ? "\(start + k)." : "-"
423 var head = indent + bullet + " "
424 if ordered, k == 0, start != 1 { head += "[@\(start)] " }
425 if let task = item.task {
426 switch task {
427 case " ": head += "[ ] "
428 case "x", "X": head += "[X] "
429 case "/": head += "[-] "
430 default:
431 issues.append(.taskStatus(String(task)))
432 head += "[ ] "
433 }
434 }
435 let inner = indent + String(repeating: " ", count: bullet.count + 1)
436 var body = blocks(item.blocks, indent: inner, tight: true)
437 if parsed.obsidian, item.task != nil, let first = body.first { body[0] = taskDates(first) }
438 if let first = body.first, item.blocks.first.map(Self.isParagraph) == true {
439 var text = first.dropFirst(inner.count)
440 if text.first == "\u{200B}" { text = text.dropFirst() }
441 out.append(head + text)
442 out += body.dropFirst()
443 } else {
444 out.append(head.hasSuffix(" ") ? String(head.dropLast()) : head)
445 out += body
446 }
447 }
448 return out
449 }
450
451 /// The Tasks plugin's `📅` due, `⏳` scheduled and `✅` done dates as org keywords and
452 /// timestamps; `🛫` start and `➕` created dates as plain timestamps.
453 mutating func taskDates(_ line: String) -> String {
454 var text = line
455 let marks: [(String, String?, Bool)] = [("📅", "DEADLINE: ", true), ("⏳", "SCHEDULED: ", true), ("✅", "CLOSED: ", false),
456 ("🛫", nil, true), ("➕", nil, false), ("❌", nil, false)]
457 for (mark, keyword, active) in marks {
458 while let range = text.range(of: mark) {
459 let after = text[range.upperBound...].drop { $0 == " " }
460 let date = String(after.prefix(10))
461 guard let stamp = MarkdownToOrg.timestamp(date, active: active) else { break }
462 let end = after.index(after.startIndex, offsetBy: 10)
463 text.replaceSubrange(range.lowerBound..<end, with: (keyword ?? "") + stamp)
464 }
465 }
466 if text.contains("🔁") { issues.append(.recurrence) }
467 return text
468 }
469
470 mutating func table(header: [String], rows: [[String]], indent: String) -> [String] {
471 func cell(_ text: String) -> String {
472 inline.convert(text).replacingOccurrences(of: "\u{1}", with: "\\vert{}")
473 }
474 let all = [header.map(cell)] + rows.map { $0.map(cell) }
475 var widths = Array(repeating: 1, count: header.count)
476 for row in all {
477 for (k, text) in row.enumerated() where k < widths.count { widths[k] = max(widths[k], text.count) }
478 }
479 func line(_ row: [String]) -> String {
480 indent + "| " + row.enumerated().map { k, text in text + String(repeating: " ", count: widths[k] - text.count) }.joined(separator: " | ") + " |"
481 }
482 return [line(all[0]), indent + "|" + widths.map { String(repeating: "-", count: $0 + 2) }.joined(separator: "+") + "|"] + all.dropFirst().map(line)
483 }
484 }
485}