Sources/OrgCore/Commands/ElementCommands.swift
167 lines · 9019 bytes
1import Foundation
2
3// Org 9.8.7: `org-insert-drawer` (C-c C-x d), `org-drag-element-forward` and
4// `org-drag-element-backward` (M-<down> and M-<up> away from headings, items and tables), and
5// `org-cycle-list-bullet` both ways (S-<right> and S-<left> on items).
6
7/// C-c C-x d: `org-insert-drawer`. Asks for the name; inserts an empty drawer at the caret,
8/// or puts the selected lines in it.
9public struct InsertDrawer: OrgCommand {
10 public init() {}
11 public var id: String { "org.drawer.insert" }
12 public var title: String { "Insert Drawer" }
13 public func applies(in context: EditContext) -> Bool { true }
14 public func run(in context: EditContext) -> CommandStep {
15 guard let name = context.answers["drawer"] else { return .prompt(Prompt(key: "drawer", message: "Drawer:")) }
16 guard (":" + name + ":").range(of: "^:[-_\\w]+:$", options: .regularExpression) != nil else { return .failed("Invalid drawer name") }
17 let region = context.selection.first.flatMap { $0.isEmpty ? nil : $0 }
18 return commitBuffer(context) { buffer in
19 guard let region else {
20 if !buffer.bolp { buffer.insert("\n") }
21 buffer.insert(":\(name):\n\n:END:\n")
22 buffer.forwardLine(-2)
23 return
24 }
25 let end = buffer.marker(region.upperBound)
26 defer { buffer.release(end) }
27 buffer.point = buffer.lineStart(region.lowerBound)
28 if buffer.searchForward("^\\*+ ", bound: end.position, caseInsensitive: false) != nil {
29 throw EmacsBuffer.UserError(message: "Drawers cannot contain headlines")
30 }
31 // The drawer opens on the region's first non-blank line and closes after its last,
32 // at the section's indentation, and the caret ends before `:END:`.
33 buffer.point = region.lowerBound
34 buffer.skipForward([32, 9, 10, 13])
35 buffer.point = buffer.lineStart(buffer.point)
36 buffer.insert(":\(name):\n")
37 buffer.point = end.position
38 buffer.skipBackward([32, 9, 10, 13])
39 buffer.insert("\n:END:")
40 if !buffer.eolp { buffer.insert("\n") }
41 buffer.point = buffer.lineStart(buffer.point) - 1
42 }
43 }
44}
45
46/// M-<down> and M-<up> on other elements: `org-drag-element-forward` and
47/// `org-drag-element-backward`, the element swapped with the next or previous one in the same
48/// section, drawer or block, the blank lines between them kept.
49public struct DragElement: OrgCommand {
50 public let forward: Bool
51 public init(forward: Bool) { self.forward = forward }
52 public var id: String { forward ? "org.element.drag-forward" : "org.element.drag-backward" }
53 public var title: String { forward ? "Drag Element Forward" : "Drag Element Backward" }
54 public func applies(in context: EditContext) -> Bool { true }
55
56 /// An element with its affiliated keywords, the blank lines after it, and where its own
57 /// text ends (the end of its last non-blank line).
58 struct Unit {
59 let begin: Int
60 var end: Int
61 let bodyEnd: Int
62 let node: SyntaxNode
63 let isHeading: Bool
64 }
65
66 /// The elements of `container`, whose ranges count from `base` in `ns`.
67 static func units(_ container: SyntaxNode, _ ns: NSString, base: Int = 0) -> [Unit] {
68 var units: [Unit] = []
69 var affiliated: Int?
70 for child in container.children {
71 if child.kind == .heading, child.range.lowerBound == container.range.lowerBound { continue }
72 if child.kind == .affiliatedKeyword {
73 affiliated = affiliated ?? base + child.range.lowerBound
74 continue
75 }
76 if child.kind == .zerothSection {
77 units += Self.units(child, ns, base: base)
78 continue
79 }
80 var bodyEnd = base + child.range.upperBound
81 while bodyEnd > base + child.range.lowerBound, [10, 13, 32, 9].contains(ns.character(at: bodyEnd - 1)) { bodyEnd -= 1 }
82 let begin = affiliated ?? base + child.range.lowerBound
83 affiliated = nil
84 if var last = units.popLast() {
85 last.end = begin
86 units.append(last)
87 }
88 units.append(Unit(begin: begin, end: base + container.range.upperBound, bodyEnd: bodyEnd, node: child, isHeading: child.kind == .section || child.kind == .heading))
89 }
90 return units
91 }
92
93 /// A drawer or a block other than src, example, export, comment and verse: its lines are
94 /// elements.
95 static func isGreater(_ node: SyntaxNode) -> Bool {
96 if node.kind == .drawer { return true }
97 guard node.kind == .block, let type = node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/)?.1.lowercased() else { return false }
98 return !["src", "example", "export", "comment", "verse"].contains(type)
99 }
100
101 /// The element `org-element-at-point` finds at `offset`, with its siblings: the deepest
102 /// section, drawer or greater block's units, and its place among them.
103 static func locate(_ offset: Int, tree: OrgTree, text: NSString) -> (units: [Unit], index: Int)? {
104 // The innermost section (or the text before the first heading) holding the offset.
105 var container = tree.root
106 func holds(_ node: SyntaxNode) -> Bool {
107 node.range.lowerBound <= offset && (offset < node.range.upperBound || (offset == node.range.upperBound && offset == text.length))
108 }
109 while let section = container.children.first(where: { ($0.kind == .section || $0.kind == .zerothSection) && holds($0) }) { container = section }
110 var base = 0
111 while true {
112 let units = Self.units(container, text, base: base)
113 guard let index = units.lastIndex(where: { $0.begin <= offset }) else { return nil }
114 let unit = units[index]
115 // Inside a drawer or a greater block, below its first line and above its last: its
116 // contents' elements.
117 let opening = NSMaxRange(text.lineRange(for: NSRange(location: base + unit.node.range.lowerBound, length: 0)))
118 let closing = text.lineRange(for: NSRange(location: unit.bodyEnd, length: 0)).location
119 if Self.isGreater(unit.node), offset >= opening, offset < closing {
120 let inner = OrgParser.parse(text.substring(with: NSRange(location: opening, length: closing - opening)))
121 guard !Self.units(inner.root, text, base: opening).isEmpty else { return (units, index) }
122 container = inner.root
123 base = opening
124 continue
125 }
126 return (units, index)
127 }
128 }
129
130 public func run(in context: EditContext) -> CommandStep {
131 let ns = context.text as NSString
132 let caret = context.caret
133 let failure = forward ? "Cannot drag element forward" : "Cannot drag element backward"
134 guard let (units, index) = Self.locate(caret, tree: context.tree, text: ns), !units[index].isHeading else { return .failed(failure) }
135 let other = forward ? index + 1 : index - 1
136 guard units.indices.contains(other), !units[other].isHeading else { return .failed(failure) }
137 let (a, b) = forward ? (units[index], units[other]) : (units[other], units[index])
138 let bodyA = ns.substring(with: NSRange(location: a.begin, length: a.bodyEnd - a.begin))
139 let bodyB = ns.substring(with: NSRange(location: b.begin, length: b.bodyEnd - b.begin))
140 let middle = ns.substring(with: NSRange(location: a.bodyEnd, length: b.begin - a.bodyEnd))
141 let edit = TextEdit(range: a.begin..<b.bodyEnd, replacement: bodyB + middle + bodyA)
142 let newCaret: Int
143 if forward {
144 let lineAfterB = b.bodyEnd < ns.length ? b.bodyEnd + 1 : b.bodyEnd
145 let lineAfterA = a.bodyEnd < ns.length ? a.bodyEnd + 1 : a.bodyEnd
146 newCaret = caret + (lineAfterB - b.begin) + (a.end - lineAfterA)
147 } else {
148 newCaret = a.begin + (caret - b.begin)
149 }
150 return .commit(EditResult(baseRevision: context.revision, edits: [edit], selection: [newCaret..<newCaret]))
151 }
152}
153
154/// S-<right> and S-<left> on an item: `org-cycle-list-bullet`, the list's bullets to the next
155/// kind, or with `previous` the one before.
156public struct CycleBullet: OrgCommand {
157 public let previous: Bool
158 public init(previous: Bool) { self.previous = previous }
159 public var id: String { previous ? "org.item.bullet-previous" : "org.item.bullet-next" }
160 public var title: String { previous ? "Previous Bullet Type" : "Next Bullet Type" }
161 public func applies(in context: EditContext) -> Bool {
162 EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings).inItem() != nil
163 }
164 public func run(in context: EditContext) -> CommandStep {
165 commitBuffer(context) { try $0.cycleListBullet(previous: previous) }
166 }
167}