Commit 7ce6477706
Verified · cmc
Layout: unified · split
Sources/OrgApp/DocumentSession.swift +15 −13
| @@ -604,19 +604,21 @@ public final class DocumentSession { | |||
| 604 | return nil | 604 | return nil |
| 605 | } | 605 | } |
| 606 | 606 | ||
| 607 | /// Moves the subtree at the caret, or at `from`, under `target`. For another file, that | 607 | /// Moves the subtree at the caret, or at `from`, under `target`, or with `keep` copies it |
| 608 | /// file is written first, through the save path; the subtree leaves its file only once it | 608 | /// there (`org-copy`). For another file, that file is written first, through the save |
| 609 | /// has. Returns a message for the echo area. | 609 | /// path; the subtree leaves its file only once it has. Returns a message for the echo area. |
| 610 | @discardableResult | 610 | @discardableResult |
| 611 | public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? { | 611 | public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? { |
| 612 | guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." } | 612 | guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." } |
| 613 | let done = (keep ? "Copied to " : "Refiled to ") + target.label | ||
| 613 | if target.path == path { | 614 | if target.path == path { |
| 614 | let answers = ["refile": target.start.map(String.init) ?? ""] | 615 | let answers = ["refile": target.start.map(String.init) ?? ""] |
| 615 | let step = from == nil ? buffer?.perform(RefileWithinFile(), now: now, answers: answers) | 616 | let command = RefileWithinFile(keep: keep) |
| 616 | : perform(RefileWithinFile(), path: path, at: from!.offset, expect: nil, answers: answers, now: now) | 617 | let step = from == nil ? buffer?.perform(command, now: now, answers: answers) |
| 618 | : perform(command, path: path, at: from!.offset, expect: nil, answers: answers, now: now) | ||
| 617 | if case .failed(let message)? = step { return message } | 619 | if case .failed(let message)? = step { return message } |
| 618 | if from == nil { bufferChanged() } | 620 | if from == nil { bufferChanged() } |
| 619 | return "Refiled to \(target.label)" | 621 | return done |
| 620 | } | 622 | } |
| 621 | let url = URL(fileURLWithPath: target.path) | 623 | let url = URL(fileURLWithPath: target.path) |
| 622 | let targetName = (target.path as NSString).lastPathComponent | 624 | let targetName = (target.path as NSString).lastPathComponent |
| @@ -625,23 +627,23 @@ public final class DocumentSession { | |||
| 625 | let state = open.buffer.document | 627 | let state = open.buffer.document |
| 626 | guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." } | 628 | guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." } |
| 627 | guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." } | 629 | guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." } |
| 628 | guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." } | 630 | guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." } |
| 629 | let edit = EditResult(baseRevision: state.revision, edits: [result.target]) | 631 | let edit = EditResult(baseRevision: state.revision, edits: [result.target]) |
| 630 | if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message } | 632 | if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message } |
| 631 | changed(open) | 633 | changed(open) |
| 632 | if let message = applySource(result.source, path: path, now: now) { return message } | 634 | if !keep, let message = applySource(result.source, path: path, now: now) { return message } |
| 633 | return "Refiled to \(target.label)" | 635 | return done |
| 634 | } | 636 | } |
| 635 | do { | 637 | do { |
| 636 | guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." } | 638 | guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." } |
| 637 | var state = loaded(bytes, path: url.path) | 639 | var state = loaded(bytes, path: url.path) |
| 638 | guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." } | 640 | guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." } |
| 639 | guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." } | 641 | guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." } |
| 640 | guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." } | 642 | guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." } |
| 641 | try state.apply([result.target], baseRevision: state.revision) | 643 | try state.apply([result.target], baseRevision: state.revision) |
| 642 | if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." } | 644 | if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." } |
| 643 | if let message = applySource(result.source, path: path, now: now) { return message } | 645 | if !keep, let message = applySource(result.source, path: path, now: now) { return message } |
| 644 | return "Refiled to \(target.label)" | 646 | return done |
| 645 | } catch { | 647 | } catch { |
| 646 | return "Can't refile: \(error.localizedDescription)" | 648 | return "Can't refile: \(error.localizedDescription)" |
| 647 | } | 649 | } |
Sources/OrgApp/EmacsImport.swift +1 −1
| @@ -746,7 +746,7 @@ public struct EmacsImport: Sendable { | |||
| 746 | "org-babel-execute-src-block": "org.babel.execute", "org-clock-in": "app.clock.in", "org-clock-out": "app.clock.out", | 746 | "org-babel-execute-src-block": "org.babel.execute", "org-clock-in": "app.clock.in", "org-clock-out": "app.clock.out", |
| 747 | "org-clock-cancel": "app.clock.cancel", "org-clock-goto": "app.clock.goto", "org-clock-in-last": "app.clock.in-last", | 747 | "org-clock-cancel": "app.clock.cancel", "org-clock-goto": "app.clock.goto", "org-clock-in-last": "app.clock.in-last", |
| 748 | "org-resolve-clocks": "app.clock.resolve", "org-clock-mark-default-task": "app.clock.default", | 748 | "org-resolve-clocks": "app.clock.resolve", "org-clock-mark-default-task": "app.clock.default", |
| 749 | "org-refile": "app.refile", "org-archive-subtree": "app.archive", "org-archive-subtree-default": "app.archive", | 749 | "org-refile": "app.refile", "org-copy": "app.refile.copy", "org-refile-copy": "app.refile.copy", "org-archive-subtree": "app.archive", "org-archive-subtree-default": "app.archive", |
| 750 | "org-capture": "app.capture", "org-agenda": "app.agenda", "org-agenda-list": "app.agenda", | 750 | "org-capture": "app.capture", "org-agenda": "app.agenda", "org-agenda-list": "app.agenda", |
| 751 | "save-buffer": "app.save", "find-file": "app.quick-open", "projectile-find-file": "app.quick-open", "+default/find-file-under-here": "app.quick-open", | 751 | "save-buffer": "app.save", "find-file": "app.quick-open", "projectile-find-file": "app.quick-open", "+default/find-file-under-here": "app.quick-open", |
| 752 | "execute-extended-command": "app.palette", "counsel-M-x": "app.palette", | 752 | "execute-extended-command": "app.palette", "counsel-M-x": "app.palette", |
Sources/OrgCore/Commands/Command.swift +1
| @@ -302,6 +302,7 @@ public enum Commands { | |||
| 302 | OpenLinkAtPoint(), CreateID(), ToggleComment(), ToggleHeading(), ToggleItem(), MarkSubtree(), | 302 | OpenLinkAtPoint(), CreateID(), ToggleComment(), ToggleHeading(), ToggleItem(), MarkSubtree(), |
| 303 | CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target), | 303 | CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target), |
| 304 | UpdateDynamicBlock(), ClockReportTable(), SetEffort(), CtrlCCtrlC(), EvaluateTimeRange(), FootnoteAction(), FootnoteAction(special: true), TableEvalFormula(named: false), TableEvalFormula(named: true), SortTableLines(), TransposeTable(), GotoHeading(), SparseTreeCommand(), SetPriority(), SetPriority(value: "A"), SetPriority(value: "B"), SetPriority(value: "C"), SetPriority(value: " "), ReadAndSetProperty(), DeleteProperty(), DeleteProperty(globally: true), PropertyAction(), NextAllowedValue(previous: false), NextAllowedValue(previous: true), InsertColumnView(), ShowColumnView(), ShowColumnView(global: true), ToggleArchiveTag(), ArchiveToSibling(), ToggleOrderedProperty(), | 304 | UpdateDynamicBlock(), ClockReportTable(), SetEffort(), CtrlCCtrlC(), EvaluateTimeRange(), FootnoteAction(), FootnoteAction(special: true), TableEvalFormula(named: false), TableEvalFormula(named: true), SortTableLines(), TransposeTable(), GotoHeading(), SparseTreeCommand(), SetPriority(), SetPriority(value: "A"), SetPriority(value: "B"), SetPriority(value: "C"), SetPriority(value: " "), ReadAndSetProperty(), DeleteProperty(), DeleteProperty(globally: true), PropertyAction(), NextAllowedValue(previous: false), NextAllowedValue(previous: true), InsertColumnView(), ShowColumnView(), ShowColumnView(global: true), ToggleArchiveTag(), ArchiveToSibling(), ToggleOrderedProperty(), |
| 305 | InsertDrawer(), DragElement(forward: true), DragElement(forward: false), CycleBullet(previous: false), CycleBullet(previous: true), | ||
| 305 | ] | 306 | ] |
| 306 | 307 | ||
| 307 | public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) } | 308 | public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) } |
Sources/OrgCore/Commands/ElementCommands.swift added +168
| @@ -0,0 +1,168 @@ | |||
| 1 | import 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. | ||
| 9 | public 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. | ||
| 50 | public 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. | ||
| 157 | public 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 | } | ||
Sources/OrgCore/Commands/Refile.swift +14 −8
| @@ -86,8 +86,9 @@ extension EmacsBuffer { | |||
| 86 | } | 86 | } |
| 87 | } | 87 | } |
| 88 | 88 | ||
| 89 | /// `org-refile` to a heading in this buffer, or to its end when `target` is nil. | 89 | /// `org-refile` to a heading in this buffer, or to its end when `target` is nil; with |
| 90 | func refileWithinBuffer(to target: Int?) throws { | 90 | /// `keep`, `org-copy`, which leaves the subtree where it was. |
| 91 | func refileWithinBuffer(to target: Int?, keep: Bool = false) throws { | ||
| 91 | let subtree = try subtreeRange() | 92 | let subtree = try subtreeRange() |
| 92 | if let target, subtree.contains(target) { | 93 | if let target, subtree.contains(target) { |
| 93 | throw UserError(message: "Cannot refile to position inside the tree or region") | 94 | throw UserError(message: "Cannot refile to position inside the tree or region") |
| @@ -97,24 +98,27 @@ extension EmacsBuffer { | |||
| 97 | defer { release(origin) } | 98 | defer { release(origin) } |
| 98 | try refileInsert(tree, under: target) | 99 | try refileInsert(tree, under: target) |
| 99 | point = origin.position | 100 | point = origin.position |
| 101 | if keep { return } | ||
| 100 | let range = try subtreeRange() | 102 | let range = try subtreeRange() |
| 101 | deleteRegion(range.lowerBound, range.upperBound) | 103 | deleteRegion(range.lowerBound, range.upperBound) |
| 102 | } | 104 | } |
| 103 | } | 105 | } |
| 104 | 106 | ||
| 105 | /// C-c C-w within one file: moves the subtree at the caret under the heading starting at the | 107 | /// C-c C-w within one file: moves the subtree at the caret under the heading starting at the |
| 106 | /// answer's offset, or to the end of the file for an empty answer. | 108 | /// answer's offset, or to the end of the file for an empty answer. With `keep`, C-c M-w |
| 109 | /// copies it there. | ||
| 107 | public struct RefileWithinFile: OrgCommand { | 110 | public struct RefileWithinFile: OrgCommand { |
| 108 | public init() {} | 111 | public let keep: Bool |
| 109 | public var id: String { "org.refile.local" } | 112 | public init(keep: Bool = false) { self.keep = keep } |
| 110 | public var title: String { "Refile Within File" } | 113 | public var id: String { keep ? "org.refile.local-copy" : "org.refile.local" } |
| 114 | public var title: String { keep ? "Copy Within File" : "Refile Within File" } | ||
| 111 | public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil } | 115 | public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil } |
| 112 | 116 | ||
| 113 | public func run(in context: EditContext) -> CommandStep { | 117 | public func run(in context: EditContext) -> CommandStep { |
| 114 | guard let answer = context.answers["refile"] else { | 118 | guard let answer = context.answers["refile"] else { |
| 115 | return .prompt(Prompt(key: "refile", message: "Refile to:")) | 119 | return .prompt(Prompt(key: "refile", message: "Refile to:")) |
| 116 | } | 120 | } |
| 117 | return commitBuffer(context) { try $0.refileWithinBuffer(to: Int(answer)) } | 121 | return commitBuffer(context) { try $0.refileWithinBuffer(to: Int(answer), keep: keep) } |
| 118 | } | 122 | } |
| 119 | } | 123 | } |
| 120 | 124 | ||
| @@ -125,12 +129,14 @@ public enum Refile { | |||
| 125 | public let target: TextEdit | 129 | public let target: TextEdit |
| 126 | } | 130 | } |
| 127 | 131 | ||
| 128 | public static func toOtherFile(source context: EditContext, target text: String, under heading: Int?) -> Result? { | 132 | /// With `keep`, the source's edit leaves its text as it is. |
| 133 | public static func toOtherFile(source context: EditContext, target text: String, under heading: Int?, keep: Bool = false) -> Result? { | ||
| 129 | let target = EmacsBuffer(text, point: 0, settings: context.tree.settings, options: context.options) | 134 | let target = EmacsBuffer(text, point: 0, settings: context.tree.settings, options: context.options) |
| 130 | var tree = "" | 135 | var tree = "" |
| 131 | let step = commitBuffer(context) { buffer in | 136 | let step = commitBuffer(context) { buffer in |
| 132 | tree = try buffer.copySubtree() | 137 | tree = try buffer.copySubtree() |
| 133 | try target.refileInsert(tree, under: heading) | 138 | try target.refileInsert(tree, under: heading) |
| 139 | if keep { return } | ||
| 134 | let range = try buffer.subtreeRange() | 140 | let range = try buffer.subtreeRange() |
| 135 | buffer.deleteRegion(range.lowerBound, range.upperBound) | 141 | buffer.deleteRegion(range.lowerBound, range.upperBound) |
| 136 | } | 142 | } |
Sources/OrgCore/Commands/ToggleCommands.swift +3 −3
| @@ -283,7 +283,7 @@ extension EmacsBuffer { | |||
| 283 | 283 | ||
| 284 | /// `org-cycle-list-bullet`: the list's bullets go through `-`, `+`, `*` (not at the | 284 | /// `org-cycle-list-bullet`: the list's bullets go through `-`, `+`, `*` (not at the |
| 285 | /// margin), `1.`, `1)` and, with alphabetical lists, `a.`, `A.`, `a)`, `A)`. | 285 | /// margin), `1.`, `1)` and, with alphabetical lists, `a.`, `A.`, `a)`, `A)`. |
| 286 | func cycleListBullet() throws { | 286 | func cycleListBullet(previous: Bool = false) throws { |
| 287 | guard let item = inItem() else { throw UserError(message: "Not at an item") } | 287 | guard let item = inItem() else { throw UserError(message: "Not at an item") } |
| 288 | let origin = marker(point) | 288 | let origin = marker(point) |
| 289 | defer { release(origin) } | 289 | defer { release(origin) } |
| @@ -306,8 +306,8 @@ extension EmacsBuffer { | |||
| 306 | if lookingAt("\\S") == nil { choices.append("*") } | 306 | if lookingAt("\\S") == nil { choices.append("*") } |
| 307 | if !description { choices += ["1.", "1)"] } | 307 | if !description { choices += ["1.", "1)"] } |
| 308 | if alpha, !description { choices += ["a.", "A.", "a)", "A)"] } | 308 | if alpha, !description { choices += ["a.", "A.", "a)", "A)"] } |
| 309 | let index = choices.firstIndex(of: current).map { $0 + 1 } ?? choices.count | 309 | let index = choices.firstIndex(of: current) ?? choices.count |
| 310 | let new = choices[index % choices.count] | 310 | let new = choices[((index + (previous ? -1 : 1)) % choices.count + choices.count) % choices.count] |
| 311 | let old = structure | 311 | let old = structure |
| 312 | structure.set(first) { $0.bullet = bulletString(new) } | 312 | structure.set(first) { $0.bullet = bulletString(new) } |
| 313 | fixBullets(&structure, prevs) | 313 | fixBullets(&structure, prevs) |
Sources/OrgCore/Keymap/PresetDoom.swift +4
| @@ -324,6 +324,10 @@ extension KeymapPreset { | |||
| 324 | command = "app.refile" | 324 | command = "app.refile" |
| 325 | mode = "normal" | 325 | mode = "normal" |
| 326 | [[bind]] | 326 | [[bind]] |
| 327 | keys = "SPC u SPC m r r" | ||
| 328 | command = "app.refile.goto" | ||
| 329 | mode = "normal" | ||
| 330 | [[bind]] | ||
| 327 | keys = "SPC m s r" | 331 | keys = "SPC m s r" |
| 328 | command = "app.refile" | 332 | command = "app.refile" |
| 329 | mode = "normal" | 333 | mode = "normal" |
Sources/OrgCore/Keymap/PresetEmacs.swift +23
| @@ -195,6 +195,23 @@ extension KeymapPreset { | |||
| 195 | command = "org.columns" | 195 | command = "org.columns" |
| 196 | [[bind]] | 196 | [[bind]] |
| 197 | keys = "S-<right>" | 197 | keys = "S-<right>" |
| 198 | command = "org.item.bullet-next" | ||
| 199 | when = "item" | ||
| 200 | [[bind]] | ||
| 201 | keys = "S-<left>" | ||
| 202 | command = "org.item.bullet-previous" | ||
| 203 | when = "item" | ||
| 204 | [[bind]] | ||
| 205 | keys = "C-c C-x d" | ||
| 206 | command = "org.drawer.insert" | ||
| 207 | [[bind]] | ||
| 208 | keys = "M-<up>" | ||
| 209 | command = "org.element.drag-backward" | ||
| 210 | [[bind]] | ||
| 211 | keys = "M-<down>" | ||
| 212 | command = "org.element.drag-forward" | ||
| 213 | [[bind]] | ||
| 214 | keys = "S-<right>" | ||
| 198 | command = "org.property.next-value" | 215 | command = "org.property.next-value" |
| 199 | when = "property" | 216 | when = "property" |
| 200 | [[bind]] | 217 | [[bind]] |
| @@ -432,6 +449,12 @@ extension KeymapPreset { | |||
| 432 | keys = "C-c C-w" | 449 | keys = "C-c C-w" |
| 433 | command = "app.refile" | 450 | command = "app.refile" |
| 434 | [[bind]] | 451 | [[bind]] |
| 452 | keys = "C-u C-c C-w" | ||
| 453 | command = "app.refile.goto" | ||
| 454 | [[bind]] | ||
| 455 | keys = "C-c M-w" | ||
| 456 | command = "app.refile.copy" | ||
| 457 | [[bind]] | ||
| 435 | keys = "C-c C-x C-s" | 458 | keys = "C-c C-x C-s" |
| 436 | command = "app.archive" | 459 | command = "app.archive" |
| 437 | [[bind]] | 460 | [[bind]] |
Sources/OrgEditorAppKit/EditorCommands.swift +2
| @@ -88,6 +88,8 @@ public enum EditorCommands { | |||
| 88 | EditorCommand(id: "app.search", title: "Search Notes", action: .app), | 88 | EditorCommand(id: "app.search", title: "Search Notes", action: .app), |
| 89 | EditorCommand(id: "app.reload-keymap", title: "Reload Keymap", action: .app), | 89 | EditorCommand(id: "app.reload-keymap", title: "Reload Keymap", action: .app), |
| 90 | EditorCommand(id: "app.refile", title: "Refile…", action: .app), | 90 | EditorCommand(id: "app.refile", title: "Refile…", action: .app), |
| 91 | EditorCommand(id: "app.refile.copy", title: "Copy to Refile Target…", action: .app), | ||
| 92 | EditorCommand(id: "app.refile.goto", title: "Go to Refile Target…", action: .app), | ||
| 91 | EditorCommand(id: "app.archive", title: "Archive Subtree", action: .app), | 93 | EditorCommand(id: "app.archive", title: "Archive Subtree", action: .app), |
| 92 | EditorCommand(id: "app.agenda", title: "Agenda", action: .app), | 94 | EditorCommand(id: "app.agenda", title: "Agenda", action: .app), |
| 93 | EditorCommand(id: "app.capture", title: "Capture…", action: .app), | 95 | EditorCommand(id: "app.capture", title: "Capture…", action: .app), |
Sources/Orgstar/ContentView.swift +12 −4
| @@ -716,7 +716,7 @@ struct ContentView: View { | |||
| 716 | 716 | ||
| 717 | /// Runs a command from a key, the palette or the Org menu. | 717 | /// Runs a command from a key, the palette or the Org menu. |
| 718 | private func perform(_ id: String) { | 718 | private func perform(_ id: String) { |
| 719 | let orgOnly = ["app.refile", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.") | 719 | let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.") |
| 720 | if orgOnly, !session.isOrg { | 720 | if orgOnly, !session.isOrg { |
| 721 | commands.show("Not an org file") | 721 | commands.show("Not an org file") |
| 722 | return | 722 | return |
| @@ -782,11 +782,19 @@ struct ContentView: View { | |||
| 782 | case "app.reload-keymap": | 782 | case "app.reload-keymap": |
| 783 | loadKeymap() | 783 | loadKeymap() |
| 784 | commands.show("Keymap reloaded") | 784 | commands.show("Keymap reloaded") |
| 785 | case "app.refile": | 785 | case "app.refile", "app.refile.copy": |
| 786 | let keep = id == "app.refile.copy" | ||
| 786 | let targets = workspace.refileTargets(openPath: session.path, document: session.document) | 787 | let targets = workspace.refileTargets(openPath: session.path, document: session.document) |
| 787 | commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in | 788 | commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in |
| 788 | guard let answer, let target = targets.first(where: { $0.label == answer }) else { return } | 789 | guard let answer, let target = targets.first(where: { $0.label == answer }) else { return } |
| 789 | if let message = session.refile(to: target) { commands.show(message) } | 790 | if let message = session.refile(to: target, keep: keep) { commands.show(message) } |
| 791 | } | ||
| 792 | case "app.refile.goto": | ||
| 793 | // `C-u C-c C-w`: the target heading, or the end of a file. | ||
| 794 | let targets = workspace.refileTargets(openPath: session.path, document: session.document) | ||
| 795 | commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in | ||
| 796 | guard let answer, let target = targets.first(where: { $0.label == answer }) else { return } | ||
| 797 | commands.jump(path: target.path, offset: target.start ?? Int.max) | ||
| 790 | } | 798 | } |
| 791 | case "app.archive": | 799 | case "app.archive": |
| 792 | if let message = session.archive() { commands.show(message) } | 800 | if let message = session.archive() { commands.show(message) } |
Sources/OrgstarMobile/EditorScreen.swift +16 −9
| @@ -32,13 +32,15 @@ struct EditorScreen: View { | |||
| 32 | 32 | ||
| 33 | /// One sheet at a time: two presenters on this screen interfere. | 33 | /// One sheet at a time: two presenters on this screen interfere. |
| 34 | enum Sheet: Identifiable { | 34 | enum Sheet: Identifiable { |
| 35 | case palette, conflict, syncCopies, recovery, refile | 35 | case palette, conflict, syncCopies, recovery |
| 36 | /// `app.refile`, `app.refile.copy` or `app.refile.goto`. | ||
| 37 | case refile(String) | ||
| 36 | case block(BlockEdit) | 38 | case block(BlockEdit) |
| 37 | 39 | ||
| 38 | var id: String { | 40 | var id: String { |
| 39 | switch self { | 41 | switch self { |
| 40 | case .palette: "palette" | 42 | case .palette: "palette" |
| 41 | case .refile: "refile" | 43 | case .refile(let command): command |
| 42 | case .conflict: "conflict" | 44 | case .conflict: "conflict" |
| 43 | case .syncCopies: "syncCopies" | 45 | case .syncCopies: "syncCopies" |
| 44 | case .recovery: "recovery" | 46 | case .recovery: "recovery" |
| @@ -106,10 +108,15 @@ struct EditorScreen: View { | |||
| 106 | case .conflict: ConflictSheet(session: session) | 108 | case .conflict: ConflictSheet(session: session) |
| 107 | case .syncCopies: SyncConflictSheet(session: session) { message = $0 } | 109 | case .syncCopies: SyncConflictSheet(session: session) { message = $0 } |
| 108 | case .recovery: RecoverySheet(session: session) { message = $0 } | 110 | case .recovery: RecoverySheet(session: session) { message = $0 } |
| 109 | case .refile: | 111 | case .refile(let command): |
| 110 | RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in | 112 | RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in |
| 111 | self.sheet = nil | 113 | self.sheet = nil |
| 112 | if let target { refile(to: target) } | 114 | guard let target else { return } |
| 115 | if command == "app.refile.goto" { | ||
| 116 | model.openRequest = .offset(target.path, target.start ?? Int.max) | ||
| 117 | } else { | ||
| 118 | refile(to: target, keep: command == "app.refile.copy") | ||
| 119 | } | ||
| 113 | } | 120 | } |
| 114 | case .block(let edit): | 121 | case .block(let edit): |
| 115 | BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in | 122 | BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in |
| @@ -204,8 +211,8 @@ struct EditorScreen: View { | |||
| 204 | editor.onAppCommand = { id in | 211 | editor.onAppCommand = { id in |
| 205 | if id == "app.save" { | 212 | if id == "app.save" { |
| 206 | _ = session.save(path) | 213 | _ = session.save(path) |
| 207 | } else if id == "app.refile" { | 214 | } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) { |
| 208 | sheet = .refile | 215 | sheet = .refile(id) |
| 209 | } else if id == "app.toggle-markup" { | 216 | } else if id == "app.toggle-markup" { |
| 210 | model.showMarkup.toggle() | 217 | model.showMarkup.toggle() |
| 211 | } else if MobileEditor.linkCommands.contains(id) { | 218 | } else if MobileEditor.linkCommands.contains(id) { |
| @@ -229,14 +236,14 @@ struct EditorScreen: View { | |||
| 229 | extension EditorScreen { | 236 | extension EditorScreen { |
| 230 | /// `org-refile` of the entry at the caret, to a target worked out again from the files | 237 | /// `org-refile` of the entry at the caret, to a target worked out again from the files |
| 231 | /// now, as the agenda's Refile… does. | 238 | /// now, as the agenda's Refile… does. |
| 232 | func refile(to target: RefileTarget) { | 239 | func refile(to target: RefileTarget, keep: Bool = false) { |
| 233 | guard let editor, let path = session.path else { return } | 240 | guard let editor, let path = session.path else { return } |
| 234 | let caret = editor.editContext().caret | 241 | let caret = editor.editContext().caret |
| 235 | guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else { | 242 | guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else { |
| 236 | message = "Can't find \(target.label) any more." | 243 | message = "Can't find \(target.label) any more." |
| 237 | return | 244 | return |
| 238 | } | 245 | } |
| 239 | message = session.refile(to: current, from: (path, caret)) | 246 | message = session.refile(to: current, from: (path, caret), keep: keep) |
| 240 | } | 247 | } |
| 241 | } | 248 | } |
| 242 | 249 | ||
| @@ -514,7 +521,7 @@ struct CommandPalette: View { | |||
| 514 | ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"), | 521 | ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"), |
| 515 | ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"), | 522 | ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"), |
| 516 | ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"), | 523 | ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"), |
| 517 | ("app.refile", "Refile…"), | 524 | ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"), |
| 518 | ("app.toggle-markup", "Show or Hide Markup"), | 525 | ("app.toggle-markup", "Show or Hide Markup"), |
| 519 | ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), | 526 | ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), |
| 520 | ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"), | 527 | ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"), |
Sources/OrgstarMobile/MobileEditor.swift +2 −1
| @@ -293,7 +293,8 @@ final class MobileEditor: NSObject, DocumentBuffer { | |||
| 293 | case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true | 293 | case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true |
| 294 | case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last", | 294 | case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last", |
| 295 | "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil | 295 | "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil |
| 296 | case "app.refile": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil | 296 | case "app.refile.goto": return onAppCommand != nil |
| 297 | case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil | ||
| 297 | case _ where Self.linkCommands.contains(id): return onAppCommand != nil | 298 | case _ where Self.linkCommands.contains(id): return onAppCommand != nil |
| 298 | case "org.link.open": return OpenLinkAtPoint().applies(in: context) | 299 | case "org.link.open": return OpenLinkAtPoint().applies(in: context) |
| 299 | case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": | 300 | case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": |
Tests/OrgAppTests/AppTests.swift +20
| @@ -409,6 +409,26 @@ struct MoveSubtreeTests { | |||
| 409 | #expect(session.document?.text == "* two\n") | 409 | #expect(session.document?.text == "* two\n") |
| 410 | } | 410 | } |
| 411 | 411 | ||
| 412 | @Test func copyLeavesTheSubtree() async throws { | ||
| 413 | let notes = try Folder() | ||
| 414 | let file = try notes.write("a.org", "* one\nbody\n* two\n") | ||
| 415 | let other = try notes.write("b.org", "* inbox\n") | ||
| 416 | let workspace = try WorkspaceModel(directory: nil) | ||
| 417 | try await workspace.addRoot(notes.url) | ||
| 418 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | ||
| 419 | session.saveMode = .explicit | ||
| 420 | session.open(file.path) | ||
| 421 | let targets = workspace.refileTargets(openPath: session.path, document: session.document) | ||
| 422 | #expect(session.refile(to: targets[2], keep: true) == "Copied to a.org/two") | ||
| 423 | #expect(session.document?.text == "* one\nbody\n* two\n** one\nbody\n") | ||
| 424 | |||
| 425 | let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" }) | ||
| 426 | StateBufferCaret.set(session, 0) | ||
| 427 | #expect(session.refile(to: inbox, keep: true) == "Copied to b.org/inbox") | ||
| 428 | #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n") | ||
| 429 | #expect(session.document?.text == "* one\nbody\n* two\n** one\nbody\n") | ||
| 430 | } | ||
| 431 | |||
| 412 | @Test func archiveToTheArchiveFile() throws { | 432 | @Test func archiveToTheArchiveFile() throws { |
| 413 | let notes = try Folder() | 433 | let notes = try Folder() |
| 414 | let file = try notes.write("a.org", "* done\n* keep\n") | 434 | let file = try notes.write("a.org", "* done\n* keep\n") |
Tests/OrgCoreTests/ElementCommandTests.swift added +102
| @@ -0,0 +1,102 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import OrgCore | ||
| 4 | |||
| 5 | /// `org-drag-element-*`, `org-insert-drawer` and `org-cycle-list-bullet` against Org. | ||
| 6 | struct ElementCommandTests { | ||
| 7 | static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil | ||
| 8 | |||
| 9 | /// Texts with `¶` where the caret is. | ||
| 10 | static let drags = [ | ||
| 11 | "* H\nFirst ¶para\nstill first\n\nSecond para\n\nThird\n", | ||
| 12 | "* H\nFirst para\n\nSecond ¶para\n\nThird\n", | ||
| 13 | "* H\nFirst para\n\n\nSecond para\n¶\nThird\n", | ||
| 14 | "* H\n#+NAME: x\n#+begin_src sh\necho ¶hi\n#+end_src\n\nAfter\n", | ||
| 15 | "* H\nBefore\n\n#+NAME: x\n#+begin_src sh\necho ¶hi\n#+end_src\n", | ||
| 16 | "* H\nOnly ¶para\n** Child\nbody\n", | ||
| 17 | "* H\nLast ¶para\n* Next\n", | ||
| 18 | "Pre¶amble\n\nmore\n* H\n", | ||
| 19 | "* H\n#+begin_quote\nin ¶quote\n\nsecond in quote\n#+end_quote\n", | ||
| 20 | "* H\n:NOTES:\none\n\n¶two\n:END:\nafter\n", | ||
| 21 | "* H\nA\nB¶", | ||
| 22 | ] | ||
| 23 | |||
| 24 | static func place(_ marked: String) -> (text: String, caret: Int) { | ||
| 25 | let ns = marked as NSString | ||
| 26 | let at = ns.range(of: "¶").location | ||
| 27 | return (ns.replacingCharacters(in: NSRange(location: at, length: 1), with: ""), at) | ||
| 28 | } | ||
| 29 | |||
| 30 | static func ours(_ command: any OrgCommand, _ text: String, _ caret: Int, answers: [String: String] = [:], selection: Range<Int>? = nil) -> (text: String, caret: Int, failure: String?) { | ||
| 31 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection ?? caret..<caret], answers: answers) | ||
| 32 | switch command.run(in: context) { | ||
| 33 | case .commit(let result): | ||
| 34 | let new = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) } | ||
| 35 | return (new, result.selection?.first?.lowerBound ?? caret, nil) | ||
| 36 | case .failed(let message): return (text, caret, message) | ||
| 37 | default: return (text, caret, "other") | ||
| 38 | } | ||
| 39 | } | ||
| 40 | |||
| 41 | @Test(.enabled(if: oracle)) | ||
| 42 | func dragsLikeOrg() throws { | ||
| 43 | var cases: [EmacsOracle.Case] = [] | ||
| 44 | var ours: [(String, Int, String?)] = [] | ||
| 45 | for marked in Self.drags { | ||
| 46 | let (text, caret) = Self.place(marked) | ||
| 47 | for forward in [true, false] { | ||
| 48 | cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: forward ? "(org-drag-element-forward)" : "(org-drag-element-backward)")) | ||
| 49 | ours.append(Self.ours(DragElement(forward: forward), text, caret)) | ||
| 50 | } | ||
| 51 | } | ||
| 52 | for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() { | ||
| 53 | let failed = !theirs.error.isEmpty | ||
| 54 | let label = "\(cases[i].form) on \(cases[i].text.debugDescription)" | ||
| 55 | if failed { | ||
| 56 | #expect(mine.2 != nil && mine.0 == cases[i].text, "\(label): emacs \(theirs.error), ours \(mine.0.debugDescription)") | ||
| 57 | } else { | ||
| 58 | #expect(mine.0 == theirs.text && mine.1 == EmacsOracle.offset(theirs.point, in: theirs.text), | ||
| 59 | "\(label)\nours: \(mine.0.debugDescription) @\(mine.1) \(mine.2 ?? "")\nemacs: \(theirs.text.debugDescription) @\(EmacsOracle.offset(theirs.point, in: theirs.text))") | ||
| 60 | } | ||
| 61 | } | ||
| 62 | } | ||
| 63 | |||
| 64 | @Test(.enabled(if: oracle)) | ||
| 65 | func insertsDrawersLikeOrg() throws { | ||
| 66 | let texts: [(String, Range<Int>?)] = [ | ||
| 67 | ("* H\nbody¶\n", nil), ("* H\n¶\n", nil), ("* H\nbo¶dy\n", nil), | ||
| 68 | ("* H\n¶one\ntwo\n\nafter\n", 4..<12), ("* H\n ¶indented\n more\n", 4..<22), | ||
| 69 | ] | ||
| 70 | var cases: [EmacsOracle.Case] = [] | ||
| 71 | var ours: [(String, Int, String?)] = [] | ||
| 72 | for (marked, region) in texts { | ||
| 73 | let (text, caret) = Self.place(marked) | ||
| 74 | let form = region.map { "(progn (transient-mark-mode 1) (set-mark \(EmacsOracle.point($0.lowerBound, in: text))) (goto-char \(EmacsOracle.point($0.upperBound, in: text))) (activate-mark) (org-insert-drawer nil \"NOTES\"))" } | ||
| 75 | ?? "(org-insert-drawer nil \"NOTES\")" | ||
| 76 | cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(region?.upperBound ?? caret, in: text), form: form)) | ||
| 77 | ours.append(Self.ours(InsertDrawer(), text, region?.upperBound ?? caret, answers: ["drawer": "NOTES"], selection: region)) | ||
| 78 | } | ||
| 79 | for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() { | ||
| 80 | #expect(mine.0 == theirs.text && mine.1 == EmacsOracle.offset(theirs.point, in: theirs.text), | ||
| 81 | "\(cases[i].form) on \(cases[i].text.debugDescription)\nours: \(mine.0.debugDescription) @\(mine.1) \(mine.2 ?? "")\nemacs: \(theirs.text.debugDescription) @\(EmacsOracle.offset(theirs.point, in: theirs.text)) \(theirs.error)") | ||
| 82 | } | ||
| 83 | #expect(Self.ours(InsertDrawer(), "x\n", 0, answers: ["drawer": "bad name"]).failure == "Invalid drawer name") | ||
| 84 | } | ||
| 85 | |||
| 86 | @Test(.enabled(if: oracle)) | ||
| 87 | func cyclesBulletsBothWaysLikeOrg() throws { | ||
| 88 | let texts = ["- a¶\n- b\n", "+ a¶\n+ b\n", "1. a¶\n2. b\n", "1) a¶\n", " * a¶\n * b\n"] | ||
| 89 | var cases: [EmacsOracle.Case] = [] | ||
| 90 | var ours: [(String, Int, String?)] = [] | ||
| 91 | for marked in texts { | ||
| 92 | let (text, caret) = Self.place(marked) | ||
| 93 | for previous in [false, true] { | ||
| 94 | cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: previous ? "(org-cycle-list-bullet 'previous)" : "(org-cycle-list-bullet)")) | ||
| 95 | ours.append(Self.ours(CycleBullet(previous: previous), text, caret)) | ||
| 96 | } | ||
| 97 | } | ||
| 98 | for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() { | ||
| 99 | #expect(mine.0 == theirs.text, "\(cases[i].form) on \(cases[i].text.debugDescription)\nours: \(mine.0.debugDescription)\nemacs: \(theirs.text.debugDescription) \(theirs.error)") | ||
| 100 | } | ||
| 101 | } | ||
| 102 | } | ||
Tests/OrgCoreTests/KeymapTests.swift +13
| @@ -181,6 +181,19 @@ struct KeymapTests { | |||
| 181 | } | 181 | } |
| 182 | } | 182 | } |
| 183 | 183 | ||
| 184 | @Test func structureCommandsAreBound() { | ||
| 185 | let emacs = KeymapPreset.emacs.keymap, doom = KeymapPreset.doom.keymap | ||
| 186 | for (command, keys) in [("org.drawer.insert", "C-c C-x d"), ("app.refile.copy", "C-c M-w"), ("app.refile.goto", "C-u C-c C-w"), | ||
| 187 | ("org.element.drag-forward", "M-<down>"), ("org.item.bullet-next", "S-<right>")] { | ||
| 188 | #expect(emacs.keyLabels(for: command).contains(keys), "\(command)") | ||
| 189 | } | ||
| 190 | #expect(doom.keyLabels(for: "app.refile.goto", modes: ["normal"]).contains("SPC u SPC m r r")) | ||
| 191 | #expect(doom.keyLabels(for: "org.element.drag-backward", modes: ["normal"]).contains("M-k")) | ||
| 192 | let labels = doom.keyLabels(for: "org.item.bullet-previous", modes: ["normal"], limit: 5) | ||
| 193 | #expect(labels.contains("C-H"), "\(labels)") | ||
| 194 | #expect(doom.keyLabels(for: "app.refile.copy", modes: ["normal"]).contains("C-c M-w")) | ||
| 195 | } | ||
| 196 | |||
| 184 | @Test func shadowedBindingsShowNoKeys() throws { | 197 | @Test func shadowedBindingsShowNoKeys() throws { |
| 185 | var problems: [String] = [] | 198 | var problems: [String] = [] |
| 186 | let map = Keymap.layered([KeymapPreset.emacs.keymap, try Keymap(toml: "[[bind]]\nkeys = \"C-c C-t\"\ncommand = \"app.save\"\n", problems: &problems)]) | 199 | let map = Keymap.layered([KeymapPreset.emacs.keymap, try Keymap(toml: "[[bind]]\nkeys = \"C-c C-t\"\ncommand = \"app.save\"\n", problems: &problems)]) |
docs/manual/guide/03-keys.org +9 −1
| @@ -537,7 +537,7 @@ Besides the leader, the preset binds these evil-org and Doom keys in normal stat | |||
| 537 | | =] b=, =[ b= | Next or previous buffer. | | 537 | | =] b=, =[ b= | Next or previous buffer. | |
| 538 | | =M-h=, =M-j=, =M-k=, =M-l= | =M-<left>=, =M-<down>=, =M-<up>=, =M-<right>=: promote, move down, move up, demote on headings; the same for items; move columns and rows in tables. Also in insert and visual state. | | 538 | | =M-h=, =M-j=, =M-k=, =M-l= | =M-<left>=, =M-<down>=, =M-<up>=, =M-<right>=: promote, move down, move up, demote on headings; the same for items; move columns and rows in tables. Also in insert and visual state. | |
| 539 | | =M-H=, =M-J=, =M-K=, =M-L= | The =M-S-= arrow forms: subtree promote and demote, table row and column insert and delete. Also in insert and visual state. | | 539 | | =M-H=, =M-J=, =M-K=, =M-L= | The =M-S-= arrow forms: subtree promote and demote, table row and column insert and delete. Also in insert and visual state. | |
| 540 | | =C-S-h=, =C-S-j=, =C-S-k=, =C-S-l= | The =S-= arrow forms: TODO keyword, priority, timestamp and property value changes. Also in insert state. | | 540 | | =C-S-h=, =C-S-j=, =C-S-k=, =C-S-l= | The =S-= arrow forms: TODO keyword, priority, timestamp, property value and list bullet changes. Also in insert state. | |
| 541 | 541 | ||
| 542 | ** The leader | 542 | ** The leader |
| 543 | 543 | ||
| @@ -622,6 +622,7 @@ Besides the leader, the preset binds these evil-org and Doom keys in normal stat | |||
| 622 | | =SPC m p u= | Raise Priority (=org.priority.up=) | | 622 | | =SPC m p u= | Raise Priority (=org.priority.up=) | |
| 623 | | =SPC m q= | Set Tags (=org.tags.set=) | | 623 | | =SPC m q= | Set Tags (=org.tags.set=) | |
| 624 | | =SPC m r r= | Refile… (=app.refile=) | | 624 | | =SPC m r r= | Refile… (=app.refile=) | |
| 625 | | =SPC u SPC m r r= | Go to Refile Target… (=app.refile.goto=) | | ||
| 625 | | =SPC m s A= | Archive Subtree (=app.archive=) | | 626 | | =SPC m s A= | Archive Subtree (=app.archive=) | |
| 626 | | =SPC m s N= | Widen (=org.widen=) | | 627 | | =SPC m s N= | Widen (=org.widen=) | |
| 627 | | =SPC m s S= | Sort Entries (=org.sort=) | | 628 | | =SPC m s S= | Sort Entries (=org.sort=) | |
| @@ -820,6 +821,11 @@ When a key appears in several rows, it runs the command whose condition holds at | |||
| 820 | | Toggle Heading (=org.heading.toggle=) | =C-c *= | — | =SPC m h= (N) | Outside a table, turns headings into text and lines or items into headings (=org-toggle-heading=). | | 821 | | Toggle Heading (=org.heading.toggle=) | =C-c *= | — | =SPC m h= (N) | Outside a table, turns headings into text and lines or items into headings (=org-toggle-heading=). | |
| 821 | | Toggle COMMENT (=org.heading.toggle-comment=) | =C-c ;= | — | — | Adds or removes the =COMMENT= keyword (=org-toggle-comment=). | | 822 | | Toggle COMMENT (=org.heading.toggle-comment=) | =C-c ;= | — | — | Adds or removes the =COMMENT= keyword (=org-toggle-comment=). | |
| 822 | | Refile… (=app.refile=) | =C-c C-w= | =⌃⌘W= | =SPC m r r= (N), =SPC m s r= (N) | Asks for a target heading in your folders and moves the subtree there (=org-refile=). | | 823 | | Refile… (=app.refile=) | =C-c C-w= | =⌃⌘W= | =SPC m r r= (N), =SPC m s r= (N) | Asks for a target heading in your folders and moves the subtree there (=org-refile=). | |
| 824 | | Copy to Refile Target… (=app.refile.copy=) | =C-c M-w= | — | =C-c M-w= | Asks for a target and copies the subtree there (=org-copy=). | | ||
| 825 | | Go to Refile Target… (=app.refile.goto=) | =C-u C-c C-w= | — | =SPC u SPC m r r= (N) | Asks for a target and jumps to it (=org-refile= with a prefix). | | ||
| 826 | | Drag Element Backward (=org.element.drag-backward=) | =M-<up>= | — | =M-k= | Away from headings, items and tables, swaps the element with the one before it (=org-drag-element-backward=). | | ||
| 827 | | Drag Element Forward (=org.element.drag-forward=) | =M-<down>= | — | =M-j= | Away from headings, items and tables, swaps the element with the one after it (=org-drag-element-forward=). | | ||
| 828 | | Insert Drawer (=org.drawer.insert=) | =C-c C-x d= | — | =C-c C-x d= | Asks for a name and inserts a drawer, or puts the selected lines in one (=org-insert-drawer=). | | ||
| 823 | | Archive Subtree (=app.archive=) | =C-c C-x C-s=, =C-c $= | =⌃⌘A= | =SPC m A= (N), =SPC m s A= (N) | Moves the subtree to the archive file (=org-archive-subtree=). | | 829 | | Archive Subtree (=app.archive=) | =C-c C-x C-s=, =C-c $= | =⌃⌘A= | =SPC m A= (N), =SPC m s A= (N) | Moves the subtree to the archive file (=org-archive-subtree=). | |
| 824 | | Toggle ARCHIVE Tag (=org.archive.toggle-tag=) | =C-c C-x a= | — | =SPC m s a= (N) | Adds or removes the =ARCHIVE= tag (=org-toggle-archive-tag=). | | 830 | | Toggle ARCHIVE Tag (=org.archive.toggle-tag=) | =C-c C-x a= | — | =SPC m s a= (N) | Adds or removes the =ARCHIVE= tag (=org-toggle-archive-tag=). | |
| 825 | | Archive to Archive Sibling (=org.archive.to-sibling=) | =C-c C-x A= | — | — | Moves the subtree under an =Archive= sibling heading (=org-archive-to-archive-sibling=). | | 831 | | Archive to Archive Sibling (=org.archive.to-sibling=) | =C-c C-x A= | — | — | Moves the subtree under an =Archive= sibling heading (=org-archive-to-archive-sibling=). | |
| @@ -837,6 +843,8 @@ When a key appears in several rows, it runs the command whose condition holds at | |||
| 837 | | Move Item Up (=org.item.up=) | =M-<up>= | =⌃⌥⌘↑= | =M-k= | In a list, swaps the item with the one above (=org-move-item-up=). | | 843 | | Move Item Up (=org.item.up=) | =M-<up>= | =⌃⌥⌘↑= | =M-k= | In a list, swaps the item with the one above (=org-move-item-up=). | |
| 838 | | Move Item Down (=org.item.down=) | =M-<down>= | =⌃⌥⌘↓= | =M-j= | In a list, swaps the item with the one below (=org-move-item-down=). | | 844 | | Move Item Down (=org.item.down=) | =M-<down>= | =⌃⌥⌘↓= | =M-j= | In a list, swaps the item with the one below (=org-move-item-down=). | |
| 839 | | Toggle Checkbox (=org.checkbox.toggle=) | =C-c C-x C-b= | =⌃⌘C= | =SPC m x= (N) | Checks or unchecks the item's checkbox (=org-toggle-checkbox=). | | 845 | | Toggle Checkbox (=org.checkbox.toggle=) | =C-c C-x C-b= | =⌃⌘C= | =SPC m x= (N) | Checks or unchecks the item's checkbox (=org-toggle-checkbox=). | |
| 846 | | Next Bullet Type (=org.item.bullet-next=) | =S-<right>= | — | =C-S-l= (N, I) | On an item, gives the list the next bullet type (=org-cycle-list-bullet=). | | ||
| 847 | | Previous Bullet Type (=org.item.bullet-previous=) | =S-<left>= | — | =C-S-h= (N, I) | On an item, gives the list the previous bullet type (=org-cycle-list-bullet= with =previous=). | | ||
| 840 | | Toggle Item (=org.item.toggle=) | =C-c -= | — | =SPC m i= (N) | Outside a table: on an item, cycles the list's bullet style; elsewhere turns lines into items and items into text (=org-ctrl-c-minus=). | | 848 | | Toggle Item (=org.item.toggle=) | =C-c -= | — | =SPC m i= (N) | Outside a table: on an item, cycles the list's bullet style; elsewhere turns lines into items and items into text (=org-ctrl-c-minus=). | |
| 841 | 849 | ||
| 842 | ** TODO, priority and tags | 850 | ** TODO, priority and tags |
docs/manual/guide/04-outlines.org +13 −8
| @@ -114,7 +114,10 @@ The subtree at the caret swaps places with the previous or next sibling subtree. | |||
| 114 | can't move past its parent or the start or end of the file. The caret keeps its column. | 114 | can't move past its parent or the start or end of the file. The caret keeps its column. |
| 115 | 115 | ||
| 116 | On a list item the same keys move the item; in a table they move the row. On other | 116 | On a list item the same keys move the item; in a table they move the row. On other |
| 117 | lines they do nothing. orgstar has no =org-drag-element= for paragraphs. | 117 | elements (paragraphs, blocks, drawers, keywords) they drag the element past the one |
| 118 | before or after it in the same section, drawer or greater block, as | ||
| 119 | =org-drag-element-backward= and =org-drag-element-forward= do. The blank lines between | ||
| 120 | the two stay where they were. | ||
| 118 | 121 | ||
| 119 | ** Moving between headings | 122 | ** Moving between headings |
| 120 | 123 | ||
| @@ -368,8 +371,8 @@ list (=org-cycle-list-bullet=) through: | |||
| 368 | 371 | ||
| 369 | =*= is skipped for a list at the left margin. Description lists skip the numbered and | 372 | =*= is skipped for a list at the left margin. Description lists skip the numbered and |
| 370 | lettered bullets. Lettered bullets are offered only when the list has 26 items or | 373 | lettered bullets. Lettered bullets are offered only when the list has 26 items or |
| 371 | fewer. Org also cycles bullets with =S-<left>= and =S-<right>= on an item; orgstar | 374 | fewer. =S-<right>= and =S-<left>= on an item (Doom =C-S-l= and =C-S-h=) cycle forward |
| 372 | does not bind those on items. | 375 | and backward. |
| 373 | 376 | ||
| 374 | Numbered and lettered lists are renumbered whenever a list command changes them, and | 377 | Numbered and lettered lists are renumbered whenever a list command changes them, and |
| 375 | by =C-c C-c= on any item. To start a list at a given number, put a counter after the | 378 | by =C-c C-c= on any item. To start a list at a given number, put a counter after the |
| @@ -528,7 +531,9 @@ file opens, as with Org's =org-cycle-hide-drawer-startup= (=true= by default in | |||
| 528 | =config.toml=). =#+STARTUP: nohidedrawers= keeps them open in one file, and | 531 | =config.toml=). =#+STARTUP: nohidedrawers= keeps them open in one file, and |
| 529 | =#+STARTUP: hidedrawers= folds them when the setting is off. | 532 | =#+STARTUP: hidedrawers= folds them when the setting is off. |
| 530 | 533 | ||
| 531 | Org's =org-insert-drawer= (=C-c C-x d=) is not available; type the two lines yourself. | 534 | Insert Drawer (=org-insert-drawer=, =C-c C-x d=) asks for a name. With no selection |
| 535 | it inserts an empty drawer on a new line; with a selection it puts the selected lines | ||
| 536 | in the drawer. A selection containing a heading is refused. | ||
| 532 | 537 | ||
| 533 | * Properties | 538 | * Properties |
| 534 | 539 | ||
| @@ -769,6 +774,10 @@ files, =org-refile-use-outline-path= set to =file=, =org-reverse-note-order= =ni | |||
| 769 | entries go last), =org-log-refile= =nil= and =org-refile-keep= =nil=. None of these is | 774 | entries go last), =org-log-refile= =nil= and =org-refile-keep= =nil=. None of these is |
| 770 | configurable in orgstar. Refiling from the agenda is covered in [[file:07-agenda.org][Agenda]]. | 775 | configurable in orgstar. Refiling from the agenda is covered in [[file:07-agenda.org][Agenda]]. |
| 771 | 776 | ||
| 777 | Copy to Refile Target… (=org-copy=, =C-c M-w=) asks the same way and copies the | ||
| 778 | subtree there, leaving it in place. Go to Refile Target… (=C-u C-c C-w=, Doom | ||
| 779 | =SPC u SPC m r r=) asks the same way and jumps to the heading, or to the end of a file. | ||
| 780 | |||
| 772 | * Archiving | 781 | * Archiving |
| 773 | 782 | ||
| 774 | ** Archive Subtree | 783 | ** Archive Subtree |
| @@ -886,11 +895,7 @@ The full list is in [[file:03-keys.org][Keys]]. | |||
| 886 | 895 | ||
| 887 | These Org structure features are not in orgstar: | 896 | These Org structure features are not in orgstar: |
| 888 | 897 | ||
| 889 | - =org-insert-drawer=, =org-copy= (refile a copy) and =org-refile= with a prefix | ||
| 890 | (jump to a target). | ||
| 891 | - Editing values in column view, and writing summaries from it; the | 898 | - Editing values in column view, and writing summaries from it; the |
| 892 | =columnview= dynamic block does write summaries. | 899 | =columnview= dynamic block does write summaries. |
| 893 | - The =ORDERED= property, radio lists and timer list items in the list commands. | 900 | - The =ORDERED= property, radio lists and timer list items in the list commands. |
| 894 | - =S-<left>= and =S-<right>= to cycle bullets on an item; use =C-c -=. | ||
| 895 | - =org-drag-element= (=M-<up>= and =M-<down>= on paragraphs). | ||
| 896 | - Custom =org-refile-targets=. | 901 | - Custom =org-refile-targets=. |