Sources/OrgCore/MarkdownImport/MarkdownToOrg.swift

be996c163c7399849cca3987b604bf1f64a98962
orgstar/Sources/OrgCore/MarkdownImport/MarkdownToOrg.swift

487 lines · 26376 bytes

  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}
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