Sources/OrgPresentation/Folding.swift
244 lines · 11310 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 /// `org-cycle-set-visibility-according-to-property` and `org-cycle-hide-archived-subtrees`
157 /// after the startup visibility: each heading's `VISIBILITY` (`folded`, `children`, `content`,
158 /// `all`) in turn, then ARCHIVE-tagged subtrees folded.
159 public static func applyVisibilityProperties(_ state: FoldState, in tree: OrgTree) -> FoldState {
160 let outline = outline(tree)
161 let model = DocumentModel(tree: tree)
162 var next = state
163 for (index, heading) in model.headings.enumerated() {
164 guard index < outline.count,
165 let value = heading.properties.last(where: { $0.key.uppercased() == "VISIBILITY" })?.value.lowercased() else { continue }
166 let entry = outline[index]
167 let descendants = outline.filter { $0.start > entry.start && $0.start < entry.end }.map(\.start)
168 let children = outline.enumerated().filter { $0.element.parent == index }.map(\.element.start)
169 switch value {
170 case "folded":
171 next.folds.insert(entry.start)
172 case "children":
173 next.folds.remove(entry.start)
174 next.bodyFolds.remove(entry.start)
175 next.folds.formUnion(children)
176 case "content":
177 next.folds.subtract([entry.start] + descendants)
178 next.bodyFolds.formUnion([entry.start] + descendants)
179 case "all", "showall":
180 next.folds.subtract([entry.start] + descendants)
181 next.bodyFolds.subtract([entry.start] + descendants)
182 default:
183 break
184 }
185 }
186 for (index, heading) in model.headings.enumerated() where index < outline.count && heading.localTags.contains("ARCHIVE") {
187 next.folds.insert(outline[index].start)
188 }
189 return next
190 }
191
192 /// Headings of levels 1 through `levels` visible, no bodies.
193 public static func foldState(showingLevels levels: Int, in tree: OrgTree) -> FoldState {
194 let outline = outline(tree)
195 return FoldState(
196 folds: Set(outline.filter { $0.level == levels }.map(\.start)),
197 bodyFolds: Set(outline.filter { $0.level < levels }.map(\.start))
198 )
199 }
200
201 /// The fold state for the file's `#+STARTUP` visibility, or nil when it sets none.
202 /// `overview`/`fold`, `content`, `showall`/`nofold`/`showeverything`, `show2levels`...
203 public static func startupFoldState(_ tree: OrgTree) -> FoldState? {
204 var result: FoldState?
205 for option in startupOptions(tree) {
206 switch option.lowercased() {
207 case "overview", "fold": result = foldState(for: .overview, in: tree)
208 case "content": result = foldState(for: .contents, in: tree)
209 case "showall", "nofold", "showeverything": result = FoldState()
210 case let word where word.hasPrefix("show") && word.hasSuffix("levels"):
211 if let levels = Int(word.dropFirst(4).dropLast(6)), levels > 0 {
212 result = foldState(showingLevels: levels, in: tree)
213 }
214 default: break
215 }
216 }
217 return result
218 }
219
220 /// Words of every `#+STARTUP:` line. Only element-level keywords count, so text inside
221 /// blocks and paragraphs is never read as a setting.
222 public static func startupOptions(_ tree: OrgTree) -> [String] {
223 var options = tree.settings.setupKeywords.split(separator: "\n").filter { $0.uppercased().hasPrefix("#+STARTUP:") }
224 .flatMap { $0.dropFirst("#+STARTUP:".count).split(whereSeparator: \.isWhitespace).map(String.init) }
225 func visit(_ node: GreenNode) {
226 for case .node(let child) in node.children {
227 switch child.kind {
228 case .keyword:
229 let text = child.text
230 if text.uppercased().drop(while: { $0 == " " || $0 == "\t" }).hasPrefix("#+STARTUP:"),
231 let colon = text.firstIndex(of: ":") {
232 options += text[text.index(after: colon)...].split(whereSeparator: \.isWhitespace).map(String.init)
233 }
234 case .document, .zerothSection, .section, .drawer:
235 visit(child)
236 default:
237 break
238 }
239 }
240 }
241 visit(tree.green)
242 return options
243 }
244}