Sources/OrgPresentation/Folding.swift
299 lines · 13863 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 /// Doom's `za` (`+org/toggle-fold`) on a heading: folded, it opens one level (its body and
91 /// child headings, folded); otherwise it folds.
92 public static func toggleFold(_ heading: Int, in tree: OrgTree, _ state: FoldState) -> FoldState {
93 isFolded(heading, state) ? showChildren(heading, in: tree, state) : hideSubtree(heading, state)
94 }
95
96 /// Doom's `zo` (`+org/open-fold`): a folded heading opens one level; an open one stays.
97 public static func openFold(_ heading: Int, in tree: OrgTree, _ state: FoldState) -> FoldState {
98 isFolded(heading, state) ? showChildren(heading, in: tree, state) : state
99 }
100
101 /// `zc` (`outline-hide-subtree`): the heading's subtree folded.
102 public static func hideSubtree(_ heading: Int, _ state: FoldState) -> FoldState {
103 var next = state
104 next.folds.insert(heading)
105 return next
106 }
107
108 /// Doom's `zO` (`outline-show-subtree`): the heading's whole subtree open.
109 public static func showSubtree(_ heading: Int, in tree: OrgTree, _ state: FoldState) -> FoldState {
110 guard let entry = outline(tree).first(where: { $0.start == heading }) else { return state }
111 var next = state
112 next.folds = next.folds.filter { $0 < entry.start || $0 >= entry.end }
113 next.bodyFolds = next.bodyFolds.filter { $0 < entry.start || $0 >= entry.end }
114 return next
115 }
116
117 /// Doom's `zR` (`outline-show-all`): every heading open; drawers and blocks stay as they are.
118 public static func showAllHeadings(_ state: FoldState) -> FoldState {
119 FoldState(wrapperFolds: state.wrapperFolds)
120 }
121
122 /// `outline-hide-sublevels`, behind Doom's `zM`, `zr` and `zm`: headings down to `levels`
123 /// show, without bodies.
124 public static func hideSublevels(_ levels: Int, in tree: OrgTree, _ state: FoldState) -> FoldState {
125 var next = foldState(showingLevels: levels, in: tree)
126 next.wrapperFolds = state.wrapperFolds
127 return next
128 }
129
130 /// Doom's `+org--get-foldlevel`: the deepest level of a visible folded heading, or 1.
131 public static func foldLevel(in tree: OrgTree, _ state: FoldState) -> Int {
132 let outline = outline(tree)
133 var level = 1
134 for entry in outline where isFolded(entry.start, state) {
135 var parent = entry.parent
136 var hidden = false
137 while let index = parent {
138 if state.folds.contains(outline[index].start) { hidden = true }
139 parent = outline[index].parent
140 }
141 if !hidden { level = max(level, entry.level) }
142 }
143 return level
144 }
145
146 /// Whether the heading's body is hidden.
147 private static func isFolded(_ heading: Int, _ state: FoldState) -> Bool {
148 state.folds.contains(heading) || state.bodyFolds.contains(heading)
149 }
150
151 /// org's children view of a heading: its body and child headings show, their subtrees folded.
152 private static func showChildren(_ heading: Int, in tree: OrgTree, _ state: FoldState) -> FoldState {
153 let outline = outline(tree)
154 guard let index = outline.firstIndex(where: { $0.start == heading }) else { return state }
155 let entry = outline[index]
156 let subtree = outline.filter { $0.start >= entry.start && $0.start < entry.end }.map(\.start)
157 var next = state
158 next.folds.subtract(subtree)
159 next.bodyFolds.subtract(subtree)
160 next.folds.formUnion(outline.enumerated().filter { $0.element.parent == index }.map(\.element.start))
161 return next
162 }
163
164 /// TAB at `offset` (`org-cycle`): on the first or last line of a drawer or block, folds or
165 /// unfolds it; on a heading, cycles it. Nil elsewhere.
166 public static func cycle(at offset: Int, in tree: OrgTree, _ state: FoldState) -> FoldState? {
167 if let wrapper = Wrappers.toggleable(at: offset, in: tree) {
168 var next = state
169 if next.wrapperFolds.remove(wrapper.start) == nil { next.wrapperFolds.insert(wrapper.start) }
170 return next
171 }
172 return heading(containing: offset, in: tree).map { cycle($0, in: tree, state) }
173 }
174
175 /// Shift-TAB: overview, contents, show all, and around. Drawer and block folds carry over
176 /// from `wrapperFolds`: show all opens blocks, and overview and contents fold the drawers
177 /// before the first heading (`org-cycle-hide-drawers`).
178 public static func cycleGlobal(from current: GlobalVisibility?, in tree: OrgTree, wrapperFolds: Set<Int> = []) -> (GlobalVisibility, FoldState) {
179 let next: GlobalVisibility = switch current {
180 case .overview: .contents
181 case .contents: .showAll
182 case .showAll, nil: .overview
183 }
184 var state = foldState(for: next, in: tree)
185 let wrappers = Wrappers.all(tree)
186 switch next {
187 case .showAll:
188 let blocks = Set(wrappers.filter { $0.kind == .block }.map(\.start))
189 state.wrapperFolds = wrapperFolds.subtracting(blocks)
190 case .overview, .contents:
191 let firstHeading = outline(tree).first?.start ?? Int.max
192 state.wrapperFolds = wrapperFolds.union(wrappers.filter { $0.kind == .drawer && $0.start < firstHeading }.map(\.start))
193 }
194 return (next, state)
195 }
196
197 /// The drawers and blocks folded when a file opens: drawers unless `org-cycle-hide-drawer-startup`
198 /// is off, blocks when `org-cycle-hide-block-startup` is on; `#+STARTUP` (`hidedrawers`,
199 /// `nohidedrawers`, `hideblocks`, `nohideblocks`, `showeverything`) overrides both.
200 public static func startupWrapperFolds(_ tree: OrgTree, hideDrawers: Bool = true, hideBlocks: Bool = false) -> Set<Int> {
201 Set(startupWrappers(tree, hideDrawers: hideDrawers, hideBlocks: hideBlocks).map(\.start))
202 }
203
204 public static func startupWrappers(_ tree: OrgTree, hideDrawers: Bool = true, hideBlocks: Bool = false) -> [Wrapper] {
205 var drawers = hideDrawers
206 var blocks = hideBlocks
207 for option in startupOptions(tree) {
208 switch option.lowercased() {
209 case "hidedrawers": drawers = true
210 case "nohidedrawers": drawers = false
211 case "hideblocks": blocks = true
212 case "nohideblocks": blocks = false
213 case "showeverything": return []
214 default: break
215 }
216 }
217 guard drawers || blocks else { return [] }
218 return Wrappers.all(tree).filter { $0.kind == .drawer ? drawers : blocks }
219 }
220
221 public static func foldState(for visibility: GlobalVisibility, in tree: OrgTree) -> FoldState {
222 let outline = outline(tree)
223 switch visibility {
224 case .overview: return FoldState(folds: Set(outline.filter(\.isTopLevel).map(\.start)))
225 case .contents: return FoldState(bodyFolds: Set(outline.map(\.start)))
226 case .showAll: return FoldState()
227 }
228 }
229
230 /// `org-cycle-set-visibility-according-to-property` and `org-cycle-hide-archived-subtrees`
231 /// after the startup visibility: each heading's `VISIBILITY` (`folded`, `children`, `content`,
232 /// `all`) in turn, then ARCHIVE-tagged subtrees folded.
233 public static func applyVisibilityProperties(_ state: FoldState, in tree: OrgTree) -> FoldState {
234 let outline = outline(tree)
235 let model = DocumentModel(tree: tree)
236 var next = state
237 for (index, heading) in model.headings.enumerated() {
238 guard index < outline.count,
239 let value = heading.properties.last(where: { $0.key.uppercased() == "VISIBILITY" })?.value.lowercased() else { continue }
240 let entry = outline[index]
241 let descendants = outline.filter { $0.start > entry.start && $0.start < entry.end }.map(\.start)
242 let children = outline.enumerated().filter { $0.element.parent == index }.map(\.element.start)
243 switch value {
244 case "folded":
245 next.folds.insert(entry.start)
246 case "children":
247 next.folds.remove(entry.start)
248 next.bodyFolds.remove(entry.start)
249 next.folds.formUnion(children)
250 case "content":
251 next.folds.subtract([entry.start] + descendants)
252 next.bodyFolds.formUnion([entry.start] + descendants)
253 case "all", "showall":
254 next.folds.subtract([entry.start] + descendants)
255 next.bodyFolds.subtract([entry.start] + descendants)
256 default:
257 break
258 }
259 }
260 for (index, heading) in model.headings.enumerated() where index < outline.count && heading.localTags.contains("ARCHIVE") {
261 next.folds.insert(outline[index].start)
262 }
263 return next
264 }
265
266 /// Headings of levels 1 through `levels` visible, no bodies.
267 public static func foldState(showingLevels levels: Int, in tree: OrgTree) -> FoldState {
268 let outline = outline(tree)
269 return FoldState(
270 folds: Set(outline.filter { $0.level == levels }.map(\.start)),
271 bodyFolds: Set(outline.filter { $0.level < levels }.map(\.start))
272 )
273 }
274
275 /// The fold state for the file's `#+STARTUP` visibility, or nil when it sets none.
276 /// `overview`/`fold`, `content`, `showall`/`nofold`/`showeverything`, `show2levels`...
277 public static func startupFoldState(_ tree: OrgTree) -> FoldState? {
278 var result: FoldState?
279 for option in startupOptions(tree) {
280 switch option.lowercased() {
281 case "overview", "fold": result = foldState(for: .overview, in: tree)
282 case "content": result = foldState(for: .contents, in: tree)
283 case "showall", "nofold", "showeverything": result = FoldState()
284 case let word where word.hasPrefix("show") && word.hasSuffix("levels"):
285 if let levels = Int(word.dropFirst(4).dropLast(6)), levels > 0 {
286 result = foldState(showingLevels: levels, in: tree)
287 }
288 default: break
289 }
290 }
291 return result
292 }
293
294 /// Words of every `#+STARTUP:` keyword line (`OrgSettings.startup`); lines inside blocks
295 /// are not settings.
296 public static func startupOptions(_ tree: OrgTree) -> [String] {
297 tree.settings.startup
298 }
299}