Sources/OrgCore/Commands/ElementCommands.swift
168 lines · 9138 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 if buffer.lookingAtLine("^:END:") == nil { buffer.point = buffer.lineStart(max(0, buffer.point - 1)) - 1 }
43 }
44 }
45}
46
47/// M-<down> and M-<up> on other elements: `org-drag-element-forward` and
48/// `org-drag-element-backward`, the element swapped with the next or previous one in the same
49/// section, drawer or block, the blank lines between them kept.
50public struct DragElement: OrgCommand {
51 public let forward: Bool
52 public init(forward: Bool) { self.forward = forward }
53 public var id: String { forward ? "org.element.drag-forward" : "org.element.drag-backward" }
54 public var title: String { forward ? "Drag Element Forward" : "Drag Element Backward" }
55 public func applies(in context: EditContext) -> Bool { true }
56
57 /// An element with its affiliated keywords, the blank lines after it, and where its own
58 /// text ends (the end of its last non-blank line).
59 struct Unit {
60 let begin: Int
61 var end: Int
62 let bodyEnd: Int
63 let node: SyntaxNode
64 let isHeading: Bool
65 }
66
67 /// The elements of `container`, whose ranges count from `base` in `ns`.
68 static func units(_ container: SyntaxNode, _ ns: NSString, base: Int = 0) -> [Unit] {
69 var units: [Unit] = []
70 var affiliated: Int?
71 for child in container.children {
72 if child.kind == .heading, child.range.lowerBound == container.range.lowerBound { continue }
73 if child.kind == .affiliatedKeyword {
74 affiliated = affiliated ?? base + child.range.lowerBound
75 continue
76 }
77 if child.kind == .zerothSection {
78 units += Self.units(child, ns, base: base)
79 continue
80 }
81 var bodyEnd = base + child.range.upperBound
82 while bodyEnd > base + child.range.lowerBound, [10, 13, 32, 9].contains(ns.character(at: bodyEnd - 1)) { bodyEnd -= 1 }
83 let begin = affiliated ?? base + child.range.lowerBound
84 affiliated = nil
85 if var last = units.popLast() {
86 last.end = begin
87 units.append(last)
88 }
89 units.append(Unit(begin: begin, end: base + container.range.upperBound, bodyEnd: bodyEnd, node: child, isHeading: child.kind == .section || child.kind == .heading))
90 }
91 return units
92 }
93
94 /// A drawer or a block other than src, example, export, comment and verse: its lines are
95 /// elements.
96 static func isGreater(_ node: SyntaxNode) -> Bool {
97 if node.kind == .drawer { return true }
98 guard node.kind == .block, let type = node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/)?.1.lowercased() else { return false }
99 return !["src", "example", "export", "comment", "verse"].contains(type)
100 }
101
102 /// The element `org-element-at-point` finds at `offset`, with its siblings: the deepest
103 /// section, drawer or greater block's units, and its place among them.
104 static func locate(_ offset: Int, tree: OrgTree, text: NSString) -> (units: [Unit], index: Int)? {
105 // The innermost section (or the text before the first heading) holding the offset.
106 var container = tree.root
107 func holds(_ node: SyntaxNode) -> Bool {
108 node.range.lowerBound <= offset && (offset < node.range.upperBound || (offset == node.range.upperBound && offset == text.length))
109 }
110 while let section = container.children.first(where: { ($0.kind == .section || $0.kind == .zerothSection) && holds($0) }) { container = section }
111 var base = 0
112 while true {
113 let units = Self.units(container, text, base: base)
114 guard let index = units.lastIndex(where: { $0.begin <= offset }) else { return nil }
115 let unit = units[index]
116 // Inside a drawer or a greater block, below its first line and above its last: its
117 // contents' elements.
118 let opening = NSMaxRange(text.lineRange(for: NSRange(location: base + unit.node.range.lowerBound, length: 0)))
119 let closing = text.lineRange(for: NSRange(location: unit.bodyEnd, length: 0)).location
120 if Self.isGreater(unit.node), offset >= opening, offset < closing {
121 let inner = OrgParser.parse(text.substring(with: NSRange(location: opening, length: closing - opening)))
122 guard !Self.units(inner.root, text, base: opening).isEmpty else { return (units, index) }
123 container = inner.root
124 base = opening
125 continue
126 }
127 return (units, index)
128 }
129 }
130
131 public func run(in context: EditContext) -> CommandStep {
132 let ns = context.text as NSString
133 let caret = context.caret
134 let failure = forward ? "Cannot drag element forward" : "Cannot drag element backward"
135 guard let (units, index) = Self.locate(caret, tree: context.tree, text: ns), !units[index].isHeading else { return .failed(failure) }
136 let other = forward ? index + 1 : index - 1
137 guard units.indices.contains(other), !units[other].isHeading else { return .failed(failure) }
138 let (a, b) = forward ? (units[index], units[other]) : (units[other], units[index])
139 let bodyA = ns.substring(with: NSRange(location: a.begin, length: a.bodyEnd - a.begin))
140 let bodyB = ns.substring(with: NSRange(location: b.begin, length: b.bodyEnd - b.begin))
141 let middle = ns.substring(with: NSRange(location: a.bodyEnd, length: b.begin - a.bodyEnd))
142 let edit = TextEdit(range: a.begin..<b.bodyEnd, replacement: bodyB + middle + bodyA)
143 let newCaret: Int
144 if forward {
145 let lineAfterB = b.bodyEnd < ns.length ? b.bodyEnd + 1 : b.bodyEnd
146 let lineAfterA = a.bodyEnd < ns.length ? a.bodyEnd + 1 : a.bodyEnd
147 newCaret = caret + (lineAfterB - b.begin) + (a.end - lineAfterA)
148 } else {
149 newCaret = a.begin + (caret - b.begin)
150 }
151 return .commit(EditResult(baseRevision: context.revision, edits: [edit], selection: [newCaret..<newCaret]))
152 }
153}
154
155/// S-<right> and S-<left> on an item: `org-cycle-list-bullet`, the list's bullets to the next
156/// kind, or with `previous` the one before.
157public struct CycleBullet: OrgCommand {
158 public let previous: Bool
159 public init(previous: Bool) { self.previous = previous }
160 public var id: String { previous ? "org.item.bullet-previous" : "org.item.bullet-next" }
161 public var title: String { previous ? "Previous Bullet Type" : "Next Bullet Type" }
162 public func applies(in context: EditContext) -> Bool {
163 EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings).inItem() != nil
164 }
165 public func run(in context: EditContext) -> CommandStep {
166 commitBuffer(context) { try $0.cycleListBullet(previous: previous) }
167 }
168}