Commit 6384ff6ccb
Verified · cmc
Layout: unified · split
Sources/OrgCore/Commands/Command.swift +1 −1
| @@ -333,7 +333,7 @@ public enum Commands { | |||
| 333 | TimerSetCountdown(), TimerShowRemaining(), TimerChangeTimes(), | 333 | TimerSetCountdown(), TimerShowRemaining(), TimerChangeTimes(), |
| 334 | InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true), | 334 | InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true), |
| 335 | RemovePlanning(deadline: false), RemovePlanning(deadline: true), FillParagraph(), CreateTable(), | 335 | RemovePlanning(deadline: false), RemovePlanning(deadline: true), FillParagraph(), CreateTable(), |
| 336 | TableRecalculate(all: false), TableRecalculate(all: true), TableIterate(), ExecuteSrcBlock(), OrgDwim(), | 336 | TableRecalculate(all: false), TableRecalculate(all: true), TableIterate(), TableElMoveCell(forward: true), TableElMoveCell(forward: false), TableElAlign(), ExecuteSrcBlock(), OrgDwim(), |
| 337 | ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false), | 337 | ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false), |
| 338 | OpenLinkAtPoint(), CreateID(), ToggleComment(), ToggleHeading(), ToggleItem(), MarkSubtree(), | 338 | OpenLinkAtPoint(), CreateID(), ToggleComment(), ToggleHeading(), ToggleItem(), MarkSubtree(), |
| 339 | CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target), | 339 | CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target), |
Sources/OrgCore/Commands/CtrlCCtrlC.swift +2
| @@ -35,6 +35,8 @@ public struct CtrlCCtrlC: OrgCommand { | |||
| 35 | } | 35 | } |
| 36 | return TableRecalculate.inEmacs(step, form: "(org-ctrl-c-ctrl-c)", in: context) | 36 | return TableRecalculate.inEmacs(step, form: "(org-ctrl-c-ctrl-c)", in: context) |
| 37 | } | 37 | } |
| 38 | // Org says to edit table.el tables with C-c '; here their borders line up again. | ||
| 39 | if KeyContext.holds("table-el", in: context) { return TableElAlign().run(in: context) } | ||
| 38 | if buffer.footnoteReferenceAtPoint() != nil | 40 | if buffer.footnoteReferenceAtPoint() != nil |
| 39 | || buffer.footnoteDefinitions().contains(where: { $0.begin <= context.caret && context.caret < ($0.contentsBegin ?? $0.end) }) { | 41 | || buffer.footnoteDefinitions().contains(where: { $0.begin <= context.caret && context.caret < ($0.contentsBegin ?? $0.end) }) { |
| 40 | return FootnoteAction().run(in: context) | 42 | return FootnoteAction().run(in: context) |
Sources/OrgCore/Commands/TableElCommands.swift added +181
| @@ -0,0 +1,181 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // Editing table.el tables (`+---+` borders) in place: moving between cells as | ||
| 4 | // `table-forward-cell` does, and lining the borders up again after typing, which table.el | ||
| 5 | // does as each character goes in. Org itself edits them only in table.el's buffer (C-c '). | ||
| 6 | |||
| 7 | /// A table.el table in the text: its lines, without their common indentation. | ||
| 8 | struct TableElDrawing { | ||
| 9 | /// Where each line starts in the text, and the lines. | ||
| 10 | let starts: [Int] | ||
| 11 | let lines: [[Character]] | ||
| 12 | let indent: String | ||
| 13 | |||
| 14 | init?(_ context: EditContext) { | ||
| 15 | var node = context.tree.root | ||
| 16 | var table: SyntaxNode? | ||
| 17 | while let child = node.child(containing: context.caret) { | ||
| 18 | if child.kind == .tableEl { table = child } | ||
| 19 | node = child | ||
| 20 | } | ||
| 21 | guard let table else { return nil } | ||
| 22 | let ns = context.text as NSString | ||
| 23 | var starts: [Int] = [] | ||
| 24 | var raw: [String] = [] | ||
| 25 | var at = table.range.lowerBound | ||
| 26 | while at < table.range.upperBound { | ||
| 27 | let line = ns.lineRange(for: NSRange(location: at, length: 0)) | ||
| 28 | let text = ns.substring(with: line).trimmingCharacters(in: .newlines) | ||
| 29 | if text.trimmingCharacters(in: .whitespaces).isEmpty { break } | ||
| 30 | starts.append(line.location) | ||
| 31 | raw.append(text) | ||
| 32 | at = NSMaxRange(line) | ||
| 33 | } | ||
| 34 | let indent = raw.map { $0.prefix { $0 == " " || $0 == "\t" }.count }.min() ?? 0 | ||
| 35 | self.starts = starts | ||
| 36 | self.lines = raw.map { Array($0.dropFirst(indent)) } | ||
| 37 | self.indent = String(raw.first?.prefix(indent) ?? "") | ||
| 38 | } | ||
| 39 | |||
| 40 | /// The line and character column of a text offset, the column past the indentation. | ||
| 41 | func position(_ offset: Int, in text: String) -> (line: Int, column: Int)? { | ||
| 42 | guard let line = starts.lastIndex(where: { $0 <= offset }) else { return nil } | ||
| 43 | let ns = text as NSString | ||
| 44 | let before = ns.substring(with: NSRange(location: starts[line], length: offset - starts[line])) | ||
| 45 | return (line, before.count - indent.count) | ||
| 46 | } | ||
| 47 | |||
| 48 | /// The text offset of a line and column. | ||
| 49 | func offset(line: Int, column: Int) -> Int { | ||
| 50 | let prefix = indent + String(lines[line].prefix(max(0, column))) | ||
| 51 | return starts[line] + (prefix as NSString).length | ||
| 52 | } | ||
| 53 | } | ||
| 54 | |||
| 55 | extension TableEl { | ||
| 56 | /// `table-forward-cell`: the cell after the one holding the caret, or before it, wrapping | ||
| 57 | /// around; the caret at its first character. Nil when the drawing has no cells. | ||
| 58 | static func move(_ drawing: TableElDrawing, from position: (line: Int, column: Int), forward: Bool) -> (line: Int, column: Int)? { | ||
| 59 | guard let rects = rects(drawing.lines)?.map(\.rect), !rects.isEmpty else { return nil } | ||
| 60 | let ordered = rects.sorted { ($0.top, $0.left) < ($1.top, $1.left) } | ||
| 61 | let current = ordered.firstIndex { $0.top < position.line && position.line < $0.bottom && $0.left < position.column && position.column <= $0.right } | ||
| 62 | let next: Rect | ||
| 63 | if let current { | ||
| 64 | next = ordered[(current + (forward ? 1 : ordered.count - 1)) % ordered.count] | ||
| 65 | } else { | ||
| 66 | // On a border: the first cell after the caret, or the last before it. | ||
| 67 | let after = ordered.first { ($0.top + 1, $0.left + 1) > (position.line, position.column) } | ||
| 68 | let before = ordered.last { ($0.top + 1, $0.left + 1) < (position.line, position.column) } | ||
| 69 | next = (forward ? after ?? ordered.first : before ?? ordered.last)! | ||
| 70 | } | ||
| 71 | return (next.top + 1, next.left + 1) | ||
| 72 | } | ||
| 73 | |||
| 74 | /// The drawing with its borders lined up: each column as wide as its widest cell, and no | ||
| 75 | /// narrower than its rules. Nil for tables with merged cells, or lines that aren't rules | ||
| 76 | /// or rows of the same number of cells. | ||
| 77 | static func aligned(_ lines: [[Character]]) -> [[Character]]? { | ||
| 78 | let strings = lines.map { String($0) } | ||
| 79 | let rules = strings.map { $0.trimmingCharacters(in: .whitespaces).wholeMatch(of: /\+(?:-+\+)+/) != nil } | ||
| 80 | let columns = strings.enumerated().compactMap { rules[$0.offset] ? $0.element.trimmingCharacters(in: .whitespaces).filter { $0 == "+" }.count - 1 : nil } | ||
| 81 | guard let count = columns.first, columns.allSatisfy({ $0 == count }) else { return nil } | ||
| 82 | var cells: [[String]?] = [] | ||
| 83 | var widths = [Int](repeating: 0, count: count) | ||
| 84 | for (index, line) in strings.enumerated() { | ||
| 85 | let trimmed = line.trimmingCharacters(in: .whitespaces) | ||
| 86 | if rules[index] { | ||
| 87 | let segments = trimmed.dropFirst().dropLast().split(separator: "+", omittingEmptySubsequences: false) | ||
| 88 | for (j, segment) in segments.enumerated() { widths[j] = max(widths[j], segment.count) } | ||
| 89 | cells.append(nil) | ||
| 90 | continue | ||
| 91 | } | ||
| 92 | guard trimmed.hasPrefix("|"), trimmed.hasSuffix("|"), trimmed.count >= 2 else { return nil } | ||
| 93 | let parts = trimmed.dropFirst().dropLast().split(separator: "|", omittingEmptySubsequences: false).map(String.init) | ||
| 94 | guard parts.count == count else { return nil } | ||
| 95 | // Text typed into a cell takes up its trailing spaces first. | ||
| 96 | let content = parts.map { $0.replacing(/[ \t]+$/, with: "") } | ||
| 97 | for (j, cell) in content.enumerated() { widths[j] = max(widths[j], cell.count) } | ||
| 98 | cells.append(content) | ||
| 99 | } | ||
| 100 | return cells.map { row in | ||
| 101 | guard let row else { return Array("+" + widths.map { String(repeating: "-", count: $0) }.joined(separator: "+") + "+") } | ||
| 102 | return Array("|" + zip(row, widths).map { $0 + String(repeating: " ", count: $1 - $0.count) }.joined(separator: "|") + "|") | ||
| 103 | } | ||
| 104 | } | ||
| 105 | } | ||
| 106 | |||
| 107 | /// The table's text and caret after lining up its borders: the caret stays in its cell, at the | ||
| 108 | /// same place in the cell's text. Nil when the table can't be aligned. | ||
| 109 | private func alignedTable(_ drawing: TableElDrawing, _ context: EditContext) -> (edit: TextEdit, caretLine: Int, caretColumn: Int)? { | ||
| 110 | guard let lines = TableEl.aligned(drawing.lines) else { return nil } | ||
| 111 | let position = drawing.position(context.caret, in: context.text) ?? (0, 0) | ||
| 112 | // The caret's cell is the number of bars before it on its line; its place in the cell | ||
| 113 | // the characters after the last bar. | ||
| 114 | let line = drawing.lines[position.line] | ||
| 115 | let before = line.prefix(max(0, position.column)) | ||
| 116 | let bars = before.filter { $0 == "|" || $0 == "+" }.count | ||
| 117 | let inCell = before.count - ((before.lastIndex { $0 == "|" || $0 == "+" }).map { $0 + 1 } ?? 0) | ||
| 118 | var column = 0 | ||
| 119 | var seen = 0 | ||
| 120 | for (index, ch) in lines[position.line].enumerated() where ch == "|" || ch == "+" { | ||
| 121 | seen += 1 | ||
| 122 | if seen == bars { column = index + 1; break } | ||
| 123 | } | ||
| 124 | let ns = context.text as NSString | ||
| 125 | let start = drawing.starts.first! | ||
| 126 | let lastLine = ns.lineRange(for: NSRange(location: drawing.starts.last!, length: 0)) | ||
| 127 | let end = NSMaxRange(lastLine) - (ns.substring(with: lastLine).hasSuffix("\n") ? 1 : 0) | ||
| 128 | let text = lines.map { drawing.indent + String($0) }.joined(separator: "\n") | ||
| 129 | let cellWidth = (lines[position.line].dropFirst(column).firstIndex { $0 == "|" || $0 == "+" } ?? lines[position.line].count) - column | ||
| 130 | return (TextEdit(range: start..<end, replacement: text), position.line, column + min(inCell, max(0, cellWidth))) | ||
| 131 | } | ||
| 132 | |||
| 133 | /// TAB and S-TAB in a table.el table: the borders lined up, then the next or previous cell | ||
| 134 | /// (`table-forward-cell`, `table-backward-cell`). | ||
| 135 | public struct TableElMoveCell: OrgCommand { | ||
| 136 | public let forward: Bool | ||
| 137 | public init(forward: Bool) { self.forward = forward } | ||
| 138 | public var id: String { forward ? "org.table-el.next-cell" : "org.table-el.previous-cell" } | ||
| 139 | public var title: String { forward ? "Next table.el Cell" : "Previous table.el Cell" } | ||
| 140 | public func applies(in context: EditContext) -> Bool { TableElDrawing(context) != nil } | ||
| 141 | |||
| 142 | public func run(in context: EditContext) -> CommandStep { | ||
| 143 | guard var drawing = TableElDrawing(context) else { return .failed("Not in a table.el table") } | ||
| 144 | var edits: [TextEdit] = [] | ||
| 145 | var position = drawing.position(context.caret, in: context.text) ?? (0, 0) | ||
| 146 | var text = context.text | ||
| 147 | if let aligned = alignedTable(drawing, context), aligned.edit.replacement != (text as NSString).substring(with: NSRange(aligned.edit.range)) { | ||
| 148 | edits = [aligned.edit] | ||
| 149 | text = aligned.edit.apply(to: text) | ||
| 150 | position = (aligned.caretLine, aligned.caretColumn) | ||
| 151 | let tree = OrgParser.parse(text, defaults: context.tree.settings) | ||
| 152 | let caret = drawing.offset(line: 0, column: 0) | ||
| 153 | guard let again = TableElDrawing(EditContext(revision: context.revision, text: text, tree: tree, selection: [caret..<caret])) else { return .failed("Not in a table.el table") } | ||
| 154 | drawing = again | ||
| 155 | } | ||
| 156 | guard let target = TableEl.move(drawing, from: position, forward: forward) else { return .failed("Not a table.el table with cells") } | ||
| 157 | let caret = drawing.offset(line: target.line, column: target.column) | ||
| 158 | return .commit(EditResult(baseRevision: context.revision, edits: edits, selection: [caret..<caret])) | ||
| 159 | } | ||
| 160 | } | ||
| 161 | |||
| 162 | /// C-c C-c in a table.el table: the borders lined up again. | ||
| 163 | public struct TableElAlign: OrgCommand { | ||
| 164 | public init() {} | ||
| 165 | public var id: String { "org.table-el.align" } | ||
| 166 | public var title: String { "Align table.el Table" } | ||
| 167 | public func applies(in context: EditContext) -> Bool { TableElDrawing(context) != nil } | ||
| 168 | |||
| 169 | public func run(in context: EditContext) -> CommandStep { | ||
| 170 | guard let drawing = TableElDrawing(context) else { return .failed("Not in a table.el table") } | ||
| 171 | guard let aligned = alignedTable(drawing, context) else { return .failed("Can't align a table.el table with merged cells") } | ||
| 172 | let text = aligned.edit.apply(to: context.text) | ||
| 173 | let tree = OrgParser.parse(text, defaults: context.tree.settings) | ||
| 174 | let first = drawing.starts.first! | ||
| 175 | guard let again = TableElDrawing(EditContext(revision: context.revision, text: text, tree: tree, selection: [first..<first])) else { | ||
| 176 | return .failed("Not in a table.el table") | ||
| 177 | } | ||
| 178 | let caret = again.offset(line: aligned.caretLine, column: aligned.caretColumn) | ||
| 179 | return .commit(EditResult(baseRevision: context.revision, edits: [aligned.edit], selection: [caret..<caret])) | ||
| 180 | } | ||
| 181 | } | ||
Sources/OrgCore/Export/TableEl.swift +30 −14
| @@ -10,11 +10,15 @@ enum TableEl { | |||
| 10 | var rowspan: Int | 10 | var rowspan: Int |
| 11 | } | 11 | } |
| 12 | 12 | ||
| 13 | /// The cells in reading order, or nil when the drawing isn't a well-formed table. | 13 | /// A cell's borders in the drawing: the lines of its top and bottom rules, and the |
| 14 | static func cells(_ text: String) -> [Cell]? { | 14 | /// columns of its left and right bars. |
| 15 | let raw = text.components(separatedBy: "\n").filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty } | 15 | struct Rect: Equatable { |
| 16 | let indent = raw.map { $0.prefix { $0 == " " || $0 == "\t" }.count }.min() ?? 0 | 16 | var top: Int, left: Int, right: Int, bottom: Int |
| 17 | let grid = raw.map { Array($0.dropFirst(indent)) } | 17 | } |
| 18 | |||
| 19 | /// The cells' borders in reading order, with the grid rows and columns each spans, or nil | ||
| 20 | /// when the drawing isn't a well-formed table. | ||
| 21 | static func rects(_ grid: [[Character]]) -> [(rect: Rect, colspan: Int, rowspan: Int)]? { | ||
| 18 | guard grid.count >= 3 else { return nil } | 22 | guard grid.count >= 3 else { return nil } |
| 19 | func at(_ r: Int, _ c: Int) -> Character? { r >= 0 && r < grid.count && c >= 0 && c < grid[r].count ? grid[r][c] : nil } | 23 | func at(_ r: Int, _ c: Int) -> Character? { r >= 0 && r < grid.count && c >= 0 && c < grid[r].count ? grid[r][c] : nil } |
| 20 | func vertical(_ r: Int, _ c: Int) -> Bool { at(r, c) == "|" || at(r, c) == "+" } | 24 | func vertical(_ r: Int, _ c: Int) -> Bool { at(r, c) == "|" || at(r, c) == "+" } |
| @@ -28,7 +32,7 @@ enum TableEl { | |||
| 28 | if horizontal(r, c + 1) || horizontal(r, c - 1) { if rows.last != r { rows.append(r) } } | 32 | if horizontal(r, c + 1) || horizontal(r, c - 1) { if rows.last != r { rows.append(r) } } |
| 29 | } | 33 | } |
| 30 | } | 34 | } |
| 31 | var cells: [Cell] = [] | 35 | var found: [(rect: Rect, colspan: Int, rowspan: Int)] = [] |
| 32 | for r in rows { | 36 | for r in rows { |
| 33 | for c in grid[r].indices where grid[r][c] == "+" && at(r, c + 1) == "-" && vertical(r + 1, c) { | 37 | for c in grid[r].indices where grid[r][c] == "+" && at(r, c + 1) == "-" && vertical(r + 1, c) { |
| 34 | // Right edge: the next corner along the top with a border below it. | 38 | // Right edge: the next corner along the top with a border below it. |
| @@ -39,15 +43,27 @@ enum TableEl { | |||
| 39 | var r2 = r + 1 | 43 | var r2 = r + 1 |
| 40 | while r2 < grid.count, !(at(r2, c) == "+" && horizontal(r2, c + 1)) { r2 += 1 } | 44 | while r2 < grid.count, !(at(r2, c) == "+" && horizontal(r2, c + 1)) { r2 += 1 } |
| 41 | guard r2 < grid.count, r2 > r + 1 else { return nil } | 45 | guard r2 < grid.count, r2 > r + 1 else { return nil } |
| 42 | let lines = (r + 1..<r2).map { line -> String in | 46 | found.append((Rect(top: r, left: c, right: x2, bottom: r2), columns.filter { $0 > c && $0 < x2 }.count + 1, |
| 43 | let row = grid[line] | 47 | rows.filter { $0 > r && $0 < r2 }.count + 1)) |
| 44 | let end = min(x2, row.count) | 48 | } |
| 45 | return c + 1 < end ? String(row[(c + 1)..<end]).trimmingCharacters(in: .whitespaces) : "" | 49 | } |
| 46 | } | 50 | return found.isEmpty ? nil : found |
| 47 | cells.append(Cell(row: r, lines: lines, colspan: columns.filter { $0 > c && $0 < x2 }.count + 1, | 51 | } |
| 48 | rowspan: rows.filter { $0 > r && $0 < r2 }.count + 1)) | 52 | |
| 53 | /// The cells in reading order, or nil when the drawing isn't a well-formed table. | ||
| 54 | static func cells(_ text: String) -> [Cell]? { | ||
| 55 | let raw = text.components(separatedBy: "\n").filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty } | ||
| 56 | let indent = raw.map { $0.prefix { $0 == " " || $0 == "\t" }.count }.min() ?? 0 | ||
| 57 | let grid = raw.map { Array($0.dropFirst(indent)) } | ||
| 58 | guard let rects = rects(grid) else { return nil } | ||
| 59 | return rects.map { found in | ||
| 60 | let rect = found.rect | ||
| 61 | let lines = (rect.top + 1..<rect.bottom).map { line -> String in | ||
| 62 | let row = grid[line] | ||
| 63 | let end = min(rect.right, row.count) | ||
| 64 | return rect.left + 1 < end ? String(row[(rect.left + 1)..<end]).trimmingCharacters(in: .whitespaces) : "" | ||
| 49 | } | 65 | } |
| 66 | return Cell(row: rect.top, lines: lines, colspan: found.colspan, rowspan: found.rowspan) | ||
| 50 | } | 67 | } |
| 51 | return cells.isEmpty ? nil : cells | ||
| 52 | } | 68 | } |
| 53 | } | 69 | } |
Sources/OrgCore/Keymap/Keymap.swift +2 −1
| @@ -146,12 +146,13 @@ public struct Keymap: Sendable, Equatable { | |||
| 146 | 146 | ||
| 147 | /// Context names a binding's `when` can use. | 147 | /// Context names a binding's `when` can use. |
| 148 | public enum KeyContext { | 148 | public enum KeyContext { |
| 149 | public static let names: Set<String> = ["heading", "table", "item", "region", "timestamp", "tblfm", "src", "fold-line", "dblock", "speed", "property"] | 149 | public static let names: Set<String> = ["heading", "table", "table-el", "item", "region", "timestamp", "tblfm", "src", "fold-line", "dblock", "speed", "property"] |
| 150 | 150 | ||
| 151 | public static func holds(_ name: String, in context: EditContext) -> Bool { | 151 | public static func holds(_ name: String, in context: EditContext) -> Bool { |
| 152 | switch name { | 152 | switch name { |
| 153 | case "heading": return headingOnLine(at: context.caret, in: context.tree) != nil | 153 | case "heading": return headingOnLine(at: context.caret, in: context.tree) != nil |
| 154 | case "table": return enclosing(.table, context) != nil | 154 | case "table": return enclosing(.table, context) != nil |
| 155 | case "table-el": return enclosing(.tableEl, context) != nil | ||
| 155 | case "item": return enclosing(.item, context) != nil | 156 | case "item": return enclosing(.item, context) != nil |
| 156 | case "region": return context.selection.contains { !$0.isEmpty } | 157 | case "region": return context.selection.contains { !$0.isEmpty } |
| 157 | case "timestamp": return EmacsBuffer(context.text, point: context.caret).atTimestamp() != nil | 158 | case "timestamp": return EmacsBuffer(context.text, point: context.caret).atTimestamp() != nil |
Sources/OrgCore/Keymap/Presets.swift +8
| @@ -75,6 +75,14 @@ public enum KeymapPreset: String, Sendable, CaseIterable { | |||
| 75 | keys = "RET" | 75 | keys = "RET" |
| 76 | command = "org.table.next-row" | 76 | command = "org.table.next-row" |
| 77 | when = "table" | 77 | when = "table" |
| 78 | [[bind]] | ||
| 79 | keys = "TAB" | ||
| 80 | command = "org.table-el.next-cell" | ||
| 81 | when = "table-el" | ||
| 82 | [[bind]] | ||
| 83 | keys = "S-TAB" | ||
| 84 | command = "org.table-el.previous-cell" | ||
| 85 | when = "table-el" | ||
| 78 | 86 | ||
| 79 | """ | 87 | """ |
| 80 | 88 | ||
Tests/OrgCoreTests/TableElEditTests.swift added +99
| @@ -0,0 +1,99 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import OrgCore | ||
| 4 | |||
| 5 | struct TableElEditTests { | ||
| 6 | static let simple = """ | ||
| 7 | * Notes | ||
| 8 | +-----+-----+ | ||
| 9 | | a | b | | ||
| 10 | | | b2 | | ||
| 11 | +-----+-----+ | ||
| 12 | | c | d | | ||
| 13 | +-----+-----+ | ||
| 14 | |||
| 15 | """ | ||
| 16 | |||
| 17 | static let merged = """ | ||
| 18 | +-----+-----+-----+ | ||
| 19 | | a | b | | ||
| 20 | +-----+-----+-----+ | ||
| 21 | | c | d | e | | ||
| 22 | | +-----+-----+ | ||
| 23 | | | f | g | | ||
| 24 | +-----+-----+-----+ | ||
| 25 | |||
| 26 | """ | ||
| 27 | |||
| 28 | /// Carets inside cells: every character after a bar on a row line, before the next bar. | ||
| 29 | static func cellCarets(_ text: String) -> [Int] { | ||
| 30 | var carets: [Int] = [] | ||
| 31 | let ns = text as NSString | ||
| 32 | var offset = 0 | ||
| 33 | for line in text.components(separatedBy: "\n") { | ||
| 34 | let chars = Array(line) | ||
| 35 | var inside = false | ||
| 36 | var utf16 = offset | ||
| 37 | for ch in chars { | ||
| 38 | if ch == "|" || ch == "+" { inside = line.trimmingCharacters(in: .whitespaces).hasPrefix("|") } | ||
| 39 | else if inside, ch != "-" { carets.append(utf16) } | ||
| 40 | utf16 += String(ch).utf16.count | ||
| 41 | } | ||
| 42 | offset += (line as NSString).length + 1 | ||
| 43 | if offset > ns.length { break } | ||
| 44 | } | ||
| 45 | return carets | ||
| 46 | } | ||
| 47 | |||
| 48 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | ||
| 49 | func movingMatchesTableEl() throws { | ||
| 50 | var cases: [EmacsOracle.Case] = [] | ||
| 51 | var ours: [(label: String, caret: Int?)] = [] | ||
| 52 | for text in [Self.simple, Self.merged] { | ||
| 53 | for caret in Self.cellCarets(text) { | ||
| 54 | for forward in [true, false] { | ||
| 55 | cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """ | ||
| 56 | (progn (require 'table) (table-recognize-table) (\(forward ? "table-forward-cell" : "table-backward-cell") 1)) | ||
| 57 | """)) | ||
| 58 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) | ||
| 59 | var mine: Int? | ||
| 60 | if case .commit(let result) = TableElMoveCell(forward: forward).run(in: context), result.edits.isEmpty { mine = result.selection?.first?.lowerBound } | ||
| 61 | ours.append(("\(forward ? "forward" : "backward") from \(caret)", mine)) | ||
| 62 | } | ||
| 63 | } | ||
| 64 | } | ||
| 65 | let results = try EmacsOracle.run(cases) | ||
| 66 | var mismatches = 0 | ||
| 67 | for ((label, mine), theirs) in zip(ours, results) { | ||
| 68 | let theirCaret = theirs.text.unicodeScalars.prefix(theirs.point - 1).reduce(0) { $0 + $1.utf16.count } | ||
| 69 | if mine != theirCaret || !theirs.error.isEmpty { | ||
| 70 | mismatches += 1 | ||
| 71 | if mismatches <= 10 { Issue.record("\(label): ours \(mine.map(String.init) ?? "none") emacs \(theirCaret) \(theirs.error)") } | ||
| 72 | } | ||
| 73 | } | ||
| 74 | #expect(mismatches == 0, "\(mismatches) of \(cases.count) differ") | ||
| 75 | } | ||
| 76 | |||
| 77 | @Test func aligningAfterTyping() { | ||
| 78 | let typed = " +-----+-----+\n | abcXY | d |\n +-----+-----+\n | e| f |\n +-----+-----+\n" | ||
| 79 | let caret = (typed as NSString).range(of: "XY").location + 2 | ||
| 80 | let context = EditContext(revision: 0, text: typed, tree: OrgParser.parse(typed), selection: [caret..<caret]) | ||
| 81 | guard case .commit(let result) = TableElAlign().run(in: context) else { Issue.record("not aligned"); return } | ||
| 82 | let new = result.edits.reduce(typed) { $1.apply(to: $0) } | ||
| 83 | #expect(new == " +------+-----+\n | abcXY| d |\n +------+-----+\n | e | f |\n +------+-----+\n") | ||
| 84 | // The caret stays after the typed text. | ||
| 85 | #expect(result.selection?.first?.lowerBound == (new as NSString).range(of: "XY").location + 2) | ||
| 86 | // TAB lines the borders up first, then goes on to the next cell. | ||
| 87 | guard case .commit(let tab) = TableElMoveCell(forward: true).run(in: context) else { Issue.record("no move"); return } | ||
| 88 | let tabbed = tab.edits.reduce(typed) { $1.apply(to: $0) } | ||
| 89 | #expect(tabbed == new) | ||
| 90 | #expect(tab.selection?.first?.lowerBound == (new as NSString).range(of: " d").location) | ||
| 91 | } | ||
| 92 | |||
| 93 | @Test func mergedCellsArentAligned() { | ||
| 94 | let caret = (Self.merged as NSString).range(of: "d").location | ||
| 95 | let context = EditContext(revision: 0, text: Self.merged, tree: OrgParser.parse(Self.merged), selection: [caret..<caret]) | ||
| 96 | #expect(TableElAlign().run(in: context) == .failed("Can't align a table.el table with merged cells")) | ||
| 97 | #expect(KeyContext.holds("table-el", in: context)) | ||
| 98 | } | ||
| 99 | } | ||
docs/manual/guide/03-keys.org +3
| @@ -932,6 +932,9 @@ When a key appears in several rows, it runs the command whose condition holds at | |||
| 932 | | Recalculate Table Row (=org.table.recalc=) | =C-c *= | =⌃⌘*= | — | In a table, recalculates the current row (=org-table-recalculate=). On a US keyboard, =⌃⌘*= is typed =⌃⇧⌘8=. | | 932 | | Recalculate Table Row (=org.table.recalc=) | =C-c *= | =⌃⌘*= | — | In a table, recalculates the current row (=org-table-recalculate=). On a US keyboard, =⌃⌘*= is typed =⌃⇧⌘8=. | |
| 933 | | Recalculate Table (=org.table.recalc-all=) | =C-c C-c=, =C-u C-c *= | =⌃⌘X= | =SPC m b r= (N) | Recalculates the whole table; =C-c C-c= and =⌃⌘X= run it on a =#+TBLFM= line (=org-table-recalculate= with =C-u=). | | 933 | | Recalculate Table (=org.table.recalc-all=) | =C-c C-c=, =C-u C-c *= | =⌃⌘X= | =SPC m b r= (N) | Recalculates the whole table; =C-c C-c= and =⌃⌘X= run it on a =#+TBLFM= line (=org-table-recalculate= with =C-u=). | |
| 934 | | Iterate Table Formulas (=org.table.iterate=) | =C-u C-u C-c *= | — | — | Recalculates the whole table until it stops changing, at most ten times (=org-table-iterate=). | | 934 | | Iterate Table Formulas (=org.table.iterate=) | =C-u C-u C-c *= | — | — | Recalculates the whole table until it stops changing, at most ten times (=org-table-iterate=). | |
| 935 | | Next table.el Cell (=org.table-el.next-cell=) | =TAB= | =⇥= | =TAB= | In a table.el table, lines up its borders and moves to the next cell (=table-forward-cell=). | | ||
| 936 | | Previous table.el Cell (=org.table-el.previous-cell=) | =S-TAB= | =⇧⇥= | =S-TAB= | The same, to the previous cell (=table-backward-cell=). | | ||
| 937 | | Align table.el Table (=org.table-el.align=) | =C-c C-c= | =⌃⌘X= | =C-c C-c= | In a table.el table, lines up its borders. | | ||
| 935 | | Set Column Formula (=org.table.column-formula=) | ~C-c =~ | — | — | Asks for the column's formula, offering the stored one (=org-table-eval-formula=). | | 938 | | Set Column Formula (=org.table.column-formula=) | ~C-c =~ | — | — | Asks for the column's formula, offering the stored one (=org-table-eval-formula=). | |
| 936 | | Edit Table Field (=org.table.edit-field=) | =C-c `= | — | — | In a table, edits the field in a separate editor (=org-table-edit-field=). | | 939 | | Edit Table Field (=org.table.edit-field=) | =C-c `= | — | — | In a table, edits the field in a separate editor (=org-table-edit-field=). | |
| 937 | | Shrink or Expand Table Column (=org.table.toggle-column-width=) | =C-c TAB= | — | — | In a table, shrinks or expands the column (=org-table-toggle-column-width=). | | 940 | | Shrink or Expand Table Column (=org.table.toggle-column-width=) | =C-c TAB= | — | — | In a table, shrinks or expands the column (=org-table-toggle-column-width=). | |
docs/manual/guide/10-tables.org +13 −2
| @@ -566,8 +566,19 @@ them, are recognized and kept as written: | |||
| 566 | +-------+-------+ | 566 | +-------+-------+ |
| 567 | #+END_SRC | 567 | #+END_SRC |
| 568 | 568 | ||
| 569 | orgstar doesn't edit them as tables: =TAB=, alignment and formulas don't apply. HTML | 569 | Edit the text in the cells as usual. =TAB= and =S-TAB= line the borders up, then move to |
| 570 | export renders them as tables, with cells that span rows and columns, and Markdown | 570 | the next or previous cell, wrapping around at the ends of the table, as table.el's |
| 571 | =table-forward-cell= and =table-backward-cell= do; the caret goes to the cell's first | ||
| 572 | character. =C-c C-c= (Mac =⌃⌘X=) lines the borders up without moving. Lining up makes | ||
| 573 | each column as wide as its widest text, and never narrower than its rules: text typed | ||
| 574 | into a cell uses up the spaces at its end first, as table.el does when you type. | ||
| 575 | |||
| 576 | Org edits table.el tables in table.el's own buffer, with =C-c '=, and says so for =TAB= | ||
| 577 | and =C-c C-c=; orgstar does the editing in place instead. Tables with merged cells, which | ||
| 578 | span rows or columns, can be moved through but not lined up ("Can't align a table.el | ||
| 579 | table with merged cells"). Formulas, sorting and the other table commands don't apply. | ||
| 580 | |||
| 581 | HTML export renders them as tables, with cells that span rows and columns, and Markdown | ||
| 571 | export writes them as a code block. See [[file:12-export.org][Export]]. | 582 | export writes them as a code block. See [[file:12-export.org][Export]]. |
| 572 | 583 | ||
| 573 | * Plotting | 584 | * Plotting |