Sources/OrgCore/Commands/StructureCommands.swift

design-themes-widgets
orgstar/Sources/OrgCore/Commands/StructureCommands.swift history · blame · raw

443 lines · 17335 bytes

  1import Foundation
  2
  3// Structure commands, ported from Org 9.8.7 onto `EmacsBuffer` and matched to Emacs by the
  4// oracle tests. Defaults as in org: `org-blank-before-new-entry` heading `auto`,
  5// `org-M-RET-may-split-line` t, `org-auto-align-tags` t.
  6
  7extension EmacsBuffer {
  8    /// `org--blank-before-heading-p` for headings.
  9    var blankBeforeHeading: Bool {
 10        saveExcursion {
 11            if beforeFirstHeading, !outlineNextHeading() { return false }
 12            _ = try? backToHeading()
 13            if !bobp { return previousLineEmpty }
 14            if outlineNextHeading() { return previousLineEmpty }
 15            skipBackward(Self.blanks)
 16            return bolp ? previousLineEmpty : false
 17        }
 18    }
 19
 20    /// `org-N-empty-lines-before-current`.
 21    func emptyLinesBeforeCurrent(_ n: Int) {
 22        let column = currentColumn
 23        forwardLine(0)
 24        if !bobp {
 25            let start = saveExcursion {
 26                skipBackward(Self.whitespace)
 27                return lineEnd(point)
 28            }
 29            deleteRegion(start, point - 1)
 30        }
 31        insert(String(repeating: "\n", count: n))
 32        moveToColumn(column)
 33    }
 34
 35    /// The blank line `org-insert-heading` keeps before the next heading.
 36    func addBlankAfter(_ blank: Bool) {
 37        saveExcursion {
 38            endOfLine()
 39            guard !eobp else { return }
 40            point += 1
 41            if blank, atHeading { insert("\n") }
 42        }
 43    }
 44
 45    /// `org-insert-heading` with no prefix, or with `respectContent` as C-RET.
 46    func insertHeading(respectContent: Bool, hidden: [Range<Int>]) throws {
 47        let blank = blankBeforeHeading
 48        let level = currentLevel
 49        let stars = String(repeating: "*", count: level ?? 1)
 50        // The caret at the end of a folded heading's line, just before its hidden body, is where
 51        // Emacs's point sits behind the ellipsis.
 52        let invisible = hidden.contains { $0.contains(max(point - 1, 0)) || (!$0.isEmpty && $0.lowerBound == point + 1 && atHeading && eolp) }
 53        if respectContent || invisible {
 54            if level == nil {
 55                outlineNextHeading()
 56            } else {
 57                try backToHeading()
 58                endOfSubtree(toHeading: true)
 59            }
 60            if !bolp { insert("\n") }
 61            if blank, saveExcursion({ point -= 1; return beforeFirstHeading }) {
 62                insert("\n")
 63                point -= 1
 64            }
 65            if level == nil, !eobp, !bobp {
 66                if atHeading { insert("\n") }
 67                point -= 1
 68            }
 69            if !(blank && previousLineEmpty) { emptyLinesBeforeCurrent(blank ? 1 : 0) }
 70            insert(stars + " \n")
 71            point -= 1
 72            addBlankAfter(blank)
 73        } else if atHeading {
 74            if bolp {
 75                if blank { saveExcursion { insert("\n") } }
 76                saveExcursion { insert(stars + " \n") }
 77                if !(blank && previousLineEmpty) { emptyLinesBeforeCurrent(blank ? 1 : 0) }
 78                endOfLine()
 79            } else if options.metaReturnMaySplitLine,
 80                      let match = saveExcursion({ () -> [Range<Int>?]? in beginningOfLine(); return lookingAt(complexHeadingPattern) }),
 81                      let title = match[4], title.lowerBound <= point, point <= title.upperBound {
 82                let split = substring(point, title.upperBound)
 83                deleteRegion(point, title.upperBound)
 84                if let blanks = lookingAt("[ \\t]*$") {
 85                    deleteRegion(blanks[0]!.lowerBound, blanks[0]!.upperBound)
 86                } else {
 87                    alignTags(onLineAt: point)
 88                }
 89                endOfLine()
 90                if blank { insert("\n") }
 91                insert("\n" + stars + " ")
 92                addBlankAfter(blank)
 93                if split.contains(where: { !$0.isWhitespace }) { insert(split) }
 94            } else {
 95                endOfLine()
 96                if blank { insert("\n") }
 97                insert("\n" + stars + " ")
 98                addBlankAfter(blank)
 99            }
100        } else if bolp {
101            insert(stars + " ")
102            if !(blank && previousLineEmpty) { emptyLinesBeforeCurrent(blank ? 1 : 0) }
103            addBlankAfter(blank)
104        } else {
105            if !options.metaReturnMaySplitLine { endOfLine() }
106            insert("\n" + stars + " ")
107            if !(blank && previousLineEmpty) { emptyLinesBeforeCurrent(blank ? 1 : 0) }
108            addBlankAfter(blank)
109        }
110    }
111
112    /// `org-forward-heading-same-level` over all headings, visible or not.
113    func forwardHeadingSameLevel(_ count: Int) throws {
114        let backward = count < 0
115        if beforeFirstHeading {
116            if backward { point = 0 } else { outlineNextHeading() }
117            return
118        }
119        try backToHeading()
120        if !backward { endOfLine() }
121        let level = currentLevel ?? 0
122        var remaining = abs(count)
123        var result = point
124        while remaining > 0, let found = backward ? searchHeadingBackward() : searchHeadingForward() {
125            let l = headingLevel(atLine: found)!
126            if l < level {
127                remaining = 0
128            } else if l == level {
129                remaining -= 1
130                result = point
131            }
132        }
133        point = result
134        forwardLine(0)
135    }
136
137    /// `re-search-forward "^\\*+ " nil 'move`: point to the match end, or the buffer end.
138    /// Returns the heading's line start.
139    func searchHeadingForward() -> Int? {
140        var line = bolp ? point : lineEnd(point) + 1
141        while line <= length {
142            if let level = headingLevel(atLine: line) {
143                point = line + level + 1
144                return line
145            }
146            line = lineEnd(line) + 1
147        }
148        point = length
149        return nil
150    }
151
152    /// `re-search-backward "^\\*+ " nil 'move`: point to the match start, or the buffer start.
153    /// The match must end by point.
154    func searchHeadingBackward() -> Int? {
155        var line = lineStart(point)
156        if let level = headingLevel(atLine: line), line + level + 1 <= point {
157            point = line
158            return line
159        }
160        while line > 0 {
161            line = lineStart(line - 1)
162            if headingLevel(atLine: line) != nil {
163                point = line
164                return line
165            }
166        }
167        point = 0
168        return nil
169    }
170
171    /// `org-promote` or `org-demote` on the heading at point.
172    func changeLevel(by delta: Int) throws {
173        try saveExcursion {
174            try backToHeading()
175            let level = headingLevel(atLine: point)!
176            guard level + delta >= 1 else { throw UserError(message: "Cannot promote to level 0.  UNDO to recover if necessary") }
177            replace(point..<(point + level + 1), with: String(repeating: "*", count: level + delta) + " ")
178            alignTags(onLineAt: point)
179        }
180    }
181
182    /// `org-fix-position-after-promote`.
183    func fixPositionAfterPromote() {
184        let position = point
185        let match = saveExcursion { () -> [Range<Int>?]? in
186            forwardLine(0)
187            return lookingAt(todoLinePattern)
188        }
189        guard let match, match[1]?.upperBound == position || match[2]?.upperBound == position else { return }
190        if eobp || eolp {
191            insert(" ")
192        } else if character(at: point) == 32 {
193            point += 1
194        }
195    }
196
197    /// `org-map-tree` over the subtree at point.
198    func mapTree(_ body: () throws -> Void) throws {
199        try backToHeading()
200        let level = outlineLevel
201        try saveExcursion {
202            try body()
203            while true {
204                outlineNextHeading()
205                guard outlineLevel > level, !eobp else { break }
206                try body()
207            }
208        }
209    }
210
211    /// `org-back-over-empty-lines` with blank lines before headings on (`auto`).
212    func backOverEmptyLines() {
213        let position = point
214        skipBackward(Self.whitespace)
215        forwardLine(1)
216        point = min(point, position)
217    }
218
219    /// `org-move-subtree-down`; negative counts move up.
220    func moveSubtree(_ count: Int) throws {
221        let column = currentColumn
222        try backToHeading()
223        let begin = point
224        endOfSubtree(toHeading: true)
225        if !eobp { point -= 1 }
226        outlineNextHeading()
227        let end = point
228        point = begin
229        for _ in 0..<abs(count) {
230            let found = count > 0 ? nextSibling() : previousSibling()
231            guard found != nil, atHeading, bolp else {
232                point = begin
233                throw UserError(message: "Cannot move past superior level or buffer limit")
234            }
235        }
236        if count > 0 {
237            endOfSubtree(toHeading: true)
238            saveExcursion {
239                backOverEmptyLines()
240                if !bolp { insert("\n") }
241            }
242        }
243        let insertion = marker(point)
244        defer { release(insertion) }
245        let subtree = substring(begin, end)
246        deleteRegion(begin, end)
247        if !bolp, character(at: point) == Self.newline { point += 1 }
248        let at = point
249        insertBeforeMarkers(subtree)
250        insertion.position = at
251        if !bolp { insert("\n") }
252        point = insertion.position
253        skipForward(Self.whitespace)
254        moveToColumn(column)
255    }
256}
257
258private func headingCommand(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
259    commitBuffer(context, body)
260}
261
262// MARK: - Inserting
263
264/// M-RET on a heading or text: `org-insert-heading`.
265public struct InsertHeading: OrgCommand {
266    public init() {}
267    public var id: String { "org.heading.insert" }
268    public var title: String { "Insert Heading" }
269    public func applies(in context: EditContext) -> Bool { true }
270    public func run(in context: EditContext) -> CommandStep {
271        headingCommand(context) { try $0.insertHeading(respectContent: context.options.insertHeadingRespectContent, hidden: context.hidden) }
272    }
273}
274
275/// C-RET: `org-insert-heading-respect-content`.
276public struct InsertHeadingAfterSubtree: OrgCommand {
277    public init() {}
278    public var id: String { "org.heading.insert-after-subtree" }
279    public var title: String { "Insert Heading After Subtree" }
280    public func applies(in context: EditContext) -> Bool { true }
281    public func run(in context: EditContext) -> CommandStep {
282        headingCommand(context) { try $0.insertHeading(respectContent: true, hidden: context.hidden) }
283    }
284}
285
286/// M-S-RET on a heading or text: `org-insert-todo-heading`.
287public struct InsertTodoHeading: OrgCommand {
288    public init() {}
289    public var id: String { "org.heading.insert-todo" }
290    public var title: String { "Insert TODO Heading" }
291    public func applies(in context: EditContext) -> Bool { true }
292    public func run(in context: EditContext) -> CommandStep {
293        headingCommand(context) { buffer in
294            try buffer.insertHeading(respectContent: context.options.insertHeadingRespectContent, hidden: context.hidden)
295            let previous = buffer.saveExcursion { () -> String? in
296                try? buffer.forwardHeadingSameLevel(-1)
297                guard let match = buffer.lookingAt(buffer.todoLinePattern), let keyword = match[2] else { return nil }
298                return buffer.substring(keyword.lowerBound, keyword.upperBound)
299            }
300            let keyword = previous.flatMap { context.tree.settings.isDone($0) ? nil : $0 } ?? buffer.keywordsInOrder.first ?? "TODO"
301            buffer.forwardLine(0)
302            if let stars = buffer.lookingAt("\\*+ ") {
303                buffer.point = stars[0]!.upperBound
304                buffer.insert(keyword + " ")
305            }
306            buffer.updateParentTodoStatistics()
307        }
308    }
309}
310
311// MARK: - Moving and levels
312
313/// M-up on a heading: `org-move-subtree-up`.
314public struct MoveSubtreeUp: OrgCommand {
315    public init() {}
316    public var id: String { "org.subtree.up" }
317    public var title: String { "Move Subtree Up" }
318    public func applies(in context: EditContext) -> Bool { headingOnLine(at: context.caret, in: context.tree) != nil }
319    public func run(in context: EditContext) -> CommandStep { headingCommand(context) { try $0.moveSubtree(-1) } }
320}
321
322/// M-down on a heading: `org-move-subtree-down`.
323public struct MoveSubtreeDown: OrgCommand {
324    public init() {}
325    public var id: String { "org.subtree.down" }
326    public var title: String { "Move Subtree Down" }
327    public func applies(in context: EditContext) -> Bool { headingOnLine(at: context.caret, in: context.tree) != nil }
328    public func run(in context: EditContext) -> CommandStep { headingCommand(context) { try $0.moveSubtree(1) } }
329}
330
331/// M-S-left on a heading: `org-promote-subtree`.
332public struct PromoteSubtree: OrgCommand {
333    public init() {}
334    public var id: String { "org.subtree.promote" }
335    public var title: String { "Promote Subtree" }
336    public func applies(in context: EditContext) -> Bool { headingOnLine(at: context.caret, in: context.tree) != nil }
337    public func run(in context: EditContext) -> CommandStep {
338        headingCommand(context) { buffer in
339            try buffer.saveExcursion {
340                try buffer.backToHeading()
341                try buffer.mapTree { try buffer.changeLevel(by: -1) }
342            }
343            buffer.fixPositionAfterPromote()
344        }
345    }
346}
347
348/// M-S-right on a heading: `org-demote-subtree`.
349public struct DemoteSubtree: OrgCommand {
350    public init() {}
351    public var id: String { "org.subtree.demote" }
352    public var title: String { "Demote Subtree" }
353    public func applies(in context: EditContext) -> Bool { headingOnLine(at: context.caret, in: context.tree) != nil }
354    public func run(in context: EditContext) -> CommandStep {
355        headingCommand(context) { buffer in
356            try buffer.saveExcursion {
357                try buffer.backToHeading()
358                try buffer.mapTree { try buffer.changeLevel(by: 1) }
359            }
360            buffer.fixPositionAfterPromote()
361        }
362    }
363}
364
365// MARK: - Motion
366
367/// C-c C-n: `org-next-visible-heading`.
368public struct NextHeading: OrgCommand {
369    public init() {}
370    public var id: String { "org.heading.next" }
371    public var title: String { "Next Heading" }
372    public func applies(in context: EditContext) -> Bool { true }
373    public func run(in context: EditContext) -> CommandStep {
374        headingCommand(context) { buffer in
375            buffer.endOfLine()
376            var found = buffer.nextHeadingStart(after: buffer.point)
377            while let start = found, context.hidden.contains(where: { $0.contains(start) }) {
378                found = buffer.nextHeadingStart(after: start)
379            }
380            buffer.point = found ?? buffer.length
381        }
382    }
383}
384
385/// C-c C-p: `org-previous-visible-heading`.
386public struct PreviousHeading: OrgCommand {
387    public init() {}
388    public var id: String { "org.heading.previous" }
389    public var title: String { "Previous Heading" }
390    public func applies(in context: EditContext) -> Bool { true }
391    public func run(in context: EditContext) -> CommandStep {
392        headingCommand(context) { buffer in
393            buffer.forwardLine(0)
394            var found = buffer.previousHeadingStart(before: buffer.point)
395            while let start = found, context.hidden.contains(where: { $0.contains(start) }) {
396                found = buffer.previousHeadingStart(before: start)
397            }
398            buffer.point = found ?? 0
399        }
400    }
401}
402
403/// C-c C-f: `org-forward-heading-same-level`.
404public struct ForwardSameLevel: OrgCommand {
405    public init() {}
406    public var id: String { "org.heading.forward-same-level" }
407    public var title: String { "Next Heading at Same Level" }
408    public func applies(in context: EditContext) -> Bool { true }
409    public func run(in context: EditContext) -> CommandStep { headingCommand(context) { try $0.forwardHeadingSameLevel(1) } }
410}
411
412/// C-c C-b: `org-backward-heading-same-level`.
413public struct BackwardSameLevel: OrgCommand {
414    public init() {}
415    public var id: String { "org.heading.backward-same-level" }
416    public var title: String { "Previous Heading at Same Level" }
417    public func applies(in context: EditContext) -> Bool { true }
418    public func run(in context: EditContext) -> CommandStep { headingCommand(context) { try $0.forwardHeadingSameLevel(-1) } }
419}
420
421/// C-c C-u: `outline-up-heading`.
422public struct UpHeading: OrgCommand {
423    public init() {}
424    public var id: String { "org.heading.up" }
425    public var title: String { "Up to Parent Heading" }
426    public func applies(in context: EditContext) -> Bool { true }
427    public func run(in context: EditContext) -> CommandStep {
428        headingCommand(context) { buffer in
429            do {
430                try buffer.backToHeading()
431            } catch {
432                throw EmacsBuffer.UserError(message: "before first heading")
433            }
434            let start = buffer.outlineLevel
435            guard start > 1 else { throw EmacsBuffer.UserError(message: "Already at top level of the outline") }
436            var level = start
437            while level >= start, !buffer.bobp {
438                buffer.outlinePreviousHeading()
439                level = buffer.outlineLevel
440            }
441        }
442    }
443}