Sources/OrgCore/Commands/TableElCommands.swift

181 lines · 10423 bytes

  1import 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.
  8struct 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
 55extension 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.
109private 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`).
135public 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.
163public 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}