Sources/OrgPresentation/SlideShow.swift

801e496807e41f08001dbd99622e2fa686a34058
orgstar/Sources/OrgPresentation/SlideShow.swift

107 lines · 6299 bytes

  1import Foundation
  2import OrgCore
  3
  4/// The open file as slides, as org-tree-slide shows it: one heading at a time with its text but
  5/// not its children, which are slides of their own; a title slide first from `#+TITLE`,
  6/// `#+AUTHOR` and `#+DATE` and the text before the first heading. Headings tagged with an
  7/// excluded tag (`noexport`) and COMMENT headings are left out with their children. Planning
  8/// lines, drawers, keywords and comments don't show; `#+BEGIN_NOTES` blocks are the slide's
  9/// speaker notes.
 10public enum SlideShow {
 11    public struct Slide: Sendable, Equatable {
 12        public enum Piece: Sendable, Equatable {
 13            /// File text, shown as the editor styles it.
 14            case text(Range<Int>)
 15            /// An image link alone on its line: the image's path as written.
 16            case image(String, width: Int?)
 17        }
 18
 19        /// The heading line from its keyword to the end of its title; nil on the title slide.
 20        public var heading: Range<Int>?
 21        public var level: Int
 22        /// Where the heading starts; nil on the title slide.
 23        public var start: Int?
 24        public var pieces: [Piece]
 25        /// The text of the slide's notes blocks.
 26        public var notes: String
 27        /// The title slide's title, author and date.
 28        public var title: String?
 29        public var byline: [String] = []
 30    }
 31
 32    public static func slides(_ tree: OrgTree, settings: OrgSettings = .default) -> [Slide] {
 33        let text = tree.text as NSString
 34        let options = ExportOptions.parse(settings.setupKeywords + tree.text)
 35        let meta = HTMLExport.metadata(tree.text, settings: settings)
 36        var slides: [Slide] = []
 37        if let zeroth = tree.root.children.first(where: { $0.kind == .zerothSection }) {
 38            let (pieces, notes) = content(zeroth.children, tree)
 39            let byline = [meta.author, meta.date].compactMap { $0 }.filter { !$0.isEmpty }
 40            if meta.title != nil || !byline.isEmpty || !pieces.isEmpty {
 41                slides.append(Slide(level: 0, pieces: pieces, notes: notes, title: meta.title, byline: byline))
 42            }
 43        }
 44        func visit(_ section: SyntaxNode) {
 45            guard let heading = section.firstChild(.heading) else { return }
 46            let tags = heading.tokens.first { $0.kind == .tags }?.text.split(separator: ":").map(String.init) ?? []
 47            let title = heading.firstChild(.title)?.text.trimmingCharacters(in: .whitespaces) ?? ""
 48            if tags.contains(where: options.excludeTags.contains) || title == "COMMENT" || title.hasPrefix("COMMENT ") { return }
 49            let level = heading.tokens.first { $0.kind == .stars }?.text.count ?? 1
 50            let stars = heading.tokens.first { $0.kind == .stars }?.range ?? heading.range.lowerBound..<heading.range.lowerBound
 51            let lineEnd = heading.tokens.first { $0.kind == .tags }?.range.lowerBound
 52                ?? NSMaxRange(text.lineRange(for: NSRange(location: heading.range.lowerBound, length: 0)))
 53            var end = lineEnd
 54            while end > stars.upperBound, let scalar = Unicode.Scalar(text.character(at: end - 1)), CharacterSet.whitespacesAndNewlines.contains(scalar) { end -= 1 }
 55            let start = min(stars.upperBound + 1, end)
 56            let (pieces, notes) = content(section.children.filter { $0.kind != .heading && $0.kind != .section }, tree)
 57            slides.append(Slide(heading: start..<end, level: level, start: heading.range.lowerBound, pieces: pieces, notes: notes))
 58            for child in section.children where child.kind == .section { visit(child) }
 59        }
 60        for section in tree.root.children where section.kind == .section { visit(section) }
 61        return slides
 62    }
 63
 64    /// What `nodes` show on a slide, image links on lines of their own as images, and the text
 65    /// of their notes blocks.
 66    static func content(_ nodes: [SyntaxNode], _ tree: OrgTree) -> (pieces: [Slide.Piece], notes: String) {
 67        let text = tree.text as NSString
 68        var pieces: [Slide.Piece] = []
 69        var notes: [String] = []
 70        for node in nodes {
 71            switch node.kind {
 72            case .planning, .propertyDrawer, .drawer, .clock, .keyword, .affiliatedKeyword, .comment:
 73                continue
 74            case .block:
 75                let first = node.text.prefix { $0 != "\n" }.lowercased().trimmingCharacters(in: .whitespaces)
 76                if first.hasPrefix("#+begin_notes") {
 77                    let lines = node.text.split(separator: "\n", omittingEmptySubsequences: false).dropFirst()
 78                    let body = lines.prefix { !$0.trimmingCharacters(in: .whitespaces).lowercased().hasPrefix("#+end_notes") }
 79                    notes.append(body.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines))
 80                    continue
 81                }
 82                if first.hasPrefix("#+begin_comment") { continue }
 83            default: break
 84            }
 85            var from = node.range.lowerBound
 86            let images = Presentation.imagePlacements(InlineImages.links(tree, in: node.range), in: text).filter(\.ownLine)
 87            for placement in images where placement.link.range.lowerBound >= from {
 88                let line = text.lineRange(for: NSRange(location: placement.link.range.lowerBound, length: 0))
 89                if line.location > from { pieces.append(.text(from..<line.location)) }
 90                pieces.append(.image(placement.link.image.path, width: placement.link.image.width))
 91                from = min(NSMaxRange(line), node.range.upperBound)
 92            }
 93            if from < node.range.upperBound { pieces.append(.text(from..<node.range.upperBound)) }
 94        }
 95        // Blank lines at the end of the slide's text.
 96        while case .text(let range)? = pieces.last {
 97            var end = range.upperBound
 98            while end > range.lowerBound, let scalar = Unicode.Scalar(text.character(at: end - 1)), CharacterSet.whitespacesAndNewlines.contains(scalar) { end -= 1 }
 99            if end > range.lowerBound {
100                pieces[pieces.count - 1] = .text(range.lowerBound..<end)
101                break
102            }
103            pieces.removeLast()
104        }
105        return (pieces, notes.filter { !$0.isEmpty }.joined(separator: "\n\n"))
106    }
107}
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