Sources/OrgCore/Commands/ListCommands.swift
424 lines · 20945 bytes
1import Foundation
2
3// Plain list commands from org-list.el (Org 9.8.7) on `EmacsBuffer`, matched to Emacs by the
4// oracle tests. The ORDERED property is not handled.
5
6extension EmacsBuffer {
7 /// `org-insert-item`. False when point isn't in an item.
8 func insertListItem(checkbox: Bool) -> Bool {
9 guard let start = inItem() else { return false }
10 let pos = point
11 var structure = saveExcursion { point = start; return listStruct() }
12 let prevs = structure.prevs
13 let description = structure.listType(start, prevs) == .descriptive ? " :: " : nil
14 structure = insertItem(at: pos, structure, prevs, checkbox: checkbox, afterBullet: description, splitLine: options.metaReturnMaySplitLine)
15 writeStruct(&structure, structure.parents)
16 if checkbox { updateCheckboxCount() }
17 forwardLine(0)
18 let match = looking(Self.fullItemPattern)!
19 if let tag = match[4], substring(match[1]!.lowerBound, match[1]!.upperBound).contains(where: { $0 == "." || $0 == ")" }) {
20 point = tag.lowerBound
21 } else {
22 point = match[0]!.upperBound
23 }
24 if description != nil { point -= 1 }
25 return true
26 }
27
28 /// `org-list-indent-item-generic` without a region.
29 func indentItem(_ direction: Int, subtree: Bool) throws {
30 guard atItem else { throw UserError(message: "Not at an item") }
31 var structure = listStruct()
32 try saveExcursion {
33 let top = structure.top
34 let parents = structure.parents
35 let prevs = structure.prevs
36 let line = lineStart(point)
37 let special = top == line
38 if special, !subtree { throw UserError(message: "At first item: use S-M-<left/right> to move the whole list") }
39 let begin = line
40 let end = special ? structure.bottom : !subtree ? line + 1 : structure.end(line)
41 if special {
42 let offset = direction < 0 ? -1 : 1
43 let topInd = structure.ind(begin)
44 let old = structure
45 guard topInd + offset >= 0 else { throw UserError(message: "Cannot outdent beyond margin") }
46 if topInd + offset == 0, structure.bullet(begin).contains("*") {
47 structure.set(begin) { $0.bullet = bulletString("-") }
48 }
49 for i in structure.indices { structure[i].ind += offset }
50 fixBullets(&structure, prevs)
51 applyStruct(structure, old)
52 } else if direction < 0,
53 (!subtree && structure.hasChild(begin) != nil)
54 || structure.hasChild(structure.last { $0.pos < end }!.pos) != nil {
55 throw UserError(message: "Cannot outdent an item without its children")
56 } else {
57 let old = structure
58 let newParents = direction < 0
59 ? try structOutdent(begin, end, structure, parents)
60 : try structIndent(begin, end, structure, parents, prevs)
61 writeStruct(&structure, newParents, old: old)
62 updateCheckboxCount()
63 }
64 }
65 }
66
67 /// `org-move-item-down` and `org-move-item-up`.
68 func moveItem(down: Bool) throws {
69 guard atItem else { throw UserError(message: "Not at an item") }
70 let column = currentColumn
71 let item = lineStart(point)
72 var structure = listStruct()
73 let prevs = structure.prevs
74 if down {
75 guard let next = structure.nextItem(item, prevs) else { throw UserError(message: "Cannot move this item further down") }
76 structure = swapItems(item, next, structure)
77 point = structure.nextItem(item, structure.prevs)!
78 } else {
79 guard let previous = structure.previousItem(item, prevs) else { throw UserError(message: "Cannot move this item further up") }
80 structure = swapItems(previous, item, structure)
81 }
82 writeStruct(&structure, structure.parents)
83 moveToColumn(column)
84 }
85
86 static let affiliatedKeyword = "^[ \\t]*#\\+(?:attr_[-_A-Za-z0-9]+|caption|data|headers?|label|name|plot|resname|results?|source|srcname|tblname)(?:\\[.*\\])?:"
87
88 /// The first item of the list whose affiliated keywords hold point's line, or nil.
89 func affiliatedListStart() -> Int? {
90 saveExcursion {
91 beginningOfLine()
92 guard looking(Self.affiliatedKeyword) != nil else { return nil }
93 while looking(Self.affiliatedKeyword) != nil { if forwardLine(1) != 0 { return nil } }
94 guard looking(itemPattern) != nil, atItem, inItem() == point else { return nil }
95 return point
96 }
97 }
98
99 /// `org-at-radio-list-p`: point's line is an item of a list whose affiliated keywords have
100 /// `#+ATTR_ORG: … :radio` other than `nil`.
101 func atRadioList() -> Bool {
102 guard saveExcursion({ () -> Bool in beginningOfLine(); return looking(itemPattern) != nil }), let item = inItem() else { return false }
103 let structure = saveExcursion { point = item; return listStruct() }
104 guard structure.item(item) != nil else { return false }
105 var line = structure.listBegin(item, structure.prevs)
106 while line > 0 {
107 let previous = lineStart(line - 1)
108 let keyword = substring(previous, line)
109 guard keyword.range(of: Self.affiliatedKeyword, options: [.regularExpression, .caseInsensitive]) != nil else { break }
110 if let radio = keyword.firstMatch(of: /(?i)^[ \t]*#\+attr_org:.* :radio (\S+)/) { return radio.1 != "nil" }
111 line = previous
112 }
113 return false
114 }
115
116 /// `org-toggle-radio-button`: every item of the list at point unchecked, and the item at
117 /// point toggled.
118 func toggleRadioButton() throws {
119 guard atItem, let item = inItem() else { throw UserError(message: "Cannot toggle checkbox outside of a list") }
120 saveExcursion {
121 point = item
122 var structure = listStruct()
123 let old = structure
124 let parents = structure.parents
125 let box = structure.checkbox(item)
126 for pos in structure.allItems(structure.listBegin(item, structure.prevs), structure.prevs) {
127 structure.set(pos) { $0.checkbox = "[ ]" }
128 }
129 structure.set(item) { $0.checkbox = box == "[X]" ? "[ ]" : "[X]" }
130 fixCheckboxes(&structure, parents)
131 applyStruct(structure, old)
132 }
133 updateCheckboxCount()
134 }
135
136 /// `org-toggle-checkbox` on the item at point.
137 func toggleCheckbox() throws {
138 if atRadioList() { return try toggleRadioButton() }
139 guard atItem else { throw UserError(message: "Not at an item or heading, and no active region") }
140 saveExcursion {
141 let lower = lineStart(point)
142 let upper = marker(lineEnd(point))
143 defer { release(upper) }
144 point = lower
145 let current = looking(itemPattern).flatMap { match -> String? in
146 let box = saveExcursion { () -> [Range<Int>?]? in
147 point = match[0]!.upperBound
148 if let counter = looking(options.listAllowAlphabetical ? "(?:\\[@(?:start:)?([0-9]+|[A-Za-z])\\][ \\t]*)" : "(?:\\[@(?:start:)?[0-9]+\\][ \\t]*)") { point = counter[0]!.upperBound }
149 return looking("(\\[[- X]\\])[ \\t]+")
150 }
151 return box.map { substring($0[1]!.lowerBound, $0[1]!.upperBound) }
152 }
153 let reference = current == "[X]" ? "[ ]" : "[X]"
154 point = lower
155 while point < upper.position, searchForward(itemBeginningPattern, bound: upper.position, move: true) != nil {
156 var structure = listStruct()
157 let old = structure
158 let parents = structure.parents
159 let bottom = marker(structure.bottom)
160 for i in structure.indices where structure[i].pos >= lower && structure[i].pos <= upper.position {
161 if structure[i].checkbox != nil { structure[i].checkbox = reference }
162 }
163 fixCheckboxes(&structure, parents)
164 point = bottom.position
165 release(bottom)
166 applyStruct(structure, old)
167 }
168 }
169 updateCheckboxCount()
170 }
171
172 // MARK: - Statistics
173
174 /// `org-update-checkbox-count` for the current section.
175 func updateCheckboxCount() {
176 saveExcursion {
177 let end = saveExcursion { () -> Int in outlineNextHeading(); return point }
178 if beforeFirstHeading { point = 0 } else { _ = try? backToHeading() }
179 let sectionStart = point
180 let section = OrgParser.parse(substring(sectionStart, end))
181 let cookies = section.root.descendants().filter { $0.kind == .statisticsCookie }.map { node in
182 (range: (node.range.lowerBound + sectionStart)..<(node.range.upperBound + sectionStart), node: node)
183 }
184 let cookieData = entryProperty("COOKIE_DATA", sectionStart: sectionStart, end: end) ?? ""
185 let recursive = cookieData.range(of: "\\brecursive\\b", options: .regularExpression) != nil
186 var found: [(begin: Int, end: Int, percent: Bool, checked: Int, total: Int)] = []
187 var cache: [Int: (Int, Int)] = [:]
188 let cookiePattern = "((\\[[0-9]*%\\])|(\\[[0-9]*/[0-9]*\\]))"
189 while let match = searchForward(cookiePattern, bound: end) {
190 let last = match[0]!.upperBound - 1
191 guard let cookie = cookies.first(where: { $0.range.contains(last) }), cookieData.range(of: "\\btodo\\b", options: .regularExpression) == nil else { continue }
192 let container = containerRange(of: cookie.node, sectionStart: sectionStart)
193 let begin = container?.contents.lowerBound ?? saveExcursion { () -> Int in
194 point = match[0]!.lowerBound
195 outlinePreviousHeading()
196 return point
197 }
198 let count: (Int, Int)
199 if let cached = cache[begin] {
200 count = cached
201 } else {
202 let limit = container?.contents.upperBound ?? end
203 var structures: [ListStruct] = []
204 saveExcursion {
205 point = begin
206 let boxPattern = "^[ \\t]*([-+*]|([0-9]+|[A-Za-z])[.)])[ \\t]+(?:\\[@(?:start:)?([0-9]+|[A-Za-z])\\][ \\t]*)?(\\[[- X]\\])"
207 while searchForward(boxPattern, bound: limit) != nil {
208 guard atItem else { continue }
209 let structure = listStruct()
210 structures.append(structure)
211 point = min(max(structure.bottom, point), limit)
212 }
213 }
214 count = countBoxes(item: container?.item, structures, recursive: recursive)
215 cache[begin] = count
216 }
217 found.insert((match[1]!.lowerBound, match[1]!.upperBound, match[2] != nil, count.0, count.1), at: 0)
218 }
219 for cookie in found {
220 point = cookie.begin
221 let text = cookie.percent ? "[\(Int((100.0 * Double(cookie.checked) / Double(max(1, cookie.total))).rounded(.down)))%]" : "[\(cookie.checked)/\(cookie.total)]"
222 insert(text)
223 deleteRegion(point, point + (cookie.end - cookie.begin))
224 fixTagsOnTheFly()
225 }
226 }
227 }
228
229 /// Checked and total boxes, as `count-boxes` in `org-update-checkbox-count`.
230 private func countBoxes(item: Int?, _ structures: [ListStruct], recursive: Bool) -> (Int, Int) {
231 var on = 0, all = 0
232 for structure in structures {
233 let items: [Int]
234 if recursive, let item {
235 items = structure.subtree(item)
236 } else if recursive {
237 items = structure.map(\.pos)
238 } else if let item {
239 items = structure.children(item, structure.parents)
240 } else {
241 items = structure.allItems(structure.top, structure.prevs)
242 }
243 let boxes = items.compactMap { structure.checkbox($0) }
244 all += boxes.count
245 on += boxes.filter { $0 == "[X]" }.count
246 }
247 return (on, all)
248 }
249
250 /// The innermost container org counts a statistics cookie over: its contents range, and its
251 /// start when it is an item.
252 private func containerRange(of cookie: SyntaxNode, sectionStart: Int) -> (contents: Range<Int>, item: Int?)? {
253 var node = cookie.parent
254 while let current = node {
255 let start = current.range.lowerBound + sectionStart
256 let end = current.range.upperBound + sectionStart
257 switch current.kind {
258 case .item:
259 let item = start
260 let structure = saveExcursion { point = item; return listStruct() }
261 let itemEnd = structure.item(item)?.end ?? end
262 let contentsStart = saveExcursion { () -> Int? in
263 point = item
264 let match = looking(Self.fullItemPattern)!
265 let bullet = substring(match[1]!.lowerBound, match[1]!.upperBound)
266 point = match[4] != nil && bullet.contains(where: { $0 == "." || $0 == ")" }) ? match[4]!.lowerBound : match[0]!.upperBound
267 while point < itemEnd, let c = character(at: point), Self.whitespace.contains(c) { point += 1 }
268 if point == itemEnd { return nil }
269 return bolp ? lineStart(point) : point
270 }
271 guard let contentsStart else { return (item..<item, item) }
272 let contentsEnd = saveExcursion { () -> Int in
273 point = itemEnd
274 skipBackward(Self.whitespace)
275 return min(lineEnd(point) + 1, length)
276 }
277 return (contentsStart..<contentsEnd, item)
278 case .drawer, .dynamicBlock:
279 return (bodyRange(start, end), nil)
280 case .block:
281 let firstLine = substring(start, lineEnd(start)).lowercased()
282 let name = firstLine.range(of: "#\\+begin_(\\S+)", options: .regularExpression).map { String(firstLine[$0].dropFirst(8)) } ?? ""
283 if !["src", "example", "export", "comment"].contains(name) { return (bodyRange(start, end), nil) }
284 default:
285 break
286 }
287 node = current.parent
288 }
289 return nil
290 }
291
292 /// Lines between a container's first and last line.
293 private func bodyRange(_ start: Int, _ end: Int) -> Range<Int> {
294 let contentsStart = lineEnd(start) + 1
295 var last = end
296 if character(at: last - 1) == Self.newline { last -= 1 }
297 let closing = saveExcursion { () -> Int in
298 point = last
299 skipBackward(Self.whitespace)
300 return lineStart(point)
301 }
302 return contentsStart..<max(contentsStart, closing)
303 }
304
305 /// A property of the entry from its property drawer, without inheritance.
306 private func entryProperty(_ name: String, sectionStart: Int, end: Int) -> String? {
307 let text = substring(sectionStart, end)
308 let pattern = "^[ \\t]*:" + NSRegularExpression.escapedPattern(for: name) + ":[ \\t]+(.*?)[ \\t]*$"
309 guard let range = text.range(of: pattern, options: [.regularExpression, .caseInsensitive]) else { return nil }
310 return String(text[range]).replacingOccurrences(of: "^[ \\t]*:[^:]+:[ \\t]+", with: "", options: .regularExpression)
311 }
312
313 /// `org-fix-tags-on-the-fly`.
314 private func fixTagsOnTheFly() {
315 let line = saveExcursion { () -> [Range<Int>?]? in
316 beginningOfLine()
317 return looking(SetTags.tagLine)
318 }
319 guard let tags = line?[1], point < tags.lowerBound else { return }
320 alignTags(onLineAt: point)
321 }
322}
323
324private func listCommand(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
325 commitBuffer(context, body)
326}
327
328/// M-RET in a list: `org-insert-item`.
329public struct InsertItem: OrgCommand {
330 public init() {}
331 public var id: String { "org.item.insert" }
332 public var title: String { "Insert Item" }
333 public func applies(in context: EditContext) -> Bool { KeyContext.holds("item", in: context) }
334 public func run(in context: EditContext) -> CommandStep {
335 // A timer list's items are added by `org-timer-item`.
336 if EmacsBuffer.atTimerList(context) { return InsertTimerItem().run(in: context) }
337 return listCommand(context) { buffer in
338 guard buffer.insertListItem(checkbox: false) else { throw EmacsBuffer.UserError(message: "Not in an item") }
339 }
340 }
341}
342
343/// M-S-RET in a list: `org-insert-item` with a checkbox.
344public struct InsertCheckboxItem: OrgCommand {
345 public init() {}
346 public var id: String { "org.item.insert-checkbox" }
347 public var title: String { "Insert Checkbox Item" }
348 public func applies(in context: EditContext) -> Bool { KeyContext.holds("item", in: context) }
349 public func run(in context: EditContext) -> CommandStep {
350 // A timer list's items are added by `org-timer-item`.
351 if EmacsBuffer.atTimerList(context) { return InsertTimerItem().run(in: context) }
352 return listCommand(context) { buffer in
353 guard buffer.insertListItem(checkbox: true) else { throw EmacsBuffer.UserError(message: "Not in an item") }
354 }
355 }
356}
357
358/// An item command that needs point on an item's first line.
359private func atItemLine(_ context: EditContext) -> Bool {
360 EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options).atItem
361}
362
363/// M-right on an item: `org-indent-item`.
364public struct IndentItem: OrgCommand {
365 public init() {}
366 public var id: String { "org.item.indent" }
367 public var title: String { "Indent Item" }
368 public func applies(in context: EditContext) -> Bool { atItemLine(context) }
369 public func run(in context: EditContext) -> CommandStep { listCommand(context) { try $0.indentItem(1, subtree: false) } }
370}
371
372/// M-left on an item: `org-outdent-item`.
373public struct OutdentItem: OrgCommand {
374 public init() {}
375 public var id: String { "org.item.outdent" }
376 public var title: String { "Outdent Item" }
377 public func applies(in context: EditContext) -> Bool { atItemLine(context) }
378 public func run(in context: EditContext) -> CommandStep { listCommand(context) { try $0.indentItem(-1, subtree: false) } }
379}
380
381/// M-S-right on an item: `org-indent-item-tree`.
382public struct IndentItemTree: OrgCommand {
383 public init() {}
384 public var id: String { "org.item.indent-tree" }
385 public var title: String { "Indent Item and Children" }
386 public func applies(in context: EditContext) -> Bool { atItemLine(context) }
387 public func run(in context: EditContext) -> CommandStep { listCommand(context) { try $0.indentItem(1, subtree: true) } }
388}
389
390/// M-S-left on an item: `org-outdent-item-tree`.
391public struct OutdentItemTree: OrgCommand {
392 public init() {}
393 public var id: String { "org.item.outdent-tree" }
394 public var title: String { "Outdent Item and Children" }
395 public func applies(in context: EditContext) -> Bool { atItemLine(context) }
396 public func run(in context: EditContext) -> CommandStep { listCommand(context) { try $0.indentItem(-1, subtree: true) } }
397}
398
399/// M-up on an item: `org-move-item-up`.
400public struct MoveItemUp: OrgCommand {
401 public init() {}
402 public var id: String { "org.item.up" }
403 public var title: String { "Move Item Up" }
404 public func applies(in context: EditContext) -> Bool { atItemLine(context) }
405 public func run(in context: EditContext) -> CommandStep { listCommand(context) { try $0.moveItem(down: false) } }
406}
407
408/// M-down on an item: `org-move-item-down`.
409public struct MoveItemDown: OrgCommand {
410 public init() {}
411 public var id: String { "org.item.down" }
412 public var title: String { "Move Item Down" }
413 public func applies(in context: EditContext) -> Bool { atItemLine(context) }
414 public func run(in context: EditContext) -> CommandStep { listCommand(context) { try $0.moveItem(down: true) } }
415}
416
417/// C-c C-c on an item: `org-toggle-checkbox`.
418public struct ToggleCheckbox: OrgCommand {
419 public init() {}
420 public var id: String { "org.checkbox.toggle" }
421 public var title: String { "Toggle Checkbox" }
422 public func applies(in context: EditContext) -> Bool { atItemLine(context) }
423 public func run(in context: EditContext) -> CommandStep { listCommand(context) { try $0.toggleCheckbox() } }
424}