Sources/OrgPresentation/Folding.swift
207 lines · 9250 bytes
1import OrgCore
2
3/// Which headings are folded, whole subtrees or only their own bodies, and which drawers and
4/// blocks. Drawer and block folds are kept apart, as org's `drawer` and `block` fold specs:
5/// cycling headings leaves them as they are.
6public struct FoldState: Sendable, Equatable {
7 public var folds: Set<Int>
8 public var bodyFolds: Set<Int>
9 /// Opening-line starts of folded drawers and blocks.
10 public var wrapperFolds: Set<Int>
11
12 public init(folds: Set<Int> = [], bodyFolds: Set<Int> = [], wrapperFolds: Set<Int> = []) {
13 self.folds = folds
14 self.bodyFolds = bodyFolds
15 self.wrapperFolds = wrapperFolds
16 }
17}
18
19/// org's global visibility states, cycled by Shift-TAB.
20public enum GlobalVisibility: Sendable, Equatable {
21 /// Top-level headings only.
22 case overview
23 /// Every heading, no bodies.
24 case contents
25 case showAll
26}
27
28public struct OutlineEntry: Sendable, Equatable {
29 /// Start offset of the heading line.
30 public let start: Int
31 public let level: Int
32 /// The title as written.
33 public let title: String
34 /// End of the heading's section.
35 public let end: Int
36 /// Index of the parent entry.
37 public let parent: Int?
38 public let isTopLevel: Bool
39}
40
41extension Presentation {
42 /// Every heading in document order.
43 public static func outline(_ tree: OrgTree) -> [OutlineEntry] {
44 var entries: [OutlineEntry] = []
45 collectOutline(tree.root, parent: nil, topLevel: true, &entries)
46 return entries
47 }
48
49 private static func collectOutline(_ node: SyntaxNode, parent: Int?, topLevel: Bool, _ entries: inout [OutlineEntry]) {
50 for section in node.children where section.kind == .section {
51 guard let heading = section.firstChild(.heading) else { continue }
52 let index = entries.count
53 entries.append(OutlineEntry(
54 start: heading.range.lowerBound,
55 level: heading.tokens.first { $0.kind == .stars }?.text.count ?? 1,
56 title: heading.firstChild(.title)?.text ?? "",
57 end: section.range.upperBound,
58 parent: parent,
59 isTopLevel: topLevel
60 ))
61 collectOutline(section, parent: index, topLevel: false, &entries)
62 }
63 }
64
65 /// TAB on a heading: folded, then its children, then the whole subtree, then folded again.
66 /// A heading without children goes straight from folded to unfolded.
67 public static func cycle(_ heading: Int, in tree: OrgTree, _ state: FoldState) -> FoldState {
68 let outline = outline(tree)
69 guard let index = outline.firstIndex(where: { $0.start == heading }) else { return state }
70 let entry = outline[index]
71 let descendants = outline.filter { $0.start > entry.start && $0.start < entry.end }.map(\.start)
72 let children = outline.enumerated().filter { $0.element.parent == index }.map(\.element.start)
73 var next = state
74 func unfoldSubtree() {
75 next.folds.subtract([heading] + descendants)
76 next.bodyFolds.subtract([heading] + descendants)
77 }
78 if state.folds.contains(heading) {
79 unfoldSubtree()
80 next.folds.formUnion(children)
81 } else if state.bodyFolds.contains(heading) || descendants.contains(where: { state.folds.contains($0) || state.bodyFolds.contains($0) }) {
82 unfoldSubtree()
83 } else {
84 unfoldSubtree()
85 next.folds.insert(heading)
86 }
87 return next
88 }
89
90 /// TAB at `offset` (`org-cycle`): on the first or last line of a drawer or block, folds or
91 /// unfolds it; on a heading, cycles it. Nil elsewhere.
92 public static func cycle(at offset: Int, in tree: OrgTree, _ state: FoldState) -> FoldState? {
93 if let wrapper = Wrappers.toggleable(at: offset, in: tree) {
94 var next = state
95 if next.wrapperFolds.remove(wrapper.start) == nil { next.wrapperFolds.insert(wrapper.start) }
96 return next
97 }
98 return heading(containing: offset, in: tree).map { cycle($0, in: tree, state) }
99 }
100
101 /// Shift-TAB: overview, contents, show all, and around. Drawer and block folds carry over
102 /// from `wrapperFolds`: show all opens blocks, and overview and contents fold the drawers
103 /// before the first heading (`org-cycle-hide-drawers`).
104 public static func cycleGlobal(from current: GlobalVisibility?, in tree: OrgTree, wrapperFolds: Set<Int> = []) -> (GlobalVisibility, FoldState) {
105 let next: GlobalVisibility = switch current {
106 case .overview: .contents
107 case .contents: .showAll
108 case .showAll, nil: .overview
109 }
110 var state = foldState(for: next, in: tree)
111 let wrappers = Wrappers.all(tree)
112 switch next {
113 case .showAll:
114 let blocks = Set(wrappers.filter { $0.kind == .block }.map(\.start))
115 state.wrapperFolds = wrapperFolds.subtracting(blocks)
116 case .overview, .contents:
117 let firstHeading = outline(tree).first?.start ?? Int.max
118 state.wrapperFolds = wrapperFolds.union(wrappers.filter { $0.kind == .drawer && $0.start < firstHeading }.map(\.start))
119 }
120 return (next, state)
121 }
122
123 /// The drawers and blocks folded when a file opens: drawers unless `org-cycle-hide-drawer-startup`
124 /// is off, blocks when `org-cycle-hide-block-startup` is on; `#+STARTUP` (`hidedrawers`,
125 /// `nohidedrawers`, `hideblocks`, `nohideblocks`, `showeverything`) overrides both.
126 public static func startupWrapperFolds(_ tree: OrgTree, hideDrawers: Bool = true, hideBlocks: Bool = false) -> Set<Int> {
127 Set(startupWrappers(tree, hideDrawers: hideDrawers, hideBlocks: hideBlocks).map(\.start))
128 }
129
130 public static func startupWrappers(_ tree: OrgTree, hideDrawers: Bool = true, hideBlocks: Bool = false) -> [Wrapper] {
131 var drawers = hideDrawers
132 var blocks = hideBlocks
133 for option in startupOptions(tree) {
134 switch option.lowercased() {
135 case "hidedrawers": drawers = true
136 case "nohidedrawers": drawers = false
137 case "hideblocks": blocks = true
138 case "nohideblocks": blocks = false
139 case "showeverything": return []
140 default: break
141 }
142 }
143 guard drawers || blocks else { return [] }
144 return Wrappers.all(tree).filter { $0.kind == .drawer ? drawers : blocks }
145 }
146
147 public static func foldState(for visibility: GlobalVisibility, in tree: OrgTree) -> FoldState {
148 let outline = outline(tree)
149 switch visibility {
150 case .overview: return FoldState(folds: Set(outline.filter(\.isTopLevel).map(\.start)))
151 case .contents: return FoldState(bodyFolds: Set(outline.map(\.start)))
152 case .showAll: return FoldState()
153 }
154 }
155
156 /// Headings of levels 1 through `levels` visible, no bodies.
157 public static func foldState(showingLevels levels: Int, in tree: OrgTree) -> FoldState {
158 let outline = outline(tree)
159 return FoldState(
160 folds: Set(outline.filter { $0.level == levels }.map(\.start)),
161 bodyFolds: Set(outline.filter { $0.level < levels }.map(\.start))
162 )
163 }
164
165 /// The fold state for the file's `#+STARTUP` visibility, or nil when it sets none.
166 /// `overview`/`fold`, `content`, `showall`/`nofold`/`showeverything`, `show2levels`...
167 public static func startupFoldState(_ tree: OrgTree) -> FoldState? {
168 var result: FoldState?
169 for option in startupOptions(tree) {
170 switch option.lowercased() {
171 case "overview", "fold": result = foldState(for: .overview, in: tree)
172 case "content": result = foldState(for: .contents, in: tree)
173 case "showall", "nofold", "showeverything": result = FoldState()
174 case let word where word.hasPrefix("show") && word.hasSuffix("levels"):
175 if let levels = Int(word.dropFirst(4).dropLast(6)), levels > 0 {
176 result = foldState(showingLevels: levels, in: tree)
177 }
178 default: break
179 }
180 }
181 return result
182 }
183
184 /// Words of every `#+STARTUP:` line. Only element-level keywords count, so text inside
185 /// blocks and paragraphs is never read as a setting.
186 public static func startupOptions(_ tree: OrgTree) -> [String] {
187 var options: [String] = []
188 func visit(_ node: GreenNode) {
189 for case .node(let child) in node.children {
190 switch child.kind {
191 case .keyword:
192 let text = child.text
193 if text.uppercased().drop(while: { $0 == " " || $0 == "\t" }).hasPrefix("#+STARTUP:"),
194 let colon = text.firstIndex(of: ":") {
195 options += text[text.index(after: colon)...].split(whereSeparator: \.isWhitespace).map(String.init)
196 }
197 case .document, .zerothSection, .section, .drawer:
198 visit(child)
199 default:
200 break
201 }
202 }
203 }
204 visit(tree.green)
205 return options
206 }
207}