Sources/OrgCore/Commands/OrgListIndent.swift

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

328 lines · 15601 bytes

  1import Foundation
  2
  3extension EmacsBuffer {
  4    // MARK: - Indentation changes
  5
  6    /// `org-list-struct-outdent`.
  7    func structOutdent(_ start: Int, _ end: Int, _ structure: ListStruct, _ parents: [(item: Int, parent: Int?)]) throws -> [(item: Int, parent: Int?)] {
  8        var acc: [Int: Int] = [:]
  9        return try parents.map { cell in
 10            let (item, parent) = cell
 11            if item < start { return cell }
 12            if item >= end {
 13                if let parent, let convert = acc[parent] { return (item, convert) }
 14                return cell
 15            }
 16            guard let parent else { throw UserError(message: "Cannot outdent top-level items") }
 17            if parent >= start {
 18                acc[parent] = item
 19                return cell
 20            }
 21            acc[parent] = item
 22            return (item, structure.parent(parent, parents))
 23        }
 24    }
 25
 26    /// `org-list-struct-indent`.
 27    func structIndent(_ start: Int, _ end: Int, _ structure: ListStruct, _ parents: [(item: Int, parent: Int?)], _ prevs: [Int: Int]) throws -> [(item: Int, parent: Int?)] {
 28        var acc: [(item: Int, parent: Int?)] = []
 29        func remember(_ cell: (item: Int, parent: Int?)) -> (item: Int, parent: Int?) {
 30            acc.insert(cell, at: 0)
 31            return cell
 32        }
 33        return try parents.map { cell in
 34            let (item, parent) = cell
 35            if item < start { return cell }
 36            if item >= end {
 37                if let convert = acc.first(where: { $0.item == parent }) { return (item, convert.parent) }
 38                return cell
 39            }
 40            let previous = structure.previousItem(item, prevs)
 41            guard let previous else {
 42                if parent == nil || parent! < start { throw UserError(message: "Cannot indent the first item of a list") }
 43                return remember(cell)
 44            }
 45            if previous < start { return remember((item, previous)) }
 46            return remember((item, acc.first { $0.item == previous }?.parent ?? nil))
 47        }
 48    }
 49
 50    // MARK: - Repairs
 51
 52    /// Records a successful `string-match' on a string in the match data.
 53    private func stringMatched(_ string: String, _ range: Range<String.Index>) {
 54        let start = string.utf16.distance(from: string.startIndex, to: range.lowerBound)
 55        lastMatch = [start..<(start + string[range].utf16.count)]
 56    }
 57
 58    /// `org-list-inc-bullet-maybe`.
 59    func incrementBullet(_ bullet: String) -> String {
 60        if let range = bullet.range(of: "[0-9]+", options: .regularExpression) {
 61            stringMatched(bullet, range)
 62            return bullet.replacingCharacters(in: range, with: String(Int(bullet[range])! + 1))
 63        }
 64        if let range = bullet.range(of: "[A-Za-z]", options: .regularExpression) {
 65            stringMatched(bullet, range)
 66            let scalar = bullet[range].unicodeScalars.first!.value + 1
 67            return bullet.replacingCharacters(in: range, with: String(Character(Unicode.Scalar(scalar)!)))
 68        }
 69        return bullet
 70    }
 71
 72    /// `org-list-struct-fix-bul` (alphabetical bullets off).
 73    func fixBullets(_ structure: inout ListStruct, _ prevs: [Int: Int]) {
 74        func find(_ pattern: String, _ string: String) -> Range<String.Index>? {
 75            guard let range = string.range(of: pattern, options: .regularExpression) else { return nil }
 76            stringMatched(string, range)
 77            return range
 78        }
 79        for pos in structure.map(\.pos) {
 80            let previous = prevs[pos]
 81            let counter = structure.item(pos)!.counter
 82            let bullet = structure.bullet(pos)
 83            let previousBullet = previous.map { structure.bullet($0) }
 84            let alphap = previous == nil && useAlphabeticalBullets(pos, structure, prevs)
 85            let new: String
 86            if previous != nil, let counter, let previousBullet, find("[a-zA-Z]", counter) != nil, find("[a-zA-Z]", previousBullet) != nil {
 87                let lower = find("[a-z]", previousBullet)
 88                let range = lower ?? find("[A-Z]", previousBullet)!
 89                new = previousBullet.replacingCharacters(in: range, with: lower != nil ? counter.lowercased() : counter.uppercased())
 90            } else if previous != nil, let counter, let previousBullet, let counterRange = find("[0-9]+", counter),
 91                      let range = find("[0-9]+", previousBullet) {
 92                new = previousBullet.replacingCharacters(in: range, with: counter[counterRange])
 93            } else if let previousBullet {
 94                new = incrementBullet(previousBullet)
 95            } else if let counter, useAlphabeticalBullets(pos, structure, prevs), find("[A-Za-z]", counter) != nil, find("[A-Za-z]", bullet) != nil {
 96                let lower = find("[a-z]", bullet)
 97                let range = lower ?? find("[A-Z]", bullet)!
 98                new = bullet.replacingCharacters(in: range, with: lower != nil ? counter.lowercased() : counter.uppercased())
 99            } else if let counter, let counterRange = find("[0-9]+", counter), let range = find("[0-9]+", bullet) {
100                new = bullet.replacingCharacters(in: range, with: counter[counterRange])
101            } else if alphap, let range = find("[A-Z]", bullet) {
102                new = bullet.replacingCharacters(in: range, with: "A")
103            } else if alphap, let range = find("[a-z]", bullet) {
104                new = bullet.replacingCharacters(in: range, with: "a")
105            } else if let range = find("([0-9]+|[A-Za-z])", bullet) {
106                new = bullet.replacingCharacters(in: range, with: "1")
107            } else {
108                new = bullet
109            }
110            structure.set(pos) { $0.bullet = bulletString(new) }
111        }
112    }
113
114    /// `org-list-use-alpha-bul-p`: the list starting at `first` fits in the alphabet.
115    func useAlphabeticalBullets(_ first: Int, _ structure: ListStruct, _ prevs: [Int: Int]) -> Bool {
116        guard options.listAllowAlphabetical else { return false }
117        var item: Int? = first
118        var ascii = 64
119        while let current = item {
120            if let counter = structure.item(current)?.counter, let letter = counter.first, letter.isASCII, letter.isLetter {
121                ascii = Int(letter.uppercased().unicodeScalars.first!.value)
122            } else {
123                ascii += 1
124            }
125            if ascii > 90 { return false }
126            item = structure.nextItem(current, prevs)
127        }
128        return true
129    }
130
131    /// `org-list-struct-fix-ind`.
132    func fixIndentation(_ structure: inout ListStruct, _ parents: [(item: Int, parent: Int?)], bulletSize: Int? = nil) {
133        let topInd = structure.ind(structure.top)
134        for pos in structure.dropFirst().map(\.pos) {
135            if let parent = structure.parent(pos, parents) {
136                let ind = (bulletSize ?? (structure.bullet(parent) as NSString).length) + structure.ind(parent)
137                structure.set(pos) { $0.ind = ind }
138            } else {
139                structure.set(pos) { $0.ind = topInd }
140            }
141        }
142    }
143
144    /// `org-list-struct-fix-box` without ORDERED.
145    func fixCheckboxes(_ structure: inout ListStruct, _ parents: [(item: Int, parent: Int?)]) {
146        var parentList: [Int] = []
147        for pos in structure.map(\.pos) {
148            guard let parent = structure.parent(pos, parents), structure.checkbox(parent) != nil, !parentList.contains(parent) else { continue }
149            parentList.insert(parent, at: 0)
150        }
151        // `sort` in Emacs is stable; ties keep their order.
152        let ordered = parentList.enumerated().sorted { lhs, rhs in
153            let (a, b) = (structure.ind(lhs.element), structure.ind(rhs.element))
154            return a != b ? a > b : lhs.offset < rhs.offset
155        }.map(\.element)
156        for item in ordered {
157            let boxes = structure.children(item, parents).map { structure.checkbox($0) }
158            let new: String?
159            if boxes.contains("[ ]"), boxes.contains("[X]") {
160                new = "[-]"
161            } else if boxes.contains("[-]") {
162                new = "[-]"
163            } else if boxes.contains("[X]") {
164                new = "[X]"
165            } else if boxes.contains("[ ]") {
166                new = "[ ]"
167            } else {
168                new = structure.checkbox(item)
169            }
170            structure.set(item) { $0.checkbox = new }
171        }
172    }
173
174    /// `org-list-struct-fix-item-end`.
175    func fixItemEnds(_ structure: inout ListStruct) {
176        var endList: [(ind: Int, pos: Int)] = []
177        var accEnd: [(end: Int, pos: Int)] = []
178        for item in structure {
179            if structure.item(item.end) == nil {
180                let up = accEnd.first { item.end < $0.end }?.pos
181                endList.insert((up.map { structure.ind($0) + 2 } ?? 0, item.end), at: 0)
182            }
183            endList.insert((item.ind, item.pos), at: 0)
184            accEnd.insert((item.end, item.pos), at: 0)
185        }
186        let sorted = endList.enumerated().sorted { $0.element.pos != $1.element.pos ? $0.element.pos < $1.element.pos : $0.offset < $1.offset }.map(\.element)
187        assocEnd(&structure, sorted)
188    }
189
190    /// The previous match data, with groups it lacks as unmatched.
191    private var staleMatch: [Range<Int>?] {
192        lastMatch + Array(repeating: nil, count: max(0, 6 - lastMatch.count))
193    }
194
195    /// `org-list-struct-apply-struct`.
196    func applyStruct(_ structure: ListStruct, _ old: ListStruct) {
197        let origin = marker(point)
198        defer {
199            point = origin.position
200            release(origin)
201        }
202        func shiftBody(end: Int, begin: Int, delta: Int, ind: Int?) {
203            point = end
204            skipBackward(Self.whitespace)
205            beginningOfLine()
206            while point > begin || (point == begin && looking(itemPattern) == nil) {
207                if looking("^[ \\t]*\\S", setsMatch: false) != nil {
208                    indentLineTo(max(currentTextIndentation + delta, ind.map { $0 + 1 } ?? -1))
209                }
210                if point == 0 { break }
211                forwardLine(-1)
212            }
213        }
214        func modify(_ item: Int) {
215            point = item
216            let newInd = structure.ind(item)
217            let oldInd = currentTextIndentation
218            let newBullet = bulletString(structure.bullet(item))
219            let oldBullet = old.bullet(item)
220            let newBox = structure.checkbox(item)
221            // A failed `looking-at' leaves the previous match data, which org then uses; this
222            // happens when a split item takes a sub-list with it.
223            var match = looking(Self.fullItemPattern) ?? staleMatch
224            if oldBullet != newBullet {
225                var keepSpace = ""
226                saveExcursion {
227                    let bulletRange = match[1]!
228                    if bulletRange.lowerBound <= origin.position, origin.position <= bulletRange.upperBound {
229                        let spaces = saveExcursion { () -> String? in
230                            point = origin.position
231                            return looking("[ \\t]+", setsMatch: false).map { substring($0[0]!.lowerBound, $0[0]!.upperBound) }
232                        }
233                        keepSpace = spaces ?? ""
234                    }
235                    replace(bulletRange, with: "")
236                    point = bulletRange.lowerBound
237                    insertBeforeMarkers(newBullet)
238                    insert(keepSpace)
239                }
240            }
241            point = item
242            match = looking(Self.fullItemPattern) ?? staleMatch
243            let oldBox = match[3].map { substring($0.lowerBound, $0.upperBound) }
244            if oldBox == newBox {
245            } else if let boxRange = match[3], let newBox {
246                replace(boxRange, with: newBox)
247            } else if oldBox != nil {
248                let box = looking(".*?([ \\t]*\\[[ X-]\\])")!
249                replace(box[1]!, with: "")
250            } else if let newBox {
251                let counterEnd = match[2]?.upperBound
252                point = counterEnd.map { $0 + 1 } ?? match[1]!.upperBound
253                insert(newBox + (counterEnd == nil ? " " : ""))
254            }
255            if newInd != oldInd {
256                point = lineStart(point)
257                let start = point
258                skipForward(Self.blanks)
259                deleteRegion(start, point)
260                indentTo(newInd)
261            }
262        }
263        var endList: [(end: Int, up: Int?)] = []
264        var accEnd: [(end: Int, pos: Int)] = []
265        var shifts: [Int: (delta: Int, ind: Int)] = [:]
266        for entry in old {
267            let pos = entry.pos
268            let indNew = structure.ind(pos), indOld = entry.ind
269            let delta = (indNew + (structure.bullet(pos) as NSString).length) - (indOld + (entry.bullet as NSString).length)
270            shifts[pos] = (delta, indNew)
271            if old.item(entry.end) == nil {
272                endList.insert((entry.end, accEnd.first { entry.end < $0.end }?.pos), at: 0)
273            }
274            accEnd.insert((entry.end, pos), at: 0)
275        }
276        var uniqueEnds: [Int] = []
277        for end in endList.map(\.end) where !uniqueEnds.contains(end) { uniqueEnds.append(end) }
278        var allEnds = (old.map(\.pos) + uniqueEnds).sorted()
279        accEnd.reverse()
280        var slices: [(down: Int, up: Int, delta: Int, ind: Int?)] = []
281        while allEnds.count > 1 {
282            let up = allEnds.removeFirst()
283            let down = allEnds[0]
284            let isItem = structure.item(up) != nil
285            let delta: Int
286            if isItem {
287                delta = shifts[up]!.delta
288            } else {
289                let child = accEnd.first { $0.end == up }!.pos
290                let ind = structure.ind(child)
291                var minInd = Int.max
292                saveExcursion {
293                    point = up
294                    while point < down {
295                        if looking("[ \\t]*$", setsMatch: false) == nil {
296                            minInd = min(currentTextIndentation, minInd)
297                            if let open = looking("#\\+BEGIN(:|_\\S+)") {
298                                let name = NSRegularExpression.escapedPattern(for: substring(open[1]!.lowerBound, open[1]!.upperBound))
299                                searchForward("^[ \\t]*#\\+END\(name)[ \\t]*$", bound: down)
300                            } else if looking(Self.drawerPattern) != nil {
301                                searchForward("^[ \\t]*:END:[ \\t]*$", bound: down)
302                            }
303                        }
304                        if forwardLine(1) != 0 { break }
305                    }
306                }
307                delta = ind - minInd
308            }
309            slices.insert((down, up, delta, isItem ? shifts[up]!.ind : nil), at: 0)
310        }
311        for slice in slices {
312            if slice.delta != 0 { shiftBody(end: slice.down, begin: slice.up, delta: slice.delta, ind: slice.ind) }
313            if let cell = structure.item(slice.up), cell != old.item(slice.up) { modify(slice.up) }
314        }
315    }
316
317    /// `org-list-write-struct`.
318    func writeStruct(_ structure: inout ListStruct, _ parents: [(item: Int, parent: Int?)], old: ListStruct? = nil) {
319        let old = old ?? structure
320        fixIndentation(&structure, parents, bulletSize: 2)
321        fixItemEnds(&structure)
322        let prevs = structure.prevs
323        fixBullets(&structure, prevs)
324        fixIndentation(&structure, parents)
325        fixCheckboxes(&structure, parents)
326        applyStruct(structure, old)
327    }
328}