Commit 1777d5c05f
Verified · cmc
Layout: unified · split
Sources/OrgCore/Commands/OrgList.swift +1 −326
| @@ -133,7 +133,7 @@ extension ListStruct { | |||
| 133 | } | 133 | } |
| 134 | 134 | ||
| 135 | /// `org-list-struct-assoc-end`: gives each item the first ending at its indentation or less. | 135 | /// `org-list-struct-assoc-end`: gives each item the first ending at its indentation or less. |
| 136 | private func assocEnd(_ structure: inout ListStruct, _ endList: [(ind: Int, pos: Int)]) { | 136 | func assocEnd(_ structure: inout ListStruct, _ endList: [(ind: Int, pos: Int)]) { |
| 137 | var endings = endList[...] | 137 | var endings = endList[...] |
| 138 | for i in structure.indices { | 138 | for i in structure.indices { |
| 139 | let item = structure[i] | 139 | let item = structure[i] |
| @@ -681,329 +681,4 @@ extension EmacsBuffer { | |||
| 681 | result = (result + copies).sorted { $0.pos < $1.pos } | 681 | result = (result + copies).sorted { $0.pos < $1.pos } |
| 682 | return deleteItem(itemMarker.position, result) | 682 | return deleteItem(itemMarker.position, result) |
| 683 | } | 683 | } |
| 684 | |||
| 685 | // MARK: - Indentation changes | ||
| 686 | |||
| 687 | /// `org-list-struct-outdent`. | ||
| 688 | func structOutdent(_ start: Int, _ end: Int, _ structure: ListStruct, _ parents: [(item: Int, parent: Int?)]) throws -> [(item: Int, parent: Int?)] { | ||
| 689 | var acc: [Int: Int] = [:] | ||
| 690 | return try parents.map { cell in | ||
| 691 | let (item, parent) = cell | ||
| 692 | if item < start { return cell } | ||
| 693 | if item >= end { | ||
| 694 | if let parent, let convert = acc[parent] { return (item, convert) } | ||
| 695 | return cell | ||
| 696 | } | ||
| 697 | guard let parent else { throw UserError(message: "Cannot outdent top-level items") } | ||
| 698 | if parent >= start { | ||
| 699 | acc[parent] = item | ||
| 700 | return cell | ||
| 701 | } | ||
| 702 | acc[parent] = item | ||
| 703 | return (item, structure.parent(parent, parents)) | ||
| 704 | } | ||
| 705 | } | ||
| 706 | |||
| 707 | /// `org-list-struct-indent`. | ||
| 708 | func structIndent(_ start: Int, _ end: Int, _ structure: ListStruct, _ parents: [(item: Int, parent: Int?)], _ prevs: [Int: Int]) throws -> [(item: Int, parent: Int?)] { | ||
| 709 | var acc: [(item: Int, parent: Int?)] = [] | ||
| 710 | func remember(_ cell: (item: Int, parent: Int?)) -> (item: Int, parent: Int?) { | ||
| 711 | acc.insert(cell, at: 0) | ||
| 712 | return cell | ||
| 713 | } | ||
| 714 | return try parents.map { cell in | ||
| 715 | let (item, parent) = cell | ||
| 716 | if item < start { return cell } | ||
| 717 | if item >= end { | ||
| 718 | if let convert = acc.first(where: { $0.item == parent }) { return (item, convert.parent) } | ||
| 719 | return cell | ||
| 720 | } | ||
| 721 | let previous = structure.previousItem(item, prevs) | ||
| 722 | guard let previous else { | ||
| 723 | if parent == nil || parent! < start { throw UserError(message: "Cannot indent the first item of a list") } | ||
| 724 | return remember(cell) | ||
| 725 | } | ||
| 726 | if previous < start { return remember((item, previous)) } | ||
| 727 | return remember((item, acc.first { $0.item == previous }?.parent ?? nil)) | ||
| 728 | } | ||
| 729 | } | ||
| 730 | |||
| 731 | // MARK: - Repairs | ||
| 732 | |||
| 733 | /// Records a successful `string-match' on a string in the match data. | ||
| 734 | private func stringMatched(_ string: String, _ range: Range<String.Index>) { | ||
| 735 | let start = string.utf16.distance(from: string.startIndex, to: range.lowerBound) | ||
| 736 | lastMatch = [start..<(start + string[range].utf16.count)] | ||
| 737 | } | ||
| 738 | |||
| 739 | /// `org-list-inc-bullet-maybe`. | ||
| 740 | func incrementBullet(_ bullet: String) -> String { | ||
| 741 | if let range = bullet.range(of: "[0-9]+", options: .regularExpression) { | ||
| 742 | stringMatched(bullet, range) | ||
| 743 | return bullet.replacingCharacters(in: range, with: String(Int(bullet[range])! + 1)) | ||
| 744 | } | ||
| 745 | if let range = bullet.range(of: "[A-Za-z]", options: .regularExpression) { | ||
| 746 | stringMatched(bullet, range) | ||
| 747 | let scalar = bullet[range].unicodeScalars.first!.value + 1 | ||
| 748 | return bullet.replacingCharacters(in: range, with: String(Character(Unicode.Scalar(scalar)!))) | ||
| 749 | } | ||
| 750 | return bullet | ||
| 751 | } | ||
| 752 | |||
| 753 | /// `org-list-struct-fix-bul` (alphabetical bullets off). | ||
| 754 | func fixBullets(_ structure: inout ListStruct, _ prevs: [Int: Int]) { | ||
| 755 | func find(_ pattern: String, _ string: String) -> Range<String.Index>? { | ||
| 756 | guard let range = string.range(of: pattern, options: .regularExpression) else { return nil } | ||
| 757 | stringMatched(string, range) | ||
| 758 | return range | ||
| 759 | } | ||
| 760 | for pos in structure.map(\.pos) { | ||
| 761 | let previous = prevs[pos] | ||
| 762 | let counter = structure.item(pos)!.counter | ||
| 763 | let bullet = structure.bullet(pos) | ||
| 764 | let previousBullet = previous.map { structure.bullet($0) } | ||
| 765 | let alphap = previous == nil && useAlphabeticalBullets(pos, structure, prevs) | ||
| 766 | let new: String | ||
| 767 | if previous != nil, let counter, let previousBullet, find("[a-zA-Z]", counter) != nil, find("[a-zA-Z]", previousBullet) != nil { | ||
| 768 | let lower = find("[a-z]", previousBullet) | ||
| 769 | let range = lower ?? find("[A-Z]", previousBullet)! | ||
| 770 | new = previousBullet.replacingCharacters(in: range, with: lower != nil ? counter.lowercased() : counter.uppercased()) | ||
| 771 | } else if previous != nil, let counter, let previousBullet, let counterRange = find("[0-9]+", counter), | ||
| 772 | let range = find("[0-9]+", previousBullet) { | ||
| 773 | new = previousBullet.replacingCharacters(in: range, with: counter[counterRange]) | ||
| 774 | } else if let previousBullet { | ||
| 775 | new = incrementBullet(previousBullet) | ||
| 776 | } else if let counter, useAlphabeticalBullets(pos, structure, prevs), find("[A-Za-z]", counter) != nil, find("[A-Za-z]", bullet) != nil { | ||
| 777 | let lower = find("[a-z]", bullet) | ||
| 778 | let range = lower ?? find("[A-Z]", bullet)! | ||
| 779 | new = bullet.replacingCharacters(in: range, with: lower != nil ? counter.lowercased() : counter.uppercased()) | ||
| 780 | } else if let counter, let counterRange = find("[0-9]+", counter), let range = find("[0-9]+", bullet) { | ||
| 781 | new = bullet.replacingCharacters(in: range, with: counter[counterRange]) | ||
| 782 | } else if alphap, let range = find("[A-Z]", bullet) { | ||
| 783 | new = bullet.replacingCharacters(in: range, with: "A") | ||
| 784 | } else if alphap, let range = find("[a-z]", bullet) { | ||
| 785 | new = bullet.replacingCharacters(in: range, with: "a") | ||
| 786 | } else if let range = find("([0-9]+|[A-Za-z])", bullet) { | ||
| 787 | new = bullet.replacingCharacters(in: range, with: "1") | ||
| 788 | } else { | ||
| 789 | new = bullet | ||
| 790 | } | ||
| 791 | structure.set(pos) { $0.bullet = bulletString(new) } | ||
| 792 | } | ||
| 793 | } | ||
| 794 | |||
| 795 | /// `org-list-use-alpha-bul-p`: the list starting at `first` fits in the alphabet. | ||
| 796 | func useAlphabeticalBullets(_ first: Int, _ structure: ListStruct, _ prevs: [Int: Int]) -> Bool { | ||
| 797 | guard options.listAllowAlphabetical else { return false } | ||
| 798 | var item: Int? = first | ||
| 799 | var ascii = 64 | ||
| 800 | while let current = item { | ||
| 801 | if let counter = structure.item(current)?.counter, let letter = counter.first, letter.isASCII, letter.isLetter { | ||
| 802 | ascii = Int(letter.uppercased().unicodeScalars.first!.value) | ||
| 803 | } else { | ||
| 804 | ascii += 1 | ||
| 805 | } | ||
| 806 | if ascii > 90 { return false } | ||
| 807 | item = structure.nextItem(current, prevs) | ||
| 808 | } | ||
| 809 | return true | ||
| 810 | } | ||
| 811 | |||
| 812 | /// `org-list-struct-fix-ind`. | ||
| 813 | func fixIndentation(_ structure: inout ListStruct, _ parents: [(item: Int, parent: Int?)], bulletSize: Int? = nil) { | ||
| 814 | let topInd = structure.ind(structure.top) | ||
| 815 | for pos in structure.dropFirst().map(\.pos) { | ||
| 816 | if let parent = structure.parent(pos, parents) { | ||
| 817 | let ind = (bulletSize ?? (structure.bullet(parent) as NSString).length) + structure.ind(parent) | ||
| 818 | structure.set(pos) { $0.ind = ind } | ||
| 819 | } else { | ||
| 820 | structure.set(pos) { $0.ind = topInd } | ||
| 821 | } | ||
| 822 | } | ||
| 823 | } | ||
| 824 | |||
| 825 | /// `org-list-struct-fix-box` without ORDERED. | ||
| 826 | func fixCheckboxes(_ structure: inout ListStruct, _ parents: [(item: Int, parent: Int?)]) { | ||
| 827 | var parentList: [Int] = [] | ||
| 828 | for pos in structure.map(\.pos) { | ||
| 829 | guard let parent = structure.parent(pos, parents), structure.checkbox(parent) != nil, !parentList.contains(parent) else { continue } | ||
| 830 | parentList.insert(parent, at: 0) | ||
| 831 | } | ||
| 832 | // `sort` in Emacs is stable; ties keep their order. | ||
| 833 | let ordered = parentList.enumerated().sorted { lhs, rhs in | ||
| 834 | let (a, b) = (structure.ind(lhs.element), structure.ind(rhs.element)) | ||
| 835 | return a != b ? a > b : lhs.offset < rhs.offset | ||
| 836 | }.map(\.element) | ||
| 837 | for item in ordered { | ||
| 838 | let boxes = structure.children(item, parents).map { structure.checkbox($0) } | ||
| 839 | let new: String? | ||
| 840 | if boxes.contains("[ ]"), boxes.contains("[X]") { | ||
| 841 | new = "[-]" | ||
| 842 | } else if boxes.contains("[-]") { | ||
| 843 | new = "[-]" | ||
| 844 | } else if boxes.contains("[X]") { | ||
| 845 | new = "[X]" | ||
| 846 | } else if boxes.contains("[ ]") { | ||
| 847 | new = "[ ]" | ||
| 848 | } else { | ||
| 849 | new = structure.checkbox(item) | ||
| 850 | } | ||
| 851 | structure.set(item) { $0.checkbox = new } | ||
| 852 | } | ||
| 853 | } | ||
| 854 | |||
| 855 | /// `org-list-struct-fix-item-end`. | ||
| 856 | func fixItemEnds(_ structure: inout ListStruct) { | ||
| 857 | var endList: [(ind: Int, pos: Int)] = [] | ||
| 858 | var accEnd: [(end: Int, pos: Int)] = [] | ||
| 859 | for item in structure { | ||
| 860 | if structure.item(item.end) == nil { | ||
| 861 | let up = accEnd.first { item.end < $0.end }?.pos | ||
| 862 | endList.insert((up.map { structure.ind($0) + 2 } ?? 0, item.end), at: 0) | ||
| 863 | } | ||
| 864 | endList.insert((item.ind, item.pos), at: 0) | ||
| 865 | accEnd.insert((item.end, item.pos), at: 0) | ||
| 866 | } | ||
| 867 | let sorted = endList.enumerated().sorted { $0.element.pos != $1.element.pos ? $0.element.pos < $1.element.pos : $0.offset < $1.offset }.map(\.element) | ||
| 868 | assocEnd(&structure, sorted) | ||
| 869 | } | ||
| 870 | |||
| 871 | /// The previous match data, with groups it lacks as unmatched. | ||
| 872 | private var staleMatch: [Range<Int>?] { | ||
| 873 | lastMatch + Array(repeating: nil, count: max(0, 6 - lastMatch.count)) | ||
| 874 | } | ||
| 875 | |||
| 876 | /// `org-list-struct-apply-struct`. | ||
| 877 | func applyStruct(_ structure: ListStruct, _ old: ListStruct) { | ||
| 878 | let origin = marker(point) | ||
| 879 | defer { | ||
| 880 | point = origin.position | ||
| 881 | release(origin) | ||
| 882 | } | ||
| 883 | func shiftBody(end: Int, begin: Int, delta: Int, ind: Int?) { | ||
| 884 | point = end | ||
| 885 | skipBackward(Self.whitespace) | ||
| 886 | beginningOfLine() | ||
| 887 | while point > begin || (point == begin && looking(itemPattern) == nil) { | ||
| 888 | if looking("^[ \\t]*\\S", setsMatch: false) != nil { | ||
| 889 | indentLineTo(max(currentTextIndentation + delta, ind.map { $0 + 1 } ?? -1)) | ||
| 890 | } | ||
| 891 | if point == 0 { break } | ||
| 892 | forwardLine(-1) | ||
| 893 | } | ||
| 894 | } | ||
| 895 | func modify(_ item: Int) { | ||
| 896 | point = item | ||
| 897 | let newInd = structure.ind(item) | ||
| 898 | let oldInd = currentTextIndentation | ||
| 899 | let newBullet = bulletString(structure.bullet(item)) | ||
| 900 | let oldBullet = old.bullet(item) | ||
| 901 | let newBox = structure.checkbox(item) | ||
| 902 | // A failed `looking-at' leaves the previous match data, which org then uses; this | ||
| 903 | // happens when a split item takes a sub-list with it. | ||
| 904 | var match = looking(Self.fullItemPattern) ?? staleMatch | ||
| 905 | if oldBullet != newBullet { | ||
| 906 | var keepSpace = "" | ||
| 907 | saveExcursion { | ||
| 908 | let bulletRange = match[1]! | ||
| 909 | if bulletRange.lowerBound <= origin.position, origin.position <= bulletRange.upperBound { | ||
| 910 | let spaces = saveExcursion { () -> String? in | ||
| 911 | point = origin.position | ||
| 912 | return looking("[ \\t]+", setsMatch: false).map { substring($0[0]!.lowerBound, $0[0]!.upperBound) } | ||
| 913 | } | ||
| 914 | keepSpace = spaces ?? "" | ||
| 915 | } | ||
| 916 | replace(bulletRange, with: "") | ||
| 917 | point = bulletRange.lowerBound | ||
| 918 | insertBeforeMarkers(newBullet) | ||
| 919 | insert(keepSpace) | ||
| 920 | } | ||
| 921 | } | ||
| 922 | point = item | ||
| 923 | match = looking(Self.fullItemPattern) ?? staleMatch | ||
| 924 | let oldBox = match[3].map { substring($0.lowerBound, $0.upperBound) } | ||
| 925 | if oldBox == newBox { | ||
| 926 | } else if let boxRange = match[3], let newBox { | ||
| 927 | replace(boxRange, with: newBox) | ||
| 928 | } else if oldBox != nil { | ||
| 929 | let box = looking(".*?([ \\t]*\\[[ X-]\\])")! | ||
| 930 | replace(box[1]!, with: "") | ||
| 931 | } else if let newBox { | ||
| 932 | let counterEnd = match[2]?.upperBound | ||
| 933 | point = counterEnd.map { $0 + 1 } ?? match[1]!.upperBound | ||
| 934 | insert(newBox + (counterEnd == nil ? " " : "")) | ||
| 935 | } | ||
| 936 | if newInd != oldInd { | ||
| 937 | point = lineStart(point) | ||
| 938 | let start = point | ||
| 939 | skipForward(Self.blanks) | ||
| 940 | deleteRegion(start, point) | ||
| 941 | indentTo(newInd) | ||
| 942 | } | ||
| 943 | } | ||
| 944 | var endList: [(end: Int, up: Int?)] = [] | ||
| 945 | var accEnd: [(end: Int, pos: Int)] = [] | ||
| 946 | var shifts: [Int: (delta: Int, ind: Int)] = [:] | ||
| 947 | for entry in old { | ||
| 948 | let pos = entry.pos | ||
| 949 | let indNew = structure.ind(pos), indOld = entry.ind | ||
| 950 | let delta = (indNew + (structure.bullet(pos) as NSString).length) - (indOld + (entry.bullet as NSString).length) | ||
| 951 | shifts[pos] = (delta, indNew) | ||
| 952 | if old.item(entry.end) == nil { | ||
| 953 | endList.insert((entry.end, accEnd.first { entry.end < $0.end }?.pos), at: 0) | ||
| 954 | } | ||
| 955 | accEnd.insert((entry.end, pos), at: 0) | ||
| 956 | } | ||
| 957 | var uniqueEnds: [Int] = [] | ||
| 958 | for end in endList.map(\.end) where !uniqueEnds.contains(end) { uniqueEnds.append(end) } | ||
| 959 | var allEnds = (old.map(\.pos) + uniqueEnds).sorted() | ||
| 960 | accEnd.reverse() | ||
| 961 | var slices: [(down: Int, up: Int, delta: Int, ind: Int?)] = [] | ||
| 962 | while allEnds.count > 1 { | ||
| 963 | let up = allEnds.removeFirst() | ||
| 964 | let down = allEnds[0] | ||
| 965 | let isItem = structure.item(up) != nil | ||
| 966 | let delta: Int | ||
| 967 | if isItem { | ||
| 968 | delta = shifts[up]!.delta | ||
| 969 | } else { | ||
| 970 | let child = accEnd.first { $0.end == up }!.pos | ||
| 971 | let ind = structure.ind(child) | ||
| 972 | var minInd = Int.max | ||
| 973 | saveExcursion { | ||
| 974 | point = up | ||
| 975 | while point < down { | ||
| 976 | if looking("[ \\t]*$", setsMatch: false) == nil { | ||
| 977 | minInd = min(currentTextIndentation, minInd) | ||
| 978 | if let open = looking("#\\+BEGIN(:|_\\S+)") { | ||
| 979 | let name = NSRegularExpression.escapedPattern(for: substring(open[1]!.lowerBound, open[1]!.upperBound)) | ||
| 980 | searchForward("^[ \\t]*#\\+END\(name)[ \\t]*$", bound: down) | ||
| 981 | } else if looking(Self.drawerPattern) != nil { | ||
| 982 | searchForward("^[ \\t]*:END:[ \\t]*$", bound: down) | ||
| 983 | } | ||
| 984 | } | ||
| 985 | if forwardLine(1) != 0 { break } | ||
| 986 | } | ||
| 987 | } | ||
| 988 | delta = ind - minInd | ||
| 989 | } | ||
| 990 | slices.insert((down, up, delta, isItem ? shifts[up]!.ind : nil), at: 0) | ||
| 991 | } | ||
| 992 | for slice in slices { | ||
| 993 | if slice.delta != 0 { shiftBody(end: slice.down, begin: slice.up, delta: slice.delta, ind: slice.ind) } | ||
| 994 | if let cell = structure.item(slice.up), cell != old.item(slice.up) { modify(slice.up) } | ||
| 995 | } | ||
| 996 | } | ||
| 997 | |||
| 998 | /// `org-list-write-struct`. | ||
| 999 | func writeStruct(_ structure: inout ListStruct, _ parents: [(item: Int, parent: Int?)], old: ListStruct? = nil) { | ||
| 1000 | let old = old ?? structure | ||
| 1001 | fixIndentation(&structure, parents, bulletSize: 2) | ||
| 1002 | fixItemEnds(&structure) | ||
| 1003 | let prevs = structure.prevs | ||
| 1004 | fixBullets(&structure, prevs) | ||
| 1005 | fixIndentation(&structure, parents) | ||
| 1006 | fixCheckboxes(&structure, parents) | ||
| 1007 | applyStruct(structure, old) | ||
| 1008 | } | ||
| 1009 | } | 684 | } |
Sources/OrgCore/Commands/OrgListIndent.swift added +328
| @@ -0,0 +1,328 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | extension 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 | } | ||