Sources/OrgCore/Export/RevealExport.swift

429 lines · 25389 bytes

22 symbols in this file
  1import Foundation
  2
  3/// reveal.js export, as org-re-reveal (3.x) writes a deck: a title slide, a slide for each
  4/// heading down to `H`, those below `#+REVEAL_HLEVEL` (1) as vertical slides under the one
  5/// above, speaker notes from `#+BEGIN_NOTES` blocks, fragments from `#+ATTR_REVEAL: :frag`, and
  6/// everything inside a slide as HTML export writes it.
  7///
  8/// Without `#+REVEAL_ROOT` the deck is one file with reveal.js, its theme and plugins in the
  9/// page, read from `library` (reveal.js 6.0.2's `dist` files), and local images as `data:`
 10/// URIs. With it, the deck links to reveal.js there, as org-re-reveal does, laid out as
 11/// reveal.js 6 lays out its `dist` folder.
 12public enum RevealExport {
 13    /// The folder with reveal.js, `reveal.css`, `reset.css`, `theme/` and `plugin/`, which the
 14    /// apps set from `OrgMathJax.reveal`.
 15    nonisolated(unsafe) public static var library: URL?
 16    /// MathJax's `tex-svg-full.js`, put in a deck with math that inlines reveal.js.
 17    nonisolated(unsafe) public static var mathJax: URL?
 18
 19    /// `org-re-reveal-plugins`, less markdown, which org text never needs.
 20    public static let defaultPlugins = ["notes", "search", "zoom"]
 21    /// The plugins in `library`; a deck that inlines reveal.js leaves out others.
 22    public static let bundledPlugins: Set<String> = ["notes", "search", "zoom", "math"]
 23    /// The themes in `library`.
 24    public static let themes = ["beige", "black", "black-contrast", "blood", "dracula", "league", "moon", "night", "serif", "simple", "sky", "solarized", "white", "white-contrast"]
 25    /// Themes with light text on a dark background, which take the dark code colors.
 26    static let darkThemes: Set<String> = ["black", "black-contrast", "blood", "dracula", "league", "moon", "night"]
 27    static let pluginNames = [
 28        "markdown": "RevealMarkdown", "notes": "RevealNotes", "search": "RevealSearch", "zoom": "RevealZoom",
 29        "highlight": "RevealHighlight", "math": "RevealMath.MathJax3",
 30    ]
 31
 32    /// The `#+REVEAL_…` keywords of `text`, after its setup files', each with its values in order.
 33    static func keywords(_ text: String) -> [String: [String]] {
 34        var keywords: [String: [String]] = [:]
 35        for m in text.matches(of: #/(?mi)^[ \t]*#\+(REVEAL_[A-Z_]+|SUBTITLE|EMAIL):[ \t]*(.*?)[ \t]*$/#) {
 36            keywords[m.1.uppercased(), default: []].append(String(m.2))
 37        }
 38        return keywords
 39    }
 40
 41    /// The deck. `path` is the file's, for includes, images and `#+REVEAL_EXTRA_CSS`.
 42    public static func document(
 43        _ text: String, fallbackTitle: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(),
 44        codeStyle: HTMLCodeStyle? = nil, language: String = "en", library: URL? = RevealExport.library, mathJax: URL? = RevealExport.mathJax
 45    ) -> String {
 46        let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
 47        let expanded = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
 48        let text = ExportPreprocess.attachments(expanded, path: path, settings: settings)
 49        let options = ExportOptions.parse(settings.setupKeywords + text)
 50        let keywords = Self.keywords(settings.setupKeywords + "\n" + text)
 51        func keyword(_ key: String) -> String? { keywords[key]?.last }
 52        func flag(_ item: String, _ fallback: Bool) -> Bool { options.items[item].map { $0 != "nil" } ?? fallback }
 53
 54        let root = keyword("REVEAL_ROOT").flatMap { $0.isEmpty ? nil : $0 }
 55        let inline = root == nil && library.map { FileManager.default.fileExists(atPath: $0.appendingPathComponent("reveal.js").path) } == true
 56        let base = root.map { $0.hasSuffix("/") ? $0 : $0 + "/" } ?? "./reveal.js/"
 57        let theme = keyword("REVEAL_THEME").flatMap { $0.isEmpty ? nil : $0 } ?? "black"
 58        let plugins = keyword("REVEAL_PLUGINS").map { $0.split(whereSeparator: { "() \t".contains($0) }).map { String($0).lowercased() } } ?? defaultPlugins
 59        let hlevel = keyword("REVEAL_HLEVEL").flatMap { Int($0) } ?? 1
 60
 61        let meta = HTMLExport.metadata(text, settings: settings)
 62        let title = meta.title ?? fallbackTitle
 63        let minLevel = DocumentModel(tree: OrgParser.parse(text, defaults: settings)).headings.map(\.level).min() ?? 1
 64        let slides = RevealSlides(hlevel: hlevel, headlineLevels: options.headlineLevels, minLevel: minLevel, fragmentStyle: keyword("REVEAL_DEFAULT_FRAG_STYLE"))
 65        let renderer = HTMLRenderer(settings: settings, options: options)
 66        renderer.codeStyle = codeStyle
 67        renderer.language = meta.language ?? language
 68        renderer.reveal = slides
 69        renderer.inTitle = true
 70        let titleHTML = renderer.inlineString(title)
 71        let subtitleHTML = keyword("SUBTITLE").map(renderer.inlineString) ?? ""
 72        renderer.inTitle = false
 73        renderer.citations = CiteProcessor(text: text, directory: directory, global: settings.citeGlobalBibliography)
 74        var body = renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
 75        let footnotes = renderer.footnoteSection()
 76        if !footnotes.isEmpty { body += "<section>\n\(footnotes)</section>\n" }
 77        var contents = renderer.tableOfContents()
 78        if !contents.isEmpty { contents = "<section id=\"table-of-contents-section\">\n\(contents)</section>\n" }
 79        // reveal.js goes to a slide by `#/id`.
 80        var slidesHTML = contents + body
 81        for id in slides.headingIDs {
 82            slidesHTML = slidesHTML.replacingOccurrences(of: "href=\"#\(HTMLRenderer.escape(id))\"", with: "href=\"#/slide-\(HTMLRenderer.escape(id))\"")
 83        }
 84
 85        // The title slide: org-re-reveal's `auto` template, a template of `%` specs, or none.
 86        var titleSlide = ""
 87        let template = keywords["REVEAL_TITLE_SLIDE"].map { $0.joined(separator: "\n") } ?? "auto"
 88        if flag("reveal_title_slide", true), template != "nil", !template.isEmpty {
 89            let escape = HTMLRenderer.escape
 90            let author = options.author ? meta.author.map(escape) ?? "" : ""
 91            let date = options.date ? meta.date.map(escape) ?? "" : ""
 92            let email = flag("email", false) ? keyword("EMAIL").map(escape) ?? "" : ""
 93            var content: String
 94            if template == "auto" {
 95                content = options.title && !title.isEmpty ? "<h1 class=\"title\">\(titleHTML)</h1>" : ""
 96                if !subtitleHTML.isEmpty { content += "<h2 class=\"subtitle\">\(subtitleHTML)</h2>" }
 97                if !author.isEmpty { content += "<h2 class=\"author\">\(author)</h2>" }
 98                if !email.isEmpty { content += "<h2 class=\"email\">\(email)</h2>" }
 99                if !date.isEmpty { content += "<h2 class=\"date\">\(date)</h2>" }
100                if let misc = keyword("REVEAL_MISCINFO"), !misc.isEmpty { content += "<p class=\"misc\">\(misc)</p>" }
101            } else {
102                let specs: [Character: String] = [
103                    "t": titleHTML, "s": subtitleHTML, "a": author, "e": email, "d": date,
104                    "A": keyword("REVEAL_ACADEMIC_TITLE") ?? "", "m": keyword("REVEAL_MISCINFO") ?? "", "%": "%",
105                ]
106                content = ""
107                var chars = template.makeIterator()
108                while let c = chars.next() {
109                    guard c == "%", let spec = chars.next() else {
110                        content.append(c)
111                        continue
112                    }
113                    content += specs[spec] ?? "%" + String(spec)
114                }
115            }
116            let background = slides.attributes([
117                ("data-background", keyword("REVEAL_TITLE_SLIDE_BACKGROUND")),
118                ("data-background-size", keyword("REVEAL_TITLE_SLIDE_BACKGROUND_SIZE")),
119                ("data-background-position", keyword("REVEAL_TITLE_SLIDE_BACKGROUND_POSITION")),
120                ("data-background-repeat", keyword("REVEAL_TITLE_SLIDE_BACKGROUND_REPEAT")),
121                ("data-background-transition", keyword("REVEAL_TITLE_SLIDE_BACKGROUND_TRANSITION")),
122            ])
123            titleSlide = "<section id=\"sec-title-slide\"\(background)>\n\(content)\n</section>\n"
124        }
125
126        // The page around the slides.
127        func file(_ name: String) -> String? {
128            guard let library else { return nil }
129            return try? String(contentsOf: library.appendingPathComponent(name), encoding: .utf8)
130        }
131        func style(_ css: String, id: String? = nil) -> String {
132            "<style\(id.map { " id=\"\($0)\"" } ?? "")>\n\(css.replacingOccurrences(of: "</style", with: "<\\/style"))\n</style>\n"
133        }
134        func script(_ js: String) -> String {
135            "<script>\n\(js.replacingOccurrences(of: "</script", with: "<\\/script"))\n</script>\n"
136        }
137        var head = ""
138        if inline, let reset = file("reset.css"), let css = file("reveal.css") {
139            head += style(reset) + style(css)
140        } else {
141            head += "<link rel=\"stylesheet\" href=\"\(base)dist/reset.css\"/>\n<link rel=\"stylesheet\" href=\"\(base)dist/reveal.css\"/>\n"
142        }
143        // A theme by name, or a stylesheet of one's own.
144        if theme.hasSuffix(".css") || theme.contains("/") {
145            head += "<link rel=\"stylesheet\" href=\"\(HTMLRenderer.escape(theme))\" id=\"theme\"/>\n"
146        } else if inline {
147            if let css = file("theme/\(themes.contains(theme) ? theme : "black").css") { head += style(css, id: "theme") }
148        } else {
149            head += "<link rel=\"stylesheet\" href=\"\(base)dist/theme/\(HTMLRenderer.escape(theme)).css\" id=\"theme\"/>\n"
150        }
151        if !inline, plugins.contains("highlight") {
152            head += "<link rel=\"stylesheet\" href=\"\(base)dist/plugin/highlight/monokai.css\"/>\n"
153        }
154        for extra in keywords["REVEAL_EXTRA_CSS"] ?? [] where !extra.isEmpty {
155            let url = extra.hasPrefix("/") || extra.contains(":") ? nil : directory?.appendingPathComponent(extra)
156            if inline, let url, let css = try? String(contentsOf: url, encoding: .utf8) {
157                head += style(css)
158            } else {
159                head += "<link rel=\"stylesheet\" href=\"\(HTMLRenderer.escape(extra))\"/>\n"
160            }
161        }
162        if let codeStyle { head += style(Self.codeCSS(codeStyle.css, dark: darkThemes.contains(theme))) }
163        head += options.htmlHead.map { $0 + "\n" }.joined()
164        head += (keywords["REVEAL_HEAD_PREAMBLE"] ?? []).map { $0 + "\n" }.joined()
165        if renderer.hasMath, !plugins.contains("math") {
166            head += "<script>window.MathJax = { tex: { inlineMath: [['\\\\(', '\\\\)']], displayMath: [['\\\\[', '\\\\]'], ['$$', '$$']] } };</script>\n"
167            if inline, let mathJax, let js = try? String(contentsOf: mathJax, encoding: .utf8) {
168                head += "<script id=\"MathJax-script\">\n\(js.replacingOccurrences(of: "</script", with: "<\\/script"))\n</script>\n"
169            } else {
170                head += HTMLExport.mathJaxScript + "\n"
171            }
172        }
173
174        var scripts = ""
175        if inline, let js = file("reveal.js") {
176            scripts += script(js)
177        } else {
178            scripts += "<script src=\"\(base)dist/reveal.js\"></script>\n"
179        }
180        var used: [String] = []
181        for plugin in plugins where pluginNames[plugin] != nil && !used.contains(plugin) {
182            if inline {
183                guard bundledPlugins.contains(plugin), let js = file("plugin/\(plugin).js") else { continue }
184                scripts += script(js)
185            } else {
186                scripts += "<script src=\"\(base)dist/plugin/\(plugin).js\"></script>\n"
187            }
188            used.append(plugin)
189        }
190        // `org-re-reveal`'s defaults, then `#+REVEAL_INIT_OPTIONS`, which win.
191        func bool(_ item: String, _ fallback: Bool) -> String { flag(item, fallback) ? "true" : "false" }
192        func quoted(_ s: String) -> String { "'" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "'", with: "\\'") + "'" }
193        let slideNumber = options.items["reveal_slide_number"].map { $0 == "nil" ? "false" : $0 == "t" ? "'c'" : quoted($0) } ?? "'c'"
194        var initialize = [
195            "controls: \(bool("reveal_control", true))", "progress: \(bool("reveal_progress", true))", "history: \(bool("reveal_history", false))",
196            "center: \(bool("reveal_center", true))", "slideNumber: \(slideNumber)", "rollingLinks: \(bool("reveal_rolling_links", false))",
197            "keyboard: \(bool("reveal_keyboard", true))", "mouseWheel: \(bool("reveal_mousewheel", false))",
198            "fragmentInURL: \(bool("reveal_fragmentinurl", false))", "hashOneBasedIndex: \(bool("reveal_hashonebasedindex", false))",
199            "pdfSeparateFragments: \(bool("reveal_pdfseparatefragments", true))", "overview: \(bool("reveal_overview", true))",
200        ]
201        for (key, option) in [("REVEAL_MARGIN", "margin"), ("REVEAL_MIN_SCALE", "minScale"), ("REVEAL_MAX_SCALE", "maxScale")] {
202            if let value = keyword(key), Double(value) != nil { initialize.append("\(option): \(value)") }
203        }
204        initialize.append("transition: \(quoted(keyword("REVEAL_TRANS").flatMap { $0.isEmpty ? nil : $0 } ?? "convex"))")
205        initialize.append("transitionSpeed: \(quoted(keyword("REVEAL_SPEED").flatMap { $0.isEmpty ? nil : $0 } ?? "default"))")
206        for line in keywords["REVEAL_INIT_OPTIONS"] ?? [] {
207            let trimmed = line.trimmingCharacters(in: CharacterSet(charactersIn: ", \t"))
208            if !trimmed.isEmpty { initialize.append(trimmed) }
209        }
210        initialize.append("plugins: [ \(used.compactMap { pluginNames[$0] }.joined(separator: ", ")) ]")
211        scripts += script("Reveal.initialize({\n" + initialize.joined(separator: ",\n") + "\n});")
212
213        var page = """
214            <!DOCTYPE html>
215            <html lang="\(HTMLRenderer.escape(renderer.language))">
216            <head>
217            <meta charset="utf-8"/>
218            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
219            <title>\(HTMLRenderer.escape(title))</title>
220            \(options.author ? meta.author.map { "<meta name=\"author\" content=\"\(HTMLRenderer.escape($0))\"/>\n" } ?? "" : "")\(head)</head>
221            <body>
222            \((keywords["REVEAL_PREAMBLE"] ?? []).map { $0 + "\n" }.joined())<div class="reveal">
223            <div class="slides">
224            \(titleSlide)\(slidesHTML)</div>
225            \((keywords["REVEAL_POSTAMBLE"] ?? []).map { $0 + "\n" }.joined())</div>
226            \(scripts)</body>
227            </html>
228
229            """
230        if inline { page = inliningImages(page, directory: directory) }
231        return page
232    }
233
234    /// The light rules of an `HTMLCodeStyle`'s stylesheet, or its dark ones, for a theme's
235    /// background rather than the system's appearance.
236    static func codeCSS(_ css: String, dark: Bool) -> String {
237        let marker = "@media (prefers-color-scheme: dark) { "
238        guard let range = css.range(of: marker) else { return css }
239        if !dark { return String(css[..<range.lowerBound]).trimmingCharacters(in: .whitespacesAndNewlines) }
240        let rest = css[range.upperBound...]
241        guard let end = rest.range(of: " }", options: .backwards) else { return css }
242        return String(rest[..<end.lowerBound])
243    }
244
245    static let imageTypes = ["png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "svg": "image/svg+xml", "webp": "image/webp", "bmp": "image/bmp", "avif": "image/avif"]
246
247    /// `html` with the local images that `<img src>` and slide backgrounds name as `data:` URIs.
248    /// Files that can't be read keep their link.
249    static func inliningImages(_ html: String, directory: URL?) -> String {
250        html.replacing(#/(<img\b[^>]*?\bsrc="|\bdata-background(?:-image)?=")([^"]*)(")/#) { match in
251            let (whole, before, src, after) = match.output
252            let path = String(src).replacingOccurrences(of: "&amp;", with: "&").replacingOccurrences(of: "&quot;", with: "\"")
253            guard let type = imageTypes[(path as NSString).pathExtension.lowercased()] else { return String(whole) }
254            let url: URL?
255            if path.hasPrefix("file://") {
256                url = URL(string: path)
257            } else if path.hasPrefix("/") {
258                url = URL(fileURLWithPath: path)
259            } else if path.hasPrefix("~/") {
260                url = URL(fileURLWithPath: OrgPaths.expandingTilde(path))
261            } else if !path.contains(":") {
262                url = directory?.appendingPathComponent(path)
263            } else {
264                url = nil
265            }
266            guard let url, let data = try? Data(contentsOf: url) else { return String(whole) }
267            return before + "data:\(type);base64,\(data.base64EncodedString())" + after
268        }
269    }
270}
271
272/// The slides of a deck as `HTMLRenderer` writes them: each heading down to `H` opens a
273/// `<section>`, closing the one before, and a heading down to `hlevel` also opens a `<section>`
274/// that holds it and the vertical slides after it, as `org-re-reveal-headline` writes them.
275final class RevealSlides {
276    let hlevel: Int
277    let headlineLevels: Int
278    let minLevel: Int
279    /// `#+REVEAL_DEFAULT_FRAG_STYLE`, for `:frag t`.
280    let fragmentStyle: String?
281    private var slideOpen = false
282    private var groupOpen = false
283    /// The open slide's attributes but its id, for `#+REVEAL: split`.
284    private var slideAttributes = ""
285    /// The headings' ids that slides are named after, as `slide-<id>`.
286    private(set) var headingIDs: [String] = []
287
288    init(hlevel: Int, headlineLevels: Int, minLevel: Int, fragmentStyle: String?) {
289        self.hlevel = hlevel
290        self.headlineLevels = headlineLevels
291        self.minLevel = minLevel
292        self.fragmentStyle = fragmentStyle
293    }
294
295    /// ` key="value"` for each value given.
296    func attributes(_ pairs: [(String, String?)]) -> String {
297        pairs.compactMap { key, value in value.flatMap { $0.isEmpty ? nil : " \(key)=\"\(HTMLRenderer.escape($0))\"" } }.joined()
298    }
299
300    /// The section under `heading` as a slide, with its text, then the slides of its children;
301    /// nil for a heading below `H`, which HTML export writes. `all` is false for an archived
302    /// heading, which shows only its title.
303    func section(_ node: SyntaxNode, heading: SyntaxNode, all: Bool, renderer: HTMLRenderer) -> String? {
304        let stars = heading.tokens.first { $0.kind == .stars }?.text.count ?? 1
305        let level = stars - minLevel + 1
306        guard level <= headlineLevels else { return nil }
307        var properties: [String: String] = [:]
308        for drawer in node.children where drawer.kind == .propertyDrawer {
309            for property in drawer.children where property.kind == .nodeProperty {
310                if let m = property.text.trimmingCharacters(in: .whitespacesAndNewlines).firstMatch(of: /^:([^:\s]+):[ \t]*(.*)$/) { properties[m.1.uppercased()] = String(m.2) }
311            }
312        }
313        var out = ""
314        if slideOpen { out += "</section>\n" }
315        if level <= hlevel {
316            if groupOpen { out += "</section>\n" }
317            out += "<section>\n"
318            groupOpen = true
319        }
320        let headingHTML = renderer.heading(heading)
321        let id = headingHTML.firstMatch(of: /id="([^"]*)"/).map { String($0.1) } ?? ""
322        headingIDs.append(id.replacingOccurrences(of: "&quot;", with: "\"").replacingOccurrences(of: "&lt;", with: "<").replacingOccurrences(of: "&gt;", with: ">").replacingOccurrences(of: "&amp;", with: "&"))
323        slideAttributes = attributes([
324            ("class", properties["HTML_CONTAINER_CLASS"]),
325            ("data-transition", properties["REVEAL_DATA_TRANSITION"]),
326            ("data-state", properties["REVEAL_DATA_STATE"]),
327            ("data-background", properties["REVEAL_BACKGROUND"]),
328            ("data-background-size", properties["REVEAL_BACKGROUND_SIZE"]),
329            ("data-background-position", properties["REVEAL_BACKGROUND_POSITION"]),
330            ("data-background-repeat", properties["REVEAL_BACKGROUND_REPEAT"]),
331            ("data-background-transition", properties["REVEAL_BACKGROUND_TRANS"]),
332            ("data-background-opacity", properties["REVEAL_BACKGROUND_OPACITY"]),
333            ("data-background-iframe", properties["REVEAL_BACKGROUND_IFRAME"]),
334            ("data-background-video", properties["REVEAL_BACKGROUND_VIDEO"]),
335        ]) + (properties["REVEAL_EXTRA_ATTR"].map { $0.isEmpty ? "" : " " + $0 } ?? "")
336        out += "<section id=\"slide-\(id)\"\(slideAttributes)>\n" + headingHTML
337        slideOpen = true
338        if all {
339            for child in node.children where child.kind != .heading { out += renderer.element(child) }
340        }
341        return out
342    }
343
344    /// Text before the first heading, on a slide of its own.
345    func preamble(_ html: String) -> String {
346        html.allSatisfy(\.isWhitespace) ? "" : "<section>\n\(html)</section>\n"
347    }
348
349    /// What closes the slides still open at the end.
350    func close() -> String {
351        defer { (slideOpen, groupOpen) = (false, false) }
352        return (slideOpen ? "</section>\n" : "") + (groupOpen ? "</section>\n" : "")
353    }
354
355    /// `#+REVEAL_HTML: …` as written, `#+REVEAL: split` a new slide with the same attributes;
356    /// other keywords nothing.
357    func keyword(_ text: String) -> String {
358        guard let m = text.trimmingCharacters(in: .whitespacesAndNewlines).firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) else { return "" }
359        switch m.1.uppercased() {
360        case "REVEAL_HTML": return String(m.2) + "\n"
361        case "REVEAL" where m.2.lowercased().hasPrefix("split") && slideOpen: return "</section>\n<section\(slideAttributes)>\n"
362        default: return ""
363        }
364    }
365
366    /// `:frag` and `:frag_idx` from an `#+ATTR_REVEAL` line: their value, or the values of a
367    /// parenthesized list.
368    static func values(_ key: String, in attributes: String) -> [String]? {
369        guard let m = attributes.firstMatch(of: try! Regex(":\(key)[ \\t]+(\\([^)]*\\)|\\S+)")) else { return nil }
370        let value = String(m.output[1].substring ?? "")
371        if value.hasPrefix("(") { return value.dropFirst().dropLast().split(whereSeparator: \.isWhitespace).map(String.init) }
372        return [value]
373    }
374
375    /// The classes for a `:frag` style: `t` the default style, `none` none.
376    func fragmentClass(_ style: String) -> String? {
377        switch style {
378        case "t": fragmentStyle.map { "fragment \($0)" } ?? "fragment"
379        case "none", "nil": nil
380        default: "fragment \(style)"
381        }
382    }
383
384    /// `html`, an element's, as a fragment: its first tag gets the classes and index. In a
385    /// list, a parenthesized `:frag` makes each item a fragment, the last style and index
386    /// standing for items past the end of their lists.
387    func fragment(_ html: String, attributes: String, list: Bool) -> String {
388        guard let styles = Self.values("frag", in: attributes), !styles.isEmpty else { return html }
389        let indexes = Self.values("frag_idx", in: attributes) ?? []
390        let perItem = list && attributes.firstMatch(of: /:frag[ \t]+\(/) != nil
391        guard perItem else { return Self.adding(fragmentClass(styles[0]), index: indexes.first, to: html, at: html.startIndex) }
392        var out = html
393        var depth = 0
394        var item = 0
395        var at = out.startIndex
396        while let tag = out[at...].firstMatch(of: /<(\/?)(ul|ol|li)\b/) {
397            if tag.output.1.isEmpty, tag.output.2 == "li", depth == 1 {
398                let style = styles[min(item, styles.count - 1)]
399                let index = indexes.isEmpty ? nil : indexes[min(item, indexes.count - 1)]
400                let before = out.distance(from: out.startIndex, to: tag.range.lowerBound)
401                out = Self.adding(fragmentClass(style), index: index, to: out, at: tag.range.lowerBound)
402                at = out.index(out.startIndex, offsetBy: before + 3)
403                item += 1
404                continue
405            }
406            if tag.output.2 != "li" { depth += tag.output.1.isEmpty ? 1 : -1 }
407            at = tag.range.upperBound
408        }
409        return out
410    }
411
412    /// `html` with the classes and `data-fragment-index` added to the tag at `position`.
413    static func adding(_ classes: String?, index: String?, to html: String, at position: String.Index) -> String {
414        guard classes != nil || (index != nil && index != "-") else { return html }
415        guard let open = html[position...].firstMatch(of: /<([a-zA-Z0-9]+)([^>]*)>/) else { return html }
416        var attributes = String(open.output.2)
417        if let classes {
418            if let existing = attributes.firstMatch(of: /\bclass="([^"]*)"/) {
419                attributes.replaceSubrange(existing.range, with: "class=\"\(existing.output.1) \(classes)\"")
420            } else {
421                attributes += " class=\"\(classes)\""
422            }
423        }
424        if let index, index != "-" { attributes += " data-fragment-index=\"\(HTMLRenderer.escape(index))\"" }
425        var out = html
426        out.replaceSubrange(open.range, with: "<\(open.output.1)\(attributes)>")
427        return out
428    }
429}
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