Sources/OrgCore/Keymap/VimObjects.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Keymap/VimObjects.swift history · blame · raw

149 lines · 7211 bytes

7 symbols in this file
  1import Foundation
  2
  3// Sentences (`(`, `)`, `is`, `as`) and XML tags (`it`, `at`).
  4
  5extension Vim.Buffer {
  6    /// `sentence-end` with Doom's `sentence-end-double-space` off, and the blanks after it.
  7    private static let sentenceEnd = try! NSRegularExpression(pattern: "[.?!…‽][\\]\"'”’)}»›]*(?:$|[ \\t])[ \\t\\n]*", options: .anchorsMatchLines)
  8    private static let orgParagraphStart = try! NSRegularExpression(pattern: "^(?:\\*+ |[ \\t]*(?:[-+]|[0-9]+[.)])(?: |$)|[ \\t]+\\* )")
  9
 10    private func isBlankLine(_ line: Int) -> Bool {
 11        (line..<lineEnd(line)).allSatisfy { Self.isBlank(char($0)!) }
 12    }
 13
 14    /// Each line's start.
 15    private var lineStarts: [Int] {
 16        var lines = [0]
 17        var p = 0
 18        while p < length {
 19            if char(p) == 10, p + 1 < length { lines.append(p + 1) }
 20            p += 1
 21        }
 22        return lines
 23    }
 24
 25    /// Where sentences begin, in order: after a sentence's end and at the start of a
 26    /// paragraph's text. Blank lines separate paragraphs; in Org, headings and list items
 27    /// start one too.
 28    func sentenceStarts(org: Bool) -> [Int] {
 29        var all: Set<Int> = []
 30        var previousSeparates = true
 31        for line in lineStarts {
 32            let text = substring(line..<lineEnd(line))
 33            let special = org && Self.orgParagraphStart.firstMatch(in: text, range: NSRange(location: 0, length: (text as NSString).length)) != nil
 34            if isBlankLine(line) {
 35                previousSeparates = true
 36                continue
 37            }
 38            if previousSeparates || special { all.insert(firstNonBlankOrEnd(line)) }
 39            previousSeparates = org && text.hasPrefix("*") && special
 40        }
 41        for match in Self.sentenceEnd.matches(in: ns as String, range: NSRange(location: 0, length: length)) where NSMaxRange(match.range) < length {
 42            all.insert(NSMaxRange(match.range))
 43        }
 44        return all.sorted()
 45    }
 46
 47    /// `)` and `(`: the next sentence's beginning or the blank line after the paragraph; the
 48    /// previous sentence's beginning or the blank line before the paragraph.
 49    func sentence(_ c: Int, forward: Bool, org: Bool) -> Int {
 50        let starts = sentenceStarts(org: org)
 51        let lines = lineStarts
 52        if forward {
 53            var target = starts.first { $0 > c } ?? length
 54            for (i, line) in lines.enumerated() where line > c && line < target && i > 0 && isBlankLine(line) && !isBlankLine(lines[i - 1]) {
 55                target = line
 56                break
 57            }
 58            return target
 59        }
 60        var target = starts.last { $0 < c } ?? 0
 61        for (i, line) in lines.enumerated().reversed() where line < c && line > target && i + 1 < lines.count && isBlankLine(line) && !isBlankLine(lines[i + 1]) {
 62            target = line
 63            break
 64        }
 65        return target
 66    }
 67
 68    /// `is` and `as`: sentences and the blanks between them count alike for `is`; `as` takes a
 69    /// sentence with the blanks after it on its line, or else the blanks before it on its
 70    /// line, and on blanks takes them with the sentence after.
 71    func sentenceObject(_ c: Int, inner: Bool, count: Int, org: Bool) -> Range<Int>? {
 72        let starts = sentenceStarts(org: org)
 73        guard c < length, !starts.isEmpty else { return nil }
 74        // Each sentence's text, without the blanks after it.
 75        var sentences: [Range<Int>] = []
 76        for (i, start) in starts.enumerated() {
 77            var end = i + 1 < starts.count ? starts[i + 1] : length
 78            while end > start, let ch = char(end - 1), Self.isSpace(ch) { end -= 1 }
 79            sentences.append(start..<end)
 80        }
 81        let n = max(1, count)
 82        let index = sentences.firstIndex { $0.contains(c) }
 83        if inner {
 84            // Sentences and gaps in order.
 85            var bounds = [0]
 86            for s in sentences { bounds += [s.lowerBound, s.upperBound] }
 87            bounds.append(length)
 88            let segments = zip(bounds, bounds.dropFirst()).filter { $0 < $1 }.map { $0..<$1 }
 89            guard let first = segments.firstIndex(where: { $0.contains(c) }) else { return nil }
 90            return segments[first].lowerBound..<segments[min(segments.count - 1, first + n - 1)].upperBound
 91        }
 92        func nextStart(_ i: Int) -> Int { i + 1 < sentences.count ? sentences[i + 1].lowerBound : length }
 93        var lower: Int
 94        var last: Int
 95        // Whether the range ends with the blanks after `last`.
 96        var blanksAfter = false
 97        if let index {
 98            last = index
 99            lower = sentences[index].lowerBound
100            let end = sentences[index].upperBound
101            let before = max(index > 0 ? sentences[index - 1].upperBound : 0, lineStart(lower))
102            if min(nextStart(index), lineEnd(end)) > end {
103                blanksAfter = true
104                if n == 1 { return lower..<min(nextStart(index), lineEnd(end)) }
105            } else if before < lower {
106                lower = before
107            }
108        } else {
109            guard let next = sentences.firstIndex(where: { $0.lowerBound > c }) else { return nil }
110            lower = next > 0 ? sentences[next - 1].upperBound : 0
111            last = next
112        }
113        for _ in 1..<n where last + 1 < sentences.count {
114            last += 1
115            if blanksAfter { blanksAfter = nextStart(last) > sentences[last].upperBound }
116        }
117        return lower..<(blanksAfter ? nextStart(last) : sentences[last].upperBound)
118    }
119
120    private static let tag = try! NSRegularExpression(pattern: "<(/?)([^\\s<>/]+)(?:\\s[^<>]*?)?(/?)>")
121
122    /// `it` and `at`: the `count`th pair of XML tags around `c`, a tag itself counting as inside
123    /// its pair; `inner` is the text between them.
124    func tagObject(_ c: Int, inner: Bool, count: Int) -> Range<Int>? {
125        var open: [(name: String, range: NSRange)] = []
126        var pairs: [(open: NSRange, close: NSRange)] = []
127        for match in Self.tag.matches(in: ns as String, range: NSRange(location: 0, length: length)) {
128            guard match.range(at: 3).length == 0 else { continue }
129            let name = ns.substring(with: match.range(at: 2))
130            if match.range(at: 1).length == 0 {
131                open.append((name, match.range))
132            } else if let i = open.lastIndex(where: { $0.name == name }) {
133                pairs.append((open[i].range, match.range))
134                open.removeSubrange(i...)
135            }
136        }
137        // Innermost first.
138        let around = pairs.filter { $0.open.location <= c && c < NSMaxRange($0.close) }.sorted { $0.open.location > $1.open.location }
139        guard around.count >= max(1, count) else { return nil }
140        let pair = around[max(1, count) - 1]
141        return inner ? NSMaxRange(pair.open)..<pair.close.location : pair.open.location..<NSMaxRange(pair.close)
142    }
143
144    /// Whether `range` is every character of two or more lines, which makes `at` take the lines.
145    func coversLines(_ range: Range<Int>) -> Bool {
146        range.lowerBound == lineStart(range.lowerBound) && range.upperBound == lineEnd(range.upperBound)
147            && lineStart(range.upperBound) > range.lowerBound
148    }
149}