Split the Swift files over 1,000 lines !234
41 files changed, +7214 −7049
Layout: unified · split
Sources/OrgCore/Commands/OrgList.swift +1 −326
| @@ -133,7 +133,7 @@ extension ListStruct { | ||
| 133 | 133 | } |
| 134 | 134 | |
| 135 | 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 | 137 | var endings = endList[...] |
| 138 | 138 | for i in structure.indices { |
| 139 | 139 | let item = structure[i] |
| @@ -681,329 +681,4 @@ extension EmacsBuffer { | ||
| 681 | 681 | result = (result + copies).sorted { $0.pos < $1.pos } |
| 682 | 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 | } | |
Sources/OrgCore/Compute/Babel.swift −1420
| @@ -566,1426 +566,6 @@ public enum Babel { | ||
| 566 | 566 | case message(String) |
| 567 | 567 | } |
| 568 | 568 | |
| 569 | // MARK: - Noweb | |
| 570 | ||
| 571 | /// `org-babel-noweb-p` in the `:eval` context. | |
| 572 | static func nowebEvaluates(_ value: String?) -> Bool { | |
| 573 | (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "no-export", "strip-export", "eval", "strip-tangle"].contains(String($0)) } | |
| 574 | } | |
| 575 | ||
| 576 | /// `org-babel-noweb-p` for `:tangle`. | |
| 577 | static func nowebTangles(_ value: String?) -> Bool { | |
| 578 | (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "tangle", "no-export", "strip-export", "strip-tangle"].contains(String($0)) } | |
| 579 | } | |
| 580 | ||
| 581 | /// `org-babel-expand-noweb-references` for evaluation: each `<<name>>` becomes the body of | |
| 582 | /// the block named so, or of every block with that `:noweb-ref`, joined by `:noweb-sep`, or | |
| 583 | /// the contents of the heading with that ID; the text before it on its line goes before | |
| 584 | /// each line it brings. | |
| 585 | /// `tangling` expands the blocks it brings in as tangling would (`:noweb tangle`), not as | |
| 586 | /// evaluation does. | |
| 587 | /// `links` gives a block's begin and end comments, for `:comments noweb` when tangling. | |
| 588 | static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0, | |
| 589 | links: ((SrcBlockInfo, Params) throws -> (begin: String, end: String))? = nil) throws -> String { | |
| 590 | guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") } | |
| 591 | let body = normalizedBody(block) | |
| 592 | let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true | |
| 593 | let commenting = tangling && links != nil && params.single[":comments"] == "noweb" | |
| 594 | func expand(_ other: SrcBlockInfo) throws -> String { | |
| 595 | let otherParams = try Params(block: other, model: model, text: text) | |
| 596 | let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"]) | |
| 597 | let b = expands | |
| 598 | ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1, links: links) | |
| 599 | : normalizedBody(other) | |
| 600 | guard commenting, let links else { return b } | |
| 601 | // `c-wrap`: commented in this block's language, trimmed. | |
| 602 | func wrap(_ s: String) throws -> String { | |
| 603 | try Tangle.commentRegion(s, language: block.language ?? "").trimmingCharacters(in: .whitespacesAndNewlines) | |
| 604 | } | |
| 605 | var (begin, end) = try links(other.name == nil ? block : other, other.name == nil ? params : otherParams) | |
| 606 | // A `:noweb-ref` block without a name: the link is the including block's, the name empty. | |
| 607 | if other.name == nil { | |
| 608 | if let split = begin.range(of: "][") { begin = begin[..<split.lowerBound] + "][]]" } | |
| 609 | end = " ends here" | |
| 610 | } | |
| 611 | return try wrap(begin) + "\n" + b + "\n" + (try wrap(end)) + "\n" | |
| 612 | } | |
| 613 | func inCommentedHeading(_ b: SrcBlockInfo) -> Bool { | |
| 614 | guard let h = b.heading else { return false } | |
| 615 | return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") } | |
| 616 | } | |
| 617 | let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)") | |
| 618 | let ns = body as NSString | |
| 619 | var out = "" | |
| 620 | var at = 0 | |
| 621 | for m in regex.matches(in: body, range: NSRange(location: 0, length: ns.length)) { | |
| 622 | let prefix = ns.substring(with: m.range(at: 1)) | |
| 623 | let id = ns.substring(with: m.range(at: 3)) | |
| 624 | out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at)) | |
| 625 | at = NSMaxRange(m.range) | |
| 626 | var expansion = "" | |
| 627 | if id.range(of: "\\(.*\\)", options: .regularExpression) != nil { | |
| 628 | throw Failure.message("Noweb references that run a block (\(id)) aren't supported yet; nothing was run.") | |
| 629 | } else if let heading = model.headings.firstIndex(where: { h in | |
| 630 | h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) } | |
| 631 | }) { | |
| 632 | expansion = headlineBody(heading, model: model, text: text) | |
| 633 | } else if let named = model.srcBlocks.first(where: { $0.name == id }), !inCommentedHeading(named) { | |
| 634 | expansion = try expand(named) | |
| 635 | } else { | |
| 636 | var parts: [String] = [] | |
| 637 | var separators: [String] = [] | |
| 638 | for other in model.srcBlocks where !inCommentedHeading(other) { | |
| 639 | let p = try Params(block: other, model: model, text: text) | |
| 640 | guard p.single[":noweb-ref"] == id else { continue } | |
| 641 | parts.append(try expand(other)) | |
| 642 | separators.append(p.single[":noweb-sep"] ?? "\n") | |
| 643 | } | |
| 644 | for (i, part) in parts.enumerated() { | |
| 645 | if i > 0 { expansion += separators[i - 1] } | |
| 646 | expansion += part | |
| 647 | } | |
| 648 | } | |
| 649 | out += prefixing ? expansion.components(separatedBy: CharacterSet(charactersIn: "\n\r")).joined(separator: "\n" + prefix) : expansion | |
| 650 | } | |
| 651 | return out + ns.substring(from: at) | |
| 652 | } | |
| 653 | ||
| 654 | /// `org-babel-ref-headline-body`: the entry after its planning and drawers. | |
| 655 | static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String { | |
| 656 | let heading = model.headings[index] | |
| 657 | let buffer = EmacsBuffer(text as String, point: heading.headingRange.lowerBound) | |
| 658 | buffer.endOfMetaData() | |
| 659 | let start = buffer.point | |
| 660 | let end = model.headings[(index + 1)...].first.map { $0.headingRange.lowerBound } ?? text.length | |
| 661 | return start < end ? text.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) : "" | |
| 662 | } | |
| 663 | ||
| 664 | /// `org-babel--normalize-body`: without the final newline, and without the indentation | |
| 665 | /// common to its lines unless `-i` keeps it. | |
| 666 | static func normalizedBody(_ block: SrcBlockInfo) -> String { | |
| 667 | var lines = block.body.components(separatedBy: "\n") | |
| 668 | if lines.last == "" { lines.removeLast() } | |
| 669 | // Org escapes lines starting with `*` or `#+` inside blocks with a comma. | |
| 670 | lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) } | |
| 671 | if !block.switches.contains("-i") { | |
| 672 | let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count } | |
| 673 | let common = indents.min() ?? 0 | |
| 674 | lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) } | |
| 675 | } | |
| 676 | return lines.joined(separator: "\n") | |
| 677 | } | |
| 678 | ||
| 679 | // MARK: - Tables in variables | |
| 680 | ||
| 681 | /// Variables after `org-babel-disassemble-tables`, with the names taken off their tables. | |
| 682 | struct Tables { | |
| 683 | var vars: [(String, VarValue)] = [] | |
| 684 | var colnames: [(name: String, names: [Cell])] = [] | |
| 685 | var rownames: [(name: String, names: [Cell])] = [] | |
| 686 | ||
| 687 | /// `org-babel-pick-name`: a Lisp list given as the header argument, or the last | |
| 688 | /// variable's names, unless the header argument is absent, whose `nil` selects none. | |
| 689 | func picked(_ names: [(name: String, names: [Cell])], _ key: String, _ params: Params) -> [String]? { | |
| 690 | if let list = params.evaluated[key].flatMap(Babel.lispNames) { return list } | |
| 691 | guard params.single[key] != nil, let last = names.last else { return nil } | |
| 692 | return last.names.map(Babel.cellText) | |
| 693 | } | |
| 694 | } | |
| 695 | ||
| 696 | /// A Lisp list of strings and numbers, as names. | |
| 697 | static func lispNames(_ value: Sexp) -> [String]? { | |
| 698 | guard case .list(let items) = value else { return nil } | |
| 699 | return try? items.map { item in | |
| 700 | if let s = item.string { return s } | |
| 701 | let printed = Elisp.printed(item) | |
| 702 | guard number(printed) == printed else { throw Failure.message(printed) } | |
| 703 | return printed | |
| 704 | } | |
| 705 | } | |
| 706 | ||
| 707 | static func cellText(_ c: Cell) -> String { | |
| 708 | switch c { | |
| 709 | case .number(let n): n | |
| 710 | case .text(let s): s | |
| 711 | } | |
| 712 | } | |
| 713 | ||
| 714 | /// `org-babel-disassemble-tables`: a table's header row comes off when `:colnames` asks, or | |
| 715 | /// by default when only its second row is a rule; its first column with `:rownames`; its | |
| 716 | /// rules unless `:hlines yes`. | |
| 717 | static func disassemble(_ vars: [(String, VarValue)], params: Params) throws -> Tables { | |
| 718 | for key in [":colnames", ":rownames"] where params.lisp.contains(key) && params.evaluated[key].flatMap(lispNames) == nil { | |
| 719 | throw Failure.message("\(key) \(params.single[key] ?? "") is Lisp that only Emacs can evaluate; nothing was run.") | |
| 720 | } | |
| 721 | let colnames = params.single[":colnames"] | |
| 722 | let rownames = params.single[":rownames"] | |
| 723 | let hlines = params.single[":hlines"] ?? "no" | |
| 724 | var tables = Tables() | |
| 725 | for (name, value) in vars { | |
| 726 | guard case .table(var rows) = value else { | |
| 727 | tables.vars.append((name, value)) | |
| 728 | continue | |
| 729 | } | |
| 730 | let auto = rows.count > 1 && rows[0] != nil && rows[1] == nil && !rows.dropFirst(2).contains(where: { $0 == nil }) | |
| 731 | if colnames != "no", colnames != nil || auto { | |
| 732 | while let first = rows.first, first == nil { rows.removeFirst() } | |
| 733 | if let header = rows.first ?? nil { | |
| 734 | rows.removeFirst(rows.count > 1 && rows[1] == nil ? 2 : 1) | |
| 735 | tables.colnames.append((name, header)) | |
| 736 | } | |
| 737 | } | |
| 738 | if let rownames, rownames != "no" { | |
| 739 | let kept = rows.compactMap { $0 } | |
| 740 | tables.rownames.append((name, kept.map { $0.first ?? .text("") })) | |
| 741 | rows = kept.map { Array($0.dropFirst()) } | |
| 742 | } | |
| 743 | if hlines != "yes" { rows = rows.filter { $0 != nil } } | |
| 744 | tables.vars.append((name, .table(rows))) | |
| 745 | } | |
| 746 | return tables | |
| 747 | } | |
| 748 | ||
| 749 | /// `org-babel-reassemble-table` on a result. | |
| 750 | static func reassemble(_ value: Value, _ finish: BabelJob.Finish) -> Value { | |
| 751 | guard case .table(var rows) = value else { return value } | |
| 752 | if let names = finish.rownames, names.count == rows.count { | |
| 753 | var next = names.makeIterator() | |
| 754 | rows = rows.map { row in row.map { [next.next() ?? ""] + $0 } } | |
| 755 | } | |
| 756 | if let names = finish.colnames, let first = rows.first ?? nil, first.count == names.count { | |
| 757 | rows = [names, nil] + rows | |
| 758 | } | |
| 759 | return .table(rows) | |
| 760 | } | |
| 761 | ||
| 762 | /// A `:var` value that is Lisp (`org-babel-read`): evaluated, as a number, string, list or | |
| 763 | /// table. | |
| 764 | static func lispValue(_ value: String) throws -> VarValue { | |
| 765 | let refusal = Failure.message(":var value \(value) is Lisp that only Emacs can evaluate.") | |
| 766 | guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form) else { throw refusal } | |
| 767 | func cell(_ v: Sexp) throws -> Cell { | |
| 768 | if let s = v.string { return .text(s) } | |
| 769 | if let n = number(Elisp.printed(v)), Elisp.printed(v) == n { return .number(n) } | |
| 770 | throw refusal | |
| 771 | } | |
| 772 | if let s = result.string { return .scalar(s) } | |
| 773 | if case .list(let items) = result, !items.isEmpty { | |
| 774 | if items.allSatisfy({ if case .list = $0 { return true }; return $0 == .symbol("hline") }) { | |
| 775 | return .table(try items.map { item in | |
| 776 | if item == .symbol("hline") { return nil } | |
| 777 | guard case .list(let cells) = item else { throw refusal } | |
| 778 | return try cells.map(cell) | |
| 779 | }) | |
| 780 | } | |
| 781 | return .list(try items.map(cell)) | |
| 782 | } | |
| 783 | if case .number(let n) = try? cell(result) { return .number(n) } | |
| 784 | throw refusal | |
| 785 | } | |
| 786 | ||
| 787 | // MARK: - Cache | |
| 788 | ||
| 789 | /// `:cache yes` (`org-babel-execute-src-block`): the block's hash, and whether its results | |
| 790 | /// already carry it, with their value when it can be read. | |
| 791 | static func cacheState(language: String, params: Params, tables: Tables, body: String, location: Range<Int>, name: String?, | |
| 792 | call: Bool, text: NSString, options: Options, model: DocumentModel) throws -> (hash: String, current: Bool, value: VarValue?) { | |
| 793 | let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location.lowerBound } | |
| 794 | // The hash is taken outside the shell's own binding of `shell-file-name`, so its | |
| 795 | // variables are written for the user's shell whatever the block's language. | |
| 796 | let expanded = try languageExpansion(body, language: language, tables: tables, params: params, | |
| 797 | properties: { inheritedProperty($0, heading: heading, model: model) }) | |
| 798 | ?? expandedBody(language: language, vars: tables.vars, body: body, shell: options.shell, params: params) | |
| 799 | let input = try cacheInput(language: language, params: params, tables: tables, expanded: expanded, call: call) | |
| 800 | let hash = Insecure.SHA1.hash(data: Data(input.utf8)).map { String(format: "%02x", $0) }.joined() | |
| 801 | guard let line = existingResults(name: name, block: location, text: text), resultsHash(at: line, text: text) == hash else { | |
| 802 | return (hash, false, nil) | |
| 803 | } | |
| 804 | return (hash, true, readResult(after: line, text: text)) | |
| 805 | } | |
| 806 | ||
| 807 | static func cachedMessage(_ value: VarValue?) -> String { | |
| 808 | value.map { "Cached: " + lispLiteral($0) } ?? "Cached; nothing was run." | |
| 809 | } | |
| 810 | ||
| 811 | /// The body with its variables, as the language's `org-babel-expand-body:` writes it. | |
| 812 | static func expandedBody(language: String, vars: [(String, VarValue)], body: String, shell: String, params: Params) -> String { | |
| 813 | if shells.contains(language) { | |
| 814 | return (shellAssignments(vars, shell: shell, params: params) + [body]).joined(separator: "\n") | |
| 815 | } | |
| 816 | if language == "python" { | |
| 817 | return (vars.map { "\($0.0)=\(pythonLiteral($0.1))" } + [body]).joined(separator: "\n") | |
| 818 | } | |
| 819 | if language == "emacs-lisp" || language == "elisp" { | |
| 820 | let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" } | |
| 821 | return bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)" | |
| 822 | } | |
| 823 | return body | |
| 824 | } | |
| 825 | ||
| 826 | /// What `org-babel-sha1-hash` hashes: the header arguments after `org-babel-process-params`, | |
| 827 | /// sorted by key and printed with `%S`, then the expanded body. | |
| 828 | static func cacheInput(language: String, params: Params, tables: Tables, expanded: String, call: Bool) throws -> String { | |
| 829 | if let key = params.lisp.first(where: { params.evaluated[$0] == nil }) { | |
| 830 | throw Failure.message(":cache with \(key) \(params.single[key] ?? "") needs Emacs to evaluate the Lisp; nothing was run.") | |
| 831 | } | |
| 832 | let ignored: Set<String> = ["replace", "silent", "none", "discard", "append", "prepend"] | |
| 833 | let drawsFile = language == "dot" || language == "plantuml" | |
| 834 | // `org-babel-default-header-args`, the language's and `org-babel-default-lob-header-args`. | |
| 835 | var defaults = [":session": "none", ":exports": call || drawsFile ? "results" : "code", ":cache": "no", ":noweb": "no", ":hlines": "no", ":tangle": "no"] | |
| 836 | if language == "emacs-lisp" || language == "elisp" { defaults[":lexical"] = "no" } | |
| 837 | var entries: [(key: String, printed: String)] = [] | |
| 838 | for (key, value) in defaults.merging(params.single, uniquingKeysWith: { $1 }) { | |
| 839 | let printed: String | |
| 840 | if let evaluated = params.evaluated[key] { | |
| 841 | printed = Elisp.printed(evaluated, escape: true) | |
| 842 | } else if value.isEmpty { | |
| 843 | continue | |
| 844 | } else if key == ":exports" { | |
| 845 | printed = lispString(value.split(whereSeparator: \.isWhitespace).map(String.init).filter { !ignored.contains($0) }.sorted().joined(separator: " ")) | |
| 846 | } else if params.single[key] != nil, !params.quoted.contains(key), let n = number(value) { | |
| 847 | printed = n | |
| 848 | } else { | |
| 849 | printed = lispString(value) | |
| 850 | } | |
| 851 | entries.append((key, printed)) | |
| 852 | } | |
| 853 | var words = params.results | |
| 854 | if drawsFile, !words.contains(where: { Params.resultGroups[0].contains($0) }) { words.append("file") } | |
| 855 | let kept = words.filter { !ignored.contains($0) }.sorted() | |
| 856 | if !kept.isEmpty { entries.append((":result-params", "(" + kept.map { lispString($0) }.joined(separator: " ") + ")")) } | |
| 857 | entries.append((":result-type", words.contains("output") ? "output" : "value")) | |
| 858 | entries.append((":results", lispString(kept.joined(separator: " ")))) | |
| 859 | if let wrap = params.wrap, !wrap.isEmpty { entries.append((":wrap", lispString(wrap))) } | |
| 860 | for (key, names) in [(":colname-names", tables.colnames), (":rowname-names", tables.rownames)] where !names.isEmpty { | |
| 861 | entries.append((key, "(" + names.map { "(\($0.name) " + lispLiteral(.list($0.names)).dropFirst() }.joined(separator: " ") + ")")) | |
| 862 | } | |
| 863 | for (name, value) in tables.vars { | |
| 864 | switch value { | |
| 865 | case .scalar, .number: entries.append((":var", "(\(name) . \(lispLiteral(value)))")) | |
| 866 | case .list, .table: entries.append((":var", "(\(name) " + lispLiteral(value).dropFirst())) | |
| 867 | } | |
| 868 | } | |
| 869 | let sorted = entries.enumerated().sorted { ($0.element.key, $0.offset) < ($1.element.key, $1.offset) }.map(\.element.printed) | |
| 870 | return sorted.joined(separator: ":") + "-" + expanded | |
| 871 | } | |
| 872 | ||
| 873 | /// `org-babel-read-result` for fixed-width lines, a table or a plain list after the | |
| 874 | /// `#+RESULTS` line at `line`; nil for anything else. | |
| 875 | static func readResult(after line: Int, text ns: NSString) -> VarValue? { | |
| 876 | var location = NSMaxRange(ns.lineRange(for: NSRange(location: line, length: 0))) | |
| 877 | var lines: [String] = [] | |
| 878 | while location < ns.length { | |
| 879 | let range = ns.lineRange(for: NSRange(location: location, length: 0)) | |
| 880 | let content = ns.substring(with: range).trimmingCharacters(in: .newlines) | |
| 881 | if content.trimmingCharacters(in: .whitespaces).isEmpty { break } | |
| 882 | lines.append(content.trimmingCharacters(in: .whitespaces)) | |
| 883 | location = NSMaxRange(range) | |
| 884 | } | |
| 885 | guard let first = lines.first else { return nil } | |
| 886 | if first == ":" || first.hasPrefix(": ") { | |
| 887 | var fixed: [String] = [] | |
| 888 | for l in lines { | |
| 889 | guard l == ":" || l.hasPrefix(": ") else { break } | |
| 890 | fixed.append(String(l.dropFirst(2))) | |
| 891 | } | |
| 892 | let value = fixed.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) | |
| 893 | return number(value).map(VarValue.number) ?? .scalar(value) | |
| 894 | } | |
| 895 | if first.hasPrefix("|") { | |
| 896 | var rows: [[Cell]?] = [] | |
| 897 | for l in lines { | |
| 898 | guard l.hasPrefix("|") else { break } | |
| 899 | if l.hasPrefix("|-") { | |
| 900 | rows.append(nil) | |
| 901 | continue | |
| 902 | } | |
| 903 | let cells = l.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) } | |
| 904 | rows.append((l.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell)) | |
| 905 | } | |
| 906 | return .table(rows) | |
| 907 | } | |
| 908 | if first.firstMatch(of: #/^[-+*] /#) != nil { | |
| 909 | var items: [Cell] = [] | |
| 910 | for l in lines { | |
| 911 | guard let m = l.firstMatch(of: /^[-+*] (.*)$/) else { return nil } | |
| 912 | items.append(cell(String(m.1))) | |
| 913 | } | |
| 914 | return .list(items) | |
| 915 | } | |
| 916 | return nil | |
| 917 | } | |
| 918 | ||
| 919 | // MARK: - Header arguments | |
| 920 | ||
| 921 | struct Params { | |
| 922 | var results: [String] = ["replace"] | |
| 923 | var single: [String: String] = [:] | |
| 924 | var vars: [(name: String, value: String)] = [] | |
| 925 | var wrap: String? | |
| 926 | /// Keys whose value is Lisp to evaluate (`org-babel-read`): unquoted, starting with `(`, `'`, `` ` `` or `[`. | |
| 927 | var lisp: Set<String> = [] | |
| 928 | /// Keys whose value was a quoted string, which `org-babel-read` doesn't take for a number. | |
| 929 | var quoted: Set<String> = [] | |
| 930 | /// Lisp values evaluated to something other than a string or number, such as a list of | |
| 931 | /// column names. | |
| 932 | var evaluated: [String: Sexp] = [:] | |
| 933 | ||
| 934 | /// `org-babel-read` on the Lisp values the interpreter can evaluate: a string or number | |
| 935 | /// takes the form's place; other values are kept in `evaluated`. | |
| 936 | mutating func evaluateLisp(file: String?) { | |
| 937 | for key in lisp { | |
| 938 | guard let form = try? LispReader.readFirst(single[key] ?? "").sexp, | |
| 939 | let value = try? (file.map { Tangle.fileLisp(path: $0) } ?? Elisp()).eval(form) else { continue } | |
| 940 | let printed = Elisp.printed(value) | |
| 941 | if let s = value.string { | |
| 942 | single[key] = s | |
| 943 | quoted.insert(key) | |
| 944 | lisp.remove(key) | |
| 945 | } else if Babel.number(printed) == printed { | |
| 946 | single[key] = printed | |
| 947 | lisp.remove(key) | |
| 948 | } else { | |
| 949 | evaluated[key] = value | |
| 950 | } | |
| 951 | } | |
| 952 | } | |
| 953 | ||
| 954 | static let resultGroups: [Set<String>] = [ | |
| 955 | ["file", "list", "vector", "table", "scalar", "verbatim"], | |
| 956 | ["raw", "html", "latex", "org", "code", "pp", "drawer", "link", "graphics"], | |
| 957 | ["replace", "silent", "none", "discard", "append", "prepend"], | |
| 958 | ["output", "value"], | |
| 959 | ] | |
| 960 | ||
| 961 | /// `defaults` go under the properties, as `org-babel-default-inline-header-args` do. | |
| 962 | init(block: SrcBlockInfo, model: DocumentModel, text: NSString, defaults: [(String, String)] = [], extra: [[(String, String)]] = [], | |
| 963 | inline: Bool = false) throws { | |
| 964 | var layers: [[(String, String)]] = [defaults, Babel.languageDefaults[block.language ?? ""] ?? []] | |
| 965 | layers += Params.propertyLayers(language: block.language ?? "", heading: block.heading, model: model) | |
| 966 | let firstLine = inline ? "" : text.substring(with: text.lineRange(for: NSRange(location: block.range.lowerBound, length: 0))) | |
| 967 | if let r = firstLine.range(of: "(?i)#\\+begin_src[ \\t]+\\S+", options: .regularExpression) { | |
| 968 | var rest = String(firstLine[r.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines) | |
| 969 | while let first = rest.split(separator: " ").first, first.hasPrefix("-") || first.hasPrefix("+") { | |
| 970 | rest = String(rest.dropFirst(first.count)).trimmingCharacters(in: .whitespaces) | |
| 971 | } | |
| 972 | layers.append(Params.parse(rest)) | |
| 973 | } | |
| 974 | // `#+HEADER:` lines above the block. | |
| 975 | var headers: [String] = [] | |
| 976 | var location = block.range.lowerBound | |
| 977 | while !inline, location > 0 { | |
| 978 | let previous = text.lineRange(for: NSRange(location: location - 1, length: 0)) | |
| 979 | let line = text.substring(with: previous).trimmingCharacters(in: .whitespacesAndNewlines) | |
| 980 | guard line.range(of: "(?i)^#\\+(header|name|caption|attr_[a-z]+|results|plot|label):", options: .regularExpression) != nil else { break } | |
| 981 | if line.lowercased().hasPrefix("#+header:") { headers.insert(String(line.dropFirst("#+header:".count)), at: 0) } | |
| 982 | location = previous.location | |
| 983 | } | |
| 984 | for header in headers { layers.append(Params.parse(header)) } | |
| 985 | layers += extra | |
| 986 | ||
| 987 | for layer in layers { | |
| 988 | for (key, raw) in layer { | |
| 989 | let quoted = key != ":var" && raw.count >= 2 && raw.hasPrefix("\"") && raw.hasSuffix("\"") | |
| 990 | let value = quoted ? Params.unescape(String(raw.dropFirst().dropLast())) : raw | |
| 991 | if key != ":var" { | |
| 992 | if !quoted, let first = value.first, "('`[".contains(first) { lisp.insert(key) } else { lisp.remove(key) } | |
| 993 | if quoted { self.quoted.insert(key) } else { self.quoted.remove(key) } | |
| 994 | } | |
| 995 | switch key { | |
| 996 | case ":results": | |
| 997 | for word in value.split(whereSeparator: \.isWhitespace).map(String.init) { | |
| 998 | if let group = Params.resultGroups.first(where: { $0.contains(word) }) { results.removeAll { group.contains($0) } } | |
| 999 | results.removeAll { $0 == word } | |
| 1000 | results.insert(word, at: 0) | |
| 1001 | } | |
| 1002 | case ":var": | |
| 1003 | for value in Params.splitVars(value) { | |
| 1004 | guard let eq = value.firstIndex(of: "=") else { throw Failure.message(":var \(value) needs a name and a value") } | |
| 1005 | let name = value[..<eq].trimmingCharacters(in: .whitespaces) | |
| 1006 | let assigned = value[value.index(after: eq)...].trimmingCharacters(in: .whitespaces) | |
| 1007 | vars.removeAll { $0.name == name } | |
| 1008 | vars.append((name, assigned)) | |
| 1009 | } | |
| 1010 | case ":wrap": | |
| 1011 | wrap = value | |
| 1012 | default: | |
| 1013 | single[key] = value | |
| 1014 | } | |
| 1015 | } | |
| 1016 | } | |
| 1017 | } | |
| 1018 | ||
| 1019 | /// `org-babel-params-from-properties` under `heading`, or before any: the inherited | |
| 1020 | /// `header-args`, then the inherited `header-args:LANG`, each the nearest value with `+` | |
| 1021 | /// additions after it. | |
| 1022 | static func propertyLayers(language: String, heading: Int?, model: DocumentModel) -> [[(String, String)]] { | |
| 1023 | var levels = [model.fileProperties] | |
| 1024 | if let heading { | |
| 1025 | levels += (model.ancestors(of: heading) + [heading]).map { model.headings[$0].properties } | |
| 1026 | } | |
| 1027 | return ["header-args", "header-args:\(language)"].compactMap { key in | |
| 1028 | var value: String? | |
| 1029 | for entries in levels { | |
| 1030 | for entry in entries where entry.key.lowercased() == key { | |
| 1031 | value = entry.additive ? [value, entry.value].compactMap { $0 }.joined(separator: " ") : entry.value | |
| 1032 | } | |
| 1033 | } | |
| 1034 | return value.map(Params.parse) | |
| 1035 | } | |
| 1036 | } | |
| 1037 | ||
| 1038 | /// `org-babel-parse-header-arguments`: split before each `:key` outside quotes and | |
| 1039 | /// parentheses. | |
| 1040 | /// A Lisp string's contents as `read` gives them. | |
| 1041 | static func unescape(_ s: String) -> String { | |
| 1042 | var out = "" | |
| 1043 | var escaped = false | |
| 1044 | for c in s { | |
| 1045 | if escaped { | |
| 1046 | switch c { | |
| 1047 | case "n": out.append("\n") | |
| 1048 | case "t": out.append("\t") | |
| 1049 | default: out.append(c) | |
| 1050 | } | |
| 1051 | escaped = false | |
| 1052 | } else if c == "\\" { | |
| 1053 | escaped = true | |
| 1054 | } else { | |
| 1055 | out.append(c) | |
| 1056 | } | |
| 1057 | } | |
| 1058 | return out | |
| 1059 | } | |
| 1060 | ||
| 1061 | /// `org-babel-parse-multiple-vars`: one `:var` value holding several assignments split | |
| 1062 | /// on spaces outside quotes and brackets, pieces split beside `=` joined again. | |
| 1063 | static func splitVars(_ value: String) -> [String] { | |
| 1064 | var pieces: [String] = [] | |
| 1065 | var current = "" | |
| 1066 | var depth = 0 | |
| 1067 | var quoted = false | |
| 1068 | var previous: Character = " " | |
| 1069 | for c in value { | |
| 1070 | if c == "\"", previous != "\\" { quoted.toggle() } | |
| 1071 | previous = c | |
| 1072 | if !quoted, "([{".contains(c) { depth += 1 } | |
| 1073 | if !quoted, ")]}".contains(c) { depth = max(0, depth - 1) } | |
| 1074 | if c == " ", !quoted, depth == 0 { | |
| 1075 | if !current.isEmpty { pieces.append(current) } | |
| 1076 | current = "" | |
| 1077 | } else { | |
| 1078 | current.append(c) | |
| 1079 | } | |
| 1080 | } | |
| 1081 | if !current.isEmpty { pieces.append(current) } | |
| 1082 | var joined: [String] = [] | |
| 1083 | for piece in pieces { | |
| 1084 | if let last = joined.last, last.hasSuffix("=") || piece.hasPrefix("=") { | |
| 1085 | joined[joined.count - 1] = last + piece | |
| 1086 | } else { | |
| 1087 | joined.append(piece) | |
| 1088 | } | |
| 1089 | } | |
| 1090 | return joined.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } | |
| 1091 | } | |
| 1092 | ||
| 1093 | static func parse(_ text: String) -> [(String, String)] { | |
| 1094 | var parts: [String] = [] | |
| 1095 | var current = "" | |
| 1096 | var depth = 0 | |
| 1097 | var quoted = false | |
| 1098 | var previous: Character = " " | |
| 1099 | for c in text { | |
| 1100 | if c == "\"", previous != "\\" { quoted.toggle() } | |
| 1101 | if !quoted { | |
| 1102 | if c == "(" { depth += 1 } | |
| 1103 | if c == ")" { depth = max(0, depth - 1) } | |
| 1104 | } | |
| 1105 | if c == ":", !quoted, depth == 0, previous == " " || previous == "\t" { | |
| 1106 | parts.append(current) | |
| 1107 | current = "" | |
| 1108 | } | |
| 1109 | current.append(c) | |
| 1110 | previous = c | |
| 1111 | } | |
| 1112 | parts.append(current) | |
| 1113 | var pairs: [(String, String)] = [] | |
| 1114 | for part in parts { | |
| 1115 | let trimmed = part.trimmingCharacters(in: .whitespaces) | |
| 1116 | guard trimmed.hasPrefix(":") else { continue } | |
| 1117 | let key = String(trimmed.prefix { !$0.isWhitespace }).lowercased() | |
| 1118 | // Quotes stay until the value is used, so a quoted string isn't taken for Lisp. | |
| 1119 | pairs.append((key, trimmed.dropFirst(key.count).trimmingCharacters(in: .whitespaces))) | |
| 1120 | } | |
| 1121 | return pairs | |
| 1122 | } | |
| 1123 | } | |
| 1124 | ||
| 1125 | // MARK: - Variables | |
| 1126 | ||
| 1127 | /// A referenced block's result as a `:var` value. | |
| 1128 | static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> VarValue { | |
| 1129 | switch value(finish, output) { | |
| 1130 | case .none: return .scalar("") | |
| 1131 | case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s) | |
| 1132 | case .table(let rows): return .table(rows.map { $0?.map(cell) }) | |
| 1133 | } | |
| 1134 | } | |
| 1135 | ||
| 1136 | enum VarValue: Equatable, Sendable { | |
| 1137 | case scalar(String) | |
| 1138 | case number(String) | |
| 1139 | /// Rows; nil is a rule (`hline`). | |
| 1140 | case table([[Cell]?]) | |
| 1141 | case list([Cell]) | |
| 1142 | } | |
| 1143 | ||
| 1144 | enum Cell: Equatable, Sendable { | |
| 1145 | case text(String) | |
| 1146 | case number(String) | |
| 1147 | } | |
| 1148 | ||
| 1149 | /// `org-babel--string-to-number`, keeping Emacs's printed form. | |
| 1150 | static func number(_ s: String) -> String? { | |
| 1151 | let t = s.trimmingCharacters(in: .whitespaces) | |
| 1152 | guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil } | |
| 1153 | if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil { | |
| 1154 | var digits = t.hasSuffix(".") ? String(t.dropLast()) : t | |
| 1155 | let negative = digits.hasPrefix("-") | |
| 1156 | if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() } | |
| 1157 | digits = String(digits.drop { $0 == "0" }) | |
| 1158 | if digits.isEmpty { return "0" } | |
| 1159 | return (negative ? "-" : "") + digits | |
| 1160 | } | |
| 1161 | guard t.range(of: "^[-+]?([0-9]+\\.[0-9]+|[0-9]*\\.[0-9]+|[0-9]+(\\.[0-9]*)?e[-+]?[0-9]+|[0-9]*\\.[0-9]+e[-+]?[0-9]+)$", options: .regularExpression) != nil, | |
| 1162 | let d = Double(t) else { return nil } | |
| 1163 | return emacsFloat(d) | |
| 1164 | } | |
| 1165 | ||
| 1166 | /// How Emacs prints a float. | |
| 1167 | static func emacsFloat(_ d: Double) -> String { | |
| 1168 | if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) } | |
| 1169 | return "\(d)" | |
| 1170 | } | |
| 1171 | ||
| 1172 | static func cell(_ s: String) -> Cell { | |
| 1173 | var t = s | |
| 1174 | if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) } | |
| 1175 | return number(t).map(Cell.number) ?? .text(t) | |
| 1176 | } | |
| 1177 | ||
| 1178 | /// `name` or `name(args)` naming a src block in the file: the block and its call arguments. | |
| 1179 | static func referencedBlock(_ value: String, model: DocumentModel) -> (block: SrcBlockInfo, arguments: String?)? { | |
| 1180 | guard let m = value.firstMatch(of: /^([^\s()\[\]"]+)(?:\((.*)\))?$/), | |
| 1181 | let block = model.srcBlocks.first(where: { $0.name == String(m.1) }) else { return nil } | |
| 1182 | return (block, m.2.map(String.init)) | |
| 1183 | } | |
| 1184 | ||
| 1185 | /// The blocks `params`' references run, directly or through theirs. | |
| 1186 | static func referencedBlocks(_ params: Params, model: DocumentModel, text: NSString, seen: Set<String>) -> [SrcBlockInfo] { | |
| 1187 | var found: [SrcBlockInfo] = [] | |
| 1188 | var seen = seen | |
| 1189 | for value in params.vars.map(\.value) + [params.single[":stdin"]].compactMap({ $0 }) { | |
| 1190 | guard let (block, arguments) = referencedBlock(value, model: model), let name = block.name, seen.insert(name).inserted else { continue } | |
| 1191 | found.append(block) | |
| 1192 | let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? [] | |
| 1193 | if let inner = try? Params(block: block, model: model, text: text, extra: extra) { | |
| 1194 | found += referencedBlocks(inner, model: model, text: text, seen: seen) | |
| 1195 | } | |
| 1196 | } | |
| 1197 | return found | |
| 1198 | } | |
| 1199 | ||
| 1200 | /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src | |
| 1201 | /// blocks, which run first (`Needed`) and give their result. | |
| 1202 | static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References) throws -> VarValue { | |
| 1203 | if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) } | |
| 1204 | if let n = number(value) { return .number(n) } | |
| 1205 | if let first = value.first, "('`[".contains(first) { return try lispValue(value) } | |
| 1206 | if let known = refs.resolved[value] { return known } | |
| 1207 | if let (block, arguments) = referencedBlock(value, model: model), let name = block.name { | |
| 1208 | guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through :var") } | |
| 1209 | let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? [] | |
| 1210 | var inner = refs | |
| 1211 | inner.visiting.insert(name) | |
| 1212 | var params = try Params(block: block, model: model, text: text, extra: extra) | |
| 1213 | params.evaluateLisp(file: refs.options.file) | |
| 1214 | // A cached block gives its result without running, as `org-babel-execute-src-block` does. | |
| 1215 | var useCache = true | |
| 1216 | if params.single[":cache"] == "yes", let language = block.language { | |
| 1217 | let tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: text, refs: inner)) }, params: params) | |
| 1218 | let body = nowebEvaluates(params.single[":noweb"]) ? try expandNoweb(block, params: params, model: model, text: text) : normalizedBody(block) | |
| 1219 | let state = try cacheState(language: language, params: params, tables: tables, body: body, location: block.range, name: name, call: false, text: text, options: refs.options, model: model) | |
| 1220 | if state.current { | |
| 1221 | if let value = state.value { return value } | |
| 1222 | useCache = false | |
| 1223 | } | |
| 1224 | } | |
| 1225 | switch plan(block, params: params, model: model, text: text, | |
| 1226 | options: refs.options, location: block.range, name: name, refs: inner, useCache: useCache) { | |
| 1227 | case .failure(let failure): throw failure | |
| 1228 | case .success(let job): | |
| 1229 | throw Needed(need: job.needs.first ?? BabelJob.Need(reference: value, job: job)) | |
| 1230 | } | |
| 1231 | } | |
| 1232 | if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") } | |
| 1233 | // A named element: `#+NAME: value` above a table or list. | |
| 1234 | let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$" | |
| 1235 | guard let r = (text as String).range(of: pattern, options: .regularExpression) else { | |
| 1236 | throw Failure.message("Can't find \(value) for :var.") | |
| 1237 | } | |
| 1238 | let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String))) | |
| 1239 | var location = start | |
| 1240 | var rows: [[Cell]?] = [] | |
| 1241 | var items: [Cell] = [] | |
| 1242 | while location < text.length { | |
| 1243 | let lineRange = text.lineRange(for: NSRange(location: location, length: 0)) | |
| 1244 | let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines) | |
| 1245 | let trimmed = line.trimmingCharacters(in: .whitespaces) | |
| 1246 | if trimmed.hasPrefix("|") { | |
| 1247 | if trimmed.hasPrefix("|-") { | |
| 1248 | rows.append(nil) | |
| 1249 | location = NSMaxRange(lineRange) | |
| 1250 | continue | |
| 1251 | } | |
| 1252 | let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) } | |
| 1253 | rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell)) | |
| 1254 | } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty { | |
| 1255 | items.append(cell(String(m.1))) | |
| 1256 | } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) { | |
| 1257 | if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") { | |
| 1258 | throw Failure.message("Using a src block's result in :var isn't supported yet.") | |
| 1259 | } | |
| 1260 | break | |
| 1261 | } else { | |
| 1262 | break | |
| 1263 | } | |
| 1264 | location = NSMaxRange(lineRange) | |
| 1265 | } | |
| 1266 | if !rows.isEmpty { return .table(rows) } | |
| 1267 | if !items.isEmpty { return .list(items) } | |
| 1268 | throw Failure.message("\(value) isn't a table or list.") | |
| 1269 | } | |
| 1270 | ||
| 1271 | /// `org-babel-sh-var-to-string`: a table's rows as tab-separated lines, a list's items as | |
| 1272 | /// lines. | |
| 1273 | static func shellString(_ value: VarValue, separator: String? = nil, hline: String? = nil) -> String { | |
| 1274 | switch value { | |
| 1275 | case .scalar(let s), .number(let s): return s | |
| 1276 | case .list(let items): return items.map(cellText).joined(separator: "\n") | |
| 1277 | case .table(let rows): return rows.compactMap { $0?.map(cellText).joined(separator: separator ?? "\t") ?? hline }.joined(separator: "\n") | |
| 1278 | } | |
| 1279 | } | |
| 1280 | ||
| 1281 | /// `org-babel-variable-assignments:shell`, by the shell's name: for bash, an array for a | |
| 1282 | /// list and an associative array for a table of two or more columns; `set` for fish; a | |
| 1283 | /// quoted string otherwise. | |
| 1284 | static func shellAssignments(_ vars: [(String, VarValue)], shell: String, params: Params) -> [String] { | |
| 1285 | let separator = params.single[":separator"] | |
| 1286 | let hline = params.single[":hlines"] == "yes" ? params.single[":hline-string"] ?? "hline" : nil | |
| 1287 | func quoted(_ value: VarValue) -> String { | |
| 1288 | "'" + shellString(value, separator: separator, hline: hline).replacingOccurrences(of: "'", with: "'\"'\"'") + "'" | |
| 1289 | } | |
| 1290 | return vars.map { name, value in | |
| 1291 | if shell.hasSuffix("bash") { | |
| 1292 | switch value { | |
| 1293 | case .table(let rows) where (rows.first ?? nil).map({ $0.count >= 2 }) ?? false: | |
| 1294 | let entries = rows.compactMap { $0 }.map { row in | |
| 1295 | "\(name)[\(quoted(.scalar(cellText(row[0]))))]=\(quoted(.list(Array(row.dropFirst()))))" | |
| 1296 | } | |
| 1297 | return (["unset \(name)", "declare -A \(name)"] + entries).joined(separator: "\n") | |
| 1298 | case .table(let rows): | |
| 1299 | let items = rows.map { $0.map { quoted(.list($0)) } ?? quoted(.scalar("hline")) } | |
| 1300 | return "unset \(name)\ndeclare -a \(name)=( \(items.joined(separator: " ")) )" | |
| 1301 | case .list(let items): | |
| 1302 | return "unset \(name)\ndeclare -a \(name)=( \(items.map { quoted(.scalar(cellText($0))) }.joined(separator: " ")) )" | |
| 1303 | case .scalar, .number: | |
| 1304 | break | |
| 1305 | } | |
| 1306 | } | |
| 1307 | return (shell.hasSuffix("fish") ? "set \(name) " : "\(name)=") + quoted(value) | |
| 1308 | } | |
| 1309 | } | |
| 1310 | ||
| 1311 | /// `org-babel-python-var-to-python`. | |
| 1312 | static func pythonLiteral(_ value: VarValue) -> String { | |
| 1313 | func cell(_ c: Cell) -> String { | |
| 1314 | switch c { | |
| 1315 | case .number(let n): return n | |
| 1316 | case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r")) | |
| 1317 | } | |
| 1318 | } | |
| 1319 | switch value { | |
| 1320 | case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r")) | |
| 1321 | case .number(let n): return n | |
| 1322 | case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]" | |
| 1323 | case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", ") + "]" } ?? "None" }.joined(separator: ", ") + "]" | |
| 1324 | } | |
| 1325 | } | |
| 1326 | ||
| 1327 | /// `prin1` of a string. | |
| 1328 | static func lispString(_ s: String, triple: Bool = false) -> String { | |
| 1329 | let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" | |
| 1330 | return triple ? "\"\"" + quoted + "\"\"" : quoted | |
| 1331 | } | |
| 1332 | ||
| 1333 | static func lispLiteral(_ value: VarValue) -> String { | |
| 1334 | func cell(_ c: Cell) -> String { | |
| 1335 | switch c { | |
| 1336 | case .number(let n): return n | |
| 1337 | case .text(let s): return lispString(s) | |
| 1338 | } | |
| 1339 | } | |
| 1340 | switch value { | |
| 1341 | case .scalar(let s): return lispString(s) | |
| 1342 | case .number(let n): return n | |
| 1343 | case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")" | |
| 1344 | case .table(let rows): return "(" + rows.map { $0.map { "(" + $0.map(cell).joined(separator: " ") + ")" } ?? "hline" }.joined(separator: " ") + ")" | |
| 1345 | } | |
| 1346 | } | |
| 1347 | ||
| 1348 | // MARK: - Python | |
| 1349 | ||
| 1350 | /// Writes the value of `main()` to the result file as org's Python wrapper does: `pprint` | |
| 1351 | /// for `pp`, `key :: value` items for a dict as a list, dicts as rows for tables, | |
| 1352 | /// otherwise `str`. | |
| 1353 | static let pythonFormatter = """ | |
| 1354 | def __orgstar_format(value, path, params): | |
| 1355 | def rows(v): | |
| 1356 | if isinstance(v, dict): | |
| 1357 | return [(k, rows(x)) for k, x in v.items()] | |
| 1358 | if isinstance(v, (list, tuple)): | |
| 1359 | return [rows(x) for x in v] | |
| 1360 | return v | |
| 1361 | with open(path, 'w') as out: | |
| 1362 | if 'pp' in params: | |
| 1363 | import pprint | |
| 1364 | out.write(pprint.pformat(value)) | |
| 1365 | elif 'list' in params and isinstance(value, dict): | |
| 1366 | out.write(str(['{} :: {}'.format(k, v) for k, v in value.items()])) | |
| 1367 | else: | |
| 1368 | if not set(params) & {'scalar', 'verbatim', 'raw'} and 'table' in params: | |
| 1369 | value = rows(value) | |
| 1370 | out.write(str(value)) | |
| 1371 | ||
| 1372 | """ | |
| 1373 | ||
| 1374 | /// `org-babel-python--shift-right`: four spaces more on every line outside strings. | |
| 1375 | static func shiftRight(_ body: String) -> String { | |
| 1376 | var inString: String? | |
| 1377 | var lines: [String] = [] | |
| 1378 | for line in body.components(separatedBy: "\n") { | |
| 1379 | lines.append(inString == nil ? " " + line : line) | |
| 1380 | var i = line.startIndex | |
| 1381 | while i < line.endIndex { | |
| 1382 | if let delimiter = inString { | |
| 1383 | if line[i...].hasPrefix(delimiter) { | |
| 1384 | inString = nil | |
| 1385 | i = line.index(i, offsetBy: 3) | |
| 1386 | continue | |
| 1387 | } | |
| 1388 | } else if line[i] == "#" { | |
| 1389 | break | |
| 1390 | } else if line[i...].hasPrefix("\"\"\"") || line[i...].hasPrefix("'''") { | |
| 1391 | inString = String(line[i...].prefix(3)) | |
| 1392 | i = line.index(i, offsetBy: 3) | |
| 1393 | continue | |
| 1394 | } else if line[i] == "\"" || line[i] == "'" { | |
| 1395 | let quote = line[i] | |
| 1396 | i = line.index(after: i) | |
| 1397 | while i < line.endIndex, line[i] != quote { | |
| 1398 | if line[i] == "\\" { i = line.index(after: i) } | |
| 1399 | if i < line.endIndex { i = line.index(after: i) } | |
| 1400 | } | |
| 1401 | } | |
| 1402 | if i < line.endIndex { i = line.index(after: i) } | |
| 1403 | } | |
| 1404 | } | |
| 1405 | return lines.joined(separator: "\n") | |
| 1406 | } | |
| 1407 | ||
| 1408 | // MARK: - Emacs Lisp | |
| 1409 | ||
| 1410 | /// Evaluates `form` and prints the result as JSON: its `%s` and `%S` forms, and its rows | |
| 1411 | /// when it is a table. | |
| 1412 | static func emacsScript(form: String, params: [String]) -> String { | |
| 1413 | """ | |
| 1414 | ;;; -*- lexical-binding: t -*- | |
| 1415 | (require 'cl-lib) | |
| 1416 | (require 'json) | |
| 1417 | (let* ((result \(form)) | |
| 1418 | (print-level nil) | |
| 1419 | (print-length nil) | |
| 1420 | (cell (lambda (c) (if (stringp c) c (format "%s" c)))) | |
| 1421 | (tabulable (and (proper-list-p result) | |
| 1422 | (cl-every (lambda (e) (or (atom e) (proper-list-p e))) result))) | |
| 1423 | (rows (and tabulable result | |
| 1424 | (if (cl-every (lambda (e) (or (eq e 'hline) (listp e))) result) | |
| 1425 | (mapcar (lambda (r) (if (eq r 'hline) "hline" (vconcat (mapcar cell r)))) result) | |
| 1426 | (list (vconcat (mapcar cell result))))))) | |
| 1427 | (princ (json-encode `((s . ,(format "%s" result)) | |
| 1428 | (S . ,(format "%S" result)) | |
| 1429 | (string . ,(if (stringp result) t :json-false)) | |
| 1430 | (rows . ,(if rows (vconcat rows) :json-null)))))) | |
| 1431 | """ | |
| 1432 | } | |
| 1433 | ||
| 1434 | /// An Emacs Lisp job run by `Elisp` instead of Emacs: the output `emacsScript` would print. | |
| 1435 | /// A Lisp error fails the run, as it does in Emacs; nil when the block uses what `Elisp` | |
| 1436 | /// doesn't have. | |
| 1437 | public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? { | |
| 1438 | guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil } | |
| 1439 | let lisp = Elisp() | |
| 1440 | let result: Sexp | |
| 1441 | do { | |
| 1442 | result = try lisp.eval(sexp) | |
| 1443 | } catch is Elisp.Unsupported { | |
| 1444 | return nil | |
| 1445 | } catch { | |
| 1446 | throw .message("\(error)") | |
| 1447 | } | |
| 1448 | func cell(_ c: Sexp) -> String { Elisp.printed(c) } | |
| 1449 | func isProper(_ v: Sexp) -> Bool { | |
| 1450 | if case .list = v { return true } | |
| 1451 | return Elisp.isNil(v) | |
| 1452 | } | |
| 1453 | func isAtom(_ v: Sexp) -> Bool { | |
| 1454 | switch v { | |
| 1455 | case .list(let items): items.isEmpty | |
| 1456 | case .dotted: false | |
| 1457 | default: true | |
| 1458 | } | |
| 1459 | } | |
| 1460 | var rows: [Any] = [] | |
| 1461 | if case .list(let items) = result, items.allSatisfy({ isAtom($0) || isProper($0) }) { | |
| 1462 | if items.allSatisfy({ $0 == .symbol("hline") || isProper($0) }) { | |
| 1463 | rows = items.map { $0 == .symbol("hline") ? "hline" as Any : ((try? Elisp.elements($0)) ?? []).map(cell) as Any } | |
| 1464 | } else { | |
| 1465 | rows = [items.map(cell)] | |
| 1466 | } | |
| 1467 | } | |
| 1468 | var object: [String: Any] = ["s": Elisp.printed(result), "S": Elisp.printed(result, escape: true), "string": result.string != nil] | |
| 1469 | object["rows"] = rows.isEmpty ? NSNull() : rows | |
| 1470 | guard let data = try? JSONSerialization.data(withJSONObject: object), let json = String(data: data, encoding: .utf8) else { return nil } | |
| 1471 | return BabelOutput(stdout: lisp.standardOutput + json, stderr: lisp.messages) | |
| 1472 | } | |
| 1473 | ||
| 1474 | // MARK: - Finishing | |
| 1475 | ||
| 1476 | /// What the run produced, as Babel holds it before inserting. | |
| 1477 | enum Value: Equatable { | |
| 1478 | case none | |
| 1479 | case string(String) | |
| 1480 | /// Rows of cells; nil rows are rules. | |
| 1481 | case table([[String]?]) | |
| 1482 | } | |
| 1483 | ||
| 1484 | /// The edit that writes the run's result under the block, or why it can't. | |
| 1485 | public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> { | |
| 1486 | let ns = text as NSString | |
| 1487 | var blockRange = job.block | |
| 1488 | if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText { | |
| 1489 | let found = ns.range(of: job.blockText) | |
| 1490 | guard found.location != NSNotFound, | |
| 1491 | ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else { | |
| 1492 | return .failure(.message("The block changed while it ran; the result wasn't written.")) | |
| 1493 | } | |
| 1494 | blockRange = found.location..<NSMaxRange(found) | |
| 1495 | } | |
| 1496 | let value = Self.value(job.finish, output) | |
| 1497 | if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) } | |
| 1498 | let buffer = EmacsBuffer(text, point: 0, settings: settings) | |
| 1499 | if job.finish.inline { | |
| 1500 | do { | |
| 1501 | try insertInlineResult(value, job.finish, at: blockRange, buffer: buffer) | |
| 1502 | } catch let error as Failure { | |
| 1503 | return .failure(error) | |
| 1504 | } catch { | |
| 1505 | return .failure(.message("\(error)")) | |
| 1506 | } | |
| 1507 | return .success(TextEdit.between(text, buffer.text as String)) | |
| 1508 | } | |
| 1509 | insertResult(value, job.finish, block: blockRange, buffer: buffer) | |
| 1510 | return .success(TextEdit.between(text, buffer.text as String)) | |
| 1511 | } | |
| 1512 | ||
| 1513 | /// The language's result handling: `org-babel-result-cond` and the table import. | |
| 1514 | static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value { | |
| 1515 | reassemble(rawValue(finish, output), finish) | |
| 1516 | } | |
| 1517 | ||
| 1518 | static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value { | |
| 1519 | let params = finish.params | |
| 1520 | if params.contains("file") { | |
| 1521 | // `org-babel-result-to-file`: a link to `:file`, or to the result as a path. | |
| 1522 | let path = finish.file ?? rawResult(finish, output) | |
| 1523 | var link = "[[file:" + path + "]" | |
| 1524 | if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" } | |
| 1525 | return .string(link + "]") | |
| 1526 | } | |
| 1527 | let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code") | |
| 1528 | || params.contains("pp") || params.contains("file") | |
| 1529 | || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table")) | |
| 1530 | switch finish.kind { | |
| 1531 | case .shell(let valueIsExitStatus): | |
| 1532 | var results = output.stdout | |
| 1533 | if valueIsExitStatus { | |
| 1534 | results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? "" | |
| 1535 | } | |
| 1536 | if scalar { return .string(results) } | |
| 1537 | return importTable(results) | |
| 1538 | case .generic: | |
| 1539 | return .string(output.stdout) | |
| 1540 | case .python: | |
| 1541 | let raw = finish.output ? output.stdout : (output.resultFile ?? "") | |
| 1542 | if scalar { return .string(raw) } | |
| 1543 | return pythonValue(raw) | |
| 1544 | case .emacsLisp: | |
| 1545 | guard let data = output.stdout.data(using: .utf8), | |
| 1546 | let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) } | |
| 1547 | if scalar { | |
| 1548 | return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "") | |
| 1549 | } | |
| 1550 | if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") } | |
| 1551 | if let rows = object["rows"] as? [Any] { | |
| 1552 | return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) }) | |
| 1553 | } | |
| 1554 | let printed = object["S"] as? String ?? "" | |
| 1555 | return printed == "nil" ? .none : .string(printed) | |
| 1556 | case .compiled: | |
| 1557 | return compiledValue(finish, output, scalar: scalar) | |
| 1558 | } | |
| 1559 | } | |
| 1560 | ||
| 1561 | /// The result as the program left it, before tables are read. | |
| 1562 | static func rawResult(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String { | |
| 1563 | switch finish.kind { | |
| 1564 | case .python: return finish.output ? output.stdout : (output.resultFile ?? "") | |
| 1565 | case .emacsLisp: | |
| 1566 | guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout } | |
| 1567 | return object["s"] as? String ?? "" | |
| 1568 | case .shell(let valueIsExitStatus): | |
| 1569 | return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout | |
| 1570 | case .generic: return output.stdout | |
| 1571 | case .compiled: return compiledResult(finish, output) | |
| 1572 | } | |
| 1573 | } | |
| 1574 | ||
| 1575 | /// With `:results file` and `:file`, what to write there, relative to the run's folder; | |
| 1576 | /// nil when there's nothing to write or the program wrote it. | |
| 1577 | public static func fileResult(_ job: BabelJob, output: BabelOutput) -> (path: String, contents: String)? { | |
| 1578 | guard job.finish.params.contains("file"), let file = job.finish.file, !job.finish.writesFile else { return nil } | |
| 1579 | return (file, rawResult(job.finish, output)) | |
| 1580 | } | |
| 1581 | ||
| 1582 | /// `org-babel-import-elisp-from-file`. | |
| 1583 | static func importTable(_ results: String) -> Value { | |
| 1584 | guard !results.isEmpty else { return .none } | |
| 1585 | var lines = results.components(separatedBy: "\n") | |
| 1586 | if lines.last == "" { lines.removeLast() } | |
| 1587 | let nonEmpty = lines.filter { !$0.isEmpty } | |
| 1588 | let rows: [[String]] | |
| 1589 | if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) { | |
| 1590 | rows = lines.map { $0.components(separatedBy: "\t") } | |
| 1591 | } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) { | |
| 1592 | rows = lines.map(csvFields) | |
| 1593 | } else if lines.count == 1 { | |
| 1594 | rows = [[lines[0]]] | |
| 1595 | } else { | |
| 1596 | rows = lines.map { line in | |
| 1597 | let trimmed = line.drop { $0 == " " } | |
| 1598 | return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty | |
| 1599 | ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init) | |
| 1600 | } | |
| 1601 | } | |
| 1602 | let cells = rows.map { row in row.map { field -> String in | |
| 1603 | let trimmed = field.trimmingCharacters(in: .whitespaces) | |
| 1604 | switch cell(trimmed) { | |
| 1605 | case .number(let n): return n | |
| 1606 | case .text(let t): return t | |
| 1607 | } | |
| 1608 | } } | |
| 1609 | if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) } | |
| 1610 | return .table(cells) | |
| 1611 | } | |
| 1612 | ||
| 1613 | static func csvFields(_ line: String) -> [String] { | |
| 1614 | var fields: [String] = [] | |
| 1615 | var current = "" | |
| 1616 | var quoted = false | |
| 1617 | for c in line { | |
| 1618 | if c == "\"" { | |
| 1619 | quoted.toggle() | |
| 1620 | } else if c == ",", !quoted { | |
| 1621 | fields.append(current.trimmingCharacters(in: .whitespaces)) | |
| 1622 | current = "" | |
| 1623 | } else { | |
| 1624 | current.append(c) | |
| 1625 | } | |
| 1626 | } | |
| 1627 | fields.append(current.trimmingCharacters(in: .whitespaces)) | |
| 1628 | return fields | |
| 1629 | } | |
| 1630 | ||
| 1631 | /// `org-babel-python-table-or-string`; with `none` "null" and `braces`, | |
| 1632 | /// `org-babel-java-table-or-string`, which reads `{…}` as a list too. | |
| 1633 | static func pythonValue(_ raw: String, none: String = "None", braces: Bool = false) -> Value { | |
| 1634 | guard let first = raw.first, let last = raw.last, raw.count >= 2, | |
| 1635 | (first == "[" && last == "]") || (first == "(" && last == ")") || (braces && first == "{" && last == "}") else { | |
| 1636 | if raw.isEmpty { return .string("") } | |
| 1637 | if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) { | |
| 1638 | return .string(String(raw.dropFirst().dropLast())) | |
| 1639 | } | |
| 1640 | if let n = number(raw) { return .string(n) } | |
| 1641 | return .string(raw) | |
| 1642 | } | |
| 1643 | var parser = PythonLiteral(Array(raw)) | |
| 1644 | parser.braces = braces | |
| 1645 | guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) } | |
| 1646 | func text(_ v: PythonLiteral.Node) -> String { | |
| 1647 | switch v { | |
| 1648 | case .atom(let s): return s | |
| 1649 | case .string(let s): return s | |
| 1650 | case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")" | |
| 1651 | } | |
| 1652 | } | |
| 1653 | if items.allSatisfy({ if case .list = $0 { return true }; if case .atom(none) = $0 { return true }; return false }) { | |
| 1654 | return .table(items.map { item -> [String]? in | |
| 1655 | if case .list(let cells) = item { return cells.map(text) } | |
| 1656 | return nil | |
| 1657 | }) | |
| 1658 | } | |
| 1659 | return .table([items.map { if case .atom(none) = $0 { return "hline" }; return text($0) }]) | |
| 1660 | } | |
| 1661 | ||
| 1662 | struct PythonLiteral { | |
| 1663 | indirect enum Node: Equatable { | |
| 1664 | case atom(String) | |
| 1665 | case string(String) | |
| 1666 | case list([Node]) | |
| 1667 | } | |
| 1668 | ||
| 1669 | let chars: [Character] | |
| 1670 | var i = 0 | |
| 1671 | /// `{…}` is a list, as `org-babel-script-escape` reads it. | |
| 1672 | var braces = false | |
| 1673 | init(_ chars: [Character]) { self.chars = chars } | |
| 1674 | var atEnd: Bool { mutating get { skip(); return i == chars.count } } | |
| 1675 | ||
| 1676 | mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } } | |
| 1677 | ||
| 1678 | mutating func parse() -> Node? { | |
| 1679 | skip() | |
| 1680 | guard i < chars.count else { return nil } | |
| 1681 | let c = chars[i] | |
| 1682 | if c == "[" || c == "(" || (braces && c == "{") { | |
| 1683 | let close: Character = c == "[" ? "]" : c == "{" ? "}" : ")" | |
| 1684 | i += 1 | |
| 1685 | var items: [Node] = [] | |
| 1686 | skip() | |
| 1687 | if i < chars.count, chars[i] == close { | |
| 1688 | i += 1 | |
| 1689 | return .list(items) | |
| 1690 | } | |
| 1691 | while true { | |
| 1692 | guard let item = parse() else { return nil } | |
| 1693 | items.append(item) | |
| 1694 | skip() | |
| 1695 | guard i < chars.count else { return nil } | |
| 1696 | if chars[i] == "," { | |
| 1697 | i += 1 | |
| 1698 | skip() | |
| 1699 | if i < chars.count, chars[i] == close { | |
| 1700 | i += 1 | |
| 1701 | return .list(items) | |
| 1702 | } | |
| 1703 | continue | |
| 1704 | } | |
| 1705 | if chars[i] == close { | |
| 1706 | i += 1 | |
| 1707 | return .list(items) | |
| 1708 | } | |
| 1709 | return nil | |
| 1710 | } | |
| 1711 | } | |
| 1712 | if c == "'" || c == "\"" { | |
| 1713 | i += 1 | |
| 1714 | var s = "" | |
| 1715 | while i < chars.count, chars[i] != c { | |
| 1716 | if chars[i] == "\\", i + 1 < chars.count { | |
| 1717 | i += 1 | |
| 1718 | switch chars[i] { | |
| 1719 | case "n": s.append("\n") | |
| 1720 | case "t": s.append("\t") | |
| 1721 | default: s.append(chars[i]) | |
| 1722 | } | |
| 1723 | } else { | |
| 1724 | s.append(chars[i]) | |
| 1725 | } | |
| 1726 | i += 1 | |
| 1727 | } | |
| 1728 | guard i < chars.count else { return nil } | |
| 1729 | i += 1 | |
| 1730 | return .string(s) | |
| 1731 | } | |
| 1732 | var s = "" | |
| 1733 | while i < chars.count, !",)] \n".contains(chars[i]), !(braces && chars[i] == "}") { | |
| 1734 | s.append(chars[i]) | |
| 1735 | i += 1 | |
| 1736 | } | |
| 1737 | guard !s.isEmpty else { return nil } | |
| 1738 | return .atom(number(s) ?? s) | |
| 1739 | } | |
| 1740 | } | |
| 1741 | ||
| 1742 | // MARK: - Inserting | |
| 1743 | ||
| 1744 | static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:" | |
| 1745 | ||
| 1746 | /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results | |
| 1747 | /// keyword, added when there is none. | |
| 1748 | /// The `#+RESULTS` line of a block's results (`org-babel-where-is-src-block-result`): | |
| 1749 | /// the one naming `name`, or for an unnamed block an empty one right after it. | |
| 1750 | static func existingResults(name: String?, block: Range<Int>, text ns: NSString) -> Int? { | |
| 1751 | if let name { | |
| 1752 | let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$" | |
| 1753 | let regex = try! NSRegularExpression(pattern: pattern) | |
| 1754 | return regex.firstMatch(in: ns as String, range: NSRange(location: 0, length: ns.length))?.range.location | |
| 1755 | } | |
| 1756 | // The element after the block, past blank lines. | |
| 1757 | var location = block.upperBound | |
| 1758 | while location < ns.length { | |
| 1759 | let line = ns.lineRange(for: NSRange(location: location, length: 0)) | |
| 1760 | let content = ns.substring(with: line) | |
| 1761 | if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { | |
| 1762 | location = NSMaxRange(line) | |
| 1763 | continue | |
| 1764 | } | |
| 1765 | if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil { | |
| 1766 | return line.location | |
| 1767 | } | |
| 1768 | break | |
| 1769 | } | |
| 1770 | return nil | |
| 1771 | } | |
| 1772 | ||
| 1773 | /// The hash in the `#+RESULTS[…]:` line at `line` (`org-babel-result-regexp`). | |
| 1774 | static func resultsHash(at line: Int, text ns: NSString) -> String? { | |
| 1775 | let content = ns.substring(with: ns.lineRange(for: NSRange(location: line, length: 0))) | |
| 1776 | return content.firstMatch(of: #/(?i)^[ \t]*#\+results\[(?:\(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\) )?([0-9a-f]+)\]:/#).map { String($0.1) } | |
| 1777 | } | |
| 1778 | ||
| 1779 | static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int { | |
| 1780 | if let line = existingResults(name: finish.name, block: block, text: buffer.text) { | |
| 1781 | // `org-babel--clear-results-maybe`: a different hash clears the results and | |
| 1782 | // rewrites the keyword. | |
| 1783 | if let hash = finish.hash, resultsHash(at: line, text: buffer.text) != hash { | |
| 1784 | buffer.point = line | |
| 1785 | let indent = String(buffer.substring(line, buffer.lineEnd(line)).prefix { $0 == " " || $0 == "\t" }) | |
| 1786 | buffer.forwardLine(1) | |
| 1787 | let contents = buffer.point | |
| 1788 | buffer.deleteRegion(contents, max(contents, resultEnd(buffer))) | |
| 1789 | buffer.deleteRegion(line, contents) | |
| 1790 | buffer.point = line | |
| 1791 | buffer.insert(indent + "#+RESULTS[\(hash)]:" + (finish.name.map { " " + $0 } ?? "") + "\n") | |
| 1792 | if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil { | |
| 1793 | buffer.saveExcursion { buffer.insert("\n") } | |
| 1794 | } | |
| 1795 | } | |
| 1796 | return line | |
| 1797 | } | |
| 1798 | // A new keyword after the block. | |
| 1799 | buffer.point = min(block.upperBound, buffer.length) | |
| 1800 | buffer.skipBackward([32, 9, 10, 13]) | |
| 1801 | buffer.forwardLine(1) | |
| 1802 | if !buffer.bolp { buffer.insert("\n") } | |
| 1803 | let indent = buffer.saveExcursion { () -> String in | |
| 1804 | buffer.point = block.lowerBound | |
| 1805 | let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point)) | |
| 1806 | return String(line.prefix { $0 == " " || $0 == "\t" }) | |
| 1807 | } | |
| 1808 | buffer.insert("\n") | |
| 1809 | let keywordLine = buffer.point | |
| 1810 | buffer.insert(indent + "#+RESULTS" + (finish.hash.map { "[\($0)]" } ?? "") + ":" + (finish.name.map { " " + $0 } ?? "") + "\n") | |
| 1811 | if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil { | |
| 1812 | buffer.saveExcursion { buffer.insert("\n") } | |
| 1813 | } | |
| 1814 | return keywordLine | |
| 1815 | } | |
| 1816 | ||
| 1817 | /// `org-babel-result-end` with point at the start of the result. | |
| 1818 | static func resultEnd(_ buffer: EmacsBuffer) -> Int { | |
| 1819 | let start = buffer.point | |
| 1820 | let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start)) | |
| 1821 | if line.trimmingCharacters(in: .whitespaces).isEmpty { return start } | |
| 1822 | if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil { | |
| 1823 | return min(buffer.length, buffer.lineEnd(start) + 1) | |
| 1824 | } | |
| 1825 | let tree = OrgParser.parse(buffer.text as String) | |
| 1826 | var node = tree.root | |
| 1827 | var found: SyntaxNode? | |
| 1828 | while let child = node.child(containing: start) { | |
| 1829 | if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) { | |
| 1830 | if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) { | |
| 1831 | found = child | |
| 1832 | break | |
| 1833 | } | |
| 1834 | } | |
| 1835 | node = child | |
| 1836 | } | |
| 1837 | guard let element = found else { return start } | |
| 1838 | var end = element.range.upperBound | |
| 1839 | while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 } | |
| 1840 | return min(buffer.length, buffer.lineEnd(end) + 1) | |
| 1841 | } | |
| 1842 | ||
| 1843 | /// `org-babel-insert-result` for a src block. | |
| 1844 | /// An inline block's result, after it: ` {{{results(=value=)}}}`, replacing one already | |
| 1845 | /// there; raw results go in as they are. | |
| 1846 | static func insertInlineResult(_ value: Value, _ finish: BabelJob.Finish, at object: Range<Int>, buffer: EmacsBuffer) throws { | |
| 1847 | var string: String | |
| 1848 | switch value { | |
| 1849 | case .none: string = "" | |
| 1850 | case .string(let s): string = s | |
| 1851 | case .table(let rows): | |
| 1852 | let cells = rows.compactMap { $0 } | |
| 1853 | guard cells.count == 1, cells[0].count == 1 else { throw Failure.message("Inline source block results can't be tables or lists") } | |
| 1854 | string = cells[0][0] | |
| 1855 | } | |
| 1856 | buffer.point = object.upperBound | |
| 1857 | if let existing = buffer.lookingAt("[ \\t]*\\{\\{\\{results\\(.*?\\)\\}\\}\\}") { | |
| 1858 | buffer.deleteRegion(existing[0]!.lowerBound, existing[0]!.upperBound) | |
| 1859 | } | |
| 1860 | if finish.params.contains("raw") { | |
| 1861 | buffer.insert(" " + string) | |
| 1862 | return | |
| 1863 | } | |
| 1864 | if string.hasSuffix("\n") { string.removeLast() } | |
| 1865 | guard !string.contains("\n") else { throw Failure.message("Inline source block results must be one line") } | |
| 1866 | buffer.insert(" {{{results(=" + string + "=)}}}") | |
| 1867 | } | |
| 1868 | ||
| 1869 | static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) { | |
| 1870 | let params = finish.params | |
| 1871 | let keyword = resultsLine(finish, block: block, buffer: buffer) | |
| 1872 | buffer.point = keyword | |
| 1873 | let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count | |
| 1874 | buffer.forwardLine(1) | |
| 1875 | if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") } | |
| 1876 | var beg = buffer.point | |
| 1877 | if params.contains("replace") { | |
| 1878 | buffer.deleteRegion(beg, resultEnd(buffer)) | |
| 1879 | buffer.point = beg | |
| 1880 | } else if params.contains("append") { | |
| 1881 | buffer.point = resultEnd(buffer) | |
| 1882 | beg = buffer.point | |
| 1883 | } | |
| 1884 | var tabulated = false | |
| 1885 | // A list made from a string is examplified, as a string result is. | |
| 1886 | var listed = false | |
| 1887 | switch value { | |
| 1888 | case .none: | |
| 1889 | break | |
| 1890 | case .string(var s) where params.contains("list"): | |
| 1891 | if s.last != "\n" { s += "\n" } | |
| 1892 | let items = s.split(separator: "\n", omittingEmptySubsequences: true) | |
| 1893 | buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n") | |
| 1894 | case .table(let rows) where params.contains("list"): | |
| 1895 | listed = true | |
| 1896 | let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") } | |
| 1897 | buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n") | |
| 1898 | case .table(let rows): | |
| 1899 | tabulated = true | |
| 1900 | let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" } | |
| 1901 | let start = buffer.point | |
| 1902 | buffer.insert(lines.joined(separator: "\n") + "\n") | |
| 1903 | buffer.point = start | |
| 1904 | buffer.tableAlign() | |
| 1905 | buffer.point = buffer.tableEnd() | |
| 1906 | case .string(var s): | |
| 1907 | if !s.isEmpty, s.last != "\n" { s += "\n" } | |
| 1908 | buffer.insert(s) | |
| 1909 | } | |
| 1910 | let end = buffer.marker(buffer.point, advances: true) | |
| 1911 | defer { buffer.release(end) } | |
| 1912 | func wrap(_ open: String, _ close: String, escape: Bool) { | |
| 1913 | buffer.point = end.position | |
| 1914 | buffer.insert(close + "\n") | |
| 1915 | buffer.point = beg | |
| 1916 | buffer.insert(open + "\n") | |
| 1917 | if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) } | |
| 1918 | } | |
| 1919 | if let wrapValue = finish.wrap { | |
| 1920 | let full = wrapValue.isEmpty ? "results" : wrapValue | |
| 1921 | let type = String(full.split(separator: " ").first ?? "results") | |
| 1922 | if type.lowercased() != "nil", type.lowercased() != "no" { | |
| 1923 | wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true) | |
| 1924 | } | |
| 1925 | } else if params.contains("html") { | |
| 1926 | wrap("#+begin_export html", "#+end_export", escape: true) | |
| 1927 | } else if params.contains("latex") { | |
| 1928 | wrap("#+begin_export latex", "#+end_export", escape: true) | |
| 1929 | } else if params.contains("org") { | |
| 1930 | wrap("#+begin_src org", "#+end_src", escape: true) | |
| 1931 | } else if params.contains("code") { | |
| 1932 | wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true) | |
| 1933 | } else if params.contains("raw") || params.contains("file") { | |
| 1934 | // As inserted. | |
| 1935 | } else if params.contains("drawer") { | |
| 1936 | wrap(":results:", ":end:", escape: false) | |
| 1937 | } else if !tabulated, !(params.contains("list") && listed) { | |
| 1938 | examplify(buffer, beg, end.position) | |
| 1939 | } | |
| 1940 | if indent > 0, !(tabulated && params.contains("append")) { | |
| 1941 | buffer.point = beg | |
| 1942 | while buffer.point < end.position { | |
| 1943 | if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) } | |
| 1944 | if buffer.forwardLine(1) != 0 { break } | |
| 1945 | } | |
| 1946 | } | |
| 1947 | } | |
| 1948 | ||
| 1949 | /// `org-escape-code-in-region`. | |
| 1950 | static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) { | |
| 1951 | buffer.point = start | |
| 1952 | let stop = buffer.marker(end) | |
| 1953 | defer { buffer.release(stop) } | |
| 1954 | while buffer.point < stop.position { | |
| 1955 | let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point)) | |
| 1956 | if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) { | |
| 1957 | buffer.point += line[..<m.1.startIndex].utf16.count | |
| 1958 | buffer.insert(",") | |
| 1959 | } | |
| 1960 | if buffer.forwardLine(1) != 0 { break } | |
| 1961 | } | |
| 1962 | } | |
| 1963 | ||
| 1964 | /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block. | |
| 1965 | static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) { | |
| 1966 | let text = buffer.substring(beg, end) | |
| 1967 | var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0) | |
| 1968 | if text.isEmpty { size = 0 } | |
| 1969 | guard size > 0 else { return } | |
| 1970 | if size < 10 { | |
| 1971 | buffer.point = beg | |
| 1972 | for _ in 0..<size { | |
| 1973 | buffer.point = buffer.lineStart(buffer.point) | |
| 1974 | buffer.insert(": ") | |
| 1975 | buffer.forwardLine(1) | |
| 1976 | } | |
| 1977 | return | |
| 1978 | } | |
| 1979 | let endMarker = buffer.marker(end) | |
| 1980 | defer { buffer.release(endMarker) } | |
| 1981 | buffer.point = beg | |
| 1982 | buffer.insert("#+begin_example\n") | |
| 1983 | escapeCode(buffer, from: buffer.point, to: endMarker.position) | |
| 1984 | buffer.point = endMarker.position | |
| 1985 | if !buffer.bolp { buffer.insert("\n") } | |
| 1986 | buffer.insert("#+end_example") | |
| 1987 | if !buffer.eolp { buffer.insert("\n") } | |
| 1988 | } | |
| 1989 | 569 | } |
| 1990 | 570 | |
| 1991 | 571 | /// C-c C-c in a src block: `org-babel-execute-src-block`. |
Sources/OrgCore/Compute/BabelCache.swift added +136
| @@ -0,0 +1,136 @@ | ||
| 1 | import CryptoKit | |
| 2 | import Foundation | |
| 3 | ||
| 4 | extension Babel { | |
| 5 | // MARK: - Cache | |
| 6 | ||
| 7 | /// `:cache yes` (`org-babel-execute-src-block`): the block's hash, and whether its results | |
| 8 | /// already carry it, with their value when it can be read. | |
| 9 | static func cacheState(language: String, params: Params, tables: Tables, body: String, location: Range<Int>, name: String?, | |
| 10 | call: Bool, text: NSString, options: Options, model: DocumentModel) throws -> (hash: String, current: Bool, value: VarValue?) { | |
| 11 | let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location.lowerBound } | |
| 12 | // The hash is taken outside the shell's own binding of `shell-file-name`, so its | |
| 13 | // variables are written for the user's shell whatever the block's language. | |
| 14 | let expanded = try languageExpansion(body, language: language, tables: tables, params: params, | |
| 15 | properties: { inheritedProperty($0, heading: heading, model: model) }) | |
| 16 | ?? expandedBody(language: language, vars: tables.vars, body: body, shell: options.shell, params: params) | |
| 17 | let input = try cacheInput(language: language, params: params, tables: tables, expanded: expanded, call: call) | |
| 18 | let hash = Insecure.SHA1.hash(data: Data(input.utf8)).map { String(format: "%02x", $0) }.joined() | |
| 19 | guard let line = existingResults(name: name, block: location, text: text), resultsHash(at: line, text: text) == hash else { | |
| 20 | return (hash, false, nil) | |
| 21 | } | |
| 22 | return (hash, true, readResult(after: line, text: text)) | |
| 23 | } | |
| 24 | ||
| 25 | static func cachedMessage(_ value: VarValue?) -> String { | |
| 26 | value.map { "Cached: " + lispLiteral($0) } ?? "Cached; nothing was run." | |
| 27 | } | |
| 28 | ||
| 29 | /// The body with its variables, as the language's `org-babel-expand-body:` writes it. | |
| 30 | static func expandedBody(language: String, vars: [(String, VarValue)], body: String, shell: String, params: Params) -> String { | |
| 31 | if shells.contains(language) { | |
| 32 | return (shellAssignments(vars, shell: shell, params: params) + [body]).joined(separator: "\n") | |
| 33 | } | |
| 34 | if language == "python" { | |
| 35 | return (vars.map { "\($0.0)=\(pythonLiteral($0.1))" } + [body]).joined(separator: "\n") | |
| 36 | } | |
| 37 | if language == "emacs-lisp" || language == "elisp" { | |
| 38 | let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" } | |
| 39 | return bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)" | |
| 40 | } | |
| 41 | return body | |
| 42 | } | |
| 43 | ||
| 44 | /// What `org-babel-sha1-hash` hashes: the header arguments after `org-babel-process-params`, | |
| 45 | /// sorted by key and printed with `%S`, then the expanded body. | |
| 46 | static func cacheInput(language: String, params: Params, tables: Tables, expanded: String, call: Bool) throws -> String { | |
| 47 | if let key = params.lisp.first(where: { params.evaluated[$0] == nil }) { | |
| 48 | throw Failure.message(":cache with \(key) \(params.single[key] ?? "") needs Emacs to evaluate the Lisp; nothing was run.") | |
| 49 | } | |
| 50 | let ignored: Set<String> = ["replace", "silent", "none", "discard", "append", "prepend"] | |
| 51 | let drawsFile = language == "dot" || language == "plantuml" | |
| 52 | // `org-babel-default-header-args`, the language's and `org-babel-default-lob-header-args`. | |
| 53 | var defaults = [":session": "none", ":exports": call || drawsFile ? "results" : "code", ":cache": "no", ":noweb": "no", ":hlines": "no", ":tangle": "no"] | |
| 54 | if language == "emacs-lisp" || language == "elisp" { defaults[":lexical"] = "no" } | |
| 55 | var entries: [(key: String, printed: String)] = [] | |
| 56 | for (key, value) in defaults.merging(params.single, uniquingKeysWith: { $1 }) { | |
| 57 | let printed: String | |
| 58 | if let evaluated = params.evaluated[key] { | |
| 59 | printed = Elisp.printed(evaluated, escape: true) | |
| 60 | } else if value.isEmpty { | |
| 61 | continue | |
| 62 | } else if key == ":exports" { | |
| 63 | printed = lispString(value.split(whereSeparator: \.isWhitespace).map(String.init).filter { !ignored.contains($0) }.sorted().joined(separator: " ")) | |
| 64 | } else if params.single[key] != nil, !params.quoted.contains(key), let n = number(value) { | |
| 65 | printed = n | |
| 66 | } else { | |
| 67 | printed = lispString(value) | |
| 68 | } | |
| 69 | entries.append((key, printed)) | |
| 70 | } | |
| 71 | var words = params.results | |
| 72 | if drawsFile, !words.contains(where: { Params.resultGroups[0].contains($0) }) { words.append("file") } | |
| 73 | let kept = words.filter { !ignored.contains($0) }.sorted() | |
| 74 | if !kept.isEmpty { entries.append((":result-params", "(" + kept.map { lispString($0) }.joined(separator: " ") + ")")) } | |
| 75 | entries.append((":result-type", words.contains("output") ? "output" : "value")) | |
| 76 | entries.append((":results", lispString(kept.joined(separator: " ")))) | |
| 77 | if let wrap = params.wrap, !wrap.isEmpty { entries.append((":wrap", lispString(wrap))) } | |
| 78 | for (key, names) in [(":colname-names", tables.colnames), (":rowname-names", tables.rownames)] where !names.isEmpty { | |
| 79 | entries.append((key, "(" + names.map { "(\($0.name) " + lispLiteral(.list($0.names)).dropFirst() }.joined(separator: " ") + ")")) | |
| 80 | } | |
| 81 | for (name, value) in tables.vars { | |
| 82 | switch value { | |
| 83 | case .scalar, .number: entries.append((":var", "(\(name) . \(lispLiteral(value)))")) | |
| 84 | case .list, .table: entries.append((":var", "(\(name) " + lispLiteral(value).dropFirst())) | |
| 85 | } | |
| 86 | } | |
| 87 | let sorted = entries.enumerated().sorted { ($0.element.key, $0.offset) < ($1.element.key, $1.offset) }.map(\.element.printed) | |
| 88 | return sorted.joined(separator: ":") + "-" + expanded | |
| 89 | } | |
| 90 | ||
| 91 | /// `org-babel-read-result` for fixed-width lines, a table or a plain list after the | |
| 92 | /// `#+RESULTS` line at `line`; nil for anything else. | |
| 93 | static func readResult(after line: Int, text ns: NSString) -> VarValue? { | |
| 94 | var location = NSMaxRange(ns.lineRange(for: NSRange(location: line, length: 0))) | |
| 95 | var lines: [String] = [] | |
| 96 | while location < ns.length { | |
| 97 | let range = ns.lineRange(for: NSRange(location: location, length: 0)) | |
| 98 | let content = ns.substring(with: range).trimmingCharacters(in: .newlines) | |
| 99 | if content.trimmingCharacters(in: .whitespaces).isEmpty { break } | |
| 100 | lines.append(content.trimmingCharacters(in: .whitespaces)) | |
| 101 | location = NSMaxRange(range) | |
| 102 | } | |
| 103 | guard let first = lines.first else { return nil } | |
| 104 | if first == ":" || first.hasPrefix(": ") { | |
| 105 | var fixed: [String] = [] | |
| 106 | for l in lines { | |
| 107 | guard l == ":" || l.hasPrefix(": ") else { break } | |
| 108 | fixed.append(String(l.dropFirst(2))) | |
| 109 | } | |
| 110 | let value = fixed.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) | |
| 111 | return number(value).map(VarValue.number) ?? .scalar(value) | |
| 112 | } | |
| 113 | if first.hasPrefix("|") { | |
| 114 | var rows: [[Cell]?] = [] | |
| 115 | for l in lines { | |
| 116 | guard l.hasPrefix("|") else { break } | |
| 117 | if l.hasPrefix("|-") { | |
| 118 | rows.append(nil) | |
| 119 | continue | |
| 120 | } | |
| 121 | let cells = l.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) } | |
| 122 | rows.append((l.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell)) | |
| 123 | } | |
| 124 | return .table(rows) | |
| 125 | } | |
| 126 | if first.firstMatch(of: #/^[-+*] /#) != nil { | |
| 127 | var items: [Cell] = [] | |
| 128 | for l in lines { | |
| 129 | guard let m = l.firstMatch(of: /^[-+*] (.*)$/) else { return nil } | |
| 130 | items.append(cell(String(m.1))) | |
| 131 | } | |
| 132 | return .list(items) | |
| 133 | } | |
| 134 | return nil | |
| 135 | } | |
| 136 | } | |
Sources/OrgCore/Compute/BabelHeaders.swift added +209
| @@ -0,0 +1,209 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Babel { | |
| 4 | // MARK: - Header arguments | |
| 5 | ||
| 6 | struct Params { | |
| 7 | var results: [String] = ["replace"] | |
| 8 | var single: [String: String] = [:] | |
| 9 | var vars: [(name: String, value: String)] = [] | |
| 10 | var wrap: String? | |
| 11 | /// Keys whose value is Lisp to evaluate (`org-babel-read`): unquoted, starting with `(`, `'`, `` ` `` or `[`. | |
| 12 | var lisp: Set<String> = [] | |
| 13 | /// Keys whose value was a quoted string, which `org-babel-read` doesn't take for a number. | |
| 14 | var quoted: Set<String> = [] | |
| 15 | /// Lisp values evaluated to something other than a string or number, such as a list of | |
| 16 | /// column names. | |
| 17 | var evaluated: [String: Sexp] = [:] | |
| 18 | ||
| 19 | /// `org-babel-read` on the Lisp values the interpreter can evaluate: a string or number | |
| 20 | /// takes the form's place; other values are kept in `evaluated`. | |
| 21 | mutating func evaluateLisp(file: String?) { | |
| 22 | for key in lisp { | |
| 23 | guard let form = try? LispReader.readFirst(single[key] ?? "").sexp, | |
| 24 | let value = try? (file.map { Tangle.fileLisp(path: $0) } ?? Elisp()).eval(form) else { continue } | |
| 25 | let printed = Elisp.printed(value) | |
| 26 | if let s = value.string { | |
| 27 | single[key] = s | |
| 28 | quoted.insert(key) | |
| 29 | lisp.remove(key) | |
| 30 | } else if Babel.number(printed) == printed { | |
| 31 | single[key] = printed | |
| 32 | lisp.remove(key) | |
| 33 | } else { | |
| 34 | evaluated[key] = value | |
| 35 | } | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | static let resultGroups: [Set<String>] = [ | |
| 40 | ["file", "list", "vector", "table", "scalar", "verbatim"], | |
| 41 | ["raw", "html", "latex", "org", "code", "pp", "drawer", "link", "graphics"], | |
| 42 | ["replace", "silent", "none", "discard", "append", "prepend"], | |
| 43 | ["output", "value"], | |
| 44 | ] | |
| 45 | ||
| 46 | /// `defaults` go under the properties, as `org-babel-default-inline-header-args` do. | |
| 47 | init(block: SrcBlockInfo, model: DocumentModel, text: NSString, defaults: [(String, String)] = [], extra: [[(String, String)]] = [], | |
| 48 | inline: Bool = false) throws { | |
| 49 | var layers: [[(String, String)]] = [defaults, Babel.languageDefaults[block.language ?? ""] ?? []] | |
| 50 | layers += Params.propertyLayers(language: block.language ?? "", heading: block.heading, model: model) | |
| 51 | let firstLine = inline ? "" : text.substring(with: text.lineRange(for: NSRange(location: block.range.lowerBound, length: 0))) | |
| 52 | if let r = firstLine.range(of: "(?i)#\\+begin_src[ \\t]+\\S+", options: .regularExpression) { | |
| 53 | var rest = String(firstLine[r.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines) | |
| 54 | while let first = rest.split(separator: " ").first, first.hasPrefix("-") || first.hasPrefix("+") { | |
| 55 | rest = String(rest.dropFirst(first.count)).trimmingCharacters(in: .whitespaces) | |
| 56 | } | |
| 57 | layers.append(Params.parse(rest)) | |
| 58 | } | |
| 59 | // `#+HEADER:` lines above the block. | |
| 60 | var headers: [String] = [] | |
| 61 | var location = block.range.lowerBound | |
| 62 | while !inline, location > 0 { | |
| 63 | let previous = text.lineRange(for: NSRange(location: location - 1, length: 0)) | |
| 64 | let line = text.substring(with: previous).trimmingCharacters(in: .whitespacesAndNewlines) | |
| 65 | guard line.range(of: "(?i)^#\\+(header|name|caption|attr_[a-z]+|results|plot|label):", options: .regularExpression) != nil else { break } | |
| 66 | if line.lowercased().hasPrefix("#+header:") { headers.insert(String(line.dropFirst("#+header:".count)), at: 0) } | |
| 67 | location = previous.location | |
| 68 | } | |
| 69 | for header in headers { layers.append(Params.parse(header)) } | |
| 70 | layers += extra | |
| 71 | ||
| 72 | for layer in layers { | |
| 73 | for (key, raw) in layer { | |
| 74 | let quoted = key != ":var" && raw.count >= 2 && raw.hasPrefix("\"") && raw.hasSuffix("\"") | |
| 75 | let value = quoted ? Params.unescape(String(raw.dropFirst().dropLast())) : raw | |
| 76 | if key != ":var" { | |
| 77 | if !quoted, let first = value.first, "('`[".contains(first) { lisp.insert(key) } else { lisp.remove(key) } | |
| 78 | if quoted { self.quoted.insert(key) } else { self.quoted.remove(key) } | |
| 79 | } | |
| 80 | switch key { | |
| 81 | case ":results": | |
| 82 | for word in value.split(whereSeparator: \.isWhitespace).map(String.init) { | |
| 83 | if let group = Params.resultGroups.first(where: { $0.contains(word) }) { results.removeAll { group.contains($0) } } | |
| 84 | results.removeAll { $0 == word } | |
| 85 | results.insert(word, at: 0) | |
| 86 | } | |
| 87 | case ":var": | |
| 88 | for value in Params.splitVars(value) { | |
| 89 | guard let eq = value.firstIndex(of: "=") else { throw Failure.message(":var \(value) needs a name and a value") } | |
| 90 | let name = value[..<eq].trimmingCharacters(in: .whitespaces) | |
| 91 | let assigned = value[value.index(after: eq)...].trimmingCharacters(in: .whitespaces) | |
| 92 | vars.removeAll { $0.name == name } | |
| 93 | vars.append((name, assigned)) | |
| 94 | } | |
| 95 | case ":wrap": | |
| 96 | wrap = value | |
| 97 | default: | |
| 98 | single[key] = value | |
| 99 | } | |
| 100 | } | |
| 101 | } | |
| 102 | } | |
| 103 | ||
| 104 | /// `org-babel-params-from-properties` under `heading`, or before any: the inherited | |
| 105 | /// `header-args`, then the inherited `header-args:LANG`, each the nearest value with `+` | |
| 106 | /// additions after it. | |
| 107 | static func propertyLayers(language: String, heading: Int?, model: DocumentModel) -> [[(String, String)]] { | |
| 108 | var levels = [model.fileProperties] | |
| 109 | if let heading { | |
| 110 | levels += (model.ancestors(of: heading) + [heading]).map { model.headings[$0].properties } | |
| 111 | } | |
| 112 | return ["header-args", "header-args:\(language)"].compactMap { key in | |
| 113 | var value: String? | |
| 114 | for entries in levels { | |
| 115 | for entry in entries where entry.key.lowercased() == key { | |
| 116 | value = entry.additive ? [value, entry.value].compactMap { $0 }.joined(separator: " ") : entry.value | |
| 117 | } | |
| 118 | } | |
| 119 | return value.map(Params.parse) | |
| 120 | } | |
| 121 | } | |
| 122 | ||
| 123 | /// `org-babel-parse-header-arguments`: split before each `:key` outside quotes and | |
| 124 | /// parentheses. | |
| 125 | /// A Lisp string's contents as `read` gives them. | |
| 126 | static func unescape(_ s: String) -> String { | |
| 127 | var out = "" | |
| 128 | var escaped = false | |
| 129 | for c in s { | |
| 130 | if escaped { | |
| 131 | switch c { | |
| 132 | case "n": out.append("\n") | |
| 133 | case "t": out.append("\t") | |
| 134 | default: out.append(c) | |
| 135 | } | |
| 136 | escaped = false | |
| 137 | } else if c == "\\" { | |
| 138 | escaped = true | |
| 139 | } else { | |
| 140 | out.append(c) | |
| 141 | } | |
| 142 | } | |
| 143 | return out | |
| 144 | } | |
| 145 | ||
| 146 | /// `org-babel-parse-multiple-vars`: one `:var` value holding several assignments split | |
| 147 | /// on spaces outside quotes and brackets, pieces split beside `=` joined again. | |
| 148 | static func splitVars(_ value: String) -> [String] { | |
| 149 | var pieces: [String] = [] | |
| 150 | var current = "" | |
| 151 | var depth = 0 | |
| 152 | var quoted = false | |
| 153 | var previous: Character = " " | |
| 154 | for c in value { | |
| 155 | if c == "\"", previous != "\\" { quoted.toggle() } | |
| 156 | previous = c | |
| 157 | if !quoted, "([{".contains(c) { depth += 1 } | |
| 158 | if !quoted, ")]}".contains(c) { depth = max(0, depth - 1) } | |
| 159 | if c == " ", !quoted, depth == 0 { | |
| 160 | if !current.isEmpty { pieces.append(current) } | |
| 161 | current = "" | |
| 162 | } else { | |
| 163 | current.append(c) | |
| 164 | } | |
| 165 | } | |
| 166 | if !current.isEmpty { pieces.append(current) } | |
| 167 | var joined: [String] = [] | |
| 168 | for piece in pieces { | |
| 169 | if let last = joined.last, last.hasSuffix("=") || piece.hasPrefix("=") { | |
| 170 | joined[joined.count - 1] = last + piece | |
| 171 | } else { | |
| 172 | joined.append(piece) | |
| 173 | } | |
| 174 | } | |
| 175 | return joined.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } | |
| 176 | } | |
| 177 | ||
| 178 | static func parse(_ text: String) -> [(String, String)] { | |
| 179 | var parts: [String] = [] | |
| 180 | var current = "" | |
| 181 | var depth = 0 | |
| 182 | var quoted = false | |
| 183 | var previous: Character = " " | |
| 184 | for c in text { | |
| 185 | if c == "\"", previous != "\\" { quoted.toggle() } | |
| 186 | if !quoted { | |
| 187 | if c == "(" { depth += 1 } | |
| 188 | if c == ")" { depth = max(0, depth - 1) } | |
| 189 | } | |
| 190 | if c == ":", !quoted, depth == 0, previous == " " || previous == "\t" { | |
| 191 | parts.append(current) | |
| 192 | current = "" | |
| 193 | } | |
| 194 | current.append(c) | |
| 195 | previous = c | |
| 196 | } | |
| 197 | parts.append(current) | |
| 198 | var pairs: [(String, String)] = [] | |
| 199 | for part in parts { | |
| 200 | let trimmed = part.trimmingCharacters(in: .whitespaces) | |
| 201 | guard trimmed.hasPrefix(":") else { continue } | |
| 202 | let key = String(trimmed.prefix { !$0.isWhitespace }).lowercased() | |
| 203 | // Quotes stay until the value is used, so a quoted string isn't taken for Lisp. | |
| 204 | pairs.append((key, trimmed.dropFirst(key.count).trimmingCharacters(in: .whitespaces))) | |
| 205 | } | |
| 206 | return pairs | |
| 207 | } | |
| 208 | } | |
| 209 | } | |
Sources/OrgCore/Compute/BabelLanguages.swift added +129
| @@ -0,0 +1,129 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Babel { | |
| 4 | // MARK: - Python | |
| 5 | ||
| 6 | /// Writes the value of `main()` to the result file as org's Python wrapper does: `pprint` | |
| 7 | /// for `pp`, `key :: value` items for a dict as a list, dicts as rows for tables, | |
| 8 | /// otherwise `str`. | |
| 9 | static let pythonFormatter = """ | |
| 10 | def __orgstar_format(value, path, params): | |
| 11 | def rows(v): | |
| 12 | if isinstance(v, dict): | |
| 13 | return [(k, rows(x)) for k, x in v.items()] | |
| 14 | if isinstance(v, (list, tuple)): | |
| 15 | return [rows(x) for x in v] | |
| 16 | return v | |
| 17 | with open(path, 'w') as out: | |
| 18 | if 'pp' in params: | |
| 19 | import pprint | |
| 20 | out.write(pprint.pformat(value)) | |
| 21 | elif 'list' in params and isinstance(value, dict): | |
| 22 | out.write(str(['{} :: {}'.format(k, v) for k, v in value.items()])) | |
| 23 | else: | |
| 24 | if not set(params) & {'scalar', 'verbatim', 'raw'} and 'table' in params: | |
| 25 | value = rows(value) | |
| 26 | out.write(str(value)) | |
| 27 | ||
| 28 | """ | |
| 29 | ||
| 30 | /// `org-babel-python--shift-right`: four spaces more on every line outside strings. | |
| 31 | static func shiftRight(_ body: String) -> String { | |
| 32 | var inString: String? | |
| 33 | var lines: [String] = [] | |
| 34 | for line in body.components(separatedBy: "\n") { | |
| 35 | lines.append(inString == nil ? " " + line : line) | |
| 36 | var i = line.startIndex | |
| 37 | while i < line.endIndex { | |
| 38 | if let delimiter = inString { | |
| 39 | if line[i...].hasPrefix(delimiter) { | |
| 40 | inString = nil | |
| 41 | i = line.index(i, offsetBy: 3) | |
| 42 | continue | |
| 43 | } | |
| 44 | } else if line[i] == "#" { | |
| 45 | break | |
| 46 | } else if line[i...].hasPrefix("\"\"\"") || line[i...].hasPrefix("'''") { | |
| 47 | inString = String(line[i...].prefix(3)) | |
| 48 | i = line.index(i, offsetBy: 3) | |
| 49 | continue | |
| 50 | } else if line[i] == "\"" || line[i] == "'" { | |
| 51 | let quote = line[i] | |
| 52 | i = line.index(after: i) | |
| 53 | while i < line.endIndex, line[i] != quote { | |
| 54 | if line[i] == "\\" { i = line.index(after: i) } | |
| 55 | if i < line.endIndex { i = line.index(after: i) } | |
| 56 | } | |
| 57 | } | |
| 58 | if i < line.endIndex { i = line.index(after: i) } | |
| 59 | } | |
| 60 | } | |
| 61 | return lines.joined(separator: "\n") | |
| 62 | } | |
| 63 | ||
| 64 | // MARK: - Emacs Lisp | |
| 65 | ||
| 66 | /// Evaluates `form` and prints the result as JSON: its `%s` and `%S` forms, and its rows | |
| 67 | /// when it is a table. | |
| 68 | static func emacsScript(form: String, params: [String]) -> String { | |
| 69 | """ | |
| 70 | ;;; -*- lexical-binding: t -*- | |
| 71 | (require 'cl-lib) | |
| 72 | (require 'json) | |
| 73 | (let* ((result \(form)) | |
| 74 | (print-level nil) | |
| 75 | (print-length nil) | |
| 76 | (cell (lambda (c) (if (stringp c) c (format "%s" c)))) | |
| 77 | (tabulable (and (proper-list-p result) | |
| 78 | (cl-every (lambda (e) (or (atom e) (proper-list-p e))) result))) | |
| 79 | (rows (and tabulable result | |
| 80 | (if (cl-every (lambda (e) (or (eq e 'hline) (listp e))) result) | |
| 81 | (mapcar (lambda (r) (if (eq r 'hline) "hline" (vconcat (mapcar cell r)))) result) | |
| 82 | (list (vconcat (mapcar cell result))))))) | |
| 83 | (princ (json-encode `((s . ,(format "%s" result)) | |
| 84 | (S . ,(format "%S" result)) | |
| 85 | (string . ,(if (stringp result) t :json-false)) | |
| 86 | (rows . ,(if rows (vconcat rows) :json-null)))))) | |
| 87 | """ | |
| 88 | } | |
| 89 | ||
| 90 | /// An Emacs Lisp job run by `Elisp` instead of Emacs: the output `emacsScript` would print. | |
| 91 | /// A Lisp error fails the run, as it does in Emacs; nil when the block uses what `Elisp` | |
| 92 | /// doesn't have. | |
| 93 | public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? { | |
| 94 | guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil } | |
| 95 | let lisp = Elisp() | |
| 96 | let result: Sexp | |
| 97 | do { | |
| 98 | result = try lisp.eval(sexp) | |
| 99 | } catch is Elisp.Unsupported { | |
| 100 | return nil | |
| 101 | } catch { | |
| 102 | throw .message("\(error)") | |
| 103 | } | |
| 104 | func cell(_ c: Sexp) -> String { Elisp.printed(c) } | |
| 105 | func isProper(_ v: Sexp) -> Bool { | |
| 106 | if case .list = v { return true } | |
| 107 | return Elisp.isNil(v) | |
| 108 | } | |
| 109 | func isAtom(_ v: Sexp) -> Bool { | |
| 110 | switch v { | |
| 111 | case .list(let items): items.isEmpty | |
| 112 | case .dotted: false | |
| 113 | default: true | |
| 114 | } | |
| 115 | } | |
| 116 | var rows: [Any] = [] | |
| 117 | if case .list(let items) = result, items.allSatisfy({ isAtom($0) || isProper($0) }) { | |
| 118 | if items.allSatisfy({ $0 == .symbol("hline") || isProper($0) }) { | |
| 119 | rows = items.map { $0 == .symbol("hline") ? "hline" as Any : ((try? Elisp.elements($0)) ?? []).map(cell) as Any } | |
| 120 | } else { | |
| 121 | rows = [items.map(cell)] | |
| 122 | } | |
| 123 | } | |
| 124 | var object: [String: Any] = ["s": Elisp.printed(result), "S": Elisp.printed(result, escape: true), "string": result.string != nil] | |
| 125 | object["rows"] = rows.isEmpty ? NSNull() : rows | |
| 126 | guard let data = try? JSONSerialization.data(withJSONObject: object), let json = String(data: data, encoding: .utf8) else { return nil } | |
| 127 | return BabelOutput(stdout: lisp.standardOutput + json, stderr: lisp.messages) | |
| 128 | } | |
| 129 | } | |
Sources/OrgCore/Compute/BabelNoweb.swift added +113
| @@ -0,0 +1,113 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Babel { | |
| 4 | // MARK: - Noweb | |
| 5 | ||
| 6 | /// `org-babel-noweb-p` in the `:eval` context. | |
| 7 | static func nowebEvaluates(_ value: String?) -> Bool { | |
| 8 | (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "no-export", "strip-export", "eval", "strip-tangle"].contains(String($0)) } | |
| 9 | } | |
| 10 | ||
| 11 | /// `org-babel-noweb-p` for `:tangle`. | |
| 12 | static func nowebTangles(_ value: String?) -> Bool { | |
| 13 | (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "tangle", "no-export", "strip-export", "strip-tangle"].contains(String($0)) } | |
| 14 | } | |
| 15 | ||
| 16 | /// `org-babel-expand-noweb-references` for evaluation: each `<<name>>` becomes the body of | |
| 17 | /// the block named so, or of every block with that `:noweb-ref`, joined by `:noweb-sep`, or | |
| 18 | /// the contents of the heading with that ID; the text before it on its line goes before | |
| 19 | /// each line it brings. | |
| 20 | /// `tangling` expands the blocks it brings in as tangling would (`:noweb tangle`), not as | |
| 21 | /// evaluation does. | |
| 22 | /// `links` gives a block's begin and end comments, for `:comments noweb` when tangling. | |
| 23 | static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0, | |
| 24 | links: ((SrcBlockInfo, Params) throws -> (begin: String, end: String))? = nil) throws -> String { | |
| 25 | guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") } | |
| 26 | let body = normalizedBody(block) | |
| 27 | let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true | |
| 28 | let commenting = tangling && links != nil && params.single[":comments"] == "noweb" | |
| 29 | func expand(_ other: SrcBlockInfo) throws -> String { | |
| 30 | let otherParams = try Params(block: other, model: model, text: text) | |
| 31 | let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"]) | |
| 32 | let b = expands | |
| 33 | ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1, links: links) | |
| 34 | : normalizedBody(other) | |
| 35 | guard commenting, let links else { return b } | |
| 36 | // `c-wrap`: commented in this block's language, trimmed. | |
| 37 | func wrap(_ s: String) throws -> String { | |
| 38 | try Tangle.commentRegion(s, language: block.language ?? "").trimmingCharacters(in: .whitespacesAndNewlines) | |
| 39 | } | |
| 40 | var (begin, end) = try links(other.name == nil ? block : other, other.name == nil ? params : otherParams) | |
| 41 | // A `:noweb-ref` block without a name: the link is the including block's, the name empty. | |
| 42 | if other.name == nil { | |
| 43 | if let split = begin.range(of: "][") { begin = begin[..<split.lowerBound] + "][]]" } | |
| 44 | end = " ends here" | |
| 45 | } | |
| 46 | return try wrap(begin) + "\n" + b + "\n" + (try wrap(end)) + "\n" | |
| 47 | } | |
| 48 | func inCommentedHeading(_ b: SrcBlockInfo) -> Bool { | |
| 49 | guard let h = b.heading else { return false } | |
| 50 | return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") } | |
| 51 | } | |
| 52 | let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)") | |
| 53 | let ns = body as NSString | |
| 54 | var out = "" | |
| 55 | var at = 0 | |
| 56 | for m in regex.matches(in: body, range: NSRange(location: 0, length: ns.length)) { | |
| 57 | let prefix = ns.substring(with: m.range(at: 1)) | |
| 58 | let id = ns.substring(with: m.range(at: 3)) | |
| 59 | out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at)) | |
| 60 | at = NSMaxRange(m.range) | |
| 61 | var expansion = "" | |
| 62 | if id.range(of: "\\(.*\\)", options: .regularExpression) != nil { | |
| 63 | throw Failure.message("Noweb references that run a block (\(id)) aren't supported yet; nothing was run.") | |
| 64 | } else if let heading = model.headings.firstIndex(where: { h in | |
| 65 | h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) } | |
| 66 | }) { | |
| 67 | expansion = headlineBody(heading, model: model, text: text) | |
| 68 | } else if let named = model.srcBlocks.first(where: { $0.name == id }), !inCommentedHeading(named) { | |
| 69 | expansion = try expand(named) | |
| 70 | } else { | |
| 71 | var parts: [String] = [] | |
| 72 | var separators: [String] = [] | |
| 73 | for other in model.srcBlocks where !inCommentedHeading(other) { | |
| 74 | let p = try Params(block: other, model: model, text: text) | |
| 75 | guard p.single[":noweb-ref"] == id else { continue } | |
| 76 | parts.append(try expand(other)) | |
| 77 | separators.append(p.single[":noweb-sep"] ?? "\n") | |
| 78 | } | |
| 79 | for (i, part) in parts.enumerated() { | |
| 80 | if i > 0 { expansion += separators[i - 1] } | |
| 81 | expansion += part | |
| 82 | } | |
| 83 | } | |
| 84 | out += prefixing ? expansion.components(separatedBy: CharacterSet(charactersIn: "\n\r")).joined(separator: "\n" + prefix) : expansion | |
| 85 | } | |
| 86 | return out + ns.substring(from: at) | |
| 87 | } | |
| 88 | ||
| 89 | /// `org-babel-ref-headline-body`: the entry after its planning and drawers. | |
| 90 | static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String { | |
| 91 | let heading = model.headings[index] | |
| 92 | let buffer = EmacsBuffer(text as String, point: heading.headingRange.lowerBound) | |
| 93 | buffer.endOfMetaData() | |
| 94 | let start = buffer.point | |
| 95 | let end = model.headings[(index + 1)...].first.map { $0.headingRange.lowerBound } ?? text.length | |
| 96 | return start < end ? text.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) : "" | |
| 97 | } | |
| 98 | ||
| 99 | /// `org-babel--normalize-body`: without the final newline, and without the indentation | |
| 100 | /// common to its lines unless `-i` keeps it. | |
| 101 | static func normalizedBody(_ block: SrcBlockInfo) -> String { | |
| 102 | var lines = block.body.components(separatedBy: "\n") | |
| 103 | if lines.last == "" { lines.removeLast() } | |
| 104 | // Org escapes lines starting with `*` or `#+` inside blocks with a comma. | |
| 105 | lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) } | |
| 106 | if !block.switches.contains("-i") { | |
| 107 | let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count } | |
| 108 | let common = indents.min() ?? 0 | |
| 109 | lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) } | |
| 110 | } | |
| 111 | return lines.joined(separator: "\n") | |
| 112 | } | |
| 113 | } | |
Sources/OrgCore/Compute/BabelResults.swift added +519
| @@ -0,0 +1,519 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Babel { | |
| 4 | // MARK: - Finishing | |
| 5 | ||
| 6 | /// What the run produced, as Babel holds it before inserting. | |
| 7 | enum Value: Equatable { | |
| 8 | case none | |
| 9 | case string(String) | |
| 10 | /// Rows of cells; nil rows are rules. | |
| 11 | case table([[String]?]) | |
| 12 | } | |
| 13 | ||
| 14 | /// The edit that writes the run's result under the block, or why it can't. | |
| 15 | public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> { | |
| 16 | let ns = text as NSString | |
| 17 | var blockRange = job.block | |
| 18 | if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText { | |
| 19 | let found = ns.range(of: job.blockText) | |
| 20 | guard found.location != NSNotFound, | |
| 21 | ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else { | |
| 22 | return .failure(.message("The block changed while it ran; the result wasn't written.")) | |
| 23 | } | |
| 24 | blockRange = found.location..<NSMaxRange(found) | |
| 25 | } | |
| 26 | let value = Self.value(job.finish, output) | |
| 27 | if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) } | |
| 28 | let buffer = EmacsBuffer(text, point: 0, settings: settings) | |
| 29 | if job.finish.inline { | |
| 30 | do { | |
| 31 | try insertInlineResult(value, job.finish, at: blockRange, buffer: buffer) | |
| 32 | } catch let error as Failure { | |
| 33 | return .failure(error) | |
| 34 | } catch { | |
| 35 | return .failure(.message("\(error)")) | |
| 36 | } | |
| 37 | return .success(TextEdit.between(text, buffer.text as String)) | |
| 38 | } | |
| 39 | insertResult(value, job.finish, block: blockRange, buffer: buffer) | |
| 40 | return .success(TextEdit.between(text, buffer.text as String)) | |
| 41 | } | |
| 42 | ||
| 43 | /// The language's result handling: `org-babel-result-cond` and the table import. | |
| 44 | static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value { | |
| 45 | reassemble(rawValue(finish, output), finish) | |
| 46 | } | |
| 47 | ||
| 48 | static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value { | |
| 49 | let params = finish.params | |
| 50 | if params.contains("file") { | |
| 51 | // `org-babel-result-to-file`: a link to `:file`, or to the result as a path. | |
| 52 | let path = finish.file ?? rawResult(finish, output) | |
| 53 | var link = "[[file:" + path + "]" | |
| 54 | if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" } | |
| 55 | return .string(link + "]") | |
| 56 | } | |
| 57 | let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code") | |
| 58 | || params.contains("pp") || params.contains("file") | |
| 59 | || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table")) | |
| 60 | switch finish.kind { | |
| 61 | case .shell(let valueIsExitStatus): | |
| 62 | var results = output.stdout | |
| 63 | if valueIsExitStatus { | |
| 64 | results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? "" | |
| 65 | } | |
| 66 | if scalar { return .string(results) } | |
| 67 | return importTable(results) | |
| 68 | case .generic: | |
| 69 | return .string(output.stdout) | |
| 70 | case .python: | |
| 71 | let raw = finish.output ? output.stdout : (output.resultFile ?? "") | |
| 72 | if scalar { return .string(raw) } | |
| 73 | return pythonValue(raw) | |
| 74 | case .emacsLisp: | |
| 75 | guard let data = output.stdout.data(using: .utf8), | |
| 76 | let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) } | |
| 77 | if scalar { | |
| 78 | return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "") | |
| 79 | } | |
| 80 | if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") } | |
| 81 | if let rows = object["rows"] as? [Any] { | |
| 82 | return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) }) | |
| 83 | } | |
| 84 | let printed = object["S"] as? String ?? "" | |
| 85 | return printed == "nil" ? .none : .string(printed) | |
| 86 | case .compiled: | |
| 87 | return compiledValue(finish, output, scalar: scalar) | |
| 88 | } | |
| 89 | } | |
| 90 | ||
| 91 | /// The result as the program left it, before tables are read. | |
| 92 | static func rawResult(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String { | |
| 93 | switch finish.kind { | |
| 94 | case .python: return finish.output ? output.stdout : (output.resultFile ?? "") | |
| 95 | case .emacsLisp: | |
| 96 | guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout } | |
| 97 | return object["s"] as? String ?? "" | |
| 98 | case .shell(let valueIsExitStatus): | |
| 99 | return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout | |
| 100 | case .generic: return output.stdout | |
| 101 | case .compiled: return compiledResult(finish, output) | |
| 102 | } | |
| 103 | } | |
| 104 | ||
| 105 | /// With `:results file` and `:file`, what to write there, relative to the run's folder; | |
| 106 | /// nil when there's nothing to write or the program wrote it. | |
| 107 | public static func fileResult(_ job: BabelJob, output: BabelOutput) -> (path: String, contents: String)? { | |
| 108 | guard job.finish.params.contains("file"), let file = job.finish.file, !job.finish.writesFile else { return nil } | |
| 109 | return (file, rawResult(job.finish, output)) | |
| 110 | } | |
| 111 | ||
| 112 | /// `org-babel-import-elisp-from-file`. | |
| 113 | static func importTable(_ results: String) -> Value { | |
| 114 | guard !results.isEmpty else { return .none } | |
| 115 | var lines = results.components(separatedBy: "\n") | |
| 116 | if lines.last == "" { lines.removeLast() } | |
| 117 | let nonEmpty = lines.filter { !$0.isEmpty } | |
| 118 | let rows: [[String]] | |
| 119 | if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) { | |
| 120 | rows = lines.map { $0.components(separatedBy: "\t") } | |
| 121 | } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) { | |
| 122 | rows = lines.map(csvFields) | |
| 123 | } else if lines.count == 1 { | |
| 124 | rows = [[lines[0]]] | |
| 125 | } else { | |
| 126 | rows = lines.map { line in | |
| 127 | let trimmed = line.drop { $0 == " " } | |
| 128 | return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty | |
| 129 | ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init) | |
| 130 | } | |
| 131 | } | |
| 132 | let cells = rows.map { row in row.map { field -> String in | |
| 133 | let trimmed = field.trimmingCharacters(in: .whitespaces) | |
| 134 | switch cell(trimmed) { | |
| 135 | case .number(let n): return n | |
| 136 | case .text(let t): return t | |
| 137 | } | |
| 138 | } } | |
| 139 | if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) } | |
| 140 | return .table(cells) | |
| 141 | } | |
| 142 | ||
| 143 | static func csvFields(_ line: String) -> [String] { | |
| 144 | var fields: [String] = [] | |
| 145 | var current = "" | |
| 146 | var quoted = false | |
| 147 | for c in line { | |
| 148 | if c == "\"" { | |
| 149 | quoted.toggle() | |
| 150 | } else if c == ",", !quoted { | |
| 151 | fields.append(current.trimmingCharacters(in: .whitespaces)) | |
| 152 | current = "" | |
| 153 | } else { | |
| 154 | current.append(c) | |
| 155 | } | |
| 156 | } | |
| 157 | fields.append(current.trimmingCharacters(in: .whitespaces)) | |
| 158 | return fields | |
| 159 | } | |
| 160 | ||
| 161 | /// `org-babel-python-table-or-string`; with `none` "null" and `braces`, | |
| 162 | /// `org-babel-java-table-or-string`, which reads `{…}` as a list too. | |
| 163 | static func pythonValue(_ raw: String, none: String = "None", braces: Bool = false) -> Value { | |
| 164 | guard let first = raw.first, let last = raw.last, raw.count >= 2, | |
| 165 | (first == "[" && last == "]") || (first == "(" && last == ")") || (braces && first == "{" && last == "}") else { | |
| 166 | if raw.isEmpty { return .string("") } | |
| 167 | if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) { | |
| 168 | return .string(String(raw.dropFirst().dropLast())) | |
| 169 | } | |
| 170 | if let n = number(raw) { return .string(n) } | |
| 171 | return .string(raw) | |
| 172 | } | |
| 173 | var parser = PythonLiteral(Array(raw)) | |
| 174 | parser.braces = braces | |
| 175 | guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) } | |
| 176 | func text(_ v: PythonLiteral.Node) -> String { | |
| 177 | switch v { | |
| 178 | case .atom(let s): return s | |
| 179 | case .string(let s): return s | |
| 180 | case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")" | |
| 181 | } | |
| 182 | } | |
| 183 | if items.allSatisfy({ if case .list = $0 { return true }; if case .atom(none) = $0 { return true }; return false }) { | |
| 184 | return .table(items.map { item -> [String]? in | |
| 185 | if case .list(let cells) = item { return cells.map(text) } | |
| 186 | return nil | |
| 187 | }) | |
| 188 | } | |
| 189 | return .table([items.map { if case .atom(none) = $0 { return "hline" }; return text($0) }]) | |
| 190 | } | |
| 191 | ||
| 192 | struct PythonLiteral { | |
| 193 | indirect enum Node: Equatable { | |
| 194 | case atom(String) | |
| 195 | case string(String) | |
| 196 | case list([Node]) | |
| 197 | } | |
| 198 | ||
| 199 | let chars: [Character] | |
| 200 | var i = 0 | |
| 201 | /// `{…}` is a list, as `org-babel-script-escape` reads it. | |
| 202 | var braces = false | |
| 203 | init(_ chars: [Character]) { self.chars = chars } | |
| 204 | var atEnd: Bool { mutating get { skip(); return i == chars.count } } | |
| 205 | ||
| 206 | mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } } | |
| 207 | ||
| 208 | mutating func parse() -> Node? { | |
| 209 | skip() | |
| 210 | guard i < chars.count else { return nil } | |
| 211 | let c = chars[i] | |
| 212 | if c == "[" || c == "(" || (braces && c == "{") { | |
| 213 | let close: Character = c == "[" ? "]" : c == "{" ? "}" : ")" | |
| 214 | i += 1 | |
| 215 | var items: [Node] = [] | |
| 216 | skip() | |
| 217 | if i < chars.count, chars[i] == close { | |
| 218 | i += 1 | |
| 219 | return .list(items) | |
| 220 | } | |
| 221 | while true { | |
| 222 | guard let item = parse() else { return nil } | |
| 223 | items.append(item) | |
| 224 | skip() | |
| 225 | guard i < chars.count else { return nil } | |
| 226 | if chars[i] == "," { | |
| 227 | i += 1 | |
| 228 | skip() | |
| 229 | if i < chars.count, chars[i] == close { | |
| 230 | i += 1 | |
| 231 | return .list(items) | |
| 232 | } | |
| 233 | continue | |
| 234 | } | |
| 235 | if chars[i] == close { | |
| 236 | i += 1 | |
| 237 | return .list(items) | |
| 238 | } | |
| 239 | return nil | |
| 240 | } | |
| 241 | } | |
| 242 | if c == "'" || c == "\"" { | |
| 243 | i += 1 | |
| 244 | var s = "" | |
| 245 | while i < chars.count, chars[i] != c { | |
| 246 | if chars[i] == "\\", i + 1 < chars.count { | |
| 247 | i += 1 | |
| 248 | switch chars[i] { | |
| 249 | case "n": s.append("\n") | |
| 250 | case "t": s.append("\t") | |
| 251 | default: s.append(chars[i]) | |
| 252 | } | |
| 253 | } else { | |
| 254 | s.append(chars[i]) | |
| 255 | } | |
| 256 | i += 1 | |
| 257 | } | |
| 258 | guard i < chars.count else { return nil } | |
| 259 | i += 1 | |
| 260 | return .string(s) | |
| 261 | } | |
| 262 | var s = "" | |
| 263 | while i < chars.count, !",)] \n".contains(chars[i]), !(braces && chars[i] == "}") { | |
| 264 | s.append(chars[i]) | |
| 265 | i += 1 | |
| 266 | } | |
| 267 | guard !s.isEmpty else { return nil } | |
| 268 | return .atom(number(s) ?? s) | |
| 269 | } | |
| 270 | } | |
| 271 | ||
| 272 | // MARK: - Inserting | |
| 273 | ||
| 274 | static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:" | |
| 275 | ||
| 276 | /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results | |
| 277 | /// keyword, added when there is none. | |
| 278 | /// The `#+RESULTS` line of a block's results (`org-babel-where-is-src-block-result`): | |
| 279 | /// the one naming `name`, or for an unnamed block an empty one right after it. | |
| 280 | static func existingResults(name: String?, block: Range<Int>, text ns: NSString) -> Int? { | |
| 281 | if let name { | |
| 282 | let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$" | |
| 283 | let regex = try! NSRegularExpression(pattern: pattern) | |
| 284 | return regex.firstMatch(in: ns as String, range: NSRange(location: 0, length: ns.length))?.range.location | |
| 285 | } | |
| 286 | // The element after the block, past blank lines. | |
| 287 | var location = block.upperBound | |
| 288 | while location < ns.length { | |
| 289 | let line = ns.lineRange(for: NSRange(location: location, length: 0)) | |
| 290 | let content = ns.substring(with: line) | |
| 291 | if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { | |
| 292 | location = NSMaxRange(line) | |
| 293 | continue | |
| 294 | } | |
| 295 | if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil { | |
| 296 | return line.location | |
| 297 | } | |
| 298 | break | |
| 299 | } | |
| 300 | return nil | |
| 301 | } | |
| 302 | ||
| 303 | /// The hash in the `#+RESULTS[…]:` line at `line` (`org-babel-result-regexp`). | |
| 304 | static func resultsHash(at line: Int, text ns: NSString) -> String? { | |
| 305 | let content = ns.substring(with: ns.lineRange(for: NSRange(location: line, length: 0))) | |
| 306 | return content.firstMatch(of: #/(?i)^[ \t]*#\+results\[(?:\(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\) )?([0-9a-f]+)\]:/#).map { String($0.1) } | |
| 307 | } | |
| 308 | ||
| 309 | static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int { | |
| 310 | if let line = existingResults(name: finish.name, block: block, text: buffer.text) { | |
| 311 | // `org-babel--clear-results-maybe`: a different hash clears the results and | |
| 312 | // rewrites the keyword. | |
| 313 | if let hash = finish.hash, resultsHash(at: line, text: buffer.text) != hash { | |
| 314 | buffer.point = line | |
| 315 | let indent = String(buffer.substring(line, buffer.lineEnd(line)).prefix { $0 == " " || $0 == "\t" }) | |
| 316 | buffer.forwardLine(1) | |
| 317 | let contents = buffer.point | |
| 318 | buffer.deleteRegion(contents, max(contents, resultEnd(buffer))) | |
| 319 | buffer.deleteRegion(line, contents) | |
| 320 | buffer.point = line | |
| 321 | buffer.insert(indent + "#+RESULTS[\(hash)]:" + (finish.name.map { " " + $0 } ?? "") + "\n") | |
| 322 | if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil { | |
| 323 | buffer.saveExcursion { buffer.insert("\n") } | |
| 324 | } | |
| 325 | } | |
| 326 | return line | |
| 327 | } | |
| 328 | // A new keyword after the block. | |
| 329 | buffer.point = min(block.upperBound, buffer.length) | |
| 330 | buffer.skipBackward([32, 9, 10, 13]) | |
| 331 | buffer.forwardLine(1) | |
| 332 | if !buffer.bolp { buffer.insert("\n") } | |
| 333 | let indent = buffer.saveExcursion { () -> String in | |
| 334 | buffer.point = block.lowerBound | |
| 335 | let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point)) | |
| 336 | return String(line.prefix { $0 == " " || $0 == "\t" }) | |
| 337 | } | |
| 338 | buffer.insert("\n") | |
| 339 | let keywordLine = buffer.point | |
| 340 | buffer.insert(indent + "#+RESULTS" + (finish.hash.map { "[\($0)]" } ?? "") + ":" + (finish.name.map { " " + $0 } ?? "") + "\n") | |
| 341 | if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil { | |
| 342 | buffer.saveExcursion { buffer.insert("\n") } | |
| 343 | } | |
| 344 | return keywordLine | |
| 345 | } | |
| 346 | ||
| 347 | /// `org-babel-result-end` with point at the start of the result. | |
| 348 | static func resultEnd(_ buffer: EmacsBuffer) -> Int { | |
| 349 | let start = buffer.point | |
| 350 | let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start)) | |
| 351 | if line.trimmingCharacters(in: .whitespaces).isEmpty { return start } | |
| 352 | if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil { | |
| 353 | return min(buffer.length, buffer.lineEnd(start) + 1) | |
| 354 | } | |
| 355 | let tree = OrgParser.parse(buffer.text as String) | |
| 356 | var node = tree.root | |
| 357 | var found: SyntaxNode? | |
| 358 | while let child = node.child(containing: start) { | |
| 359 | if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) { | |
| 360 | if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) { | |
| 361 | found = child | |
| 362 | break | |
| 363 | } | |
| 364 | } | |
| 365 | node = child | |
| 366 | } | |
| 367 | guard let element = found else { return start } | |
| 368 | var end = element.range.upperBound | |
| 369 | while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 } | |
| 370 | return min(buffer.length, buffer.lineEnd(end) + 1) | |
| 371 | } | |
| 372 | ||
| 373 | /// `org-babel-insert-result` for a src block. | |
| 374 | /// An inline block's result, after it: ` {{{results(=value=)}}}`, replacing one already | |
| 375 | /// there; raw results go in as they are. | |
| 376 | static func insertInlineResult(_ value: Value, _ finish: BabelJob.Finish, at object: Range<Int>, buffer: EmacsBuffer) throws { | |
| 377 | var string: String | |
| 378 | switch value { | |
| 379 | case .none: string = "" | |
| 380 | case .string(let s): string = s | |
| 381 | case .table(let rows): | |
| 382 | let cells = rows.compactMap { $0 } | |
| 383 | guard cells.count == 1, cells[0].count == 1 else { throw Failure.message("Inline source block results can't be tables or lists") } | |
| 384 | string = cells[0][0] | |
| 385 | } | |
| 386 | buffer.point = object.upperBound | |
| 387 | if let existing = buffer.lookingAt("[ \\t]*\\{\\{\\{results\\(.*?\\)\\}\\}\\}") { | |
| 388 | buffer.deleteRegion(existing[0]!.lowerBound, existing[0]!.upperBound) | |
| 389 | } | |
| 390 | if finish.params.contains("raw") { | |
| 391 | buffer.insert(" " + string) | |
| 392 | return | |
| 393 | } | |
| 394 | if string.hasSuffix("\n") { string.removeLast() } | |
| 395 | guard !string.contains("\n") else { throw Failure.message("Inline source block results must be one line") } | |
| 396 | buffer.insert(" {{{results(=" + string + "=)}}}") | |
| 397 | } | |
| 398 | ||
| 399 | static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) { | |
| 400 | let params = finish.params | |
| 401 | let keyword = resultsLine(finish, block: block, buffer: buffer) | |
| 402 | buffer.point = keyword | |
| 403 | let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count | |
| 404 | buffer.forwardLine(1) | |
| 405 | if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") } | |
| 406 | var beg = buffer.point | |
| 407 | if params.contains("replace") { | |
| 408 | buffer.deleteRegion(beg, resultEnd(buffer)) | |
| 409 | buffer.point = beg | |
| 410 | } else if params.contains("append") { | |
| 411 | buffer.point = resultEnd(buffer) | |
| 412 | beg = buffer.point | |
| 413 | } | |
| 414 | var tabulated = false | |
| 415 | // A list made from a string is examplified, as a string result is. | |
| 416 | var listed = false | |
| 417 | switch value { | |
| 418 | case .none: | |
| 419 | break | |
| 420 | case .string(var s) where params.contains("list"): | |
| 421 | if s.last != "\n" { s += "\n" } | |
| 422 | let items = s.split(separator: "\n", omittingEmptySubsequences: true) | |
| 423 | buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n") | |
| 424 | case .table(let rows) where params.contains("list"): | |
| 425 | listed = true | |
| 426 | let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") } | |
| 427 | buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n") | |
| 428 | case .table(let rows): | |
| 429 | tabulated = true | |
| 430 | let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" } | |
| 431 | let start = buffer.point | |
| 432 | buffer.insert(lines.joined(separator: "\n") + "\n") | |
| 433 | buffer.point = start | |
| 434 | buffer.tableAlign() | |
| 435 | buffer.point = buffer.tableEnd() | |
| 436 | case .string(var s): | |
| 437 | if !s.isEmpty, s.last != "\n" { s += "\n" } | |
| 438 | buffer.insert(s) | |
| 439 | } | |
| 440 | let end = buffer.marker(buffer.point, advances: true) | |
| 441 | defer { buffer.release(end) } | |
| 442 | func wrap(_ open: String, _ close: String, escape: Bool) { | |
| 443 | buffer.point = end.position | |
| 444 | buffer.insert(close + "\n") | |
| 445 | buffer.point = beg | |
| 446 | buffer.insert(open + "\n") | |
| 447 | if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) } | |
| 448 | } | |
| 449 | if let wrapValue = finish.wrap { | |
| 450 | let full = wrapValue.isEmpty ? "results" : wrapValue | |
| 451 | let type = String(full.split(separator: " ").first ?? "results") | |
| 452 | if type.lowercased() != "nil", type.lowercased() != "no" { | |
| 453 | wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true) | |
| 454 | } | |
| 455 | } else if params.contains("html") { | |
| 456 | wrap("#+begin_export html", "#+end_export", escape: true) | |
| 457 | } else if params.contains("latex") { | |
| 458 | wrap("#+begin_export latex", "#+end_export", escape: true) | |
| 459 | } else if params.contains("org") { | |
| 460 | wrap("#+begin_src org", "#+end_src", escape: true) | |
| 461 | } else if params.contains("code") { | |
| 462 | wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true) | |
| 463 | } else if params.contains("raw") || params.contains("file") { | |
| 464 | // As inserted. | |
| 465 | } else if params.contains("drawer") { | |
| 466 | wrap(":results:", ":end:", escape: false) | |
| 467 | } else if !tabulated, !(params.contains("list") && listed) { | |
| 468 | examplify(buffer, beg, end.position) | |
| 469 | } | |
| 470 | if indent > 0, !(tabulated && params.contains("append")) { | |
| 471 | buffer.point = beg | |
| 472 | while buffer.point < end.position { | |
| 473 | if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) } | |
| 474 | if buffer.forwardLine(1) != 0 { break } | |
| 475 | } | |
| 476 | } | |
| 477 | } | |
| 478 | ||
| 479 | /// `org-escape-code-in-region`. | |
| 480 | static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) { | |
| 481 | buffer.point = start | |
| 482 | let stop = buffer.marker(end) | |
| 483 | defer { buffer.release(stop) } | |
| 484 | while buffer.point < stop.position { | |
| 485 | let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point)) | |
| 486 | if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) { | |
| 487 | buffer.point += line[..<m.1.startIndex].utf16.count | |
| 488 | buffer.insert(",") | |
| 489 | } | |
| 490 | if buffer.forwardLine(1) != 0 { break } | |
| 491 | } | |
| 492 | } | |
| 493 | ||
| 494 | /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block. | |
| 495 | static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) { | |
| 496 | let text = buffer.substring(beg, end) | |
| 497 | var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0) | |
| 498 | if text.isEmpty { size = 0 } | |
| 499 | guard size > 0 else { return } | |
| 500 | if size < 10 { | |
| 501 | buffer.point = beg | |
| 502 | for _ in 0..<size { | |
| 503 | buffer.point = buffer.lineStart(buffer.point) | |
| 504 | buffer.insert(": ") | |
| 505 | buffer.forwardLine(1) | |
| 506 | } | |
| 507 | return | |
| 508 | } | |
| 509 | let endMarker = buffer.marker(end) | |
| 510 | defer { buffer.release(endMarker) } | |
| 511 | buffer.point = beg | |
| 512 | buffer.insert("#+begin_example\n") | |
| 513 | escapeCode(buffer, from: buffer.point, to: endMarker.position) | |
| 514 | buffer.point = endMarker.position | |
| 515 | if !buffer.bolp { buffer.insert("\n") } | |
| 516 | buffer.insert("#+end_example") | |
| 517 | if !buffer.eolp { buffer.insert("\n") } | |
| 518 | } | |
| 519 | } | |
Sources/OrgCore/Compute/BabelVars.swift added +334
| @@ -0,0 +1,334 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Babel { | |
| 4 | // MARK: - Tables in variables | |
| 5 | ||
| 6 | /// Variables after `org-babel-disassemble-tables`, with the names taken off their tables. | |
| 7 | struct Tables { | |
| 8 | var vars: [(String, VarValue)] = [] | |
| 9 | var colnames: [(name: String, names: [Cell])] = [] | |
| 10 | var rownames: [(name: String, names: [Cell])] = [] | |
| 11 | ||
| 12 | /// `org-babel-pick-name`: a Lisp list given as the header argument, or the last | |
| 13 | /// variable's names, unless the header argument is absent, whose `nil` selects none. | |
| 14 | func picked(_ names: [(name: String, names: [Cell])], _ key: String, _ params: Params) -> [String]? { | |
| 15 | if let list = params.evaluated[key].flatMap(Babel.lispNames) { return list } | |
| 16 | guard params.single[key] != nil, let last = names.last else { return nil } | |
| 17 | return last.names.map(Babel.cellText) | |
| 18 | } | |
| 19 | } | |
| 20 | ||
| 21 | /// A Lisp list of strings and numbers, as names. | |
| 22 | static func lispNames(_ value: Sexp) -> [String]? { | |
| 23 | guard case .list(let items) = value else { return nil } | |
| 24 | return try? items.map { item in | |
| 25 | if let s = item.string { return s } | |
| 26 | let printed = Elisp.printed(item) | |
| 27 | guard number(printed) == printed else { throw Failure.message(printed) } | |
| 28 | return printed | |
| 29 | } | |
| 30 | } | |
| 31 | ||
| 32 | static func cellText(_ c: Cell) -> String { | |
| 33 | switch c { | |
| 34 | case .number(let n): n | |
| 35 | case .text(let s): s | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | /// `org-babel-disassemble-tables`: a table's header row comes off when `:colnames` asks, or | |
| 40 | /// by default when only its second row is a rule; its first column with `:rownames`; its | |
| 41 | /// rules unless `:hlines yes`. | |
| 42 | static func disassemble(_ vars: [(String, VarValue)], params: Params) throws -> Tables { | |
| 43 | for key in [":colnames", ":rownames"] where params.lisp.contains(key) && params.evaluated[key].flatMap(lispNames) == nil { | |
| 44 | throw Failure.message("\(key) \(params.single[key] ?? "") is Lisp that only Emacs can evaluate; nothing was run.") | |
| 45 | } | |
| 46 | let colnames = params.single[":colnames"] | |
| 47 | let rownames = params.single[":rownames"] | |
| 48 | let hlines = params.single[":hlines"] ?? "no" | |
| 49 | var tables = Tables() | |
| 50 | for (name, value) in vars { | |
| 51 | guard case .table(var rows) = value else { | |
| 52 | tables.vars.append((name, value)) | |
| 53 | continue | |
| 54 | } | |
| 55 | let auto = rows.count > 1 && rows[0] != nil && rows[1] == nil && !rows.dropFirst(2).contains(where: { $0 == nil }) | |
| 56 | if colnames != "no", colnames != nil || auto { | |
| 57 | while let first = rows.first, first == nil { rows.removeFirst() } | |
| 58 | if let header = rows.first ?? nil { | |
| 59 | rows.removeFirst(rows.count > 1 && rows[1] == nil ? 2 : 1) | |
| 60 | tables.colnames.append((name, header)) | |
| 61 | } | |
| 62 | } | |
| 63 | if let rownames, rownames != "no" { | |
| 64 | let kept = rows.compactMap { $0 } | |
| 65 | tables.rownames.append((name, kept.map { $0.first ?? .text("") })) | |
| 66 | rows = kept.map { Array($0.dropFirst()) } | |
| 67 | } | |
| 68 | if hlines != "yes" { rows = rows.filter { $0 != nil } } | |
| 69 | tables.vars.append((name, .table(rows))) | |
| 70 | } | |
| 71 | return tables | |
| 72 | } | |
| 73 | ||
| 74 | /// `org-babel-reassemble-table` on a result. | |
| 75 | static func reassemble(_ value: Value, _ finish: BabelJob.Finish) -> Value { | |
| 76 | guard case .table(var rows) = value else { return value } | |
| 77 | if let names = finish.rownames, names.count == rows.count { | |
| 78 | var next = names.makeIterator() | |
| 79 | rows = rows.map { row in row.map { [next.next() ?? ""] + $0 } } | |
| 80 | } | |
| 81 | if let names = finish.colnames, let first = rows.first ?? nil, first.count == names.count { | |
| 82 | rows = [names, nil] + rows | |
| 83 | } | |
| 84 | return .table(rows) | |
| 85 | } | |
| 86 | ||
| 87 | /// A `:var` value that is Lisp (`org-babel-read`): evaluated, as a number, string, list or | |
| 88 | /// table. | |
| 89 | static func lispValue(_ value: String) throws -> VarValue { | |
| 90 | let refusal = Failure.message(":var value \(value) is Lisp that only Emacs can evaluate.") | |
| 91 | guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form) else { throw refusal } | |
| 92 | func cell(_ v: Sexp) throws -> Cell { | |
| 93 | if let s = v.string { return .text(s) } | |
| 94 | if let n = number(Elisp.printed(v)), Elisp.printed(v) == n { return .number(n) } | |
| 95 | throw refusal | |
| 96 | } | |
| 97 | if let s = result.string { return .scalar(s) } | |
| 98 | if case .list(let items) = result, !items.isEmpty { | |
| 99 | if items.allSatisfy({ if case .list = $0 { return true }; return $0 == .symbol("hline") }) { | |
| 100 | return .table(try items.map { item in | |
| 101 | if item == .symbol("hline") { return nil } | |
| 102 | guard case .list(let cells) = item else { throw refusal } | |
| 103 | return try cells.map(cell) | |
| 104 | }) | |
| 105 | } | |
| 106 | return .list(try items.map(cell)) | |
| 107 | } | |
| 108 | if case .number(let n) = try? cell(result) { return .number(n) } | |
| 109 | throw refusal | |
| 110 | } | |
| 111 | ||
| 112 | // MARK: - Variables | |
| 113 | ||
| 114 | /// A referenced block's result as a `:var` value. | |
| 115 | static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> VarValue { | |
| 116 | switch value(finish, output) { | |
| 117 | case .none: return .scalar("") | |
| 118 | case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s) | |
| 119 | case .table(let rows): return .table(rows.map { $0?.map(cell) }) | |
| 120 | } | |
| 121 | } | |
| 122 | ||
| 123 | enum VarValue: Equatable, Sendable { | |
| 124 | case scalar(String) | |
| 125 | case number(String) | |
| 126 | /// Rows; nil is a rule (`hline`). | |
| 127 | case table([[Cell]?]) | |
| 128 | case list([Cell]) | |
| 129 | } | |
| 130 | ||
| 131 | enum Cell: Equatable, Sendable { | |
| 132 | case text(String) | |
| 133 | case number(String) | |
| 134 | } | |
| 135 | ||
| 136 | /// `org-babel--string-to-number`, keeping Emacs's printed form. | |
| 137 | static func number(_ s: String) -> String? { | |
| 138 | let t = s.trimmingCharacters(in: .whitespaces) | |
| 139 | guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil } | |
| 140 | if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil { | |
| 141 | var digits = t.hasSuffix(".") ? String(t.dropLast()) : t | |
| 142 | let negative = digits.hasPrefix("-") | |
| 143 | if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() } | |
| 144 | digits = String(digits.drop { $0 == "0" }) | |
| 145 | if digits.isEmpty { return "0" } | |
| 146 | return (negative ? "-" : "") + digits | |
| 147 | } | |
| 148 | guard t.range(of: "^[-+]?([0-9]+\\.[0-9]+|[0-9]*\\.[0-9]+|[0-9]+(\\.[0-9]*)?e[-+]?[0-9]+|[0-9]*\\.[0-9]+e[-+]?[0-9]+)$", options: .regularExpression) != nil, | |
| 149 | let d = Double(t) else { return nil } | |
| 150 | return emacsFloat(d) | |
| 151 | } | |
| 152 | ||
| 153 | /// How Emacs prints a float. | |
| 154 | static func emacsFloat(_ d: Double) -> String { | |
| 155 | if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) } | |
| 156 | return "\(d)" | |
| 157 | } | |
| 158 | ||
| 159 | static func cell(_ s: String) -> Cell { | |
| 160 | var t = s | |
| 161 | if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) } | |
| 162 | return number(t).map(Cell.number) ?? .text(t) | |
| 163 | } | |
| 164 | ||
| 165 | /// `name` or `name(args)` naming a src block in the file: the block and its call arguments. | |
| 166 | static func referencedBlock(_ value: String, model: DocumentModel) -> (block: SrcBlockInfo, arguments: String?)? { | |
| 167 | guard let m = value.firstMatch(of: /^([^\s()\[\]"]+)(?:\((.*)\))?$/), | |
| 168 | let block = model.srcBlocks.first(where: { $0.name == String(m.1) }) else { return nil } | |
| 169 | return (block, m.2.map(String.init)) | |
| 170 | } | |
| 171 | ||
| 172 | /// The blocks `params`' references run, directly or through theirs. | |
| 173 | static func referencedBlocks(_ params: Params, model: DocumentModel, text: NSString, seen: Set<String>) -> [SrcBlockInfo] { | |
| 174 | var found: [SrcBlockInfo] = [] | |
| 175 | var seen = seen | |
| 176 | for value in params.vars.map(\.value) + [params.single[":stdin"]].compactMap({ $0 }) { | |
| 177 | guard let (block, arguments) = referencedBlock(value, model: model), let name = block.name, seen.insert(name).inserted else { continue } | |
| 178 | found.append(block) | |
| 179 | let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? [] | |
| 180 | if let inner = try? Params(block: block, model: model, text: text, extra: extra) { | |
| 181 | found += referencedBlocks(inner, model: model, text: text, seen: seen) | |
| 182 | } | |
| 183 | } | |
| 184 | return found | |
| 185 | } | |
| 186 | ||
| 187 | /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src | |
| 188 | /// blocks, which run first (`Needed`) and give their result. | |
| 189 | static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References) throws -> VarValue { | |
| 190 | if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) } | |
| 191 | if let n = number(value) { return .number(n) } | |
| 192 | if let first = value.first, "('`[".contains(first) { return try lispValue(value) } | |
| 193 | if let known = refs.resolved[value] { return known } | |
| 194 | if let (block, arguments) = referencedBlock(value, model: model), let name = block.name { | |
| 195 | guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through :var") } | |
| 196 | let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? [] | |
| 197 | var inner = refs | |
| 198 | inner.visiting.insert(name) | |
| 199 | var params = try Params(block: block, model: model, text: text, extra: extra) | |
| 200 | params.evaluateLisp(file: refs.options.file) | |
| 201 | // A cached block gives its result without running, as `org-babel-execute-src-block` does. | |
| 202 | var useCache = true | |
| 203 | if params.single[":cache"] == "yes", let language = block.language { | |
| 204 | let tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: text, refs: inner)) }, params: params) | |
| 205 | let body = nowebEvaluates(params.single[":noweb"]) ? try expandNoweb(block, params: params, model: model, text: text) : normalizedBody(block) | |
| 206 | let state = try cacheState(language: language, params: params, tables: tables, body: body, location: block.range, name: name, call: false, text: text, options: refs.options, model: model) | |
| 207 | if state.current { | |
| 208 | if let value = state.value { return value } | |
| 209 | useCache = false | |
| 210 | } | |
| 211 | } | |
| 212 | switch plan(block, params: params, model: model, text: text, | |
| 213 | options: refs.options, location: block.range, name: name, refs: inner, useCache: useCache) { | |
| 214 | case .failure(let failure): throw failure | |
| 215 | case .success(let job): | |
| 216 | throw Needed(need: job.needs.first ?? BabelJob.Need(reference: value, job: job)) | |
| 217 | } | |
| 218 | } | |
| 219 | if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") } | |
| 220 | // A named element: `#+NAME: value` above a table or list. | |
| 221 | let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$" | |
| 222 | guard let r = (text as String).range(of: pattern, options: .regularExpression) else { | |
| 223 | throw Failure.message("Can't find \(value) for :var.") | |
| 224 | } | |
| 225 | let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String))) | |
| 226 | var location = start | |
| 227 | var rows: [[Cell]?] = [] | |
| 228 | var items: [Cell] = [] | |
| 229 | while location < text.length { | |
| 230 | let lineRange = text.lineRange(for: NSRange(location: location, length: 0)) | |
| 231 | let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines) | |
| 232 | let trimmed = line.trimmingCharacters(in: .whitespaces) | |
| 233 | if trimmed.hasPrefix("|") { | |
| 234 | if trimmed.hasPrefix("|-") { | |
| 235 | rows.append(nil) | |
| 236 | location = NSMaxRange(lineRange) | |
| 237 | continue | |
| 238 | } | |
| 239 | let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) } | |
| 240 | rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell)) | |
| 241 | } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty { | |
| 242 | items.append(cell(String(m.1))) | |
| 243 | } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) { | |
| 244 | if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") { | |
| 245 | throw Failure.message("Using a src block's result in :var isn't supported yet.") | |
| 246 | } | |
| 247 | break | |
| 248 | } else { | |
| 249 | break | |
| 250 | } | |
| 251 | location = NSMaxRange(lineRange) | |
| 252 | } | |
| 253 | if !rows.isEmpty { return .table(rows) } | |
| 254 | if !items.isEmpty { return .list(items) } | |
| 255 | throw Failure.message("\(value) isn't a table or list.") | |
| 256 | } | |
| 257 | ||
| 258 | /// `org-babel-sh-var-to-string`: a table's rows as tab-separated lines, a list's items as | |
| 259 | /// lines. | |
| 260 | static func shellString(_ value: VarValue, separator: String? = nil, hline: String? = nil) -> String { | |
| 261 | switch value { | |
| 262 | case .scalar(let s), .number(let s): return s | |
| 263 | case .list(let items): return items.map(cellText).joined(separator: "\n") | |
| 264 | case .table(let rows): return rows.compactMap { $0?.map(cellText).joined(separator: separator ?? "\t") ?? hline }.joined(separator: "\n") | |
| 265 | } | |
| 266 | } | |
| 267 | ||
| 268 | /// `org-babel-variable-assignments:shell`, by the shell's name: for bash, an array for a | |
| 269 | /// list and an associative array for a table of two or more columns; `set` for fish; a | |
| 270 | /// quoted string otherwise. | |
| 271 | static func shellAssignments(_ vars: [(String, VarValue)], shell: String, params: Params) -> [String] { | |
| 272 | let separator = params.single[":separator"] | |
| 273 | let hline = params.single[":hlines"] == "yes" ? params.single[":hline-string"] ?? "hline" : nil | |
| 274 | func quoted(_ value: VarValue) -> String { | |
| 275 | "'" + shellString(value, separator: separator, hline: hline).replacingOccurrences(of: "'", with: "'\"'\"'") + "'" | |
| 276 | } | |
| 277 | return vars.map { name, value in | |
| 278 | if shell.hasSuffix("bash") { | |
| 279 | switch value { | |
| 280 | case .table(let rows) where (rows.first ?? nil).map({ $0.count >= 2 }) ?? false: | |
| 281 | let entries = rows.compactMap { $0 }.map { row in | |
| 282 | "\(name)[\(quoted(.scalar(cellText(row[0]))))]=\(quoted(.list(Array(row.dropFirst()))))" | |
| 283 | } | |
| 284 | return (["unset \(name)", "declare -A \(name)"] + entries).joined(separator: "\n") | |
| 285 | case .table(let rows): | |
| 286 | let items = rows.map { $0.map { quoted(.list($0)) } ?? quoted(.scalar("hline")) } | |
| 287 | return "unset \(name)\ndeclare -a \(name)=( \(items.joined(separator: " ")) )" | |
| 288 | case .list(let items): | |
| 289 | return "unset \(name)\ndeclare -a \(name)=( \(items.map { quoted(.scalar(cellText($0))) }.joined(separator: " ")) )" | |
| 290 | case .scalar, .number: | |
| 291 | break | |
| 292 | } | |
| 293 | } | |
| 294 | return (shell.hasSuffix("fish") ? "set \(name) " : "\(name)=") + quoted(value) | |
| 295 | } | |
| 296 | } | |
| 297 | ||
| 298 | /// `org-babel-python-var-to-python`. | |
| 299 | static func pythonLiteral(_ value: VarValue) -> String { | |
| 300 | func cell(_ c: Cell) -> String { | |
| 301 | switch c { | |
| 302 | case .number(let n): return n | |
| 303 | case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r")) | |
| 304 | } | |
| 305 | } | |
| 306 | switch value { | |
| 307 | case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r")) | |
| 308 | case .number(let n): return n | |
| 309 | case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]" | |
| 310 | case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", ") + "]" } ?? "None" }.joined(separator: ", ") + "]" | |
| 311 | } | |
| 312 | } | |
| 313 | ||
| 314 | /// `prin1` of a string. | |
| 315 | static func lispString(_ s: String, triple: Bool = false) -> String { | |
| 316 | let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" | |
| 317 | return triple ? "\"\"" + quoted + "\"\"" : quoted | |
| 318 | } | |
| 319 | ||
| 320 | static func lispLiteral(_ value: VarValue) -> String { | |
| 321 | func cell(_ c: Cell) -> String { | |
| 322 | switch c { | |
| 323 | case .number(let n): return n | |
| 324 | case .text(let s): return lispString(s) | |
| 325 | } | |
| 326 | } | |
| 327 | switch value { | |
| 328 | case .scalar(let s): return lispString(s) | |
| 329 | case .number(let n): return n | |
| 330 | case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")" | |
| 331 | case .table(let rows): return "(" + rows.map { $0.map { "(" + $0.map(cell).joined(separator: " ") + ")" } ?? "hline" }.joined(separator: " ") + ")" | |
| 332 | } | |
| 333 | } | |
| 334 | } | |
Sources/OrgCore/Compute/TableFormulaCommands.swift added +337
| @@ -0,0 +1,337 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the | |
| 4 | /// native evaluator can't do fail with `TableRecalculate.emacsMessage`, and the app | |
| 5 | /// recalculates them in Emacs. | |
| 6 | public struct TableRecalculate: OrgCommand { | |
| 7 | public let all: Bool | |
| 8 | public init(all: Bool) { self.all = all } | |
| 9 | public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" } | |
| 10 | public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" } | |
| 11 | ||
| 12 | public static let emacsMessage = "needs Emacs: " | |
| 13 | ||
| 14 | public func applies(in context: EditContext) -> Bool { | |
| 15 | KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil | |
| 16 | } | |
| 17 | ||
| 18 | static func tblfmLine(in context: EditContext) -> String? { | |
| 19 | let buffer = EmacsBuffer(context.text, point: context.caret) | |
| 20 | let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point)) | |
| 21 | guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil } | |
| 22 | return line | |
| 23 | } | |
| 24 | ||
| 25 | public func run(in context: EditContext) -> CommandStep { | |
| 26 | let step = commitBuffer(context) { buffer in | |
| 27 | do { | |
| 28 | if let line = Self.tblfmLine(in: context) { | |
| 29 | // `org-table-calc-current-TBLFM`: that line's formulas, every row, with | |
| 30 | // point at the end of the table. | |
| 31 | let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " ")) | |
| 32 | let saved = buffer.marker(buffer.point) | |
| 33 | defer { buffer.release(saved) } | |
| 34 | guard let tableEnd = buffer.saveExcursion({ () -> Int? in | |
| 35 | while buffer.forwardLine(-1) == 0 { | |
| 36 | if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) } | |
| 37 | } | |
| 38 | return nil | |
| 39 | }) else { throw EmacsBuffer.UserError(message: "Not at a table") } | |
| 40 | buffer.point = tableEnd | |
| 41 | try buffer.tableRecalculate(all: true, tblfm: formulas) | |
| 42 | buffer.point = saved.position | |
| 43 | } else { | |
| 44 | try buffer.tableRecalculate(all: all) | |
| 45 | } | |
| 46 | } catch let error as Calc.Unsupported { | |
| 47 | throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason) | |
| 48 | } | |
| 49 | } | |
| 50 | let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)" | |
| 51 | return Self.inEmacs(step, form: form, in: context) | |
| 52 | } | |
| 53 | ||
| 54 | /// A step that failed with `emacsMessage` as a request to run `form` on the table in | |
| 55 | /// Emacs, whose text then replaces the table here; other steps unchanged. | |
| 56 | static func inEmacs(_ step: CommandStep, form: String, in context: EditContext) -> CommandStep { | |
| 57 | guard case .failed(let message) = step, message.hasPrefix(emacsMessage) else { return step } | |
| 58 | let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options) | |
| 59 | let onTblfm = tblfmLine(in: context) != nil | |
| 60 | if onTblfm { | |
| 61 | while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {} | |
| 62 | } | |
| 63 | let table = buffer.tableBegin()..<buffer.tableEnd() | |
| 64 | let tblfm = onTblfm ? tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? "" | |
| 65 | return .external(.emacsTable( | |
| 66 | table: table, point: context.caret, form: form, | |
| 67 | reason: String(message.dropFirst(emacsMessage.count)), lisp: tblfm.contains("'(") | |
| 68 | )) | |
| 69 | } | |
| 70 | } | |
| 71 | ||
| 72 | // Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`). | |
| 73 | extension EmacsBuffer { | |
| 74 | /// `org-table-formula-make-cmp-string`. | |
| 75 | static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? { | |
| 76 | var a = lhs | |
| 77 | if let arrow = a.firstMatch(of: /^\$([<>])/) { | |
| 78 | a = (try? handleFirstLast(a, analysis: analysis)) ?? a | |
| 79 | a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))" | |
| 80 | } | |
| 81 | guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil } | |
| 82 | var key = "" | |
| 83 | if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) } | |
| 84 | if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) } | |
| 85 | if let name = m.5 { key += "@@" + name } | |
| 86 | return key | |
| 87 | } | |
| 88 | ||
| 89 | /// `sort` with `org-table-formula-less-p`. | |
| 90 | static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] { | |
| 91 | var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = [] | |
| 92 | // Stable insertion, as `sort` with a partial predicate. | |
| 93 | for formula in formulas { | |
| 94 | let key = formulaSortKey(formula.lhs, analysis: analysis) | |
| 95 | var index = sorted.count | |
| 96 | while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 } | |
| 97 | sorted.insert((formula, key), at: index) | |
| 98 | } | |
| 99 | return sorted.map(\.formula) | |
| 100 | } | |
| 101 | ||
| 102 | /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`. | |
| 103 | func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) { | |
| 104 | let sorted = Self.sortFormulas(formulas, analysis: analysis) | |
| 105 | saveExcursion { | |
| 106 | point = tableEnd() | |
| 107 | if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) { | |
| 108 | deleteRegion(match[3]!.lowerBound, match[0]!.upperBound) | |
| 109 | point = match[3]!.lowerBound | |
| 110 | } else { | |
| 111 | insert("#+TBLFM:") | |
| 112 | } | |
| 113 | insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n") | |
| 114 | } | |
| 115 | } | |
| 116 | ||
| 117 | /// `org-table-get-formula`: stores EQUATION for the current column, or with `named` the | |
| 118 | /// current field, and returns it; nil when a blank EQUATION removed the formula. `read` | |
| 119 | /// when EQUATION is the prompt's answer, which the stored formula never replaces. | |
| 120 | func tableGetFormula(_ equation: String, named: Bool, read: Bool = false, analysis: TableAnalysis) throws -> String? { | |
| 121 | var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "") | |
| 122 | let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())" | |
| 123 | let scol = named ? ref : "$\(tableCurrentColumn())" | |
| 124 | let old = stored.first { $0.lhs == scol }?.rhs | |
| 125 | var eq = !read && old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation | |
| 126 | guard eq.contains(where: { !$0.isWhitespace }) else { | |
| 127 | stored.removeAll { $0.lhs == scol } | |
| 128 | tableStoreFormulas(stored, analysis: analysis) | |
| 129 | // Org's user error, which keeps the stored formulas and stops the command. | |
| 130 | message = "Formula removed" | |
| 131 | return nil | |
| 132 | } | |
| 133 | eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression) | |
| 134 | eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression) | |
| 135 | var mustSave = false | |
| 136 | if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) { | |
| 137 | stored.remove(at: index) | |
| 138 | mustSave = true | |
| 139 | } | |
| 140 | if let index = stored.firstIndex(where: { $0.lhs == scol }) { | |
| 141 | stored[index].rhs = eq | |
| 142 | } else { | |
| 143 | stored.insert((scol, eq), at: 0) | |
| 144 | } | |
| 145 | if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) } | |
| 146 | return eq | |
| 147 | } | |
| 148 | ||
| 149 | /// `org-table-eval-formula` for the current field with EQUATION, which is stored first. | |
| 150 | /// A formula only Emacs can evaluate stays stored, the field unchanged. | |
| 151 | func tableEvalFormula(equation: String, named: Bool, read: Bool = false) throws { | |
| 152 | try checkInsideDataField() | |
| 153 | let analysis = try tableAnalyze() | |
| 154 | guard let formula = try tableGetFormula(equation, named: named, read: read, analysis: analysis) else { return } | |
| 155 | do { | |
| 156 | try tableEvalFormula(formula, analysis: analysis, substituted: false) | |
| 157 | } catch let error as Calc.Unsupported { | |
| 158 | message = "The formula was stored; recalculating it needs Emacs: " + error.reason | |
| 159 | } | |
| 160 | tableAlign() | |
| 161 | } | |
| 162 | ||
| 163 | /// `org-table-maybe-eval-formula`. | |
| 164 | func tableMaybeEvalFormula() throws { | |
| 165 | skipBackwardNot([124, 10]) | |
| 166 | guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return } | |
| 167 | let start = point | |
| 168 | var end = point | |
| 169 | while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 } | |
| 170 | point = min(lineEnd(point), start + 1) | |
| 171 | let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r")) | |
| 172 | guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return } | |
| 173 | try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":")) | |
| 174 | } | |
| 175 | } | |
| 176 | ||
| 177 | /// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's | |
| 178 | /// formula, the stored one offered. | |
| 179 | public struct TableEvalFormula: OrgCommand { | |
| 180 | let named: Bool | |
| 181 | public init(named: Bool) { self.named = named } | |
| 182 | public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" } | |
| 183 | public var title: String { named ? "Set Field Formula" : "Set Column Formula" } | |
| 184 | public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) } | |
| 185 | public func run(in context: EditContext) -> CommandStep { | |
| 186 | guard let answer = context.answers["formula"] else { | |
| 187 | let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options) | |
| 188 | guard buffer.atTable else { return .failed("Not at a table") } | |
| 189 | let column = buffer.tableCurrentColumn() | |
| 190 | let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)" | |
| 191 | let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs | |
| 192 | return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? "")) | |
| 193 | } | |
| 194 | return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named, read: true) } | |
| 195 | } | |
| 196 | } | |
| 197 | ||
| 198 | // The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor. | |
| 199 | extension BlockEdit { | |
| 200 | static let formulasKind = "formulas" | |
| 201 | ||
| 202 | /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as | |
| 203 | /// org's editor lists them. The range runs from the table (or that line) to the formulas. | |
| 204 | public static func formulas(at offset: Int, text: String) -> BlockEdit? { | |
| 205 | let buffer = EmacsBuffer(text, point: offset) | |
| 206 | let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset)) | |
| 207 | let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil | |
| 208 | guard atTblfm || buffer.atTable else { return nil } | |
| 209 | let start: Int | |
| 210 | let end: Int | |
| 211 | let formulas: [(lhs: String, rhs: String)] | |
| 212 | if atTblfm { | |
| 213 | start = buffer.lineStart(offset) | |
| 214 | end = min(buffer.length, buffer.lineEnd(offset) + 1) | |
| 215 | let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " ")) | |
| 216 | formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? [] | |
| 217 | guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil } | |
| 218 | } else { | |
| 219 | start = buffer.tableBegin() | |
| 220 | let tableEnd = buffer.tableEnd() | |
| 221 | end = buffer.saveExcursion { | |
| 222 | buffer.point = tableEnd | |
| 223 | return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd | |
| 224 | } | |
| 225 | formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? [] | |
| 226 | } | |
| 227 | guard let analysis = try? buffer.tableAnalyze() else { return nil } | |
| 228 | var content = "" | |
| 229 | var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")] | |
| 230 | for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) { | |
| 231 | let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named" | |
| 232 | if let index = titles.firstIndex(where: { $0.type == type }) { | |
| 233 | if !content.isEmpty { content += "\n" } | |
| 234 | content += titles[index].title | |
| 235 | titles.remove(at: index) | |
| 236 | } | |
| 237 | content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n" | |
| 238 | } | |
| 239 | let ns = text as NSString | |
| 240 | return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind) | |
| 241 | } | |
| 242 | ||
| 243 | /// `org-table-fedit-finish`'s reading of the editor's text. | |
| 244 | static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] { | |
| 245 | let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines) | |
| 246 | let ns = content as NSString | |
| 247 | var result: [(lhs: String, rhs: String)] = [] | |
| 248 | for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) { | |
| 249 | let lhs = ns.substring(with: m.range(at: 1)) | |
| 250 | var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r")) | |
| 251 | guard !rhs.isEmpty else { continue } | |
| 252 | rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression) | |
| 253 | if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") } | |
| 254 | result.insert((lhs, rhs), at: 0) | |
| 255 | } | |
| 256 | return result | |
| 257 | } | |
| 258 | ||
| 259 | /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument. | |
| 260 | func installFormulas(_ content: String, in context: EditContext) -> CommandStep { | |
| 261 | let step = commitBuffer(context) { buffer in | |
| 262 | let formulas = try Self.parseFormulas(content) | |
| 263 | buffer.point = range.lowerBound | |
| 264 | let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in | |
| 265 | if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) } | |
| 266 | return try buffer.tableAnalyze() | |
| 267 | } | |
| 268 | buffer.tableStoreFormulas(formulas, analysis: analysis) | |
| 269 | } | |
| 270 | guard case .commit(let result) = step else { return step } | |
| 271 | return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, | |
| 272 | effects: result.effects + [.message("New formulas installed - Recalculate Table (C-c C-c on the #+TBLFM line) applies them.")])) | |
| 273 | } | |
| 274 | } | |
| 275 | ||
| 276 | // `org-table-edit-field` (C-c `): a field's text edited apart, then put back. | |
| 277 | extension BlockEdit { | |
| 278 | static let fieldKind = "field" | |
| 279 | ||
| 280 | /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged. | |
| 281 | public static func field(at offset: Int, text: String) -> BlockEdit? { | |
| 282 | let buffer = EmacsBuffer(text, point: offset) | |
| 283 | guard buffer.insideDataField else { return nil } | |
| 284 | let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())" | |
| 285 | let field = buffer.saveExcursion { () -> String in | |
| 286 | buffer.skipBackwardNot([124, 10]) | |
| 287 | return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound) | |
| 288 | } | |
| 289 | let start = buffer.lineStart(offset) | |
| 290 | let end = buffer.lineEnd(offset) | |
| 291 | return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines), | |
| 292 | language: nil, kind: fieldKind, point: offset, coordinate: coordinate) | |
| 293 | } | |
| 294 | ||
| 295 | /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the | |
| 296 | /// table is aligned. | |
| 297 | func installField(_ content: String, in context: EditContext) -> CommandStep { | |
| 298 | var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression) | |
| 299 | text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression) | |
| 300 | text = text.trimmingCharacters(in: .whitespacesAndNewlines) | |
| 301 | return commitBuffer(context) { buffer in | |
| 302 | buffer.point = point ?? range.lowerBound | |
| 303 | guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") } | |
| 304 | buffer.skipBackwardNot([124, 10]) | |
| 305 | let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound | |
| 306 | buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text) | |
| 307 | buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1) | |
| 308 | buffer.tableAlign() | |
| 309 | } | |
| 310 | } | |
| 311 | } | |
| 312 | ||
| 313 | extension EmacsBuffer { | |
| 314 | /// `org-table-check-inside-data-field` with NOERROR. | |
| 315 | var insideDataField: Bool { | |
| 316 | atTable && !atTableHline | |
| 317 | && !saveExcursion { () -> Bool in | |
| 318 | while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 } | |
| 319 | return bolp | |
| 320 | } | |
| 321 | && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil | |
| 322 | } | |
| 323 | } | |
| 324 | ||
| 325 | /// C-c `: `org-table-edit-field`, in the block editor. | |
| 326 | public struct TableEditField: OrgCommand { | |
| 327 | public init() {} | |
| 328 | public var id: String { "org.table.edit-field" } | |
| 329 | public var title: String { "Edit Table Field" } | |
| 330 | public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) } | |
| 331 | public func run(in context: EditContext) -> CommandStep { | |
| 332 | guard let edit = BlockEdit.field(at: context.caret, text: context.text) else { | |
| 333 | return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table") | |
| 334 | } | |
| 335 | return .external(.editBlock(edit)) | |
| 336 | } | |
| 337 | } | |
Sources/OrgCore/Compute/TableFormulas.swift −336
| @@ -903,339 +903,3 @@ extension EmacsBuffer { | ||
| 903 | 903 | return above ? low : high |
| 904 | 904 | } |
| 905 | 905 | } |
| 906 | ||
| 907 | /// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the | |
| 908 | /// native evaluator can't do fail with `TableRecalculate.emacsMessage`, and the app | |
| 909 | /// recalculates them in Emacs. | |
| 910 | public struct TableRecalculate: OrgCommand { | |
| 911 | public let all: Bool | |
| 912 | public init(all: Bool) { self.all = all } | |
| 913 | public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" } | |
| 914 | public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" } | |
| 915 | ||
| 916 | public static let emacsMessage = "needs Emacs: " | |
| 917 | ||
| 918 | public func applies(in context: EditContext) -> Bool { | |
| 919 | KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil | |
| 920 | } | |
| 921 | ||
| 922 | static func tblfmLine(in context: EditContext) -> String? { | |
| 923 | let buffer = EmacsBuffer(context.text, point: context.caret) | |
| 924 | let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point)) | |
| 925 | guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil } | |
| 926 | return line | |
| 927 | } | |
| 928 | ||
| 929 | public func run(in context: EditContext) -> CommandStep { | |
| 930 | let step = commitBuffer(context) { buffer in | |
| 931 | do { | |
| 932 | if let line = Self.tblfmLine(in: context) { | |
| 933 | // `org-table-calc-current-TBLFM`: that line's formulas, every row, with | |
| 934 | // point at the end of the table. | |
| 935 | let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " ")) | |
| 936 | let saved = buffer.marker(buffer.point) | |
| 937 | defer { buffer.release(saved) } | |
| 938 | guard let tableEnd = buffer.saveExcursion({ () -> Int? in | |
| 939 | while buffer.forwardLine(-1) == 0 { | |
| 940 | if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) } | |
| 941 | } | |
| 942 | return nil | |
| 943 | }) else { throw EmacsBuffer.UserError(message: "Not at a table") } | |
| 944 | buffer.point = tableEnd | |
| 945 | try buffer.tableRecalculate(all: true, tblfm: formulas) | |
| 946 | buffer.point = saved.position | |
| 947 | } else { | |
| 948 | try buffer.tableRecalculate(all: all) | |
| 949 | } | |
| 950 | } catch let error as Calc.Unsupported { | |
| 951 | throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason) | |
| 952 | } | |
| 953 | } | |
| 954 | let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)" | |
| 955 | return Self.inEmacs(step, form: form, in: context) | |
| 956 | } | |
| 957 | ||
| 958 | /// A step that failed with `emacsMessage` as a request to run `form` on the table in | |
| 959 | /// Emacs, whose text then replaces the table here; other steps unchanged. | |
| 960 | static func inEmacs(_ step: CommandStep, form: String, in context: EditContext) -> CommandStep { | |
| 961 | guard case .failed(let message) = step, message.hasPrefix(emacsMessage) else { return step } | |
| 962 | let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options) | |
| 963 | let onTblfm = tblfmLine(in: context) != nil | |
| 964 | if onTblfm { | |
| 965 | while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {} | |
| 966 | } | |
| 967 | let table = buffer.tableBegin()..<buffer.tableEnd() | |
| 968 | let tblfm = onTblfm ? tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? "" | |
| 969 | return .external(.emacsTable( | |
| 970 | table: table, point: context.caret, form: form, | |
| 971 | reason: String(message.dropFirst(emacsMessage.count)), lisp: tblfm.contains("'(") | |
| 972 | )) | |
| 973 | } | |
| 974 | } | |
| 975 | ||
| 976 | // Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`). | |
| 977 | extension EmacsBuffer { | |
| 978 | /// `org-table-formula-make-cmp-string`. | |
| 979 | static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? { | |
| 980 | var a = lhs | |
| 981 | if let arrow = a.firstMatch(of: /^\$([<>])/) { | |
| 982 | a = (try? handleFirstLast(a, analysis: analysis)) ?? a | |
| 983 | a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))" | |
| 984 | } | |
| 985 | guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil } | |
| 986 | var key = "" | |
| 987 | if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) } | |
| 988 | if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) } | |
| 989 | if let name = m.5 { key += "@@" + name } | |
| 990 | return key | |
| 991 | } | |
| 992 | ||
| 993 | /// `sort` with `org-table-formula-less-p`. | |
| 994 | static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] { | |
| 995 | var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = [] | |
| 996 | // Stable insertion, as `sort` with a partial predicate. | |
| 997 | for formula in formulas { | |
| 998 | let key = formulaSortKey(formula.lhs, analysis: analysis) | |
| 999 | var index = sorted.count | |
| 1000 | while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 } | |
| 1001 | sorted.insert((formula, key), at: index) | |
| 1002 | } | |
| 1003 | return sorted.map(\.formula) | |
| 1004 | } | |
| 1005 | ||
| 1006 | /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`. | |
| 1007 | func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) { | |
| 1008 | let sorted = Self.sortFormulas(formulas, analysis: analysis) | |
| 1009 | saveExcursion { | |
| 1010 | point = tableEnd() | |
| 1011 | if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) { | |
| 1012 | deleteRegion(match[3]!.lowerBound, match[0]!.upperBound) | |
| 1013 | point = match[3]!.lowerBound | |
| 1014 | } else { | |
| 1015 | insert("#+TBLFM:") | |
| 1016 | } | |
| 1017 | insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n") | |
| 1018 | } | |
| 1019 | } | |
| 1020 | ||
| 1021 | /// `org-table-get-formula`: stores EQUATION for the current column, or with `named` the | |
| 1022 | /// current field, and returns it; nil when a blank EQUATION removed the formula. `read` | |
| 1023 | /// when EQUATION is the prompt's answer, which the stored formula never replaces. | |
| 1024 | func tableGetFormula(_ equation: String, named: Bool, read: Bool = false, analysis: TableAnalysis) throws -> String? { | |
| 1025 | var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "") | |
| 1026 | let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())" | |
| 1027 | let scol = named ? ref : "$\(tableCurrentColumn())" | |
| 1028 | let old = stored.first { $0.lhs == scol }?.rhs | |
| 1029 | var eq = !read && old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation | |
| 1030 | guard eq.contains(where: { !$0.isWhitespace }) else { | |
| 1031 | stored.removeAll { $0.lhs == scol } | |
| 1032 | tableStoreFormulas(stored, analysis: analysis) | |
| 1033 | // Org's user error, which keeps the stored formulas and stops the command. | |
| 1034 | message = "Formula removed" | |
| 1035 | return nil | |
| 1036 | } | |
| 1037 | eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression) | |
| 1038 | eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression) | |
| 1039 | var mustSave = false | |
| 1040 | if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) { | |
| 1041 | stored.remove(at: index) | |
| 1042 | mustSave = true | |
| 1043 | } | |
| 1044 | if let index = stored.firstIndex(where: { $0.lhs == scol }) { | |
| 1045 | stored[index].rhs = eq | |
| 1046 | } else { | |
| 1047 | stored.insert((scol, eq), at: 0) | |
| 1048 | } | |
| 1049 | if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) } | |
| 1050 | return eq | |
| 1051 | } | |
| 1052 | ||
| 1053 | /// `org-table-eval-formula` for the current field with EQUATION, which is stored first. | |
| 1054 | /// A formula only Emacs can evaluate stays stored, the field unchanged. | |
| 1055 | func tableEvalFormula(equation: String, named: Bool, read: Bool = false) throws { | |
| 1056 | try checkInsideDataField() | |
| 1057 | let analysis = try tableAnalyze() | |
| 1058 | guard let formula = try tableGetFormula(equation, named: named, read: read, analysis: analysis) else { return } | |
| 1059 | do { | |
| 1060 | try tableEvalFormula(formula, analysis: analysis, substituted: false) | |
| 1061 | } catch let error as Calc.Unsupported { | |
| 1062 | message = "The formula was stored; recalculating it needs Emacs: " + error.reason | |
| 1063 | } | |
| 1064 | tableAlign() | |
| 1065 | } | |
| 1066 | ||
| 1067 | /// `org-table-maybe-eval-formula`. | |
| 1068 | func tableMaybeEvalFormula() throws { | |
| 1069 | skipBackwardNot([124, 10]) | |
| 1070 | guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return } | |
| 1071 | let start = point | |
| 1072 | var end = point | |
| 1073 | while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 } | |
| 1074 | point = min(lineEnd(point), start + 1) | |
| 1075 | let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r")) | |
| 1076 | guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return } | |
| 1077 | try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":")) | |
| 1078 | } | |
| 1079 | } | |
| 1080 | ||
| 1081 | /// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's | |
| 1082 | /// formula, the stored one offered. | |
| 1083 | public struct TableEvalFormula: OrgCommand { | |
| 1084 | let named: Bool | |
| 1085 | public init(named: Bool) { self.named = named } | |
| 1086 | public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" } | |
| 1087 | public var title: String { named ? "Set Field Formula" : "Set Column Formula" } | |
| 1088 | public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) } | |
| 1089 | public func run(in context: EditContext) -> CommandStep { | |
| 1090 | guard let answer = context.answers["formula"] else { | |
| 1091 | let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options) | |
| 1092 | guard buffer.atTable else { return .failed("Not at a table") } | |
| 1093 | let column = buffer.tableCurrentColumn() | |
| 1094 | let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)" | |
| 1095 | let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs | |
| 1096 | return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? "")) | |
| 1097 | } | |
| 1098 | return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named, read: true) } | |
| 1099 | } | |
| 1100 | } | |
| 1101 | ||
| 1102 | // The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor. | |
| 1103 | extension BlockEdit { | |
| 1104 | static let formulasKind = "formulas" | |
| 1105 | ||
| 1106 | /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as | |
| 1107 | /// org's editor lists them. The range runs from the table (or that line) to the formulas. | |
| 1108 | public static func formulas(at offset: Int, text: String) -> BlockEdit? { | |
| 1109 | let buffer = EmacsBuffer(text, point: offset) | |
| 1110 | let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset)) | |
| 1111 | let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil | |
| 1112 | guard atTblfm || buffer.atTable else { return nil } | |
| 1113 | let start: Int | |
| 1114 | let end: Int | |
| 1115 | let formulas: [(lhs: String, rhs: String)] | |
| 1116 | if atTblfm { | |
| 1117 | start = buffer.lineStart(offset) | |
| 1118 | end = min(buffer.length, buffer.lineEnd(offset) + 1) | |
| 1119 | let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " ")) | |
| 1120 | formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? [] | |
| 1121 | guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil } | |
| 1122 | } else { | |
| 1123 | start = buffer.tableBegin() | |
| 1124 | let tableEnd = buffer.tableEnd() | |
| 1125 | end = buffer.saveExcursion { | |
| 1126 | buffer.point = tableEnd | |
| 1127 | return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd | |
| 1128 | } | |
| 1129 | formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? [] | |
| 1130 | } | |
| 1131 | guard let analysis = try? buffer.tableAnalyze() else { return nil } | |
| 1132 | var content = "" | |
| 1133 | var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")] | |
| 1134 | for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) { | |
| 1135 | let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named" | |
| 1136 | if let index = titles.firstIndex(where: { $0.type == type }) { | |
| 1137 | if !content.isEmpty { content += "\n" } | |
| 1138 | content += titles[index].title | |
| 1139 | titles.remove(at: index) | |
| 1140 | } | |
| 1141 | content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n" | |
| 1142 | } | |
| 1143 | let ns = text as NSString | |
| 1144 | return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind) | |
| 1145 | } | |
| 1146 | ||
| 1147 | /// `org-table-fedit-finish`'s reading of the editor's text. | |
| 1148 | static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] { | |
| 1149 | let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines) | |
| 1150 | let ns = content as NSString | |
| 1151 | var result: [(lhs: String, rhs: String)] = [] | |
| 1152 | for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) { | |
| 1153 | let lhs = ns.substring(with: m.range(at: 1)) | |
| 1154 | var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r")) | |
| 1155 | guard !rhs.isEmpty else { continue } | |
| 1156 | rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression) | |
| 1157 | if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") } | |
| 1158 | result.insert((lhs, rhs), at: 0) | |
| 1159 | } | |
| 1160 | return result | |
| 1161 | } | |
| 1162 | ||
| 1163 | /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument. | |
| 1164 | func installFormulas(_ content: String, in context: EditContext) -> CommandStep { | |
| 1165 | let step = commitBuffer(context) { buffer in | |
| 1166 | let formulas = try Self.parseFormulas(content) | |
| 1167 | buffer.point = range.lowerBound | |
| 1168 | let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in | |
| 1169 | if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) } | |
| 1170 | return try buffer.tableAnalyze() | |
| 1171 | } | |
| 1172 | buffer.tableStoreFormulas(formulas, analysis: analysis) | |
| 1173 | } | |
| 1174 | guard case .commit(let result) = step else { return step } | |
| 1175 | return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, | |
| 1176 | effects: result.effects + [.message("New formulas installed - Recalculate Table (C-c C-c on the #+TBLFM line) applies them.")])) | |
| 1177 | } | |
| 1178 | } | |
| 1179 | ||
| 1180 | // `org-table-edit-field` (C-c `): a field's text edited apart, then put back. | |
| 1181 | extension BlockEdit { | |
| 1182 | static let fieldKind = "field" | |
| 1183 | ||
| 1184 | /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged. | |
| 1185 | public static func field(at offset: Int, text: String) -> BlockEdit? { | |
| 1186 | let buffer = EmacsBuffer(text, point: offset) | |
| 1187 | guard buffer.insideDataField else { return nil } | |
| 1188 | let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())" | |
| 1189 | let field = buffer.saveExcursion { () -> String in | |
| 1190 | buffer.skipBackwardNot([124, 10]) | |
| 1191 | return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound) | |
| 1192 | } | |
| 1193 | let start = buffer.lineStart(offset) | |
| 1194 | let end = buffer.lineEnd(offset) | |
| 1195 | return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines), | |
| 1196 | language: nil, kind: fieldKind, point: offset, coordinate: coordinate) | |
| 1197 | } | |
| 1198 | ||
| 1199 | /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the | |
| 1200 | /// table is aligned. | |
| 1201 | func installField(_ content: String, in context: EditContext) -> CommandStep { | |
| 1202 | var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression) | |
| 1203 | text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression) | |
| 1204 | text = text.trimmingCharacters(in: .whitespacesAndNewlines) | |
| 1205 | return commitBuffer(context) { buffer in | |
| 1206 | buffer.point = point ?? range.lowerBound | |
| 1207 | guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") } | |
| 1208 | buffer.skipBackwardNot([124, 10]) | |
| 1209 | let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound | |
| 1210 | buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text) | |
| 1211 | buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1) | |
| 1212 | buffer.tableAlign() | |
| 1213 | } | |
| 1214 | } | |
| 1215 | } | |
| 1216 | ||
| 1217 | extension EmacsBuffer { | |
| 1218 | /// `org-table-check-inside-data-field` with NOERROR. | |
| 1219 | var insideDataField: Bool { | |
| 1220 | atTable && !atTableHline | |
| 1221 | && !saveExcursion { () -> Bool in | |
| 1222 | while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 } | |
| 1223 | return bolp | |
| 1224 | } | |
| 1225 | && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil | |
| 1226 | } | |
| 1227 | } | |
| 1228 | ||
| 1229 | /// C-c `: `org-table-edit-field`, in the block editor. | |
| 1230 | public struct TableEditField: OrgCommand { | |
| 1231 | public init() {} | |
| 1232 | public var id: String { "org.table.edit-field" } | |
| 1233 | public var title: String { "Edit Table Field" } | |
| 1234 | public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) } | |
| 1235 | public func run(in context: EditContext) -> CommandStep { | |
| 1236 | guard let edit = BlockEdit.field(at: context.caret, text: context.text) else { | |
| 1237 | return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table") | |
| 1238 | } | |
| 1239 | return .external(.editBlock(edit)) | |
| 1240 | } | |
| 1241 | } | |
Sources/OrgCore/Keymap/PresetDoom.swift added +497
| @@ -0,0 +1,497 @@ | ||
| 1 | extension KeymapPreset { | |
| 2 | static var doomToml: String { | |
| 3 | var problems: [String] = [] | |
| 4 | let emacs = try! Keymap(toml: common + emacsBindings, problems: &problems) | |
| 5 | let translations: [String: String] = ["<left>": "h", "<right>": "l", "<up>": "k", "<down>": "j"] | |
| 6 | var out = "" | |
| 7 | func bind(_ keys: String, _ command: String, when: String?, mode: String) { | |
| 8 | out += "[[bind]]\nkeys = \"\(keys.replacingOccurrences(of: "\\", with: "\\\\"))\"\ncommand = \"\(command)\"\n" | |
| 9 | if let when { out += "when = \"\(when)\"\n" } | |
| 10 | out += "mode = \"\(mode)\"\n" | |
| 11 | } | |
| 12 | for binding in emacs.bindings { | |
| 13 | let first = binding.keys[0] | |
| 14 | let keys = KeySequence.format(binding.keys) | |
| 15 | let orgKey = first.key == "c" && first.modifiers == [.control] || first.key == "x" && first.modifiers == [.control] | |
| 16 | || (first.modifiers.contains(.meta) && ["<left>", "<right>", "<up>", "<down>", "RET"].contains(first.key)) | |
| 17 | || (first.modifiers.contains(.shift) && ["<left>", "<right>", "<up>", "<down>"].contains(first.key)) | |
| 18 | || (first.modifiers == [.control] && first.key == "RET") | |
| 19 | || keys == "M-x" || keys == "M-q" | |
| 20 | guard orgKey else { continue } | |
| 21 | for mode in ["normal", "insert", "visual"] { bind(keys, binding.command, when: binding.when, mode: mode) } | |
| 22 | // evil-org: M-h/j/k/l and M-H/J/K/L in normal, visual and insert. | |
| 23 | if binding.keys.count == 1, first.modifiers.contains(.meta), let letter = translations[first.key] { | |
| 24 | let shifted = first.modifiers.contains(.shift) | |
| 25 | let key = "M-" + (shifted ? letter.uppercased() : letter) | |
| 26 | for mode in ["normal", "insert", "visual"] { bind(key, binding.command, when: binding.when, mode: mode) } | |
| 27 | } | |
| 28 | // Doom: C-S-h/j/k/l are org-shift* in normal and insert. | |
| 29 | if binding.keys.count == 1, first.modifiers == [.shift], let letter = translations[first.key] { | |
| 30 | for mode in ["normal", "insert"] { bind("C-" + letter.uppercased(), binding.command, when: binding.when, mode: mode) } | |
| 31 | } | |
| 32 | // evil-org insert state: C-t demotes, C-d promotes. | |
| 33 | if binding.keys.count == 1, first.modifiers == [.meta], first.key == "<right>" || first.key == "<left>" { | |
| 34 | bind(first.key == "<right>" ? "C-t" : "C-d", binding.command, when: binding.when, mode: "insert") | |
| 35 | } | |
| 36 | } | |
| 37 | return out + doomBindings | |
| 38 | } | |
| 39 | ||
| 40 | static let doomBindings = """ | |
| 41 | # Leader | |
| 42 | [[bind]] | |
| 43 | keys = "SPC SPC" | |
| 44 | command = "app.quick-open" | |
| 45 | mode = "normal" | |
| 46 | [[bind]] | |
| 47 | keys = "SPC q q" | |
| 48 | command = "app.quit" | |
| 49 | mode = "normal" | |
| 50 | [[bind]] | |
| 51 | keys = "SPC ." | |
| 52 | command = "app.quick-open" | |
| 53 | mode = "normal" | |
| 54 | [[bind]] | |
| 55 | keys = "SPC f f" | |
| 56 | command = "app.quick-open" | |
| 57 | mode = "normal" | |
| 58 | [[bind]] | |
| 59 | keys = "SPC f s" | |
| 60 | command = "app.save" | |
| 61 | mode = "normal" | |
| 62 | # Buffers | |
| 63 | [[bind]] | |
| 64 | keys = "SPC b b" | |
| 65 | command = "app.buffer.switch" | |
| 66 | mode = "normal" | |
| 67 | [[bind]] | |
| 68 | keys = "SPC b B" | |
| 69 | command = "app.buffer.switch" | |
| 70 | mode = "normal" | |
| 71 | [[bind]] | |
| 72 | keys = "SPC ," | |
| 73 | command = "app.buffer.switch" | |
| 74 | mode = "normal" | |
| 75 | [[bind]] | |
| 76 | keys = "SPC `" | |
| 77 | command = "app.buffer.last" | |
| 78 | mode = "normal" | |
| 79 | [[bind]] | |
| 80 | keys = "SPC b k" | |
| 81 | command = "app.buffer.kill" | |
| 82 | mode = "normal" | |
| 83 | [[bind]] | |
| 84 | keys = "SPC b d" | |
| 85 | command = "app.buffer.kill" | |
| 86 | mode = "normal" | |
| 87 | [[bind]] | |
| 88 | keys = "SPC b K" | |
| 89 | command = "app.buffer.kill-all" | |
| 90 | mode = "normal" | |
| 91 | [[bind]] | |
| 92 | keys = "SPC b O" | |
| 93 | command = "app.buffer.kill-others" | |
| 94 | mode = "normal" | |
| 95 | [[bind]] | |
| 96 | keys = "SPC b n" | |
| 97 | command = "app.buffer.next" | |
| 98 | mode = "normal" | |
| 99 | [[bind]] | |
| 100 | keys = "SPC b p" | |
| 101 | command = "app.buffer.previous" | |
| 102 | mode = "normal" | |
| 103 | [[bind]] | |
| 104 | keys = "SPC b ]" | |
| 105 | command = "app.buffer.next" | |
| 106 | mode = "normal" | |
| 107 | [[bind]] | |
| 108 | keys = "SPC b [" | |
| 109 | command = "app.buffer.previous" | |
| 110 | mode = "normal" | |
| 111 | [[bind]] | |
| 112 | keys = "] b" | |
| 113 | command = "app.buffer.next" | |
| 114 | mode = "normal" | |
| 115 | [[bind]] | |
| 116 | keys = "[ b" | |
| 117 | command = "app.buffer.previous" | |
| 118 | mode = "normal" | |
| 119 | [[bind]] | |
| 120 | keys = "SPC b s" | |
| 121 | command = "app.save" | |
| 122 | mode = "normal" | |
| 123 | [[bind]] | |
| 124 | keys = "SPC b S" | |
| 125 | command = "app.save-all" | |
| 126 | mode = "normal" | |
| 127 | [[bind]] | |
| 128 | keys = "SPC s s" | |
| 129 | command = "edit.find" | |
| 130 | mode = "normal" | |
| 131 | [[bind]] | |
| 132 | keys = "SPC /" | |
| 133 | command = "app.search" | |
| 134 | mode = "normal" | |
| 135 | [[bind]] | |
| 136 | keys = "SPC s p" | |
| 137 | command = "app.search" | |
| 138 | mode = "normal" | |
| 139 | [[bind]] | |
| 140 | keys = "SPC :" | |
| 141 | command = "app.palette" | |
| 142 | mode = "normal" | |
| 143 | [[bind]] | |
| 144 | keys = "SPC o a" | |
| 145 | command = "app.agenda" | |
| 146 | mode = "normal" | |
| 147 | [[bind]] | |
| 148 | keys = "SPC X" | |
| 149 | command = "app.capture" | |
| 150 | mode = "normal" | |
| 151 | [[bind]] | |
| 152 | keys = "SPC z t" | |
| 153 | command = "app.clock.report" | |
| 154 | mode = "normal" | |
| 155 | [[bind]] | |
| 156 | keys = "SPC h r r" | |
| 157 | command = "app.reload-keymap" | |
| 158 | mode = "normal" | |
| 159 | [[bind]] | |
| 160 | keys = "SPC t s" | |
| 161 | command = "editor.toggle-spell-check" | |
| 162 | mode = "normal" | |
| 163 | [[bind]] | |
| 164 | keys = "SPC t w" | |
| 165 | command = "editor.toggle-truncate-lines" | |
| 166 | mode = "normal" | |
| 167 | ||
| 168 | # Localleader (SPC m) | |
| 169 | [[bind]] | |
| 170 | keys = "SPC m '" | |
| 171 | command = "org.edit-special" | |
| 172 | mode = "normal" | |
| 173 | [[bind]] | |
| 174 | keys = "SPC m s c" | |
| 175 | command = "org.subtree.clone" | |
| 176 | mode = "normal" | |
| 177 | [[bind]] | |
| 178 | keys = "SPC m s d" | |
| 179 | command = "org.subtree.cut" | |
| 180 | mode = "normal" | |
| 181 | [[bind]] | |
| 182 | keys = "SPC m s S" | |
| 183 | command = "org.sort" | |
| 184 | mode = "normal" | |
| 185 | [[bind]] | |
| 186 | keys = "SPC m s n" | |
| 187 | command = "org.narrow.subtree" | |
| 188 | mode = "normal" | |
| 189 | [[bind]] | |
| 190 | keys = "SPC m s s" | |
| 191 | command = "org.sparse-tree" | |
| 192 | mode = "normal" | |
| 193 | [[bind]] | |
| 194 | keys = "SPC m s N" | |
| 195 | command = "org.widen" | |
| 196 | mode = "normal" | |
| 197 | [[bind]] | |
| 198 | keys = "SPC m ." | |
| 199 | command = "org.goto" | |
| 200 | mode = "normal" | |
| 201 | [[bind]] | |
| 202 | keys = "SPC m h" | |
| 203 | command = "org.heading.toggle" | |
| 204 | mode = "normal" | |
| 205 | [[bind]] | |
| 206 | keys = "SPC m i" | |
| 207 | command = "org.item.toggle" | |
| 208 | mode = "normal" | |
| 209 | [[bind]] | |
| 210 | keys = "SPC m l l" | |
| 211 | command = "org.link.insert" | |
| 212 | mode = "normal" | |
| 213 | [[bind]] | |
| 214 | keys = "SPC m l s" | |
| 215 | command = "org.link.store" | |
| 216 | mode = "normal" | |
| 217 | [[bind]] | |
| 218 | keys = "SPC m l i" | |
| 219 | command = "org.id.store-link" | |
| 220 | mode = "normal" | |
| 221 | [[bind]] | |
| 222 | keys = "SPC n l" | |
| 223 | command = "org.link.store" | |
| 224 | mode = "normal" | |
| 225 | [[bind]] | |
| 226 | keys = "SPC m t" | |
| 227 | command = "org.todo.cycle" | |
| 228 | mode = "normal" | |
| 229 | [[bind]] | |
| 230 | keys = "SPC m q" | |
| 231 | command = "org.tags.set" | |
| 232 | mode = "normal" | |
| 233 | [[bind]] | |
| 234 | keys = "SPC m x" | |
| 235 | command = "org.checkbox.toggle" | |
| 236 | mode = "normal" | |
| 237 | [[bind]] | |
| 238 | keys = "SPC m A" | |
| 239 | command = "app.archive" | |
| 240 | mode = "normal" | |
| 241 | [[bind]] | |
| 242 | keys = "SPC m e h h" | |
| 243 | command = "app.export.html" | |
| 244 | mode = "normal" | |
| 245 | [[bind]] | |
| 246 | keys = "SPC m e h o" | |
| 247 | command = "app.export.html-open" | |
| 248 | mode = "normal" | |
| 249 | [[bind]] | |
| 250 | keys = "SPC m e m m" | |
| 251 | command = "app.export.markdown" | |
| 252 | mode = "normal" | |
| 253 | [[bind]] | |
| 254 | keys = "SPC m e l p" | |
| 255 | command = "app.export.pdf" | |
| 256 | mode = "normal" | |
| 257 | [[bind]] | |
| 258 | keys = "SPC m d d" | |
| 259 | command = "org.deadline" | |
| 260 | mode = "normal" | |
| 261 | [[bind]] | |
| 262 | keys = "SPC m d s" | |
| 263 | command = "org.schedule" | |
| 264 | mode = "normal" | |
| 265 | [[bind]] | |
| 266 | keys = "SPC m d t" | |
| 267 | command = "org.timestamp.active" | |
| 268 | mode = "normal" | |
| 269 | [[bind]] | |
| 270 | keys = "SPC m d T" | |
| 271 | command = "org.timestamp.inactive" | |
| 272 | mode = "normal" | |
| 273 | [[bind]] | |
| 274 | keys = "SPC m r r" | |
| 275 | command = "app.refile" | |
| 276 | mode = "normal" | |
| 277 | [[bind]] | |
| 278 | keys = "SPC m s r" | |
| 279 | command = "app.refile" | |
| 280 | mode = "normal" | |
| 281 | [[bind]] | |
| 282 | keys = "SPC m s A" | |
| 283 | command = "app.archive" | |
| 284 | mode = "normal" | |
| 285 | [[bind]] | |
| 286 | keys = "SPC m s a" | |
| 287 | command = "org.archive.toggle-tag" | |
| 288 | mode = "normal" | |
| 289 | [[bind]] | |
| 290 | keys = "SPC m s h" | |
| 291 | command = "org.subtree.promote" | |
| 292 | mode = "normal" | |
| 293 | [[bind]] | |
| 294 | keys = "SPC m s l" | |
| 295 | command = "org.subtree.demote" | |
| 296 | mode = "normal" | |
| 297 | [[bind]] | |
| 298 | keys = "SPC m s j" | |
| 299 | command = "org.subtree.down" | |
| 300 | mode = "normal" | |
| 301 | [[bind]] | |
| 302 | keys = "SPC m s k" | |
| 303 | command = "org.subtree.up" | |
| 304 | mode = "normal" | |
| 305 | [[bind]] | |
| 306 | keys = "SPC m c i" | |
| 307 | command = "app.clock.in" | |
| 308 | mode = "normal" | |
| 309 | [[bind]] | |
| 310 | keys = "SPC m c o" | |
| 311 | command = "app.clock.out" | |
| 312 | mode = "normal" | |
| 313 | [[bind]] | |
| 314 | keys = "SPC m c c" | |
| 315 | command = "app.clock.cancel" | |
| 316 | mode = "normal" | |
| 317 | [[bind]] | |
| 318 | keys = "SPC m c g" | |
| 319 | command = "app.clock.goto" | |
| 320 | mode = "normal" | |
| 321 | [[bind]] | |
| 322 | keys = "SPC m c G" | |
| 323 | command = "app.clock.goto-recent" | |
| 324 | mode = "normal" | |
| 325 | [[bind]] | |
| 326 | keys = "SPC m c I" | |
| 327 | command = "app.clock.in-last" | |
| 328 | mode = "normal" | |
| 329 | [[bind]] | |
| 330 | keys = "SPC m c d" | |
| 331 | command = "app.clock.default" | |
| 332 | mode = "normal" | |
| 333 | [[bind]] | |
| 334 | keys = "SPC m c r" | |
| 335 | command = "app.clock.resolve" | |
| 336 | mode = "normal" | |
| 337 | [[bind]] | |
| 338 | keys = "SPC m c R" | |
| 339 | command = "app.clock.report" | |
| 340 | mode = "normal" | |
| 341 | [[bind]] | |
| 342 | keys = "SPC m c E" | |
| 343 | command = "org.effort.set" | |
| 344 | mode = "normal" | |
| 345 | [[bind]] | |
| 346 | keys = "SPC m p p" | |
| 347 | command = "org.priority.set" | |
| 348 | mode = "normal" | |
| 349 | [[bind]] | |
| 350 | keys = "SPC m o" | |
| 351 | command = "org.property.read-and-set" | |
| 352 | mode = "normal" | |
| 353 | [[bind]] | |
| 354 | keys = "SPC m p u" | |
| 355 | command = "org.priority.up" | |
| 356 | mode = "normal" | |
| 357 | [[bind]] | |
| 358 | keys = "SPC m p d" | |
| 359 | command = "org.priority.down" | |
| 360 | mode = "normal" | |
| 361 | [[bind]] | |
| 362 | keys = "SPC m b -" | |
| 363 | command = "org.table.insert-hline" | |
| 364 | mode = "normal" | |
| 365 | [[bind]] | |
| 366 | keys = "SPC m b a" | |
| 367 | command = "org.table.align" | |
| 368 | mode = "normal" | |
| 369 | [[bind]] | |
| 370 | keys = "SPC m b r" | |
| 371 | command = "org.table.recalc-all" | |
| 372 | mode = "normal" | |
| 373 | [[bind]] | |
| 374 | keys = "SPC m b d c" | |
| 375 | command = "org.table.delete-column" | |
| 376 | mode = "normal" | |
| 377 | [[bind]] | |
| 378 | keys = "SPC m b d r" | |
| 379 | command = "org.table.kill-row" | |
| 380 | mode = "normal" | |
| 381 | [[bind]] | |
| 382 | keys = "SPC m b i c" | |
| 383 | command = "org.table.insert-column" | |
| 384 | mode = "normal" | |
| 385 | [[bind]] | |
| 386 | keys = "SPC m b i r" | |
| 387 | command = "org.table.insert-row" | |
| 388 | mode = "normal" | |
| 389 | [[bind]] | |
| 390 | keys = "SPC m b i h" | |
| 391 | command = "org.table.insert-hline" | |
| 392 | mode = "normal" | |
| 393 | ||
| 394 | # evil-org and Doom's org keys | |
| 395 | [[bind]] | |
| 396 | keys = "TAB" | |
| 397 | command = "org.cycle" | |
| 398 | mode = "normal" | |
| 399 | [[bind]] | |
| 400 | keys = "S-TAB" | |
| 401 | command = "org.cycle-global" | |
| 402 | mode = "normal" | |
| 403 | [[bind]] | |
| 404 | keys = "RET" | |
| 405 | command = "org.dwim" | |
| 406 | mode = "normal" | |
| 407 | [[bind]] | |
| 408 | keys = "z a" | |
| 409 | command = "org.fold.toggle" | |
| 410 | mode = "normal" | |
| 411 | [[bind]] | |
| 412 | keys = "z c" | |
| 413 | command = "org.fold.close" | |
| 414 | mode = "normal" | |
| 415 | [[bind]] | |
| 416 | keys = "z o" | |
| 417 | command = "org.fold.open" | |
| 418 | mode = "normal" | |
| 419 | [[bind]] | |
| 420 | keys = "z A" | |
| 421 | command = "org.cycle-global" | |
| 422 | mode = "normal" | |
| 423 | [[bind]] | |
| 424 | keys = "g h" | |
| 425 | command = "org.heading.up" | |
| 426 | mode = "normal" | |
| 427 | [[bind]] | |
| 428 | keys = "] h" | |
| 429 | command = "org.heading.forward-same-level" | |
| 430 | mode = "normal" | |
| 431 | [[bind]] | |
| 432 | keys = "[ h" | |
| 433 | command = "org.heading.backward-same-level" | |
| 434 | mode = "normal" | |
| 435 | [[bind]] | |
| 436 | keys = "RET" | |
| 437 | command = "org.table.next-row" | |
| 438 | when = "table" | |
| 439 | mode = "insert" | |
| 440 | [[bind]] | |
| 441 | keys = "TAB" | |
| 442 | command = "org.cycle" | |
| 443 | mode = "visual" | |
| 444 | [[bind]] | |
| 445 | keys = "S-TAB" | |
| 446 | command = "org.cycle-global" | |
| 447 | mode = "visual" | |
| 448 | ||
| 449 | # Doom's corfu: completion-at-point in insert state. | |
| 450 | [[bind]] | |
| 451 | keys = "C-SPC" | |
| 452 | command = "editor.complete" | |
| 453 | mode = "insert" | |
| 454 | [[bind]] | |
| 455 | keys = "C-@" | |
| 456 | command = "editor.complete" | |
| 457 | mode = "insert" | |
| 458 | ||
| 459 | # Insert state: org-cycle and org-shifttab with Doom's +org-indent-maybe-h, which | |
| 460 | # demotes or promotes a heading and indents or outdents an item tree. | |
| 461 | [[bind]] | |
| 462 | keys = "S-TAB" | |
| 463 | command = "org.cycle-global" | |
| 464 | mode = "insert" | |
| 465 | [[bind]] | |
| 466 | keys = "TAB" | |
| 467 | command = "org.table.next-field" | |
| 468 | when = "table" | |
| 469 | mode = "insert" | |
| 470 | [[bind]] | |
| 471 | keys = "S-TAB" | |
| 472 | command = "org.table.previous-field" | |
| 473 | when = "table" | |
| 474 | mode = "insert" | |
| 475 | [[bind]] | |
| 476 | keys = "TAB" | |
| 477 | command = "org.item.indent-tree" | |
| 478 | when = "item" | |
| 479 | mode = "insert" | |
| 480 | [[bind]] | |
| 481 | keys = "S-TAB" | |
| 482 | command = "org.item.outdent-tree" | |
| 483 | when = "item" | |
| 484 | mode = "insert" | |
| 485 | [[bind]] | |
| 486 | keys = "TAB" | |
| 487 | command = "org.heading.demote" | |
| 488 | when = "heading" | |
| 489 | mode = "insert" | |
| 490 | [[bind]] | |
| 491 | keys = "S-TAB" | |
| 492 | command = "org.heading.promote" | |
| 493 | when = "heading" | |
| 494 | mode = "insert" | |
| 495 | ||
| 496 | """ | |
| 497 | } | |
Sources/OrgCore/Keymap/PresetEmacs.swift added +513
| @@ -0,0 +1,513 @@ | ||
| 1 | extension KeymapPreset { | |
| 2 | static let emacsBindings = """ | |
| 3 | # Movement and editing. With a mark set (C-SPC), movement extends the region. | |
| 4 | [[bind]] | |
| 5 | keys = "C-f" | |
| 6 | command = "edit.forward-char" | |
| 7 | [[bind]] | |
| 8 | keys = "C-b" | |
| 9 | command = "edit.backward-char" | |
| 10 | [[bind]] | |
| 11 | keys = "C-n" | |
| 12 | command = "edit.next-line" | |
| 13 | [[bind]] | |
| 14 | keys = "C-p" | |
| 15 | command = "edit.previous-line" | |
| 16 | [[bind]] | |
| 17 | keys = "C-a" | |
| 18 | command = "edit.beginning-of-line" | |
| 19 | [[bind]] | |
| 20 | keys = "C-e" | |
| 21 | command = "edit.end-of-line" | |
| 22 | [[bind]] | |
| 23 | keys = "M-f" | |
| 24 | command = "edit.forward-word" | |
| 25 | [[bind]] | |
| 26 | keys = "M-b" | |
| 27 | command = "edit.backward-word" | |
| 28 | [[bind]] | |
| 29 | keys = "M-<" | |
| 30 | command = "edit.beginning-of-buffer" | |
| 31 | [[bind]] | |
| 32 | keys = "M->" | |
| 33 | command = "edit.end-of-buffer" | |
| 34 | [[bind]] | |
| 35 | keys = "C-v" | |
| 36 | command = "edit.scroll-up" | |
| 37 | [[bind]] | |
| 38 | keys = "M-v" | |
| 39 | command = "edit.scroll-down" | |
| 40 | [[bind]] | |
| 41 | keys = "C-l" | |
| 42 | command = "edit.recenter" | |
| 43 | [[bind]] | |
| 44 | keys = "C-d" | |
| 45 | command = "edit.delete-char" | |
| 46 | [[bind]] | |
| 47 | keys = "M-d" | |
| 48 | command = "edit.kill-word" | |
| 49 | [[bind]] | |
| 50 | keys = "M-DEL" | |
| 51 | command = "edit.backward-kill-word" | |
| 52 | [[bind]] | |
| 53 | keys = "C-k" | |
| 54 | command = "edit.kill-line" | |
| 55 | [[bind]] | |
| 56 | keys = "C-y" | |
| 57 | command = "edit.yank" | |
| 58 | [[bind]] | |
| 59 | keys = "C-SPC" | |
| 60 | command = "edit.set-mark" | |
| 61 | [[bind]] | |
| 62 | keys = "C-M-i" | |
| 63 | command = "editor.complete" | |
| 64 | [[bind]] | |
| 65 | keys = "C-x h" | |
| 66 | command = "edit.select-all" | |
| 67 | [[bind]] | |
| 68 | keys = "C-w" | |
| 69 | command = "edit.kill-region" | |
| 70 | [[bind]] | |
| 71 | keys = "M-w" | |
| 72 | command = "edit.copy-region" | |
| 73 | [[bind]] | |
| 74 | keys = "C-/" | |
| 75 | command = "edit.undo" | |
| 76 | [[bind]] | |
| 77 | keys = "C-_" | |
| 78 | command = "edit.undo" | |
| 79 | [[bind]] | |
| 80 | keys = "C-x u" | |
| 81 | command = "edit.undo" | |
| 82 | [[bind]] | |
| 83 | keys = "C-g" | |
| 84 | command = "edit.keyboard-quit" | |
| 85 | [[bind]] | |
| 86 | keys = "C-t" | |
| 87 | command = "edit.transpose-chars" | |
| 88 | [[bind]] | |
| 89 | keys = "C-s" | |
| 90 | command = "edit.find" | |
| 91 | [[bind]] | |
| 92 | keys = "C-r" | |
| 93 | command = "edit.find" | |
| 94 | [[bind]] | |
| 95 | keys = "M-%" | |
| 96 | command = "edit.replace" | |
| 97 | ||
| 98 | # Files and commands | |
| 99 | [[bind]] | |
| 100 | keys = "C-x C-s" | |
| 101 | command = "app.save" | |
| 102 | [[bind]] | |
| 103 | keys = "C-c C-o" | |
| 104 | command = "org.link.open" | |
| 105 | [[bind]] | |
| 106 | keys = "C-c C-l" | |
| 107 | command = "org.link.insert" | |
| 108 | [[bind]] | |
| 109 | keys = "C-c l" | |
| 110 | command = "org.link.store" | |
| 111 | [[bind]] | |
| 112 | keys = "C-c ;" | |
| 113 | command = "org.heading.toggle-comment" | |
| 114 | [[bind]] | |
| 115 | keys = "C-c *" | |
| 116 | command = "org.heading.toggle" | |
| 117 | [[bind]] | |
| 118 | keys = "C-c -" | |
| 119 | command = "org.item.toggle" | |
| 120 | [[bind]] | |
| 121 | keys = "C-c @" | |
| 122 | command = "org.subtree.mark" | |
| 123 | [[bind]] | |
| 124 | keys = "C-c C-x C-w" | |
| 125 | command = "org.subtree.cut" | |
| 126 | [[bind]] | |
| 127 | keys = "C-c C-x M-w" | |
| 128 | command = "org.subtree.copy" | |
| 129 | [[bind]] | |
| 130 | keys = "C-c C-x C-y" | |
| 131 | command = "org.subtree.paste" | |
| 132 | [[bind]] | |
| 133 | keys = "C-c C-x c" | |
| 134 | command = "org.subtree.clone" | |
| 135 | [[bind]] | |
| 136 | keys = "C-c ^" | |
| 137 | command = "org.sort" | |
| 138 | [[bind]] | |
| 139 | keys = "C-c C-c" | |
| 140 | command = "org.ctrl-c-ctrl-c" | |
| 141 | [[bind]] | |
| 142 | keys = "C-c C-y" | |
| 143 | command = "org.timestamp.evaluate-range" | |
| 144 | [[bind]] | |
| 145 | keys = "C-c C-x f" | |
| 146 | command = "org.footnote.action" | |
| 147 | [[bind]] | |
| 148 | keys = "C-c =" | |
| 149 | command = "org.table.column-formula" | |
| 150 | [[bind]] | |
| 151 | keys = "C-c TAB" | |
| 152 | command = "org.table.toggle-column-width" | |
| 153 | when = "table" | |
| 154 | [[bind]] | |
| 155 | keys = "C-x n s" | |
| 156 | command = "org.narrow.subtree" | |
| 157 | [[bind]] | |
| 158 | keys = "C-x n b" | |
| 159 | command = "org.narrow.block" | |
| 160 | [[bind]] | |
| 161 | keys = "C-x n w" | |
| 162 | command = "org.widen" | |
| 163 | [[bind]] | |
| 164 | keys = "C-x x t" | |
| 165 | command = "editor.toggle-truncate-lines" | |
| 166 | [[bind]] | |
| 167 | keys = "C-c C-j" | |
| 168 | command = "org.goto" | |
| 169 | [[bind]] | |
| 170 | keys = "C-c /" | |
| 171 | command = "org.sparse-tree" | |
| 172 | [[bind]] | |
| 173 | keys = "C-c ," | |
| 174 | command = "org.priority.set" | |
| 175 | [[bind]] | |
| 176 | keys = "C-c C-x p" | |
| 177 | command = "org.property.read-and-set" | |
| 178 | [[bind]] | |
| 179 | keys = "C-c C-x i" | |
| 180 | command = "org.columns.insert-dblock" | |
| 181 | [[bind]] | |
| 182 | keys = "C-c C-x a" | |
| 183 | command = "org.archive.toggle-tag" | |
| 184 | [[bind]] | |
| 185 | keys = "C-c C-x A" | |
| 186 | command = "org.archive.to-sibling" | |
| 187 | [[bind]] | |
| 188 | keys = "C-c C-x o" | |
| 189 | command = "org.property.toggle-ordered" | |
| 190 | [[bind]] | |
| 191 | keys = "C-c C-x C-v" | |
| 192 | command = "org.toggle-inline-images" | |
| 193 | [[bind]] | |
| 194 | keys = "C-c C-x C-c" | |
| 195 | command = "org.columns" | |
| 196 | [[bind]] | |
| 197 | keys = "S-<right>" | |
| 198 | command = "org.property.next-value" | |
| 199 | when = "property" | |
| 200 | [[bind]] | |
| 201 | keys = "S-<left>" | |
| 202 | command = "org.property.previous-value" | |
| 203 | when = "property" | |
| 204 | [[bind]] | |
| 205 | keys = "C-c C-x C-r" | |
| 206 | command = "org.clock.report" | |
| 207 | [[bind]] | |
| 208 | keys = "C-c C-x C-u" | |
| 209 | command = "org.dblock.update" | |
| 210 | [[bind]] | |
| 211 | keys = "C-c C-x e" | |
| 212 | command = "org.effort.set" | |
| 213 | [[bind]] | |
| 214 | keys = "C-c C-c" | |
| 215 | command = "org.dblock.update" | |
| 216 | when = "dblock" | |
| 217 | [[bind]] | |
| 218 | keys = "C-c C-," | |
| 219 | command = "org.structure-template" | |
| 220 | [[bind]] | |
| 221 | keys = "C-c '" | |
| 222 | command = "org.edit-special" | |
| 223 | [[bind]] | |
| 224 | keys = "C-c C-v t" | |
| 225 | command = "org.babel.tangle" | |
| 226 | [[bind]] | |
| 227 | keys = "C-c C-v C-t" | |
| 228 | command = "org.babel.tangle" | |
| 229 | [[bind]] | |
| 230 | keys = "C-c `" | |
| 231 | command = "org.table.edit-field" | |
| 232 | when = "table" | |
| 233 | [[bind]] | |
| 234 | keys = "C-x b" | |
| 235 | command = "app.buffer.switch" | |
| 236 | [[bind]] | |
| 237 | keys = "C-x C-b" | |
| 238 | command = "app.buffer.switch" | |
| 239 | [[bind]] | |
| 240 | keys = "C-x k" | |
| 241 | command = "app.buffer.kill" | |
| 242 | [[bind]] | |
| 243 | keys = "C-x <right>" | |
| 244 | command = "app.buffer.next" | |
| 245 | [[bind]] | |
| 246 | keys = "C-x <left>" | |
| 247 | command = "app.buffer.previous" | |
| 248 | [[bind]] | |
| 249 | keys = "C-x s" | |
| 250 | command = "app.save-all" | |
| 251 | [[bind]] | |
| 252 | keys = "C-x C-f" | |
| 253 | command = "app.quick-open" | |
| 254 | [[bind]] | |
| 255 | keys = "M-x" | |
| 256 | command = "app.palette" | |
| 257 | [[bind]] | |
| 258 | keys = "C-c a" | |
| 259 | command = "app.agenda" | |
| 260 | [[bind]] | |
| 261 | keys = "C-c c" | |
| 262 | command = "app.capture" | |
| 263 | [[bind]] | |
| 264 | keys = "C-c C-x C-i" | |
| 265 | command = "app.clock.in" | |
| 266 | [[bind]] | |
| 267 | keys = "C-c C-x C-o" | |
| 268 | command = "app.clock.out" | |
| 269 | [[bind]] | |
| 270 | keys = "C-c C-x C-q" | |
| 271 | command = "app.clock.cancel" | |
| 272 | [[bind]] | |
| 273 | keys = "C-c C-x C-j" | |
| 274 | command = "app.clock.goto" | |
| 275 | [[bind]] | |
| 276 | keys = "C-c C-x C-x" | |
| 277 | command = "app.clock.in-last" | |
| 278 | [[bind]] | |
| 279 | keys = "C-c C-x C-z" | |
| 280 | command = "app.clock.resolve" | |
| 281 | [[bind]] | |
| 282 | keys = "C-c C-e h h" | |
| 283 | command = "app.export.html" | |
| 284 | [[bind]] | |
| 285 | keys = "C-c C-e h o" | |
| 286 | command = "app.export.html-open" | |
| 287 | [[bind]] | |
| 288 | keys = "C-c C-e m m" | |
| 289 | command = "app.export.markdown" | |
| 290 | [[bind]] | |
| 291 | keys = "C-c C-e l p" | |
| 292 | command = "app.export.pdf" | |
| 293 | [[bind]] | |
| 294 | keys = "C-c C-e l l" | |
| 295 | command = "app.export.latex" | |
| 296 | [[bind]] | |
| 297 | keys = "C-c C-e o o" | |
| 298 | command = "app.export.odt" | |
| 299 | [[bind]] | |
| 300 | keys = "C-c C-e t u" | |
| 301 | command = "app.export.text" | |
| 302 | ||
| 303 | # Org | |
| 304 | [[bind]] | |
| 305 | keys = "C-c C-t" | |
| 306 | command = "org.todo.cycle" | |
| 307 | [[bind]] | |
| 308 | keys = "S-<right>" | |
| 309 | command = "org.todo.next" | |
| 310 | when = "heading" | |
| 311 | [[bind]] | |
| 312 | keys = "S-<left>" | |
| 313 | command = "org.todo.previous" | |
| 314 | when = "heading" | |
| 315 | [[bind]] | |
| 316 | keys = "S-<up>" | |
| 317 | command = "org.priority.up" | |
| 318 | when = "heading" | |
| 319 | [[bind]] | |
| 320 | keys = "S-<down>" | |
| 321 | command = "org.priority.down" | |
| 322 | when = "heading" | |
| 323 | [[bind]] | |
| 324 | keys = "M-<left>" | |
| 325 | command = "org.heading.promote" | |
| 326 | when = "heading" | |
| 327 | [[bind]] | |
| 328 | keys = "M-<right>" | |
| 329 | command = "org.heading.demote" | |
| 330 | when = "heading" | |
| 331 | [[bind]] | |
| 332 | keys = "M-S-<left>" | |
| 333 | command = "org.subtree.promote" | |
| 334 | when = "heading" | |
| 335 | [[bind]] | |
| 336 | keys = "M-S-<right>" | |
| 337 | command = "org.subtree.demote" | |
| 338 | when = "heading" | |
| 339 | [[bind]] | |
| 340 | keys = "M-<up>" | |
| 341 | command = "org.subtree.up" | |
| 342 | when = "heading" | |
| 343 | [[bind]] | |
| 344 | keys = "M-<down>" | |
| 345 | command = "org.subtree.down" | |
| 346 | when = "heading" | |
| 347 | [[bind]] | |
| 348 | keys = "M-RET" | |
| 349 | command = "org.heading.insert" | |
| 350 | [[bind]] | |
| 351 | keys = "C-RET" | |
| 352 | command = "org.heading.insert-after-subtree" | |
| 353 | [[bind]] | |
| 354 | keys = "M-S-RET" | |
| 355 | command = "org.heading.insert-todo" | |
| 356 | [[bind]] | |
| 357 | keys = "C-c C-n" | |
| 358 | command = "org.heading.next" | |
| 359 | [[bind]] | |
| 360 | keys = "C-c C-p" | |
| 361 | command = "org.heading.previous" | |
| 362 | [[bind]] | |
| 363 | keys = "C-c C-f" | |
| 364 | command = "org.heading.forward-same-level" | |
| 365 | [[bind]] | |
| 366 | keys = "C-c C-b" | |
| 367 | command = "org.heading.backward-same-level" | |
| 368 | [[bind]] | |
| 369 | keys = "C-c C-u" | |
| 370 | command = "org.heading.up" | |
| 371 | [[bind]] | |
| 372 | keys = "C-c C-q" | |
| 373 | command = "org.tags.set" | |
| 374 | [[bind]] | |
| 375 | keys = "M-RET" | |
| 376 | command = "org.item.insert" | |
| 377 | when = "item" | |
| 378 | [[bind]] | |
| 379 | keys = "M-S-RET" | |
| 380 | command = "org.item.insert-checkbox" | |
| 381 | when = "item" | |
| 382 | [[bind]] | |
| 383 | keys = "M-<left>" | |
| 384 | command = "org.item.outdent" | |
| 385 | when = "item" | |
| 386 | [[bind]] | |
| 387 | keys = "M-<right>" | |
| 388 | command = "org.item.indent" | |
| 389 | when = "item" | |
| 390 | [[bind]] | |
| 391 | keys = "M-S-<left>" | |
| 392 | command = "org.item.outdent-tree" | |
| 393 | when = "item" | |
| 394 | [[bind]] | |
| 395 | keys = "M-S-<right>" | |
| 396 | command = "org.item.indent-tree" | |
| 397 | when = "item" | |
| 398 | [[bind]] | |
| 399 | keys = "M-<up>" | |
| 400 | command = "org.item.up" | |
| 401 | when = "item" | |
| 402 | [[bind]] | |
| 403 | keys = "M-<down>" | |
| 404 | command = "org.item.down" | |
| 405 | when = "item" | |
| 406 | [[bind]] | |
| 407 | keys = "C-c C-c" | |
| 408 | command = "org.ctrl-c-ctrl-c" | |
| 409 | when = "item" | |
| 410 | [[bind]] | |
| 411 | keys = "C-c C-x C-b" | |
| 412 | command = "org.checkbox.toggle" | |
| 413 | [[bind]] | |
| 414 | keys = "C-c C-w" | |
| 415 | command = "app.refile" | |
| 416 | [[bind]] | |
| 417 | keys = "C-c C-x C-s" | |
| 418 | command = "app.archive" | |
| 419 | [[bind]] | |
| 420 | keys = "C-c $" | |
| 421 | command = "app.archive" | |
| 422 | [[bind]] | |
| 423 | keys = "C-c ." | |
| 424 | command = "org.timestamp.active" | |
| 425 | [[bind]] | |
| 426 | keys = "C-c !" | |
| 427 | command = "org.timestamp.inactive" | |
| 428 | [[bind]] | |
| 429 | keys = "C-c C-s" | |
| 430 | command = "org.schedule" | |
| 431 | [[bind]] | |
| 432 | keys = "C-c C-d" | |
| 433 | command = "org.deadline" | |
| 434 | [[bind]] | |
| 435 | keys = "M-q" | |
| 436 | command = "org.fill-paragraph" | |
| 437 | [[bind]] | |
| 438 | keys = "C-c C-c" | |
| 439 | command = "org.ctrl-c-ctrl-c" | |
| 440 | when = "table" | |
| 441 | [[bind]] | |
| 442 | keys = "C-c C-c" | |
| 443 | command = "org.table.recalc-all" | |
| 444 | when = "tblfm" | |
| 445 | [[bind]] | |
| 446 | keys = "C-c *" | |
| 447 | command = "org.table.recalc" | |
| 448 | when = "table" | |
| 449 | [[bind]] | |
| 450 | keys = "C-c C-c" | |
| 451 | command = "org.babel.execute" | |
| 452 | when = "src" | |
| 453 | [[bind]] | |
| 454 | keys = "M-<up>" | |
| 455 | command = "org.table.row-up" | |
| 456 | when = "table" | |
| 457 | [[bind]] | |
| 458 | keys = "M-<down>" | |
| 459 | command = "org.table.row-down" | |
| 460 | when = "table" | |
| 461 | [[bind]] | |
| 462 | keys = "M-<left>" | |
| 463 | command = "org.table.column-left" | |
| 464 | when = "table" | |
| 465 | [[bind]] | |
| 466 | keys = "M-<right>" | |
| 467 | command = "org.table.column-right" | |
| 468 | when = "table" | |
| 469 | [[bind]] | |
| 470 | keys = "M-S-<right>" | |
| 471 | command = "org.table.insert-column" | |
| 472 | when = "table" | |
| 473 | [[bind]] | |
| 474 | keys = "M-S-<left>" | |
| 475 | command = "org.table.delete-column" | |
| 476 | when = "table" | |
| 477 | [[bind]] | |
| 478 | keys = "M-S-<up>" | |
| 479 | command = "org.table.kill-row" | |
| 480 | when = "table" | |
| 481 | [[bind]] | |
| 482 | keys = "M-S-<down>" | |
| 483 | command = "org.table.insert-row" | |
| 484 | when = "table" | |
| 485 | [[bind]] | |
| 486 | keys = "C-c -" | |
| 487 | command = "org.table.insert-hline" | |
| 488 | when = "table" | |
| 489 | [[bind]] | |
| 490 | keys = "C-c |" | |
| 491 | command = "org.table.create" | |
| 492 | [[bind]] | |
| 493 | keys = "S-<up>" | |
| 494 | command = "org.timestamp.up" | |
| 495 | when = "timestamp" | |
| 496 | [[bind]] | |
| 497 | keys = "S-<down>" | |
| 498 | command = "org.timestamp.down" | |
| 499 | when = "timestamp" | |
| 500 | [[bind]] | |
| 501 | keys = "S-<right>" | |
| 502 | command = "org.timestamp.day-later" | |
| 503 | when = "timestamp" | |
| 504 | [[bind]] | |
| 505 | keys = "S-<left>" | |
| 506 | command = "org.timestamp.day-earlier" | |
| 507 | when = "timestamp" | |
| 508 | ||
| 509 | """ | |
| 510 | ||
| 511 | /// Standard Mac text keys stay as they are; org commands use Control-Command chords, which | |
| 512 | /// macOS text editing leaves free. | |
| 513 | } | |
Sources/OrgCore/Keymap/PresetMac.swift added +270
| @@ -0,0 +1,270 @@ | ||
| 1 | extension KeymapPreset { | |
| 2 | static let macBindings = """ | |
| 3 | [[bind]] | |
| 4 | keys = "C-TAB" | |
| 5 | command = "app.buffer.next" | |
| 6 | [[bind]] | |
| 7 | keys = "C-S-TAB" | |
| 8 | command = "app.buffer.previous" | |
| 9 | [[bind]] | |
| 10 | keys = "C-s-t" | |
| 11 | command = "org.todo.cycle" | |
| 12 | [[bind]] | |
| 13 | keys = "C-s-<up>" | |
| 14 | command = "org.priority.up" | |
| 15 | [[bind]] | |
| 16 | keys = "C-s-<down>" | |
| 17 | command = "org.priority.down" | |
| 18 | [[bind]] | |
| 19 | keys = "C-s-<left>" | |
| 20 | command = "org.heading.promote" | |
| 21 | [[bind]] | |
| 22 | keys = "C-s-<right>" | |
| 23 | command = "org.heading.demote" | |
| 24 | [[bind]] | |
| 25 | keys = "C-M-s-<left>" | |
| 26 | command = "org.subtree.promote" | |
| 27 | [[bind]] | |
| 28 | keys = "C-M-s-<right>" | |
| 29 | command = "org.subtree.demote" | |
| 30 | [[bind]] | |
| 31 | keys = "C-M-s-<up>" | |
| 32 | command = "org.subtree.up" | |
| 33 | [[bind]] | |
| 34 | keys = "C-M-s-<down>" | |
| 35 | command = "org.subtree.down" | |
| 36 | [[bind]] | |
| 37 | keys = "s-RET" | |
| 38 | command = "org.heading.insert" | |
| 39 | [[bind]] | |
| 40 | keys = "C-s-RET" | |
| 41 | command = "org.heading.insert-after-subtree" | |
| 42 | [[bind]] | |
| 43 | keys = "s-S-RET" | |
| 44 | command = "org.heading.insert-todo" | |
| 45 | [[bind]] | |
| 46 | keys = "M-s-<down>" | |
| 47 | command = "org.heading.next" | |
| 48 | [[bind]] | |
| 49 | keys = "M-s-<up>" | |
| 50 | command = "org.heading.previous" | |
| 51 | [[bind]] | |
| 52 | keys = "C-s-g" | |
| 53 | command = "org.tags.set" | |
| 54 | [[bind]] | |
| 55 | keys = "s-RET" | |
| 56 | command = "org.item.insert" | |
| 57 | when = "item" | |
| 58 | [[bind]] | |
| 59 | keys = "s-S-RET" | |
| 60 | command = "org.item.insert-checkbox" | |
| 61 | when = "item" | |
| 62 | [[bind]] | |
| 63 | keys = "C-s-<left>" | |
| 64 | command = "org.item.outdent" | |
| 65 | when = "item" | |
| 66 | [[bind]] | |
| 67 | keys = "C-s-<right>" | |
| 68 | command = "org.item.indent" | |
| 69 | when = "item" | |
| 70 | [[bind]] | |
| 71 | keys = "C-M-s-<left>" | |
| 72 | command = "org.item.outdent-tree" | |
| 73 | when = "item" | |
| 74 | [[bind]] | |
| 75 | keys = "C-M-s-<right>" | |
| 76 | command = "org.item.indent-tree" | |
| 77 | when = "item" | |
| 78 | [[bind]] | |
| 79 | keys = "C-M-s-<up>" | |
| 80 | command = "org.item.up" | |
| 81 | when = "item" | |
| 82 | [[bind]] | |
| 83 | keys = "C-M-s-<down>" | |
| 84 | command = "org.item.down" | |
| 85 | when = "item" | |
| 86 | [[bind]] | |
| 87 | keys = "C-s-c" | |
| 88 | command = "org.checkbox.toggle" | |
| 89 | [[bind]] | |
| 90 | keys = "C-s-w" | |
| 91 | command = "app.refile" | |
| 92 | [[bind]] | |
| 93 | keys = "C-s-a" | |
| 94 | command = "app.archive" | |
| 95 | [[bind]] | |
| 96 | keys = "C-s-." | |
| 97 | command = "org.timestamp.active" | |
| 98 | [[bind]] | |
| 99 | keys = "C-M-s-." | |
| 100 | command = "org.timestamp.inactive" | |
| 101 | [[bind]] | |
| 102 | keys = "C-s-s" | |
| 103 | command = "org.schedule" | |
| 104 | [[bind]] | |
| 105 | keys = "C-s-e" | |
| 106 | command = "org.deadline" | |
| 107 | [[bind]] | |
| 108 | keys = "C-s-p" | |
| 109 | command = "org.fill-paragraph" | |
| 110 | [[bind]] | |
| 111 | keys = "C-s-<up>" | |
| 112 | command = "org.table.row-up" | |
| 113 | when = "table" | |
| 114 | [[bind]] | |
| 115 | keys = "C-s-<down>" | |
| 116 | command = "org.table.row-down" | |
| 117 | when = "table" | |
| 118 | [[bind]] | |
| 119 | keys = "C-s-<left>" | |
| 120 | command = "org.table.column-left" | |
| 121 | when = "table" | |
| 122 | [[bind]] | |
| 123 | keys = "C-s-<right>" | |
| 124 | command = "org.table.column-right" | |
| 125 | when = "table" | |
| 126 | [[bind]] | |
| 127 | keys = "C-M-s-<right>" | |
| 128 | command = "org.table.insert-column" | |
| 129 | when = "table" | |
| 130 | [[bind]] | |
| 131 | keys = "C-M-s-<left>" | |
| 132 | command = "org.table.delete-column" | |
| 133 | when = "table" | |
| 134 | [[bind]] | |
| 135 | keys = "C-M-s-<up>" | |
| 136 | command = "org.table.kill-row" | |
| 137 | when = "table" | |
| 138 | [[bind]] | |
| 139 | keys = "C-M-s-<down>" | |
| 140 | command = "org.table.insert-row" | |
| 141 | when = "table" | |
| 142 | [[bind]] | |
| 143 | keys = "C-s--" | |
| 144 | command = "org.table.insert-hline" | |
| 145 | when = "table" | |
| 146 | [[bind]] | |
| 147 | keys = "C-s-*" | |
| 148 | command = "org.table.recalc" | |
| 149 | when = "table" | |
| 150 | [[bind]] | |
| 151 | keys = "C-s-\\\\" | |
| 152 | command = "org.table.create" | |
| 153 | [[bind]] | |
| 154 | keys = "C-s-<up>" | |
| 155 | command = "org.timestamp.up" | |
| 156 | when = "timestamp" | |
| 157 | [[bind]] | |
| 158 | keys = "C-s-<down>" | |
| 159 | command = "org.timestamp.down" | |
| 160 | when = "timestamp" | |
| 161 | [[bind]] | |
| 162 | keys = "C-s-<right>" | |
| 163 | command = "org.timestamp.day-later" | |
| 164 | when = "timestamp" | |
| 165 | [[bind]] | |
| 166 | keys = "C-s-<left>" | |
| 167 | command = "org.timestamp.day-earlier" | |
| 168 | when = "timestamp" | |
| 169 | ||
| 170 | # Act at point, links, clocking, export and the rest of C-c. | |
| 171 | [[bind]] | |
| 172 | keys = "C-s-x" | |
| 173 | command = "org.ctrl-c-ctrl-c" | |
| 174 | [[bind]] | |
| 175 | keys = "C-s-x" | |
| 176 | command = "org.dblock.update" | |
| 177 | when = "dblock" | |
| 178 | [[bind]] | |
| 179 | keys = "C-s-x" | |
| 180 | command = "org.table.recalc-all" | |
| 181 | when = "tblfm" | |
| 182 | [[bind]] | |
| 183 | keys = "C-s-x" | |
| 184 | command = "org.babel.execute" | |
| 185 | when = "src" | |
| 186 | [[bind]] | |
| 187 | keys = "s-k" | |
| 188 | command = "org.link.insert" | |
| 189 | [[bind]] | |
| 190 | keys = "C-s-o" | |
| 191 | command = "org.link.open" | |
| 192 | [[bind]] | |
| 193 | keys = "C-s-l" | |
| 194 | command = "org.link.store" | |
| 195 | [[bind]] | |
| 196 | keys = "C-s-i" | |
| 197 | command = "app.clock.in" | |
| 198 | [[bind]] | |
| 199 | keys = "C-S-s-i" | |
| 200 | command = "app.clock.out" | |
| 201 | [[bind]] | |
| 202 | keys = "C-s-j" | |
| 203 | command = "app.clock.goto" | |
| 204 | [[bind]] | |
| 205 | keys = "C-M-s-i" | |
| 206 | command = "app.clock.in-recent" | |
| 207 | [[bind]] | |
| 208 | keys = "C-M-s-j" | |
| 209 | command = "app.clock.goto-recent" | |
| 210 | [[bind]] | |
| 211 | keys = "C-s-k" | |
| 212 | command = "app.clock.cancel" | |
| 213 | [[bind]] | |
| 214 | keys = "s-S-e" | |
| 215 | command = "app.export-dialog" | |
| 216 | [[bind]] | |
| 217 | keys = "C-s-n" | |
| 218 | command = "org.narrow.toggle" | |
| 219 | [[bind]] | |
| 220 | keys = "C-S-s-s" | |
| 221 | command = "org.sort" | |
| 222 | [[bind]] | |
| 223 | keys = "C-S-s-p" | |
| 224 | command = "org.property.read-and-set" | |
| 225 | [[bind]] | |
| 226 | keys = "C-S-s-f" | |
| 227 | command = "org.footnote.action" | |
| 228 | [[bind]] | |
| 229 | keys = "C-s-'" | |
| 230 | command = "org.edit-special" | |
| 231 | [[bind]] | |
| 232 | keys = "C-S-s-<right>" | |
| 233 | command = "org.todo.next" | |
| 234 | when = "heading" | |
| 235 | [[bind]] | |
| 236 | keys = "C-S-s-<left>" | |
| 237 | command = "org.todo.previous" | |
| 238 | when = "heading" | |
| 239 | [[bind]] | |
| 240 | keys = "C-S-s-<right>" | |
| 241 | command = "org.property.next-value" | |
| 242 | when = "property" | |
| 243 | [[bind]] | |
| 244 | keys = "C-S-s-<left>" | |
| 245 | command = "org.property.previous-value" | |
| 246 | when = "property" | |
| 247 | [[bind]] | |
| 248 | keys = "M-S-s-<down>" | |
| 249 | command = "org.heading.forward-same-level" | |
| 250 | [[bind]] | |
| 251 | keys = "M-S-s-<up>" | |
| 252 | command = "org.heading.backward-same-level" | |
| 253 | [[bind]] | |
| 254 | keys = "C-S-s-e" | |
| 255 | command = "org.effort.set" | |
| 256 | [[bind]] | |
| 257 | keys = "C-s-," | |
| 258 | command = "org.priority.set" | |
| 259 | [[bind]] | |
| 260 | keys = "C-s-v" | |
| 261 | command = "org.babel.tangle" | |
| 262 | [[bind]] | |
| 263 | keys = "C-S-s-v" | |
| 264 | command = "org.babel.tangle-block" | |
| 265 | [[bind]] | |
| 266 | keys = "C-M-s-v" | |
| 267 | command = "org.babel.tangle-target" | |
| 268 | ||
| 269 | """ | |
| 270 | } | |
Sources/OrgCore/Keymap/Presets.swift −1276
| @@ -50,503 +50,6 @@ public enum KeymapPreset: String, Sendable, CaseIterable { | ||
| 50 | 50 | |
| 51 | 51 | /// Doom: the Emacs preset's org bindings in every evil state (as org-mode-map's are), with |
| 52 | 52 | /// evil-org's `M-h/j/k/l` forms, then Doom's leader, localleader and evil-org keys. |
| 53 | static var doomToml: String { | |
| 54 | var problems: [String] = [] | |
| 55 | let emacs = try! Keymap(toml: common + emacsBindings, problems: &problems) | |
| 56 | let translations: [String: String] = ["<left>": "h", "<right>": "l", "<up>": "k", "<down>": "j"] | |
| 57 | var out = "" | |
| 58 | func bind(_ keys: String, _ command: String, when: String?, mode: String) { | |
| 59 | out += "[[bind]]\nkeys = \"\(keys.replacingOccurrences(of: "\\", with: "\\\\"))\"\ncommand = \"\(command)\"\n" | |
| 60 | if let when { out += "when = \"\(when)\"\n" } | |
| 61 | out += "mode = \"\(mode)\"\n" | |
| 62 | } | |
| 63 | for binding in emacs.bindings { | |
| 64 | let first = binding.keys[0] | |
| 65 | let keys = KeySequence.format(binding.keys) | |
| 66 | let orgKey = first.key == "c" && first.modifiers == [.control] || first.key == "x" && first.modifiers == [.control] | |
| 67 | || (first.modifiers.contains(.meta) && ["<left>", "<right>", "<up>", "<down>", "RET"].contains(first.key)) | |
| 68 | || (first.modifiers.contains(.shift) && ["<left>", "<right>", "<up>", "<down>"].contains(first.key)) | |
| 69 | || (first.modifiers == [.control] && first.key == "RET") | |
| 70 | || keys == "M-x" || keys == "M-q" | |
| 71 | guard orgKey else { continue } | |
| 72 | for mode in ["normal", "insert", "visual"] { bind(keys, binding.command, when: binding.when, mode: mode) } | |
| 73 | // evil-org: M-h/j/k/l and M-H/J/K/L in normal, visual and insert. | |
| 74 | if binding.keys.count == 1, first.modifiers.contains(.meta), let letter = translations[first.key] { | |
| 75 | let shifted = first.modifiers.contains(.shift) | |
| 76 | let key = "M-" + (shifted ? letter.uppercased() : letter) | |
| 77 | for mode in ["normal", "insert", "visual"] { bind(key, binding.command, when: binding.when, mode: mode) } | |
| 78 | } | |
| 79 | // Doom: C-S-h/j/k/l are org-shift* in normal and insert. | |
| 80 | if binding.keys.count == 1, first.modifiers == [.shift], let letter = translations[first.key] { | |
| 81 | for mode in ["normal", "insert"] { bind("C-" + letter.uppercased(), binding.command, when: binding.when, mode: mode) } | |
| 82 | } | |
| 83 | // evil-org insert state: C-t demotes, C-d promotes. | |
| 84 | if binding.keys.count == 1, first.modifiers == [.meta], first.key == "<right>" || first.key == "<left>" { | |
| 85 | bind(first.key == "<right>" ? "C-t" : "C-d", binding.command, when: binding.when, mode: "insert") | |
| 86 | } | |
| 87 | } | |
| 88 | return out + doomBindings | |
| 89 | } | |
| 90 | ||
| 91 | static let doomBindings = """ | |
| 92 | # Leader | |
| 93 | [[bind]] | |
| 94 | keys = "SPC SPC" | |
| 95 | command = "app.quick-open" | |
| 96 | mode = "normal" | |
| 97 | [[bind]] | |
| 98 | keys = "SPC q q" | |
| 99 | command = "app.quit" | |
| 100 | mode = "normal" | |
| 101 | [[bind]] | |
| 102 | keys = "SPC ." | |
| 103 | command = "app.quick-open" | |
| 104 | mode = "normal" | |
| 105 | [[bind]] | |
| 106 | keys = "SPC f f" | |
| 107 | command = "app.quick-open" | |
| 108 | mode = "normal" | |
| 109 | [[bind]] | |
| 110 | keys = "SPC f s" | |
| 111 | command = "app.save" | |
| 112 | mode = "normal" | |
| 113 | # Buffers | |
| 114 | [[bind]] | |
| 115 | keys = "SPC b b" | |
| 116 | command = "app.buffer.switch" | |
| 117 | mode = "normal" | |
| 118 | [[bind]] | |
| 119 | keys = "SPC b B" | |
| 120 | command = "app.buffer.switch" | |
| 121 | mode = "normal" | |
| 122 | [[bind]] | |
| 123 | keys = "SPC ," | |
| 124 | command = "app.buffer.switch" | |
| 125 | mode = "normal" | |
| 126 | [[bind]] | |
| 127 | keys = "SPC `" | |
| 128 | command = "app.buffer.last" | |
| 129 | mode = "normal" | |
| 130 | [[bind]] | |
| 131 | keys = "SPC b k" | |
| 132 | command = "app.buffer.kill" | |
| 133 | mode = "normal" | |
| 134 | [[bind]] | |
| 135 | keys = "SPC b d" | |
| 136 | command = "app.buffer.kill" | |
| 137 | mode = "normal" | |
| 138 | [[bind]] | |
| 139 | keys = "SPC b K" | |
| 140 | command = "app.buffer.kill-all" | |
| 141 | mode = "normal" | |
| 142 | [[bind]] | |
| 143 | keys = "SPC b O" | |
| 144 | command = "app.buffer.kill-others" | |
| 145 | mode = "normal" | |
| 146 | [[bind]] | |
| 147 | keys = "SPC b n" | |
| 148 | command = "app.buffer.next" | |
| 149 | mode = "normal" | |
| 150 | [[bind]] | |
| 151 | keys = "SPC b p" | |
| 152 | command = "app.buffer.previous" | |
| 153 | mode = "normal" | |
| 154 | [[bind]] | |
| 155 | keys = "SPC b ]" | |
| 156 | command = "app.buffer.next" | |
| 157 | mode = "normal" | |
| 158 | [[bind]] | |
| 159 | keys = "SPC b [" | |
| 160 | command = "app.buffer.previous" | |
| 161 | mode = "normal" | |
| 162 | [[bind]] | |
| 163 | keys = "] b" | |
| 164 | command = "app.buffer.next" | |
| 165 | mode = "normal" | |
| 166 | [[bind]] | |
| 167 | keys = "[ b" | |
| 168 | command = "app.buffer.previous" | |
| 169 | mode = "normal" | |
| 170 | [[bind]] | |
| 171 | keys = "SPC b s" | |
| 172 | command = "app.save" | |
| 173 | mode = "normal" | |
| 174 | [[bind]] | |
| 175 | keys = "SPC b S" | |
| 176 | command = "app.save-all" | |
| 177 | mode = "normal" | |
| 178 | [[bind]] | |
| 179 | keys = "SPC s s" | |
| 180 | command = "edit.find" | |
| 181 | mode = "normal" | |
| 182 | [[bind]] | |
| 183 | keys = "SPC /" | |
| 184 | command = "app.search" | |
| 185 | mode = "normal" | |
| 186 | [[bind]] | |
| 187 | keys = "SPC s p" | |
| 188 | command = "app.search" | |
| 189 | mode = "normal" | |
| 190 | [[bind]] | |
| 191 | keys = "SPC :" | |
| 192 | command = "app.palette" | |
| 193 | mode = "normal" | |
| 194 | [[bind]] | |
| 195 | keys = "SPC o a" | |
| 196 | command = "app.agenda" | |
| 197 | mode = "normal" | |
| 198 | [[bind]] | |
| 199 | keys = "SPC X" | |
| 200 | command = "app.capture" | |
| 201 | mode = "normal" | |
| 202 | [[bind]] | |
| 203 | keys = "SPC z t" | |
| 204 | command = "app.clock.report" | |
| 205 | mode = "normal" | |
| 206 | [[bind]] | |
| 207 | keys = "SPC h r r" | |
| 208 | command = "app.reload-keymap" | |
| 209 | mode = "normal" | |
| 210 | [[bind]] | |
| 211 | keys = "SPC t s" | |
| 212 | command = "editor.toggle-spell-check" | |
| 213 | mode = "normal" | |
| 214 | [[bind]] | |
| 215 | keys = "SPC t w" | |
| 216 | command = "editor.toggle-truncate-lines" | |
| 217 | mode = "normal" | |
| 218 | ||
| 219 | # Localleader (SPC m) | |
| 220 | [[bind]] | |
| 221 | keys = "SPC m '" | |
| 222 | command = "org.edit-special" | |
| 223 | mode = "normal" | |
| 224 | [[bind]] | |
| 225 | keys = "SPC m s c" | |
| 226 | command = "org.subtree.clone" | |
| 227 | mode = "normal" | |
| 228 | [[bind]] | |
| 229 | keys = "SPC m s d" | |
| 230 | command = "org.subtree.cut" | |
| 231 | mode = "normal" | |
| 232 | [[bind]] | |
| 233 | keys = "SPC m s S" | |
| 234 | command = "org.sort" | |
| 235 | mode = "normal" | |
| 236 | [[bind]] | |
| 237 | keys = "SPC m s n" | |
| 238 | command = "org.narrow.subtree" | |
| 239 | mode = "normal" | |
| 240 | [[bind]] | |
| 241 | keys = "SPC m s s" | |
| 242 | command = "org.sparse-tree" | |
| 243 | mode = "normal" | |
| 244 | [[bind]] | |
| 245 | keys = "SPC m s N" | |
| 246 | command = "org.widen" | |
| 247 | mode = "normal" | |
| 248 | [[bind]] | |
| 249 | keys = "SPC m ." | |
| 250 | command = "org.goto" | |
| 251 | mode = "normal" | |
| 252 | [[bind]] | |
| 253 | keys = "SPC m h" | |
| 254 | command = "org.heading.toggle" | |
| 255 | mode = "normal" | |
| 256 | [[bind]] | |
| 257 | keys = "SPC m i" | |
| 258 | command = "org.item.toggle" | |
| 259 | mode = "normal" | |
| 260 | [[bind]] | |
| 261 | keys = "SPC m l l" | |
| 262 | command = "org.link.insert" | |
| 263 | mode = "normal" | |
| 264 | [[bind]] | |
| 265 | keys = "SPC m l s" | |
| 266 | command = "org.link.store" | |
| 267 | mode = "normal" | |
| 268 | [[bind]] | |
| 269 | keys = "SPC m l i" | |
| 270 | command = "org.id.store-link" | |
| 271 | mode = "normal" | |
| 272 | [[bind]] | |
| 273 | keys = "SPC n l" | |
| 274 | command = "org.link.store" | |
| 275 | mode = "normal" | |
| 276 | [[bind]] | |
| 277 | keys = "SPC m t" | |
| 278 | command = "org.todo.cycle" | |
| 279 | mode = "normal" | |
| 280 | [[bind]] | |
| 281 | keys = "SPC m q" | |
| 282 | command = "org.tags.set" | |
| 283 | mode = "normal" | |
| 284 | [[bind]] | |
| 285 | keys = "SPC m x" | |
| 286 | command = "org.checkbox.toggle" | |
| 287 | mode = "normal" | |
| 288 | [[bind]] | |
| 289 | keys = "SPC m A" | |
| 290 | command = "app.archive" | |
| 291 | mode = "normal" | |
| 292 | [[bind]] | |
| 293 | keys = "SPC m e h h" | |
| 294 | command = "app.export.html" | |
| 295 | mode = "normal" | |
| 296 | [[bind]] | |
| 297 | keys = "SPC m e h o" | |
| 298 | command = "app.export.html-open" | |
| 299 | mode = "normal" | |
| 300 | [[bind]] | |
| 301 | keys = "SPC m e m m" | |
| 302 | command = "app.export.markdown" | |
| 303 | mode = "normal" | |
| 304 | [[bind]] | |
| 305 | keys = "SPC m e l p" | |
| 306 | command = "app.export.pdf" | |
| 307 | mode = "normal" | |
| 308 | [[bind]] | |
| 309 | keys = "SPC m d d" | |
| 310 | command = "org.deadline" | |
| 311 | mode = "normal" | |
| 312 | [[bind]] | |
| 313 | keys = "SPC m d s" | |
| 314 | command = "org.schedule" | |
| 315 | mode = "normal" | |
| 316 | [[bind]] | |
| 317 | keys = "SPC m d t" | |
| 318 | command = "org.timestamp.active" | |
| 319 | mode = "normal" | |
| 320 | [[bind]] | |
| 321 | keys = "SPC m d T" | |
| 322 | command = "org.timestamp.inactive" | |
| 323 | mode = "normal" | |
| 324 | [[bind]] | |
| 325 | keys = "SPC m r r" | |
| 326 | command = "app.refile" | |
| 327 | mode = "normal" | |
| 328 | [[bind]] | |
| 329 | keys = "SPC m s r" | |
| 330 | command = "app.refile" | |
| 331 | mode = "normal" | |
| 332 | [[bind]] | |
| 333 | keys = "SPC m s A" | |
| 334 | command = "app.archive" | |
| 335 | mode = "normal" | |
| 336 | [[bind]] | |
| 337 | keys = "SPC m s a" | |
| 338 | command = "org.archive.toggle-tag" | |
| 339 | mode = "normal" | |
| 340 | [[bind]] | |
| 341 | keys = "SPC m s h" | |
| 342 | command = "org.subtree.promote" | |
| 343 | mode = "normal" | |
| 344 | [[bind]] | |
| 345 | keys = "SPC m s l" | |
| 346 | command = "org.subtree.demote" | |
| 347 | mode = "normal" | |
| 348 | [[bind]] | |
| 349 | keys = "SPC m s j" | |
| 350 | command = "org.subtree.down" | |
| 351 | mode = "normal" | |
| 352 | [[bind]] | |
| 353 | keys = "SPC m s k" | |
| 354 | command = "org.subtree.up" | |
| 355 | mode = "normal" | |
| 356 | [[bind]] | |
| 357 | keys = "SPC m c i" | |
| 358 | command = "app.clock.in" | |
| 359 | mode = "normal" | |
| 360 | [[bind]] | |
| 361 | keys = "SPC m c o" | |
| 362 | command = "app.clock.out" | |
| 363 | mode = "normal" | |
| 364 | [[bind]] | |
| 365 | keys = "SPC m c c" | |
| 366 | command = "app.clock.cancel" | |
| 367 | mode = "normal" | |
| 368 | [[bind]] | |
| 369 | keys = "SPC m c g" | |
| 370 | command = "app.clock.goto" | |
| 371 | mode = "normal" | |
| 372 | [[bind]] | |
| 373 | keys = "SPC m c G" | |
| 374 | command = "app.clock.goto-recent" | |
| 375 | mode = "normal" | |
| 376 | [[bind]] | |
| 377 | keys = "SPC m c I" | |
| 378 | command = "app.clock.in-last" | |
| 379 | mode = "normal" | |
| 380 | [[bind]] | |
| 381 | keys = "SPC m c d" | |
| 382 | command = "app.clock.default" | |
| 383 | mode = "normal" | |
| 384 | [[bind]] | |
| 385 | keys = "SPC m c r" | |
| 386 | command = "app.clock.resolve" | |
| 387 | mode = "normal" | |
| 388 | [[bind]] | |
| 389 | keys = "SPC m c R" | |
| 390 | command = "app.clock.report" | |
| 391 | mode = "normal" | |
| 392 | [[bind]] | |
| 393 | keys = "SPC m c E" | |
| 394 | command = "org.effort.set" | |
| 395 | mode = "normal" | |
| 396 | [[bind]] | |
| 397 | keys = "SPC m p p" | |
| 398 | command = "org.priority.set" | |
| 399 | mode = "normal" | |
| 400 | [[bind]] | |
| 401 | keys = "SPC m o" | |
| 402 | command = "org.property.read-and-set" | |
| 403 | mode = "normal" | |
| 404 | [[bind]] | |
| 405 | keys = "SPC m p u" | |
| 406 | command = "org.priority.up" | |
| 407 | mode = "normal" | |
| 408 | [[bind]] | |
| 409 | keys = "SPC m p d" | |
| 410 | command = "org.priority.down" | |
| 411 | mode = "normal" | |
| 412 | [[bind]] | |
| 413 | keys = "SPC m b -" | |
| 414 | command = "org.table.insert-hline" | |
| 415 | mode = "normal" | |
| 416 | [[bind]] | |
| 417 | keys = "SPC m b a" | |
| 418 | command = "org.table.align" | |
| 419 | mode = "normal" | |
| 420 | [[bind]] | |
| 421 | keys = "SPC m b r" | |
| 422 | command = "org.table.recalc-all" | |
| 423 | mode = "normal" | |
| 424 | [[bind]] | |
| 425 | keys = "SPC m b d c" | |
| 426 | command = "org.table.delete-column" | |
| 427 | mode = "normal" | |
| 428 | [[bind]] | |
| 429 | keys = "SPC m b d r" | |
| 430 | command = "org.table.kill-row" | |
| 431 | mode = "normal" | |
| 432 | [[bind]] | |
| 433 | keys = "SPC m b i c" | |
| 434 | command = "org.table.insert-column" | |
| 435 | mode = "normal" | |
| 436 | [[bind]] | |
| 437 | keys = "SPC m b i r" | |
| 438 | command = "org.table.insert-row" | |
| 439 | mode = "normal" | |
| 440 | [[bind]] | |
| 441 | keys = "SPC m b i h" | |
| 442 | command = "org.table.insert-hline" | |
| 443 | mode = "normal" | |
| 444 | ||
| 445 | # evil-org and Doom's org keys | |
| 446 | [[bind]] | |
| 447 | keys = "TAB" | |
| 448 | command = "org.cycle" | |
| 449 | mode = "normal" | |
| 450 | [[bind]] | |
| 451 | keys = "S-TAB" | |
| 452 | command = "org.cycle-global" | |
| 453 | mode = "normal" | |
| 454 | [[bind]] | |
| 455 | keys = "RET" | |
| 456 | command = "org.dwim" | |
| 457 | mode = "normal" | |
| 458 | [[bind]] | |
| 459 | keys = "z a" | |
| 460 | command = "org.fold.toggle" | |
| 461 | mode = "normal" | |
| 462 | [[bind]] | |
| 463 | keys = "z c" | |
| 464 | command = "org.fold.close" | |
| 465 | mode = "normal" | |
| 466 | [[bind]] | |
| 467 | keys = "z o" | |
| 468 | command = "org.fold.open" | |
| 469 | mode = "normal" | |
| 470 | [[bind]] | |
| 471 | keys = "z A" | |
| 472 | command = "org.cycle-global" | |
| 473 | mode = "normal" | |
| 474 | [[bind]] | |
| 475 | keys = "g h" | |
| 476 | command = "org.heading.up" | |
| 477 | mode = "normal" | |
| 478 | [[bind]] | |
| 479 | keys = "] h" | |
| 480 | command = "org.heading.forward-same-level" | |
| 481 | mode = "normal" | |
| 482 | [[bind]] | |
| 483 | keys = "[ h" | |
| 484 | command = "org.heading.backward-same-level" | |
| 485 | mode = "normal" | |
| 486 | [[bind]] | |
| 487 | keys = "RET" | |
| 488 | command = "org.table.next-row" | |
| 489 | when = "table" | |
| 490 | mode = "insert" | |
| 491 | [[bind]] | |
| 492 | keys = "TAB" | |
| 493 | command = "org.cycle" | |
| 494 | mode = "visual" | |
| 495 | [[bind]] | |
| 496 | keys = "S-TAB" | |
| 497 | command = "org.cycle-global" | |
| 498 | mode = "visual" | |
| 499 | ||
| 500 | # Doom's corfu: completion-at-point in insert state. | |
| 501 | [[bind]] | |
| 502 | keys = "C-SPC" | |
| 503 | command = "editor.complete" | |
| 504 | mode = "insert" | |
| 505 | [[bind]] | |
| 506 | keys = "C-@" | |
| 507 | command = "editor.complete" | |
| 508 | mode = "insert" | |
| 509 | ||
| 510 | # Insert state: org-cycle and org-shifttab with Doom's +org-indent-maybe-h, which | |
| 511 | # demotes or promotes a heading and indents or outdents an item tree. | |
| 512 | [[bind]] | |
| 513 | keys = "S-TAB" | |
| 514 | command = "org.cycle-global" | |
| 515 | mode = "insert" | |
| 516 | [[bind]] | |
| 517 | keys = "TAB" | |
| 518 | command = "org.table.next-field" | |
| 519 | when = "table" | |
| 520 | mode = "insert" | |
| 521 | [[bind]] | |
| 522 | keys = "S-TAB" | |
| 523 | command = "org.table.previous-field" | |
| 524 | when = "table" | |
| 525 | mode = "insert" | |
| 526 | [[bind]] | |
| 527 | keys = "TAB" | |
| 528 | command = "org.item.indent-tree" | |
| 529 | when = "item" | |
| 530 | mode = "insert" | |
| 531 | [[bind]] | |
| 532 | keys = "S-TAB" | |
| 533 | command = "org.item.outdent-tree" | |
| 534 | when = "item" | |
| 535 | mode = "insert" | |
| 536 | [[bind]] | |
| 537 | keys = "TAB" | |
| 538 | command = "org.heading.demote" | |
| 539 | when = "heading" | |
| 540 | mode = "insert" | |
| 541 | [[bind]] | |
| 542 | keys = "S-TAB" | |
| 543 | command = "org.heading.promote" | |
| 544 | when = "heading" | |
| 545 | mode = "insert" | |
| 546 | ||
| 547 | """ | |
| 548 | ||
| 549 | ||
| 550 | 53 | static let common = """ |
| 551 | 54 | [[bind]] |
| 552 | 55 | keys = "TAB" |
| @@ -575,783 +78,4 @@ public enum KeymapPreset: String, Sendable, CaseIterable { | ||
| 575 | 78 | |
| 576 | 79 | """ |
| 577 | 80 | |
| 578 | static let emacsBindings = """ | |
| 579 | # Movement and editing. With a mark set (C-SPC), movement extends the region. | |
| 580 | [[bind]] | |
| 581 | keys = "C-f" | |
| 582 | command = "edit.forward-char" | |
| 583 | [[bind]] | |
| 584 | keys = "C-b" | |
| 585 | command = "edit.backward-char" | |
| 586 | [[bind]] | |
| 587 | keys = "C-n" | |
| 588 | command = "edit.next-line" | |
| 589 | [[bind]] | |
| 590 | keys = "C-p" | |
| 591 | command = "edit.previous-line" | |
| 592 | [[bind]] | |
| 593 | keys = "C-a" | |
| 594 | command = "edit.beginning-of-line" | |
| 595 | [[bind]] | |
| 596 | keys = "C-e" | |
| 597 | command = "edit.end-of-line" | |
| 598 | [[bind]] | |
| 599 | keys = "M-f" | |
| 600 | command = "edit.forward-word" | |
| 601 | [[bind]] | |
| 602 | keys = "M-b" | |
| 603 | command = "edit.backward-word" | |
| 604 | [[bind]] | |
| 605 | keys = "M-<" | |
| 606 | command = "edit.beginning-of-buffer" | |
| 607 | [[bind]] | |
| 608 | keys = "M->" | |
| 609 | command = "edit.end-of-buffer" | |
| 610 | [[bind]] | |
| 611 | keys = "C-v" | |
| 612 | command = "edit.scroll-up" | |
| 613 | [[bind]] | |
| 614 | keys = "M-v" | |
| 615 | command = "edit.scroll-down" | |
| 616 | [[bind]] | |
| 617 | keys = "C-l" | |
| 618 | command = "edit.recenter" | |
| 619 | [[bind]] | |
| 620 | keys = "C-d" | |
| 621 | command = "edit.delete-char" | |
| 622 | [[bind]] | |
| 623 | keys = "M-d" | |
| 624 | command = "edit.kill-word" | |
| 625 | [[bind]] | |
| 626 | keys = "M-DEL" | |
| 627 | command = "edit.backward-kill-word" | |
| 628 | [[bind]] | |
| 629 | keys = "C-k" | |
| 630 | command = "edit.kill-line" | |
| 631 | [[bind]] | |
| 632 | keys = "C-y" | |
| 633 | command = "edit.yank" | |
| 634 | [[bind]] | |
| 635 | keys = "C-SPC" | |
| 636 | command = "edit.set-mark" | |
| 637 | [[bind]] | |
| 638 | keys = "C-M-i" | |
| 639 | command = "editor.complete" | |
| 640 | [[bind]] | |
| 641 | keys = "C-x h" | |
| 642 | command = "edit.select-all" | |
| 643 | [[bind]] | |
| 644 | keys = "C-w" | |
| 645 | command = "edit.kill-region" | |
| 646 | [[bind]] | |
| 647 | keys = "M-w" | |
| 648 | command = "edit.copy-region" | |
| 649 | [[bind]] | |
| 650 | keys = "C-/" | |
| 651 | command = "edit.undo" | |
| 652 | [[bind]] | |
| 653 | keys = "C-_" | |
| 654 | command = "edit.undo" | |
| 655 | [[bind]] | |
| 656 | keys = "C-x u" | |
| 657 | command = "edit.undo" | |
| 658 | [[bind]] | |
| 659 | keys = "C-g" | |
| 660 | command = "edit.keyboard-quit" | |
| 661 | [[bind]] | |
| 662 | keys = "C-t" | |
| 663 | command = "edit.transpose-chars" | |
| 664 | [[bind]] | |
| 665 | keys = "C-s" | |
| 666 | command = "edit.find" | |
| 667 | [[bind]] | |
| 668 | keys = "C-r" | |
| 669 | command = "edit.find" | |
| 670 | [[bind]] | |
| 671 | keys = "M-%" | |
| 672 | command = "edit.replace" | |
| 673 | ||
| 674 | # Files and commands | |
| 675 | [[bind]] | |
| 676 | keys = "C-x C-s" | |
| 677 | command = "app.save" | |
| 678 | [[bind]] | |
| 679 | keys = "C-c C-o" | |
| 680 | command = "org.link.open" | |
| 681 | [[bind]] | |
| 682 | keys = "C-c C-l" | |
| 683 | command = "org.link.insert" | |
| 684 | [[bind]] | |
| 685 | keys = "C-c l" | |
| 686 | command = "org.link.store" | |
| 687 | [[bind]] | |
| 688 | keys = "C-c ;" | |
| 689 | command = "org.heading.toggle-comment" | |
| 690 | [[bind]] | |
| 691 | keys = "C-c *" | |
| 692 | command = "org.heading.toggle" | |
| 693 | [[bind]] | |
| 694 | keys = "C-c -" | |
| 695 | command = "org.item.toggle" | |
| 696 | [[bind]] | |
| 697 | keys = "C-c @" | |
| 698 | command = "org.subtree.mark" | |
| 699 | [[bind]] | |
| 700 | keys = "C-c C-x C-w" | |
| 701 | command = "org.subtree.cut" | |
| 702 | [[bind]] | |
| 703 | keys = "C-c C-x M-w" | |
| 704 | command = "org.subtree.copy" | |
| 705 | [[bind]] | |
| 706 | keys = "C-c C-x C-y" | |
| 707 | command = "org.subtree.paste" | |
| 708 | [[bind]] | |
| 709 | keys = "C-c C-x c" | |
| 710 | command = "org.subtree.clone" | |
| 711 | [[bind]] | |
| 712 | keys = "C-c ^" | |
| 713 | command = "org.sort" | |
| 714 | [[bind]] | |
| 715 | keys = "C-c C-c" | |
| 716 | command = "org.ctrl-c-ctrl-c" | |
| 717 | [[bind]] | |
| 718 | keys = "C-c C-y" | |
| 719 | command = "org.timestamp.evaluate-range" | |
| 720 | [[bind]] | |
| 721 | keys = "C-c C-x f" | |
| 722 | command = "org.footnote.action" | |
| 723 | [[bind]] | |
| 724 | keys = "C-c =" | |
| 725 | command = "org.table.column-formula" | |
| 726 | [[bind]] | |
| 727 | keys = "C-c TAB" | |
| 728 | command = "org.table.toggle-column-width" | |
| 729 | when = "table" | |
| 730 | [[bind]] | |
| 731 | keys = "C-x n s" | |
| 732 | command = "org.narrow.subtree" | |
| 733 | [[bind]] | |
| 734 | keys = "C-x n b" | |
| 735 | command = "org.narrow.block" | |
| 736 | [[bind]] | |
| 737 | keys = "C-x n w" | |
| 738 | command = "org.widen" | |
| 739 | [[bind]] | |
| 740 | keys = "C-x x t" | |
| 741 | command = "editor.toggle-truncate-lines" | |
| 742 | [[bind]] | |
| 743 | keys = "C-c C-j" | |
| 744 | command = "org.goto" | |
| 745 | [[bind]] | |
| 746 | keys = "C-c /" | |
| 747 | command = "org.sparse-tree" | |
| 748 | [[bind]] | |
| 749 | keys = "C-c ," | |
| 750 | command = "org.priority.set" | |
| 751 | [[bind]] | |
| 752 | keys = "C-c C-x p" | |
| 753 | command = "org.property.read-and-set" | |
| 754 | [[bind]] | |
| 755 | keys = "C-c C-x i" | |
| 756 | command = "org.columns.insert-dblock" | |
| 757 | [[bind]] | |
| 758 | keys = "C-c C-x a" | |
| 759 | command = "org.archive.toggle-tag" | |
| 760 | [[bind]] | |
| 761 | keys = "C-c C-x A" | |
| 762 | command = "org.archive.to-sibling" | |
| 763 | [[bind]] | |
| 764 | keys = "C-c C-x o" | |
| 765 | command = "org.property.toggle-ordered" | |
| 766 | [[bind]] | |
| 767 | keys = "C-c C-x C-v" | |
| 768 | command = "org.toggle-inline-images" | |
| 769 | [[bind]] | |
| 770 | keys = "C-c C-x C-c" | |
| 771 | command = "org.columns" | |
| 772 | [[bind]] | |
| 773 | keys = "S-<right>" | |
| 774 | command = "org.property.next-value" | |
| 775 | when = "property" | |
| 776 | [[bind]] | |
| 777 | keys = "S-<left>" | |
| 778 | command = "org.property.previous-value" | |
| 779 | when = "property" | |
| 780 | [[bind]] | |
| 781 | keys = "C-c C-x C-r" | |
| 782 | command = "org.clock.report" | |
| 783 | [[bind]] | |
| 784 | keys = "C-c C-x C-u" | |
| 785 | command = "org.dblock.update" | |
| 786 | [[bind]] | |
| 787 | keys = "C-c C-x e" | |
| 788 | command = "org.effort.set" | |
| 789 | [[bind]] | |
| 790 | keys = "C-c C-c" | |
| 791 | command = "org.dblock.update" | |
| 792 | when = "dblock" | |
| 793 | [[bind]] | |
| 794 | keys = "C-c C-," | |
| 795 | command = "org.structure-template" | |
| 796 | [[bind]] | |
| 797 | keys = "C-c '" | |
| 798 | command = "org.edit-special" | |
| 799 | [[bind]] | |
| 800 | keys = "C-c C-v t" | |
| 801 | command = "org.babel.tangle" | |
| 802 | [[bind]] | |
| 803 | keys = "C-c C-v C-t" | |
| 804 | command = "org.babel.tangle" | |
| 805 | [[bind]] | |
| 806 | keys = "C-c `" | |
| 807 | command = "org.table.edit-field" | |
| 808 | when = "table" | |
| 809 | [[bind]] | |
| 810 | keys = "C-x b" | |
| 811 | command = "app.buffer.switch" | |
| 812 | [[bind]] | |
| 813 | keys = "C-x C-b" | |
| 814 | command = "app.buffer.switch" | |
| 815 | [[bind]] | |
| 816 | keys = "C-x k" | |
| 817 | command = "app.buffer.kill" | |
| 818 | [[bind]] | |
| 819 | keys = "C-x <right>" | |
| 820 | command = "app.buffer.next" | |
| 821 | [[bind]] | |
| 822 | keys = "C-x <left>" | |
| 823 | command = "app.buffer.previous" | |
| 824 | [[bind]] | |
| 825 | keys = "C-x s" | |
| 826 | command = "app.save-all" | |
| 827 | [[bind]] | |
| 828 | keys = "C-x C-f" | |
| 829 | command = "app.quick-open" | |
| 830 | [[bind]] | |
| 831 | keys = "M-x" | |
| 832 | command = "app.palette" | |
| 833 | [[bind]] | |
| 834 | keys = "C-c a" | |
| 835 | command = "app.agenda" | |
| 836 | [[bind]] | |
| 837 | keys = "C-c c" | |
| 838 | command = "app.capture" | |
| 839 | [[bind]] | |
| 840 | keys = "C-c C-x C-i" | |
| 841 | command = "app.clock.in" | |
| 842 | [[bind]] | |
| 843 | keys = "C-c C-x C-o" | |
| 844 | command = "app.clock.out" | |
| 845 | [[bind]] | |
| 846 | keys = "C-c C-x C-q" | |
| 847 | command = "app.clock.cancel" | |
| 848 | [[bind]] | |
| 849 | keys = "C-c C-x C-j" | |
| 850 | command = "app.clock.goto" | |
| 851 | [[bind]] | |
| 852 | keys = "C-c C-x C-x" | |
| 853 | command = "app.clock.in-last" | |
| 854 | [[bind]] | |
| 855 | keys = "C-c C-x C-z" | |
| 856 | command = "app.clock.resolve" | |
| 857 | [[bind]] | |
| 858 | keys = "C-c C-e h h" | |
| 859 | command = "app.export.html" | |
| 860 | [[bind]] | |
| 861 | keys = "C-c C-e h o" | |
| 862 | command = "app.export.html-open" | |
| 863 | [[bind]] | |
| 864 | keys = "C-c C-e m m" | |
| 865 | command = "app.export.markdown" | |
| 866 | [[bind]] | |
| 867 | keys = "C-c C-e l p" | |
| 868 | command = "app.export.pdf" | |
| 869 | [[bind]] | |
| 870 | keys = "C-c C-e l l" | |
| 871 | command = "app.export.latex" | |
| 872 | [[bind]] | |
| 873 | keys = "C-c C-e o o" | |
| 874 | command = "app.export.odt" | |
| 875 | [[bind]] | |
| 876 | keys = "C-c C-e t u" | |
| 877 | command = "app.export.text" | |
| 878 | ||
| 879 | # Org | |
| 880 | [[bind]] | |
| 881 | keys = "C-c C-t" | |
| 882 | command = "org.todo.cycle" | |
| 883 | [[bind]] | |
| 884 | keys = "S-<right>" | |
| 885 | command = "org.todo.next" | |
| 886 | when = "heading" | |
| 887 | [[bind]] | |
| 888 | keys = "S-<left>" | |
| 889 | command = "org.todo.previous" | |
| 890 | when = "heading" | |
| 891 | [[bind]] | |
| 892 | keys = "S-<up>" | |
| 893 | command = "org.priority.up" | |
| 894 | when = "heading" | |
| 895 | [[bind]] | |
| 896 | keys = "S-<down>" | |
| 897 | command = "org.priority.down" | |
| 898 | when = "heading" | |
| 899 | [[bind]] | |
| 900 | keys = "M-<left>" | |
| 901 | command = "org.heading.promote" | |
| 902 | when = "heading" | |
| 903 | [[bind]] | |
| 904 | keys = "M-<right>" | |
| 905 | command = "org.heading.demote" | |
| 906 | when = "heading" | |
| 907 | [[bind]] | |
| 908 | keys = "M-S-<left>" | |
| 909 | command = "org.subtree.promote" | |
| 910 | when = "heading" | |
| 911 | [[bind]] | |
| 912 | keys = "M-S-<right>" | |
| 913 | command = "org.subtree.demote" | |
| 914 | when = "heading" | |
| 915 | [[bind]] | |
| 916 | keys = "M-<up>" | |
| 917 | command = "org.subtree.up" | |
| 918 | when = "heading" | |
| 919 | [[bind]] | |
| 920 | keys = "M-<down>" | |
| 921 | command = "org.subtree.down" | |
| 922 | when = "heading" | |
| 923 | [[bind]] | |
| 924 | keys = "M-RET" | |
| 925 | command = "org.heading.insert" | |
| 926 | [[bind]] | |
| 927 | keys = "C-RET" | |
| 928 | command = "org.heading.insert-after-subtree" | |
| 929 | [[bind]] | |
| 930 | keys = "M-S-RET" | |
| 931 | command = "org.heading.insert-todo" | |
| 932 | [[bind]] | |
| 933 | keys = "C-c C-n" | |
| 934 | command = "org.heading.next" | |
| 935 | [[bind]] | |
| 936 | keys = "C-c C-p" | |
| 937 | command = "org.heading.previous" | |
| 938 | [[bind]] | |
| 939 | keys = "C-c C-f" | |
| 940 | command = "org.heading.forward-same-level" | |
| 941 | [[bind]] | |
| 942 | keys = "C-c C-b" | |
| 943 | command = "org.heading.backward-same-level" | |
| 944 | [[bind]] | |
| 945 | keys = "C-c C-u" | |
| 946 | command = "org.heading.up" | |
| 947 | [[bind]] | |
| 948 | keys = "C-c C-q" | |
| 949 | command = "org.tags.set" | |
| 950 | [[bind]] | |
| 951 | keys = "M-RET" | |
| 952 | command = "org.item.insert" | |
| 953 | when = "item" | |
| 954 | [[bind]] | |
| 955 | keys = "M-S-RET" | |
| 956 | command = "org.item.insert-checkbox" | |
| 957 | when = "item" | |
| 958 | [[bind]] | |
| 959 | keys = "M-<left>" | |
| 960 | command = "org.item.outdent" | |
| 961 | when = "item" | |
| 962 | [[bind]] | |
| 963 | keys = "M-<right>" | |
| 964 | command = "org.item.indent" | |
| 965 | when = "item" | |
| 966 | [[bind]] | |
| 967 | keys = "M-S-<left>" | |
| 968 | command = "org.item.outdent-tree" | |
| 969 | when = "item" | |
| 970 | [[bind]] | |
| 971 | keys = "M-S-<right>" | |
| 972 | command = "org.item.indent-tree" | |
| 973 | when = "item" | |
| 974 | [[bind]] | |
| 975 | keys = "M-<up>" | |
| 976 | command = "org.item.up" | |
| 977 | when = "item" | |
| 978 | [[bind]] | |
| 979 | keys = "M-<down>" | |
| 980 | command = "org.item.down" | |
| 981 | when = "item" | |
| 982 | [[bind]] | |
| 983 | keys = "C-c C-c" | |
| 984 | command = "org.ctrl-c-ctrl-c" | |
| 985 | when = "item" | |
| 986 | [[bind]] | |
| 987 | keys = "C-c C-x C-b" | |
| 988 | command = "org.checkbox.toggle" | |
| 989 | [[bind]] | |
| 990 | keys = "C-c C-w" | |
| 991 | command = "app.refile" | |
| 992 | [[bind]] | |
| 993 | keys = "C-c C-x C-s" | |
| 994 | command = "app.archive" | |
| 995 | [[bind]] | |
| 996 | keys = "C-c $" | |
| 997 | command = "app.archive" | |
| 998 | [[bind]] | |
| 999 | keys = "C-c ." | |
| 1000 | command = "org.timestamp.active" | |
| 1001 | [[bind]] | |
| 1002 | keys = "C-c !" | |
| 1003 | command = "org.timestamp.inactive" | |
| 1004 | [[bind]] | |
| 1005 | keys = "C-c C-s" | |
| 1006 | command = "org.schedule" | |
| 1007 | [[bind]] | |
| 1008 | keys = "C-c C-d" | |
| 1009 | command = "org.deadline" | |
| 1010 | [[bind]] | |
| 1011 | keys = "M-q" | |
| 1012 | command = "org.fill-paragraph" | |
| 1013 | [[bind]] | |
| 1014 | keys = "C-c C-c" | |
| 1015 | command = "org.ctrl-c-ctrl-c" | |
| 1016 | when = "table" | |
| 1017 | [[bind]] | |
| 1018 | keys = "C-c C-c" | |
| 1019 | command = "org.table.recalc-all" | |
| 1020 | when = "tblfm" | |
| 1021 | [[bind]] | |
| 1022 | keys = "C-c *" | |
| 1023 | command = "org.table.recalc" | |
| 1024 | when = "table" | |
| 1025 | [[bind]] | |
| 1026 | keys = "C-c C-c" | |
| 1027 | command = "org.babel.execute" | |
| 1028 | when = "src" | |
| 1029 | [[bind]] | |
| 1030 | keys = "M-<up>" | |
| 1031 | command = "org.table.row-up" | |
| 1032 | when = "table" | |
| 1033 | [[bind]] | |
| 1034 | keys = "M-<down>" | |
| 1035 | command = "org.table.row-down" | |
| 1036 | when = "table" | |
| 1037 | [[bind]] | |
| 1038 | keys = "M-<left>" | |
| 1039 | command = "org.table.column-left" | |
| 1040 | when = "table" | |
| 1041 | [[bind]] | |
| 1042 | keys = "M-<right>" | |
| 1043 | command = "org.table.column-right" | |
| 1044 | when = "table" | |
| 1045 | [[bind]] | |
| 1046 | keys = "M-S-<right>" | |
| 1047 | command = "org.table.insert-column" | |
| 1048 | when = "table" | |
| 1049 | [[bind]] | |
| 1050 | keys = "M-S-<left>" | |
| 1051 | command = "org.table.delete-column" | |
| 1052 | when = "table" | |
| 1053 | [[bind]] | |
| 1054 | keys = "M-S-<up>" | |
| 1055 | command = "org.table.kill-row" | |
| 1056 | when = "table" | |
| 1057 | [[bind]] | |
| 1058 | keys = "M-S-<down>" | |
| 1059 | command = "org.table.insert-row" | |
| 1060 | when = "table" | |
| 1061 | [[bind]] | |
| 1062 | keys = "C-c -" | |
| 1063 | command = "org.table.insert-hline" | |
| 1064 | when = "table" | |
| 1065 | [[bind]] | |
| 1066 | keys = "C-c |" | |
| 1067 | command = "org.table.create" | |
| 1068 | [[bind]] | |
| 1069 | keys = "S-<up>" | |
| 1070 | command = "org.timestamp.up" | |
| 1071 | when = "timestamp" | |
| 1072 | [[bind]] | |
| 1073 | keys = "S-<down>" | |
| 1074 | command = "org.timestamp.down" | |
| 1075 | when = "timestamp" | |
| 1076 | [[bind]] | |
| 1077 | keys = "S-<right>" | |
| 1078 | command = "org.timestamp.day-later" | |
| 1079 | when = "timestamp" | |
| 1080 | [[bind]] | |
| 1081 | keys = "S-<left>" | |
| 1082 | command = "org.timestamp.day-earlier" | |
| 1083 | when = "timestamp" | |
| 1084 | ||
| 1085 | """ | |
| 1086 | ||
| 1087 | /// Standard Mac text keys stay as they are; org commands use Control-Command chords, which | |
| 1088 | /// macOS text editing leaves free. | |
| 1089 | static let macBindings = """ | |
| 1090 | [[bind]] | |
| 1091 | keys = "C-TAB" | |
| 1092 | command = "app.buffer.next" | |
| 1093 | [[bind]] | |
| 1094 | keys = "C-S-TAB" | |
| 1095 | command = "app.buffer.previous" | |
| 1096 | [[bind]] | |
| 1097 | keys = "C-s-t" | |
| 1098 | command = "org.todo.cycle" | |
| 1099 | [[bind]] | |
| 1100 | keys = "C-s-<up>" | |
| 1101 | command = "org.priority.up" | |
| 1102 | [[bind]] | |
| 1103 | keys = "C-s-<down>" | |
| 1104 | command = "org.priority.down" | |
| 1105 | [[bind]] | |
| 1106 | keys = "C-s-<left>" | |
| 1107 | command = "org.heading.promote" | |
| 1108 | [[bind]] | |
| 1109 | keys = "C-s-<right>" | |
| 1110 | command = "org.heading.demote" | |
| 1111 | [[bind]] | |
| 1112 | keys = "C-M-s-<left>" | |
| 1113 | command = "org.subtree.promote" | |
| 1114 | [[bind]] | |
| 1115 | keys = "C-M-s-<right>" | |
| 1116 | command = "org.subtree.demote" | |
| 1117 | [[bind]] | |
| 1118 | keys = "C-M-s-<up>" | |
| 1119 | command = "org.subtree.up" | |
| 1120 | [[bind]] | |
| 1121 | keys = "C-M-s-<down>" | |
| 1122 | command = "org.subtree.down" | |
| 1123 | [[bind]] | |
| 1124 | keys = "s-RET" | |
| 1125 | command = "org.heading.insert" | |
| 1126 | [[bind]] | |
| 1127 | keys = "C-s-RET" | |
| 1128 | command = "org.heading.insert-after-subtree" | |
| 1129 | [[bind]] | |
| 1130 | keys = "s-S-RET" | |
| 1131 | command = "org.heading.insert-todo" | |
| 1132 | [[bind]] | |
| 1133 | keys = "M-s-<down>" | |
| 1134 | command = "org.heading.next" | |
| 1135 | [[bind]] | |
| 1136 | keys = "M-s-<up>" | |
| 1137 | command = "org.heading.previous" | |
| 1138 | [[bind]] | |
| 1139 | keys = "C-s-g" | |
| 1140 | command = "org.tags.set" | |
| 1141 | [[bind]] | |
| 1142 | keys = "s-RET" | |
| 1143 | command = "org.item.insert" | |
| 1144 | when = "item" | |
| 1145 | [[bind]] | |
| 1146 | keys = "s-S-RET" | |
| 1147 | command = "org.item.insert-checkbox" | |
| 1148 | when = "item" | |
| 1149 | [[bind]] | |
| 1150 | keys = "C-s-<left>" | |
| 1151 | command = "org.item.outdent" | |
| 1152 | when = "item" | |
| 1153 | [[bind]] | |
| 1154 | keys = "C-s-<right>" | |
| 1155 | command = "org.item.indent" | |
| 1156 | when = "item" | |
| 1157 | [[bind]] | |
| 1158 | keys = "C-M-s-<left>" | |
| 1159 | command = "org.item.outdent-tree" | |
| 1160 | when = "item" | |
| 1161 | [[bind]] | |
| 1162 | keys = "C-M-s-<right>" | |
| 1163 | command = "org.item.indent-tree" | |
| 1164 | when = "item" | |
| 1165 | [[bind]] | |
| 1166 | keys = "C-M-s-<up>" | |
| 1167 | command = "org.item.up" | |
| 1168 | when = "item" | |
| 1169 | [[bind]] | |
| 1170 | keys = "C-M-s-<down>" | |
| 1171 | command = "org.item.down" | |
| 1172 | when = "item" | |
| 1173 | [[bind]] | |
| 1174 | keys = "C-s-c" | |
| 1175 | command = "org.checkbox.toggle" | |
| 1176 | [[bind]] | |
| 1177 | keys = "C-s-w" | |
| 1178 | command = "app.refile" | |
| 1179 | [[bind]] | |
| 1180 | keys = "C-s-a" | |
| 1181 | command = "app.archive" | |
| 1182 | [[bind]] | |
| 1183 | keys = "C-s-." | |
| 1184 | command = "org.timestamp.active" | |
| 1185 | [[bind]] | |
| 1186 | keys = "C-M-s-." | |
| 1187 | command = "org.timestamp.inactive" | |
| 1188 | [[bind]] | |
| 1189 | keys = "C-s-s" | |
| 1190 | command = "org.schedule" | |
| 1191 | [[bind]] | |
| 1192 | keys = "C-s-e" | |
| 1193 | command = "org.deadline" | |
| 1194 | [[bind]] | |
| 1195 | keys = "C-s-p" | |
| 1196 | command = "org.fill-paragraph" | |
| 1197 | [[bind]] | |
| 1198 | keys = "C-s-<up>" | |
| 1199 | command = "org.table.row-up" | |
| 1200 | when = "table" | |
| 1201 | [[bind]] | |
| 1202 | keys = "C-s-<down>" | |
| 1203 | command = "org.table.row-down" | |
| 1204 | when = "table" | |
| 1205 | [[bind]] | |
| 1206 | keys = "C-s-<left>" | |
| 1207 | command = "org.table.column-left" | |
| 1208 | when = "table" | |
| 1209 | [[bind]] | |
| 1210 | keys = "C-s-<right>" | |
| 1211 | command = "org.table.column-right" | |
| 1212 | when = "table" | |
| 1213 | [[bind]] | |
| 1214 | keys = "C-M-s-<right>" | |
| 1215 | command = "org.table.insert-column" | |
| 1216 | when = "table" | |
| 1217 | [[bind]] | |
| 1218 | keys = "C-M-s-<left>" | |
| 1219 | command = "org.table.delete-column" | |
| 1220 | when = "table" | |
| 1221 | [[bind]] | |
| 1222 | keys = "C-M-s-<up>" | |
| 1223 | command = "org.table.kill-row" | |
| 1224 | when = "table" | |
| 1225 | [[bind]] | |
| 1226 | keys = "C-M-s-<down>" | |
| 1227 | command = "org.table.insert-row" | |
| 1228 | when = "table" | |
| 1229 | [[bind]] | |
| 1230 | keys = "C-s--" | |
| 1231 | command = "org.table.insert-hline" | |
| 1232 | when = "table" | |
| 1233 | [[bind]] | |
| 1234 | keys = "C-s-*" | |
| 1235 | command = "org.table.recalc" | |
| 1236 | when = "table" | |
| 1237 | [[bind]] | |
| 1238 | keys = "C-s-\\\\" | |
| 1239 | command = "org.table.create" | |
| 1240 | [[bind]] | |
| 1241 | keys = "C-s-<up>" | |
| 1242 | command = "org.timestamp.up" | |
| 1243 | when = "timestamp" | |
| 1244 | [[bind]] | |
| 1245 | keys = "C-s-<down>" | |
| 1246 | command = "org.timestamp.down" | |
| 1247 | when = "timestamp" | |
| 1248 | [[bind]] | |
| 1249 | keys = "C-s-<right>" | |
| 1250 | command = "org.timestamp.day-later" | |
| 1251 | when = "timestamp" | |
| 1252 | [[bind]] | |
| 1253 | keys = "C-s-<left>" | |
| 1254 | command = "org.timestamp.day-earlier" | |
| 1255 | when = "timestamp" | |
| 1256 | ||
| 1257 | # Act at point, links, clocking, export and the rest of C-c. | |
| 1258 | [[bind]] | |
| 1259 | keys = "C-s-x" | |
| 1260 | command = "org.ctrl-c-ctrl-c" | |
| 1261 | [[bind]] | |
| 1262 | keys = "C-s-x" | |
| 1263 | command = "org.dblock.update" | |
| 1264 | when = "dblock" | |
| 1265 | [[bind]] | |
| 1266 | keys = "C-s-x" | |
| 1267 | command = "org.table.recalc-all" | |
| 1268 | when = "tblfm" | |
| 1269 | [[bind]] | |
| 1270 | keys = "C-s-x" | |
| 1271 | command = "org.babel.execute" | |
| 1272 | when = "src" | |
| 1273 | [[bind]] | |
| 1274 | keys = "s-k" | |
| 1275 | command = "org.link.insert" | |
| 1276 | [[bind]] | |
| 1277 | keys = "C-s-o" | |
| 1278 | command = "org.link.open" | |
| 1279 | [[bind]] | |
| 1280 | keys = "C-s-l" | |
| 1281 | command = "org.link.store" | |
| 1282 | [[bind]] | |
| 1283 | keys = "C-s-i" | |
| 1284 | command = "app.clock.in" | |
| 1285 | [[bind]] | |
| 1286 | keys = "C-S-s-i" | |
| 1287 | command = "app.clock.out" | |
| 1288 | [[bind]] | |
| 1289 | keys = "C-s-j" | |
| 1290 | command = "app.clock.goto" | |
| 1291 | [[bind]] | |
| 1292 | keys = "C-M-s-i" | |
| 1293 | command = "app.clock.in-recent" | |
| 1294 | [[bind]] | |
| 1295 | keys = "C-M-s-j" | |
| 1296 | command = "app.clock.goto-recent" | |
| 1297 | [[bind]] | |
| 1298 | keys = "C-s-k" | |
| 1299 | command = "app.clock.cancel" | |
| 1300 | [[bind]] | |
| 1301 | keys = "s-S-e" | |
| 1302 | command = "app.export-dialog" | |
| 1303 | [[bind]] | |
| 1304 | keys = "C-s-n" | |
| 1305 | command = "org.narrow.toggle" | |
| 1306 | [[bind]] | |
| 1307 | keys = "C-S-s-s" | |
| 1308 | command = "org.sort" | |
| 1309 | [[bind]] | |
| 1310 | keys = "C-S-s-p" | |
| 1311 | command = "org.property.read-and-set" | |
| 1312 | [[bind]] | |
| 1313 | keys = "C-S-s-f" | |
| 1314 | command = "org.footnote.action" | |
| 1315 | [[bind]] | |
| 1316 | keys = "C-s-'" | |
| 1317 | command = "org.edit-special" | |
| 1318 | [[bind]] | |
| 1319 | keys = "C-S-s-<right>" | |
| 1320 | command = "org.todo.next" | |
| 1321 | when = "heading" | |
| 1322 | [[bind]] | |
| 1323 | keys = "C-S-s-<left>" | |
| 1324 | command = "org.todo.previous" | |
| 1325 | when = "heading" | |
| 1326 | [[bind]] | |
| 1327 | keys = "C-S-s-<right>" | |
| 1328 | command = "org.property.next-value" | |
| 1329 | when = "property" | |
| 1330 | [[bind]] | |
| 1331 | keys = "C-S-s-<left>" | |
| 1332 | command = "org.property.previous-value" | |
| 1333 | when = "property" | |
| 1334 | [[bind]] | |
| 1335 | keys = "M-S-s-<down>" | |
| 1336 | command = "org.heading.forward-same-level" | |
| 1337 | [[bind]] | |
| 1338 | keys = "M-S-s-<up>" | |
| 1339 | command = "org.heading.backward-same-level" | |
| 1340 | [[bind]] | |
| 1341 | keys = "C-S-s-e" | |
| 1342 | command = "org.effort.set" | |
| 1343 | [[bind]] | |
| 1344 | keys = "C-s-," | |
| 1345 | command = "org.priority.set" | |
| 1346 | [[bind]] | |
| 1347 | keys = "C-s-v" | |
| 1348 | command = "org.babel.tangle" | |
| 1349 | [[bind]] | |
| 1350 | keys = "C-S-s-v" | |
| 1351 | command = "org.babel.tangle-block" | |
| 1352 | [[bind]] | |
| 1353 | keys = "C-M-s-v" | |
| 1354 | command = "org.babel.tangle-target" | |
| 1355 | ||
| 1356 | """ | |
| 1357 | 81 | } |
Sources/OrgCore/Keymap/Vim.swift +1 −1141
| @@ -81,7 +81,7 @@ public struct Vim: Sendable { | ||
| 81 | 81 | |
| 82 | 82 | public internal(set) var mode: Mode = .normal |
| 83 | 83 | /// Keys of the command being typed. |
| 84 | public private(set) var pending: [KeyChord] = [] | |
| 84 | public internal(set) var pending: [KeyChord] = [] | |
| 85 | 85 | /// Named registers. Evil's are global: an editor with several engines shares them. |
| 86 | 86 | public var registers: [Character: (text: String, linewise: Bool)] = [:] |
| 87 | 87 | /// What the clipboard held when this engine last wrote it, and whether that was whole lines. |
| @@ -210,1144 +210,4 @@ public struct Vim: Sendable { | ||
| 210 | 210 | changeKeys = keys |
| 211 | 211 | } |
| 212 | 212 | |
| 213 | // MARK: - Parsing | |
| 214 | ||
| 215 | enum Parse { | |
| 216 | case incomplete | |
| 217 | case invalid | |
| 218 | case done([Action]) | |
| 219 | } | |
| 220 | ||
| 221 | struct Command { | |
| 222 | var register: Character? | |
| 223 | var count: Int? | |
| 224 | var keys: ArraySlice<KeyChord> | |
| 225 | } | |
| 226 | ||
| 227 | /// `evil-shift-width`, which Doom keeps equal to `tab-width`: 8 in Org. | |
| 228 | static let shiftWidth = 8 | |
| 229 | ||
| 230 | /// What `indent-according-to-mode` gives a line after `line` in Org: under a list item, | |
| 231 | /// its text's column; under a heading, none; otherwise `line`'s own indentation. | |
| 232 | static func indentation(for buffer: Buffer, line: Int) -> String { | |
| 233 | let text = buffer.substring(buffer.lineStart(line)..<buffer.lineEnd(line)) | |
| 234 | let item = try! NSRegularExpression(pattern: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]+") | |
| 235 | let ns = text as NSString | |
| 236 | if text.hasPrefix("*") { return "" } | |
| 237 | if let m = item.firstMatch(in: text, range: NSRange(location: 0, length: ns.length)) { | |
| 238 | return String(repeating: " ", count: m.range.length) | |
| 239 | } | |
| 240 | return String(text.prefix { $0 == " " || $0 == "\t" }) | |
| 241 | } | |
| 242 | ||
| 243 | static func digit(_ key: KeyChord) -> Int? { | |
| 244 | guard key.modifiers.isEmpty, key.key.count == 1, let d = Int(key.key) else { return nil } | |
| 245 | return d | |
| 246 | } | |
| 247 | ||
| 248 | /// Reads `"r` and a count off the front of `keys`. | |
| 249 | static func prefix(_ keys: [KeyChord]) -> (register: Character?, count: Int?, rest: ArraySlice<KeyChord>)? { | |
| 250 | var rest = keys[...] | |
| 251 | var register: Character? | |
| 252 | if rest.first?.key == "\"", rest.first?.modifiers.isEmpty == true { | |
| 253 | guard rest.count >= 2 else { return nil } | |
| 254 | register = rest[rest.startIndex + 1].key == "SPC" ? " " : rest[rest.startIndex + 1].key.first | |
| 255 | rest = rest.dropFirst(2) | |
| 256 | } | |
| 257 | var count: Int? | |
| 258 | while let key = rest.first, let d = digit(key), !(d == 0 && count == nil) { | |
| 259 | count = (count ?? 0) * 10 + d | |
| 260 | rest = rest.dropFirst() | |
| 261 | } | |
| 262 | return (register, count, rest) | |
| 263 | } | |
| 264 | ||
| 265 | mutating func parse(_ keys: [KeyChord], _ buffer: inout Buffer, _ context: Context) -> Parse { | |
| 266 | guard let (register, count, rest) = Self.prefix(keys) else { return .incomplete } | |
| 267 | guard let first = rest.first else { return .incomplete } | |
| 268 | let visual = mode == .visual || mode == .visualLine | |
| 269 | let n = count ?? 1 | |
| 270 | let caret = context.caret | |
| 271 | ||
| 272 | if mode == .visualBlock { return parseBlock(rest, &buffer, context, register: register, count: n, keys: keys) } | |
| 273 | if let result = parseExtras(rest, &buffer, context, register: register, count: count, keys: keys) { return result } | |
| 274 | ||
| 275 | // Operators. | |
| 276 | let operatorKeys: [String: String] = ["d": "d", "c": "c", "y": "y", ">": ">", "<": "<"] | |
| 277 | var op: String? | |
| 278 | var afterOp = rest.dropFirst() | |
| 279 | if first.modifiers.isEmpty, let o = operatorKeys[first.key] { | |
| 280 | op = o | |
| 281 | } else if first.key == "g", first.modifiers.isEmpty { | |
| 282 | guard let second = rest.dropFirst().first else { return .incomplete } | |
| 283 | if ["~", "u", "U", "c", "q", "w"].contains(second.key), second.modifiers.isEmpty { | |
| 284 | op = "g" + second.key | |
| 285 | afterOp = rest.dropFirst(2) | |
| 286 | } | |
| 287 | } | |
| 288 | if let op { | |
| 289 | if visual { | |
| 290 | let range = visualRange(buffer, caret) | |
| 291 | return .done(apply(op, range: range.range, linewise: range.linewise, buffer, register: register, keys: keys, count: n)) | |
| 292 | } | |
| 293 | // A second count and the motion. | |
| 294 | guard let (_, count2, motionKeys) = Self.prefix(Array(afterOp)), let motionFirst = motionKeys.first else { return .incomplete } | |
| 295 | let total = n * (count2 ?? 1) | |
| 296 | let doubled = op.count == 1 ? op : String(op.last!) | |
| 297 | if motionFirst.key == doubled, motionFirst.modifiers.isEmpty, motionKeys.count == 1 || (op.count == 2 && motionFirst.key == String(op.last!)) { | |
| 298 | // dd, cc, yy, >>, <<, g~~, guu, gUU: whole lines. | |
| 299 | let startLine = buffer.lineStart(caret) | |
| 300 | var end = startLine | |
| 301 | for _ in 0..<total { | |
| 302 | let next = buffer.lineEnd(end) | |
| 303 | end = next < buffer.length ? next + 1 : next | |
| 304 | if end >= buffer.length { break } | |
| 305 | } | |
| 306 | return .done(apply(op, range: startLine..<max(end, buffer.lineEnd(startLine)), linewise: true, buffer, register: register, keys: keys, count: total)) | |
| 307 | } | |
| 308 | if motionFirst.key == "i" || motionFirst.key == "a", motionFirst.modifiers.isEmpty { | |
| 309 | guard motionKeys.count >= 2 else { return .incomplete } | |
| 310 | guard let object = textObject(motionFirst.key == "i", motionKeys[motionKeys.startIndex + 1], buffer, caret, count: total) else { return .invalid } | |
| 311 | // evil-org's subtree objects move point to the heading first. | |
| 312 | if motionKeys[motionKeys.startIndex + 1].key == "R" { caretForApply = buffer.lineStart(object.range.lowerBound) } | |
| 313 | return .done(apply(op, range: object.range, linewise: object.linewise, buffer, register: register, keys: keys, count: total)) | |
| 314 | } | |
| 315 | var motionCaret = caret | |
| 316 | if op == "c", motionFirst.key == "w" || motionFirst.key == "W", motionFirst.modifiers.isEmpty, | |
| 317 | let c = buffer.char(caret), !Buffer.isBlank(c) { | |
| 318 | // cw acts as ce on a word. | |
| 319 | var end = caret | |
| 320 | for _ in 0..<total { end = buffer.wordEnd(end, bigWord: motionFirst.key == "W", fromInside: true) } | |
| 321 | return .done(apply(op, range: caret..<min(buffer.length, end + 1), linewise: false, buffer, register: register, keys: keys, count: total)) | |
| 322 | } | |
| 323 | switch motion(Array(motionKeys), &buffer, &motionCaret, count: total, operatorPending: true) { | |
| 324 | case .incomplete: return .incomplete | |
| 325 | case .invalid: return .invalid | |
| 326 | case .moved(let target, let kind): | |
| 327 | var range: Range<Int> | |
| 328 | var linewise = false | |
| 329 | switch kind { | |
| 330 | case .linewise: | |
| 331 | let a = buffer.lineStart(min(caret, target)) | |
| 332 | let b = buffer.lineEnd(max(caret, target)) | |
| 333 | range = a..<min(buffer.length, b + 1) | |
| 334 | linewise = true | |
| 335 | case .inclusive: | |
| 336 | range = min(caret, target)..<min(buffer.length, max(caret, target) + 1) | |
| 337 | case .exclusive: | |
| 338 | range = min(caret, target)..<max(caret, target) | |
| 339 | // dw at the end of a line stops at the line's end. | |
| 340 | if motionFirst.key == "w" || motionFirst.key == "W", buffer.lineStart(range.upperBound) != buffer.lineStart(range.lowerBound), range.upperBound > range.lowerBound { | |
| 341 | var end = buffer.lineEnd(range.lowerBound) | |
| 342 | if end == range.lowerBound, total == 1 { end = min(buffer.length, end + 1) } | |
| 343 | let upper = buffer.firstNonBlankOrEnd(buffer.lineStart(range.upperBound)) == range.upperBound | |
| 344 | ? max(range.lowerBound, min(end, range.upperBound)) : range.upperBound | |
| 345 | range = range.lowerBound..<(upper == range.lowerBound ? end : upper) | |
| 346 | if buffer.lineStart(range.upperBound) != buffer.lineStart(range.lowerBound) { | |
| 347 | range = range.lowerBound..<buffer.lineEnd(range.lowerBound) | |
| 348 | } | |
| 349 | } | |
| 350 | } | |
| 351 | return .done(apply(op, range: range, linewise: linewise, buffer, register: register, keys: keys, count: total)) | |
| 352 | } | |
| 353 | } | |
| 354 | ||
| 355 | if visual, first.modifiers.isEmpty { | |
| 356 | switch first.key { | |
| 357 | case "ESC": | |
| 358 | lastVisual = (anchor, caret, mode) | |
| 359 | mode = .normal | |
| 360 | return .done([.move(caret: buffer.clampNormal(caret))]) | |
| 361 | case "o": | |
| 362 | let old = anchor | |
| 363 | anchor = caret | |
| 364 | return .done(visualActions(buffer, old)) | |
| 365 | case "x": | |
| 366 | let range = visualRange(buffer, caret) | |
| 367 | return .done(apply("d", range: range.range, linewise: range.linewise, buffer, register: register, keys: keys, count: n)) | |
| 368 | case "~", "u", "U": | |
| 369 | let range = visualRange(buffer, caret) | |
| 370 | return .done(apply(first.key == "~" ? "g~" : "g" + first.key, range: range.range, linewise: range.linewise, buffer, register: register, keys: keys, count: n)) | |
| 371 | case "J": | |
| 372 | let range = visualRange(buffer, caret) | |
| 373 | let lines = max(2, buffer.lineCount(range.range)) | |
| 374 | mode = .normal | |
| 375 | return .done(join(buffer, at: range.range.lowerBound, lines: lines, keys: keys)) | |
| 376 | case "p", "P": | |
| 377 | let range = visualRange(buffer, caret) | |
| 378 | guard let (text, linewise) = paste(register, context) else { return .done([]) } | |
| 379 | mode = .normal | |
| 380 | var replacement = text | |
| 381 | if linewise, !range.linewise { replacement = "\n" + text } | |
| 382 | if !linewise, range.linewise { replacement += "\n" } | |
| 383 | let removed = buffer.substring(range.range) | |
| 384 | var actions: [Action] = [.edit([TextEdit(range: range.range, replacement: replacement)], caret: range.range.lowerBound + (linewise ? 0 : max(0, replacement.utf16.count - 1)))] | |
| 385 | actions += store(removed, linewise: range.linewise, register: nil, yank: false) | |
| 386 | return .done(actions) | |
| 387 | case "v": | |
| 388 | if mode == .visual { | |
| 389 | mode = .normal | |
| 390 | return .done([.move(caret: buffer.clampNormal(caret))]) | |
| 391 | } | |
| 392 | mode = .visual | |
| 393 | return .done(visualActions(buffer, caret)) | |
| 394 | case "V": | |
| 395 | if mode == .visualLine { | |
| 396 | mode = .normal | |
| 397 | return .done([.move(caret: buffer.clampNormal(caret))]) | |
| 398 | } | |
| 399 | mode = .visualLine | |
| 400 | return .done(visualActions(buffer, caret)) | |
| 401 | case "i", "a": | |
| 402 | guard rest.count >= 2 else { return .incomplete } | |
| 403 | guard let object = textObject(first.key == "i", rest[rest.startIndex + 1], buffer, caret, count: n) else { return .invalid } | |
| 404 | if object.linewise { mode = .visualLine } | |
| 405 | anchor = object.range.lowerBound | |
| 406 | let end = max(object.range.lowerBound, object.range.upperBound - 1) | |
| 407 | return .done(visualActions(buffer, end)) | |
| 408 | default: | |
| 409 | break | |
| 410 | } | |
| 411 | } | |
| 412 | ||
| 413 | if !visual { | |
| 414 | switch (first.key, first.modifiers) { | |
| 415 | case ("i", []), ("a", []), ("I", []), ("A", []), ("o", []), ("O", []): | |
| 416 | return .done(enterInsert(first.key, buffer, caret, keys: keys)) | |
| 417 | case ("v", []): | |
| 418 | mode = .visual | |
| 419 | anchor = caret | |
| 420 | return .done(visualActions(buffer, caret)) | |
| 421 | case ("V", []): | |
| 422 | mode = .visualLine | |
| 423 | anchor = caret | |
| 424 | return .done(visualActions(buffer, caret)) | |
| 425 | case ("x", []), ("<delete>", []): | |
| 426 | guard let c = buffer.char(caret), c != 10 else { return .done([]) } | |
| 427 | let end = min(buffer.lineEnd(caret), caret + n) | |
| 428 | return .done(apply("d", range: caret..<end, linewise: false, buffer, register: register, keys: keys, count: n)) | |
| 429 | case ("X", []): | |
| 430 | let start = max(buffer.lineStart(caret), caret - n) | |
| 431 | guard start < caret else { return .done([]) } | |
| 432 | return .done(apply("d", range: start..<caret, linewise: false, buffer, register: register, keys: keys, count: n)) | |
| 433 | case ("D", []), ("C", []): | |
| 434 | var end = buffer.lineEnd(caret) | |
| 435 | for _ in 1..<max(1, n) where end < buffer.length { end = buffer.lineEnd(end + 1) } | |
| 436 | return .done(apply(first.key == "D" ? "d" : "c", range: caret..<end, linewise: false, buffer, register: register, keys: keys, count: n)) | |
| 437 | case ("Y", []): | |
| 438 | // `evil-want-Y-yank-to-eol`. | |
| 439 | return .done(apply("y", range: caret..<buffer.lineEnd(caret), linewise: false, buffer, register: register, keys: keys, count: n)) | |
| 440 | case ("p", []), ("P", []): | |
| 441 | guard let (text, linewise) = paste(register, context) else { return .done([]) } | |
| 442 | let repeated = String(repeating: text, count: n) | |
| 443 | if linewise { | |
| 444 | let body = repeated.hasSuffix("\n") ? repeated : repeated + "\n" | |
| 445 | if first.key == "p" { | |
| 446 | let end = buffer.lineEnd(caret) | |
| 447 | if end >= buffer.length { | |
| 448 | let insertion = "\n" + String(body.dropLast()) | |
| 449 | return .done(change([TextEdit(range: end..<end, replacement: insertion)], caret: buffer.firstNonBlankIn(insertion, at: end + 1), keys: keys)) | |
| 450 | } | |
| 451 | return .done(change([TextEdit(range: (end + 1)..<(end + 1), replacement: body)], caret: buffer.firstNonBlankIn(body, at: end + 1), keys: keys)) | |
| 452 | } | |
| 453 | let start = buffer.lineStart(caret) | |
| 454 | return .done(change([TextEdit(range: start..<start, replacement: body)], caret: buffer.firstNonBlankIn(body, at: start), keys: keys)) | |
| 455 | } | |
| 456 | let at = first.key == "p" && buffer.char(caret).map({ $0 != 10 }) == true ? caret + 1 : caret | |
| 457 | return .done(change([TextEdit(range: at..<at, replacement: repeated)], caret: at + max(0, repeated.utf16.count - 1), keys: keys)) | |
| 458 | case ("J", []): | |
| 459 | return .done(join(buffer, at: caret, lines: max(2, n), keys: keys)) | |
| 460 | case ("~", []): | |
| 461 | let end = min(buffer.lineEnd(caret), caret + n) | |
| 462 | guard end > caret else { return .done([]) } | |
| 463 | let flipped = String(buffer.substring(caret..<end).map { $0.isUppercase ? Character($0.lowercased()) : Character($0.uppercased()) }) | |
| 464 | return .done(change([TextEdit(range: caret..<end, replacement: flipped)], caret: buffer.clampNormal(end, in: buffer.lineStart(caret)), keys: keys)) | |
| 465 | case ("r", []): | |
| 466 | guard rest.count >= 2 else { return .incomplete } | |
| 467 | let target = rest[rest.startIndex + 1] | |
| 468 | let char = target.key == "SPC" ? " " : target.key == "RET" ? "\n" : target.key | |
| 469 | guard char.count == 1, caret + n <= buffer.lineEnd(caret) else { return .done([]) } | |
| 470 | let replacement = char == "\n" ? "\n" : String(repeating: char, count: n) | |
| 471 | return .done(change([TextEdit(range: caret..<(caret + n), replacement: replacement)], caret: char == "\n" ? caret + 1 : caret + n - 1, keys: keys)) | |
| 472 | case ("u", []): | |
| 473 | return .done([.undo(n)]) | |
| 474 | case ("r", [.control]): | |
| 475 | return .done([.redo(n)]) | |
| 476 | case (".", []): | |
| 477 | return .done(repeatChange(n, context)) | |
| 478 | case (":", []): | |
| 479 | return .done([.prompt(":")]) | |
| 480 | case ("/", []), ("?", []): | |
| 481 | return .done([.prompt(first.key)]) | |
| 482 | case ("Z", []): | |
| 483 | guard rest.count >= 2 else { return .incomplete } | |
| 484 | switch rest[rest.startIndex + 1].key { | |
| 485 | case "Z": return .done([.ex("wq")]) | |
| 486 | case "Q": return .done([.ex("q!")]) | |
| 487 | default: return .invalid | |
| 488 | } | |
| 489 | default: | |
| 490 | break | |
| 491 | } | |
| 492 | } | |
| 493 | ||
| 494 | if mode == .normal, !contextOrg, rest.count == 2, first == KeyChord("g"), rest.last == KeyChord("j") || rest.last == KeyChord("k") { | |
| 495 | return .done([.visualLines(rest.last == KeyChord("j") ? n : -n)]) | |
| 496 | } | |
| 497 | ||
| 498 | // Motions move the caret, or extend the selection in visual states. | |
| 499 | var target = caret | |
| 500 | switch motion(Array(rest), &buffer, &target, count: n, operatorPending: false) { | |
| 501 | case .incomplete: return .incomplete | |
| 502 | case .invalid: return .invalid | |
| 503 | case .moved(let to, _): | |
| 504 | if visual { return .done(visualActions(buffer, to)) } | |
| 505 | let jump: [Action] = Self.isJump(Array(rest)) && to != caret ? [.jumped(from: caret)] : [] | |
| 506 | return .done(jump + [.move(caret: buffer.clampNormal(to))]) | |
| 507 | } | |
| 508 | } | |
| 509 | ||
| 510 | // MARK: - Motions | |
| 511 | ||
| 512 | enum MotionKind { case exclusive, inclusive, linewise } | |
| 513 | ||
| 514 | enum MotionResult { | |
| 515 | case incomplete | |
| 516 | case invalid | |
| 517 | case moved(Int, MotionKind) | |
| 518 | } | |
| 519 | ||
| 520 | mutating func motion(_ keys: [KeyChord], _ buffer: inout Buffer, _ caret: inout Int, count n: Int, operatorPending: Bool) -> MotionResult { | |
| 521 | guard let key = keys.first else { return .incomplete } | |
| 522 | let c = caret | |
| 523 | func column(_ position: Int) -> Int { position - buffer.lineStart(position) } | |
| 524 | switch (key.key, key.modifiers) { | |
| 525 | case ("h", []), ("<left>", []), ("DEL", []): | |
| 526 | goalColumn = nil | |
| 527 | return .moved(max(buffer.lineStart(c), c - n), .exclusive) | |
| 528 | case ("l", []), ("<right>", []), ("SPC", []): | |
| 529 | goalColumn = nil | |
| 530 | let end = buffer.lineEnd(c) | |
| 531 | let limit = operatorPending ? end : max(buffer.lineStart(c), end - 1) | |
| 532 | return .moved(min(limit, c + n), .exclusive) | |
| 533 | case ("j", []), ("k", []), ("<down>", []), ("<up>", []), ("d", [.control]), ("u", [.control]), ("+", []), ("-", []), ("RET", []): | |
| 534 | let down = ["j", "<down>", "+", "RET"].contains(key.key) || key == KeyChord("d", .control) | |
| 535 | let lines = key.modifiers.contains(.control) ? (n == 1 ? contextHalfPage : n) : n | |
| 536 | let goal = goalColumn ?? column(c) | |
| 537 | var line = buffer.lineStart(c) | |
| 538 | var moved = 0 | |
| 539 | for _ in 0..<lines { | |
| 540 | if down { | |
| 541 | let end = buffer.lineEnd(line) | |
| 542 | guard end < buffer.length, end + 1 <= buffer.length else { break } | |
| 543 | if end + 1 == buffer.length { break } | |
| 544 | line = end + 1 | |
| 545 | } else { | |
| 546 | guard line > 0 else { break } | |
| 547 | line = buffer.lineStart(line - 1) | |
| 548 | } | |
| 549 | moved += 1 | |
| 550 | } | |
| 551 | if moved == 0, !key.modifiers.contains(.control) { return .invalid } | |
| 552 | if ["+", "-", "RET"].contains(key.key) { return .moved(buffer.firstNonBlank(line), .linewise) } | |
| 553 | goalColumn = goal | |
| 554 | let length = buffer.lineEnd(line) - line | |
| 555 | return .moved(line + min(goal, operatorPending ? length : max(0, length - 1)), .linewise) | |
| 556 | case ("w", []), ("W", []): | |
| 557 | goalColumn = nil | |
| 558 | var p = c | |
| 559 | for _ in 0..<n { p = buffer.wordForward(p, bigWord: key.key == "W") } | |
| 560 | return .moved(p, .exclusive) | |
| 561 | case ("b", []), ("B", []): | |
| 562 | goalColumn = nil | |
| 563 | var p = c | |
| 564 | for _ in 0..<n { p = buffer.wordBackward(p, bigWord: key.key == "B", stopAtLine: false) } | |
| 565 | return .moved(p, .exclusive) | |
| 566 | case ("e", []), ("E", []): | |
| 567 | goalColumn = nil | |
| 568 | var p = c | |
| 569 | for _ in 0..<n { p = buffer.wordEnd(p, bigWord: key.key == "E", fromInside: false) } | |
| 570 | return .moved(p, .inclusive) | |
| 571 | case ("0", []), ("<home>", []): | |
| 572 | goalColumn = nil | |
| 573 | return .moved(buffer.lineStart(c), .exclusive) | |
| 574 | case ("^", []): | |
| 575 | goalColumn = nil | |
| 576 | return .moved(buffer.firstNonBlank(buffer.lineStart(c)), .exclusive) | |
| 577 | case ("$", []), ("<end>", []): | |
| 578 | var line = buffer.lineStart(c) | |
| 579 | for _ in 1..<max(1, n) where buffer.lineEnd(line) < buffer.length { line = buffer.lineEnd(line) + 1 } | |
| 580 | goalColumn = Int.max | |
| 581 | let end = buffer.lineEnd(line) | |
| 582 | if mode == .visual { return .moved(end, .inclusive) } | |
| 583 | return .moved(max(line, end - 1), .inclusive) | |
| 584 | case ("G", []): | |
| 585 | // `evil-start-of-line` nil: the column stays. | |
| 586 | let line = n > 1 || keys.count > 1 ? buffer.lineOffset(n) : buffer.lineStart(buffer.length) | |
| 587 | let column = c - buffer.lineStart(c) | |
| 588 | let length = buffer.lineEnd(line) - line | |
| 589 | return .moved(line + min(column, operatorPending ? length : max(0, length - 1)), .linewise) | |
| 590 | case ("g", []): | |
| 591 | guard keys.count >= 2 else { return .incomplete } | |
| 592 | switch keys[1].key { | |
| 593 | case "g": | |
| 594 | let line = buffer.lineOffset(n) | |
| 595 | let column = c - buffer.lineStart(c) | |
| 596 | let length = buffer.lineEnd(line) - line | |
| 597 | return .moved(line + min(column, operatorPending ? length : max(0, length - 1)), .linewise) | |
| 598 | case "e", "E": | |
| 599 | var p = c | |
| 600 | for _ in 0..<n { p = buffer.wordEndBackward(p, bigWord: keys[1].key == "E") } | |
| 601 | return .moved(p, .inclusive) | |
| 602 | case "j" where contextOrg, "k" where contextOrg: | |
| 603 | // evil-org: org-forward-element and org-backward-element, which take no count. | |
| 604 | guard let p = Self.orgObject(keys[1].key, inner: false, buffer, c)?.range.lowerBound, p != c else { return .invalid } | |
| 605 | goalColumn = nil | |
| 606 | return .moved(p, .exclusive) | |
| 607 | case "j": | |
| 608 | return motion([KeyChord("j")], &buffer, &caret, count: n, operatorPending: operatorPending) | |
| 609 | case "k": | |
| 610 | return motion([KeyChord("k")], &buffer, &caret, count: n, operatorPending: operatorPending) | |
| 611 | case "_": | |
| 612 | let end = buffer.lineEnd(c) | |
| 613 | var p = end | |
| 614 | while p > buffer.lineStart(c), let ch = buffer.char(p - 1), Buffer.isBlank(ch) { p -= 1 } | |
| 615 | return .moved(max(buffer.lineStart(c), p - 1), .inclusive) | |
| 616 | default: | |
| 617 | return .invalid | |
| 618 | } | |
| 619 | case ("f", []), ("F", []), ("t", []), ("T", []): | |
| 620 | // evil-snipe-override-mode: one-character snipes. | |
| 621 | guard keys.count >= 2 else { return .incomplete } | |
| 622 | let char = keys[1].key == "SPC" ? " " : keys[1].key == "TAB" ? "\t" : keys[1].key | |
| 623 | guard char.count == 1 else { return .invalid } | |
| 624 | let forward = key.key == "f" || key.key == "t" | |
| 625 | lastSnipe = (forward, char, n, key.key == "f" || key.key == "F", (KeyChord(key.key.lowercased()), KeyChord(key.key.uppercased()))) | |
| 626 | return snipe(forward: forward, count: n, buffer, c, operatorPending: operatorPending, repeating: false) | |
| 627 | case (";", []), (",", []): | |
| 628 | // evil-snipe-repeat, with Doom's `evil-snipe-repeat-scope` visible. | |
| 629 | guard let last = lastSnipe else { return .invalid } | |
| 630 | let forward = key.key == ";" ? last.forward : !last.forward | |
| 631 | return snipe(forward: forward, count: n * last.count, buffer, c, operatorPending: operatorPending, repeating: true) | |
| 632 | case ("s", []) where !operatorPending, ("S", []) where !operatorPending: | |
| 633 | guard keys.count >= 3 else { return .incomplete } | |
| 634 | let chars = keys[1...2].map { $0.key == "SPC" ? " " : $0.key == "TAB" ? "\t" : $0.key }.joined() | |
| 635 | lastSnipe = (key.key == "s", chars, n, true, (KeyChord("s"), KeyChord("S"))) | |
| 636 | return snipe(forward: key.key == "s", count: n, buffer, c, operatorPending: operatorPending, repeating: false) | |
| 637 | case ("%", []): | |
| 638 | guard let p = buffer.matchingBracket(c) else { return .invalid } | |
| 639 | return .moved(p, .inclusive) | |
| 640 | case ("'", []), ("`", []): | |
| 641 | guard keys.count >= 2 else { return .incomplete } | |
| 642 | let name = keys[1].key == "'" || keys[1].key == "`" ? Character("'") : keys[1].key.first | |
| 643 | guard let name, let mark = currentMarks[name] else { return .invalid } | |
| 644 | goalColumn = nil | |
| 645 | let p = min(mark, buffer.length) | |
| 646 | return key.key == "'" ? .moved(buffer.firstNonBlank(buffer.lineStart(p)), .linewise) : .moved(p, .exclusive) | |
| 647 | case ("}", []), ("{", []): | |
| 648 | var p = c | |
| 649 | for _ in 0..<n { p = buffer.paragraph(p, forward: key.key == "}") } | |
| 650 | return .moved(p, .exclusive) | |
| 651 | case ("n", []), ("N", []): | |
| 652 | guard let search = lastSearch else { return .invalid } | |
| 653 | let forward = key.key == "n" ? search.forward : !search.forward | |
| 654 | guard let p = buffer.search(search.pattern, from: c, forward: forward, count: n) else { return .invalid } | |
| 655 | return .moved(p, .exclusive) | |
| 656 | case ("*", []), ("#", []): | |
| 657 | guard let word = buffer.wordAt(c) else { return .invalid } | |
| 658 | let pattern = "\\b" + NSRegularExpression.escapedPattern(for: word) + "\\b" | |
| 659 | lastSearch = (pattern, key.key == "*") | |
| 660 | guard let p = buffer.search(pattern, from: buffer.wordStart(c), forward: key.key == "*", count: n) else { return .invalid } | |
| 661 | return .moved(p, .exclusive) | |
| 662 | case ("H", []), ("M", []), ("L", []): | |
| 663 | // The visible lines: H the count-th from the top, L from the bottom, M the middle. | |
| 664 | guard let visible = contextVisible else { return .invalid } | |
| 665 | goalColumn = nil | |
| 666 | let lower = min(visible.lowerBound, buffer.length) | |
| 667 | let last = buffer.lineStart(max(lower, min(visible.upperBound, buffer.length) - 1)) | |
| 668 | var lines: [Int] = [] | |
| 669 | var line = buffer.lineStart(lower) | |
| 670 | while true { | |
| 671 | lines.append(line) | |
| 672 | guard line < last, buffer.lineEnd(line) < buffer.length else { break } | |
| 673 | line = buffer.lineEnd(line) + 1 | |
| 674 | } | |
| 675 | let index = key.key == "H" ? min(n, lines.count) - 1 : key.key == "L" ? max(0, lines.count - n) : (lines.count - 1) / 2 | |
| 676 | return .moved(buffer.firstNonBlank(lines[index]), .linewise) | |
| 677 | default: | |
| 678 | return .invalid | |
| 679 | } | |
| 680 | } | |
| 681 | ||
| 682 | /// `evil-snipe--seek` for the last snipe: the `n`th match from `c` in the line after (or | |
| 683 | /// before) the search start, or for a repeat in the visible text, with smart case, | |
| 684 | /// Doom's `evil-snipe-char-fold` and `evil-snipe-skip-leading-whitespace`. | |
| 685 | mutating func snipe(forward: Bool, count n: Int, _ buffer: Buffer, _ c: Int, operatorPending: Bool, repeating: Bool) -> MotionResult { | |
| 686 | guard let last = lastSnipe else { return .invalid } | |
| 687 | // f, s and F search from the next or this character, t and T one further. | |
| 688 | let start = forward ? c + (last.consume ? 1 : 2) : c - (last.consume ? 0 : 1) | |
| 689 | guard start >= 0, start <= buffer.length else { return .invalid } | |
| 690 | var bound = forward ? buffer.lineEnd(start) : buffer.lineStart(start) | |
| 691 | if repeating, let visible = contextVisible { | |
| 692 | bound = forward ? min(visible.upperBound, buffer.length) - 1 : min(visible.lowerBound, start) | |
| 693 | } | |
| 694 | let blankKeys = last.chars.first == " " || last.chars.first == "\t" | |
| 695 | let regexps = last.chars.map(CharFold.regexp) | |
| 696 | var pattern = regexps.map(CharFold.icu).joined() | |
| 697 | if blankKeys, let ch = buffer.char(start), Buffer.isBlank(ch) { pattern += "[^ \t]" } | |
| 698 | // `evil-snipe--case-p`: case matters when the regexps hold a capital letter. | |
| 699 | let caseFold = !regexps.joined().unicodeScalars.contains { ("A"..."Z").contains($0) } | |
| 700 | let regex = try! NSRegularExpression(pattern: pattern, options: caseFold ? .caseInsensitive : []) | |
| 701 | var match: NSRange? | |
| 702 | if forward, start <= bound { | |
| 703 | var from = start | |
| 704 | for _ in 0..<n { | |
| 705 | match = regex.firstMatch(in: buffer.ns as String, range: NSRange(location: from, length: bound - from))?.range | |
| 706 | guard let found = match else { break } | |
| 707 | from = NSMaxRange(found) | |
| 708 | } | |
| 709 | } else if !forward { | |
| 710 | var from = start | |
| 711 | for _ in 0..<n { | |
| 712 | match = nil | |
| 713 | var p = from - 1 | |
| 714 | while p >= bound, match == nil { | |
| 715 | match = regex.firstMatch(in: buffer.ns as String, options: .anchored, range: NSRange(location: p, length: from - p))?.range | |
| 716 | p -= 1 | |
| 717 | } | |
| 718 | guard let found = match else { break } | |
| 719 | from = found.location | |
| 720 | } | |
| 721 | } | |
| 722 | guard let found = match else { | |
| 723 | if repeating { snipeRepeatKeys = last.keys } | |
| 724 | return .invalid | |
| 725 | } | |
| 726 | if !operatorPending { snipeRepeatKeys = last.keys } | |
| 727 | var end = NSMaxRange(found) | |
| 728 | var length = found.length | |
| 729 | if blankKeys { | |
| 730 | end -= 1 | |
| 731 | length -= 1 | |
| 732 | } | |
| 733 | let visual = mode == .visual || mode == .visualLine || mode == .visualBlock | |
| 734 | var p: Int | |
| 735 | if !forward { | |
| 736 | p = last.consume ? found.location : end | |
| 737 | } else { | |
| 738 | p = visual ? (last.consume ? end : found.location) : operatorPending ? end : found.location | |
| 739 | if last.consume { | |
| 740 | if visual { p -= 1 } | |
| 741 | } else { | |
| 742 | p -= length | |
| 743 | if length > 1, !operatorPending { p += 1 } | |
| 744 | } | |
| 745 | } | |
| 746 | return .moved(p, .exclusive) | |
| 747 | } | |
| 748 | ||
| 749 | // MARK: - Text objects | |
| 750 | ||
| 751 | func textObject(_ inner: Bool, _ key: KeyChord, _ buffer: Buffer, _ c: Int, count: Int) -> (range: Range<Int>, linewise: Bool)? { | |
| 752 | switch key.key { | |
| 753 | case "w", "W": | |
| 754 | return buffer.wordObject(c, inner: inner, bigWord: key.key == "W", count: count).map { ($0, false) } | |
| 755 | case "\"", "'", "`": | |
| 756 | return buffer.quoteObject(c, quote: key.key.utf16.first!, inner: inner).map { ($0, false) } | |
| 757 | case "(", ")", "b": | |
| 758 | return buffer.bracketObject(c, open: 40, close: 41, inner: inner).map { ($0, false) } | |
| 759 | case "[", "]": | |
| 760 | return buffer.bracketObject(c, open: 91, close: 93, inner: inner).map { ($0, false) } | |
| 761 | case "{", "}", "B": | |
| 762 | return buffer.bracketObject(c, open: 123, close: 125, inner: inner).map { ($0, false) } | |
| 763 | case "<", ">": | |
| 764 | return buffer.bracketObject(c, open: 60, close: 62, inner: inner).map { ($0, false) } | |
| 765 | case "p": | |
| 766 | return buffer.paragraphObject(c, inner: inner).map { ($0, true) } | |
| 767 | case "e", "E", "r", "R": | |
| 768 | return Self.orgObject(key.key, inner: inner, buffer, c) | |
| 769 | default: | |
| 770 | return nil | |
| 771 | } | |
| 772 | } | |
| 773 | ||
| 774 | // MARK: - Applying | |
| 775 | ||
| 776 | func visualRange(_ buffer: Buffer, _ caret: Int) -> (range: Range<Int>, linewise: Bool) { | |
| 777 | let a = min(anchor, caret) | |
| 778 | let b = max(anchor, caret) | |
| 779 | if mode == .visualLine { | |
| 780 | let end = buffer.lineEnd(b) | |
| 781 | return (buffer.lineStart(a)..<min(buffer.length, end + 1), true) | |
| 782 | } | |
| 783 | return (a..<min(buffer.length, b + 1), false) | |
| 784 | } | |
| 785 | ||
| 786 | func visualActions(_ buffer: Buffer, _ caret: Int) -> [Action] { | |
| 787 | let a = min(anchor, caret) | |
| 788 | let b = max(anchor, caret) | |
| 789 | let range = mode == .visualLine ? buffer.lineStart(a)..<buffer.lineEnd(b) : a..<min(buffer.length, b + 1) | |
| 790 | return [.move(caret: caret), .select(range)] | |
| 791 | } | |
| 792 | ||
| 793 | mutating func store(_ text: String, linewise: Bool, register: Character?, yank: Bool) -> [Action] { | |
| 794 | if register == "_" { return [] } | |
| 795 | if let register, register.isLetter { | |
| 796 | let key = Character(register.lowercased()) | |
| 797 | if register.isUppercase, let existing = registers[key] { | |
| 798 | registers[key] = (existing.text + text, existing.linewise || linewise) | |
| 799 | } else { | |
| 800 | registers[key] = (text, linewise) | |
| 801 | } | |
| 802 | return [] | |
| 803 | } | |
| 804 | if yank { registers["0"] = (text, linewise) } | |
| 805 | clipboardRecord = (text, linewise) | |
| 806 | return [.setClipboard(text)] | |
| 807 | } | |
| 808 | ||
| 809 | func paste(_ register: Character?, _ context: Context) -> (String, Bool)? { | |
| 810 | if let register, register != "\"", register != "+", register != "*" { | |
| 811 | return registers[Character(register.lowercased())] | |
| 812 | } | |
| 813 | guard let clip = context.clipboard ?? clipboardRecord?.text else { return nil } | |
| 814 | if let record = clipboardRecord, record.text == clip { return (clip, record.linewise) } | |
| 815 | return (clip, false) | |
| 816 | } | |
| 817 | ||
| 818 | mutating func change(_ edits: [TextEdit], caret: Int, keys: [KeyChord]) -> [Action] { | |
| 819 | lastChange = (keys, nil) | |
| 820 | return [.edit(edits, caret: caret)] | |
| 821 | } | |
| 822 | ||
| 823 | mutating func apply(_ op: String, range: Range<Int>, linewise: Bool, _ buffer: Buffer, register: Character?, keys: [KeyChord], count: Int) -> [Action] { | |
| 824 | let wasVisual = mode == .visual || mode == .visualLine | |
| 825 | if wasVisual { lastVisual = (anchor, caretForApply, mode) } | |
| 826 | let context0Column = max(0, caretForApply - buffer.lineStart(caretForApply)) | |
| 827 | mode = .normal | |
| 828 | let text = buffer.substring(range) | |
| 829 | switch op { | |
| 830 | case "y": | |
| 831 | var actions = store(text, linewise: linewise, register: register, yank: true) | |
| 832 | let caret = linewise && !wasVisual ? min(range.lowerBound, buffer.length) : range.lowerBound | |
| 833 | actions.append(.move(caret: linewise && wasVisual ? buffer.lineStart(range.lowerBound) : caret)) | |
| 834 | return actions | |
| 835 | case "d": | |
| 836 | var actions = store(text, linewise: linewise, register: register, yank: false) | |
| 837 | var deletion = range | |
| 838 | if linewise, range.upperBound >= buffer.length, range.lowerBound > 0, buffer.char(range.upperBound - 1) != 10 || range.upperBound == buffer.length { | |
| 839 | // The last line takes the newline before it. | |
| 840 | if buffer.char(range.lowerBound - 1) == 10, range.upperBound == buffer.length, !(text.hasSuffix("\n")) { | |
| 841 | deletion = (range.lowerBound - 1)..<range.upperBound | |
| 842 | } | |
| 843 | } | |
| 844 | let after = buffer.removing(deletion) | |
| 845 | var caret = deletion.lowerBound | |
| 846 | if linewise { | |
| 847 | let column = context0Column | |
| 848 | let line = after.lineStart(min(deletion.lowerBound, after.length)) | |
| 849 | let length = after.lineEnd(line) - line | |
| 850 | caret = line + min(column, max(0, length - 1)) | |
| 851 | } else { | |
| 852 | caret = after.clampNormal(caret) | |
| 853 | } | |
| 854 | lastChange = (wasVisual ? [] : keys, nil) | |
| 855 | actions.insert(.edit([TextEdit(range: deletion, replacement: "")], caret: caret), at: 0) | |
| 856 | return actions | |
| 857 | case "c": | |
| 858 | var actions = store(text, linewise: linewise, register: register, yank: false) | |
| 859 | var deletion = range | |
| 860 | var replacement = "" | |
| 861 | if linewise { | |
| 862 | // cc keeps the newline and indents as the line before it calls for. | |
| 863 | replacement = range.lowerBound == 0 ? "" : Self.indentation(for: buffer, line: range.lowerBound - 1) | |
| 864 | if buffer.char(range.upperBound - 1) == 10 { deletion = range.lowerBound..<(range.upperBound - 1) } | |
| 865 | } | |
| 866 | let caret = deletion.lowerBound + replacement.utf16.count | |
| 867 | actions.insert(.edit([TextEdit(range: deletion, replacement: replacement)], caret: caret), at: 0) | |
| 868 | enterInsert(at: caret, keys: wasVisual ? [] : keys) | |
| 869 | return actions | |
| 870 | case ">", "<": | |
| 871 | let start = buffer.lineStart(range.lowerBound) | |
| 872 | var edits: [TextEdit] = [] | |
| 873 | var line = start | |
| 874 | let end = linewise ? range.upperBound : max(range.upperBound, buffer.lineEnd(max(range.lowerBound, range.upperBound - 1))) | |
| 875 | while line < end || (line == start && line <= buffer.length) { | |
| 876 | let lineEnd = buffer.lineEnd(line) | |
| 877 | if lineEnd > line { | |
| 878 | if op == ">" { | |
| 879 | edits.append(TextEdit(range: line..<line, replacement: String(repeating: " ", count: Self.shiftWidth))) | |
| 880 | } else { | |
| 881 | let indent = buffer.substring(line..<buffer.firstNonBlankOrEnd(line)) | |
| 882 | let remove = min(Self.shiftWidth, indent.count) | |
| 883 | if remove > 0 { edits.append(TextEdit(range: line..<(line + remove), replacement: "")) } | |
| 884 | } | |
| 885 | } | |
| 886 | guard lineEnd < buffer.length else { break } | |
| 887 | line = lineEnd + 1 | |
| 888 | if line >= end { break } | |
| 889 | } | |
| 890 | lastChange = (wasVisual ? [] : keys, nil) | |
| 891 | return [.edit(edits, caret: start)] | |
| 892 | case "gc": | |
| 893 | lastChange = (wasVisual ? [] : keys, nil) | |
| 894 | return [.edit(Self.toggleComments(buffer, range), caret: buffer.lineStart(range.lowerBound))] | |
| 895 | case "gq", "gw": | |
| 896 | // Whole lines, as evil's fill operators take them. | |
| 897 | lastChange = (wasVisual ? [] : keys, nil) | |
| 898 | let end = buffer.lineEnd(max(range.lowerBound, range.upperBound - 1)) | |
| 899 | let lines = buffer.lineStart(range.lowerBound)..<min(buffer.length, end + 1) | |
| 900 | return [.fill(lines, keep: op == "gw" ? caretForApply : nil)] | |
| 901 | default: | |
| 902 | let transformed: String | |
| 903 | switch op { | |
| 904 | case "gu": transformed = text.lowercased() | |
| 905 | case "gU": transformed = text.uppercased() | |
| 906 | default: transformed = String(text.map { $0.isUppercase ? Character($0.lowercased()) : Character($0.uppercased()) }) | |
| 907 | } | |
| 908 | lastChange = (wasVisual ? [] : keys, nil) | |
| 909 | return [.edit([TextEdit(range: range, replacement: transformed)], caret: range.lowerBound)] | |
| 910 | } | |
| 911 | } | |
| 912 | ||
| 913 | mutating func enterInsert(_ key: String, _ buffer: Buffer, _ caret: Int, keys: [KeyChord]) -> [Action] { | |
| 914 | switch key { | |
| 915 | case "i": | |
| 916 | enterInsert(at: caret, keys: keys) | |
| 917 | return [.move(caret: caret)] | |
| 918 | case "a": | |
| 919 | let p = buffer.char(caret).map { $0 != 10 } == true ? caret + 1 : caret | |
| 920 | enterInsert(at: p, keys: keys) | |
| 921 | return [.move(caret: p)] | |
| 922 | case "I": | |
| 923 | let p = buffer.firstNonBlank(buffer.lineStart(caret)) | |
| 924 | enterInsert(at: p, keys: keys) | |
| 925 | return [.move(caret: p)] | |
| 926 | case "A": | |
| 927 | let p = buffer.lineEnd(caret) | |
| 928 | enterInsert(at: p, keys: keys) | |
| 929 | return [.move(caret: p)] | |
| 930 | case "o": | |
| 931 | let end = buffer.lineEnd(caret) | |
| 932 | let indent = Self.indentation(for: buffer, line: caret) | |
| 933 | enterInsert(at: end + 1 + indent.utf16.count, keys: keys) | |
| 934 | return [.edit([TextEdit(range: end..<end, replacement: "\n" + indent)], caret: end + 1 + indent.utf16.count)] | |
| 935 | default: | |
| 936 | let start = buffer.lineStart(caret) | |
| 937 | let indent = Self.indentation(for: buffer, line: max(0, start - 1)) == "" || start == 0 ? "" : Self.indentation(for: buffer, line: start - 1) | |
| 938 | enterInsert(at: start + indent.utf16.count, keys: keys) | |
| 939 | return [.edit([TextEdit(range: start..<start, replacement: indent + "\n")], caret: start + indent.utf16.count)] | |
| 940 | } | |
| 941 | } | |
| 942 | ||
| 943 | mutating func join(_ buffer: Buffer, at caret: Int, lines: Int, keys: [KeyChord]) -> [Action] { | |
| 944 | var edits: [TextEdit] = [] | |
| 945 | var line = buffer.lineStart(caret) | |
| 946 | var position = caret | |
| 947 | for _ in 1..<lines { | |
| 948 | let end = buffer.lineEnd(line) | |
| 949 | guard end < buffer.length else { break } | |
| 950 | let nextStart = end + 1 | |
| 951 | let nextText = buffer.firstNonBlankOrEnd(nextStart) | |
| 952 | let joinsEmpty = buffer.lineEnd(nextStart) == nextText | |
| 953 | let separator = joinsEmpty || buffer.char(nextText) == 41 ? "" : (end > line && buffer.char(end - 1) == 32 ? "" : " ") | |
| 954 | var from = end | |
| 955 | while from > line, let c = buffer.char(from - 1), c == 32 || c == 9 { from -= 1 } | |
| 956 | if !separator.isEmpty || from == end { from = end } | |
| 957 | edits.append(TextEdit(range: from..<nextText, replacement: separator)) | |
| 958 | position = from | |
| 959 | line = nextStart | |
| 960 | } | |
| 961 | guard !edits.isEmpty else { return [] } | |
| 962 | lastChange = (keys, nil) | |
| 963 | // Positions in edits refer to the original text; apply back to front. | |
| 964 | let shift = edits.dropLast().reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count } | |
| 965 | return [.edit(edits, caret: position + shift)] | |
| 966 | } | |
| 967 | ||
| 968 | mutating func repeatChange(_ count: Int, _ context: Context) -> [Action] { | |
| 969 | guard let change = lastChange, !change.keys.isEmpty else { return [] } | |
| 970 | var copy = self | |
| 971 | copy.lastChange = nil | |
| 972 | copy.pending = [] | |
| 973 | var keys = change.keys | |
| 974 | if count > 1, let (_, _, rest) = Self.prefix(keys) { | |
| 975 | keys = Array("\(count)".map { KeyChord(String($0)) }) + Array(rest) | |
| 976 | } | |
| 977 | var actions: [Action] = [] | |
| 978 | var text = context.text | |
| 979 | var caret = context.caret | |
| 980 | for key in keys { | |
| 981 | if copy.mode == .insert, key == KeyChord("ESC") { | |
| 982 | if let inserted = change.inserted, !inserted.isEmpty { | |
| 983 | let edit = TextEdit(range: caret..<caret, replacement: inserted) | |
| 984 | actions.append(.edit([edit], caret: caret + inserted.utf16.count)) | |
| 985 | text = edit.apply(to: text) | |
| 986 | caret += inserted.utf16.count | |
| 987 | } | |
| 988 | } | |
| 989 | let produced = copy.feed(key, Context(text: text, caret: caret, clipboard: context.clipboard, halfPage: context.halfPage, visible: context.visible, org: context.org)) | |
| 990 | for action in produced { | |
| 991 | switch action { | |
| 992 | case .edit(let edits, let to): | |
| 993 | var new = text | |
| 994 | for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) } | |
| 995 | text = new | |
| 996 | caret = to | |
| 997 | case .move(let to): | |
| 998 | caret = to | |
| 999 | default: | |
| 1000 | break | |
| 1001 | } | |
| 1002 | actions.append(action) | |
| 1003 | } | |
| 1004 | } | |
| 1005 | let preserved = (registers, clipboardRecord) | |
| 1006 | self = copy | |
| 1007 | registers = preserved.0 | |
| 1008 | clipboardRecord = copy.clipboardRecord ?? preserved.1 | |
| 1009 | lastChange = change | |
| 1010 | return actions | |
| 1011 | } | |
| 1012 | ||
| 1013 | /// `/pattern` or `?pattern` from the prompt: the caret's new place. | |
| 1014 | public mutating func search(_ pattern: String, forward: Bool, _ context: Context) -> [Action] { | |
| 1015 | lastSearch = (pattern, forward) | |
| 1016 | let buffer = Buffer(context) | |
| 1017 | guard let p = buffer.search(pattern, from: context.caret, forward: forward, count: 1) else { return [.message("Search failed: \(pattern)")] } | |
| 1018 | if mode == .visual || mode == .visualLine { return visualActions(buffer, p) } | |
| 1019 | return [.jumped(from: context.caret), .move(caret: p)] | |
| 1020 | } | |
| 1021 | ||
| 1022 | /// Leave a visual state without acting, as `ESC` does. | |
| 1023 | public mutating func reset() { | |
| 1024 | pending = [] | |
| 1025 | if mode == .visual || mode == .visualLine || mode == .visualBlock { mode = .normal } | |
| 1026 | } | |
| 1027 | ||
| 1028 | // MARK: - Text | |
| 1029 | ||
| 1030 | struct Buffer { | |
| 1031 | let ns: NSString | |
| 1032 | var length: Int { ns.length } | |
| 1033 | ||
| 1034 | init(_ context: Context) { ns = context.text as NSString } | |
| 1035 | init(_ text: String) { ns = text as NSString } | |
| 1036 | ||
| 1037 | func char(_ i: Int) -> unichar? { i >= 0 && i < ns.length ? ns.character(at: i) : nil } | |
| 1038 | func substring(_ r: Range<Int>) -> String { ns.substring(with: NSRange(location: r.lowerBound, length: r.count)) } | |
| 1039 | func lineStart(_ i: Int) -> Int { ns.lineRange(for: NSRange(location: min(i, ns.length), length: 0)).location } | |
| 1040 | func lineEnd(_ i: Int) -> Int { | |
| 1041 | var end = 0 | |
| 1042 | ns.getLineStart(nil, end: nil, contentsEnd: &end, for: NSRange(location: min(i, ns.length), length: 0)) | |
| 1043 | return end | |
| 1044 | } | |
| 1045 | func removing(_ r: Range<Int>) -> Buffer { Buffer(ns.replacingCharacters(in: NSRange(location: r.lowerBound, length: r.count), with: "")) } | |
| 1046 | func applying(_ edits: [TextEdit]) -> Buffer { | |
| 1047 | var text = ns as String | |
| 1048 | for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { text = edit.apply(to: text) } | |
| 1049 | return Buffer(text) | |
| 1050 | } | |
| 1051 | ||
| 1052 | static func isBlank(_ c: unichar) -> Bool { c == 32 || c == 9 } | |
| 1053 | static func isSpace(_ c: unichar) -> Bool { c == 32 || c == 9 || c == 10 || c == 13 } | |
| 1054 | static func isWord(_ c: unichar) -> Bool { | |
| 1055 | guard let scalar = Unicode.Scalar(c) else { return true } | |
| 1056 | return CharacterSet.alphanumerics.contains(scalar) || c == 95 | |
| 1057 | } | |
| 1058 | ||
| 1059 | /// 0 blank, 1 word, 2 other. | |
| 1060 | func kind(_ i: Int, bigWord: Bool) -> Int { | |
| 1061 | guard let c = char(i) else { return 0 } | |
| 1062 | if Self.isSpace(c) { return 0 } | |
| 1063 | if bigWord { return 1 } | |
| 1064 | return Self.isWord(c) ? 1 : 2 | |
| 1065 | } | |
| 1066 | ||
| 1067 | func clampNormal(_ i: Int) -> Int { clampNormal(i, in: lineStart(i)) } | |
| 1068 | func clampNormal(_ i: Int, in line: Int) -> Int { | |
| 1069 | let end = lineEnd(line) | |
| 1070 | return max(line, min(i, end > line ? end - 1 : line)) | |
| 1071 | } | |
| 1072 | ||
| 1073 | func firstNonBlank(_ line: Int) -> Int { | |
| 1074 | var p = line | |
| 1075 | let end = lineEnd(line) | |
| 1076 | while p < end, let c = char(p), Self.isBlank(c) { p += 1 } | |
| 1077 | return p == end && end > line ? end - 1 : (p == end ? line : p) | |
| 1078 | } | |
| 1079 | ||
| 1080 | func firstNonBlankOrEnd(_ line: Int) -> Int { | |
| 1081 | var p = line | |
| 1082 | let end = lineEnd(line) | |
| 1083 | while p < end, let c = char(p), Self.isBlank(c) { p += 1 } | |
| 1084 | return p | |
| 1085 | } | |
| 1086 | ||
| 1087 | func firstNonBlankIn(_ inserted: String, at start: Int) -> Int { | |
| 1088 | start + inserted.prefix { $0 == " " || $0 == "\t" }.utf16.count | |
| 1089 | } | |
| 1090 | ||
| 1091 | func lineOffset(_ number: Int) -> Int { | |
| 1092 | var line = 0 | |
| 1093 | for _ in 1..<max(1, number) { | |
| 1094 | let end = lineEnd(line) | |
| 1095 | guard end < length, end + 1 < length else { break } | |
| 1096 | line = end + 1 | |
| 1097 | } | |
| 1098 | return line | |
| 1099 | } | |
| 1100 | ||
| 1101 | /// The number, from 1, of the line holding `i`. | |
| 1102 | func lineNumber(_ i: Int) -> Int { | |
| 1103 | var count = 1 | |
| 1104 | var p = 0 | |
| 1105 | while p < min(i, length) { | |
| 1106 | if char(p) == 10 { count += 1 } | |
| 1107 | p += 1 | |
| 1108 | } | |
| 1109 | return count | |
| 1110 | } | |
| 1111 | ||
| 1112 | func lineCount(_ r: Range<Int>) -> Int { | |
| 1113 | substring(r).filter { $0 == "\n" }.count + (r.upperBound > 0 && char(r.upperBound - 1) == 10 ? 0 : 1) | |
| 1114 | } | |
| 1115 | ||
| 1116 | func wordForward(_ c: Int, bigWord: Bool) -> Int { | |
| 1117 | var p = c | |
| 1118 | let k = kind(p, bigWord: bigWord) | |
| 1119 | if k != 0 { while p < length, kind(p, bigWord: bigWord) == k { p += 1 } } | |
| 1120 | // Skip blanks; an empty line is a word. | |
| 1121 | while p < length, kind(p, bigWord: bigWord) == 0 { | |
| 1122 | if char(p) == 10, p > c, char(p - 1) == 10 { return p } | |
| 1123 | if char(p) == 10, p + 1 < length, char(p + 1) == 10, p + 1 > c { return p + 1 } | |
| 1124 | p += 1 | |
| 1125 | } | |
| 1126 | return min(p, length) | |
| 1127 | } | |
| 1128 | ||
| 1129 | func wordBackward(_ c: Int, bigWord: Bool, stopAtLine: Bool) -> Int { | |
| 1130 | var p = c | |
| 1131 | guard p > 0 else { return 0 } | |
| 1132 | p -= 1 | |
| 1133 | while p > 0, kind(p, bigWord: bigWord) == 0 { | |
| 1134 | if char(p) == 10, char(p - 1) == 10, !stopAtLine { return p } | |
| 1135 | if stopAtLine, char(p) == 10 { return p + 1 } | |
| 1136 | p -= 1 | |
| 1137 | } | |
| 1138 | let k = kind(p, bigWord: bigWord) | |
| 1139 | while p > 0, kind(p - 1, bigWord: bigWord) == k, k != 0 { p -= 1 } | |
| 1140 | return p | |
| 1141 | } | |
| 1142 | ||
| 1143 | func wordEnd(_ c: Int, bigWord: Bool, fromInside: Bool) -> Int { | |
| 1144 | var p = fromInside ? c : c + 1 | |
| 1145 | while p < length, kind(p, bigWord: bigWord) == 0 { p += 1 } | |
| 1146 | let k = kind(p, bigWord: bigWord) | |
| 1147 | while p + 1 < length, kind(p + 1, bigWord: bigWord) == k, k != 0 { p += 1 } | |
| 1148 | return min(p, max(0, length - 1)) | |
| 1149 | } | |
| 1150 | ||
| 1151 | func wordEndBackward(_ c: Int, bigWord: Bool) -> Int { | |
| 1152 | var p = c | |
| 1153 | let k = kind(p, bigWord: bigWord) | |
| 1154 | while p > 0, kind(p, bigWord: bigWord) == k, k != 0 { p -= 1 } | |
| 1155 | while p > 0, kind(p, bigWord: bigWord) == 0 { p -= 1 } | |
| 1156 | return p | |
| 1157 | } | |
| 1158 | ||
| 1159 | func wordStart(_ c: Int) -> Int { | |
| 1160 | var p = c | |
| 1161 | while p > 0, let ch = char(p - 1), Self.isWord(ch) { p -= 1 } | |
| 1162 | return p | |
| 1163 | } | |
| 1164 | ||
| 1165 | func wordAt(_ c: Int) -> String? { | |
| 1166 | var p = c | |
| 1167 | while p < lineEnd(c), let ch = char(p), !Self.isWord(ch) { p += 1 } | |
| 1168 | guard let ch = char(p), Self.isWord(ch) else { return nil } | |
| 1169 | let start = wordStart(p) | |
| 1170 | var end = p | |
| 1171 | while end < length, let e = char(end), Self.isWord(e) { end += 1 } | |
| 1172 | return substring(start..<end) | |
| 1173 | } | |
| 1174 | ||
| 1175 | func matchingBracket(_ c: Int) -> Int? { | |
| 1176 | let pairs: [unichar: (unichar, Bool)] = [40: (41, true), 91: (93, true), 123: (125, true), 41: (40, false), 93: (91, false), 125: (123, false)] | |
| 1177 | var p = c | |
| 1178 | let end = lineEnd(c) | |
| 1179 | while p < end, let ch = char(p), pairs[ch] == nil { p += 1 } | |
| 1180 | guard let open = char(p), let (close, forward) = pairs[open] else { return nil } | |
| 1181 | var depth = 0 | |
| 1182 | var q = p | |
| 1183 | while q >= 0, q < length { | |
| 1184 | if char(q) == open { depth += 1 } | |
| 1185 | if char(q) == close { | |
| 1186 | depth -= 1 | |
| 1187 | if depth == 0 { return q } | |
| 1188 | } | |
| 1189 | q += forward ? 1 : -1 | |
| 1190 | } | |
| 1191 | return nil | |
| 1192 | } | |
| 1193 | ||
| 1194 | func paragraph(_ c: Int, forward: Bool) -> Int { | |
| 1195 | func blank(_ line: Int) -> Bool { substring(line..<lineEnd(line)).allSatisfy { $0 == " " || $0 == "\t" } } | |
| 1196 | var line = lineStart(c) | |
| 1197 | if forward { | |
| 1198 | while lineEnd(line) < length, blank(line) { line = lineEnd(line) + 1 } | |
| 1199 | while lineEnd(line) < length { | |
| 1200 | line = lineEnd(line) + 1 | |
| 1201 | if blank(line) { return line } | |
| 1202 | } | |
| 1203 | return max(0, length - (length > 0 && char(length - 1) == 10 ? 1 : 0)) | |
| 1204 | } | |
| 1205 | while line > 0, blank(line) { line = lineStart(line - 1) } | |
| 1206 | while line > 0 { | |
| 1207 | line = lineStart(line - 1) | |
| 1208 | if blank(line) { return line } | |
| 1209 | } | |
| 1210 | return 0 | |
| 1211 | } | |
| 1212 | ||
| 1213 | func search(_ pattern: String, from c: Int, forward: Bool, count: Int) -> Int? { | |
| 1214 | guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil } | |
| 1215 | let all = regex.matches(in: ns as String, range: NSRange(location: 0, length: length)).map(\.range.location) | |
| 1216 | guard !all.isEmpty else { return nil } | |
| 1217 | var p = c | |
| 1218 | for _ in 0..<count { | |
| 1219 | if forward { | |
| 1220 | p = all.first { $0 > p } ?? all[0] | |
| 1221 | } else { | |
| 1222 | p = all.last { $0 < p } ?? all[all.count - 1] | |
| 1223 | } | |
| 1224 | } | |
| 1225 | return p | |
| 1226 | } | |
| 1227 | ||
| 1228 | func wordObject(_ c: Int, inner: Bool, bigWord: Bool, count: Int) -> Range<Int>? { | |
| 1229 | guard c < length else { return nil } | |
| 1230 | var start = c | |
| 1231 | var end = c | |
| 1232 | let k = kind(c, bigWord: bigWord) | |
| 1233 | let lineS = lineStart(c) | |
| 1234 | let lineE = lineEnd(c) | |
| 1235 | while start > lineS, kind(start - 1, bigWord: bigWord) == k, char(start - 1) != 10 { start -= 1 } | |
| 1236 | while end < lineE, kind(end, bigWord: bigWord) == k { end += 1 } | |
| 1237 | if inner { | |
| 1238 | for _ in 1..<max(1, count) { | |
| 1239 | let k2 = kind(end, bigWord: bigWord) | |
| 1240 | while end < lineE, kind(end, bigWord: bigWord) == k2 { end += 1 } | |
| 1241 | } | |
| 1242 | return start..<end | |
| 1243 | } | |
| 1244 | for _ in 1..<max(1, count) { | |
| 1245 | while end < lineE, let ch = char(end), Self.isBlank(ch) { end += 1 } | |
| 1246 | let k2 = kind(end, bigWord: bigWord) | |
| 1247 | while end < lineE, kind(end, bigWord: bigWord) == k2 { end += 1 } | |
| 1248 | } | |
| 1249 | if k == 0 { | |
| 1250 | let k2 = kind(end, bigWord: bigWord) | |
| 1251 | while end < lineE, kind(end, bigWord: bigWord) == k2 { end += 1 } | |
| 1252 | return start..<end | |
| 1253 | } | |
| 1254 | var trailing = end | |
| 1255 | while trailing < lineE, let ch = char(trailing), Self.isBlank(ch) { trailing += 1 } | |
| 1256 | if trailing > end { return start..<trailing } | |
| 1257 | while start > lineS, let ch = char(start - 1), Self.isBlank(ch) { start -= 1 } | |
| 1258 | return start..<end | |
| 1259 | } | |
| 1260 | ||
| 1261 | func quoteObject(_ c: Int, quote: unichar, inner: Bool) -> Range<Int>? { | |
| 1262 | let s = lineStart(c) | |
| 1263 | let e = lineEnd(c) | |
| 1264 | var positions: [Int] = [] | |
| 1265 | var p = s | |
| 1266 | while p < e { | |
| 1267 | if char(p) == quote, p == s || char(p - 1) != 92 { positions.append(p) } | |
| 1268 | p += 1 | |
| 1269 | } | |
| 1270 | var pair: (Int, Int)? | |
| 1271 | var i = 0 | |
| 1272 | while i + 1 < positions.count { | |
| 1273 | if positions[i] <= c, c <= positions[i + 1] { pair = (positions[i], positions[i + 1]); break } | |
| 1274 | i += 2 | |
| 1275 | } | |
| 1276 | guard let (open, close) = pair else { return nil } | |
| 1277 | if inner { return (open + 1)..<close } | |
| 1278 | var end = close + 1 | |
| 1279 | while end < e, let ch = char(end), Self.isBlank(ch) { end += 1 } | |
| 1280 | var start = open | |
| 1281 | if end == close + 1 { while start > s, let ch = char(start - 1), Self.isBlank(ch) { start -= 1 } } | |
| 1282 | return start..<end | |
| 1283 | } | |
| 1284 | ||
| 1285 | func bracketObject(_ c: Int, open: unichar, close: unichar, inner: Bool) -> Range<Int>? { | |
| 1286 | var depth = 0 | |
| 1287 | var p = c | |
| 1288 | var start: Int? | |
| 1289 | if char(c) == open { | |
| 1290 | start = c | |
| 1291 | } else { | |
| 1292 | if char(c) == close { p = c - 1 } | |
| 1293 | while p >= 0 { | |
| 1294 | if char(p) == close { depth += 1 } | |
| 1295 | if char(p) == open { | |
| 1296 | if depth == 0 { start = p; break } | |
| 1297 | depth -= 1 | |
| 1298 | } | |
| 1299 | p -= 1 | |
| 1300 | } | |
| 1301 | } | |
| 1302 | if start == nil { | |
| 1303 | var f = c | |
| 1304 | while f < lineEnd(c), char(f) != open { f += 1 } | |
| 1305 | if f < lineEnd(c) { start = f } | |
| 1306 | } | |
| 1307 | guard let s = start else { return nil } | |
| 1308 | depth = 0 | |
| 1309 | var q = s | |
| 1310 | var end: Int? | |
| 1311 | while q < length { | |
| 1312 | if char(q) == open { depth += 1 } | |
| 1313 | if char(q) == close { | |
| 1314 | depth -= 1 | |
| 1315 | if depth == 0 { end = q; break } | |
| 1316 | } | |
| 1317 | q += 1 | |
| 1318 | } | |
| 1319 | guard let e = end else { return nil } | |
| 1320 | if !inner { return s..<(e + 1) } | |
| 1321 | var innerStart = s + 1 | |
| 1322 | var innerEnd = e | |
| 1323 | // A block that starts and ends on its own lines keeps them. | |
| 1324 | if char(innerStart) == 10, lineStart(innerEnd) == innerEnd || substring(lineStart(innerEnd)..<innerEnd).allSatisfy({ $0 == " " || $0 == "\t" }) { | |
| 1325 | innerStart += 1 | |
| 1326 | innerEnd = lineStart(innerEnd) | |
| 1327 | } | |
| 1328 | return innerStart..<innerEnd | |
| 1329 | } | |
| 1330 | ||
| 1331 | func paragraphObject(_ c: Int, inner: Bool) -> Range<Int>? { | |
| 1332 | func blank(_ line: Int) -> Bool { substring(line..<lineEnd(line)).allSatisfy { $0 == " " || $0 == "\t" } } | |
| 1333 | var start = lineStart(c) | |
| 1334 | let isBlank = blank(start) | |
| 1335 | while start > 0, blank(lineStart(start - 1)) == isBlank { start = lineStart(start - 1) } | |
| 1336 | var end = lineEnd(c) | |
| 1337 | while end < length, end + 1 <= length, end + 1 < length || !isBlank, blank(end + 1) == isBlank, end + 1 < length { | |
| 1338 | end = lineEnd(end + 1) | |
| 1339 | } | |
| 1340 | var upper = min(length, end + 1) | |
| 1341 | if !inner { | |
| 1342 | var after = upper | |
| 1343 | while after < length, blank(after) { | |
| 1344 | let next = lineEnd(after) | |
| 1345 | after = min(length, next + 1) | |
| 1346 | if next >= length { break } | |
| 1347 | } | |
| 1348 | upper = after | |
| 1349 | } | |
| 1350 | return start..<upper | |
| 1351 | } | |
| 1352 | } | |
| 1353 | 213 | } |
Sources/OrgCore/Keymap/VimApply.swift added +583
| @@ -0,0 +1,583 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Vim { | |
| 4 | // MARK: - Applying | |
| 5 | ||
| 6 | func visualRange(_ buffer: Buffer, _ caret: Int) -> (range: Range<Int>, linewise: Bool) { | |
| 7 | let a = min(anchor, caret) | |
| 8 | let b = max(anchor, caret) | |
| 9 | if mode == .visualLine { | |
| 10 | let end = buffer.lineEnd(b) | |
| 11 | return (buffer.lineStart(a)..<min(buffer.length, end + 1), true) | |
| 12 | } | |
| 13 | return (a..<min(buffer.length, b + 1), false) | |
| 14 | } | |
| 15 | ||
| 16 | func visualActions(_ buffer: Buffer, _ caret: Int) -> [Action] { | |
| 17 | let a = min(anchor, caret) | |
| 18 | let b = max(anchor, caret) | |
| 19 | let range = mode == .visualLine ? buffer.lineStart(a)..<buffer.lineEnd(b) : a..<min(buffer.length, b + 1) | |
| 20 | return [.move(caret: caret), .select(range)] | |
| 21 | } | |
| 22 | ||
| 23 | mutating func store(_ text: String, linewise: Bool, register: Character?, yank: Bool) -> [Action] { | |
| 24 | if register == "_" { return [] } | |
| 25 | if let register, register.isLetter { | |
| 26 | let key = Character(register.lowercased()) | |
| 27 | if register.isUppercase, let existing = registers[key] { | |
| 28 | registers[key] = (existing.text + text, existing.linewise || linewise) | |
| 29 | } else { | |
| 30 | registers[key] = (text, linewise) | |
| 31 | } | |
| 32 | return [] | |
| 33 | } | |
| 34 | if yank { registers["0"] = (text, linewise) } | |
| 35 | clipboardRecord = (text, linewise) | |
| 36 | return [.setClipboard(text)] | |
| 37 | } | |
| 38 | ||
| 39 | func paste(_ register: Character?, _ context: Context) -> (String, Bool)? { | |
| 40 | if let register, register != "\"", register != "+", register != "*" { | |
| 41 | return registers[Character(register.lowercased())] | |
| 42 | } | |
| 43 | guard let clip = context.clipboard ?? clipboardRecord?.text else { return nil } | |
| 44 | if let record = clipboardRecord, record.text == clip { return (clip, record.linewise) } | |
| 45 | return (clip, false) | |
| 46 | } | |
| 47 | ||
| 48 | mutating func change(_ edits: [TextEdit], caret: Int, keys: [KeyChord]) -> [Action] { | |
| 49 | lastChange = (keys, nil) | |
| 50 | return [.edit(edits, caret: caret)] | |
| 51 | } | |
| 52 | ||
| 53 | mutating func apply(_ op: String, range: Range<Int>, linewise: Bool, _ buffer: Buffer, register: Character?, keys: [KeyChord], count: Int) -> [Action] { | |
| 54 | let wasVisual = mode == .visual || mode == .visualLine | |
| 55 | if wasVisual { lastVisual = (anchor, caretForApply, mode) } | |
| 56 | let context0Column = max(0, caretForApply - buffer.lineStart(caretForApply)) | |
| 57 | mode = .normal | |
| 58 | let text = buffer.substring(range) | |
| 59 | switch op { | |
| 60 | case "y": | |
| 61 | var actions = store(text, linewise: linewise, register: register, yank: true) | |
| 62 | let caret = linewise && !wasVisual ? min(range.lowerBound, buffer.length) : range.lowerBound | |
| 63 | actions.append(.move(caret: linewise && wasVisual ? buffer.lineStart(range.lowerBound) : caret)) | |
| 64 | return actions | |
| 65 | case "d": | |
| 66 | var actions = store(text, linewise: linewise, register: register, yank: false) | |
| 67 | var deletion = range | |
| 68 | if linewise, range.upperBound >= buffer.length, range.lowerBound > 0, buffer.char(range.upperBound - 1) != 10 || range.upperBound == buffer.length { | |
| 69 | // The last line takes the newline before it. | |
| 70 | if buffer.char(range.lowerBound - 1) == 10, range.upperBound == buffer.length, !(text.hasSuffix("\n")) { | |
| 71 | deletion = (range.lowerBound - 1)..<range.upperBound | |
| 72 | } | |
| 73 | } | |
| 74 | let after = buffer.removing(deletion) | |
| 75 | var caret = deletion.lowerBound | |
| 76 | if linewise { | |
| 77 | let column = context0Column | |
| 78 | let line = after.lineStart(min(deletion.lowerBound, after.length)) | |
| 79 | let length = after.lineEnd(line) - line | |
| 80 | caret = line + min(column, max(0, length - 1)) | |
| 81 | } else { | |
| 82 | caret = after.clampNormal(caret) | |
| 83 | } | |
| 84 | lastChange = (wasVisual ? [] : keys, nil) | |
| 85 | actions.insert(.edit([TextEdit(range: deletion, replacement: "")], caret: caret), at: 0) | |
| 86 | return actions | |
| 87 | case "c": | |
| 88 | var actions = store(text, linewise: linewise, register: register, yank: false) | |
| 89 | var deletion = range | |
| 90 | var replacement = "" | |
| 91 | if linewise { | |
| 92 | // cc keeps the newline and indents as the line before it calls for. | |
| 93 | replacement = range.lowerBound == 0 ? "" : Self.indentation(for: buffer, line: range.lowerBound - 1) | |
| 94 | if buffer.char(range.upperBound - 1) == 10 { deletion = range.lowerBound..<(range.upperBound - 1) } | |
| 95 | } | |
| 96 | let caret = deletion.lowerBound + replacement.utf16.count | |
| 97 | actions.insert(.edit([TextEdit(range: deletion, replacement: replacement)], caret: caret), at: 0) | |
| 98 | enterInsert(at: caret, keys: wasVisual ? [] : keys) | |
| 99 | return actions | |
| 100 | case ">", "<": | |
| 101 | let start = buffer.lineStart(range.lowerBound) | |
| 102 | var edits: [TextEdit] = [] | |
| 103 | var line = start | |
| 104 | let end = linewise ? range.upperBound : max(range.upperBound, buffer.lineEnd(max(range.lowerBound, range.upperBound - 1))) | |
| 105 | while line < end || (line == start && line <= buffer.length) { | |
| 106 | let lineEnd = buffer.lineEnd(line) | |
| 107 | if lineEnd > line { | |
| 108 | if op == ">" { | |
| 109 | edits.append(TextEdit(range: line..<line, replacement: String(repeating: " ", count: Self.shiftWidth))) | |
| 110 | } else { | |
| 111 | let indent = buffer.substring(line..<buffer.firstNonBlankOrEnd(line)) | |
| 112 | let remove = min(Self.shiftWidth, indent.count) | |
| 113 | if remove > 0 { edits.append(TextEdit(range: line..<(line + remove), replacement: "")) } | |
| 114 | } | |
| 115 | } | |
| 116 | guard lineEnd < buffer.length else { break } | |
| 117 | line = lineEnd + 1 | |
| 118 | if line >= end { break } | |
| 119 | } | |
| 120 | lastChange = (wasVisual ? [] : keys, nil) | |
| 121 | return [.edit(edits, caret: start)] | |
| 122 | case "gc": | |
| 123 | lastChange = (wasVisual ? [] : keys, nil) | |
| 124 | return [.edit(Self.toggleComments(buffer, range), caret: buffer.lineStart(range.lowerBound))] | |
| 125 | case "gq", "gw": | |
| 126 | // Whole lines, as evil's fill operators take them. | |
| 127 | lastChange = (wasVisual ? [] : keys, nil) | |
| 128 | let end = buffer.lineEnd(max(range.lowerBound, range.upperBound - 1)) | |
| 129 | let lines = buffer.lineStart(range.lowerBound)..<min(buffer.length, end + 1) | |
| 130 | return [.fill(lines, keep: op == "gw" ? caretForApply : nil)] | |
| 131 | default: | |
| 132 | let transformed: String | |
| 133 | switch op { | |
| 134 | case "gu": transformed = text.lowercased() | |
| 135 | case "gU": transformed = text.uppercased() | |
| 136 | default: transformed = String(text.map { $0.isUppercase ? Character($0.lowercased()) : Character($0.uppercased()) }) | |
| 137 | } | |
| 138 | lastChange = (wasVisual ? [] : keys, nil) | |
| 139 | return [.edit([TextEdit(range: range, replacement: transformed)], caret: range.lowerBound)] | |
| 140 | } | |
| 141 | } | |
| 142 | ||
| 143 | mutating func enterInsert(_ key: String, _ buffer: Buffer, _ caret: Int, keys: [KeyChord]) -> [Action] { | |
| 144 | switch key { | |
| 145 | case "i": | |
| 146 | enterInsert(at: caret, keys: keys) | |
| 147 | return [.move(caret: caret)] | |
| 148 | case "a": | |
| 149 | let p = buffer.char(caret).map { $0 != 10 } == true ? caret + 1 : caret | |
| 150 | enterInsert(at: p, keys: keys) | |
| 151 | return [.move(caret: p)] | |
| 152 | case "I": | |
| 153 | let p = buffer.firstNonBlank(buffer.lineStart(caret)) | |
| 154 | enterInsert(at: p, keys: keys) | |
| 155 | return [.move(caret: p)] | |
| 156 | case "A": | |
| 157 | let p = buffer.lineEnd(caret) | |
| 158 | enterInsert(at: p, keys: keys) | |
| 159 | return [.move(caret: p)] | |
| 160 | case "o": | |
| 161 | let end = buffer.lineEnd(caret) | |
| 162 | let indent = Self.indentation(for: buffer, line: caret) | |
| 163 | enterInsert(at: end + 1 + indent.utf16.count, keys: keys) | |
| 164 | return [.edit([TextEdit(range: end..<end, replacement: "\n" + indent)], caret: end + 1 + indent.utf16.count)] | |
| 165 | default: | |
| 166 | let start = buffer.lineStart(caret) | |
| 167 | let indent = Self.indentation(for: buffer, line: max(0, start - 1)) == "" || start == 0 ? "" : Self.indentation(for: buffer, line: start - 1) | |
| 168 | enterInsert(at: start + indent.utf16.count, keys: keys) | |
| 169 | return [.edit([TextEdit(range: start..<start, replacement: indent + "\n")], caret: start + indent.utf16.count)] | |
| 170 | } | |
| 171 | } | |
| 172 | ||
| 173 | mutating func join(_ buffer: Buffer, at caret: Int, lines: Int, keys: [KeyChord]) -> [Action] { | |
| 174 | var edits: [TextEdit] = [] | |
| 175 | var line = buffer.lineStart(caret) | |
| 176 | var position = caret | |
| 177 | for _ in 1..<lines { | |
| 178 | let end = buffer.lineEnd(line) | |
| 179 | guard end < buffer.length else { break } | |
| 180 | let nextStart = end + 1 | |
| 181 | let nextText = buffer.firstNonBlankOrEnd(nextStart) | |
| 182 | let joinsEmpty = buffer.lineEnd(nextStart) == nextText | |
| 183 | let separator = joinsEmpty || buffer.char(nextText) == 41 ? "" : (end > line && buffer.char(end - 1) == 32 ? "" : " ") | |
| 184 | var from = end | |
| 185 | while from > line, let c = buffer.char(from - 1), c == 32 || c == 9 { from -= 1 } | |
| 186 | if !separator.isEmpty || from == end { from = end } | |
| 187 | edits.append(TextEdit(range: from..<nextText, replacement: separator)) | |
| 188 | position = from | |
| 189 | line = nextStart | |
| 190 | } | |
| 191 | guard !edits.isEmpty else { return [] } | |
| 192 | lastChange = (keys, nil) | |
| 193 | // Positions in edits refer to the original text; apply back to front. | |
| 194 | let shift = edits.dropLast().reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count } | |
| 195 | return [.edit(edits, caret: position + shift)] | |
| 196 | } | |
| 197 | ||
| 198 | mutating func repeatChange(_ count: Int, _ context: Context) -> [Action] { | |
| 199 | guard let change = lastChange, !change.keys.isEmpty else { return [] } | |
| 200 | var copy = self | |
| 201 | copy.lastChange = nil | |
| 202 | copy.pending = [] | |
| 203 | var keys = change.keys | |
| 204 | if count > 1, let (_, _, rest) = Self.prefix(keys) { | |
| 205 | keys = Array("\(count)".map { KeyChord(String($0)) }) + Array(rest) | |
| 206 | } | |
| 207 | var actions: [Action] = [] | |
| 208 | var text = context.text | |
| 209 | var caret = context.caret | |
| 210 | for key in keys { | |
| 211 | if copy.mode == .insert, key == KeyChord("ESC") { | |
| 212 | if let inserted = change.inserted, !inserted.isEmpty { | |
| 213 | let edit = TextEdit(range: caret..<caret, replacement: inserted) | |
| 214 | actions.append(.edit([edit], caret: caret + inserted.utf16.count)) | |
| 215 | text = edit.apply(to: text) | |
| 216 | caret += inserted.utf16.count | |
| 217 | } | |
| 218 | } | |
| 219 | let produced = copy.feed(key, Context(text: text, caret: caret, clipboard: context.clipboard, halfPage: context.halfPage, visible: context.visible, org: context.org)) | |
| 220 | for action in produced { | |
| 221 | switch action { | |
| 222 | case .edit(let edits, let to): | |
| 223 | var new = text | |
| 224 | for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) } | |
| 225 | text = new | |
| 226 | caret = to | |
| 227 | case .move(let to): | |
| 228 | caret = to | |
| 229 | default: | |
| 230 | break | |
| 231 | } | |
| 232 | actions.append(action) | |
| 233 | } | |
| 234 | } | |
| 235 | let preserved = (registers, clipboardRecord) | |
| 236 | self = copy | |
| 237 | registers = preserved.0 | |
| 238 | clipboardRecord = copy.clipboardRecord ?? preserved.1 | |
| 239 | lastChange = change | |
| 240 | return actions | |
| 241 | } | |
| 242 | ||
| 243 | /// `/pattern` or `?pattern` from the prompt: the caret's new place. | |
| 244 | public mutating func search(_ pattern: String, forward: Bool, _ context: Context) -> [Action] { | |
| 245 | lastSearch = (pattern, forward) | |
| 246 | let buffer = Buffer(context) | |
| 247 | guard let p = buffer.search(pattern, from: context.caret, forward: forward, count: 1) else { return [.message("Search failed: \(pattern)")] } | |
| 248 | if mode == .visual || mode == .visualLine { return visualActions(buffer, p) } | |
| 249 | return [.jumped(from: context.caret), .move(caret: p)] | |
| 250 | } | |
| 251 | ||
| 252 | /// Leave a visual state without acting, as `ESC` does. | |
| 253 | public mutating func reset() { | |
| 254 | pending = [] | |
| 255 | if mode == .visual || mode == .visualLine || mode == .visualBlock { mode = .normal } | |
| 256 | } | |
| 257 | ||
| 258 | // MARK: - Text | |
| 259 | ||
| 260 | struct Buffer { | |
| 261 | let ns: NSString | |
| 262 | var length: Int { ns.length } | |
| 263 | ||
| 264 | init(_ context: Context) { ns = context.text as NSString } | |
| 265 | init(_ text: String) { ns = text as NSString } | |
| 266 | ||
| 267 | func char(_ i: Int) -> unichar? { i >= 0 && i < ns.length ? ns.character(at: i) : nil } | |
| 268 | func substring(_ r: Range<Int>) -> String { ns.substring(with: NSRange(location: r.lowerBound, length: r.count)) } | |
| 269 | func lineStart(_ i: Int) -> Int { ns.lineRange(for: NSRange(location: min(i, ns.length), length: 0)).location } | |
| 270 | func lineEnd(_ i: Int) -> Int { | |
| 271 | var end = 0 | |
| 272 | ns.getLineStart(nil, end: nil, contentsEnd: &end, for: NSRange(location: min(i, ns.length), length: 0)) | |
| 273 | return end | |
| 274 | } | |
| 275 | func removing(_ r: Range<Int>) -> Buffer { Buffer(ns.replacingCharacters(in: NSRange(location: r.lowerBound, length: r.count), with: "")) } | |
| 276 | func applying(_ edits: [TextEdit]) -> Buffer { | |
| 277 | var text = ns as String | |
| 278 | for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { text = edit.apply(to: text) } | |
| 279 | return Buffer(text) | |
| 280 | } | |
| 281 | ||
| 282 | static func isBlank(_ c: unichar) -> Bool { c == 32 || c == 9 } | |
| 283 | static func isSpace(_ c: unichar) -> Bool { c == 32 || c == 9 || c == 10 || c == 13 } | |
| 284 | static func isWord(_ c: unichar) -> Bool { | |
| 285 | guard let scalar = Unicode.Scalar(c) else { return true } | |
| 286 | return CharacterSet.alphanumerics.contains(scalar) || c == 95 | |
| 287 | } | |
| 288 | ||
| 289 | /// 0 blank, 1 word, 2 other. | |
| 290 | func kind(_ i: Int, bigWord: Bool) -> Int { | |
| 291 | guard let c = char(i) else { return 0 } | |
| 292 | if Self.isSpace(c) { return 0 } | |
| 293 | if bigWord { return 1 } | |
| 294 | return Self.isWord(c) ? 1 : 2 | |
| 295 | } | |
| 296 | ||
| 297 | func clampNormal(_ i: Int) -> Int { clampNormal(i, in: lineStart(i)) } | |
| 298 | func clampNormal(_ i: Int, in line: Int) -> Int { | |
| 299 | let end = lineEnd(line) | |
| 300 | return max(line, min(i, end > line ? end - 1 : line)) | |
| 301 | } | |
| 302 | ||
| 303 | func firstNonBlank(_ line: Int) -> Int { | |
| 304 | var p = line | |
| 305 | let end = lineEnd(line) | |
| 306 | while p < end, let c = char(p), Self.isBlank(c) { p += 1 } | |
| 307 | return p == end && end > line ? end - 1 : (p == end ? line : p) | |
| 308 | } | |
| 309 | ||
| 310 | func firstNonBlankOrEnd(_ line: Int) -> Int { | |
| 311 | var p = line | |
| 312 | let end = lineEnd(line) | |
| 313 | while p < end, let c = char(p), Self.isBlank(c) { p += 1 } | |
| 314 | return p | |
| 315 | } | |
| 316 | ||
| 317 | func firstNonBlankIn(_ inserted: String, at start: Int) -> Int { | |
| 318 | start + inserted.prefix { $0 == " " || $0 == "\t" }.utf16.count | |
| 319 | } | |
| 320 | ||
| 321 | func lineOffset(_ number: Int) -> Int { | |
| 322 | var line = 0 | |
| 323 | for _ in 1..<max(1, number) { | |
| 324 | let end = lineEnd(line) | |
| 325 | guard end < length, end + 1 < length else { break } | |
| 326 | line = end + 1 | |
| 327 | } | |
| 328 | return line | |
| 329 | } | |
| 330 | ||
| 331 | /// The number, from 1, of the line holding `i`. | |
| 332 | func lineNumber(_ i: Int) -> Int { | |
| 333 | var count = 1 | |
| 334 | var p = 0 | |
| 335 | while p < min(i, length) { | |
| 336 | if char(p) == 10 { count += 1 } | |
| 337 | p += 1 | |
| 338 | } | |
| 339 | return count | |
| 340 | } | |
| 341 | ||
| 342 | func lineCount(_ r: Range<Int>) -> Int { | |
| 343 | substring(r).filter { $0 == "\n" }.count + (r.upperBound > 0 && char(r.upperBound - 1) == 10 ? 0 : 1) | |
| 344 | } | |
| 345 | ||
| 346 | func wordForward(_ c: Int, bigWord: Bool) -> Int { | |
| 347 | var p = c | |
| 348 | let k = kind(p, bigWord: bigWord) | |
| 349 | if k != 0 { while p < length, kind(p, bigWord: bigWord) == k { p += 1 } } | |
| 350 | // Skip blanks; an empty line is a word. | |
| 351 | while p < length, kind(p, bigWord: bigWord) == 0 { | |
| 352 | if char(p) == 10, p > c, char(p - 1) == 10 { return p } | |
| 353 | if char(p) == 10, p + 1 < length, char(p + 1) == 10, p + 1 > c { return p + 1 } | |
| 354 | p += 1 | |
| 355 | } | |
| 356 | return min(p, length) | |
| 357 | } | |
| 358 | ||
| 359 | func wordBackward(_ c: Int, bigWord: Bool, stopAtLine: Bool) -> Int { | |
| 360 | var p = c | |
| 361 | guard p > 0 else { return 0 } | |
| 362 | p -= 1 | |
| 363 | while p > 0, kind(p, bigWord: bigWord) == 0 { | |
| 364 | if char(p) == 10, char(p - 1) == 10, !stopAtLine { return p } | |
| 365 | if stopAtLine, char(p) == 10 { return p + 1 } | |
| 366 | p -= 1 | |
| 367 | } | |
| 368 | let k = kind(p, bigWord: bigWord) | |
| 369 | while p > 0, kind(p - 1, bigWord: bigWord) == k, k != 0 { p -= 1 } | |
| 370 | return p | |
| 371 | } | |
| 372 | ||
| 373 | func wordEnd(_ c: Int, bigWord: Bool, fromInside: Bool) -> Int { | |
| 374 | var p = fromInside ? c : c + 1 | |
| 375 | while p < length, kind(p, bigWord: bigWord) == 0 { p += 1 } | |
| 376 | let k = kind(p, bigWord: bigWord) | |
| 377 | while p + 1 < length, kind(p + 1, bigWord: bigWord) == k, k != 0 { p += 1 } | |
| 378 | return min(p, max(0, length - 1)) | |
| 379 | } | |
| 380 | ||
| 381 | func wordEndBackward(_ c: Int, bigWord: Bool) -> Int { | |
| 382 | var p = c | |
| 383 | let k = kind(p, bigWord: bigWord) | |
| 384 | while p > 0, kind(p, bigWord: bigWord) == k, k != 0 { p -= 1 } | |
| 385 | while p > 0, kind(p, bigWord: bigWord) == 0 { p -= 1 } | |
| 386 | return p | |
| 387 | } | |
| 388 | ||
| 389 | func wordStart(_ c: Int) -> Int { | |
| 390 | var p = c | |
| 391 | while p > 0, let ch = char(p - 1), Self.isWord(ch) { p -= 1 } | |
| 392 | return p | |
| 393 | } | |
| 394 | ||
| 395 | func wordAt(_ c: Int) -> String? { | |
| 396 | var p = c | |
| 397 | while p < lineEnd(c), let ch = char(p), !Self.isWord(ch) { p += 1 } | |
| 398 | guard let ch = char(p), Self.isWord(ch) else { return nil } | |
| 399 | let start = wordStart(p) | |
| 400 | var end = p | |
| 401 | while end < length, let e = char(end), Self.isWord(e) { end += 1 } | |
| 402 | return substring(start..<end) | |
| 403 | } | |
| 404 | ||
| 405 | func matchingBracket(_ c: Int) -> Int? { | |
| 406 | let pairs: [unichar: (unichar, Bool)] = [40: (41, true), 91: (93, true), 123: (125, true), 41: (40, false), 93: (91, false), 125: (123, false)] | |
| 407 | var p = c | |
| 408 | let end = lineEnd(c) | |
| 409 | while p < end, let ch = char(p), pairs[ch] == nil { p += 1 } | |
| 410 | guard let open = char(p), let (close, forward) = pairs[open] else { return nil } | |
| 411 | var depth = 0 | |
| 412 | var q = p | |
| 413 | while q >= 0, q < length { | |
| 414 | if char(q) == open { depth += 1 } | |
| 415 | if char(q) == close { | |
| 416 | depth -= 1 | |
| 417 | if depth == 0 { return q } | |
| 418 | } | |
| 419 | q += forward ? 1 : -1 | |
| 420 | } | |
| 421 | return nil | |
| 422 | } | |
| 423 | ||
| 424 | func paragraph(_ c: Int, forward: Bool) -> Int { | |
| 425 | func blank(_ line: Int) -> Bool { substring(line..<lineEnd(line)).allSatisfy { $0 == " " || $0 == "\t" } } | |
| 426 | var line = lineStart(c) | |
| 427 | if forward { | |
| 428 | while lineEnd(line) < length, blank(line) { line = lineEnd(line) + 1 } | |
| 429 | while lineEnd(line) < length { | |
| 430 | line = lineEnd(line) + 1 | |
| 431 | if blank(line) { return line } | |
| 432 | } | |
| 433 | return max(0, length - (length > 0 && char(length - 1) == 10 ? 1 : 0)) | |
| 434 | } | |
| 435 | while line > 0, blank(line) { line = lineStart(line - 1) } | |
| 436 | while line > 0 { | |
| 437 | line = lineStart(line - 1) | |
| 438 | if blank(line) { return line } | |
| 439 | } | |
| 440 | return 0 | |
| 441 | } | |
| 442 | ||
| 443 | func search(_ pattern: String, from c: Int, forward: Bool, count: Int) -> Int? { | |
| 444 | guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil } | |
| 445 | let all = regex.matches(in: ns as String, range: NSRange(location: 0, length: length)).map(\.range.location) | |
| 446 | guard !all.isEmpty else { return nil } | |
| 447 | var p = c | |
| 448 | for _ in 0..<count { | |
| 449 | if forward { | |
| 450 | p = all.first { $0 > p } ?? all[0] | |
| 451 | } else { | |
| 452 | p = all.last { $0 < p } ?? all[all.count - 1] | |
| 453 | } | |
| 454 | } | |
| 455 | return p | |
| 456 | } | |
| 457 | ||
| 458 | func wordObject(_ c: Int, inner: Bool, bigWord: Bool, count: Int) -> Range<Int>? { | |
| 459 | guard c < length else { return nil } | |
| 460 | var start = c | |
| 461 | var end = c | |
| 462 | let k = kind(c, bigWord: bigWord) | |
| 463 | let lineS = lineStart(c) | |
| 464 | let lineE = lineEnd(c) | |
| 465 | while start > lineS, kind(start - 1, bigWord: bigWord) == k, char(start - 1) != 10 { start -= 1 } | |
| 466 | while end < lineE, kind(end, bigWord: bigWord) == k { end += 1 } | |
| 467 | if inner { | |
| 468 | for _ in 1..<max(1, count) { | |
| 469 | let k2 = kind(end, bigWord: bigWord) | |
| 470 | while end < lineE, kind(end, bigWord: bigWord) == k2 { end += 1 } | |
| 471 | } | |
| 472 | return start..<end | |
| 473 | } | |
| 474 | for _ in 1..<max(1, count) { | |
| 475 | while end < lineE, let ch = char(end), Self.isBlank(ch) { end += 1 } | |
| 476 | let k2 = kind(end, bigWord: bigWord) | |
| 477 | while end < lineE, kind(end, bigWord: bigWord) == k2 { end += 1 } | |
| 478 | } | |
| 479 | if k == 0 { | |
| 480 | let k2 = kind(end, bigWord: bigWord) | |
| 481 | while end < lineE, kind(end, bigWord: bigWord) == k2 { end += 1 } | |
| 482 | return start..<end | |
| 483 | } | |
| 484 | var trailing = end | |
| 485 | while trailing < lineE, let ch = char(trailing), Self.isBlank(ch) { trailing += 1 } | |
| 486 | if trailing > end { return start..<trailing } | |
| 487 | while start > lineS, let ch = char(start - 1), Self.isBlank(ch) { start -= 1 } | |
| 488 | return start..<end | |
| 489 | } | |
| 490 | ||
| 491 | func quoteObject(_ c: Int, quote: unichar, inner: Bool) -> Range<Int>? { | |
| 492 | let s = lineStart(c) | |
| 493 | let e = lineEnd(c) | |
| 494 | var positions: [Int] = [] | |
| 495 | var p = s | |
| 496 | while p < e { | |
| 497 | if char(p) == quote, p == s || char(p - 1) != 92 { positions.append(p) } | |
| 498 | p += 1 | |
| 499 | } | |
| 500 | var pair: (Int, Int)? | |
| 501 | var i = 0 | |
| 502 | while i + 1 < positions.count { | |
| 503 | if positions[i] <= c, c <= positions[i + 1] { pair = (positions[i], positions[i + 1]); break } | |
| 504 | i += 2 | |
| 505 | } | |
| 506 | guard let (open, close) = pair else { return nil } | |
| 507 | if inner { return (open + 1)..<close } | |
| 508 | var end = close + 1 | |
| 509 | while end < e, let ch = char(end), Self.isBlank(ch) { end += 1 } | |
| 510 | var start = open | |
| 511 | if end == close + 1 { while start > s, let ch = char(start - 1), Self.isBlank(ch) { start -= 1 } } | |
| 512 | return start..<end | |
| 513 | } | |
| 514 | ||
| 515 | func bracketObject(_ c: Int, open: unichar, close: unichar, inner: Bool) -> Range<Int>? { | |
| 516 | var depth = 0 | |
| 517 | var p = c | |
| 518 | var start: Int? | |
| 519 | if char(c) == open { | |
| 520 | start = c | |
| 521 | } else { | |
| 522 | if char(c) == close { p = c - 1 } | |
| 523 | while p >= 0 { | |
| 524 | if char(p) == close { depth += 1 } | |
| 525 | if char(p) == open { | |
| 526 | if depth == 0 { start = p; break } | |
| 527 | depth -= 1 | |
| 528 | } | |
| 529 | p -= 1 | |
| 530 | } | |
| 531 | } | |
| 532 | if start == nil { | |
| 533 | var f = c | |
| 534 | while f < lineEnd(c), char(f) != open { f += 1 } | |
| 535 | if f < lineEnd(c) { start = f } | |
| 536 | } | |
| 537 | guard let s = start else { return nil } | |
| 538 | depth = 0 | |
| 539 | var q = s | |
| 540 | var end: Int? | |
| 541 | while q < length { | |
| 542 | if char(q) == open { depth += 1 } | |
| 543 | if char(q) == close { | |
| 544 | depth -= 1 | |
| 545 | if depth == 0 { end = q; break } | |
| 546 | } | |
| 547 | q += 1 | |
| 548 | } | |
| 549 | guard let e = end else { return nil } | |
| 550 | if !inner { return s..<(e + 1) } | |
| 551 | var innerStart = s + 1 | |
| 552 | var innerEnd = e | |
| 553 | // A block that starts and ends on its own lines keeps them. | |
| 554 | if char(innerStart) == 10, lineStart(innerEnd) == innerEnd || substring(lineStart(innerEnd)..<innerEnd).allSatisfy({ $0 == " " || $0 == "\t" }) { | |
| 555 | innerStart += 1 | |
| 556 | innerEnd = lineStart(innerEnd) | |
| 557 | } | |
| 558 | return innerStart..<innerEnd | |
| 559 | } | |
| 560 | ||
| 561 | func paragraphObject(_ c: Int, inner: Bool) -> Range<Int>? { | |
| 562 | func blank(_ line: Int) -> Bool { substring(line..<lineEnd(line)).allSatisfy { $0 == " " || $0 == "\t" } } | |
| 563 | var start = lineStart(c) | |
| 564 | let isBlank = blank(start) | |
| 565 | while start > 0, blank(lineStart(start - 1)) == isBlank { start = lineStart(start - 1) } | |
| 566 | var end = lineEnd(c) | |
| 567 | while end < length, end + 1 <= length, end + 1 < length || !isBlank, blank(end + 1) == isBlank, end + 1 < length { | |
| 568 | end = lineEnd(end + 1) | |
| 569 | } | |
| 570 | var upper = min(length, end + 1) | |
| 571 | if !inner { | |
| 572 | var after = upper | |
| 573 | while after < length, blank(after) { | |
| 574 | let next = lineEnd(after) | |
| 575 | after = min(length, next + 1) | |
| 576 | if next >= length { break } | |
| 577 | } | |
| 578 | upper = after | |
| 579 | } | |
| 580 | return start..<upper | |
| 581 | } | |
| 582 | } | |
| 583 | } | |
Sources/OrgCore/Keymap/VimMotions.swift added +267
| @@ -0,0 +1,267 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Vim { | |
| 4 | // MARK: - Motions | |
| 5 | ||
| 6 | enum MotionKind { case exclusive, inclusive, linewise } | |
| 7 | ||
| 8 | enum MotionResult { | |
| 9 | case incomplete | |
| 10 | case invalid | |
| 11 | case moved(Int, MotionKind) | |
| 12 | } | |
| 13 | ||
| 14 | mutating func motion(_ keys: [KeyChord], _ buffer: inout Buffer, _ caret: inout Int, count n: Int, operatorPending: Bool) -> MotionResult { | |
| 15 | guard let key = keys.first else { return .incomplete } | |
| 16 | let c = caret | |
| 17 | func column(_ position: Int) -> Int { position - buffer.lineStart(position) } | |
| 18 | switch (key.key, key.modifiers) { | |
| 19 | case ("h", []), ("<left>", []), ("DEL", []): | |
| 20 | goalColumn = nil | |
| 21 | return .moved(max(buffer.lineStart(c), c - n), .exclusive) | |
| 22 | case ("l", []), ("<right>", []), ("SPC", []): | |
| 23 | goalColumn = nil | |
| 24 | let end = buffer.lineEnd(c) | |
| 25 | let limit = operatorPending ? end : max(buffer.lineStart(c), end - 1) | |
| 26 | return .moved(min(limit, c + n), .exclusive) | |
| 27 | case ("j", []), ("k", []), ("<down>", []), ("<up>", []), ("d", [.control]), ("u", [.control]), ("+", []), ("-", []), ("RET", []): | |
| 28 | let down = ["j", "<down>", "+", "RET"].contains(key.key) || key == KeyChord("d", .control) | |
| 29 | let lines = key.modifiers.contains(.control) ? (n == 1 ? contextHalfPage : n) : n | |
| 30 | let goal = goalColumn ?? column(c) | |
| 31 | var line = buffer.lineStart(c) | |
| 32 | var moved = 0 | |
| 33 | for _ in 0..<lines { | |
| 34 | if down { | |
| 35 | let end = buffer.lineEnd(line) | |
| 36 | guard end < buffer.length, end + 1 <= buffer.length else { break } | |
| 37 | if end + 1 == buffer.length { break } | |
| 38 | line = end + 1 | |
| 39 | } else { | |
| 40 | guard line > 0 else { break } | |
| 41 | line = buffer.lineStart(line - 1) | |
| 42 | } | |
| 43 | moved += 1 | |
| 44 | } | |
| 45 | if moved == 0, !key.modifiers.contains(.control) { return .invalid } | |
| 46 | if ["+", "-", "RET"].contains(key.key) { return .moved(buffer.firstNonBlank(line), .linewise) } | |
| 47 | goalColumn = goal | |
| 48 | let length = buffer.lineEnd(line) - line | |
| 49 | return .moved(line + min(goal, operatorPending ? length : max(0, length - 1)), .linewise) | |
| 50 | case ("w", []), ("W", []): | |
| 51 | goalColumn = nil | |
| 52 | var p = c | |
| 53 | for _ in 0..<n { p = buffer.wordForward(p, bigWord: key.key == "W") } | |
| 54 | return .moved(p, .exclusive) | |
| 55 | case ("b", []), ("B", []): | |
| 56 | goalColumn = nil | |
| 57 | var p = c | |
| 58 | for _ in 0..<n { p = buffer.wordBackward(p, bigWord: key.key == "B", stopAtLine: false) } | |
| 59 | return .moved(p, .exclusive) | |
| 60 | case ("e", []), ("E", []): | |
| 61 | goalColumn = nil | |
| 62 | var p = c | |
| 63 | for _ in 0..<n { p = buffer.wordEnd(p, bigWord: key.key == "E", fromInside: false) } | |
| 64 | return .moved(p, .inclusive) | |
| 65 | case ("0", []), ("<home>", []): | |
| 66 | goalColumn = nil | |
| 67 | return .moved(buffer.lineStart(c), .exclusive) | |
| 68 | case ("^", []): | |
| 69 | goalColumn = nil | |
| 70 | return .moved(buffer.firstNonBlank(buffer.lineStart(c)), .exclusive) | |
| 71 | case ("$", []), ("<end>", []): | |
| 72 | var line = buffer.lineStart(c) | |
| 73 | for _ in 1..<max(1, n) where buffer.lineEnd(line) < buffer.length { line = buffer.lineEnd(line) + 1 } | |
| 74 | goalColumn = Int.max | |
| 75 | let end = buffer.lineEnd(line) | |
| 76 | if mode == .visual { return .moved(end, .inclusive) } | |
| 77 | return .moved(max(line, end - 1), .inclusive) | |
| 78 | case ("G", []): | |
| 79 | // `evil-start-of-line` nil: the column stays. | |
| 80 | let line = n > 1 || keys.count > 1 ? buffer.lineOffset(n) : buffer.lineStart(buffer.length) | |
| 81 | let column = c - buffer.lineStart(c) | |
| 82 | let length = buffer.lineEnd(line) - line | |
| 83 | return .moved(line + min(column, operatorPending ? length : max(0, length - 1)), .linewise) | |
| 84 | case ("g", []): | |
| 85 | guard keys.count >= 2 else { return .incomplete } | |
| 86 | switch keys[1].key { | |
| 87 | case "g": | |
| 88 | let line = buffer.lineOffset(n) | |
| 89 | let column = c - buffer.lineStart(c) | |
| 90 | let length = buffer.lineEnd(line) - line | |
| 91 | return .moved(line + min(column, operatorPending ? length : max(0, length - 1)), .linewise) | |
| 92 | case "e", "E": | |
| 93 | var p = c | |
| 94 | for _ in 0..<n { p = buffer.wordEndBackward(p, bigWord: keys[1].key == "E") } | |
| 95 | return .moved(p, .inclusive) | |
| 96 | case "j" where contextOrg, "k" where contextOrg: | |
| 97 | // evil-org: org-forward-element and org-backward-element, which take no count. | |
| 98 | guard let p = Self.orgObject(keys[1].key, inner: false, buffer, c)?.range.lowerBound, p != c else { return .invalid } | |
| 99 | goalColumn = nil | |
| 100 | return .moved(p, .exclusive) | |
| 101 | case "j": | |
| 102 | return motion([KeyChord("j")], &buffer, &caret, count: n, operatorPending: operatorPending) | |
| 103 | case "k": | |
| 104 | return motion([KeyChord("k")], &buffer, &caret, count: n, operatorPending: operatorPending) | |
| 105 | case "_": | |
| 106 | let end = buffer.lineEnd(c) | |
| 107 | var p = end | |
| 108 | while p > buffer.lineStart(c), let ch = buffer.char(p - 1), Buffer.isBlank(ch) { p -= 1 } | |
| 109 | return .moved(max(buffer.lineStart(c), p - 1), .inclusive) | |
| 110 | default: | |
| 111 | return .invalid | |
| 112 | } | |
| 113 | case ("f", []), ("F", []), ("t", []), ("T", []): | |
| 114 | // evil-snipe-override-mode: one-character snipes. | |
| 115 | guard keys.count >= 2 else { return .incomplete } | |
| 116 | let char = keys[1].key == "SPC" ? " " : keys[1].key == "TAB" ? "\t" : keys[1].key | |
| 117 | guard char.count == 1 else { return .invalid } | |
| 118 | let forward = key.key == "f" || key.key == "t" | |
| 119 | lastSnipe = (forward, char, n, key.key == "f" || key.key == "F", (KeyChord(key.key.lowercased()), KeyChord(key.key.uppercased()))) | |
| 120 | return snipe(forward: forward, count: n, buffer, c, operatorPending: operatorPending, repeating: false) | |
| 121 | case (";", []), (",", []): | |
| 122 | // evil-snipe-repeat, with Doom's `evil-snipe-repeat-scope` visible. | |
| 123 | guard let last = lastSnipe else { return .invalid } | |
| 124 | let forward = key.key == ";" ? last.forward : !last.forward | |
| 125 | return snipe(forward: forward, count: n * last.count, buffer, c, operatorPending: operatorPending, repeating: true) | |
| 126 | case ("s", []) where !operatorPending, ("S", []) where !operatorPending: | |
| 127 | guard keys.count >= 3 else { return .incomplete } | |
| 128 | let chars = keys[1...2].map { $0.key == "SPC" ? " " : $0.key == "TAB" ? "\t" : $0.key }.joined() | |
| 129 | lastSnipe = (key.key == "s", chars, n, true, (KeyChord("s"), KeyChord("S"))) | |
| 130 | return snipe(forward: key.key == "s", count: n, buffer, c, operatorPending: operatorPending, repeating: false) | |
| 131 | case ("%", []): | |
| 132 | guard let p = buffer.matchingBracket(c) else { return .invalid } | |
| 133 | return .moved(p, .inclusive) | |
| 134 | case ("'", []), ("`", []): | |
| 135 | guard keys.count >= 2 else { return .incomplete } | |
| 136 | let name = keys[1].key == "'" || keys[1].key == "`" ? Character("'") : keys[1].key.first | |
| 137 | guard let name, let mark = currentMarks[name] else { return .invalid } | |
| 138 | goalColumn = nil | |
| 139 | let p = min(mark, buffer.length) | |
| 140 | return key.key == "'" ? .moved(buffer.firstNonBlank(buffer.lineStart(p)), .linewise) : .moved(p, .exclusive) | |
| 141 | case ("}", []), ("{", []): | |
| 142 | var p = c | |
| 143 | for _ in 0..<n { p = buffer.paragraph(p, forward: key.key == "}") } | |
| 144 | return .moved(p, .exclusive) | |
| 145 | case ("n", []), ("N", []): | |
| 146 | guard let search = lastSearch else { return .invalid } | |
| 147 | let forward = key.key == "n" ? search.forward : !search.forward | |
| 148 | guard let p = buffer.search(search.pattern, from: c, forward: forward, count: n) else { return .invalid } | |
| 149 | return .moved(p, .exclusive) | |
| 150 | case ("*", []), ("#", []): | |
| 151 | guard let word = buffer.wordAt(c) else { return .invalid } | |
| 152 | let pattern = "\\b" + NSRegularExpression.escapedPattern(for: word) + "\\b" | |
| 153 | lastSearch = (pattern, key.key == "*") | |
| 154 | guard let p = buffer.search(pattern, from: buffer.wordStart(c), forward: key.key == "*", count: n) else { return .invalid } | |
| 155 | return .moved(p, .exclusive) | |
| 156 | case ("H", []), ("M", []), ("L", []): | |
| 157 | // The visible lines: H the count-th from the top, L from the bottom, M the middle. | |
| 158 | guard let visible = contextVisible else { return .invalid } | |
| 159 | goalColumn = nil | |
| 160 | let lower = min(visible.lowerBound, buffer.length) | |
| 161 | let last = buffer.lineStart(max(lower, min(visible.upperBound, buffer.length) - 1)) | |
| 162 | var lines: [Int] = [] | |
| 163 | var line = buffer.lineStart(lower) | |
| 164 | while true { | |
| 165 | lines.append(line) | |
| 166 | guard line < last, buffer.lineEnd(line) < buffer.length else { break } | |
| 167 | line = buffer.lineEnd(line) + 1 | |
| 168 | } | |
| 169 | let index = key.key == "H" ? min(n, lines.count) - 1 : key.key == "L" ? max(0, lines.count - n) : (lines.count - 1) / 2 | |
| 170 | return .moved(buffer.firstNonBlank(lines[index]), .linewise) | |
| 171 | default: | |
| 172 | return .invalid | |
| 173 | } | |
| 174 | } | |
| 175 | ||
| 176 | /// `evil-snipe--seek` for the last snipe: the `n`th match from `c` in the line after (or | |
| 177 | /// before) the search start, or for a repeat in the visible text, with smart case, | |
| 178 | /// Doom's `evil-snipe-char-fold` and `evil-snipe-skip-leading-whitespace`. | |
| 179 | mutating func snipe(forward: Bool, count n: Int, _ buffer: Buffer, _ c: Int, operatorPending: Bool, repeating: Bool) -> MotionResult { | |
| 180 | guard let last = lastSnipe else { return .invalid } | |
| 181 | // f, s and F search from the next or this character, t and T one further. | |
| 182 | let start = forward ? c + (last.consume ? 1 : 2) : c - (last.consume ? 0 : 1) | |
| 183 | guard start >= 0, start <= buffer.length else { return .invalid } | |
| 184 | var bound = forward ? buffer.lineEnd(start) : buffer.lineStart(start) | |
| 185 | if repeating, let visible = contextVisible { | |
| 186 | bound = forward ? min(visible.upperBound, buffer.length) - 1 : min(visible.lowerBound, start) | |
| 187 | } | |
| 188 | let blankKeys = last.chars.first == " " || last.chars.first == "\t" | |
| 189 | let regexps = last.chars.map(CharFold.regexp) | |
| 190 | var pattern = regexps.map(CharFold.icu).joined() | |
| 191 | if blankKeys, let ch = buffer.char(start), Buffer.isBlank(ch) { pattern += "[^ \t]" } | |
| 192 | // `evil-snipe--case-p`: case matters when the regexps hold a capital letter. | |
| 193 | let caseFold = !regexps.joined().unicodeScalars.contains { ("A"..."Z").contains($0) } | |
| 194 | let regex = try! NSRegularExpression(pattern: pattern, options: caseFold ? .caseInsensitive : []) | |
| 195 | var match: NSRange? | |
| 196 | if forward, start <= bound { | |
| 197 | var from = start | |
| 198 | for _ in 0..<n { | |
| 199 | match = regex.firstMatch(in: buffer.ns as String, range: NSRange(location: from, length: bound - from))?.range | |
| 200 | guard let found = match else { break } | |
| 201 | from = NSMaxRange(found) | |
| 202 | } | |
| 203 | } else if !forward { | |
| 204 | var from = start | |
| 205 | for _ in 0..<n { | |
| 206 | match = nil | |
| 207 | var p = from - 1 | |
| 208 | while p >= bound, match == nil { | |
| 209 | match = regex.firstMatch(in: buffer.ns as String, options: .anchored, range: NSRange(location: p, length: from - p))?.range | |
| 210 | p -= 1 | |
| 211 | } | |
| 212 | guard let found = match else { break } | |
| 213 | from = found.location | |
| 214 | } | |
| 215 | } | |
| 216 | guard let found = match else { | |
| 217 | if repeating { snipeRepeatKeys = last.keys } | |
| 218 | return .invalid | |
| 219 | } | |
| 220 | if !operatorPending { snipeRepeatKeys = last.keys } | |
| 221 | var end = NSMaxRange(found) | |
| 222 | var length = found.length | |
| 223 | if blankKeys { | |
| 224 | end -= 1 | |
| 225 | length -= 1 | |
| 226 | } | |
| 227 | let visual = mode == .visual || mode == .visualLine || mode == .visualBlock | |
| 228 | var p: Int | |
| 229 | if !forward { | |
| 230 | p = last.consume ? found.location : end | |
| 231 | } else { | |
| 232 | p = visual ? (last.consume ? end : found.location) : operatorPending ? end : found.location | |
| 233 | if last.consume { | |
| 234 | if visual { p -= 1 } | |
| 235 | } else { | |
| 236 | p -= length | |
| 237 | if length > 1, !operatorPending { p += 1 } | |
| 238 | } | |
| 239 | } | |
| 240 | return .moved(p, .exclusive) | |
| 241 | } | |
| 242 | ||
| 243 | // MARK: - Text objects | |
| 244 | ||
| 245 | func textObject(_ inner: Bool, _ key: KeyChord, _ buffer: Buffer, _ c: Int, count: Int) -> (range: Range<Int>, linewise: Bool)? { | |
| 246 | switch key.key { | |
| 247 | case "w", "W": | |
| 248 | return buffer.wordObject(c, inner: inner, bigWord: key.key == "W", count: count).map { ($0, false) } | |
| 249 | case "\"", "'", "`": | |
| 250 | return buffer.quoteObject(c, quote: key.key.utf16.first!, inner: inner).map { ($0, false) } | |
| 251 | case "(", ")", "b": | |
| 252 | return buffer.bracketObject(c, open: 40, close: 41, inner: inner).map { ($0, false) } | |
| 253 | case "[", "]": | |
| 254 | return buffer.bracketObject(c, open: 91, close: 93, inner: inner).map { ($0, false) } | |
| 255 | case "{", "}", "B": | |
| 256 | return buffer.bracketObject(c, open: 123, close: 125, inner: inner).map { ($0, false) } | |
| 257 | case "<", ">": | |
| 258 | return buffer.bracketObject(c, open: 60, close: 62, inner: inner).map { ($0, false) } | |
| 259 | case "p": | |
| 260 | return buffer.paragraphObject(c, inner: inner).map { ($0, true) } | |
| 261 | case "e", "E", "r", "R": | |
| 262 | return Self.orgObject(key.key, inner: inner, buffer, c) | |
| 263 | default: | |
| 264 | return nil | |
| 265 | } | |
| 266 | } | |
| 267 | } | |
Sources/OrgCore/Keymap/VimParser.swift added +300
| @@ -0,0 +1,300 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Vim { | |
| 4 | // MARK: - Parsing | |
| 5 | ||
| 6 | enum Parse { | |
| 7 | case incomplete | |
| 8 | case invalid | |
| 9 | case done([Action]) | |
| 10 | } | |
| 11 | ||
| 12 | struct Command { | |
| 13 | var register: Character? | |
| 14 | var count: Int? | |
| 15 | var keys: ArraySlice<KeyChord> | |
| 16 | } | |
| 17 | ||
| 18 | /// `evil-shift-width`, which Doom keeps equal to `tab-width`: 8 in Org. | |
| 19 | static let shiftWidth = 8 | |
| 20 | ||
| 21 | /// What `indent-according-to-mode` gives a line after `line` in Org: under a list item, | |
| 22 | /// its text's column; under a heading, none; otherwise `line`'s own indentation. | |
| 23 | static func indentation(for buffer: Buffer, line: Int) -> String { | |
| 24 | let text = buffer.substring(buffer.lineStart(line)..<buffer.lineEnd(line)) | |
| 25 | let item = try! NSRegularExpression(pattern: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]+") | |
| 26 | let ns = text as NSString | |
| 27 | if text.hasPrefix("*") { return "" } | |
| 28 | if let m = item.firstMatch(in: text, range: NSRange(location: 0, length: ns.length)) { | |
| 29 | return String(repeating: " ", count: m.range.length) | |
| 30 | } | |
| 31 | return String(text.prefix { $0 == " " || $0 == "\t" }) | |
| 32 | } | |
| 33 | ||
| 34 | static func digit(_ key: KeyChord) -> Int? { | |
| 35 | guard key.modifiers.isEmpty, key.key.count == 1, let d = Int(key.key) else { return nil } | |
| 36 | return d | |
| 37 | } | |
| 38 | ||
| 39 | /// Reads `"r` and a count off the front of `keys`. | |
| 40 | static func prefix(_ keys: [KeyChord]) -> (register: Character?, count: Int?, rest: ArraySlice<KeyChord>)? { | |
| 41 | var rest = keys[...] | |
| 42 | var register: Character? | |
| 43 | if rest.first?.key == "\"", rest.first?.modifiers.isEmpty == true { | |
| 44 | guard rest.count >= 2 else { return nil } | |
| 45 | register = rest[rest.startIndex + 1].key == "SPC" ? " " : rest[rest.startIndex + 1].key.first | |
| 46 | rest = rest.dropFirst(2) | |
| 47 | } | |
| 48 | var count: Int? | |
| 49 | while let key = rest.first, let d = digit(key), !(d == 0 && count == nil) { | |
| 50 | count = (count ?? 0) * 10 + d | |
| 51 | rest = rest.dropFirst() | |
| 52 | } | |
| 53 | return (register, count, rest) | |
| 54 | } | |
| 55 | ||
| 56 | mutating func parse(_ keys: [KeyChord], _ buffer: inout Buffer, _ context: Context) -> Parse { | |
| 57 | guard let (register, count, rest) = Self.prefix(keys) else { return .incomplete } | |
| 58 | guard let first = rest.first else { return .incomplete } | |
| 59 | let visual = mode == .visual || mode == .visualLine | |
| 60 | let n = count ?? 1 | |
| 61 | let caret = context.caret | |
| 62 | ||
| 63 | if mode == .visualBlock { return parseBlock(rest, &buffer, context, register: register, count: n, keys: keys) } | |
| 64 | if let result = parseExtras(rest, &buffer, context, register: register, count: count, keys: keys) { return result } | |
| 65 | ||
| 66 | // Operators. | |
| 67 | let operatorKeys: [String: String] = ["d": "d", "c": "c", "y": "y", ">": ">", "<": "<"] | |
| 68 | var op: String? | |
| 69 | var afterOp = rest.dropFirst() | |
| 70 | if first.modifiers.isEmpty, let o = operatorKeys[first.key] { | |
| 71 | op = o | |
| 72 | } else if first.key == "g", first.modifiers.isEmpty { | |
| 73 | guard let second = rest.dropFirst().first else { return .incomplete } | |
| 74 | if ["~", "u", "U", "c", "q", "w"].contains(second.key), second.modifiers.isEmpty { | |
| 75 | op = "g" + second.key | |
| 76 | afterOp = rest.dropFirst(2) | |
| 77 | } | |
| 78 | } | |
| 79 | if let op { | |
| 80 | if visual { | |
| 81 | let range = visualRange(buffer, caret) | |
| 82 | return .done(apply(op, range: range.range, linewise: range.linewise, buffer, register: register, keys: keys, count: n)) | |
| 83 | } | |
| 84 | // A second count and the motion. | |
| 85 | guard let (_, count2, motionKeys) = Self.prefix(Array(afterOp)), let motionFirst = motionKeys.first else { return .incomplete } | |
| 86 | let total = n * (count2 ?? 1) | |
| 87 | let doubled = op.count == 1 ? op : String(op.last!) | |
| 88 | if motionFirst.key == doubled, motionFirst.modifiers.isEmpty, motionKeys.count == 1 || (op.count == 2 && motionFirst.key == String(op.last!)) { | |
| 89 | // dd, cc, yy, >>, <<, g~~, guu, gUU: whole lines. | |
| 90 | let startLine = buffer.lineStart(caret) | |
| 91 | var end = startLine | |
| 92 | for _ in 0..<total { | |
| 93 | let next = buffer.lineEnd(end) | |
| 94 | end = next < buffer.length ? next + 1 : next | |
| 95 | if end >= buffer.length { break } | |
| 96 | } | |
| 97 | return .done(apply(op, range: startLine..<max(end, buffer.lineEnd(startLine)), linewise: true, buffer, register: register, keys: keys, count: total)) | |
| 98 | } | |
| 99 | if motionFirst.key == "i" || motionFirst.key == "a", motionFirst.modifiers.isEmpty { | |
| 100 | guard motionKeys.count >= 2 else { return .incomplete } | |
| 101 | guard let object = textObject(motionFirst.key == "i", motionKeys[motionKeys.startIndex + 1], buffer, caret, count: total) else { return .invalid } | |
| 102 | // evil-org's subtree objects move point to the heading first. | |
| 103 | if motionKeys[motionKeys.startIndex + 1].key == "R" { caretForApply = buffer.lineStart(object.range.lowerBound) } | |
| 104 | return .done(apply(op, range: object.range, linewise: object.linewise, buffer, register: register, keys: keys, count: total)) | |
| 105 | } | |
| 106 | var motionCaret = caret | |
| 107 | if op == "c", motionFirst.key == "w" || motionFirst.key == "W", motionFirst.modifiers.isEmpty, | |
| 108 | let c = buffer.char(caret), !Buffer.isBlank(c) { | |
| 109 | // cw acts as ce on a word. | |
| 110 | var end = caret | |
| 111 | for _ in 0..<total { end = buffer.wordEnd(end, bigWord: motionFirst.key == "W", fromInside: true) } | |
| 112 | return .done(apply(op, range: caret..<min(buffer.length, end + 1), linewise: false, buffer, register: register, keys: keys, count: total)) | |
| 113 | } | |
| 114 | switch motion(Array(motionKeys), &buffer, &motionCaret, count: total, operatorPending: true) { | |
| 115 | case .incomplete: return .incomplete | |
| 116 | case .invalid: return .invalid | |
| 117 | case .moved(let target, let kind): | |
| 118 | var range: Range<Int> | |
| 119 | var linewise = false | |
| 120 | switch kind { | |
| 121 | case .linewise: | |
| 122 | let a = buffer.lineStart(min(caret, target)) | |
| 123 | let b = buffer.lineEnd(max(caret, target)) | |
| 124 | range = a..<min(buffer.length, b + 1) | |
| 125 | linewise = true | |
| 126 | case .inclusive: | |
| 127 | range = min(caret, target)..<min(buffer.length, max(caret, target) + 1) | |
| 128 | case .exclusive: | |
| 129 | range = min(caret, target)..<max(caret, target) | |
| 130 | // dw at the end of a line stops at the line's end. | |
| 131 | if motionFirst.key == "w" || motionFirst.key == "W", buffer.lineStart(range.upperBound) != buffer.lineStart(range.lowerBound), range.upperBound > range.lowerBound { | |
| 132 | var end = buffer.lineEnd(range.lowerBound) | |
| 133 | if end == range.lowerBound, total == 1 { end = min(buffer.length, end + 1) } | |
| 134 | let upper = buffer.firstNonBlankOrEnd(buffer.lineStart(range.upperBound)) == range.upperBound | |
| 135 | ? max(range.lowerBound, min(end, range.upperBound)) : range.upperBound | |
| 136 | range = range.lowerBound..<(upper == range.lowerBound ? end : upper) | |
| 137 | if buffer.lineStart(range.upperBound) != buffer.lineStart(range.lowerBound) { | |
| 138 | range = range.lowerBound..<buffer.lineEnd(range.lowerBound) | |
| 139 | } | |
| 140 | } | |
| 141 | } | |
| 142 | return .done(apply(op, range: range, linewise: linewise, buffer, register: register, keys: keys, count: total)) | |
| 143 | } | |
| 144 | } | |
| 145 | ||
| 146 | if visual, first.modifiers.isEmpty { | |
| 147 | switch first.key { | |
| 148 | case "ESC": | |
| 149 | lastVisual = (anchor, caret, mode) | |
| 150 | mode = .normal | |
| 151 | return .done([.move(caret: buffer.clampNormal(caret))]) | |
| 152 | case "o": | |
| 153 | let old = anchor | |
| 154 | anchor = caret | |
| 155 | return .done(visualActions(buffer, old)) | |
| 156 | case "x": | |
| 157 | let range = visualRange(buffer, caret) | |
| 158 | return .done(apply("d", range: range.range, linewise: range.linewise, buffer, register: register, keys: keys, count: n)) | |
| 159 | case "~", "u", "U": | |
| 160 | let range = visualRange(buffer, caret) | |
| 161 | return .done(apply(first.key == "~" ? "g~" : "g" + first.key, range: range.range, linewise: range.linewise, buffer, register: register, keys: keys, count: n)) | |
| 162 | case "J": | |
| 163 | let range = visualRange(buffer, caret) | |
| 164 | let lines = max(2, buffer.lineCount(range.range)) | |
| 165 | mode = .normal | |
| 166 | return .done(join(buffer, at: range.range.lowerBound, lines: lines, keys: keys)) | |
| 167 | case "p", "P": | |
| 168 | let range = visualRange(buffer, caret) | |
| 169 | guard let (text, linewise) = paste(register, context) else { return .done([]) } | |
| 170 | mode = .normal | |
| 171 | var replacement = text | |
| 172 | if linewise, !range.linewise { replacement = "\n" + text } | |
| 173 | if !linewise, range.linewise { replacement += "\n" } | |
| 174 | let removed = buffer.substring(range.range) | |
| 175 | var actions: [Action] = [.edit([TextEdit(range: range.range, replacement: replacement)], caret: range.range.lowerBound + (linewise ? 0 : max(0, replacement.utf16.count - 1)))] | |
| 176 | actions += store(removed, linewise: range.linewise, register: nil, yank: false) | |
| 177 | return .done(actions) | |
| 178 | case "v": | |
| 179 | if mode == .visual { | |
| 180 | mode = .normal | |
| 181 | return .done([.move(caret: buffer.clampNormal(caret))]) | |
| 182 | } | |
| 183 | mode = .visual | |
| 184 | return .done(visualActions(buffer, caret)) | |
| 185 | case "V": | |
| 186 | if mode == .visualLine { | |
| 187 | mode = .normal | |
| 188 | return .done([.move(caret: buffer.clampNormal(caret))]) | |
| 189 | } | |
| 190 | mode = .visualLine | |
| 191 | return .done(visualActions(buffer, caret)) | |
| 192 | case "i", "a": | |
| 193 | guard rest.count >= 2 else { return .incomplete } | |
| 194 | guard let object = textObject(first.key == "i", rest[rest.startIndex + 1], buffer, caret, count: n) else { return .invalid } | |
| 195 | if object.linewise { mode = .visualLine } | |
| 196 | anchor = object.range.lowerBound | |
| 197 | let end = max(object.range.lowerBound, object.range.upperBound - 1) | |
| 198 | return .done(visualActions(buffer, end)) | |
| 199 | default: | |
| 200 | break | |
| 201 | } | |
| 202 | } | |
| 203 | ||
| 204 | if !visual { | |
| 205 | switch (first.key, first.modifiers) { | |
| 206 | case ("i", []), ("a", []), ("I", []), ("A", []), ("o", []), ("O", []): | |
| 207 | return .done(enterInsert(first.key, buffer, caret, keys: keys)) | |
| 208 | case ("v", []): | |
| 209 | mode = .visual | |
| 210 | anchor = caret | |
| 211 | return .done(visualActions(buffer, caret)) | |
| 212 | case ("V", []): | |
| 213 | mode = .visualLine | |
| 214 | anchor = caret | |
| 215 | return .done(visualActions(buffer, caret)) | |
| 216 | case ("x", []), ("<delete>", []): | |
| 217 | guard let c = buffer.char(caret), c != 10 else { return .done([]) } | |
| 218 | let end = min(buffer.lineEnd(caret), caret + n) | |
| 219 | return .done(apply("d", range: caret..<end, linewise: false, buffer, register: register, keys: keys, count: n)) | |
| 220 | case ("X", []): | |
| 221 | let start = max(buffer.lineStart(caret), caret - n) | |
| 222 | guard start < caret else { return .done([]) } | |
| 223 | return .done(apply("d", range: start..<caret, linewise: false, buffer, register: register, keys: keys, count: n)) | |
| 224 | case ("D", []), ("C", []): | |
| 225 | var end = buffer.lineEnd(caret) | |
| 226 | for _ in 1..<max(1, n) where end < buffer.length { end = buffer.lineEnd(end + 1) } | |
| 227 | return .done(apply(first.key == "D" ? "d" : "c", range: caret..<end, linewise: false, buffer, register: register, keys: keys, count: n)) | |
| 228 | case ("Y", []): | |
| 229 | // `evil-want-Y-yank-to-eol`. | |
| 230 | return .done(apply("y", range: caret..<buffer.lineEnd(caret), linewise: false, buffer, register: register, keys: keys, count: n)) | |
| 231 | case ("p", []), ("P", []): | |
| 232 | guard let (text, linewise) = paste(register, context) else { return .done([]) } | |
| 233 | let repeated = String(repeating: text, count: n) | |
| 234 | if linewise { | |
| 235 | let body = repeated.hasSuffix("\n") ? repeated : repeated + "\n" | |
| 236 | if first.key == "p" { | |
| 237 | let end = buffer.lineEnd(caret) | |
| 238 | if end >= buffer.length { | |
| 239 | let insertion = "\n" + String(body.dropLast()) | |
| 240 | return .done(change([TextEdit(range: end..<end, replacement: insertion)], caret: buffer.firstNonBlankIn(insertion, at: end + 1), keys: keys)) | |
| 241 | } | |
| 242 | return .done(change([TextEdit(range: (end + 1)..<(end + 1), replacement: body)], caret: buffer.firstNonBlankIn(body, at: end + 1), keys: keys)) | |
| 243 | } | |
| 244 | let start = buffer.lineStart(caret) | |
| 245 | return .done(change([TextEdit(range: start..<start, replacement: body)], caret: buffer.firstNonBlankIn(body, at: start), keys: keys)) | |
| 246 | } | |
| 247 | let at = first.key == "p" && buffer.char(caret).map({ $0 != 10 }) == true ? caret + 1 : caret | |
| 248 | return .done(change([TextEdit(range: at..<at, replacement: repeated)], caret: at + max(0, repeated.utf16.count - 1), keys: keys)) | |
| 249 | case ("J", []): | |
| 250 | return .done(join(buffer, at: caret, lines: max(2, n), keys: keys)) | |
| 251 | case ("~", []): | |
| 252 | let end = min(buffer.lineEnd(caret), caret + n) | |
| 253 | guard end > caret else { return .done([]) } | |
| 254 | let flipped = String(buffer.substring(caret..<end).map { $0.isUppercase ? Character($0.lowercased()) : Character($0.uppercased()) }) | |
| 255 | return .done(change([TextEdit(range: caret..<end, replacement: flipped)], caret: buffer.clampNormal(end, in: buffer.lineStart(caret)), keys: keys)) | |
| 256 | case ("r", []): | |
| 257 | guard rest.count >= 2 else { return .incomplete } | |
| 258 | let target = rest[rest.startIndex + 1] | |
| 259 | let char = target.key == "SPC" ? " " : target.key == "RET" ? "\n" : target.key | |
| 260 | guard char.count == 1, caret + n <= buffer.lineEnd(caret) else { return .done([]) } | |
| 261 | let replacement = char == "\n" ? "\n" : String(repeating: char, count: n) | |
| 262 | return .done(change([TextEdit(range: caret..<(caret + n), replacement: replacement)], caret: char == "\n" ? caret + 1 : caret + n - 1, keys: keys)) | |
| 263 | case ("u", []): | |
| 264 | return .done([.undo(n)]) | |
| 265 | case ("r", [.control]): | |
| 266 | return .done([.redo(n)]) | |
| 267 | case (".", []): | |
| 268 | return .done(repeatChange(n, context)) | |
| 269 | case (":", []): | |
| 270 | return .done([.prompt(":")]) | |
| 271 | case ("/", []), ("?", []): | |
| 272 | return .done([.prompt(first.key)]) | |
| 273 | case ("Z", []): | |
| 274 | guard rest.count >= 2 else { return .incomplete } | |
| 275 | switch rest[rest.startIndex + 1].key { | |
| 276 | case "Z": return .done([.ex("wq")]) | |
| 277 | case "Q": return .done([.ex("q!")]) | |
| 278 | default: return .invalid | |
| 279 | } | |
| 280 | default: | |
| 281 | break | |
| 282 | } | |
| 283 | } | |
| 284 | ||
| 285 | if mode == .normal, !contextOrg, rest.count == 2, first == KeyChord("g"), rest.last == KeyChord("j") || rest.last == KeyChord("k") { | |
| 286 | return .done([.visualLines(rest.last == KeyChord("j") ? n : -n)]) | |
| 287 | } | |
| 288 | ||
| 289 | // Motions move the caret, or extend the selection in visual states. | |
| 290 | var target = caret | |
| 291 | switch motion(Array(rest), &buffer, &target, count: n, operatorPending: false) { | |
| 292 | case .incomplete: return .incomplete | |
| 293 | case .invalid: return .invalid | |
| 294 | case .moved(let to, _): | |
| 295 | if visual { return .done(visualActions(buffer, to)) } | |
| 296 | let jump: [Action] = Self.isJump(Array(rest)) && to != caret ? [.jumped(from: caret)] : [] | |
| 297 | return .done(jump + [.move(caret: buffer.clampNormal(to))]) | |
| 298 | } | |
| 299 | } | |
| 300 | } | |
Sources/OrgEditorAppKit/Fragments.swift added +145
| @@ -0,0 +1,145 @@ | ||
| 1 | #if os(macOS) | |
| 2 | import AppKit | |
| 3 | ||
| 4 | /// A line of a block, on a band across the whole width of the view, as Emacs extends the | |
| 5 | /// `org-block` face. | |
| 6 | final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 7 | private var band: CGRect { | |
| 8 | let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width | |
| 9 | // Not under the empty line TextKit adds after a final newline. | |
| 10 | let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height | |
| 11 | return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height) | |
| 12 | } | |
| 13 | ||
| 14 | override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) } | |
| 15 | ||
| 16 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 17 | context.saveGState() | |
| 18 | context.setFillColor(Theme.blockBackground.cgColor) | |
| 19 | context.fill(band.offsetBy(dx: point.x, dy: point.y)) | |
| 20 | // The band covers the view's selection highlight, so the selected text is drawn on it, | |
| 21 | // in the color the view uses: the theme's when focused, the system's muted one when not. | |
| 22 | if let manager = textLayoutManager { | |
| 23 | let active = Theme.focusedLayouts.contains(ObjectIdentifier(manager)) | |
| 24 | context.setFillColor((active ? Theme.selection : NSColor.unemphasizedSelectedTextBackgroundColor).cgColor) | |
| 25 | let single = textLineFragments.count == 1 | |
| 26 | for selection in manager.textSelections { | |
| 27 | for range in selection.textRanges where !range.isEmpty { | |
| 28 | guard let part = range.intersection(rangeInElement), !part.isEmpty else { continue } | |
| 29 | manager.enumerateTextSegments(in: part, type: .selection, options: [.rangeNotRequired]) { _, frame, _, _ in | |
| 30 | var rect = frame.offsetBy(dx: point.x - self.layoutFragmentFrame.minX, dy: point.y - self.layoutFragmentFrame.minY) | |
| 31 | // A one-line fragment's selection covers its band, leaving no gap to the next line. | |
| 32 | if single { rect = CGRect(x: rect.minX, y: point.y, width: rect.width, height: self.band.height) } | |
| 33 | context.fill(rect) | |
| 34 | return true | |
| 35 | } | |
| 36 | } | |
| 37 | } | |
| 38 | } | |
| 39 | context.restoreGState() | |
| 40 | super.draw(at: point, in: context) | |
| 41 | } | |
| 42 | } | |
| 43 | ||
| 44 | extension NSAttributedString.Key { | |
| 45 | /// The character an entity shows as, on the entity's last character. | |
| 46 | static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay") | |
| 47 | /// The image an image link's line shows under it. | |
| 48 | static let orgImage = NSAttributedString.Key("OrgImage") | |
| 49 | } | |
| 50 | ||
| 51 | final class InlineImageBox: NSObject, @unchecked Sendable { | |
| 52 | let image: NSImage | |
| 53 | let size: CGSize | |
| 54 | init(image: NSImage, size: CGSize) { | |
| 55 | self.image = image | |
| 56 | self.size = size | |
| 57 | } | |
| 58 | } | |
| 59 | ||
| 60 | /// An image link's line drawn as the image, with the paragraph spacing making room for its | |
| 61 | /// height. | |
| 62 | final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 63 | static func image(_ string: NSAttributedString) -> InlineImageBox? { | |
| 64 | var found: InlineImageBox? | |
| 65 | string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in | |
| 66 | if let box = value as? InlineImageBox { found = box; stop.pointee = true } | |
| 67 | } | |
| 68 | return found | |
| 69 | } | |
| 70 | ||
| 71 | private var frame: CGRect? { | |
| 72 | guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil } | |
| 73 | return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height) | |
| 74 | } | |
| 75 | ||
| 76 | override var renderingSurfaceBounds: CGRect { | |
| 77 | frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds | |
| 78 | } | |
| 79 | ||
| 80 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 81 | super.draw(at: point, in: context) | |
| 82 | guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return } | |
| 83 | NSGraphicsContext.saveGraphicsState() | |
| 84 | NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true) | |
| 85 | box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil) | |
| 86 | NSGraphicsContext.restoreGraphicsState() | |
| 87 | } | |
| 88 | } | |
| 89 | ||
| 90 | /// A paragraph with pretty entities: each is drawn as its character where the entity's last | |
| 91 | /// (now invisible) character sits, so it takes one column as in Emacs. | |
| 92 | final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 93 | static func hasEntities(_ string: NSAttributedString) -> Bool { | |
| 94 | var found = false | |
| 95 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in | |
| 96 | if value != nil { found = true; stop.pointee = true } | |
| 97 | } | |
| 98 | return found | |
| 99 | } | |
| 100 | ||
| 101 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 102 | super.draw(at: point, in: context) | |
| 103 | Self.drawEntities(of: self, at: point, in: context) | |
| 104 | } | |
| 105 | ||
| 106 | static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) { | |
| 107 | guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return } | |
| 108 | NSGraphicsContext.saveGraphicsState() | |
| 109 | NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true) | |
| 110 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in | |
| 111 | guard let display = value as? String, | |
| 112 | let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return } | |
| 113 | var attributes = string.attributes(at: range.location, effectiveRange: nil) | |
| 114 | attributes[.foregroundColor] = NSColor.textColor | |
| 115 | attributes[.orgEntityDisplay] = nil | |
| 116 | let x = line.locationForCharacter(at: range.location).x | |
| 117 | let bounds = line.typographicBounds | |
| 118 | NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY)) | |
| 119 | } | |
| 120 | NSGraphicsContext.restoreGraphicsState() | |
| 121 | } | |
| 122 | } | |
| 123 | ||
| 124 | /// A heading line drawn with an ellipsis after it, like org's folded headings. | |
| 125 | final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 126 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 127 | super.draw(at: point, in: context) | |
| 128 | EntityFragment.drawEntities(of: self, at: point, in: context) | |
| 129 | guard let line = textLineFragments.first else { return } | |
| 130 | let bounds = line.typographicBounds | |
| 131 | let ellipsis = NSAttributedString(string: " …", attributes: [ | |
| 132 | .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular), | |
| 133 | .foregroundColor: NSColor.secondaryLabelColor, | |
| 134 | ]) | |
| 135 | NSGraphicsContext.saveGraphicsState() | |
| 136 | NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true) | |
| 137 | ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY)) | |
| 138 | NSGraphicsContext.restoreGraphicsState() | |
| 139 | } | |
| 140 | ||
| 141 | override var renderingSurfaceBounds: CGRect { | |
| 142 | super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) | |
| 143 | } | |
| 144 | } | |
| 145 | #endif | |
Sources/OrgEditorAppKit/HiddenRanges.swift added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | #if os(macOS) | |
| 2 | import Foundation | |
| 3 | ||
| 4 | /// Hidden ranges, read by TextKit's enumeration callbacks, which may run off the main thread. | |
| 5 | final class HiddenRanges: @unchecked Sendable { | |
| 6 | private let lock = NSLock() | |
| 7 | private var ranges: [Range<Int>] = [] | |
| 8 | ||
| 9 | func set(_ new: [Range<Int>]) { | |
| 10 | lock.withLock { ranges = new } | |
| 11 | } | |
| 12 | ||
| 13 | var all: [Range<Int>] { | |
| 14 | lock.withLock { ranges } | |
| 15 | } | |
| 16 | ||
| 17 | func covers(_ start: Int, _ end: Int) -> Bool { | |
| 18 | lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } } | |
| 19 | } | |
| 20 | ||
| 21 | func containing(_ offset: Int) -> Range<Int>? { | |
| 22 | lock.withLock { ranges.first { $0.lowerBound <= offset && offset < $0.upperBound } } | |
| 23 | } | |
| 24 | } | |
| 25 | ||
| 26 | /// Folded heading starts, read by the layout-fragment callback. | |
| 27 | final class FoldedHeadings: @unchecked Sendable { | |
| 28 | private let lock = NSLock() | |
| 29 | private var starts: Set<Int> = [] | |
| 30 | ||
| 31 | func set(_ new: Set<Int>) { | |
| 32 | lock.withLock { starts = new } | |
| 33 | } | |
| 34 | ||
| 35 | func contains(_ offset: Int) -> Bool { | |
| 36 | lock.withLock { starts.contains(offset) } | |
| 37 | } | |
| 38 | ||
| 39 | var all: Set<Int> { | |
| 40 | lock.withLock { starts } | |
| 41 | } | |
| 42 | } | |
| 43 | #endif | |
Sources/OrgEditorAppKit/OrgEditor+Folding.swift added +214
| @@ -0,0 +1,214 @@ | ||
| 1 | #if os(macOS) | |
| 2 | import AppKit | |
| 3 | import OrgCore | |
| 4 | import OrgPresentation | |
| 5 | ||
| 6 | extension OrgEditor { | |
| 7 | // MARK: - Folding | |
| 8 | ||
| 9 | public var foldState: FoldState { | |
| 10 | FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds) | |
| 11 | } | |
| 12 | ||
| 13 | ||
| 14 | public func setFolds(_ state: FoldState) { | |
| 15 | setFolds(state, wrappers: nil) | |
| 16 | } | |
| 17 | ||
| 18 | /// `wrappers`, when given, holds every folded drawer and block. | |
| 19 | func setFolds(_ state: FoldState, wrappers: [Wrapper]?) { | |
| 20 | sparseHidden = nil | |
| 21 | view.folds = state.folds | |
| 22 | view.bodyFolds = state.bodyFolds | |
| 23 | view = view.pruned(to: document.tree, wrappers: false) | |
| 24 | // Found one by one, or all at once when there are many. | |
| 25 | let found = wrappers ?? (state.wrapperFolds.count > 32 | |
| 26 | ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) } | |
| 27 | : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) }) | |
| 28 | wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a } | |
| 29 | view.wrapperFolds = Set(wrapperHidden.keys) | |
| 30 | updateHiddenAndLayout() | |
| 31 | orgTextView?.redrawLineNumbers() | |
| 32 | textView.needsDisplay = true | |
| 33 | let caret = textView.selectedRange().location | |
| 34 | if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) } | |
| 35 | } | |
| 36 | ||
| 37 | ||
| 38 | func updateHidden() { | |
| 39 | if let sparseHidden { | |
| 40 | let ns = textView.string as NSString | |
| 41 | // Headings whose next line is hidden show the fold ellipsis. | |
| 42 | let headings = Presentation.outline(document.tree).map(\.start).filter { start in | |
| 43 | let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0))) | |
| 44 | return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) } | |
| 45 | } | |
| 46 | folded.set(Set(headings).union(view.wrapperFolds)) | |
| 47 | hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden) | |
| 48 | return | |
| 49 | } | |
| 50 | folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds)) | |
| 51 | hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden) | |
| 52 | } | |
| 53 | ||
| 54 | /// `updateHidden`, laying out again only the text that changed between hidden and shown | |
| 55 | /// and the headings whose fold mark changed. Laying out the whole file again makes TextKit | |
| 56 | /// estimate the height of everything above the window afresh, which moves the text under it. | |
| 57 | private func updateHiddenAndLayout() { | |
| 58 | let oldHidden = hidden.all | |
| 59 | let oldFolded = folded.all | |
| 60 | updateHidden() | |
| 61 | invalidateLayout(from: oldHidden, to: hidden.all) | |
| 62 | invalidateLayout(lines: oldFolded.symmetricDifference(folded.all).map { $0..<$0 }) | |
| 63 | } | |
| 64 | ||
| 65 | /// Lays out again the ranges in `old` and not in `new`, and the other way round. | |
| 66 | func invalidateLayout(from old: [Range<Int>], to new: [Range<Int>]) { | |
| 67 | invalidateLayout(lines: Array(Set(old).symmetricDifference(new))) | |
| 68 | } | |
| 69 | ||
| 70 | /// Lays out `ranges` again, each widened to whole lines and to the line before it: the | |
| 71 | /// heading or opening line of a fold, whose fragment draws the fold mark. | |
| 72 | func invalidateLayout(lines ranges: [Range<Int>]) { | |
| 73 | guard !ranges.isEmpty, let content = textLayoutManager.textContentManager else { return } | |
| 74 | let text = textView.string as NSString | |
| 75 | for range in ranges { | |
| 76 | let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location | |
| 77 | let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0))) | |
| 78 | guard let start = content.location(content.documentRange.location, offsetBy: lower), | |
| 79 | let end = content.location(start, offsetBy: upper - lower), | |
| 80 | let textRange = NSTextRange(location: start, end: end) else { continue } | |
| 81 | textLayoutManager.invalidateLayout(for: textRange) | |
| 82 | } | |
| 83 | } | |
| 84 | ||
| 85 | /// Runs `change`, which lays the whole file out again, and brings the line that was at the | |
| 86 | /// top of the window back there. TextKit estimates the height of text it hasn't laid out, | |
| 87 | /// so the same scroll position lands on different text after a fresh layout. | |
| 88 | func keepingTopLine(_ change: () -> Void) { | |
| 89 | guard let scroll = textView.enclosingScrollView, let content = textLayoutManager.textContentManager else { return change() } | |
| 90 | let visible = scroll.documentVisibleRect | |
| 91 | let top = visible.minY - textView.textContainerOrigin.y | |
| 92 | let start = content.documentRange.location | |
| 93 | let anchor = textLayoutManager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map { | |
| 94 | (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY) | |
| 95 | } | |
| 96 | change() | |
| 97 | guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset), | |
| 98 | let above = NSTextRange(location: start, end: location) else { return } | |
| 99 | // Styled now, not in the background passes, which would lay the text out again. | |
| 100 | while styledUpTo < anchor.offset { styleNextChunk(Self.styleChunk) } | |
| 101 | textLayoutManager.ensureLayout(for: above) | |
| 102 | guard let fragment = textLayoutManager.textLayoutFragment(for: location) else { return } | |
| 103 | let frame = fragment.layoutFragmentFrame | |
| 104 | let y = frame.minY + textView.textContainerOrigin.y + max(0, min(anchor.within, frame.height)) | |
| 105 | textLayoutManager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * visible.height)) | |
| 106 | // The view grows to the laid-out height on its next layout pass; the scroll needs it now. | |
| 107 | let needed = textLayoutManager.usageBoundsForTextContainer.maxY + textView.textContainerOrigin.y + textView.textContainerInset.height | |
| 108 | if textView.frame.height < needed { textView.setFrameSize(NSSize(width: textView.frame.width, height: needed)) } | |
| 109 | textView.scroll(NSPoint(x: visible.minX, y: y)) | |
| 110 | scroll.reflectScrolledClipView(scroll.contentView) | |
| 111 | } | |
| 112 | ||
| 113 | // MARK: - Sparse trees | |
| 114 | ||
| 115 | ||
| 116 | func showSparseTree(_ points: [Int], highlights: [Range<Int>]) { | |
| 117 | let text = textView.string | |
| 118 | var state = foldState | |
| 119 | for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) { | |
| 120 | state.wrapperFolds.remove(start) | |
| 121 | } | |
| 122 | sparseHidden = nil | |
| 123 | setFolds(state) | |
| 124 | sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree) | |
| 125 | self.highlights = highlights | |
| 126 | keepingTopLine { | |
| 127 | updateHiddenAndLayout() | |
| 128 | restyleOutsideEditing(0..<utf16Length) | |
| 129 | } | |
| 130 | orgTextView?.redrawLineNumbers() | |
| 131 | textView.needsDisplay = true | |
| 132 | let caret = textView.selectedRange().location | |
| 133 | if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) } | |
| 134 | } | |
| 135 | ||
| 136 | /// Leaves a sparse tree for ordinary folds: headings with something shown below them | |
| 137 | /// open, the others folded. | |
| 138 | func leaveSparseTree() { | |
| 139 | guard let sparse = sparseHidden else { return } | |
| 140 | sparseHidden = nil | |
| 141 | let outline = Presentation.outline(document.tree) | |
| 142 | let ns = textView.string as NSString | |
| 143 | var open: Set<Int> = [] | |
| 144 | for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) { | |
| 145 | var parent = entry.parent | |
| 146 | while let p = parent { | |
| 147 | open.insert(outline[p].start) | |
| 148 | parent = outline[p].parent | |
| 149 | } | |
| 150 | let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0))) | |
| 151 | if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) } | |
| 152 | } | |
| 153 | var state = foldState | |
| 154 | state.folds = Set(outline.map(\.start)).subtracting(open) | |
| 155 | state.bodyFolds = [] | |
| 156 | setFolds(state) | |
| 157 | } | |
| 158 | ||
| 159 | func clearHighlights() { | |
| 160 | guard !highlights.isEmpty else { return } | |
| 161 | let old = highlights | |
| 162 | highlights = [] | |
| 163 | for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) } | |
| 164 | } | |
| 165 | ||
| 166 | func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) { | |
| 167 | for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length { | |
| 168 | storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range))) | |
| 169 | } | |
| 170 | } | |
| 171 | ||
| 172 | // MARK: - Narrowing | |
| 173 | ||
| 174 | ||
| 175 | func narrow(_ id: String) { | |
| 176 | let caret = textView.selectedRange().location | |
| 177 | do { | |
| 178 | switch id { | |
| 179 | case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string) | |
| 180 | // `org-toggle-narrow-to-subtree`. | |
| 181 | case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil | |
| 182 | case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string) | |
| 183 | default: narrowed = nil | |
| 184 | } | |
| 185 | } catch let failure as Narrowing.Failure { | |
| 186 | onMessage?(failure.message) | |
| 187 | return | |
| 188 | } catch { | |
| 189 | return | |
| 190 | } | |
| 191 | updateHiddenAndLayout() | |
| 192 | orgTextView?.redrawLineNumbers() | |
| 193 | textView.needsDisplay = true | |
| 194 | if let narrowed { | |
| 195 | setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound))) | |
| 196 | textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0)) | |
| 197 | } else { | |
| 198 | textView.scrollRangeToVisible(NSRange(location: caret, length: 0)) | |
| 199 | } | |
| 200 | } | |
| 201 | ||
| 202 | /// What narrowing hides: the text before the region, and the lines after it. | |
| 203 | private var narrowHidden: [Range<Int>] { | |
| 204 | guard let narrowed else { return [] } | |
| 205 | let length = utf16Length | |
| 206 | var ranges: [Range<Int>] = [] | |
| 207 | if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) } | |
| 208 | let ns = textView.string as NSString | |
| 209 | let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound | |
| 210 | if tail < length { ranges.append(tail..<length) } | |
| 211 | return ranges | |
| 212 | } | |
| 213 | } | |
| 214 | #endif | |
Sources/OrgEditorAppKit/OrgEditor+Images.swift added +74
| @@ -0,0 +1,74 @@ | ||
| 1 | #if os(macOS) | |
| 2 | import AppKit | |
| 3 | import OrgCore | |
| 4 | ||
| 5 | extension OrgEditor { | |
| 6 | // MARK: - Inline images | |
| 7 | ||
| 8 | private static let imageCache = NSCache<NSString, NSImage>() | |
| 9 | ||
| 10 | func toggleImages() { | |
| 11 | showsImages.toggle() | |
| 12 | refreshImages() | |
| 13 | if showsImages { | |
| 14 | let ns = textView.string as NSString | |
| 15 | var count = 0 | |
| 16 | var offset = 0 | |
| 17 | while offset < ns.length { | |
| 18 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) | |
| 19 | if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 } | |
| 20 | offset = NSMaxRange(line) | |
| 21 | } | |
| 22 | onMessage?("\(count) images displayed inline") | |
| 23 | } else { | |
| 24 | onMessage?("Inline image display turned off") | |
| 25 | } | |
| 26 | } | |
| 27 | ||
| 28 | func refreshImages() { | |
| 29 | keepingTopLine { | |
| 30 | restyleOutsideEditing(0..<utf16Length) | |
| 31 | textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) | |
| 32 | } | |
| 33 | textView.needsDisplay = true | |
| 34 | } | |
| 35 | ||
| 36 | private func loadImage(_ path: String) -> NSImage? { | |
| 37 | let expanded = (path as NSString).expandingTildeInPath | |
| 38 | let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded) | |
| 39 | let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0 | |
| 40 | let key = "\(url.path)|\(modified)" as NSString | |
| 41 | if let cached = Self.imageCache.object(forKey: key) { return cached } | |
| 42 | guard let image = NSImage(contentsOf: url) else { return nil } | |
| 43 | Self.imageCache.setObject(image, forKey: key) | |
| 44 | return image | |
| 45 | } | |
| 46 | ||
| 47 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is | |
| 48 | /// on the line. | |
| 49 | func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { | |
| 50 | guard showsImages, isOrg else { return } | |
| 51 | let text = storage.string as NSString | |
| 52 | let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40) | |
| 53 | var location = range.lowerBound | |
| 54 | while location < range.upperBound, location < text.length { | |
| 55 | let line = text.lineRange(for: NSRange(location: location, length: 0)) | |
| 56 | location = NSMaxRange(line) | |
| 57 | guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue } | |
| 58 | var width = image.width.map(CGFloat.init) ?? picture.size.width | |
| 59 | width = min(width, maxWidth) | |
| 60 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 | |
| 61 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) | |
| 62 | // Invisible, keeping the line's height, so line numbers stay apart. | |
| 63 | if line.location != revealed.location, content.length > 0 { | |
| 64 | storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content) | |
| 65 | } | |
| 66 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length))) | |
| 67 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() | |
| 68 | // The image sits where the line is; the spacing makes room for the rest of it. | |
| 69 | style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height) | |
| 70 | storage.addAttribute(.paragraphStyle, value: style, range: line) | |
| 71 | } | |
| 72 | } | |
| 73 | } | |
| 74 | #endif | |
Sources/OrgEditorAppKit/OrgEditor+Shrink.swift added +155
| @@ -0,0 +1,155 @@ | ||
| 1 | #if os(macOS) | |
| 2 | import AppKit | |
| 3 | import OrgCore | |
| 4 | import OrgDocument | |
| 5 | import OrgPresentation | |
| 6 | ||
| 7 | extension OrgEditor { | |
| 8 | // MARK: - Shrunk table columns | |
| 9 | ||
| 10 | ||
| 11 | /// Narrows `columns` of `table` and widens its others. | |
| 12 | private func setShrunk(_ columns: [Int], in table: Range<Int>) { | |
| 13 | shrunk.set(columns, in: table, text: textView.string) | |
| 14 | restyleOutsideEditing(table) | |
| 15 | invalidateLayout(lines: [table]) | |
| 16 | textView.needsDisplay = true | |
| 17 | } | |
| 18 | ||
| 19 | /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`, | |
| 20 | /// `expand` for `org-table-expand`. | |
| 21 | func tableColumnWidth(_ id: String) { | |
| 22 | switch shrunk.change(for: id, at: textView.selectedRange().location, in: textView.string) { | |
| 23 | case .notInTable: onMessage?("Not in a table") | |
| 24 | case .set(let columns, let table): setShrunk(columns, in: table) | |
| 25 | case .ask(let table, let current, let max): | |
| 26 | onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in | |
| 27 | guard let self, let answer else { return } | |
| 28 | self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table) | |
| 29 | } | |
| 30 | } | |
| 31 | } | |
| 32 | ||
| 33 | /// Hides each shrunk segment's text and draws its display where the text was. | |
| 34 | func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) { | |
| 35 | guard !shrunk.isEmpty else { return } | |
| 36 | let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width | |
| 37 | for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length { | |
| 38 | let r = segment.range | |
| 39 | let shown = segment.display.count | |
| 40 | let kept = min(shown, r.count) | |
| 41 | if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) } | |
| 42 | guard kept > 0 else { continue } | |
| 43 | let visible = NSRange(location: r.upperBound - kept, length: kept) | |
| 44 | storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible) | |
| 45 | storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1)) | |
| 46 | if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) } | |
| 47 | } | |
| 48 | } | |
| 49 | ||
| 50 | /// Moves drawer and block folds through `edit`, checking again only those near it. | |
| 51 | func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) { | |
| 52 | guard !wrapperHidden.isEmpty else { return } | |
| 53 | var mapped: [Int: Range<Int>] = [:] | |
| 54 | let entries = Array(wrapperHidden) | |
| 55 | // One pass maps every start and range. | |
| 56 | let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection | |
| 57 | for i in entries.indices { | |
| 58 | let newStart = moved[2 * i].lowerBound | |
| 59 | let newRange = moved[2 * i + 1] | |
| 60 | if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound { | |
| 61 | if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden } | |
| 62 | } else { | |
| 63 | mapped[newStart] = newRange | |
| 64 | } | |
| 65 | } | |
| 66 | wrapperHidden = mapped | |
| 67 | view.wrapperFolds = Set(mapped.keys) | |
| 68 | } | |
| 69 | ||
| 70 | /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading, | |
| 71 | /// cycles folded, children, subtree. Returns false elsewhere. | |
| 72 | @discardableResult | |
| 73 | public func cycleAtCaret() -> Bool { | |
| 74 | leaveSparseTree() | |
| 75 | let caret = textView.selectedRange().location | |
| 76 | guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false } | |
| 77 | setFolds(state) | |
| 78 | // Off a closing line that folding hid, to the opening line, as org does. | |
| 79 | if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) } | |
| 80 | return true | |
| 81 | } | |
| 82 | ||
| 83 | /// Doom's `za`, `zo` (on a heading line) and `zc` (anywhere in a subtree). | |
| 84 | func fold(_ id: String) { | |
| 85 | leaveSparseTree() | |
| 86 | let caret = textView.selectedRange().location | |
| 87 | let tree = document.tree | |
| 88 | let next: FoldState? | |
| 89 | if id == "org.fold.close" { | |
| 90 | next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == utf16Length) } | |
| 91 | .map { Presentation.hideSubtree($0.start, foldState) } | |
| 92 | } else { | |
| 93 | next = Presentation.heading(containing: caret, in: tree).map { | |
| 94 | id == "org.fold.open" ? Presentation.openFold($0, in: tree, foldState) : Presentation.toggleFold($0, in: tree, foldState) | |
| 95 | } | |
| 96 | } | |
| 97 | if let next, next != foldState { setFolds(next) } | |
| 98 | } | |
| 99 | ||
| 100 | /// Shift-TAB: overview, contents, show all. | |
| 101 | public func cycleGlobal() { | |
| 102 | leaveSparseTree() | |
| 103 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds) | |
| 104 | globalVisibility = visibility | |
| 105 | setFolds(state) | |
| 106 | } | |
| 107 | ||
| 108 | /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it. | |
| 109 | public func reveal(_ offset: Int) { | |
| 110 | let target = max(0, min(offset, utf16Length)) | |
| 111 | if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") } | |
| 112 | unfold(around: target) | |
| 113 | setCaret(target) | |
| 114 | textView.scrollRangeToVisible(NSRange(location: target, length: 0)) | |
| 115 | } | |
| 116 | ||
| 117 | /// Unfolds the headings whose folds hide `offset`, leaving the selection alone. | |
| 118 | func unfold(around offset: Int) { | |
| 119 | leaveSparseTree() | |
| 120 | var state = foldState | |
| 121 | for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end { | |
| 122 | state.folds.remove(entry.start) | |
| 123 | state.bodyFolds.remove(entry.start) | |
| 124 | } | |
| 125 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true { | |
| 126 | state.wrapperFolds.remove(start) | |
| 127 | } | |
| 128 | guard state != foldState else { return } | |
| 129 | setFolds(state) | |
| 130 | } | |
| 131 | ||
| 132 | /// Applies edits through the text view as one undo step, not merged with typing around it. | |
| 133 | func applyEdits(_ edits: [TextEdit]) { | |
| 134 | guard !edits.isEmpty, let storage = textView.textStorage else { return } | |
| 135 | textView.breakUndoCoalescing() | |
| 136 | textView.undoManager?.beginUndoGrouping() | |
| 137 | // By lines, so a fold between two changes stays. | |
| 138 | let text = storage.string | |
| 139 | for edit in edits.flatMap({ splitByLines($0, in: text) }).sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { | |
| 140 | let range = NSRange(edit.range) | |
| 141 | guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue } | |
| 142 | storage.replaceCharacters(in: range, with: edit.replacement) | |
| 143 | textView.didChangeText() | |
| 144 | } | |
| 145 | textView.undoManager?.endUndoGrouping() | |
| 146 | textView.breakUndoCoalescing() | |
| 147 | } | |
| 148 | ||
| 149 | func setCaret(_ offset: Int) { | |
| 150 | let clamped = max(0, min(offset, utf16Length)) | |
| 151 | previousSelection = clamped | |
| 152 | textView.setSelectedRange(NSRange(location: clamped, length: 0)) | |
| 153 | } | |
| 154 | } | |
| 155 | #endif | |
Sources/OrgEditorAppKit/OrgEditor+Styling.swift added +153
| @@ -0,0 +1,153 @@ | ||
| 1 | #if os(macOS) | |
| 2 | import AppKit | |
| 3 | import OrgCore | |
| 4 | import OrgPresentation | |
| 5 | ||
| 6 | extension OrgEditor { | |
| 7 | // MARK: - Styling | |
| 8 | ||
| 9 | func restyleOutsideEditing(_ range: Range<Int>) { | |
| 10 | guard let storage = textView.textStorage else { return } | |
| 11 | storage.beginEditing() | |
| 12 | restyle(range, in: storage) | |
| 13 | storage.endEditing() | |
| 14 | } | |
| 15 | ||
| 16 | /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where | |
| 17 | /// attribute changes are allowed and characters must not change. | |
| 18 | func restyle(_ range: Range<Int>, in storage: NSTextStorage) { | |
| 19 | guard !range.isEmpty else { return } | |
| 20 | let whole = NSRange(range) | |
| 21 | storage.setAttributes(theme.base, range: whole) | |
| 22 | guard isOrg else { | |
| 23 | for run in plainRuns() where run.range.overlaps(range) { | |
| 24 | guard let clipped = clip(run.range, to: range) else { continue } | |
| 25 | theme.apply(.syntax(run.category), to: storage, range: clipped) | |
| 26 | } | |
| 27 | return | |
| 28 | } | |
| 29 | if indented { | |
| 30 | for line in Presentation.lineIndents(document.tree, in: range) { | |
| 31 | storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) | |
| 32 | } | |
| 33 | } | |
| 34 | let revealed = caretLine | |
| 35 | var scriptExclusions: [Range<Int>] = [] | |
| 36 | for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) { | |
| 37 | guard let clipped = clip(run.range, to: range) else { continue } | |
| 38 | if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue } | |
| 39 | if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 { | |
| 40 | storage.addAttributes(theme.hidden, range: clipped) | |
| 41 | } else { | |
| 42 | theme.apply(run.role, to: storage, range: clipped) | |
| 43 | } | |
| 44 | if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } | |
| 45 | } | |
| 46 | if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) } | |
| 47 | applyShrunk(range, in: storage) | |
| 48 | applyHighlights(range, in: storage) | |
| 49 | applyImages(range, in: storage, revealed: revealed) | |
| 50 | } | |
| 51 | ||
| 52 | /// `org-pretty-entities`: entities drawn as their character over the entity's last | |
| 53 | /// character (the rest hidden), sub/superscripts raised without their markers. | |
| 54 | private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) { | |
| 55 | let runs = Presentation.prettyRuns( | |
| 56 | storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil }, | |
| 57 | scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces | |
| 58 | ) | |
| 59 | for (lineStart, run) in runs { | |
| 60 | switch run { | |
| 61 | case .entity(let r, let display): | |
| 62 | let start = lineStart + r.lowerBound | |
| 63 | let last = lineStart + r.upperBound - 1 | |
| 64 | if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) } | |
| 65 | storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1)) | |
| 66 | case .script(let markers, let body, let superscript): | |
| 67 | for marker in markers { | |
| 68 | storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count)) | |
| 69 | } | |
| 70 | let size = theme.font.pointSize | |
| 71 | storage.addAttributes([ | |
| 72 | .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular), | |
| 73 | .baselineOffset: (superscript ? 0.3 : -0.3) * size, | |
| 74 | ], range: NSRange(location: lineStart + body.lowerBound, length: body.count)) | |
| 75 | } | |
| 76 | } | |
| 77 | } | |
| 78 | ||
| 79 | /// Moving to another line shows its markup and hides the last one's. | |
| 80 | func revealCaretLine() { | |
| 81 | guard !showMarkup, isOrg else { return } | |
| 82 | let line = caretLine | |
| 83 | guard line != revealedLine else { return } | |
| 84 | let text = textView.string as NSString | |
| 85 | // The old line may have moved with edits since; restyle the line now at its start. | |
| 86 | let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil } | |
| 87 | revealedLine = line | |
| 88 | for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo { | |
| 89 | restyleOutsideEditing(range.location..<NSMaxRange(range)) | |
| 90 | } | |
| 91 | } | |
| 92 | ||
| 93 | /// Code highlights for the whole file in plain mode. | |
| 94 | private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] { | |
| 95 | guard case .plain(let language?) = mode, let highlighter else { return [] } | |
| 96 | if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs } | |
| 97 | let runs = highlighter.highlights(language: language, code: document.text) | |
| 98 | codeRuns = (document.revision, runs) | |
| 99 | return runs | |
| 100 | } | |
| 101 | ||
| 102 | private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle { | |
| 103 | let key = IndentKey(firstLine: firstLine, wrapped: wrapped) | |
| 104 | if let style = paragraphStyles[key] { return style } | |
| 105 | let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped) | |
| 106 | paragraphStyles[key] = style | |
| 107 | return style | |
| 108 | } | |
| 109 | ||
| 110 | private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? { | |
| 111 | let clipped = run.clamped(to: range) | |
| 112 | return clipped.isEmpty ? nil : NSRange(clipped) | |
| 113 | } | |
| 114 | ||
| 115 | /// The region an edit affects in one version of the tree: inside the innermost section | |
| 116 | /// holding the edited lines (plus the line after), every element that overlaps them or the | |
| 117 | /// line on either side. A changed heading line, or an added or removed heading, widens it | |
| 118 | /// to that section's whole own body. Run on the old and the new tree, the union covers | |
| 119 | /// elements that grew and elements that shrank. | |
| 120 | static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> { | |
| 121 | let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start)) | |
| 122 | let lineRange = lines.location..<(lines.location + lines.length) | |
| 123 | let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1) | |
| 124 | var container = tree.root | |
| 125 | while let child = container.child(containing: lineRange.lowerBound), | |
| 126 | child.kind == .section || child.kind == .zerothSection, | |
| 127 | lineRange.upperBound <= child.range.upperBound { | |
| 128 | container = child | |
| 129 | } | |
| 130 | var lower = lineRange.lowerBound | |
| 131 | var upper = lineRange.upperBound | |
| 132 | // Tables and lists carry no styling of their own, so inside them only the rows or | |
| 133 | // items around the edit change, however large they are. | |
| 134 | func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] { | |
| 135 | nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in | |
| 136 | guard [.table, .plainList, .item].contains(node.kind) else { return [node] } | |
| 137 | let inner = overlapping(node.children(overlapping: around)) | |
| 138 | return inner.isEmpty ? [node] : inner | |
| 139 | } | |
| 140 | } | |
| 141 | for child in overlapping(container.children(overlapping: around)) { | |
| 142 | lower = min(lower, child.range.lowerBound) | |
| 143 | upper = max(upper, child.range.upperBound) | |
| 144 | } | |
| 145 | let heading = container.firstChild(.heading) | |
| 146 | if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true { | |
| 147 | lower = min(lower, container.range.lowerBound) | |
| 148 | upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound) | |
| 149 | } | |
| 150 | return lower..<min(upper, text.length) | |
| 151 | } | |
| 152 | } | |
| 153 | #endif | |
Sources/OrgEditorAppKit/OrgEditor.swift +17 −752
| @@ -4,53 +4,13 @@ import OrgCore | ||
| 4 | 4 | import OrgDocument |
| 5 | 5 | import OrgPresentation |
| 6 | 6 | |
| 7 | /// Hidden ranges, read by TextKit's enumeration callbacks, which may run off the main thread. | |
| 8 | final class HiddenRanges: @unchecked Sendable { | |
| 9 | private let lock = NSLock() | |
| 10 | private var ranges: [Range<Int>] = [] | |
| 11 | ||
| 12 | func set(_ new: [Range<Int>]) { | |
| 13 | lock.withLock { ranges = new } | |
| 14 | } | |
| 15 | ||
| 16 | var all: [Range<Int>] { | |
| 17 | lock.withLock { ranges } | |
| 18 | } | |
| 19 | ||
| 20 | func covers(_ start: Int, _ end: Int) -> Bool { | |
| 21 | lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } } | |
| 22 | } | |
| 23 | ||
| 24 | func containing(_ offset: Int) -> Range<Int>? { | |
| 25 | lock.withLock { ranges.first { $0.lowerBound <= offset && offset < $0.upperBound } } | |
| 26 | } | |
| 27 | } | |
| 28 | ||
| 29 | /// Folded heading starts, read by the layout-fragment callback. | |
| 30 | final class FoldedHeadings: @unchecked Sendable { | |
| 31 | private let lock = NSLock() | |
| 32 | private var starts: Set<Int> = [] | |
| 33 | ||
| 34 | func set(_ new: Set<Int>) { | |
| 35 | lock.withLock { starts = new } | |
| 36 | } | |
| 37 | ||
| 38 | func contains(_ offset: Int) -> Bool { | |
| 39 | lock.withLock { starts.contains(offset) } | |
| 40 | } | |
| 41 | ||
| 42 | var all: Set<Int> { | |
| 43 | lock.withLock { starts } | |
| 44 | } | |
| 45 | } | |
| 46 | ||
| 47 | 7 | /// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every |
| 48 | 8 | /// character edit goes through `DocumentState.apply`, and only the affected region is restyled. |
| 49 | 9 | @MainActor |
| 50 | 10 | public final class OrgEditor: NSObject { |
| 51 | 11 | public let textView: NSTextView |
| 52 | 12 | public private(set) var document: DocumentState |
| 53 | public private(set) var view = ViewState() | |
| 13 | public internal(set) var view = ViewState() | |
| 54 | 14 | /// Called with the time from a character edit to restyled text. |
| 55 | 15 | public var onEditTiming: ((Duration) -> Void)? |
| 56 | 16 | |
| @@ -74,7 +34,7 @@ public final class OrgEditor: NSObject { | ||
| 74 | 34 | } |
| 75 | 35 | } |
| 76 | 36 | private var isLoading = false |
| 77 | private var previousSelection = 0 | |
| 37 | var previousSelection = 0 | |
| 78 | 38 | /// The selection shaded block lines last drew. |
| 79 | 39 | private var previousSelectionRange = NSRange(location: 0, length: 0) |
| 80 | 40 | /// Text before this offset is styled; after it, only base attributes until the background |
| @@ -82,9 +42,9 @@ public final class OrgEditor: NSObject { | ||
| 82 | 42 | private(set) var styledUpTo = 0 |
| 83 | 43 | private var stylingScheduled = false |
| 84 | 44 | /// One paragraph style object per indent pair, shared by every line that uses it. |
| 85 | private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:] | |
| 45 | var paragraphStyles: [IndentKey: NSParagraphStyle] = [:] | |
| 86 | 46 | |
| 87 | private struct IndentKey: Hashable { | |
| 47 | struct IndentKey: Hashable { | |
| 88 | 48 | let firstLine: Int |
| 89 | 49 | let wrapped: Int |
| 90 | 50 | } |
| @@ -115,7 +75,7 @@ public final class OrgEditor: NSObject { | ||
| 115 | 75 | /// The spell checker's skipped ranges and the text they were found in. |
| 116 | 76 | var spellSkipCache: (text: String, ranges: [Range<Int>])? |
| 117 | 77 | /// Highlights of the whole file in plain mode, and the revision they were made for. |
| 118 | private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])? | |
| 78 | var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])? | |
| 119 | 79 | |
| 120 | 80 | public init( |
| 121 | 81 | document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true, |
| @@ -212,7 +172,7 @@ public final class OrgEditor: NSObject { | ||
| 212 | 172 | // MARK: - Initial styling |
| 213 | 173 | |
| 214 | 174 | /// Styles whole lines from the watermark onward, about `size` units. |
| 215 | private func styleNextChunk(_ size: Int) { | |
| 175 | func styleNextChunk(_ size: Int) { | |
| 216 | 176 | let text = textView.textStorage!.string as NSString |
| 217 | 177 | guard styledUpTo < text.length else { return } |
| 218 | 178 | let target = min(text.length, styledUpTo + size) |
| @@ -247,7 +207,7 @@ public final class OrgEditor: NSObject { | ||
| 247 | 207 | scheduleStyling() |
| 248 | 208 | } |
| 249 | 209 | |
| 250 | private var caretLine: NSRange { | |
| 210 | var caretLine: NSRange { | |
| 251 | 211 | let text = textView.string as NSString |
| 252 | 212 | return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0)) |
| 253 | 213 | } |
| @@ -345,7 +305,7 @@ public final class OrgEditor: NSObject { | ||
| 345 | 305 | var orgTextView: OrgTextView? { textView as? OrgTextView } |
| 346 | 306 | |
| 347 | 307 | /// The line last revealed while markup is hidden, to hide again when the caret leaves. |
| 348 | private var revealedLine: NSRange? | |
| 308 | var revealedLine: NSRange? | |
| 349 | 309 | var dispatcher: KeyDispatcher |
| 350 | 310 | /// Evil-style editing, for modal keymaps such as Doom's. |
| 351 | 311 | public var modal = false { |
| @@ -578,600 +538,47 @@ public final class OrgEditor: NSObject { | ||
| 578 | 538 | |
| 579 | 539 | // MARK: - Folding |
| 580 | 540 | |
| 581 | public var foldState: FoldState { | |
| 582 | FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds) | |
| 583 | } | |
| 584 | ||
| 585 | private var globalVisibility: GlobalVisibility? | |
| 586 | ||
| 587 | public func setFolds(_ state: FoldState) { | |
| 588 | setFolds(state, wrappers: nil) | |
| 589 | } | |
| 590 | ||
| 591 | /// `wrappers`, when given, holds every folded drawer and block. | |
| 592 | private func setFolds(_ state: FoldState, wrappers: [Wrapper]?) { | |
| 593 | sparseHidden = nil | |
| 594 | view.folds = state.folds | |
| 595 | view.bodyFolds = state.bodyFolds | |
| 596 | view = view.pruned(to: document.tree, wrappers: false) | |
| 597 | // Found one by one, or all at once when there are many. | |
| 598 | let found = wrappers ?? (state.wrapperFolds.count > 32 | |
| 599 | ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) } | |
| 600 | : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) }) | |
| 601 | wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a } | |
| 602 | view.wrapperFolds = Set(wrapperHidden.keys) | |
| 603 | updateHiddenAndLayout() | |
| 604 | orgTextView?.redrawLineNumbers() | |
| 605 | textView.needsDisplay = true | |
| 606 | let caret = textView.selectedRange().location | |
| 607 | if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) } | |
| 608 | } | |
| 609 | ||
| 541 | var globalVisibility: GlobalVisibility? | |
| 610 | 542 | /// What each folded drawer and block hides, by opening-line start; kept in step with |
| 611 | 543 | /// `view.wrapperFolds` and mapped through edits. |
| 612 | private var wrapperHidden: [Int: Range<Int>] = [:] | |
| 613 | ||
| 614 | private func updateHidden() { | |
| 615 | if let sparseHidden { | |
| 616 | let ns = textView.string as NSString | |
| 617 | // Headings whose next line is hidden show the fold ellipsis. | |
| 618 | let headings = Presentation.outline(document.tree).map(\.start).filter { start in | |
| 619 | let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0))) | |
| 620 | return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) } | |
| 621 | } | |
| 622 | folded.set(Set(headings).union(view.wrapperFolds)) | |
| 623 | hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden) | |
| 624 | return | |
| 625 | } | |
| 626 | folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds)) | |
| 627 | hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden) | |
| 628 | } | |
| 629 | ||
| 630 | /// `updateHidden`, laying out again only the text that changed between hidden and shown | |
| 631 | /// and the headings whose fold mark changed. Laying out the whole file again makes TextKit | |
| 632 | /// estimate the height of everything above the window afresh, which moves the text under it. | |
| 633 | private func updateHiddenAndLayout() { | |
| 634 | let oldHidden = hidden.all | |
| 635 | let oldFolded = folded.all | |
| 636 | updateHidden() | |
| 637 | invalidateLayout(from: oldHidden, to: hidden.all) | |
| 638 | invalidateLayout(lines: oldFolded.symmetricDifference(folded.all).map { $0..<$0 }) | |
| 639 | } | |
| 640 | ||
| 641 | /// Lays out again the ranges in `old` and not in `new`, and the other way round. | |
| 642 | private func invalidateLayout(from old: [Range<Int>], to new: [Range<Int>]) { | |
| 643 | invalidateLayout(lines: Array(Set(old).symmetricDifference(new))) | |
| 644 | } | |
| 645 | ||
| 646 | /// Lays out `ranges` again, each widened to whole lines and to the line before it: the | |
| 647 | /// heading or opening line of a fold, whose fragment draws the fold mark. | |
| 648 | private func invalidateLayout(lines ranges: [Range<Int>]) { | |
| 649 | guard !ranges.isEmpty, let content = textLayoutManager.textContentManager else { return } | |
| 650 | let text = textView.string as NSString | |
| 651 | for range in ranges { | |
| 652 | let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location | |
| 653 | let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0))) | |
| 654 | guard let start = content.location(content.documentRange.location, offsetBy: lower), | |
| 655 | let end = content.location(start, offsetBy: upper - lower), | |
| 656 | let textRange = NSTextRange(location: start, end: end) else { continue } | |
| 657 | textLayoutManager.invalidateLayout(for: textRange) | |
| 658 | } | |
| 659 | } | |
| 660 | ||
| 661 | /// Runs `change`, which lays the whole file out again, and brings the line that was at the | |
| 662 | /// top of the window back there. TextKit estimates the height of text it hasn't laid out, | |
| 663 | /// so the same scroll position lands on different text after a fresh layout. | |
| 664 | func keepingTopLine(_ change: () -> Void) { | |
| 665 | guard let scroll = textView.enclosingScrollView, let content = textLayoutManager.textContentManager else { return change() } | |
| 666 | let visible = scroll.documentVisibleRect | |
| 667 | let top = visible.minY - textView.textContainerOrigin.y | |
| 668 | let start = content.documentRange.location | |
| 669 | let anchor = textLayoutManager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map { | |
| 670 | (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY) | |
| 671 | } | |
| 672 | change() | |
| 673 | guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset), | |
| 674 | let above = NSTextRange(location: start, end: location) else { return } | |
| 675 | // Styled now, not in the background passes, which would lay the text out again. | |
| 676 | while styledUpTo < anchor.offset { styleNextChunk(Self.styleChunk) } | |
| 677 | textLayoutManager.ensureLayout(for: above) | |
| 678 | guard let fragment = textLayoutManager.textLayoutFragment(for: location) else { return } | |
| 679 | let frame = fragment.layoutFragmentFrame | |
| 680 | let y = frame.minY + textView.textContainerOrigin.y + max(0, min(anchor.within, frame.height)) | |
| 681 | textLayoutManager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * visible.height)) | |
| 682 | // The view grows to the laid-out height on its next layout pass; the scroll needs it now. | |
| 683 | let needed = textLayoutManager.usageBoundsForTextContainer.maxY + textView.textContainerOrigin.y + textView.textContainerInset.height | |
| 684 | if textView.frame.height < needed { textView.setFrameSize(NSSize(width: textView.frame.width, height: needed)) } | |
| 685 | textView.scroll(NSPoint(x: visible.minX, y: y)) | |
| 686 | scroll.reflectScrolledClipView(scroll.contentView) | |
| 687 | } | |
| 544 | var wrapperHidden: [Int: Range<Int>] = [:] | |
| 688 | 545 | |
| 689 | 546 | // MARK: - Sparse trees |
| 690 | 547 | |
| 691 | 548 | /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next |
| 692 | 549 | /// fold change. Mapped through edits. |
| 693 | private var sparseHidden: [Range<Int>]? | |
| 550 | var sparseHidden: [Range<Int>]? | |
| 694 | 551 | /// Sparse tree matches, highlighted until the next edit or C-c C-c. |
| 695 | private var highlights: [Range<Int>] = [] | |
| 696 | ||
| 697 | private func showSparseTree(_ points: [Int], highlights: [Range<Int>]) { | |
| 698 | let text = textView.string | |
| 699 | var state = foldState | |
| 700 | for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) { | |
| 701 | state.wrapperFolds.remove(start) | |
| 702 | } | |
| 703 | sparseHidden = nil | |
| 704 | setFolds(state) | |
| 705 | sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree) | |
| 706 | self.highlights = highlights | |
| 707 | keepingTopLine { | |
| 708 | updateHiddenAndLayout() | |
| 709 | restyleOutsideEditing(0..<utf16Length) | |
| 710 | } | |
| 711 | orgTextView?.redrawLineNumbers() | |
| 712 | textView.needsDisplay = true | |
| 713 | let caret = textView.selectedRange().location | |
| 714 | if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) } | |
| 715 | } | |
| 716 | ||
| 717 | /// Leaves a sparse tree for ordinary folds: headings with something shown below them | |
| 718 | /// open, the others folded. | |
| 719 | private func leaveSparseTree() { | |
| 720 | guard let sparse = sparseHidden else { return } | |
| 721 | sparseHidden = nil | |
| 722 | let outline = Presentation.outline(document.tree) | |
| 723 | let ns = textView.string as NSString | |
| 724 | var open: Set<Int> = [] | |
| 725 | for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) { | |
| 726 | var parent = entry.parent | |
| 727 | while let p = parent { | |
| 728 | open.insert(outline[p].start) | |
| 729 | parent = outline[p].parent | |
| 730 | } | |
| 731 | let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0))) | |
| 732 | if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) } | |
| 733 | } | |
| 734 | var state = foldState | |
| 735 | state.folds = Set(outline.map(\.start)).subtracting(open) | |
| 736 | state.bodyFolds = [] | |
| 737 | setFolds(state) | |
| 738 | } | |
| 739 | ||
| 740 | private func clearHighlights() { | |
| 741 | guard !highlights.isEmpty else { return } | |
| 742 | let old = highlights | |
| 743 | highlights = [] | |
| 744 | for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) } | |
| 745 | } | |
| 746 | ||
| 747 | private func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) { | |
| 748 | for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length { | |
| 749 | storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range))) | |
| 750 | } | |
| 751 | } | |
| 552 | var highlights: [Range<Int>] = [] | |
| 752 | 553 | |
| 753 | 554 | // MARK: - STARTUP display |
| 754 | 555 | |
| 755 | 556 | /// `org-indent-mode`: headings' bodies indented under their titles (`#+STARTUP: indent`). |
| 756 | private var indented = true | |
| 557 | var indented = true | |
| 757 | 558 | /// `org-hide-leading-stars` (`#+STARTUP: hidestars`); org-indent hides them as well. |
| 758 | private var hideStars = false | |
| 559 | var hideStars = false | |
| 759 | 560 | |
| 760 | 561 | // MARK: - Inline images |
| 761 | 562 | |
| 762 | 563 | /// `org-toggle-inline-images`: lines that are only an image link show the image. |
| 763 | public private(set) var showsImages = false | |
| 564 | public internal(set) var showsImages = false | |
| 764 | 565 | /// The file's folder, for relative image paths. |
| 765 | 566 | public var baseDirectory: URL? { |
| 766 | 567 | didSet { if showsImages, oldValue != baseDirectory { refreshImages() } } |
| 767 | 568 | } |
| 768 | private static let imageCache = NSCache<NSString, NSImage>() | |
| 769 | ||
| 770 | private func toggleImages() { | |
| 771 | showsImages.toggle() | |
| 772 | refreshImages() | |
| 773 | if showsImages { | |
| 774 | let ns = textView.string as NSString | |
| 775 | var count = 0 | |
| 776 | var offset = 0 | |
| 777 | while offset < ns.length { | |
| 778 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) | |
| 779 | if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 } | |
| 780 | offset = NSMaxRange(line) | |
| 781 | } | |
| 782 | onMessage?("\(count) images displayed inline") | |
| 783 | } else { | |
| 784 | onMessage?("Inline image display turned off") | |
| 785 | } | |
| 786 | } | |
| 787 | ||
| 788 | private func refreshImages() { | |
| 789 | keepingTopLine { | |
| 790 | restyleOutsideEditing(0..<utf16Length) | |
| 791 | textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) | |
| 792 | } | |
| 793 | textView.needsDisplay = true | |
| 794 | } | |
| 795 | ||
| 796 | private func loadImage(_ path: String) -> NSImage? { | |
| 797 | let expanded = (path as NSString).expandingTildeInPath | |
| 798 | let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded) | |
| 799 | let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0 | |
| 800 | let key = "\(url.path)|\(modified)" as NSString | |
| 801 | if let cached = Self.imageCache.object(forKey: key) { return cached } | |
| 802 | guard let image = NSImage(contentsOf: url) else { return nil } | |
| 803 | Self.imageCache.setObject(image, forKey: key) | |
| 804 | return image | |
| 805 | } | |
| 806 | ||
| 807 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is | |
| 808 | /// on the line. | |
| 809 | private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { | |
| 810 | guard showsImages, isOrg else { return } | |
| 811 | let text = storage.string as NSString | |
| 812 | let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40) | |
| 813 | var location = range.lowerBound | |
| 814 | while location < range.upperBound, location < text.length { | |
| 815 | let line = text.lineRange(for: NSRange(location: location, length: 0)) | |
| 816 | location = NSMaxRange(line) | |
| 817 | guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue } | |
| 818 | var width = image.width.map(CGFloat.init) ?? picture.size.width | |
| 819 | width = min(width, maxWidth) | |
| 820 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 | |
| 821 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) | |
| 822 | // Invisible, keeping the line's height, so line numbers stay apart. | |
| 823 | if line.location != revealed.location, content.length > 0 { | |
| 824 | storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content) | |
| 825 | } | |
| 826 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length))) | |
| 827 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() | |
| 828 | // The image sits where the line is; the spacing makes room for the rest of it. | |
| 829 | style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height) | |
| 830 | storage.addAttribute(.paragraphStyle, value: style, range: line) | |
| 831 | } | |
| 832 | } | |
| 833 | 569 | |
| 834 | 570 | // MARK: - Narrowing |
| 835 | 571 | |
| 836 | 572 | /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the |
| 837 | 573 | /// rest is hidden until `widen`. Mapped through edits. |
| 838 | public private(set) var narrowed: Range<Int>? | |
| 839 | ||
| 840 | private func narrow(_ id: String) { | |
| 841 | let caret = textView.selectedRange().location | |
| 842 | do { | |
| 843 | switch id { | |
| 844 | case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string) | |
| 845 | // `org-toggle-narrow-to-subtree`. | |
| 846 | case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil | |
| 847 | case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string) | |
| 848 | default: narrowed = nil | |
| 849 | } | |
| 850 | } catch let failure as Narrowing.Failure { | |
| 851 | onMessage?(failure.message) | |
| 852 | return | |
| 853 | } catch { | |
| 854 | return | |
| 855 | } | |
| 856 | updateHiddenAndLayout() | |
| 857 | orgTextView?.redrawLineNumbers() | |
| 858 | textView.needsDisplay = true | |
| 859 | if let narrowed { | |
| 860 | setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound))) | |
| 861 | textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0)) | |
| 862 | } else { | |
| 863 | textView.scrollRangeToVisible(NSRange(location: caret, length: 0)) | |
| 864 | } | |
| 865 | } | |
| 866 | ||
| 867 | /// What narrowing hides: the text before the region, and the lines after it. | |
| 868 | private var narrowHidden: [Range<Int>] { | |
| 869 | guard let narrowed else { return [] } | |
| 870 | let length = utf16Length | |
| 871 | var ranges: [Range<Int>] = [] | |
| 872 | if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) } | |
| 873 | let ns = textView.string as NSString | |
| 874 | let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound | |
| 875 | if tail < length { ranges.append(tail..<length) } | |
| 876 | return ranges | |
| 877 | } | |
| 574 | public internal(set) var narrowed: Range<Int>? | |
| 878 | 575 | |
| 879 | 576 | // MARK: - Shrunk table columns |
| 880 | 577 | |
| 881 | 578 | /// Narrowed table columns (`org-table-shrink`). |
| 882 | private var shrunk = ShrunkColumns() | |
| 579 | var shrunk = ShrunkColumns() | |
| 883 | 580 | private var commandEditing = false |
| 884 | 581 | |
| 885 | /// Narrows `columns` of `table` and widens its others. | |
| 886 | private func setShrunk(_ columns: [Int], in table: Range<Int>) { | |
| 887 | shrunk.set(columns, in: table, text: textView.string) | |
| 888 | restyleOutsideEditing(table) | |
| 889 | invalidateLayout(lines: [table]) | |
| 890 | textView.needsDisplay = true | |
| 891 | } | |
| 892 | ||
| 893 | /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`, | |
| 894 | /// `expand` for `org-table-expand`. | |
| 895 | private func tableColumnWidth(_ id: String) { | |
| 896 | switch shrunk.change(for: id, at: textView.selectedRange().location, in: textView.string) { | |
| 897 | case .notInTable: onMessage?("Not in a table") | |
| 898 | case .set(let columns, let table): setShrunk(columns, in: table) | |
| 899 | case .ask(let table, let current, let max): | |
| 900 | onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in | |
| 901 | guard let self, let answer else { return } | |
| 902 | self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table) | |
| 903 | } | |
| 904 | } | |
| 905 | } | |
| 906 | ||
| 907 | /// Hides each shrunk segment's text and draws its display where the text was. | |
| 908 | private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) { | |
| 909 | guard !shrunk.isEmpty else { return } | |
| 910 | let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width | |
| 911 | for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length { | |
| 912 | let r = segment.range | |
| 913 | let shown = segment.display.count | |
| 914 | let kept = min(shown, r.count) | |
| 915 | if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) } | |
| 916 | guard kept > 0 else { continue } | |
| 917 | let visible = NSRange(location: r.upperBound - kept, length: kept) | |
| 918 | storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible) | |
| 919 | storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1)) | |
| 920 | if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) } | |
| 921 | } | |
| 922 | } | |
| 923 | ||
| 924 | /// Moves drawer and block folds through `edit`, checking again only those near it. | |
| 925 | private func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) { | |
| 926 | guard !wrapperHidden.isEmpty else { return } | |
| 927 | var mapped: [Int: Range<Int>] = [:] | |
| 928 | let entries = Array(wrapperHidden) | |
| 929 | // One pass maps every start and range. | |
| 930 | let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection | |
| 931 | for i in entries.indices { | |
| 932 | let newStart = moved[2 * i].lowerBound | |
| 933 | let newRange = moved[2 * i + 1] | |
| 934 | if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound { | |
| 935 | if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden } | |
| 936 | } else { | |
| 937 | mapped[newStart] = newRange | |
| 938 | } | |
| 939 | } | |
| 940 | wrapperHidden = mapped | |
| 941 | view.wrapperFolds = Set(mapped.keys) | |
| 942 | } | |
| 943 | ||
| 944 | /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading, | |
| 945 | /// cycles folded, children, subtree. Returns false elsewhere. | |
| 946 | @discardableResult | |
| 947 | public func cycleAtCaret() -> Bool { | |
| 948 | leaveSparseTree() | |
| 949 | let caret = textView.selectedRange().location | |
| 950 | guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false } | |
| 951 | setFolds(state) | |
| 952 | // Off a closing line that folding hid, to the opening line, as org does. | |
| 953 | if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) } | |
| 954 | return true | |
| 955 | } | |
| 956 | ||
| 957 | /// Doom's `za`, `zo` (on a heading line) and `zc` (anywhere in a subtree). | |
| 958 | func fold(_ id: String) { | |
| 959 | leaveSparseTree() | |
| 960 | let caret = textView.selectedRange().location | |
| 961 | let tree = document.tree | |
| 962 | let next: FoldState? | |
| 963 | if id == "org.fold.close" { | |
| 964 | next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == utf16Length) } | |
| 965 | .map { Presentation.hideSubtree($0.start, foldState) } | |
| 966 | } else { | |
| 967 | next = Presentation.heading(containing: caret, in: tree).map { | |
| 968 | id == "org.fold.open" ? Presentation.openFold($0, in: tree, foldState) : Presentation.toggleFold($0, in: tree, foldState) | |
| 969 | } | |
| 970 | } | |
| 971 | if let next, next != foldState { setFolds(next) } | |
| 972 | } | |
| 973 | ||
| 974 | /// Shift-TAB: overview, contents, show all. | |
| 975 | public func cycleGlobal() { | |
| 976 | leaveSparseTree() | |
| 977 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds) | |
| 978 | globalVisibility = visibility | |
| 979 | setFolds(state) | |
| 980 | } | |
| 981 | ||
| 982 | /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it. | |
| 983 | public func reveal(_ offset: Int) { | |
| 984 | let target = max(0, min(offset, utf16Length)) | |
| 985 | if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") } | |
| 986 | unfold(around: target) | |
| 987 | setCaret(target) | |
| 988 | textView.scrollRangeToVisible(NSRange(location: target, length: 0)) | |
| 989 | } | |
| 990 | ||
| 991 | /// Unfolds the headings whose folds hide `offset`, leaving the selection alone. | |
| 992 | func unfold(around offset: Int) { | |
| 993 | leaveSparseTree() | |
| 994 | var state = foldState | |
| 995 | for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end { | |
| 996 | state.folds.remove(entry.start) | |
| 997 | state.bodyFolds.remove(entry.start) | |
| 998 | } | |
| 999 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true { | |
| 1000 | state.wrapperFolds.remove(start) | |
| 1001 | } | |
| 1002 | guard state != foldState else { return } | |
| 1003 | setFolds(state) | |
| 1004 | } | |
| 1005 | ||
| 1006 | /// Applies edits through the text view as one undo step, not merged with typing around it. | |
| 1007 | func applyEdits(_ edits: [TextEdit]) { | |
| 1008 | guard !edits.isEmpty, let storage = textView.textStorage else { return } | |
| 1009 | textView.breakUndoCoalescing() | |
| 1010 | textView.undoManager?.beginUndoGrouping() | |
| 1011 | // By lines, so a fold between two changes stays. | |
| 1012 | let text = storage.string | |
| 1013 | for edit in edits.flatMap({ splitByLines($0, in: text) }).sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { | |
| 1014 | let range = NSRange(edit.range) | |
| 1015 | guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue } | |
| 1016 | storage.replaceCharacters(in: range, with: edit.replacement) | |
| 1017 | textView.didChangeText() | |
| 1018 | } | |
| 1019 | textView.undoManager?.endUndoGrouping() | |
| 1020 | textView.breakUndoCoalescing() | |
| 1021 | } | |
| 1022 | ||
| 1023 | func setCaret(_ offset: Int) { | |
| 1024 | let clamped = max(0, min(offset, utf16Length)) | |
| 1025 | previousSelection = clamped | |
| 1026 | textView.setSelectedRange(NSRange(location: clamped, length: 0)) | |
| 1027 | } | |
| 1028 | ||
| 1029 | // MARK: - Styling | |
| 1030 | ||
| 1031 | private func restyleOutsideEditing(_ range: Range<Int>) { | |
| 1032 | guard let storage = textView.textStorage else { return } | |
| 1033 | storage.beginEditing() | |
| 1034 | restyle(range, in: storage) | |
| 1035 | storage.endEditing() | |
| 1036 | } | |
| 1037 | ||
| 1038 | /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where | |
| 1039 | /// attribute changes are allowed and characters must not change. | |
| 1040 | private func restyle(_ range: Range<Int>, in storage: NSTextStorage) { | |
| 1041 | guard !range.isEmpty else { return } | |
| 1042 | let whole = NSRange(range) | |
| 1043 | storage.setAttributes(theme.base, range: whole) | |
| 1044 | guard isOrg else { | |
| 1045 | for run in plainRuns() where run.range.overlaps(range) { | |
| 1046 | guard let clipped = clip(run.range, to: range) else { continue } | |
| 1047 | theme.apply(.syntax(run.category), to: storage, range: clipped) | |
| 1048 | } | |
| 1049 | return | |
| 1050 | } | |
| 1051 | if indented { | |
| 1052 | for line in Presentation.lineIndents(document.tree, in: range) { | |
| 1053 | storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) | |
| 1054 | } | |
| 1055 | } | |
| 1056 | let revealed = caretLine | |
| 1057 | var scriptExclusions: [Range<Int>] = [] | |
| 1058 | for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) { | |
| 1059 | guard let clipped = clip(run.range, to: range) else { continue } | |
| 1060 | if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue } | |
| 1061 | if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 { | |
| 1062 | storage.addAttributes(theme.hidden, range: clipped) | |
| 1063 | } else { | |
| 1064 | theme.apply(run.role, to: storage, range: clipped) | |
| 1065 | } | |
| 1066 | if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } | |
| 1067 | } | |
| 1068 | if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) } | |
| 1069 | applyShrunk(range, in: storage) | |
| 1070 | applyHighlights(range, in: storage) | |
| 1071 | applyImages(range, in: storage, revealed: revealed) | |
| 1072 | } | |
| 1073 | ||
| 1074 | /// `org-pretty-entities`: entities drawn as their character over the entity's last | |
| 1075 | /// character (the rest hidden), sub/superscripts raised without their markers. | |
| 1076 | private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) { | |
| 1077 | let runs = Presentation.prettyRuns( | |
| 1078 | storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil }, | |
| 1079 | scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces | |
| 1080 | ) | |
| 1081 | for (lineStart, run) in runs { | |
| 1082 | switch run { | |
| 1083 | case .entity(let r, let display): | |
| 1084 | let start = lineStart + r.lowerBound | |
| 1085 | let last = lineStart + r.upperBound - 1 | |
| 1086 | if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) } | |
| 1087 | storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1)) | |
| 1088 | case .script(let markers, let body, let superscript): | |
| 1089 | for marker in markers { | |
| 1090 | storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count)) | |
| 1091 | } | |
| 1092 | let size = theme.font.pointSize | |
| 1093 | storage.addAttributes([ | |
| 1094 | .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular), | |
| 1095 | .baselineOffset: (superscript ? 0.3 : -0.3) * size, | |
| 1096 | ], range: NSRange(location: lineStart + body.lowerBound, length: body.count)) | |
| 1097 | } | |
| 1098 | } | |
| 1099 | } | |
| 1100 | ||
| 1101 | /// Moving to another line shows its markup and hides the last one's. | |
| 1102 | private func revealCaretLine() { | |
| 1103 | guard !showMarkup, isOrg else { return } | |
| 1104 | let line = caretLine | |
| 1105 | guard line != revealedLine else { return } | |
| 1106 | let text = textView.string as NSString | |
| 1107 | // The old line may have moved with edits since; restyle the line now at its start. | |
| 1108 | let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil } | |
| 1109 | revealedLine = line | |
| 1110 | for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo { | |
| 1111 | restyleOutsideEditing(range.location..<NSMaxRange(range)) | |
| 1112 | } | |
| 1113 | } | |
| 1114 | ||
| 1115 | /// Code highlights for the whole file in plain mode. | |
| 1116 | private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] { | |
| 1117 | guard case .plain(let language?) = mode, let highlighter else { return [] } | |
| 1118 | if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs } | |
| 1119 | let runs = highlighter.highlights(language: language, code: document.text) | |
| 1120 | codeRuns = (document.revision, runs) | |
| 1121 | return runs | |
| 1122 | } | |
| 1123 | ||
| 1124 | private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle { | |
| 1125 | let key = IndentKey(firstLine: firstLine, wrapped: wrapped) | |
| 1126 | if let style = paragraphStyles[key] { return style } | |
| 1127 | let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped) | |
| 1128 | paragraphStyles[key] = style | |
| 1129 | return style | |
| 1130 | } | |
| 1131 | ||
| 1132 | private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? { | |
| 1133 | let clipped = run.clamped(to: range) | |
| 1134 | return clipped.isEmpty ? nil : NSRange(clipped) | |
| 1135 | } | |
| 1136 | ||
| 1137 | /// The region an edit affects in one version of the tree: inside the innermost section | |
| 1138 | /// holding the edited lines (plus the line after), every element that overlaps them or the | |
| 1139 | /// line on either side. A changed heading line, or an added or removed heading, widens it | |
| 1140 | /// to that section's whole own body. Run on the old and the new tree, the union covers | |
| 1141 | /// elements that grew and elements that shrank. | |
| 1142 | static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> { | |
| 1143 | let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start)) | |
| 1144 | let lineRange = lines.location..<(lines.location + lines.length) | |
| 1145 | let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1) | |
| 1146 | var container = tree.root | |
| 1147 | while let child = container.child(containing: lineRange.lowerBound), | |
| 1148 | child.kind == .section || child.kind == .zerothSection, | |
| 1149 | lineRange.upperBound <= child.range.upperBound { | |
| 1150 | container = child | |
| 1151 | } | |
| 1152 | var lower = lineRange.lowerBound | |
| 1153 | var upper = lineRange.upperBound | |
| 1154 | // Tables and lists carry no styling of their own, so inside them only the rows or | |
| 1155 | // items around the edit change, however large they are. | |
| 1156 | func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] { | |
| 1157 | nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in | |
| 1158 | guard [.table, .plainList, .item].contains(node.kind) else { return [node] } | |
| 1159 | let inner = overlapping(node.children(overlapping: around)) | |
| 1160 | return inner.isEmpty ? [node] : inner | |
| 1161 | } | |
| 1162 | } | |
| 1163 | for child in overlapping(container.children(overlapping: around)) { | |
| 1164 | lower = min(lower, child.range.lowerBound) | |
| 1165 | upper = max(upper, child.range.upperBound) | |
| 1166 | } | |
| 1167 | let heading = container.firstChild(.heading) | |
| 1168 | if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true { | |
| 1169 | lower = min(lower, container.range.lowerBound) | |
| 1170 | upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound) | |
| 1171 | } | |
| 1172 | return lower..<min(upper, text.length) | |
| 1173 | } | |
| 1174 | ||
| 1175 | 582 | // MARK: - Editing |
| 1176 | 583 | |
| 1177 | 584 | private var blockCheck: DispatchWorkItem? |
| @@ -1421,146 +828,4 @@ extension OrgEditor: NSTextLayoutManagerDelegate { | ||
| 1421 | 828 | return NSTextLayoutFragment(textElement: textElement, range: range) |
| 1422 | 829 | } |
| 1423 | 830 | } |
| 1424 | ||
| 1425 | /// A line of a block, on a band across the whole width of the view, as Emacs extends the | |
| 1426 | /// `org-block` face. | |
| 1427 | final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 1428 | private var band: CGRect { | |
| 1429 | let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width | |
| 1430 | // Not under the empty line TextKit adds after a final newline. | |
| 1431 | let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height | |
| 1432 | return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height) | |
| 1433 | } | |
| 1434 | ||
| 1435 | override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) } | |
| 1436 | ||
| 1437 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 1438 | context.saveGState() | |
| 1439 | context.setFillColor(Theme.blockBackground.cgColor) | |
| 1440 | context.fill(band.offsetBy(dx: point.x, dy: point.y)) | |
| 1441 | // The band covers the view's selection highlight, so the selected text is drawn on it, | |
| 1442 | // in the color the view uses: the theme's when focused, the system's muted one when not. | |
| 1443 | if let manager = textLayoutManager { | |
| 1444 | let active = Theme.focusedLayouts.contains(ObjectIdentifier(manager)) | |
| 1445 | context.setFillColor((active ? Theme.selection : NSColor.unemphasizedSelectedTextBackgroundColor).cgColor) | |
| 1446 | let single = textLineFragments.count == 1 | |
| 1447 | for selection in manager.textSelections { | |
| 1448 | for range in selection.textRanges where !range.isEmpty { | |
| 1449 | guard let part = range.intersection(rangeInElement), !part.isEmpty else { continue } | |
| 1450 | manager.enumerateTextSegments(in: part, type: .selection, options: [.rangeNotRequired]) { _, frame, _, _ in | |
| 1451 | var rect = frame.offsetBy(dx: point.x - self.layoutFragmentFrame.minX, dy: point.y - self.layoutFragmentFrame.minY) | |
| 1452 | // A one-line fragment's selection covers its band, leaving no gap to the next line. | |
| 1453 | if single { rect = CGRect(x: rect.minX, y: point.y, width: rect.width, height: self.band.height) } | |
| 1454 | context.fill(rect) | |
| 1455 | return true | |
| 1456 | } | |
| 1457 | } | |
| 1458 | } | |
| 1459 | } | |
| 1460 | context.restoreGState() | |
| 1461 | super.draw(at: point, in: context) | |
| 1462 | } | |
| 1463 | } | |
| 1464 | ||
| 1465 | extension NSAttributedString.Key { | |
| 1466 | /// The character an entity shows as, on the entity's last character. | |
| 1467 | static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay") | |
| 1468 | /// The image an image link's line shows under it. | |
| 1469 | static let orgImage = NSAttributedString.Key("OrgImage") | |
| 1470 | } | |
| 1471 | ||
| 1472 | final class InlineImageBox: NSObject, @unchecked Sendable { | |
| 1473 | let image: NSImage | |
| 1474 | let size: CGSize | |
| 1475 | init(image: NSImage, size: CGSize) { | |
| 1476 | self.image = image | |
| 1477 | self.size = size | |
| 1478 | } | |
| 1479 | } | |
| 1480 | ||
| 1481 | /// An image link's line drawn as the image, with the paragraph spacing making room for its | |
| 1482 | /// height. | |
| 1483 | final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 1484 | static func image(_ string: NSAttributedString) -> InlineImageBox? { | |
| 1485 | var found: InlineImageBox? | |
| 1486 | string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in | |
| 1487 | if let box = value as? InlineImageBox { found = box; stop.pointee = true } | |
| 1488 | } | |
| 1489 | return found | |
| 1490 | } | |
| 1491 | ||
| 1492 | private var frame: CGRect? { | |
| 1493 | guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil } | |
| 1494 | return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height) | |
| 1495 | } | |
| 1496 | ||
| 1497 | override var renderingSurfaceBounds: CGRect { | |
| 1498 | frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds | |
| 1499 | } | |
| 1500 | ||
| 1501 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 1502 | super.draw(at: point, in: context) | |
| 1503 | guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return } | |
| 1504 | NSGraphicsContext.saveGraphicsState() | |
| 1505 | NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true) | |
| 1506 | box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil) | |
| 1507 | NSGraphicsContext.restoreGraphicsState() | |
| 1508 | } | |
| 1509 | } | |
| 1510 | ||
| 1511 | /// A paragraph with pretty entities: each is drawn as its character where the entity's last | |
| 1512 | /// (now invisible) character sits, so it takes one column as in Emacs. | |
| 1513 | final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 1514 | static func hasEntities(_ string: NSAttributedString) -> Bool { | |
| 1515 | var found = false | |
| 1516 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in | |
| 1517 | if value != nil { found = true; stop.pointee = true } | |
| 1518 | } | |
| 1519 | return found | |
| 1520 | } | |
| 1521 | ||
| 1522 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 1523 | super.draw(at: point, in: context) | |
| 1524 | Self.drawEntities(of: self, at: point, in: context) | |
| 1525 | } | |
| 1526 | ||
| 1527 | static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) { | |
| 1528 | guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return } | |
| 1529 | NSGraphicsContext.saveGraphicsState() | |
| 1530 | NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true) | |
| 1531 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in | |
| 1532 | guard let display = value as? String, | |
| 1533 | let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return } | |
| 1534 | var attributes = string.attributes(at: range.location, effectiveRange: nil) | |
| 1535 | attributes[.foregroundColor] = NSColor.textColor | |
| 1536 | attributes[.orgEntityDisplay] = nil | |
| 1537 | let x = line.locationForCharacter(at: range.location).x | |
| 1538 | let bounds = line.typographicBounds | |
| 1539 | NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY)) | |
| 1540 | } | |
| 1541 | NSGraphicsContext.restoreGraphicsState() | |
| 1542 | } | |
| 1543 | } | |
| 1544 | ||
| 1545 | /// A heading line drawn with an ellipsis after it, like org's folded headings. | |
| 1546 | final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 1547 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 1548 | super.draw(at: point, in: context) | |
| 1549 | EntityFragment.drawEntities(of: self, at: point, in: context) | |
| 1550 | guard let line = textLineFragments.first else { return } | |
| 1551 | let bounds = line.typographicBounds | |
| 1552 | let ellipsis = NSAttributedString(string: " …", attributes: [ | |
| 1553 | .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular), | |
| 1554 | .foregroundColor: NSColor.secondaryLabelColor, | |
| 1555 | ]) | |
| 1556 | NSGraphicsContext.saveGraphicsState() | |
| 1557 | NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true) | |
| 1558 | ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY)) | |
| 1559 | NSGraphicsContext.restoreGraphicsState() | |
| 1560 | } | |
| 1561 | ||
| 1562 | override var renderingSurfaceBounds: CGRect { | |
| 1563 | super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) | |
| 1564 | } | |
| 1565 | } | |
| 1566 | 831 | #endif |
Sources/Orgstar/AgendaRowView.swift added +203
| @@ -0,0 +1,203 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgApp | |
| 3 | import OrgDocument | |
| 4 | import OrgCore | |
| 5 | import OrgPresentation | |
| 6 | import SwiftUI | |
| 7 | ||
| 8 | /// One agenda line: the time or status over an icon, the category above the title, progress | |
| 9 | /// and tags after it, and the TODO keyword and priority at the end. | |
| 10 | struct AgendaRowView: View { | |
| 11 | let row: AgendaRow | |
| 12 | /// The agenda day the row is on, for habit graphs. | |
| 13 | var day: Int | |
| 14 | var showsGutter = true | |
| 15 | var selected = false | |
| 16 | var hovered = false | |
| 17 | /// Marked for a bulk action. | |
| 18 | var marked = false | |
| 19 | @Environment(\.orgTheme) private var theme | |
| 20 | ||
| 21 | static let gutterWidth: CGFloat = 92 | |
| 22 | ||
| 23 | var body: some View { | |
| 24 | HStack(alignment: .center, spacing: 12) { | |
| 25 | if showsGutter { gutter } | |
| 26 | VStack(alignment: .leading, spacing: 2) { | |
| 27 | if !row.category.isEmpty { categoryLine } | |
| 28 | titleLine | |
| 29 | } | |
| 30 | .layoutPriority(1) | |
| 31 | Spacer(minLength: 8) | |
| 32 | if let habit = row.item?.habit { | |
| 33 | HabitGraph(cells: habit.graph(today: day), theme: theme) | |
| 34 | } | |
| 35 | if let todo = row.todo { | |
| 36 | let color = theme.dynamic(row.isDone ? .systemGreen : .systemRed) { [theme, row] in theme.todoColor(todo, isDone: row.isDone, dark: $0) } | |
| 37 | Text(todo) | |
| 38 | .font(.system(size: 10, weight: .bold)) | |
| 39 | .foregroundStyle(color) | |
| 40 | .padding(.horizontal, 7) | |
| 41 | .padding(.vertical, 2) | |
| 42 | .background(Capsule().fill(color.opacity(0.14))) | |
| 43 | .fixedSize() | |
| 44 | } | |
| 45 | priorityBadge | |
| 46 | .frame(width: 18) | |
| 47 | } | |
| 48 | .padding(.horizontal, 16) | |
| 49 | .padding(.vertical, 6) | |
| 50 | .frame(minHeight: 44) | |
| 51 | // `org-agenda-dim-blocked-tasks`. | |
| 52 | .opacity(row.isBlocked ? 0.5 : 1) | |
| 53 | .background { | |
| 54 | RoundedRectangle(cornerRadius: 6) | |
| 55 | .fill(selected ? theme.color("selection") ?? Color.accentColor.opacity(0.2) : hovered ? Color.primary.opacity(0.05) : .clear) | |
| 56 | .padding(.horizontal, 6) | |
| 57 | } | |
| 58 | .overlay(alignment: .leading) { | |
| 59 | if marked { | |
| 60 | Capsule().fill(theme.color("agenda-today") ?? .accentColor).frame(width: 3).padding(.vertical, 8).padding(.leading, 8) | |
| 61 | } | |
| 62 | } | |
| 63 | .accessibilityElement(children: .combine) | |
| 64 | } | |
| 65 | ||
| 66 | private var statusColor: Color { | |
| 67 | theme.dynamic(.secondaryLabelColor) { [theme, row] in theme.statusColor(row.status, dark: $0) } | |
| 68 | } | |
| 69 | ||
| 70 | private var gutter: some View { | |
| 71 | VStack(alignment: .leading, spacing: 3) { | |
| 72 | Text(row.gutter) | |
| 73 | .font(.system(size: 12, weight: row.status == .overdue || row.status == .dueSoon ? .semibold : .regular).monospacedDigit()) | |
| 74 | .foregroundStyle(statusColor) | |
| 75 | .lineLimit(1) | |
| 76 | .minimumScaleFactor(0.8) | |
| 77 | if let symbol { | |
| 78 | Image(systemName: symbol) | |
| 79 | .font(.system(size: row.icon == .event ? 8 : 10, weight: .semibold)) | |
| 80 | .foregroundStyle(iconColor) | |
| 81 | .frame(height: 12) | |
| 82 | } | |
| 83 | } | |
| 84 | .frame(width: Self.gutterWidth, alignment: .leading) | |
| 85 | } | |
| 86 | ||
| 87 | /// Overdue entries show a warning, done ones a check, as the status says first. | |
| 88 | private var symbol: String? { | |
| 89 | guard let icon = row.icon else { return nil } | |
| 90 | if row.status == .overdue { return "exclamationmark.circle.fill" } | |
| 91 | if row.status == .done { return "checkmark.circle.fill" } | |
| 92 | switch icon { | |
| 93 | case .scheduled: return "calendar" | |
| 94 | case .deadline: return "flag.fill" | |
| 95 | case .habit: return "repeat" | |
| 96 | case .event: return "circle.fill" | |
| 97 | case .timestamp: return row.start == nil ? "calendar" : "clock" | |
| 98 | } | |
| 99 | } | |
| 100 | ||
| 101 | private var iconColor: Color { | |
| 102 | if let event = row.event { return theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } } | |
| 103 | return row.status == .normal ? Color.secondary.opacity(0.8) : statusColor | |
| 104 | } | |
| 105 | ||
| 106 | private var categoryLine: some View { | |
| 107 | HStack(spacing: 5) { | |
| 108 | Circle() | |
| 109 | .fill(row.event.map { event in theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } } | |
| 110 | ?? theme.dynamic { [theme, row] in theme.categoryColor(row.category, dark: $0) }) | |
| 111 | .frame(width: 6, height: 6) | |
| 112 | Text(row.category) | |
| 113 | .font(.system(size: 11)) | |
| 114 | .foregroundStyle(theme.color("agenda-category") ?? .secondary) | |
| 115 | .lineLimit(1) | |
| 116 | } | |
| 117 | } | |
| 118 | ||
| 119 | private var titleLine: some View { | |
| 120 | HStack(spacing: 6) { | |
| 121 | Text(row.title.isEmpty ? " " : row.title) | |
| 122 | .font(.system(size: 13)) | |
| 123 | .strikethrough(row.isDone) | |
| 124 | .foregroundStyle(row.isDone ? AnyShapeStyle(.secondary) : AnyShapeStyle(theme.color("foreground") ?? .primary)) | |
| 125 | .lineLimit(1) | |
| 126 | .truncationMode(.tail) | |
| 127 | ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in | |
| 128 | Text(progress) | |
| 129 | .font(.system(size: 10, weight: .semibold).monospacedDigit()) | |
| 130 | .foregroundStyle(.secondary) | |
| 131 | .padding(.horizontal, 6) | |
| 132 | .padding(.vertical, 1) | |
| 133 | .background(Capsule().fill(Color.secondary.opacity(0.14))) | |
| 134 | .fixedSize() | |
| 135 | } | |
| 136 | ForEach(row.tags, id: \.self) { tag in | |
| 137 | Text(tag) | |
| 138 | .font(.system(size: 10, weight: .medium)) | |
| 139 | .foregroundStyle(theme.color("tags") ?? .secondary) | |
| 140 | .padding(.horizontal, 6) | |
| 141 | .padding(.vertical, 1) | |
| 142 | .background(Capsule().strokeBorder((theme.color("tags") ?? .secondary).opacity(0.35), lineWidth: 0.5)) | |
| 143 | .fixedSize() | |
| 144 | } | |
| 145 | } | |
| 146 | } | |
| 147 | ||
| 148 | @ViewBuilder | |
| 149 | private var priorityBadge: some View { | |
| 150 | if let priority = row.priority { | |
| 151 | let color = theme.dynamic(.systemOrange) { [theme] in theme.priorityColor(priority, dark: $0) } | |
| 152 | Text(priority) | |
| 153 | .font(.system(size: 10, weight: .bold)) | |
| 154 | .foregroundStyle(color) | |
| 155 | .frame(width: 18, height: 18) | |
| 156 | .background(Circle().fill(color.opacity(0.14))) | |
| 157 | .overlay(Circle().strokeBorder(color.opacity(0.6), lineWidth: 1)) | |
| 158 | .help("Priority \(priority)") | |
| 159 | } else { | |
| 160 | Color.clear.frame(width: 18, height: 18) | |
| 161 | } | |
| 162 | } | |
| 163 | } | |
| 164 | ||
| 165 | /// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today. | |
| 166 | struct HabitGraph: View { | |
| 167 | let cells: [Habit.Cell] | |
| 168 | var theme: ThemeSpec = .default | |
| 169 | ||
| 170 | var body: some View { | |
| 171 | HStack(spacing: 1) { | |
| 172 | ForEach(cells, id: \.day) { cell in | |
| 173 | Text(String(cell.glyph)) | |
| 174 | .font(.system(size: 9, weight: .bold, design: .monospaced)) | |
| 175 | .frame(width: 8, height: 14) | |
| 176 | .background(color(cell.face)) | |
| 177 | .help(Self.label(cell)) | |
| 178 | } | |
| 179 | } | |
| 180 | .accessibilityElement(children: .ignore) | |
| 181 | .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days") | |
| 182 | } | |
| 183 | ||
| 184 | /// Due-state colors, lighter for days to come, as org-habit's faces. | |
| 185 | func color(_ face: Habit.Face) -> Color { | |
| 186 | func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback } | |
| 187 | switch face { | |
| 188 | case .clear: return themed("habit-clear", .blue).opacity(0.7) | |
| 189 | case .clearFuture: return themed("habit-clear", .blue).opacity(0.35) | |
| 190 | case .ready: return themed("habit-ready", .green).opacity(0.75) | |
| 191 | case .readyFuture: return themed("habit-ready", .green).opacity(0.35) | |
| 192 | case .alert: return themed("habit-alert", .yellow).opacity(0.85) | |
| 193 | case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4) | |
| 194 | case .overdue: return themed("habit-overdue", .red).opacity(0.75) | |
| 195 | case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35) | |
| 196 | } | |
| 197 | } | |
| 198 | ||
| 199 | static func label(_ cell: Habit.Cell) -> String { | |
| 200 | let date = Days.date(cell.day) | |
| 201 | return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "") | |
| 202 | } | |
| 203 | } | |
Sources/Orgstar/AgendaView+Actions.swift added +290
| @@ -0,0 +1,290 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgApp | |
| 3 | import OrgDocument | |
| 4 | import OrgCore | |
| 5 | import OrgPresentation | |
| 6 | import SwiftUI | |
| 7 | ||
| 8 | extension AgendaView { | |
| 9 | // MARK: - Commands | |
| 10 | ||
| 11 | func handle(_ press: KeyPress) -> KeyPress.Result { | |
| 12 | let control = press.modifiers.contains(.control) | |
| 13 | // `C-x` and friends arrive as control characters or as letters with control. | |
| 14 | func isControl(_ letter: String, _ code: String) -> Bool { control && (press.characters == letter || press.characters == code) } | |
| 15 | if let pending = prefix { | |
| 16 | prefix = nil | |
| 17 | if pending == "v" { | |
| 18 | switch press.characters { | |
| 19 | case "d" where isAgenda: setSpan(.day) | |
| 20 | case "w" where isAgenda: setSpan(.week) | |
| 21 | case "m" where isAgenda: setSpan(.month) | |
| 22 | default: message = "v \(press.characters) is undefined" | |
| 23 | } | |
| 24 | if message == "v-" { message = nil } | |
| 25 | return .handled | |
| 26 | } | |
| 27 | if pending == "C-c C-x" { | |
| 28 | if isControl("s", "\u{13}") { archive() } else { message = "C-c C-x \(press.characters) is undefined" } | |
| 29 | return .handled | |
| 30 | } | |
| 31 | if isControl("s", "\u{13}") { | |
| 32 | run(SetPlanning(deadline: false)) | |
| 33 | } else if isControl("d", "\u{04}") { | |
| 34 | run(SetPlanning(deadline: true)) | |
| 35 | } else if isControl("q", "\u{11}") { | |
| 36 | run(SetTags()) | |
| 37 | } else if isControl("t", "\u{14}") { | |
| 38 | run(TodoCycle()) | |
| 39 | } else if isControl("w", "\u{17}") { | |
| 40 | refile(marked: false) | |
| 41 | } else if isControl("x", "\u{18}") { | |
| 42 | prefix = "C-c C-x" | |
| 43 | message = "C-c C-x-" | |
| 44 | } else if press.characters == "$" { | |
| 45 | archive() | |
| 46 | } else { | |
| 47 | message = "C-c \(press.characters) is undefined" | |
| 48 | } | |
| 49 | return .handled | |
| 50 | } | |
| 51 | if isControl("c", "\u{03}") { | |
| 52 | prefix = "C-c" | |
| 53 | message = "C-c-" | |
| 54 | return .handled | |
| 55 | } | |
| 56 | if isControl("n", "\u{0e}") || (press.key == .downArrow && press.modifiers.isEmpty) { | |
| 57 | step(1) | |
| 58 | return .handled | |
| 59 | } | |
| 60 | if isControl("p", "\u{10}") || (press.key == .upArrow && press.modifiers.isEmpty) { | |
| 61 | step(-1) | |
| 62 | return .handled | |
| 63 | } | |
| 64 | if press.key == .return || press.key == .tab, let selection, let line = line(selection) { | |
| 65 | open(line) | |
| 66 | return .handled | |
| 67 | } | |
| 68 | if press.key == .space, let selection { | |
| 69 | jump(selection, focus: false) | |
| 70 | return .handled | |
| 71 | } | |
| 72 | if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow { | |
| 73 | run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true) | |
| 74 | return .handled | |
| 75 | } | |
| 76 | guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored } | |
| 77 | switch press.characters { | |
| 78 | case "n": step(1) | |
| 79 | case "p": step(-1) | |
| 80 | case "f" where isAgenda: move(forward: true) | |
| 81 | case "b" where isAgenda: move(forward: false) | |
| 82 | case "." where isAgenda: goToday() | |
| 83 | case "j" where isAgenda: | |
| 84 | pickedDate = Self.date(anchorDay) | |
| 85 | showingDatePicker = true | |
| 86 | case "v" where isAgenda: | |
| 87 | prefix = "v" | |
| 88 | message = "v-" | |
| 89 | case "d" where isAgenda: setSpan(.day) | |
| 90 | case "w" where isAgenda: setSpan(.week) | |
| 91 | case "k" where isAgenda: capture(on: anchorDay) | |
| 92 | case "s": | |
| 93 | commands.run("app.save-all") | |
| 94 | message = "Saved" | |
| 95 | case "/", "\\", "=", "_": askFilter(press.characters.first!) | |
| 96 | case "<": toggleCategoryFilter() | |
| 97 | case "|": | |
| 98 | filter = AgendaFilter() | |
| 99 | message = "Filters removed" | |
| 100 | case "l" where isAgenda: | |
| 101 | logMode.toggle() | |
| 102 | message = logMode ? "Log mode on" : "Log mode off" | |
| 103 | case "g", "r": | |
| 104 | loadViews() | |
| 105 | tick += 1 | |
| 106 | case "I": clockIn() | |
| 107 | case "O": message = clock.clockOut(session) | |
| 108 | case "X": message = clock.clockOut(session, cancel: true) | |
| 109 | case "$": archive() | |
| 110 | case "m": mark(true) | |
| 111 | case "u": mark(false) | |
| 112 | case "U": | |
| 113 | marked = [] | |
| 114 | message = "No entries marked" | |
| 115 | case "B": askBulk() | |
| 116 | case "t": run(TodoCycle()) | |
| 117 | case "+": run(PriorityUp()) | |
| 118 | case "-": run(PriorityDown()) | |
| 119 | case ",": run(SetPriority()) | |
| 120 | case ":": run(SetTags()) | |
| 121 | default: return .ignored | |
| 122 | } | |
| 123 | return .handled | |
| 124 | } | |
| 125 | ||
| 126 | // MARK: - Clock, refile, archive, bulk | |
| 127 | ||
| 128 | private var selectedEntry: EntryRef? { selection.flatMap(item).flatMap(EntryRef.init) } | |
| 129 | ||
| 130 | func clockIn() { | |
| 131 | guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else { | |
| 132 | message = "No entry selected" | |
| 133 | return | |
| 134 | } | |
| 135 | let paths = workspace.files.filter { $0.kind == .org }.map(\.path) | |
| 136 | Task { | |
| 137 | let outcome = await clock.clockIn(session, target: .entry(path: entry.path, offset: offset), paths: paths, ask: commands.askClock) | |
| 138 | if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) } | |
| 139 | message = outcome.messages.last { !$0.isEmpty } | |
| 140 | tick += 1 | |
| 141 | } | |
| 142 | } | |
| 143 | ||
| 144 | func archive() { | |
| 145 | guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else { | |
| 146 | message = "No entry selected" | |
| 147 | return | |
| 148 | } | |
| 149 | message = session.archive(from: (entry.path, offset)) | |
| 150 | tick += 1 | |
| 151 | } | |
| 152 | ||
| 153 | /// Refiles the selected entry, or with `marked` the marked ones, to a target asked for in | |
| 154 | /// the main window, where the list of targets is searchable. | |
| 155 | private func refile(marked bulk: Bool) { | |
| 156 | let entries = bulk ? marked : selectedEntry.map { [$0] } ?? [] | |
| 157 | guard !entries.isEmpty else { | |
| 158 | message = "No entry selected" | |
| 159 | return | |
| 160 | } | |
| 161 | let targets = workspace.refileTargets(openPath: session.path, document: session.document) | |
| 162 | commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in | |
| 163 | guard let answer, targets.contains(where: { $0.label == answer }) else { return } | |
| 164 | message = eachEntry(entries) { entry, offset in | |
| 165 | // Targets in the entry's own file from its text now, as earlier moves shift them. | |
| 166 | let document = session.openDocuments.first { $0.path == entry.path }?.document | |
| 167 | ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) } | |
| 168 | guard let target = workspace.refileTargets(openPath: entry.path, document: document).first(where: { $0.label == answer }) else { | |
| 169 | return "Can't find \(answer) any more." | |
| 170 | } | |
| 171 | return session.refile(to: target, from: (entry.path, offset)) | |
| 172 | } | |
| 173 | if bulk { marked = [] } | |
| 174 | tick += 1 | |
| 175 | } | |
| 176 | openWindow(id: "main") | |
| 177 | } | |
| 178 | ||
| 179 | /// Runs `action` on each entry, finding it again first: later entries in a file first, so | |
| 180 | /// earlier ones keep their place. Returns the last message. | |
| 181 | private func eachEntry(_ entries: [EntryRef], _ action: (EntryRef, Int) -> String?) -> String? { | |
| 182 | var last: String? | |
| 183 | var failed = 0 | |
| 184 | for entry in entries.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) { | |
| 185 | guard let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else { | |
| 186 | failed += 1 | |
| 187 | continue | |
| 188 | } | |
| 189 | last = action(entry, offset) | |
| 190 | } | |
| 191 | return failed > 0 ? "\(failed) marked \(failed == 1 ? "entry" : "entries") changed and \(failed == 1 ? "was" : "were") skipped" : last | |
| 192 | } | |
| 193 | ||
| 194 | func mark(_ on: Bool) { | |
| 195 | guard let entry = selectedEntry else { | |
| 196 | message = "No entry selected" | |
| 197 | return | |
| 198 | } | |
| 199 | if on { | |
| 200 | if !marked.contains(entry) { marked.append(entry) } | |
| 201 | } else { | |
| 202 | marked.removeAll { $0 == entry } | |
| 203 | } | |
| 204 | message = "\(marked.count) marked" | |
| 205 | } | |
| 206 | ||
| 207 | /// `B`: an action for every marked entry. | |
| 208 | private func askBulk() { | |
| 209 | guard !marked.isEmpty else { | |
| 210 | message = "No entries are marked" | |
| 211 | return | |
| 212 | } | |
| 213 | textPrompt = TextPrompt(title: "Bulk action on \(marked.count): [$] archive [r] refile [t] TODO state [+] tag [-] untag [s] schedule [d] deadline") { answer in | |
| 214 | switch answer.trimmingCharacters(in: .whitespaces) { | |
| 215 | case "$": bulk { session.archive(from: ($0.path, $1)) } | |
| 216 | case "r": refile(marked: true) | |
| 217 | case "t": | |
| 218 | textPrompt = TextPrompt(title: "TODO state (empty for none):") { keyword in | |
| 219 | let word = keyword.trimmingCharacters(in: .whitespaces) | |
| 220 | bulk { performAt($0, $1, SetTodo(keyword: word.isEmpty ? nil : word)) } | |
| 221 | } | |
| 222 | case "+", "-": | |
| 223 | let on = answer.trimmingCharacters(in: .whitespaces) == "+" | |
| 224 | textPrompt = TextPrompt(title: on ? "Tag to add:" : "Tag to remove:") { tag in | |
| 225 | let tag = tag.trimmingCharacters(in: .whitespaces) | |
| 226 | guard !tag.isEmpty else { return } | |
| 227 | bulk { performAt($0, $1, ToggleTag(tag: tag, on: on)) } | |
| 228 | } | |
| 229 | case "s", "d": | |
| 230 | let deadline = answer.trimmingCharacters(in: .whitespaces) == "d" | |
| 231 | textPrompt = TextPrompt(title: deadline ? "Deadline (+2d, fri, 2026-10-12):" : "Schedule (+2d, fri, 2026-10-12):") { date in | |
| 232 | bulk { performAt($0, $1, SetPlanning(deadline: deadline), answers: ["date": date]) } | |
| 233 | } | |
| 234 | default: | |
| 235 | message = "No bulk action \(answer)" | |
| 236 | } | |
| 237 | } | |
| 238 | } | |
| 239 | ||
| 240 | func bulk(_ action: (EntryRef, Int) -> String?) { | |
| 241 | message = eachEntry(marked, action) ?? "Done with \(marked.count) entries" | |
| 242 | marked = [] | |
| 243 | tick += 1 | |
| 244 | } | |
| 245 | ||
| 246 | /// Runs `command` at the heading at `offset`, as `run` does for the selection. | |
| 247 | private func performAt(_ entry: EntryRef, _ offset: Int, _ command: any OrgCommand, answers: [String: String] = [:]) -> String? { | |
| 248 | switch session.perform(command, path: entry.path, at: offset, expect: (offset, entry.line), answers: answers) { | |
| 249 | case .failed(let text): text | |
| 250 | case .prompt: "\(command.title) needs an answer; run it on the entry itself" | |
| 251 | default: nil | |
| 252 | } | |
| 253 | } | |
| 254 | ||
| 255 | /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the | |
| 256 | /// timestamp the entry is listed for. | |
| 257 | func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) { | |
| 258 | guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else { | |
| 259 | message = "No entry selected" | |
| 260 | return | |
| 261 | } | |
| 262 | if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) { | |
| 263 | message = "Only dated entries can move" | |
| 264 | return | |
| 265 | } | |
| 266 | let offset = atMarker ? (item.markerOffset ?? start) : start | |
| 267 | let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers) | |
| 268 | switch step { | |
| 269 | case .prompt(let request): | |
| 270 | promptText = request.initial | |
| 271 | prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id) | |
| 272 | case .failed(let text): | |
| 273 | message = text | |
| 274 | tick += 1 | |
| 275 | case .external: | |
| 276 | message = "Not available from the agenda" | |
| 277 | case .commit: | |
| 278 | message = nil | |
| 279 | tick += 1 | |
| 280 | } | |
| 281 | } | |
| 282 | ||
| 283 | func answerPrompt() { | |
| 284 | guard let pending = prompt else { return } | |
| 285 | prompt = nil | |
| 286 | var answers = pending.answers | |
| 287 | answers[pending.prompt.key] = promptText | |
| 288 | run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID) | |
| 289 | } | |
| 290 | } | |
Sources/Orgstar/AgendaView+Toolbar.swift added +289
| @@ -0,0 +1,289 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgApp | |
| 3 | import OrgDocument | |
| 4 | import OrgCore | |
| 5 | import OrgPresentation | |
| 6 | import SwiftUI | |
| 7 | ||
| 8 | extension AgendaView { | |
| 9 | // MARK: - Toolbar | |
| 10 | ||
| 11 | @ToolbarContentBuilder | |
| 12 | var toolbar: some ToolbarContent { | |
| 13 | ToolbarItemGroup(placement: .navigation) { | |
| 14 | Menu { | |
| 15 | ForEach(views) { view in Button(view.name) { viewName = view.name } } | |
| 16 | Divider() | |
| 17 | Button(Self.match) { viewName = Self.match } | |
| 18 | Button(Self.todoMatch) { viewName = Self.todoMatch } | |
| 19 | Button(Self.search) { viewName = Self.search } | |
| 20 | Button(Self.todoSearch) { viewName = Self.todoSearch } | |
| 21 | } label: { | |
| 22 | Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon) | |
| 23 | } | |
| 24 | .help("What the agenda shows") | |
| 25 | if isMatch || isSearch { | |
| 26 | TextField(isSearch ? "Phrase or +word -word {regexp}" : "+work-boss|LEVEL>2/!TODO", text: $matchText) | |
| 27 | .frame(minWidth: 220) | |
| 28 | .onSubmit { applyView() } | |
| 29 | } | |
| 30 | } | |
| 31 | ToolbarItemGroup { | |
| 32 | if agenda.isComputing { ProgressView().controlSize(.small) } | |
| 33 | if isAgenda { | |
| 34 | Picker("Span", selection: Binding(get: { spanKind }, set: { if let kind = $0 { setSpan(kind) } })) { | |
| 35 | Text("Day").tag(AgendaSpan?.some(.day)) | |
| 36 | Text("Week").tag(AgendaSpan?.some(.week)) | |
| 37 | Text("Month").tag(AgendaSpan?.some(.month)) | |
| 38 | } | |
| 39 | .pickerStyle(.segmented) | |
| 40 | .labelsHidden() | |
| 41 | .help("Show a day, week or month (v d, v w, v m)") | |
| 42 | ControlGroup { | |
| 43 | Button("Earlier", systemImage: "chevron.left") { move(forward: false) } | |
| 44 | .help("Previous days (b)") | |
| 45 | Button("Today") { goToday() } | |
| 46 | .help("Back to today (.)") | |
| 47 | Button("Later", systemImage: "chevron.right") { move(forward: true) } | |
| 48 | .help("Next days (f)") | |
| 49 | } | |
| 50 | Button("Go to Date", systemImage: "calendar") { | |
| 51 | pickedDate = Self.date(anchorDay) | |
| 52 | showingDatePicker = true | |
| 53 | } | |
| 54 | .help("Go to a date (j)") | |
| 55 | .popover(isPresented: $showingDatePicker, arrowEdge: .bottom) { | |
| 56 | DatePicker("Date", selection: $pickedDate, displayedComponents: .date) | |
| 57 | .datePickerStyle(.graphical) | |
| 58 | .labelsHidden() | |
| 59 | .padding() | |
| 60 | .onChange(of: pickedDate) { | |
| 61 | showingDatePicker = false | |
| 62 | goTo(Days.absolute(pickedDate, calendar: .current)) | |
| 63 | } | |
| 64 | } | |
| 65 | } | |
| 66 | Menu { | |
| 67 | Button("Filter…") { askFilter("/") } | |
| 68 | Button("By Tag…") { askFilter("\\") } | |
| 69 | Button("By Category of Selected Line") { toggleCategoryFilter() } | |
| 70 | Button("By Regexp…") { askFilter("=") } | |
| 71 | Button("By Effort…") { askFilter("_") } | |
| 72 | Divider() | |
| 73 | Button("Remove Filters") { filter = AgendaFilter() } | |
| 74 | .disabled(filter.isEmpty) | |
| 75 | } label: { | |
| 76 | Label("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill") | |
| 77 | } primaryAction: { | |
| 78 | askFilter("/") | |
| 79 | } | |
| 80 | .help("Filter the entries (/, \\, <, =, _; | removes)") | |
| 81 | } | |
| 82 | } | |
| 83 | ||
| 84 | /// The span shown, as the window's title: `Week of 5 Oct 2026`. | |
| 85 | var title: String { | |
| 86 | guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") } | |
| 87 | guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return "Agenda" } | |
| 88 | switch spanKind { | |
| 89 | case .day: return Self.format(first, "EEEE d MMMM yyyy") | |
| 90 | case .week: return "Week of " + Self.format(first, "d MMM yyyy") | |
| 91 | case .month: return Self.format(first, "MMMM yyyy") | |
| 92 | case nil: | |
| 93 | if first == last { return Self.format(first, "EEEE d MMMM yyyy") } | |
| 94 | let sameYear = Days.date(first).year == Days.date(last).year | |
| 95 | return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM yyyy") | |
| 96 | } | |
| 97 | } | |
| 98 | ||
| 99 | // MARK: - Span | |
| 100 | ||
| 101 | /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first. | |
| 102 | var anchorDay: Int { | |
| 103 | if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day } | |
| 104 | let days = agenda.days.map(\.day) | |
| 105 | if days.contains(agenda.today) || days.isEmpty { return agenda.today } | |
| 106 | return days[0] | |
| 107 | } | |
| 108 | ||
| 109 | /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday | |
| 110 | /// (`org-agenda-start-on-weekday`), or the month around `anchor`. | |
| 111 | func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) { | |
| 112 | let anchor = anchor ?? anchorDay | |
| 113 | spanKind = kind | |
| 114 | selection = nil | |
| 115 | switch kind { | |
| 116 | case .day: | |
| 117 | agenda.mode = .agenda(span: 1, startOffset: nil) | |
| 118 | agenda.start = anchor | |
| 119 | case .week: | |
| 120 | agenda.mode = .agenda(span: 7, startOffset: nil) | |
| 121 | agenda.start = anchor - (Days.weekday(anchor) + 6) % 7 | |
| 122 | case .month: | |
| 123 | let d = Days.date(anchor) | |
| 124 | let first = Days.absolute(year: d.year, month: d.month, day: 1) | |
| 125 | let next = d.month == 12 ? Days.absolute(year: d.year + 1, month: 1, day: 1) : Days.absolute(year: d.year, month: d.month + 1, day: 1) | |
| 126 | agenda.mode = .agenda(span: next - first, startOffset: nil) | |
| 127 | agenda.start = first | |
| 128 | } | |
| 129 | } | |
| 130 | ||
| 131 | func move(forward: Bool) { | |
| 132 | selection = nil | |
| 133 | if spanKind == .month, let first = agenda.days.first?.day { | |
| 134 | setSpan(.month, around: forward ? first + 31 : first - 1) | |
| 135 | } else { | |
| 136 | agenda.shift(forward: forward) | |
| 137 | } | |
| 138 | } | |
| 139 | ||
| 140 | func goToday() { | |
| 141 | if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() } | |
| 142 | selection = nil | |
| 143 | } | |
| 144 | ||
| 145 | /// `org-agenda-goto-date`. | |
| 146 | private func goTo(_ day: Int) { | |
| 147 | if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day } | |
| 148 | selection = nil | |
| 149 | } | |
| 150 | ||
| 151 | /// Capture on `day`, as `org-agenda-capture`. | |
| 152 | func capture(on day: Int) { | |
| 153 | commands.capture(on: day) | |
| 154 | NSApp.activate() | |
| 155 | openWindow(id: "capture") | |
| 156 | } | |
| 157 | ||
| 158 | static func date(_ day: Int) -> Date { | |
| 159 | let d = Days.date(day) | |
| 160 | return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date() | |
| 161 | } | |
| 162 | ||
| 163 | static func format(_ day: Int, _ pattern: String) -> String { | |
| 164 | let formatter = DateFormatter() | |
| 165 | formatter.dateFormat = pattern | |
| 166 | return formatter.string(from: date(day)) | |
| 167 | } | |
| 168 | ||
| 169 | static func hhmm(_ date: Date) -> Int { | |
| 170 | let c = Calendar.current.dateComponents([.hour, .minute], from: date) | |
| 171 | return (c.hour ?? 0) * 100 + (c.minute ?? 0) | |
| 172 | } | |
| 173 | /// How far ahead notifications are set, as the design asks the agenda to show. | |
| 174 | var reminderStatus: String? { | |
| 175 | guard let scheduler, remindersEnabled else { return nil } | |
| 176 | if !scheduler.isAuthorized { return "Notifications are off for orgstar in System Settings." } | |
| 177 | guard let through = scheduler.scheduledThrough else { return nil } | |
| 178 | return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "." | |
| 179 | } | |
| 180 | ||
| 181 | var listTitle: String { | |
| 182 | switch agenda.mode { | |
| 183 | case .todo(let keywords): "TODO items: \(keywords ?? "all")" | |
| 184 | case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)" | |
| 185 | case .search(let string, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " containing \(string)" | |
| 186 | case .agenda: "" | |
| 187 | } | |
| 188 | } | |
| 189 | ||
| 190 | func loadViews() { | |
| 191 | let loaded = AgendaViewLoader.load() | |
| 192 | views = loaded.views | |
| 193 | message = loaded.problems.first | |
| 194 | } | |
| 195 | ||
| 196 | /// The days of a followed timestamp, in the agenda view. | |
| 197 | func showRequestedDays() { | |
| 198 | guard let request = commands.agendaRequest else { return } | |
| 199 | commands.agendaRequest = nil | |
| 200 | selection = nil | |
| 201 | spanKind = nil | |
| 202 | if viewName != AgendaViewLoader.builtIn[0].name { | |
| 203 | keepRequestedDays = true | |
| 204 | viewName = AgendaViewLoader.builtIn[0].name | |
| 205 | } | |
| 206 | agenda.mode = .agenda(span: request.days, startOffset: nil) | |
| 207 | agenda.start = request.start | |
| 208 | } | |
| 209 | ||
| 210 | func applyView() { | |
| 211 | if keepRequestedDays { return keepRequestedDays = false } | |
| 212 | selection = nil | |
| 213 | spanKind = nil | |
| 214 | agenda.start = nil | |
| 215 | switch viewName { | |
| 216 | case Self.match, Self.todoMatch: | |
| 217 | let match = matchText.trimmingCharacters(in: .whitespaces) | |
| 218 | guard !match.isEmpty else { return } | |
| 219 | agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch) | |
| 220 | case Self.search, Self.todoSearch: | |
| 221 | guard matchText.contains(where: { !$0.isWhitespace }) else { return } | |
| 222 | agenda.mode = .search(matchText, todoOnly: viewName == Self.todoSearch) | |
| 223 | default: | |
| 224 | if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode } | |
| 225 | } | |
| 226 | } | |
| 227 | ||
| 228 | // MARK: - Filters | |
| 229 | ||
| 230 | /// The tags and categories on the view's lines, which filter words are read against. | |
| 231 | var shown: (tags: Set<String>, categories: Set<String>) { | |
| 232 | let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil } | |
| 233 | return (Set(items.flatMap(\.tags)), Set(items.map(\.category))) | |
| 234 | } | |
| 235 | ||
| 236 | func askFilter(_ kind: Character) { | |
| 237 | switch kind { | |
| 238 | case "/": filterText = filter.description | |
| 239 | default: filterText = "" | |
| 240 | } | |
| 241 | let title = switch kind { | |
| 242 | case "/": "Filter [+cat-tag<0:10-/regexp/]:" | |
| 243 | case "\\": "Tag filter (+tag-tag):" | |
| 244 | case "=": "Regexp filter (-re to drop):" | |
| 245 | default: "Effort filter (<0:30, >1:00, =1:00):" | |
| 246 | } | |
| 247 | filterPrompt = (title, kind) | |
| 248 | } | |
| 249 | ||
| 250 | func applyFilter() { | |
| 251 | guard let kind = filterPrompt?.kind else { return } | |
| 252 | filterPrompt = nil | |
| 253 | let text = filterText.trimmingCharacters(in: .whitespaces) | |
| 254 | var current = filter | |
| 255 | switch kind { | |
| 256 | case "/": | |
| 257 | let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories) | |
| 258 | current = parsed | |
| 259 | if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" } | |
| 260 | case "\\": | |
| 261 | // Every word as a tag. | |
| 262 | current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags | |
| 263 | case "=": | |
| 264 | current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text] | |
| 265 | default: | |
| 266 | current.efforts = text.isEmpty ? [] : ["+" + text] | |
| 267 | } | |
| 268 | filter = current | |
| 269 | selection = nil | |
| 270 | } | |
| 271 | ||
| 272 | /// `<`: keep only the selected line's category, or drop that filter. | |
| 273 | func toggleCategoryFilter() { | |
| 274 | if !filter.categories.isEmpty { | |
| 275 | filter.categories = [] | |
| 276 | } else if let selection, let item = item(selection) { | |
| 277 | filter.categories = ["+" + item.category] | |
| 278 | } else { | |
| 279 | message = "No entry selected" | |
| 280 | } | |
| 281 | } | |
| 282 | ||
| 283 | /// The entry in the main window; with `focus` false the agenda keeps the keys (SPC). | |
| 284 | func jump(_ id: String, focus: Bool = true) { | |
| 285 | guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return } | |
| 286 | commands.jump(path: path, offset: offset) | |
| 287 | if focus { openWindow(id: "main") } | |
| 288 | } | |
| 289 | } | |
Sources/Orgstar/AgendaView.swift +34 −795
| @@ -31,44 +31,44 @@ struct AgendaView: View { | ||
| 31 | 31 | let commands: AppCommands |
| 32 | 32 | let scheduler: ReminderScheduler? |
| 33 | 33 | let clock: ClockModel |
| 34 | @State private var agenda: AgendaModel | |
| 35 | @State private var views = AgendaViewLoader.builtIn | |
| 36 | @State private var viewName = AgendaViewLoader.builtIn[0].name | |
| 37 | @State private var matchText = "" | |
| 34 | @State var agenda: AgendaModel | |
| 35 | @State var views = AgendaViewLoader.builtIn | |
| 36 | @State var viewName = AgendaViewLoader.builtIn[0].name | |
| 37 | @State var matchText = "" | |
| 38 | 38 | /// The selected line: `day:index` (`day:o` + index in the overdue group), or `list:index`. |
| 39 | @State private var selection: String? | |
| 40 | @State private var tick = 0 | |
| 39 | @State var selection: String? | |
| 40 | @State var tick = 0 | |
| 41 | 41 | /// The time the now line shows, kept to the minute while the agenda is open. |
| 42 | @State private var now = Date() | |
| 42 | @State var now = Date() | |
| 43 | 43 | /// The view picker moved to the agenda for a followed timestamp, which sets its own days. |
| 44 | @State private var keepRequestedDays = false | |
| 45 | @State private var message: String? | |
| 46 | @State private var prompt: PendingPrompt? | |
| 47 | @State private var promptText = "" | |
| 48 | @State private var prefix: String? | |
| 44 | @State var keepRequestedDays = false | |
| 45 | @State var message: String? | |
| 46 | @State var prompt: PendingPrompt? | |
| 47 | @State var promptText = "" | |
| 48 | @State var prefix: String? | |
| 49 | 49 | /// Entries marked for a bulk action. |
| 50 | @State private var marked: [EntryRef] = [] | |
| 51 | @State private var logMode = false | |
| 52 | @State private var filter = AgendaFilter() | |
| 50 | @State var marked: [EntryRef] = [] | |
| 51 | @State var logMode = false | |
| 52 | @State var filter = AgendaFilter() | |
| 53 | 53 | /// A filter question: its title and which filter it sets. |
| 54 | @State private var filterPrompt: (title: String, kind: Character)? | |
| 55 | @State private var filterText = "" | |
| 54 | @State var filterPrompt: (title: String, kind: Character)? | |
| 55 | @State var filterText = "" | |
| 56 | 56 | /// A one-line question for an agenda action, and what to do with the answer. |
| 57 | 57 | struct TextPrompt { |
| 58 | 58 | let title: String |
| 59 | 59 | let apply: (String) -> Void |
| 60 | 60 | } |
| 61 | @State private var textPrompt: TextPrompt? | |
| 61 | @State var textPrompt: TextPrompt? | |
| 62 | 62 | @State private var textAnswer = "" |
| 63 | 63 | /// Day, week or month chosen with `v`; nil shows the span the settings or the view give. |
| 64 | @State private var spanKind: AgendaSpan? | |
| 65 | @State private var showingDatePicker = false | |
| 66 | @State private var pickedDate = Date() | |
| 64 | @State var spanKind: AgendaSpan? | |
| 65 | @State var showingDatePicker = false | |
| 66 | @State var pickedDate = Date() | |
| 67 | 67 | @AppStorage("agendaOverdueExpanded") private var overdueShown = true |
| 68 | 68 | @State private var hovered: String? |
| 69 | 69 | @FocusState private var focused: Bool |
| 70 | @AppStorage("agendaSpan") private var span = 10 | |
| 71 | @AppStorage("agendaStartOffset") private var startOffset = 0 | |
| 70 | @AppStorage("agendaSpan") var span = 10 | |
| 71 | @AppStorage("agendaStartOffset") var startOffset = 0 | |
| 72 | 72 | @AppStorage("agendaSubfolders") private var includeSubfolders = false |
| 73 | 73 | @AppStorage("agendaShowAllDates") private var showAllDates = false |
| 74 | 74 | @AppStorage("calendarEvents") private var calendarEventsOn = false |
| @@ -76,7 +76,7 @@ struct AgendaView: View { | ||
| 76 | 76 | @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]! |
| 77 | 77 | @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]! |
| 78 | 78 | @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]! |
| 79 | @Environment(\.openWindow) private var openWindow | |
| 79 | @Environment(\.openWindow) var openWindow | |
| 80 | 80 | |
| 81 | 81 | static let match = "Match…" |
| 82 | 82 | static let todoMatch = "TODO Match…" |
| @@ -163,7 +163,7 @@ struct AgendaView: View { | ||
| 163 | 163 | let workspace: WorkspaceModel |
| 164 | 164 | let refresh: () async -> Void |
| 165 | 165 | |
| 166 | private var key: RefreshKey { | |
| 166 | var key: RefreshKey { | |
| 167 | 167 | var key = base |
| 168 | 168 | key.files = workspace.files.count |
| 169 | 169 | key.changed = workspace.changedFile?.version |
| @@ -181,13 +181,13 @@ struct AgendaView: View { | ||
| 181 | 181 | } |
| 182 | 182 | } |
| 183 | 183 | |
| 184 | private var isAgenda: Bool { | |
| 184 | var isAgenda: Bool { | |
| 185 | 185 | if case .agenda = agenda.mode { return true } |
| 186 | 186 | return false |
| 187 | 187 | } |
| 188 | 188 | |
| 189 | private var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch } | |
| 190 | private var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch } | |
| 189 | var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch } | |
| 190 | var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch } | |
| 191 | 191 | |
| 192 | 192 | @Environment(\.orgTheme) private var theme |
| 193 | 193 | |
| @@ -209,7 +209,7 @@ struct AgendaView: View { | ||
| 209 | 209 | } |
| 210 | 210 | |
| 211 | 211 | /// The lines in order, as up and down move through them. |
| 212 | private func lines(_ groups: [AgendaDayGroup]) -> [Line] { | |
| 212 | func lines(_ groups: [AgendaDayGroup]) -> [Line] { | |
| 213 | 213 | guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } } |
| 214 | 214 | return groups.flatMap { group in |
| 215 | 215 | (overdueShown ? group.overdue.enumerated().map { Line(id: "\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : []) |
| @@ -217,7 +217,7 @@ struct AgendaView: View { | ||
| 217 | 217 | } |
| 218 | 218 | } |
| 219 | 219 | |
| 220 | private func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } } | |
| 220 | func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } } | |
| 221 | 221 | |
| 222 | 222 | var body: some View { |
| 223 | 223 | let groups = self.groups |
| @@ -486,234 +486,14 @@ struct AgendaView: View { | ||
| 486 | 486 | } |
| 487 | 487 | } |
| 488 | 488 | |
| 489 | // MARK: - Toolbar | |
| 490 | ||
| 491 | @ToolbarContentBuilder | |
| 492 | private var toolbar: some ToolbarContent { | |
| 493 | ToolbarItemGroup(placement: .navigation) { | |
| 494 | Menu { | |
| 495 | ForEach(views) { view in Button(view.name) { viewName = view.name } } | |
| 496 | Divider() | |
| 497 | Button(Self.match) { viewName = Self.match } | |
| 498 | Button(Self.todoMatch) { viewName = Self.todoMatch } | |
| 499 | Button(Self.search) { viewName = Self.search } | |
| 500 | Button(Self.todoSearch) { viewName = Self.todoSearch } | |
| 501 | } label: { | |
| 502 | Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon) | |
| 503 | } | |
| 504 | .help("What the agenda shows") | |
| 505 | if isMatch || isSearch { | |
| 506 | TextField(isSearch ? "Phrase or +word -word {regexp}" : "+work-boss|LEVEL>2/!TODO", text: $matchText) | |
| 507 | .frame(minWidth: 220) | |
| 508 | .onSubmit { applyView() } | |
| 509 | } | |
| 510 | } | |
| 511 | ToolbarItemGroup { | |
| 512 | if agenda.isComputing { ProgressView().controlSize(.small) } | |
| 513 | if isAgenda { | |
| 514 | Picker("Span", selection: Binding(get: { spanKind }, set: { if let kind = $0 { setSpan(kind) } })) { | |
| 515 | Text("Day").tag(AgendaSpan?.some(.day)) | |
| 516 | Text("Week").tag(AgendaSpan?.some(.week)) | |
| 517 | Text("Month").tag(AgendaSpan?.some(.month)) | |
| 518 | } | |
| 519 | .pickerStyle(.segmented) | |
| 520 | .labelsHidden() | |
| 521 | .help("Show a day, week or month (v d, v w, v m)") | |
| 522 | ControlGroup { | |
| 523 | Button("Earlier", systemImage: "chevron.left") { move(forward: false) } | |
| 524 | .help("Previous days (b)") | |
| 525 | Button("Today") { goToday() } | |
| 526 | .help("Back to today (.)") | |
| 527 | Button("Later", systemImage: "chevron.right") { move(forward: true) } | |
| 528 | .help("Next days (f)") | |
| 529 | } | |
| 530 | Button("Go to Date", systemImage: "calendar") { | |
| 531 | pickedDate = Self.date(anchorDay) | |
| 532 | showingDatePicker = true | |
| 533 | } | |
| 534 | .help("Go to a date (j)") | |
| 535 | .popover(isPresented: $showingDatePicker, arrowEdge: .bottom) { | |
| 536 | DatePicker("Date", selection: $pickedDate, displayedComponents: .date) | |
| 537 | .datePickerStyle(.graphical) | |
| 538 | .labelsHidden() | |
| 539 | .padding() | |
| 540 | .onChange(of: pickedDate) { | |
| 541 | showingDatePicker = false | |
| 542 | goTo(Days.absolute(pickedDate, calendar: .current)) | |
| 543 | } | |
| 544 | } | |
| 545 | } | |
| 546 | Menu { | |
| 547 | Button("Filter…") { askFilter("/") } | |
| 548 | Button("By Tag…") { askFilter("\\") } | |
| 549 | Button("By Category of Selected Line") { toggleCategoryFilter() } | |
| 550 | Button("By Regexp…") { askFilter("=") } | |
| 551 | Button("By Effort…") { askFilter("_") } | |
| 552 | Divider() | |
| 553 | Button("Remove Filters") { filter = AgendaFilter() } | |
| 554 | .disabled(filter.isEmpty) | |
| 555 | } label: { | |
| 556 | Label("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill") | |
| 557 | } primaryAction: { | |
| 558 | askFilter("/") | |
| 559 | } | |
| 560 | .help("Filter the entries (/, \\, <, =, _; | removes)") | |
| 561 | } | |
| 562 | } | |
| 563 | ||
| 564 | /// The span shown, as the window's title: `Week of 5 Oct 2026`. | |
| 565 | private var title: String { | |
| 566 | guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") } | |
| 567 | guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return "Agenda" } | |
| 568 | switch spanKind { | |
| 569 | case .day: return Self.format(first, "EEEE d MMMM yyyy") | |
| 570 | case .week: return "Week of " + Self.format(first, "d MMM yyyy") | |
| 571 | case .month: return Self.format(first, "MMMM yyyy") | |
| 572 | case nil: | |
| 573 | if first == last { return Self.format(first, "EEEE d MMMM yyyy") } | |
| 574 | let sameYear = Days.date(first).year == Days.date(last).year | |
| 575 | return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM yyyy") | |
| 576 | } | |
| 577 | } | |
| 578 | ||
| 579 | // MARK: - Span | |
| 580 | ||
| 581 | /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first. | |
| 582 | private var anchorDay: Int { | |
| 583 | if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day } | |
| 584 | let days = agenda.days.map(\.day) | |
| 585 | if days.contains(agenda.today) || days.isEmpty { return agenda.today } | |
| 586 | return days[0] | |
| 587 | } | |
| 588 | ||
| 589 | /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday | |
| 590 | /// (`org-agenda-start-on-weekday`), or the month around `anchor`. | |
| 591 | private func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) { | |
| 592 | let anchor = anchor ?? anchorDay | |
| 593 | spanKind = kind | |
| 594 | selection = nil | |
| 595 | switch kind { | |
| 596 | case .day: | |
| 597 | agenda.mode = .agenda(span: 1, startOffset: nil) | |
| 598 | agenda.start = anchor | |
| 599 | case .week: | |
| 600 | agenda.mode = .agenda(span: 7, startOffset: nil) | |
| 601 | agenda.start = anchor - (Days.weekday(anchor) + 6) % 7 | |
| 602 | case .month: | |
| 603 | let d = Days.date(anchor) | |
| 604 | let first = Days.absolute(year: d.year, month: d.month, day: 1) | |
| 605 | let next = d.month == 12 ? Days.absolute(year: d.year + 1, month: 1, day: 1) : Days.absolute(year: d.year, month: d.month + 1, day: 1) | |
| 606 | agenda.mode = .agenda(span: next - first, startOffset: nil) | |
| 607 | agenda.start = first | |
| 608 | } | |
| 609 | } | |
| 610 | ||
| 611 | private func move(forward: Bool) { | |
| 612 | selection = nil | |
| 613 | if spanKind == .month, let first = agenda.days.first?.day { | |
| 614 | setSpan(.month, around: forward ? first + 31 : first - 1) | |
| 615 | } else { | |
| 616 | agenda.shift(forward: forward) | |
| 617 | } | |
| 618 | } | |
| 619 | ||
| 620 | private func goToday() { | |
| 621 | if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() } | |
| 622 | selection = nil | |
| 623 | } | |
| 624 | ||
| 625 | /// `org-agenda-goto-date`. | |
| 626 | private func goTo(_ day: Int) { | |
| 627 | if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day } | |
| 628 | selection = nil | |
| 629 | } | |
| 630 | ||
| 631 | /// Capture on `day`, as `org-agenda-capture`. | |
| 632 | private func capture(on day: Int) { | |
| 633 | commands.capture(on: day) | |
| 634 | NSApp.activate() | |
| 635 | openWindow(id: "capture") | |
| 636 | } | |
| 637 | ||
| 638 | static func date(_ day: Int) -> Date { | |
| 639 | let d = Days.date(day) | |
| 640 | return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date() | |
| 641 | } | |
| 642 | ||
| 643 | static func format(_ day: Int, _ pattern: String) -> String { | |
| 644 | let formatter = DateFormatter() | |
| 645 | formatter.dateFormat = pattern | |
| 646 | return formatter.string(from: date(day)) | |
| 647 | } | |
| 648 | ||
| 649 | static func hhmm(_ date: Date) -> Int { | |
| 650 | let c = Calendar.current.dateComponents([.hour, .minute], from: date) | |
| 651 | return (c.hour ?? 0) * 100 + (c.minute ?? 0) | |
| 652 | } | |
| 653 | ||
| 654 | @AppStorage("reminders") private var remindersEnabled = true | |
| 655 | ||
| 656 | /// How far ahead notifications are set, as the design asks the agenda to show. | |
| 657 | private var reminderStatus: String? { | |
| 658 | guard let scheduler, remindersEnabled else { return nil } | |
| 659 | if !scheduler.isAuthorized { return "Notifications are off for orgstar in System Settings." } | |
| 660 | guard let through = scheduler.scheduledThrough else { return nil } | |
| 661 | return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "." | |
| 662 | } | |
| 663 | ||
| 664 | private var listTitle: String { | |
| 665 | switch agenda.mode { | |
| 666 | case .todo(let keywords): "TODO items: \(keywords ?? "all")" | |
| 667 | case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)" | |
| 668 | case .search(let string, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " containing \(string)" | |
| 669 | case .agenda: "" | |
| 670 | } | |
| 671 | } | |
| 672 | ||
| 673 | private func loadViews() { | |
| 674 | let loaded = AgendaViewLoader.load() | |
| 675 | views = loaded.views | |
| 676 | message = loaded.problems.first | |
| 677 | } | |
| 678 | ||
| 679 | /// The days of a followed timestamp, in the agenda view. | |
| 680 | private func showRequestedDays() { | |
| 681 | guard let request = commands.agendaRequest else { return } | |
| 682 | commands.agendaRequest = nil | |
| 683 | selection = nil | |
| 684 | spanKind = nil | |
| 685 | if viewName != AgendaViewLoader.builtIn[0].name { | |
| 686 | keepRequestedDays = true | |
| 687 | viewName = AgendaViewLoader.builtIn[0].name | |
| 688 | } | |
| 689 | agenda.mode = .agenda(span: request.days, startOffset: nil) | |
| 690 | agenda.start = request.start | |
| 691 | } | |
| 692 | ||
| 693 | private func applyView() { | |
| 694 | if keepRequestedDays { return keepRequestedDays = false } | |
| 695 | selection = nil | |
| 696 | spanKind = nil | |
| 697 | agenda.start = nil | |
| 698 | switch viewName { | |
| 699 | case Self.match, Self.todoMatch: | |
| 700 | let match = matchText.trimmingCharacters(in: .whitespaces) | |
| 701 | guard !match.isEmpty else { return } | |
| 702 | agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch) | |
| 703 | case Self.search, Self.todoSearch: | |
| 704 | guard matchText.contains(where: { !$0.isWhitespace }) else { return } | |
| 705 | agenda.mode = .search(matchText, todoOnly: viewName == Self.todoSearch) | |
| 706 | default: | |
| 707 | if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode } | |
| 708 | } | |
| 709 | } | |
| 489 | @AppStorage("reminders") var remindersEnabled = true | |
| 710 | 490 | |
| 711 | 491 | // MARK: - Items |
| 712 | 492 | |
| 713 | private func item(_ id: String) -> AgendaItem? { line(id)?.row.item } | |
| 493 | func item(_ id: String) -> AgendaItem? { line(id)?.row.item } | |
| 714 | 494 | |
| 715 | 495 | /// Return and double click: the entry in the main window, or the event in Calendar. |
| 716 | private func open(_ line: Line) { | |
| 496 | func open(_ line: Line) { | |
| 717 | 497 | selection = line.id |
| 718 | 498 | if let event = line.row.event { openEvent(event) } else { jump(line.id) } |
| 719 | 499 | } |
| @@ -727,552 +507,11 @@ struct AgendaView: View { | ||
| 727 | 507 | } |
| 728 | 508 | |
| 729 | 509 | /// Moves the selection by `step` lines. |
| 730 | private func step(_ step: Int) { | |
| 510 | func step(_ step: Int) { | |
| 731 | 511 | let all = lines(groups) |
| 732 | 512 | guard !all.isEmpty else { return } |
| 733 | 513 | let index = selection.flatMap { id in all.firstIndex { $0.id == id } } |
| 734 | 514 | let next = index.map { min(max($0 + step, 0), all.count - 1) } ?? (step > 0 ? 0 : all.count - 1) |
| 735 | 515 | selection = all[next].id |
| 736 | 516 | } |
| 737 | ||
| 738 | // MARK: - Filters | |
| 739 | ||
| 740 | /// The tags and categories on the view's lines, which filter words are read against. | |
| 741 | private var shown: (tags: Set<String>, categories: Set<String>) { | |
| 742 | let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil } | |
| 743 | return (Set(items.flatMap(\.tags)), Set(items.map(\.category))) | |
| 744 | } | |
| 745 | ||
| 746 | private func askFilter(_ kind: Character) { | |
| 747 | switch kind { | |
| 748 | case "/": filterText = filter.description | |
| 749 | default: filterText = "" | |
| 750 | } | |
| 751 | let title = switch kind { | |
| 752 | case "/": "Filter [+cat-tag<0:10-/regexp/]:" | |
| 753 | case "\\": "Tag filter (+tag-tag):" | |
| 754 | case "=": "Regexp filter (-re to drop):" | |
| 755 | default: "Effort filter (<0:30, >1:00, =1:00):" | |
| 756 | } | |
| 757 | filterPrompt = (title, kind) | |
| 758 | } | |
| 759 | ||
| 760 | private func applyFilter() { | |
| 761 | guard let kind = filterPrompt?.kind else { return } | |
| 762 | filterPrompt = nil | |
| 763 | let text = filterText.trimmingCharacters(in: .whitespaces) | |
| 764 | var current = filter | |
| 765 | switch kind { | |
| 766 | case "/": | |
| 767 | let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories) | |
| 768 | current = parsed | |
| 769 | if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" } | |
| 770 | case "\\": | |
| 771 | // Every word as a tag. | |
| 772 | current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags | |
| 773 | case "=": | |
| 774 | current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text] | |
| 775 | default: | |
| 776 | current.efforts = text.isEmpty ? [] : ["+" + text] | |
| 777 | } | |
| 778 | filter = current | |
| 779 | selection = nil | |
| 780 | } | |
| 781 | ||
| 782 | /// `<`: keep only the selected line's category, or drop that filter. | |
| 783 | private func toggleCategoryFilter() { | |
| 784 | if !filter.categories.isEmpty { | |
| 785 | filter.categories = [] | |
| 786 | } else if let selection, let item = item(selection) { | |
| 787 | filter.categories = ["+" + item.category] | |
| 788 | } else { | |
| 789 | message = "No entry selected" | |
| 790 | } | |
| 791 | } | |
| 792 | ||
| 793 | /// The entry in the main window; with `focus` false the agenda keeps the keys (SPC). | |
| 794 | private func jump(_ id: String, focus: Bool = true) { | |
| 795 | guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return } | |
| 796 | commands.jump(path: path, offset: offset) | |
| 797 | if focus { openWindow(id: "main") } | |
| 798 | } | |
| 799 | ||
| 800 | // MARK: - Commands | |
| 801 | ||
| 802 | private func handle(_ press: KeyPress) -> KeyPress.Result { | |
| 803 | let control = press.modifiers.contains(.control) | |
| 804 | // `C-x` and friends arrive as control characters or as letters with control. | |
| 805 | func isControl(_ letter: String, _ code: String) -> Bool { control && (press.characters == letter || press.characters == code) } | |
| 806 | if let pending = prefix { | |
| 807 | prefix = nil | |
| 808 | if pending == "v" { | |
| 809 | switch press.characters { | |
| 810 | case "d" where isAgenda: setSpan(.day) | |
| 811 | case "w" where isAgenda: setSpan(.week) | |
| 812 | case "m" where isAgenda: setSpan(.month) | |
| 813 | default: message = "v \(press.characters) is undefined" | |
| 814 | } | |
| 815 | if message == "v-" { message = nil } | |
| 816 | return .handled | |
| 817 | } | |
| 818 | if pending == "C-c C-x" { | |
| 819 | if isControl("s", "\u{13}") { archive() } else { message = "C-c C-x \(press.characters) is undefined" } | |
| 820 | return .handled | |
| 821 | } | |
| 822 | if isControl("s", "\u{13}") { | |
| 823 | run(SetPlanning(deadline: false)) | |
| 824 | } else if isControl("d", "\u{04}") { | |
| 825 | run(SetPlanning(deadline: true)) | |
| 826 | } else if isControl("q", "\u{11}") { | |
| 827 | run(SetTags()) | |
| 828 | } else if isControl("t", "\u{14}") { | |
| 829 | run(TodoCycle()) | |
| 830 | } else if isControl("w", "\u{17}") { | |
| 831 | refile(marked: false) | |
| 832 | } else if isControl("x", "\u{18}") { | |
| 833 | prefix = "C-c C-x" | |
| 834 | message = "C-c C-x-" | |
| 835 | } else if press.characters == "$" { | |
| 836 | archive() | |
| 837 | } else { | |
| 838 | message = "C-c \(press.characters) is undefined" | |
| 839 | } | |
| 840 | return .handled | |
| 841 | } | |
| 842 | if isControl("c", "\u{03}") { | |
| 843 | prefix = "C-c" | |
| 844 | message = "C-c-" | |
| 845 | return .handled | |
| 846 | } | |
| 847 | if isControl("n", "\u{0e}") || (press.key == .downArrow && press.modifiers.isEmpty) { | |
| 848 | step(1) | |
| 849 | return .handled | |
| 850 | } | |
| 851 | if isControl("p", "\u{10}") || (press.key == .upArrow && press.modifiers.isEmpty) { | |
| 852 | step(-1) | |
| 853 | return .handled | |
| 854 | } | |
| 855 | if press.key == .return || press.key == .tab, let selection, let line = line(selection) { | |
| 856 | open(line) | |
| 857 | return .handled | |
| 858 | } | |
| 859 | if press.key == .space, let selection { | |
| 860 | jump(selection, focus: false) | |
| 861 | return .handled | |
| 862 | } | |
| 863 | if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow { | |
| 864 | run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true) | |
| 865 | return .handled | |
| 866 | } | |
| 867 | guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored } | |
| 868 | switch press.characters { | |
| 869 | case "n": step(1) | |
| 870 | case "p": step(-1) | |
| 871 | case "f" where isAgenda: move(forward: true) | |
| 872 | case "b" where isAgenda: move(forward: false) | |
| 873 | case "." where isAgenda: goToday() | |
| 874 | case "j" where isAgenda: | |
| 875 | pickedDate = Self.date(anchorDay) | |
| 876 | showingDatePicker = true | |
| 877 | case "v" where isAgenda: | |
| 878 | prefix = "v" | |
| 879 | message = "v-" | |
| 880 | case "d" where isAgenda: setSpan(.day) | |
| 881 | case "w" where isAgenda: setSpan(.week) | |
| 882 | case "k" where isAgenda: capture(on: anchorDay) | |
| 883 | case "s": | |
| 884 | commands.run("app.save-all") | |
| 885 | message = "Saved" | |
| 886 | case "/", "\\", "=", "_": askFilter(press.characters.first!) | |
| 887 | case "<": toggleCategoryFilter() | |
| 888 | case "|": | |
| 889 | filter = AgendaFilter() | |
| 890 | message = "Filters removed" | |
| 891 | case "l" where isAgenda: | |
| 892 | logMode.toggle() | |
| 893 | message = logMode ? "Log mode on" : "Log mode off" | |
| 894 | case "g", "r": | |
| 895 | loadViews() | |
| 896 | tick += 1 | |
| 897 | case "I": clockIn() | |
| 898 | case "O": message = clock.clockOut(session) | |
| 899 | case "X": message = clock.clockOut(session, cancel: true) | |
| 900 | case "$": archive() | |
| 901 | case "m": mark(true) | |
| 902 | case "u": mark(false) | |
| 903 | case "U": | |
| 904 | marked = [] | |
| 905 | message = "No entries marked" | |
| 906 | case "B": askBulk() | |
| 907 | case "t": run(TodoCycle()) | |
| 908 | case "+": run(PriorityUp()) | |
| 909 | case "-": run(PriorityDown()) | |
| 910 | case ",": run(SetPriority()) | |
| 911 | case ":": run(SetTags()) | |
| 912 | default: return .ignored | |
| 913 | } | |
| 914 | return .handled | |
| 915 | } | |
| 916 | ||
| 917 | // MARK: - Clock, refile, archive, bulk | |
| 918 | ||
| 919 | private var selectedEntry: EntryRef? { selection.flatMap(item).flatMap(EntryRef.init) } | |
| 920 | ||
| 921 | private func clockIn() { | |
| 922 | guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else { | |
| 923 | message = "No entry selected" | |
| 924 | return | |
| 925 | } | |
| 926 | let paths = workspace.files.filter { $0.kind == .org }.map(\.path) | |
| 927 | Task { | |
| 928 | let outcome = await clock.clockIn(session, target: .entry(path: entry.path, offset: offset), paths: paths, ask: commands.askClock) | |
| 929 | if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) } | |
| 930 | message = outcome.messages.last { !$0.isEmpty } | |
| 931 | tick += 1 | |
| 932 | } | |
| 933 | } | |
| 934 | ||
| 935 | private func archive() { | |
| 936 | guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else { | |
| 937 | message = "No entry selected" | |
| 938 | return | |
| 939 | } | |
| 940 | message = session.archive(from: (entry.path, offset)) | |
| 941 | tick += 1 | |
| 942 | } | |
| 943 | ||
| 944 | /// Refiles the selected entry, or with `marked` the marked ones, to a target asked for in | |
| 945 | /// the main window, where the list of targets is searchable. | |
| 946 | private func refile(marked bulk: Bool) { | |
| 947 | let entries = bulk ? marked : selectedEntry.map { [$0] } ?? [] | |
| 948 | guard !entries.isEmpty else { | |
| 949 | message = "No entry selected" | |
| 950 | return | |
| 951 | } | |
| 952 | let targets = workspace.refileTargets(openPath: session.path, document: session.document) | |
| 953 | commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in | |
| 954 | guard let answer, targets.contains(where: { $0.label == answer }) else { return } | |
| 955 | message = eachEntry(entries) { entry, offset in | |
| 956 | // Targets in the entry's own file from its text now, as earlier moves shift them. | |
| 957 | let document = session.openDocuments.first { $0.path == entry.path }?.document | |
| 958 | ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) } | |
| 959 | guard let target = workspace.refileTargets(openPath: entry.path, document: document).first(where: { $0.label == answer }) else { | |
| 960 | return "Can't find \(answer) any more." | |
| 961 | } | |
| 962 | return session.refile(to: target, from: (entry.path, offset)) | |
| 963 | } | |
| 964 | if bulk { marked = [] } | |
| 965 | tick += 1 | |
| 966 | } | |
| 967 | openWindow(id: "main") | |
| 968 | } | |
| 969 | ||
| 970 | /// Runs `action` on each entry, finding it again first: later entries in a file first, so | |
| 971 | /// earlier ones keep their place. Returns the last message. | |
| 972 | private func eachEntry(_ entries: [EntryRef], _ action: (EntryRef, Int) -> String?) -> String? { | |
| 973 | var last: String? | |
| 974 | var failed = 0 | |
| 975 | for entry in entries.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) { | |
| 976 | guard let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else { | |
| 977 | failed += 1 | |
| 978 | continue | |
| 979 | } | |
| 980 | last = action(entry, offset) | |
| 981 | } | |
| 982 | return failed > 0 ? "\(failed) marked \(failed == 1 ? "entry" : "entries") changed and \(failed == 1 ? "was" : "were") skipped" : last | |
| 983 | } | |
| 984 | ||
| 985 | private func mark(_ on: Bool) { | |
| 986 | guard let entry = selectedEntry else { | |
| 987 | message = "No entry selected" | |
| 988 | return | |
| 989 | } | |
| 990 | if on { | |
| 991 | if !marked.contains(entry) { marked.append(entry) } | |
| 992 | } else { | |
| 993 | marked.removeAll { $0 == entry } | |
| 994 | } | |
| 995 | message = "\(marked.count) marked" | |
| 996 | } | |
| 997 | ||
| 998 | /// `B`: an action for every marked entry. | |
| 999 | private func askBulk() { | |
| 1000 | guard !marked.isEmpty else { | |
| 1001 | message = "No entries are marked" | |
| 1002 | return | |
| 1003 | } | |
| 1004 | textPrompt = TextPrompt(title: "Bulk action on \(marked.count): [$] archive [r] refile [t] TODO state [+] tag [-] untag [s] schedule [d] deadline") { answer in | |
| 1005 | switch answer.trimmingCharacters(in: .whitespaces) { | |
| 1006 | case "$": bulk { session.archive(from: ($0.path, $1)) } | |
| 1007 | case "r": refile(marked: true) | |
| 1008 | case "t": | |
| 1009 | textPrompt = TextPrompt(title: "TODO state (empty for none):") { keyword in | |
| 1010 | let word = keyword.trimmingCharacters(in: .whitespaces) | |
| 1011 | bulk { performAt($0, $1, SetTodo(keyword: word.isEmpty ? nil : word)) } | |
| 1012 | } | |
| 1013 | case "+", "-": | |
| 1014 | let on = answer.trimmingCharacters(in: .whitespaces) == "+" | |
| 1015 | textPrompt = TextPrompt(title: on ? "Tag to add:" : "Tag to remove:") { tag in | |
| 1016 | let tag = tag.trimmingCharacters(in: .whitespaces) | |
| 1017 | guard !tag.isEmpty else { return } | |
| 1018 | bulk { performAt($0, $1, ToggleTag(tag: tag, on: on)) } | |
| 1019 | } | |
| 1020 | case "s", "d": | |
| 1021 | let deadline = answer.trimmingCharacters(in: .whitespaces) == "d" | |
| 1022 | textPrompt = TextPrompt(title: deadline ? "Deadline (+2d, fri, 2026-10-12):" : "Schedule (+2d, fri, 2026-10-12):") { date in | |
| 1023 | bulk { performAt($0, $1, SetPlanning(deadline: deadline), answers: ["date": date]) } | |
| 1024 | } | |
| 1025 | default: | |
| 1026 | message = "No bulk action \(answer)" | |
| 1027 | } | |
| 1028 | } | |
| 1029 | } | |
| 1030 | ||
| 1031 | private func bulk(_ action: (EntryRef, Int) -> String?) { | |
| 1032 | message = eachEntry(marked, action) ?? "Done with \(marked.count) entries" | |
| 1033 | marked = [] | |
| 1034 | tick += 1 | |
| 1035 | } | |
| 1036 | ||
| 1037 | /// Runs `command` at the heading at `offset`, as `run` does for the selection. | |
| 1038 | private func performAt(_ entry: EntryRef, _ offset: Int, _ command: any OrgCommand, answers: [String: String] = [:]) -> String? { | |
| 1039 | switch session.perform(command, path: entry.path, at: offset, expect: (offset, entry.line), answers: answers) { | |
| 1040 | case .failed(let text): text | |
| 1041 | case .prompt: "\(command.title) needs an answer; run it on the entry itself" | |
| 1042 | default: nil | |
| 1043 | } | |
| 1044 | } | |
| 1045 | ||
| 1046 | /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the | |
| 1047 | /// timestamp the entry is listed for. | |
| 1048 | private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) { | |
| 1049 | guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else { | |
| 1050 | message = "No entry selected" | |
| 1051 | return | |
| 1052 | } | |
| 1053 | if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) { | |
| 1054 | message = "Only dated entries can move" | |
| 1055 | return | |
| 1056 | } | |
| 1057 | let offset = atMarker ? (item.markerOffset ?? start) : start | |
| 1058 | let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers) | |
| 1059 | switch step { | |
| 1060 | case .prompt(let request): | |
| 1061 | promptText = request.initial | |
| 1062 | prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id) | |
| 1063 | case .failed(let text): | |
| 1064 | message = text | |
| 1065 | tick += 1 | |
| 1066 | case .external: | |
| 1067 | message = "Not available from the agenda" | |
| 1068 | case .commit: | |
| 1069 | message = nil | |
| 1070 | tick += 1 | |
| 1071 | } | |
| 1072 | } | |
| 1073 | ||
| 1074 | private func answerPrompt() { | |
| 1075 | guard let pending = prompt else { return } | |
| 1076 | prompt = nil | |
| 1077 | var answers = pending.answers | |
| 1078 | answers[pending.prompt.key] = promptText | |
| 1079 | run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID) | |
| 1080 | } | |
| 1081 | } | |
| 1082 | ||
| 1083 | /// One agenda line: the time or status over an icon, the category above the title, progress | |
| 1084 | /// and tags after it, and the TODO keyword and priority at the end. | |
| 1085 | struct AgendaRowView: View { | |
| 1086 | let row: AgendaRow | |
| 1087 | /// The agenda day the row is on, for habit graphs. | |
| 1088 | var day: Int | |
| 1089 | var showsGutter = true | |
| 1090 | var selected = false | |
| 1091 | var hovered = false | |
| 1092 | /// Marked for a bulk action. | |
| 1093 | var marked = false | |
| 1094 | @Environment(\.orgTheme) private var theme | |
| 1095 | ||
| 1096 | static let gutterWidth: CGFloat = 92 | |
| 1097 | ||
| 1098 | var body: some View { | |
| 1099 | HStack(alignment: .center, spacing: 12) { | |
| 1100 | if showsGutter { gutter } | |
| 1101 | VStack(alignment: .leading, spacing: 2) { | |
| 1102 | if !row.category.isEmpty { categoryLine } | |
| 1103 | titleLine | |
| 1104 | } | |
| 1105 | .layoutPriority(1) | |
| 1106 | Spacer(minLength: 8) | |
| 1107 | if let habit = row.item?.habit { | |
| 1108 | HabitGraph(cells: habit.graph(today: day), theme: theme) | |
| 1109 | } | |
| 1110 | if let todo = row.todo { | |
| 1111 | let color = theme.dynamic(row.isDone ? .systemGreen : .systemRed) { [theme, row] in theme.todoColor(todo, isDone: row.isDone, dark: $0) } | |
| 1112 | Text(todo) | |
| 1113 | .font(.system(size: 10, weight: .bold)) | |
| 1114 | .foregroundStyle(color) | |
| 1115 | .padding(.horizontal, 7) | |
| 1116 | .padding(.vertical, 2) | |
| 1117 | .background(Capsule().fill(color.opacity(0.14))) | |
| 1118 | .fixedSize() | |
| 1119 | } | |
| 1120 | priorityBadge | |
| 1121 | .frame(width: 18) | |
| 1122 | } | |
| 1123 | .padding(.horizontal, 16) | |
| 1124 | .padding(.vertical, 6) | |
| 1125 | .frame(minHeight: 44) | |
| 1126 | // `org-agenda-dim-blocked-tasks`. | |
| 1127 | .opacity(row.isBlocked ? 0.5 : 1) | |
| 1128 | .background { | |
| 1129 | RoundedRectangle(cornerRadius: 6) | |
| 1130 | .fill(selected ? theme.color("selection") ?? Color.accentColor.opacity(0.2) : hovered ? Color.primary.opacity(0.05) : .clear) | |
| 1131 | .padding(.horizontal, 6) | |
| 1132 | } | |
| 1133 | .overlay(alignment: .leading) { | |
| 1134 | if marked { | |
| 1135 | Capsule().fill(theme.color("agenda-today") ?? .accentColor).frame(width: 3).padding(.vertical, 8).padding(.leading, 8) | |
| 1136 | } | |
| 1137 | } | |
| 1138 | .accessibilityElement(children: .combine) | |
| 1139 | } | |
| 1140 | ||
| 1141 | private var statusColor: Color { | |
| 1142 | theme.dynamic(.secondaryLabelColor) { [theme, row] in theme.statusColor(row.status, dark: $0) } | |
| 1143 | } | |
| 1144 | ||
| 1145 | private var gutter: some View { | |
| 1146 | VStack(alignment: .leading, spacing: 3) { | |
| 1147 | Text(row.gutter) | |
| 1148 | .font(.system(size: 12, weight: row.status == .overdue || row.status == .dueSoon ? .semibold : .regular).monospacedDigit()) | |
| 1149 | .foregroundStyle(statusColor) | |
| 1150 | .lineLimit(1) | |
| 1151 | .minimumScaleFactor(0.8) | |
| 1152 | if let symbol { | |
| 1153 | Image(systemName: symbol) | |
| 1154 | .font(.system(size: row.icon == .event ? 8 : 10, weight: .semibold)) | |
| 1155 | .foregroundStyle(iconColor) | |
| 1156 | .frame(height: 12) | |
| 1157 | } | |
| 1158 | } | |
| 1159 | .frame(width: Self.gutterWidth, alignment: .leading) | |
| 1160 | } | |
| 1161 | ||
| 1162 | /// Overdue entries show a warning, done ones a check, as the status says first. | |
| 1163 | private var symbol: String? { | |
| 1164 | guard let icon = row.icon else { return nil } | |
| 1165 | if row.status == .overdue { return "exclamationmark.circle.fill" } | |
| 1166 | if row.status == .done { return "checkmark.circle.fill" } | |
| 1167 | switch icon { | |
| 1168 | case .scheduled: return "calendar" | |
| 1169 | case .deadline: return "flag.fill" | |
| 1170 | case .habit: return "repeat" | |
| 1171 | case .event: return "circle.fill" | |
| 1172 | case .timestamp: return row.start == nil ? "calendar" : "clock" | |
| 1173 | } | |
| 1174 | } | |
| 1175 | ||
| 1176 | private var iconColor: Color { | |
| 1177 | if let event = row.event { return theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } } | |
| 1178 | return row.status == .normal ? Color.secondary.opacity(0.8) : statusColor | |
| 1179 | } | |
| 1180 | ||
| 1181 | private var categoryLine: some View { | |
| 1182 | HStack(spacing: 5) { | |
| 1183 | Circle() | |
| 1184 | .fill(row.event.map { event in theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } } | |
| 1185 | ?? theme.dynamic { [theme, row] in theme.categoryColor(row.category, dark: $0) }) | |
| 1186 | .frame(width: 6, height: 6) | |
| 1187 | Text(row.category) | |
| 1188 | .font(.system(size: 11)) | |
| 1189 | .foregroundStyle(theme.color("agenda-category") ?? .secondary) | |
| 1190 | .lineLimit(1) | |
| 1191 | } | |
| 1192 | } | |
| 1193 | ||
| 1194 | private var titleLine: some View { | |
| 1195 | HStack(spacing: 6) { | |
| 1196 | Text(row.title.isEmpty ? " " : row.title) | |
| 1197 | .font(.system(size: 13)) | |
| 1198 | .strikethrough(row.isDone) | |
| 1199 | .foregroundStyle(row.isDone ? AnyShapeStyle(.secondary) : AnyShapeStyle(theme.color("foreground") ?? .primary)) | |
| 1200 | .lineLimit(1) | |
| 1201 | .truncationMode(.tail) | |
| 1202 | ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in | |
| 1203 | Text(progress) | |
| 1204 | .font(.system(size: 10, weight: .semibold).monospacedDigit()) | |
| 1205 | .foregroundStyle(.secondary) | |
| 1206 | .padding(.horizontal, 6) | |
| 1207 | .padding(.vertical, 1) | |
| 1208 | .background(Capsule().fill(Color.secondary.opacity(0.14))) | |
| 1209 | .fixedSize() | |
| 1210 | } | |
| 1211 | ForEach(row.tags, id: \.self) { tag in | |
| 1212 | Text(tag) | |
| 1213 | .font(.system(size: 10, weight: .medium)) | |
| 1214 | .foregroundStyle(theme.color("tags") ?? .secondary) | |
| 1215 | .padding(.horizontal, 6) | |
| 1216 | .padding(.vertical, 1) | |
| 1217 | .background(Capsule().strokeBorder((theme.color("tags") ?? .secondary).opacity(0.35), lineWidth: 0.5)) | |
| 1218 | .fixedSize() | |
| 1219 | } | |
| 1220 | } | |
| 1221 | } | |
| 1222 | ||
| 1223 | @ViewBuilder | |
| 1224 | private var priorityBadge: some View { | |
| 1225 | if let priority = row.priority { | |
| 1226 | let color = theme.dynamic(.systemOrange) { [theme] in theme.priorityColor(priority, dark: $0) } | |
| 1227 | Text(priority) | |
| 1228 | .font(.system(size: 10, weight: .bold)) | |
| 1229 | .foregroundStyle(color) | |
| 1230 | .frame(width: 18, height: 18) | |
| 1231 | .background(Circle().fill(color.opacity(0.14))) | |
| 1232 | .overlay(Circle().strokeBorder(color.opacity(0.6), lineWidth: 1)) | |
| 1233 | .help("Priority \(priority)") | |
| 1234 | } else { | |
| 1235 | Color.clear.frame(width: 18, height: 18) | |
| 1236 | } | |
| 1237 | } | |
| 1238 | } | |
| 1239 | ||
| 1240 | /// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today. | |
| 1241 | struct HabitGraph: View { | |
| 1242 | let cells: [Habit.Cell] | |
| 1243 | var theme: ThemeSpec = .default | |
| 1244 | ||
| 1245 | var body: some View { | |
| 1246 | HStack(spacing: 1) { | |
| 1247 | ForEach(cells, id: \.day) { cell in | |
| 1248 | Text(String(cell.glyph)) | |
| 1249 | .font(.system(size: 9, weight: .bold, design: .monospaced)) | |
| 1250 | .frame(width: 8, height: 14) | |
| 1251 | .background(color(cell.face)) | |
| 1252 | .help(Self.label(cell)) | |
| 1253 | } | |
| 1254 | } | |
| 1255 | .accessibilityElement(children: .ignore) | |
| 1256 | .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days") | |
| 1257 | } | |
| 1258 | ||
| 1259 | /// Due-state colors, lighter for days to come, as org-habit's faces. | |
| 1260 | func color(_ face: Habit.Face) -> Color { | |
| 1261 | func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback } | |
| 1262 | switch face { | |
| 1263 | case .clear: return themed("habit-clear", .blue).opacity(0.7) | |
| 1264 | case .clearFuture: return themed("habit-clear", .blue).opacity(0.35) | |
| 1265 | case .ready: return themed("habit-ready", .green).opacity(0.75) | |
| 1266 | case .readyFuture: return themed("habit-ready", .green).opacity(0.35) | |
| 1267 | case .alert: return themed("habit-alert", .yellow).opacity(0.85) | |
| 1268 | case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4) | |
| 1269 | case .overdue: return themed("habit-overdue", .red).opacity(0.75) | |
| 1270 | case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35) | |
| 1271 | } | |
| 1272 | } | |
| 1273 | ||
| 1274 | static func label(_ cell: Habit.Cell) -> String { | |
| 1275 | let date = Days.date(cell.day) | |
| 1276 | return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "") | |
| 1277 | } | |
| 1278 | 517 | } |
Sources/Orgstar/BufferTabs.swift added +80
| @@ -0,0 +1,80 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgApp | |
| 3 | import SwiftUI | |
| 4 | ||
| 5 | /// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's | |
| 6 | /// split view loops on its size constraints in short windows, so this sets a width instead. | |
| 7 | struct PaneDivider: View { | |
| 8 | @Binding var width: Double | |
| 9 | let range: ClosedRange<Double> | |
| 10 | @State private var start: Double? | |
| 11 | ||
| 12 | var body: some View { | |
| 13 | Rectangle() | |
| 14 | .fill(Color(nsColor: .separatorColor)) | |
| 15 | .frame(width: 1) | |
| 16 | .frame(maxHeight: .infinity) | |
| 17 | .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in | |
| 18 | if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() } | |
| 19 | } | |
| 20 | .gesture(DragGesture(minimumDistance: 1).onChanged { drag in | |
| 21 | let base = start ?? width | |
| 22 | start = base | |
| 23 | width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound) | |
| 24 | }.onEnded { _ in start = nil })) | |
| 25 | .accessibilityHidden(true) | |
| 26 | } | |
| 27 | } | |
| 28 | ||
| 29 | /// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits. | |
| 30 | struct BufferTabs: View { | |
| 31 | let session: DocumentSession | |
| 32 | @Environment(\.orgTheme) private var theme | |
| 33 | ||
| 34 | var body: some View { | |
| 35 | ScrollView(.horizontal, showsIndicators: false) { | |
| 36 | HStack(spacing: 0) { | |
| 37 | ForEach(session.openPaths, id: \.self) { path in | |
| 38 | tab(path) | |
| 39 | } | |
| 40 | } | |
| 41 | } | |
| 42 | .frame(height: 28) | |
| 43 | .background { Rectangle().fill(theme.color("modeline-background").map(AnyShapeStyle.init) ?? AnyShapeStyle(.bar)) } | |
| 44 | .overlay(alignment: .bottom) { Divider() } | |
| 45 | } | |
| 46 | ||
| 47 | private func tab(_ path: String) -> some View { | |
| 48 | let current = path == session.path | |
| 49 | return HStack(spacing: 6) { | |
| 50 | Text(session.bufferName(path)) | |
| 51 | .lineLimit(1) | |
| 52 | .foregroundStyle(current ? .primary : .secondary) | |
| 53 | .accessibilityAddTraits(current ? [.isButton, .isSelected] : .isButton) | |
| 54 | .accessibilityAction { session.open(path) } | |
| 55 | Button { | |
| 56 | if path == session.path { | |
| 57 | if UnsavedChanges.resolve(session) { session.kill(path) } | |
| 58 | } else if UnsavedChanges.resolve(session, paths: [path]) { | |
| 59 | session.kill(path) | |
| 60 | } | |
| 61 | } label: { | |
| 62 | Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark") | |
| 63 | .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold)) | |
| 64 | .frame(width: 12, height: 12) | |
| 65 | } | |
| 66 | .buttonStyle(.borderless) | |
| 67 | .help("Close") | |
| 68 | .accessibilityLabel("Close \(session.bufferName(path))" + (session.dirtyPaths.contains(path) ? ", unsaved" : "")) | |
| 69 | } | |
| 70 | .font(.callout) | |
| 71 | .padding(.horizontal, 12) | |
| 72 | .frame(maxHeight: .infinity) | |
| 73 | // A shape, not a color: a color background runs up under the toolbar. | |
| 74 | .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) } | |
| 75 | .overlay(alignment: .trailing) { Divider() } | |
| 76 | .contentShape(Rectangle()) | |
| 77 | .onTapGesture { session.open(path) } | |
| 78 | .help(path) | |
| 79 | } | |
| 80 | } | |
Sources/Orgstar/ContentView.swift −310
| @@ -794,313 +794,3 @@ struct ContentView: View { | ||
| 794 | 794 | Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in }) |
| 795 | 795 | } |
| 796 | 796 | } |
| 797 | ||
| 798 | struct Sidebar: View { | |
| 799 | let workspace: WorkspaceModel | |
| 800 | let session: DocumentSession | |
| 801 | @Binding var selection: String? | |
| 802 | var addFolder: () -> Void = {} | |
| 803 | /// Folders shown collapsed, by path, one per line. | |
| 804 | @AppStorage("collapsedFolders") private var collapsedText = "" | |
| 805 | @State private var removing: String? | |
| 806 | /// A file operation waiting for a name or a confirmation. | |
| 807 | @Environment(\.orgTheme) private var theme | |
| 808 | @State var pending: FileOperation? | |
| 809 | @State var name = "" | |
| 810 | @State var failure: String? | |
| 811 | ||
| 812 | private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) } | |
| 813 | ||
| 814 | private func expanded(_ root: String) -> Binding<Bool> { | |
| 815 | Binding { | |
| 816 | !collapsed.contains(root) | |
| 817 | } set: { isExpanded in | |
| 818 | var set = collapsed | |
| 819 | if isExpanded { set.remove(root) } else { set.insert(root) } | |
| 820 | collapsedText = set.sorted().joined(separator: "\n") | |
| 821 | } | |
| 822 | } | |
| 823 | ||
| 824 | var body: some View { | |
| 825 | List(selection: $selection) { | |
| 826 | ForEach(workspace.rootPaths, id: \.self) { root in | |
| 827 | Section(isExpanded: expanded(root)) { | |
| 828 | OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in | |
| 829 | Label(node.name, systemImage: icon(node)) | |
| 830 | .foregroundStyle(node.file?.kind == .conflict ? .orange : node.isDownloading ? .secondary : theme.color("sidebar-foreground") ?? .primary) | |
| 831 | .help(node.isDownloading ? "Downloading from iCloud" : "") | |
| 832 | .tag(node.file?.path) | |
| 833 | .contextMenu { fileMenu(node) } | |
| 834 | } | |
| 835 | } header: { | |
| 836 | Text((root as NSString).lastPathComponent) | |
| 837 | .foregroundStyle(theme.color("sidebar-header") ?? .secondary) | |
| 838 | .help(root) | |
| 839 | .contextMenu { folderMenu(root) } | |
| 840 | } | |
| 841 | } | |
| 842 | } | |
| 843 | .listStyle(.sidebar) | |
| 844 | .themedListBackground(theme.color("sidebar-background")) | |
| 845 | .safeAreaInset(edge: .bottom, spacing: 0) { | |
| 846 | HStack(spacing: 4) { | |
| 847 | Button("Add Folder…", systemImage: "plus", action: addFolder) | |
| 848 | .help("Add a folder (⇧⌘O)") | |
| 849 | Menu { | |
| 850 | ForEach(workspace.rootPaths, id: \.self) { root in | |
| 851 | Button((root as NSString).lastPathComponent) { removing = root } | |
| 852 | } | |
| 853 | } label: { | |
| 854 | Label("Remove Folder", systemImage: "minus") | |
| 855 | } | |
| 856 | .menuIndicator(.hidden) | |
| 857 | .fixedSize() | |
| 858 | .disabled(workspace.rootPaths.isEmpty) | |
| 859 | .help("Remove a folder from the sidebar") | |
| 860 | Spacer() | |
| 861 | } | |
| 862 | .labelStyle(.iconOnly) | |
| 863 | .buttonStyle(.borderless) | |
| 864 | .menuStyle(.borderlessButton) | |
| 865 | .padding(.horizontal, 10) | |
| 866 | .padding(.vertical, 6) | |
| 867 | } | |
| 868 | .confirmationDialog( | |
| 869 | "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?", | |
| 870 | isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } } | |
| 871 | ) { | |
| 872 | Button("Remove") { | |
| 873 | if let root = removing { try? workspace.removeRoot(path: root) } | |
| 874 | removing = nil | |
| 875 | } | |
| 876 | } message: { | |
| 877 | Text("The folder and its files stay on disk.") | |
| 878 | } | |
| 879 | .fileOperations(self) | |
| 880 | } | |
| 881 | ||
| 882 | @ViewBuilder | |
| 883 | private func folderMenu(_ root: String) -> some View { | |
| 884 | Button("New File…") { ask(.create(folder: root)) } | |
| 885 | Divider() | |
| 886 | Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() } | |
| 887 | Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) } | |
| 888 | Divider() | |
| 889 | Button("Remove from Sidebar…") { removing = root } | |
| 890 | } | |
| 891 | ||
| 892 | private func icon(_ node: FileTreeNode) -> String { | |
| 893 | if node.isDownloading { return "icloud.and.arrow.down" } | |
| 894 | guard let file = node.file else { return "folder" } | |
| 895 | switch file.kind { | |
| 896 | case .org: return "doc.text" | |
| 897 | case .archive: return "archivebox" | |
| 898 | case .conflict: return "exclamationmark.triangle" | |
| 899 | case .other: | |
| 900 | guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" } | |
| 901 | if type.conforms(to: .image) { return "photo" } | |
| 902 | if type.conforms(to: .pdf) { return "doc.richtext" } | |
| 903 | if type.conforms(to: .audiovisualContent) { return "play.rectangle" } | |
| 904 | if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" } | |
| 905 | if type.conforms(to: .text) { return "doc.plaintext" } | |
| 906 | return "doc" | |
| 907 | } | |
| 908 | } | |
| 909 | } | |
| 910 | ||
| 911 | struct OutlineColumn: View { | |
| 912 | let session: DocumentSession | |
| 913 | @Environment(\.orgTheme) private var theme | |
| 914 | ||
| 915 | var body: some View { | |
| 916 | List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in | |
| 917 | Button { | |
| 918 | session.reveal(entry.start) | |
| 919 | } label: { | |
| 920 | Text(entry.title.isEmpty ? "(untitled)" : entry.title) | |
| 921 | .foregroundStyle(theme.color("sidebar-foreground") ?? .primary) | |
| 922 | .lineLimit(1) | |
| 923 | .padding(.leading, CGFloat(entry.level - 1) * 12) | |
| 924 | } | |
| 925 | .buttonStyle(.plain) | |
| 926 | } | |
| 927 | .themedListBackground(theme.color("sidebar-background")) | |
| 928 | .overlay { | |
| 929 | if session.path != nil, !session.isOrg { | |
| 930 | ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline.")) | |
| 931 | } else if session.path != nil, session.outline.isEmpty { | |
| 932 | ContentUnavailableView("No headings", systemImage: "list.bullet.indent") | |
| 933 | } | |
| 934 | } | |
| 935 | } | |
| 936 | } | |
| 937 | ||
| 938 | struct SearchResults: View { | |
| 939 | let results: [HeadingLocation] | |
| 940 | let open: (HeadingLocation) -> Void | |
| 941 | ||
| 942 | var body: some View { | |
| 943 | List(results, id: \.self) { location in | |
| 944 | Button { | |
| 945 | open(location) | |
| 946 | } label: { | |
| 947 | VStack(alignment: .leading, spacing: 2) { | |
| 948 | Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1) | |
| 949 | Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary) | |
| 950 | } | |
| 951 | } | |
| 952 | .buttonStyle(.plain) | |
| 953 | } | |
| 954 | .overlay { | |
| 955 | if results.isEmpty { ContentUnavailableView.search } | |
| 956 | } | |
| 957 | } | |
| 958 | } | |
| 959 | ||
| 960 | struct QuickOpenView: View { | |
| 961 | let workspace: WorkspaceModel | |
| 962 | let open: (FileEntry) -> Void | |
| 963 | @State private var query = "" | |
| 964 | /// The highlighted match, moved by ↑/↓ or C-p/C-n and opened by Return. | |
| 965 | @State private var selected = 0 | |
| 966 | @Environment(\.dismiss) private var dismiss | |
| 967 | ||
| 968 | var body: some View { | |
| 969 | let matches = workspace.quickOpen(query) | |
| 970 | let current = min(selected, matches.count - 1) | |
| 971 | VStack(spacing: 0) { | |
| 972 | TextField("Open file", text: $query) | |
| 973 | .textFieldStyle(.plain) | |
| 974 | .font(.title3) | |
| 975 | .padding(12) | |
| 976 | .onSubmit { if current >= 0 { open(matches[current]) } } | |
| 977 | .onKeyPress(phases: .down) { press in | |
| 978 | let control = press.modifiers == .control | |
| 979 | let step = if press.key == .downArrow || control && press.characters == "n" { 1 } | |
| 980 | else if press.key == .upArrow || control && press.characters == "p" { -1 } else { 0 } | |
| 981 | guard step != 0 else { return .ignored } | |
| 982 | selected = max(0, min(current + step, matches.count - 1)) | |
| 983 | return .handled | |
| 984 | } | |
| 985 | .onChange(of: query) { selected = 0 } | |
| 986 | Divider() | |
| 987 | ScrollViewReader { proxy in | |
| 988 | List(matches.indices, id: \.self) { index in | |
| 989 | let entry = matches[index] | |
| 990 | Button { | |
| 991 | open(entry) | |
| 992 | } label: { | |
| 993 | VStack(alignment: .leading, spacing: 2) { | |
| 994 | Text(entry.name) | |
| 995 | Text(entry.relativePath).font(.caption).foregroundStyle(.secondary) | |
| 996 | } | |
| 997 | .frame(maxWidth: .infinity, alignment: .leading) | |
| 998 | .contentShape(Rectangle()) | |
| 999 | } | |
| 1000 | .buttonStyle(.plain) | |
| 1001 | .listRowBackground(index == current ? Color.accentColor.opacity(0.25) : Color.clear) | |
| 1002 | .accessibilityAddTraits(index == current ? .isSelected : []) | |
| 1003 | } | |
| 1004 | .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } } | |
| 1005 | } | |
| 1006 | } | |
| 1007 | .frame(width: 520, height: 360) | |
| 1008 | .onExitCommand { dismiss() } | |
| 1009 | } | |
| 1010 | } | |
| 1011 | ||
| 1012 | /// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's | |
| 1013 | /// split view loops on its size constraints in short windows, so this sets a width instead. | |
| 1014 | struct PaneDivider: View { | |
| 1015 | @Binding var width: Double | |
| 1016 | let range: ClosedRange<Double> | |
| 1017 | @State private var start: Double? | |
| 1018 | ||
| 1019 | var body: some View { | |
| 1020 | Rectangle() | |
| 1021 | .fill(Color(nsColor: .separatorColor)) | |
| 1022 | .frame(width: 1) | |
| 1023 | .frame(maxHeight: .infinity) | |
| 1024 | .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in | |
| 1025 | if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() } | |
| 1026 | } | |
| 1027 | .gesture(DragGesture(minimumDistance: 1).onChanged { drag in | |
| 1028 | let base = start ?? width | |
| 1029 | start = base | |
| 1030 | width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound) | |
| 1031 | }.onEnded { _ in start = nil })) | |
| 1032 | .accessibilityHidden(true) | |
| 1033 | } | |
| 1034 | } | |
| 1035 | ||
| 1036 | /// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits. | |
| 1037 | struct BufferTabs: View { | |
| 1038 | let session: DocumentSession | |
| 1039 | @Environment(\.orgTheme) private var theme | |
| 1040 | ||
| 1041 | var body: some View { | |
| 1042 | ScrollView(.horizontal, showsIndicators: false) { | |
| 1043 | HStack(spacing: 0) { | |
| 1044 | ForEach(session.openPaths, id: \.self) { path in | |
| 1045 | tab(path) | |
| 1046 | } | |
| 1047 | } | |
| 1048 | } | |
| 1049 | .frame(height: 28) | |
| 1050 | .background { Rectangle().fill(theme.color("modeline-background").map(AnyShapeStyle.init) ?? AnyShapeStyle(.bar)) } | |
| 1051 | .overlay(alignment: .bottom) { Divider() } | |
| 1052 | } | |
| 1053 | ||
| 1054 | private func tab(_ path: String) -> some View { | |
| 1055 | let current = path == session.path | |
| 1056 | return HStack(spacing: 6) { | |
| 1057 | Text(session.bufferName(path)) | |
| 1058 | .lineLimit(1) | |
| 1059 | .foregroundStyle(current ? .primary : .secondary) | |
| 1060 | .accessibilityAddTraits(current ? [.isButton, .isSelected] : .isButton) | |
| 1061 | .accessibilityAction { session.open(path) } | |
| 1062 | Button { | |
| 1063 | if path == session.path { | |
| 1064 | if UnsavedChanges.resolve(session) { session.kill(path) } | |
| 1065 | } else if UnsavedChanges.resolve(session, paths: [path]) { | |
| 1066 | session.kill(path) | |
| 1067 | } | |
| 1068 | } label: { | |
| 1069 | Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark") | |
| 1070 | .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold)) | |
| 1071 | .frame(width: 12, height: 12) | |
| 1072 | } | |
| 1073 | .buttonStyle(.borderless) | |
| 1074 | .help("Close") | |
| 1075 | .accessibilityLabel("Close \(session.bufferName(path))" + (session.dirtyPaths.contains(path) ? ", unsaved" : "")) | |
| 1076 | } | |
| 1077 | .font(.callout) | |
| 1078 | .padding(.horizontal, 12) | |
| 1079 | .frame(maxHeight: .infinity) | |
| 1080 | // A shape, not a color: a color background runs up under the toolbar. | |
| 1081 | .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) } | |
| 1082 | .overlay(alignment: .trailing) { Divider() } | |
| 1083 | .contentShape(Rectangle()) | |
| 1084 | .onTapGesture { session.open(path) } | |
| 1085 | .help(path) | |
| 1086 | } | |
| 1087 | } | |
| 1088 | ||
| 1089 | enum Panel: Identifiable { | |
| 1090 | case columns(UUID, ColumnView.View) | |
| 1091 | case export(UUID, URL) | |
| 1092 | case conflict(UUID) | |
| 1093 | case syncCopies(UUID) | |
| 1094 | case recovery(UUID) | |
| 1095 | ||
| 1096 | var id: UUID { | |
| 1097 | switch self { | |
| 1098 | case .columns(let id, _), .export(let id, _), .conflict(let id), .syncCopies(let id), .recovery(let id): id | |
| 1099 | } | |
| 1100 | } | |
| 1101 | } | |
| 1102 | ||
| 1103 | struct BlockEditRequest: Identifiable { | |
| 1104 | let id = UUID() | |
| 1105 | let edit: BlockEdit | |
| 1106 | } | |
Sources/Orgstar/Panels.swift added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | ||
| 4 | enum Panel: Identifiable { | |
| 5 | case columns(UUID, ColumnView.View) | |
| 6 | case export(UUID, URL) | |
| 7 | case conflict(UUID) | |
| 8 | case syncCopies(UUID) | |
| 9 | case recovery(UUID) | |
| 10 | ||
| 11 | var id: UUID { | |
| 12 | switch self { | |
| 13 | case .columns(let id, _), .export(let id, _), .conflict(let id), .syncCopies(let id), .recovery(let id): id | |
| 14 | } | |
| 15 | } | |
| 16 | } | |
| 17 | ||
| 18 | struct BlockEditRequest: Identifiable { | |
| 19 | let id = UUID() | |
| 20 | let edit: BlockEdit | |
| 21 | } | |
Sources/Orgstar/SearchViews.swift added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgApp | |
| 3 | import OrgIndex | |
| 4 | import OrgWorkspace | |
| 5 | import SwiftUI | |
| 6 | ||
| 7 | struct SearchResults: View { | |
| 8 | let results: [HeadingLocation] | |
| 9 | let open: (HeadingLocation) -> Void | |
| 10 | ||
| 11 | var body: some View { | |
| 12 | List(results, id: \.self) { location in | |
| 13 | Button { | |
| 14 | open(location) | |
| 15 | } label: { | |
| 16 | VStack(alignment: .leading, spacing: 2) { | |
| 17 | Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1) | |
| 18 | Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary) | |
| 19 | } | |
| 20 | } | |
| 21 | .buttonStyle(.plain) | |
| 22 | } | |
| 23 | .overlay { | |
| 24 | if results.isEmpty { ContentUnavailableView.search } | |
| 25 | } | |
| 26 | } | |
| 27 | } | |
| 28 | ||
| 29 | struct QuickOpenView: View { | |
| 30 | let workspace: WorkspaceModel | |
| 31 | let open: (FileEntry) -> Void | |
| 32 | @State private var query = "" | |
| 33 | /// The highlighted match, moved by ↑/↓ or C-p/C-n and opened by Return. | |
| 34 | @State private var selected = 0 | |
| 35 | @Environment(\.dismiss) private var dismiss | |
| 36 | ||
| 37 | var body: some View { | |
| 38 | let matches = workspace.quickOpen(query) | |
| 39 | let current = min(selected, matches.count - 1) | |
| 40 | VStack(spacing: 0) { | |
| 41 | TextField("Open file", text: $query) | |
| 42 | .textFieldStyle(.plain) | |
| 43 | .font(.title3) | |
| 44 | .padding(12) | |
| 45 | .onSubmit { if current >= 0 { open(matches[current]) } } | |
| 46 | .onKeyPress(phases: .down) { press in | |
| 47 | let control = press.modifiers == .control | |
| 48 | let step = if press.key == .downArrow || control && press.characters == "n" { 1 } | |
| 49 | else if press.key == .upArrow || control && press.characters == "p" { -1 } else { 0 } | |
| 50 | guard step != 0 else { return .ignored } | |
| 51 | selected = max(0, min(current + step, matches.count - 1)) | |
| 52 | return .handled | |
| 53 | } | |
| 54 | .onChange(of: query) { selected = 0 } | |
| 55 | Divider() | |
| 56 | ScrollViewReader { proxy in | |
| 57 | List(matches.indices, id: \.self) { index in | |
| 58 | let entry = matches[index] | |
| 59 | Button { | |
| 60 | open(entry) | |
| 61 | } label: { | |
| 62 | VStack(alignment: .leading, spacing: 2) { | |
| 63 | Text(entry.name) | |
| 64 | Text(entry.relativePath).font(.caption).foregroundStyle(.secondary) | |
| 65 | } | |
| 66 | .frame(maxWidth: .infinity, alignment: .leading) | |
| 67 | .contentShape(Rectangle()) | |
| 68 | } | |
| 69 | .buttonStyle(.plain) | |
| 70 | .listRowBackground(index == current ? Color.accentColor.opacity(0.25) : Color.clear) | |
| 71 | .accessibilityAddTraits(index == current ? .isSelected : []) | |
| 72 | } | |
| 73 | .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } } | |
| 74 | } | |
| 75 | } | |
| 76 | .frame(width: 520, height: 360) | |
| 77 | .onExitCommand { dismiss() } | |
| 78 | } | |
| 79 | } | |
Sources/Orgstar/Sidebar.swift added +145
| @@ -0,0 +1,145 @@ | ||
| 1 | import OrgApp | |
| 2 | import OrgCore | |
| 3 | import OrgWorkspace | |
| 4 | import SwiftUI | |
| 5 | import UniformTypeIdentifiers | |
| 6 | ||
| 7 | struct Sidebar: View { | |
| 8 | let workspace: WorkspaceModel | |
| 9 | let session: DocumentSession | |
| 10 | @Binding var selection: String? | |
| 11 | var addFolder: () -> Void = {} | |
| 12 | /// Folders shown collapsed, by path, one per line. | |
| 13 | @AppStorage("collapsedFolders") private var collapsedText = "" | |
| 14 | @State private var removing: String? | |
| 15 | /// A file operation waiting for a name or a confirmation. | |
| 16 | @Environment(\.orgTheme) private var theme | |
| 17 | @State var pending: FileOperation? | |
| 18 | @State var name = "" | |
| 19 | @State var failure: String? | |
| 20 | ||
| 21 | private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) } | |
| 22 | ||
| 23 | private func expanded(_ root: String) -> Binding<Bool> { | |
| 24 | Binding { | |
| 25 | !collapsed.contains(root) | |
| 26 | } set: { isExpanded in | |
| 27 | var set = collapsed | |
| 28 | if isExpanded { set.remove(root) } else { set.insert(root) } | |
| 29 | collapsedText = set.sorted().joined(separator: "\n") | |
| 30 | } | |
| 31 | } | |
| 32 | ||
| 33 | var body: some View { | |
| 34 | List(selection: $selection) { | |
| 35 | ForEach(workspace.rootPaths, id: \.self) { root in | |
| 36 | Section(isExpanded: expanded(root)) { | |
| 37 | OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in | |
| 38 | Label(node.name, systemImage: icon(node)) | |
| 39 | .foregroundStyle(node.file?.kind == .conflict ? .orange : node.isDownloading ? .secondary : theme.color("sidebar-foreground") ?? .primary) | |
| 40 | .help(node.isDownloading ? "Downloading from iCloud" : "") | |
| 41 | .tag(node.file?.path) | |
| 42 | .contextMenu { fileMenu(node) } | |
| 43 | } | |
| 44 | } header: { | |
| 45 | Text((root as NSString).lastPathComponent) | |
| 46 | .foregroundStyle(theme.color("sidebar-header") ?? .secondary) | |
| 47 | .help(root) | |
| 48 | .contextMenu { folderMenu(root) } | |
| 49 | } | |
| 50 | } | |
| 51 | } | |
| 52 | .listStyle(.sidebar) | |
| 53 | .themedListBackground(theme.color("sidebar-background")) | |
| 54 | .safeAreaInset(edge: .bottom, spacing: 0) { | |
| 55 | HStack(spacing: 4) { | |
| 56 | Button("Add Folder…", systemImage: "plus", action: addFolder) | |
| 57 | .help("Add a folder (⇧⌘O)") | |
| 58 | Menu { | |
| 59 | ForEach(workspace.rootPaths, id: \.self) { root in | |
| 60 | Button((root as NSString).lastPathComponent) { removing = root } | |
| 61 | } | |
| 62 | } label: { | |
| 63 | Label("Remove Folder", systemImage: "minus") | |
| 64 | } | |
| 65 | .menuIndicator(.hidden) | |
| 66 | .fixedSize() | |
| 67 | .disabled(workspace.rootPaths.isEmpty) | |
| 68 | .help("Remove a folder from the sidebar") | |
| 69 | Spacer() | |
| 70 | } | |
| 71 | .labelStyle(.iconOnly) | |
| 72 | .buttonStyle(.borderless) | |
| 73 | .menuStyle(.borderlessButton) | |
| 74 | .padding(.horizontal, 10) | |
| 75 | .padding(.vertical, 6) | |
| 76 | } | |
| 77 | .confirmationDialog( | |
| 78 | "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?", | |
| 79 | isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } } | |
| 80 | ) { | |
| 81 | Button("Remove") { | |
| 82 | if let root = removing { try? workspace.removeRoot(path: root) } | |
| 83 | removing = nil | |
| 84 | } | |
| 85 | } message: { | |
| 86 | Text("The folder and its files stay on disk.") | |
| 87 | } | |
| 88 | .fileOperations(self) | |
| 89 | } | |
| 90 | ||
| 91 | @ViewBuilder | |
| 92 | private func folderMenu(_ root: String) -> some View { | |
| 93 | Button("New File…") { ask(.create(folder: root)) } | |
| 94 | Divider() | |
| 95 | Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() } | |
| 96 | Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) } | |
| 97 | Divider() | |
| 98 | Button("Remove from Sidebar…") { removing = root } | |
| 99 | } | |
| 100 | ||
| 101 | private func icon(_ node: FileTreeNode) -> String { | |
| 102 | if node.isDownloading { return "icloud.and.arrow.down" } | |
| 103 | guard let file = node.file else { return "folder" } | |
| 104 | switch file.kind { | |
| 105 | case .org: return "doc.text" | |
| 106 | case .archive: return "archivebox" | |
| 107 | case .conflict: return "exclamationmark.triangle" | |
| 108 | case .other: | |
| 109 | guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" } | |
| 110 | if type.conforms(to: .image) { return "photo" } | |
| 111 | if type.conforms(to: .pdf) { return "doc.richtext" } | |
| 112 | if type.conforms(to: .audiovisualContent) { return "play.rectangle" } | |
| 113 | if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" } | |
| 114 | if type.conforms(to: .text) { return "doc.plaintext" } | |
| 115 | return "doc" | |
| 116 | } | |
| 117 | } | |
| 118 | } | |
| 119 | ||
| 120 | struct OutlineColumn: View { | |
| 121 | let session: DocumentSession | |
| 122 | @Environment(\.orgTheme) private var theme | |
| 123 | ||
| 124 | var body: some View { | |
| 125 | List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in | |
| 126 | Button { | |
| 127 | session.reveal(entry.start) | |
| 128 | } label: { | |
| 129 | Text(entry.title.isEmpty ? "(untitled)" : entry.title) | |
| 130 | .foregroundStyle(theme.color("sidebar-foreground") ?? .primary) | |
| 131 | .lineLimit(1) | |
| 132 | .padding(.leading, CGFloat(entry.level - 1) * 12) | |
| 133 | } | |
| 134 | .buttonStyle(.plain) | |
| 135 | } | |
| 136 | .themedListBackground(theme.color("sidebar-background")) | |
| 137 | .overlay { | |
| 138 | if session.path != nil, !session.isOrg { | |
| 139 | ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline.")) | |
| 140 | } else if session.path != nil, session.outline.isEmpty { | |
| 141 | ContentUnavailableView("No headings", systemImage: "list.bullet.indent") | |
| 142 | } | |
| 143 | } | |
| 144 | } | |
| 145 | } | |
Sources/OrgstarMobile/MobileEditor+Display.swift added +209
| @@ -0,0 +1,209 @@ | ||
| 1 | #if os(iOS) | |
| 2 | import OrgApp | |
| 3 | import OrgCore | |
| 4 | import OrgDocument | |
| 5 | import OrgHighlight | |
| 6 | import OrgPresentation | |
| 7 | import UIKit | |
| 8 | ||
| 9 | extension MobileEditor { | |
| 10 | // MARK: - Shrunk table columns | |
| 11 | ||
| 12 | /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`, | |
| 13 | /// `expand` for `org-table-expand`. | |
| 14 | func tableColumnWidth(_ id: String) { | |
| 15 | switch shrunk.change(for: id, at: textView.selectedRange.location, in: textView.textStorage.string) { | |
| 16 | case .notInTable: onMessage?("Not in a table") | |
| 17 | case .set(let columns, let table): setShrunk(columns, in: table) | |
| 18 | case .ask(let table, let current, let max): | |
| 19 | onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in | |
| 20 | guard let self, let answer else { return } | |
| 21 | self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table) | |
| 22 | } | |
| 23 | } | |
| 24 | } | |
| 25 | ||
| 26 | /// Narrows `columns` of `table` and widens its others. | |
| 27 | private func setShrunk(_ columns: [Int], in table: Range<Int>) { | |
| 28 | shrunk.set(columns, in: table, text: textView.textStorage.string) | |
| 29 | restyle(table) | |
| 30 | invalidateLayout(lines: [table]) | |
| 31 | } | |
| 32 | ||
| 33 | /// Hides each shrunk segment's text and draws its display where the text was, as pretty | |
| 34 | /// entities draw theirs. | |
| 35 | func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) { | |
| 36 | guard !shrunk.isEmpty else { return } | |
| 37 | let cell = theme.column | |
| 38 | for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length { | |
| 39 | let r = segment.range | |
| 40 | let shown = segment.display.count | |
| 41 | let kept = min(shown, r.count) | |
| 42 | if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) } | |
| 43 | guard kept > 0 else { continue } | |
| 44 | let visible = NSRange(location: r.upperBound - kept, length: kept) | |
| 45 | let color = storage.attribute(.foregroundColor, at: visible.location, effectiveRange: nil) as? UIColor ?? theme.foreground | |
| 46 | storage.addAttribute(.foregroundColor, value: UIColor.clear, range: visible) | |
| 47 | storage.addAttributes([.orgEntityDisplay: segment.display, .orgEntityColor: color], range: NSRange(location: visible.location, length: 1)) | |
| 48 | if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) } | |
| 49 | } | |
| 50 | } | |
| 51 | ||
| 52 | // MARK: - Inline images | |
| 53 | ||
| 54 | func toggleImages() { | |
| 55 | showsImages.toggle() | |
| 56 | restyleAll() | |
| 57 | if showsImages { | |
| 58 | let ns = textView.textStorage.string as NSString | |
| 59 | var count = 0 | |
| 60 | var offset = 0 | |
| 61 | while offset < ns.length { | |
| 62 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) | |
| 63 | if let image = InlineImages.image(atLine: line.location, in: ns), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 } | |
| 64 | offset = NSMaxRange(line) | |
| 65 | } | |
| 66 | onMessage?("\(count) images displayed inline") | |
| 67 | } else { | |
| 68 | onMessage?("Inline image display turned off") | |
| 69 | } | |
| 70 | } | |
| 71 | ||
| 72 | /// An image link's image, by its path or one relative to `baseDirectory`. | |
| 73 | static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? { | |
| 74 | let expanded = (path as NSString).expandingTildeInPath | |
| 75 | let url: URL | |
| 76 | if expanded.hasPrefix("/") { | |
| 77 | url = URL(fileURLWithPath: expanded) | |
| 78 | } else if let baseDirectory { | |
| 79 | url = baseDirectory.appendingPathComponent(expanded) | |
| 80 | } else { | |
| 81 | return nil | |
| 82 | } | |
| 83 | let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0 | |
| 84 | let key = "\(url.path)|\(modified)" as NSString | |
| 85 | if let cached = Self.imageCache.object(forKey: key) { return cached } | |
| 86 | guard let image = UIImage(contentsOfFile: url.path) else { return nil } | |
| 87 | Self.imageCache.setObject(image, forKey: key) | |
| 88 | return image | |
| 89 | } | |
| 90 | ||
| 91 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is | |
| 92 | /// on the line. | |
| 93 | func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { | |
| 94 | guard showsImages else { return } | |
| 95 | let text = storage.string as NSString | |
| 96 | let inset = textView.textContainerInset | |
| 97 | let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40) | |
| 98 | var location = range.lowerBound | |
| 99 | while location < range.upperBound, location < text.length { | |
| 100 | let line = text.lineRange(for: NSRange(location: location, length: 0)) | |
| 101 | location = NSMaxRange(line) | |
| 102 | guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue } | |
| 103 | let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth) | |
| 104 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 | |
| 105 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) | |
| 106 | // Invisible, keeping the line's height. | |
| 107 | if line.location != revealed.location, content.length > 0 { | |
| 108 | storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content) | |
| 109 | } | |
| 110 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length))) | |
| 111 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() | |
| 112 | // The image sits where the line is; the spacing makes room for the rest of it. | |
| 113 | style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight) | |
| 114 | storage.addAttribute(.paragraphStyle, value: style, range: line) | |
| 115 | } | |
| 116 | } | |
| 117 | ||
| 118 | // MARK: - Truncation | |
| 119 | ||
| 120 | /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead | |
| 121 | /// of wrapping. | |
| 122 | var truncatesLines: Bool { | |
| 123 | get { (textView as? KeyedTextView)?.truncates ?? false } | |
| 124 | set { | |
| 125 | guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return } | |
| 126 | keepingTopLine { | |
| 127 | view.truncates = newValue | |
| 128 | if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } | |
| 129 | } | |
| 130 | } | |
| 131 | } | |
| 132 | ||
| 133 | // MARK: - Folding | |
| 134 | ||
| 135 | func setFolds(_ state: FoldState) { | |
| 136 | fold = state | |
| 137 | updateHidden() | |
| 138 | } | |
| 139 | ||
| 140 | func updateHidden() { | |
| 141 | let tree = document.tree | |
| 142 | let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden } | |
| 143 | let before = hidden.folded | |
| 144 | let oldHidden = hidden.all | |
| 145 | hidden.set( | |
| 146 | Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers), | |
| 147 | folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds) | |
| 148 | ) | |
| 149 | // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment. | |
| 150 | let storage = textView.textStorage | |
| 151 | let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length } | |
| 152 | if !changed.isEmpty { | |
| 153 | let text = storage.string as NSString | |
| 154 | storage.beginEditing() | |
| 155 | for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) } | |
| 156 | storage.endEditing() | |
| 157 | } | |
| 158 | invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all))) | |
| 159 | textView.setNeedsDisplay() | |
| 160 | } | |
| 161 | ||
| 162 | /// TAB at the caret: a heading cycles, a drawer or block opens or closes. | |
| 163 | @discardableResult | |
| 164 | func cycleAtCaret() -> Bool { | |
| 165 | guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false } | |
| 166 | setFolds(next) | |
| 167 | return true | |
| 168 | } | |
| 169 | ||
| 170 | /// Shift-TAB: overview, contents, show all. | |
| 171 | func cycleGlobal() { | |
| 172 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds) | |
| 173 | globalVisibility = visibility | |
| 174 | setFolds(state) | |
| 175 | } | |
| 176 | ||
| 177 | /// Opens the folds hiding `offset`. | |
| 178 | func unfold(around offset: Int) { | |
| 179 | var state = fold | |
| 180 | for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end { | |
| 181 | state.folds.remove(entry.start) | |
| 182 | state.bodyFolds.remove(entry.start) | |
| 183 | } | |
| 184 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true { | |
| 185 | state.wrapperFolds.remove(start) | |
| 186 | } | |
| 187 | if state != fold { setFolds(state) } | |
| 188 | } | |
| 189 | ||
| 190 | /// Shows the heading at `offset`, unfolded, at the top. | |
| 191 | func reveal(_ offset: Int) { | |
| 192 | let length = textView.textStorage.length | |
| 193 | let target = min(max(0, offset), length) | |
| 194 | unfold(around: target) | |
| 195 | textView.selectedRange = NSRange(location: target, length: 0) | |
| 196 | textView.scrollRangeToVisible(NSRange(location: target, length: 0)) | |
| 197 | } | |
| 198 | ||
| 199 | /// The caret left hidden text (a tap past a fold): what hides it opens. | |
| 200 | func selectionChanged() { | |
| 201 | let interval = Perf.begin("editor.selection") | |
| 202 | defer { interval.end() } | |
| 203 | redrawSelectedBlocks() | |
| 204 | let caret = textView.selectedRange.location | |
| 205 | if hidden.containing(caret) != nil { unfold(around: caret) } | |
| 206 | revealCaretLine() | |
| 207 | } | |
| 208 | } | |
| 209 | #endif | |
Sources/OrgstarMobile/MobileEditor+Styling.swift added +250
| @@ -0,0 +1,250 @@ | ||
| 1 | #if os(iOS) | |
| 2 | import OrgApp | |
| 3 | import OrgCore | |
| 4 | import OrgDocument | |
| 5 | import OrgHighlight | |
| 6 | import OrgPresentation | |
| 7 | import UIKit | |
| 8 | ||
| 9 | extension MobileEditor { | |
| 10 | // MARK: - Styling | |
| 11 | ||
| 12 | func load(_ text: String) { | |
| 13 | loading = true | |
| 14 | textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base)) | |
| 15 | loading = false | |
| 16 | shaded.set(Presentation.shadedBlocks(document.tree), folded: []) | |
| 17 | restyle(0..<(text as NSString).length) | |
| 18 | textView.typingAttributes = theme.base | |
| 19 | } | |
| 20 | ||
| 21 | /// The text view's own colors, and the block band's. | |
| 22 | func applyThemeToView() { | |
| 23 | textView.backgroundColor = theme.color("background") ?? .systemBackground | |
| 24 | textView.tintColor = theme.color("cursor") | |
| 25 | textView.typingAttributes = theme.base | |
| 26 | fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width) | |
| 27 | themeSelection() | |
| 28 | } | |
| 29 | ||
| 30 | /// The selection in the theme's selection color: the text view's selection display | |
| 31 | /// interaction draws it with our highlight view; the cursor and handles keep the tint. | |
| 32 | private func themeSelection() { | |
| 33 | guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return } | |
| 34 | let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView() | |
| 35 | view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25) | |
| 36 | if interaction.highlightView !== view { interaction.highlightView = view } | |
| 37 | selectionColor = view.color | |
| 38 | } | |
| 39 | ||
| 40 | /// The highlight view draws under the text, so a block's band would cover it: blocks the | |
| 41 | /// selection enters or leaves are laid out again to draw it over their band. | |
| 42 | func redrawSelectedBlocks() { | |
| 43 | let selected = textView.selectedRange | |
| 44 | let range = selected.length > 0 ? selected.location..<NSMaxRange(selected) : nil | |
| 45 | let old = fragmentStyle.selection?.range | |
| 46 | fragmentStyle.set(selection: range, color: selectionColor) | |
| 47 | let touched = [old, range].compactMap { $0 } | |
| 48 | redraw(blocks: shaded.all.filter { block in touched.contains { $0.overlaps(block) } }) | |
| 49 | } | |
| 50 | ||
| 51 | /// Lays `blocks` out again and asks their fragments, which are kept across layout passes, | |
| 52 | /// to draw again. | |
| 53 | private func redraw(blocks: [Range<Int>]) { | |
| 54 | guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return } | |
| 55 | for block in blocks { | |
| 56 | guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound), | |
| 57 | let end = content.location(start, offsetBy: block.count), | |
| 58 | let textRange = NSTextRange(location: start, end: end) else { continue } | |
| 59 | manager.invalidateRenderingAttributes(for: textRange) | |
| 60 | manager.invalidateLayout(for: textRange) | |
| 61 | } | |
| 62 | textView.setNeedsDisplay() | |
| 63 | } | |
| 64 | ||
| 65 | /// The band behind blocks spans the view's width, or the widest line's when truncated; | |
| 66 | /// images are as wide as the view allows. Only the blocks read the band's width, so a | |
| 67 | /// wider line in a truncated file, which widens the band on each layout pass, redraws | |
| 68 | /// the blocks alone: laying the whole file out again moves the text under the view. | |
| 69 | func viewResized() { | |
| 70 | let band = fragmentStyle.blockBand | |
| 71 | let width = max(textView.bounds.width, truncatesLines ? textView.contentSize.width : 0) | |
| 72 | let resized = imageWidth != textView.bounds.width | |
| 73 | guard band.width != width || resized else { return } | |
| 74 | fragmentStyle.set(blockBackground: band.color, width: width) | |
| 75 | imageWidth = textView.bounds.width | |
| 76 | guard resized else { | |
| 77 | redraw(blocks: shaded.all) | |
| 78 | return | |
| 79 | } | |
| 80 | keepingTopLine { | |
| 81 | if showsImages { restyle(0..<textView.textStorage.length) } | |
| 82 | if let manager = textView.textLayoutManager { | |
| 83 | manager.invalidateRenderingAttributes(for: manager.documentRange) | |
| 84 | manager.invalidateLayout(for: manager.documentRange) | |
| 85 | } | |
| 86 | } | |
| 87 | } | |
| 88 | ||
| 89 | /// Styles the whole file again. | |
| 90 | func restyleAll() { | |
| 91 | let interval = Perf.begin("editor.restyleAll") | |
| 92 | defer { interval.end() } | |
| 93 | keepingTopLine { | |
| 94 | restyle(0..<textView.textStorage.length) | |
| 95 | if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } | |
| 96 | } | |
| 97 | } | |
| 98 | ||
| 99 | /// Lays out `ranges` again, each widened to whole lines and to the line before it: the | |
| 100 | /// heading or opening line of a fold, whose fragment draws the fold mark. Laying out the | |
| 101 | /// whole file again makes TextKit estimate the height of everything above the view afresh, | |
| 102 | /// which moves the text under it. | |
| 103 | func invalidateLayout(lines ranges: [Range<Int>]) { | |
| 104 | guard !ranges.isEmpty, let manager = textView.textLayoutManager, let content = manager.textContentManager else { return } | |
| 105 | let text = textView.textStorage.string as NSString | |
| 106 | for range in ranges { | |
| 107 | let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location | |
| 108 | let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0))) | |
| 109 | guard let start = content.location(content.documentRange.location, offsetBy: lower), | |
| 110 | let end = content.location(start, offsetBy: upper - lower), | |
| 111 | let textRange = NSTextRange(location: start, end: end) else { continue } | |
| 112 | manager.invalidateLayout(for: textRange) | |
| 113 | } | |
| 114 | } | |
| 115 | ||
| 116 | /// Runs `change`, which lays the whole file out again, and brings the line that was at the | |
| 117 | /// top of the view back there. TextKit estimates the height of text it hasn't laid out, | |
| 118 | /// so the same scroll position lands on different text after a fresh layout. | |
| 119 | func keepingTopLine(_ change: () -> Void) { | |
| 120 | guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return change() } | |
| 121 | let inset = textView.textContainerInset | |
| 122 | let top = textView.contentOffset.y + textView.adjustedContentInset.top - inset.top | |
| 123 | let start = content.documentRange.location | |
| 124 | let anchor = manager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map { | |
| 125 | (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY) | |
| 126 | } | |
| 127 | change() | |
| 128 | guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset), | |
| 129 | let above = NSTextRange(location: start, end: location) else { return } | |
| 130 | manager.ensureLayout(for: above) | |
| 131 | guard let fragment = manager.textLayoutFragment(for: location) else { return } | |
| 132 | let frame = fragment.layoutFragmentFrame | |
| 133 | manager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * textView.bounds.height)) | |
| 134 | // The view grows to the laid-out height on its next layout pass; the scroll needs it now. | |
| 135 | let needed = manager.usageBoundsForTextContainer.maxY + inset.top + inset.bottom | |
| 136 | if textView.contentSize.height < needed { textView.contentSize.height = needed } | |
| 137 | let y = frame.minY + inset.top + max(0, min(anchor.within, frame.height)) - textView.adjustedContentInset.top | |
| 138 | textView.contentOffset = CGPoint(x: textView.contentOffset.x, y: y) | |
| 139 | } | |
| 140 | ||
| 141 | /// Styles are set after the edit has been processed, as TextKit asks. | |
| 142 | func scheduleRestyle(_ range: Range<Int>) { | |
| 143 | if let pending = restyleScheduled { | |
| 144 | restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound) | |
| 145 | return | |
| 146 | } | |
| 147 | restyleScheduled = range | |
| 148 | DispatchQueue.main.async { [weak self] in | |
| 149 | guard let self, let range = self.restyleScheduled else { return } | |
| 150 | self.restyleScheduled = nil | |
| 151 | self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: []) | |
| 152 | // Small files are restyled whole: a heading or block line changes what follows it. | |
| 153 | let length = self.textView.textStorage.length | |
| 154 | self.restyle(length < 60_000 ? 0..<length : range) | |
| 155 | self.updateHidden() | |
| 156 | self.textView.typingAttributes = self.theme.base | |
| 157 | } | |
| 158 | } | |
| 159 | ||
| 160 | private var caretLine: NSRange { | |
| 161 | let text = textView.textStorage.string as NSString | |
| 162 | return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0)) | |
| 163 | } | |
| 164 | ||
| 165 | /// Sets attributes for the whole lines in `range`, as the Mac editor does. | |
| 166 | func restyle(_ range: Range<Int>) { | |
| 167 | let interval = Perf.begin("editor.restyle") | |
| 168 | defer { interval.end() } | |
| 169 | let storage = textView.textStorage | |
| 170 | let ns = storage.string as NSString | |
| 171 | guard ns.length > 0 else { return } | |
| 172 | let lower = min(range.lowerBound, ns.length) | |
| 173 | let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower))) | |
| 174 | let whole = lines.location..<NSMaxRange(lines) | |
| 175 | storage.beginEditing() | |
| 176 | storage.setAttributes(theme.base, range: lines) | |
| 177 | if indented { | |
| 178 | for line in Presentation.lineIndents(document.tree, in: whole) { | |
| 179 | storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) | |
| 180 | } | |
| 181 | } | |
| 182 | let revealed = caretLine | |
| 183 | var scriptExclusions: [Range<Int>] = [] | |
| 184 | for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) { | |
| 185 | let clipped = NSIntersectionRange(NSRange(run.range), lines) | |
| 186 | guard clipped.length > 0 else { continue } | |
| 187 | if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue } | |
| 188 | if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 { | |
| 189 | storage.addAttributes(theme.hidden, range: clipped) | |
| 190 | } else { | |
| 191 | theme.apply(run.role, to: storage, range: clipped) | |
| 192 | } | |
| 193 | if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } | |
| 194 | } | |
| 195 | if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) } | |
| 196 | applyShrunk(whole, in: storage) | |
| 197 | applyImages(whole, in: storage, revealed: revealed) | |
| 198 | storage.endEditing() | |
| 199 | } | |
| 200 | ||
| 201 | func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle { | |
| 202 | if let style = paragraphStyles[[firstLine, wrapped]] { return style } | |
| 203 | let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped) | |
| 204 | paragraphStyles[[firstLine, wrapped]] = style | |
| 205 | return style | |
| 206 | } | |
| 207 | ||
| 208 | /// `org-pretty-entities`: entities drawn as their character over the entity's last | |
| 209 | /// character (the rest hidden), sub/superscripts raised without their markers. | |
| 210 | private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) { | |
| 211 | let runs = Presentation.prettyRuns( | |
| 212 | storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil }, | |
| 213 | scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces | |
| 214 | ) | |
| 215 | for (lineStart, run) in runs { | |
| 216 | switch run { | |
| 217 | case .entity(let r, let display): | |
| 218 | let start = lineStart + r.lowerBound | |
| 219 | let last = lineStart + r.upperBound - 1 | |
| 220 | let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground | |
| 221 | if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) } | |
| 222 | storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1)) | |
| 223 | case .script(let markers, let body, let superscript): | |
| 224 | for marker in markers { | |
| 225 | storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count)) | |
| 226 | } | |
| 227 | let size = theme.font.pointSize | |
| 228 | storage.addAttributes([ | |
| 229 | .font: theme.font.withSize(size * 0.7), | |
| 230 | .baselineOffset: (superscript ? 0.3 : -0.3) * size, | |
| 231 | ], range: NSRange(location: lineStart + body.lowerBound, length: body.count)) | |
| 232 | } | |
| 233 | } | |
| 234 | } | |
| 235 | ||
| 236 | /// Moving to another line shows its markup and hides the last one's. | |
| 237 | func revealCaretLine() { | |
| 238 | guard !showMarkup else { return } | |
| 239 | let line = caretLine | |
| 240 | guard line != revealedLine else { return } | |
| 241 | let text = textView.textStorage.string as NSString | |
| 242 | // The old line may have moved with edits since; restyle the line now at its start. | |
| 243 | let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil } | |
| 244 | revealedLine = line | |
| 245 | for range in [old, line].compactMap({ $0 }) { | |
| 246 | restyle(range.location..<NSMaxRange(range)) | |
| 247 | } | |
| 248 | } | |
| 249 | } | |
| 250 | #endif | |
Sources/OrgstarMobile/MobileEditor.swift +15 −693
| @@ -6,97 +6,6 @@ import OrgHighlight | ||
| 6 | 6 | import OrgPresentation |
| 7 | 7 | import UIKit |
| 8 | 8 | |
| 9 | /// Ranges read by TextKit's delegate callbacks. | |
| 10 | final class LockedRanges: @unchecked Sendable { | |
| 11 | private let lock = NSLock() | |
| 12 | private var ranges: [Range<Int>] = [] | |
| 13 | private var starts: Set<Int> = [] | |
| 14 | ||
| 15 | func set(_ new: [Range<Int>], folded: Set<Int>) { lock.withLock { ranges = new; starts = folded } } | |
| 16 | var all: [Range<Int>] { lock.withLock { ranges } } | |
| 17 | func covers(_ start: Int, _ end: Int) -> Bool { lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } } } | |
| 18 | func isFolded(_ start: Int) -> Bool { lock.withLock { starts.contains(start) } } | |
| 19 | var folded: Set<Int> { lock.withLock { starts } } | |
| 20 | func containing(_ offset: Int) -> Range<Int>? { lock.withLock { ranges.first { $0.contains(offset) } } } | |
| 21 | } | |
| 22 | ||
| 23 | /// What layout fragments draw beyond the text, read by TextKit's delegate callbacks. | |
| 24 | final class FragmentStyle: @unchecked Sendable { | |
| 25 | private let lock = NSLock() | |
| 26 | private var band: (color: UIColor, width: CGFloat) = (.clear, 0) | |
| 27 | private var selected: (range: Range<Int>, color: UIColor)? | |
| 28 | ||
| 29 | func set(blockBackground color: UIColor, width: CGFloat) { lock.withLock { band = (color, width) } } | |
| 30 | var blockBand: (color: UIColor, width: CGFloat) { lock.withLock { band } } | |
| 31 | /// The selection, which a block's fragment draws over its band, as the Mac's fragments do. | |
| 32 | func set(selection range: Range<Int>?, color: UIColor) { lock.withLock { selected = range.map { ($0, color) } } } | |
| 33 | var selection: (range: Range<Int>, color: UIColor)? { lock.withLock { selected } } | |
| 34 | } | |
| 35 | ||
| 36 | /// A text view that offers hardware-keyboard presses to the editor's keymap first. | |
| 37 | final class KeyedTextView: UITextView { | |
| 38 | var keyHandler: ((UIKey) -> Bool)? | |
| 39 | /// Keys the editor took, whose release the text system doesn't see. Optional: made by | |
| 40 | /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values. | |
| 41 | private var handled: Set<UIKeyboardHIDUsage>? | |
| 42 | /// Called after each layout pass, as the view's size settles. | |
| 43 | var onLayout: (() -> Void)? | |
| 44 | /// The text container's width while lines are truncated. | |
| 45 | static let truncatedWidth: CGFloat = 100_000 | |
| 46 | ||
| 47 | /// Long lines run off the right edge and the view scrolls sideways. | |
| 48 | var truncates: Bool { | |
| 49 | get { !textContainer.widthTracksTextView } | |
| 50 | set { | |
| 51 | textContainer.widthTracksTextView = !newValue | |
| 52 | if newValue { | |
| 53 | textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude) | |
| 54 | } else { | |
| 55 | textContainer.size = CGSize(width: bounds.width - textContainerInset.left - textContainerInset.right, height: CGFloat.greatestFiniteMagnitude) | |
| 56 | contentOffset.x = 0 | |
| 57 | } | |
| 58 | showsHorizontalScrollIndicator = newValue | |
| 59 | setNeedsLayout() | |
| 60 | } | |
| 61 | } | |
| 62 | ||
| 63 | override func layoutSubviews() { | |
| 64 | // The text view sets its container's width to its own when it lays out. | |
| 65 | if truncates, textContainer.size.width != Self.truncatedWidth { | |
| 66 | textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude) | |
| 67 | } | |
| 68 | super.layoutSubviews() | |
| 69 | // The text view sizes its content to its own width; truncated lines need the widest | |
| 70 | // laid-out line's. | |
| 71 | if truncates, let manager = textLayoutManager { | |
| 72 | let width = ceil(manager.usageBoundsForTextContainer.maxX + textContainerInset.left + textContainerInset.right) | |
| 73 | if contentSize.width < width { contentSize.width = width } | |
| 74 | } | |
| 75 | onLayout?() | |
| 76 | } | |
| 77 | ||
| 78 | override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { | |
| 79 | var rest: Set<UIPress> = [] | |
| 80 | for press in presses { | |
| 81 | if let key = press.key, keyHandler?(key) == true { | |
| 82 | handled = (handled ?? []).union([key.keyCode]) | |
| 83 | } else { | |
| 84 | rest.insert(press) | |
| 85 | } | |
| 86 | } | |
| 87 | if !rest.isEmpty { super.pressesBegan(rest, with: event) } | |
| 88 | } | |
| 89 | ||
| 90 | override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) { | |
| 91 | let rest = presses.filter { press in | |
| 92 | guard let code = press.key?.keyCode, handled?.contains(code) == true else { return true } | |
| 93 | handled?.remove(code) | |
| 94 | return false | |
| 95 | } | |
| 96 | if !rest.isEmpty { super.pressesEnded(rest, with: event) } | |
| 97 | } | |
| 98 | } | |
| 99 | ||
| 100 | 9 | /// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's |
| 101 | 10 | /// `OrgEditor` is. Typing and undo go through the text view and into the document; commands |
| 102 | 11 | /// run on the document and apply their edits as one undo step; headings, drawers and blocks |
| @@ -154,32 +63,32 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 154 | 63 | /// Tags used across the workspace, for completion. |
| 155 | 64 | var knownTags: @Sendable () -> [String] = { [] } |
| 156 | 65 | |
| 157 | private var theme: MobileTheme | |
| 158 | private(set) var fold = FoldState() | |
| 159 | private var globalVisibility: GlobalVisibility? | |
| 66 | var theme: MobileTheme | |
| 67 | internal(set) var fold = FoldState() | |
| 68 | var globalVisibility: GlobalVisibility? | |
| 160 | 69 | let hidden = LockedRanges() |
| 161 | 70 | /// Blocks drawn on a band. |
| 162 | 71 | let shaded = LockedRanges() |
| 163 | 72 | let fragmentStyle = FragmentStyle() |
| 164 | private var selectionColor: UIColor = .clear | |
| 73 | var selectionColor: UIColor = .clear | |
| 165 | 74 | /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`. |
| 166 | private var indented = true | |
| 167 | private var hideStars = false | |
| 75 | var indented = true | |
| 76 | var hideStars = false | |
| 168 | 77 | /// One paragraph style per indent pair. |
| 169 | private var paragraphStyles: [[Int]: NSParagraphStyle] = [:] | |
| 78 | var paragraphStyles: [[Int]: NSParagraphStyle] = [:] | |
| 170 | 79 | /// The line last revealed while markup is hidden, to hide again when the caret leaves. |
| 171 | private var revealedLine: NSRange? | |
| 80 | var revealedLine: NSRange? | |
| 172 | 81 | /// `org-toggle-inline-images`: lines that are only an image link show the image. |
| 173 | private(set) var showsImages = false | |
| 82 | internal(set) var showsImages = false | |
| 174 | 83 | /// The view width images were last sized for. |
| 175 | private var imageWidth: CGFloat = 0 | |
| 84 | var imageWidth: CGFloat = 0 | |
| 176 | 85 | /// The file's folder, for relative image paths. |
| 177 | 86 | let baseDirectory: URL? |
| 178 | private static let imageCache = NSCache<NSString, UIImage>() | |
| 179 | private var loading = false | |
| 180 | private var restyleScheduled: Range<Int>? | |
| 87 | static let imageCache = NSCache<NSString, UIImage>() | |
| 88 | var loading = false | |
| 89 | var restyleScheduled: Range<Int>? | |
| 181 | 90 | /// Narrowed table columns (`org-table-shrink`). |
| 182 | private var shrunk = ShrunkColumns() | |
| 91 | var shrunk = ShrunkColumns() | |
| 183 | 92 | /// A command's edits being applied, which keep shrunk columns narrow. |
| 184 | 93 | private var commandEditing = false |
| 185 | 94 | |
| @@ -504,451 +413,13 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 504 | 413 | } |
| 505 | 414 | |
| 506 | 415 | /// Starts after the edit move with it; ones inside it go. |
| 507 | private static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> { | |
| 416 | static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> { | |
| 508 | 417 | Set(starts.compactMap { start in |
| 509 | 418 | if start >= old.upperBound { return start + delta } |
| 510 | 419 | return start <= old.lowerBound ? start : nil |
| 511 | 420 | }) |
| 512 | 421 | } |
| 513 | 422 | |
| 514 | // MARK: - Styling | |
| 515 | ||
| 516 | private func load(_ text: String) { | |
| 517 | loading = true | |
| 518 | textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base)) | |
| 519 | loading = false | |
| 520 | shaded.set(Presentation.shadedBlocks(document.tree), folded: []) | |
| 521 | restyle(0..<(text as NSString).length) | |
| 522 | textView.typingAttributes = theme.base | |
| 523 | } | |
| 524 | ||
| 525 | /// The text view's own colors, and the block band's. | |
| 526 | private func applyThemeToView() { | |
| 527 | textView.backgroundColor = theme.color("background") ?? .systemBackground | |
| 528 | textView.tintColor = theme.color("cursor") | |
| 529 | textView.typingAttributes = theme.base | |
| 530 | fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width) | |
| 531 | themeSelection() | |
| 532 | } | |
| 533 | ||
| 534 | /// The selection in the theme's selection color: the text view's selection display | |
| 535 | /// interaction draws it with our highlight view; the cursor and handles keep the tint. | |
| 536 | private func themeSelection() { | |
| 537 | guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return } | |
| 538 | let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView() | |
| 539 | view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25) | |
| 540 | if interaction.highlightView !== view { interaction.highlightView = view } | |
| 541 | selectionColor = view.color | |
| 542 | } | |
| 543 | ||
| 544 | /// The highlight view draws under the text, so a block's band would cover it: blocks the | |
| 545 | /// selection enters or leaves are laid out again to draw it over their band. | |
| 546 | private func redrawSelectedBlocks() { | |
| 547 | let selected = textView.selectedRange | |
| 548 | let range = selected.length > 0 ? selected.location..<NSMaxRange(selected) : nil | |
| 549 | let old = fragmentStyle.selection?.range | |
| 550 | fragmentStyle.set(selection: range, color: selectionColor) | |
| 551 | let touched = [old, range].compactMap { $0 } | |
| 552 | redraw(blocks: shaded.all.filter { block in touched.contains { $0.overlaps(block) } }) | |
| 553 | } | |
| 554 | ||
| 555 | /// Lays `blocks` out again and asks their fragments, which are kept across layout passes, | |
| 556 | /// to draw again. | |
| 557 | private func redraw(blocks: [Range<Int>]) { | |
| 558 | guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return } | |
| 559 | for block in blocks { | |
| 560 | guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound), | |
| 561 | let end = content.location(start, offsetBy: block.count), | |
| 562 | let textRange = NSTextRange(location: start, end: end) else { continue } | |
| 563 | manager.invalidateRenderingAttributes(for: textRange) | |
| 564 | manager.invalidateLayout(for: textRange) | |
| 565 | } | |
| 566 | textView.setNeedsDisplay() | |
| 567 | } | |
| 568 | ||
| 569 | /// The band behind blocks spans the view's width, or the widest line's when truncated; | |
| 570 | /// images are as wide as the view allows. Only the blocks read the band's width, so a | |
| 571 | /// wider line in a truncated file, which widens the band on each layout pass, redraws | |
| 572 | /// the blocks alone: laying the whole file out again moves the text under the view. | |
| 573 | private func viewResized() { | |
| 574 | let band = fragmentStyle.blockBand | |
| 575 | let width = max(textView.bounds.width, truncatesLines ? textView.contentSize.width : 0) | |
| 576 | let resized = imageWidth != textView.bounds.width | |
| 577 | guard band.width != width || resized else { return } | |
| 578 | fragmentStyle.set(blockBackground: band.color, width: width) | |
| 579 | imageWidth = textView.bounds.width | |
| 580 | guard resized else { | |
| 581 | redraw(blocks: shaded.all) | |
| 582 | return | |
| 583 | } | |
| 584 | keepingTopLine { | |
| 585 | if showsImages { restyle(0..<textView.textStorage.length) } | |
| 586 | if let manager = textView.textLayoutManager { | |
| 587 | manager.invalidateRenderingAttributes(for: manager.documentRange) | |
| 588 | manager.invalidateLayout(for: manager.documentRange) | |
| 589 | } | |
| 590 | } | |
| 591 | } | |
| 592 | ||
| 593 | /// Styles the whole file again. | |
| 594 | private func restyleAll() { | |
| 595 | let interval = Perf.begin("editor.restyleAll") | |
| 596 | defer { interval.end() } | |
| 597 | keepingTopLine { | |
| 598 | restyle(0..<textView.textStorage.length) | |
| 599 | if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } | |
| 600 | } | |
| 601 | } | |
| 602 | ||
| 603 | /// Lays out `ranges` again, each widened to whole lines and to the line before it: the | |
| 604 | /// heading or opening line of a fold, whose fragment draws the fold mark. Laying out the | |
| 605 | /// whole file again makes TextKit estimate the height of everything above the view afresh, | |
| 606 | /// which moves the text under it. | |
| 607 | private func invalidateLayout(lines ranges: [Range<Int>]) { | |
| 608 | guard !ranges.isEmpty, let manager = textView.textLayoutManager, let content = manager.textContentManager else { return } | |
| 609 | let text = textView.textStorage.string as NSString | |
| 610 | for range in ranges { | |
| 611 | let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location | |
| 612 | let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0))) | |
| 613 | guard let start = content.location(content.documentRange.location, offsetBy: lower), | |
| 614 | let end = content.location(start, offsetBy: upper - lower), | |
| 615 | let textRange = NSTextRange(location: start, end: end) else { continue } | |
| 616 | manager.invalidateLayout(for: textRange) | |
| 617 | } | |
| 618 | } | |
| 619 | ||
| 620 | /// Runs `change`, which lays the whole file out again, and brings the line that was at the | |
| 621 | /// top of the view back there. TextKit estimates the height of text it hasn't laid out, | |
| 622 | /// so the same scroll position lands on different text after a fresh layout. | |
| 623 | private func keepingTopLine(_ change: () -> Void) { | |
| 624 | guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return change() } | |
| 625 | let inset = textView.textContainerInset | |
| 626 | let top = textView.contentOffset.y + textView.adjustedContentInset.top - inset.top | |
| 627 | let start = content.documentRange.location | |
| 628 | let anchor = manager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map { | |
| 629 | (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY) | |
| 630 | } | |
| 631 | change() | |
| 632 | guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset), | |
| 633 | let above = NSTextRange(location: start, end: location) else { return } | |
| 634 | manager.ensureLayout(for: above) | |
| 635 | guard let fragment = manager.textLayoutFragment(for: location) else { return } | |
| 636 | let frame = fragment.layoutFragmentFrame | |
| 637 | manager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * textView.bounds.height)) | |
| 638 | // The view grows to the laid-out height on its next layout pass; the scroll needs it now. | |
| 639 | let needed = manager.usageBoundsForTextContainer.maxY + inset.top + inset.bottom | |
| 640 | if textView.contentSize.height < needed { textView.contentSize.height = needed } | |
| 641 | let y = frame.minY + inset.top + max(0, min(anchor.within, frame.height)) - textView.adjustedContentInset.top | |
| 642 | textView.contentOffset = CGPoint(x: textView.contentOffset.x, y: y) | |
| 643 | } | |
| 644 | ||
| 645 | /// Styles are set after the edit has been processed, as TextKit asks. | |
| 646 | private func scheduleRestyle(_ range: Range<Int>) { | |
| 647 | if let pending = restyleScheduled { | |
| 648 | restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound) | |
| 649 | return | |
| 650 | } | |
| 651 | restyleScheduled = range | |
| 652 | DispatchQueue.main.async { [weak self] in | |
| 653 | guard let self, let range = self.restyleScheduled else { return } | |
| 654 | self.restyleScheduled = nil | |
| 655 | self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: []) | |
| 656 | // Small files are restyled whole: a heading or block line changes what follows it. | |
| 657 | let length = self.textView.textStorage.length | |
| 658 | self.restyle(length < 60_000 ? 0..<length : range) | |
| 659 | self.updateHidden() | |
| 660 | self.textView.typingAttributes = self.theme.base | |
| 661 | } | |
| 662 | } | |
| 663 | ||
| 664 | private var caretLine: NSRange { | |
| 665 | let text = textView.textStorage.string as NSString | |
| 666 | return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0)) | |
| 667 | } | |
| 668 | ||
| 669 | /// Sets attributes for the whole lines in `range`, as the Mac editor does. | |
| 670 | private func restyle(_ range: Range<Int>) { | |
| 671 | let interval = Perf.begin("editor.restyle") | |
| 672 | defer { interval.end() } | |
| 673 | let storage = textView.textStorage | |
| 674 | let ns = storage.string as NSString | |
| 675 | guard ns.length > 0 else { return } | |
| 676 | let lower = min(range.lowerBound, ns.length) | |
| 677 | let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower))) | |
| 678 | let whole = lines.location..<NSMaxRange(lines) | |
| 679 | storage.beginEditing() | |
| 680 | storage.setAttributes(theme.base, range: lines) | |
| 681 | if indented { | |
| 682 | for line in Presentation.lineIndents(document.tree, in: whole) { | |
| 683 | storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) | |
| 684 | } | |
| 685 | } | |
| 686 | let revealed = caretLine | |
| 687 | var scriptExclusions: [Range<Int>] = [] | |
| 688 | for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) { | |
| 689 | let clipped = NSIntersectionRange(NSRange(run.range), lines) | |
| 690 | guard clipped.length > 0 else { continue } | |
| 691 | if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue } | |
| 692 | if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 { | |
| 693 | storage.addAttributes(theme.hidden, range: clipped) | |
| 694 | } else { | |
| 695 | theme.apply(run.role, to: storage, range: clipped) | |
| 696 | } | |
| 697 | if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } | |
| 698 | } | |
| 699 | if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) } | |
| 700 | applyShrunk(whole, in: storage) | |
| 701 | applyImages(whole, in: storage, revealed: revealed) | |
| 702 | storage.endEditing() | |
| 703 | } | |
| 704 | ||
| 705 | private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle { | |
| 706 | if let style = paragraphStyles[[firstLine, wrapped]] { return style } | |
| 707 | let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped) | |
| 708 | paragraphStyles[[firstLine, wrapped]] = style | |
| 709 | return style | |
| 710 | } | |
| 711 | ||
| 712 | /// `org-pretty-entities`: entities drawn as their character over the entity's last | |
| 713 | /// character (the rest hidden), sub/superscripts raised without their markers. | |
| 714 | private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) { | |
| 715 | let runs = Presentation.prettyRuns( | |
| 716 | storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil }, | |
| 717 | scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces | |
| 718 | ) | |
| 719 | for (lineStart, run) in runs { | |
| 720 | switch run { | |
| 721 | case .entity(let r, let display): | |
| 722 | let start = lineStart + r.lowerBound | |
| 723 | let last = lineStart + r.upperBound - 1 | |
| 724 | let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground | |
| 725 | if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) } | |
| 726 | storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1)) | |
| 727 | case .script(let markers, let body, let superscript): | |
| 728 | for marker in markers { | |
| 729 | storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count)) | |
| 730 | } | |
| 731 | let size = theme.font.pointSize | |
| 732 | storage.addAttributes([ | |
| 733 | .font: theme.font.withSize(size * 0.7), | |
| 734 | .baselineOffset: (superscript ? 0.3 : -0.3) * size, | |
| 735 | ], range: NSRange(location: lineStart + body.lowerBound, length: body.count)) | |
| 736 | } | |
| 737 | } | |
| 738 | } | |
| 739 | ||
| 740 | /// Moving to another line shows its markup and hides the last one's. | |
| 741 | private func revealCaretLine() { | |
| 742 | guard !showMarkup else { return } | |
| 743 | let line = caretLine | |
| 744 | guard line != revealedLine else { return } | |
| 745 | let text = textView.textStorage.string as NSString | |
| 746 | // The old line may have moved with edits since; restyle the line now at its start. | |
| 747 | let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil } | |
| 748 | revealedLine = line | |
| 749 | for range in [old, line].compactMap({ $0 }) { | |
| 750 | restyle(range.location..<NSMaxRange(range)) | |
| 751 | } | |
| 752 | } | |
| 753 | ||
| 754 | // MARK: - Shrunk table columns | |
| 755 | ||
| 756 | /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`, | |
| 757 | /// `expand` for `org-table-expand`. | |
| 758 | private func tableColumnWidth(_ id: String) { | |
| 759 | switch shrunk.change(for: id, at: textView.selectedRange.location, in: textView.textStorage.string) { | |
| 760 | case .notInTable: onMessage?("Not in a table") | |
| 761 | case .set(let columns, let table): setShrunk(columns, in: table) | |
| 762 | case .ask(let table, let current, let max): | |
| 763 | onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in | |
| 764 | guard let self, let answer else { return } | |
| 765 | self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table) | |
| 766 | } | |
| 767 | } | |
| 768 | } | |
| 769 | ||
| 770 | /// Narrows `columns` of `table` and widens its others. | |
| 771 | private func setShrunk(_ columns: [Int], in table: Range<Int>) { | |
| 772 | shrunk.set(columns, in: table, text: textView.textStorage.string) | |
| 773 | restyle(table) | |
| 774 | invalidateLayout(lines: [table]) | |
| 775 | } | |
| 776 | ||
| 777 | /// Hides each shrunk segment's text and draws its display where the text was, as pretty | |
| 778 | /// entities draw theirs. | |
| 779 | private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) { | |
| 780 | guard !shrunk.isEmpty else { return } | |
| 781 | let cell = theme.column | |
| 782 | for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length { | |
| 783 | let r = segment.range | |
| 784 | let shown = segment.display.count | |
| 785 | let kept = min(shown, r.count) | |
| 786 | if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) } | |
| 787 | guard kept > 0 else { continue } | |
| 788 | let visible = NSRange(location: r.upperBound - kept, length: kept) | |
| 789 | let color = storage.attribute(.foregroundColor, at: visible.location, effectiveRange: nil) as? UIColor ?? theme.foreground | |
| 790 | storage.addAttribute(.foregroundColor, value: UIColor.clear, range: visible) | |
| 791 | storage.addAttributes([.orgEntityDisplay: segment.display, .orgEntityColor: color], range: NSRange(location: visible.location, length: 1)) | |
| 792 | if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) } | |
| 793 | } | |
| 794 | } | |
| 795 | ||
| 796 | // MARK: - Inline images | |
| 797 | ||
| 798 | private func toggleImages() { | |
| 799 | showsImages.toggle() | |
| 800 | restyleAll() | |
| 801 | if showsImages { | |
| 802 | let ns = textView.textStorage.string as NSString | |
| 803 | var count = 0 | |
| 804 | var offset = 0 | |
| 805 | while offset < ns.length { | |
| 806 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) | |
| 807 | if let image = InlineImages.image(atLine: line.location, in: ns), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 } | |
| 808 | offset = NSMaxRange(line) | |
| 809 | } | |
| 810 | onMessage?("\(count) images displayed inline") | |
| 811 | } else { | |
| 812 | onMessage?("Inline image display turned off") | |
| 813 | } | |
| 814 | } | |
| 815 | ||
| 816 | /// An image link's image, by its path or one relative to `baseDirectory`. | |
| 817 | static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? { | |
| 818 | let expanded = (path as NSString).expandingTildeInPath | |
| 819 | let url: URL | |
| 820 | if expanded.hasPrefix("/") { | |
| 821 | url = URL(fileURLWithPath: expanded) | |
| 822 | } else if let baseDirectory { | |
| 823 | url = baseDirectory.appendingPathComponent(expanded) | |
| 824 | } else { | |
| 825 | return nil | |
| 826 | } | |
| 827 | let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0 | |
| 828 | let key = "\(url.path)|\(modified)" as NSString | |
| 829 | if let cached = Self.imageCache.object(forKey: key) { return cached } | |
| 830 | guard let image = UIImage(contentsOfFile: url.path) else { return nil } | |
| 831 | Self.imageCache.setObject(image, forKey: key) | |
| 832 | return image | |
| 833 | } | |
| 834 | ||
| 835 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is | |
| 836 | /// on the line. | |
| 837 | private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { | |
| 838 | guard showsImages else { return } | |
| 839 | let text = storage.string as NSString | |
| 840 | let inset = textView.textContainerInset | |
| 841 | let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40) | |
| 842 | var location = range.lowerBound | |
| 843 | while location < range.upperBound, location < text.length { | |
| 844 | let line = text.lineRange(for: NSRange(location: location, length: 0)) | |
| 845 | location = NSMaxRange(line) | |
| 846 | guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue } | |
| 847 | let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth) | |
| 848 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 | |
| 849 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) | |
| 850 | // Invisible, keeping the line's height. | |
| 851 | if line.location != revealed.location, content.length > 0 { | |
| 852 | storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content) | |
| 853 | } | |
| 854 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length))) | |
| 855 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() | |
| 856 | // The image sits where the line is; the spacing makes room for the rest of it. | |
| 857 | style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight) | |
| 858 | storage.addAttribute(.paragraphStyle, value: style, range: line) | |
| 859 | } | |
| 860 | } | |
| 861 | ||
| 862 | // MARK: - Truncation | |
| 863 | ||
| 864 | /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead | |
| 865 | /// of wrapping. | |
| 866 | var truncatesLines: Bool { | |
| 867 | get { (textView as? KeyedTextView)?.truncates ?? false } | |
| 868 | set { | |
| 869 | guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return } | |
| 870 | keepingTopLine { | |
| 871 | view.truncates = newValue | |
| 872 | if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } | |
| 873 | } | |
| 874 | } | |
| 875 | } | |
| 876 | ||
| 877 | // MARK: - Folding | |
| 878 | ||
| 879 | func setFolds(_ state: FoldState) { | |
| 880 | fold = state | |
| 881 | updateHidden() | |
| 882 | } | |
| 883 | ||
| 884 | private func updateHidden() { | |
| 885 | let tree = document.tree | |
| 886 | let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden } | |
| 887 | let before = hidden.folded | |
| 888 | let oldHidden = hidden.all | |
| 889 | hidden.set( | |
| 890 | Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers), | |
| 891 | folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds) | |
| 892 | ) | |
| 893 | // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment. | |
| 894 | let storage = textView.textStorage | |
| 895 | let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length } | |
| 896 | if !changed.isEmpty { | |
| 897 | let text = storage.string as NSString | |
| 898 | storage.beginEditing() | |
| 899 | for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) } | |
| 900 | storage.endEditing() | |
| 901 | } | |
| 902 | invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all))) | |
| 903 | textView.setNeedsDisplay() | |
| 904 | } | |
| 905 | ||
| 906 | /// TAB at the caret: a heading cycles, a drawer or block opens or closes. | |
| 907 | @discardableResult | |
| 908 | func cycleAtCaret() -> Bool { | |
| 909 | guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false } | |
| 910 | setFolds(next) | |
| 911 | return true | |
| 912 | } | |
| 913 | ||
| 914 | /// Shift-TAB: overview, contents, show all. | |
| 915 | func cycleGlobal() { | |
| 916 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds) | |
| 917 | globalVisibility = visibility | |
| 918 | setFolds(state) | |
| 919 | } | |
| 920 | ||
| 921 | /// Opens the folds hiding `offset`. | |
| 922 | func unfold(around offset: Int) { | |
| 923 | var state = fold | |
| 924 | for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end { | |
| 925 | state.folds.remove(entry.start) | |
| 926 | state.bodyFolds.remove(entry.start) | |
| 927 | } | |
| 928 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true { | |
| 929 | state.wrapperFolds.remove(start) | |
| 930 | } | |
| 931 | if state != fold { setFolds(state) } | |
| 932 | } | |
| 933 | ||
| 934 | /// Shows the heading at `offset`, unfolded, at the top. | |
| 935 | func reveal(_ offset: Int) { | |
| 936 | let length = textView.textStorage.length | |
| 937 | let target = min(max(0, offset), length) | |
| 938 | unfold(around: target) | |
| 939 | textView.selectedRange = NSRange(location: target, length: 0) | |
| 940 | textView.scrollRangeToVisible(NSRange(location: target, length: 0)) | |
| 941 | } | |
| 942 | ||
| 943 | /// The caret left hidden text (a tap past a fold): what hides it opens. | |
| 944 | fileprivate func selectionChanged() { | |
| 945 | let interval = Perf.begin("editor.selection") | |
| 946 | defer { interval.end() } | |
| 947 | redrawSelectedBlocks() | |
| 948 | let caret = textView.selectedRange.location | |
| 949 | if hidden.containing(caret) != nil { unfold(around: caret) } | |
| 950 | revealCaretLine() | |
| 951 | } | |
| 952 | 423 | } |
| 953 | 424 | |
| 954 | 425 | extension MobileEditor: UITextViewDelegate { |
| @@ -1057,153 +528,4 @@ extension MobileEditor: NSTextLayoutManagerDelegate { | ||
| 1057 | 528 | return fragment |
| 1058 | 529 | } |
| 1059 | 530 | } |
| 1060 | ||
| 1061 | extension NSAttributedString.Key { | |
| 1062 | /// The character an entity shows as, on the entity's last character. | |
| 1063 | static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay") | |
| 1064 | /// The color the entity's character is drawn in. | |
| 1065 | static let orgEntityColor = NSAttributedString.Key("OrgEntityColor") | |
| 1066 | /// The image an image link's line shows under it. | |
| 1067 | static let orgImage = NSAttributedString.Key("OrgImage") | |
| 1068 | } | |
| 1069 | ||
| 1070 | final class InlineImageBox: NSObject, @unchecked Sendable { | |
| 1071 | let image: UIImage | |
| 1072 | let size: CGSize | |
| 1073 | init(image: UIImage, size: CGSize) { | |
| 1074 | self.image = image | |
| 1075 | self.size = size | |
| 1076 | } | |
| 1077 | } | |
| 1078 | ||
| 1079 | /// Selected text's background, in one color however the rects overlap. | |
| 1080 | final class SelectionHighlightView: UIView, UITextSelectionHighlightView { | |
| 1081 | var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } } | |
| 1082 | var color: UIColor = .clear { didSet { setNeedsDisplay() } } | |
| 1083 | ||
| 1084 | override init(frame: CGRect) { | |
| 1085 | super.init(frame: frame) | |
| 1086 | isOpaque = false | |
| 1087 | backgroundColor = .clear | |
| 1088 | isUserInteractionEnabled = false | |
| 1089 | registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() } | |
| 1090 | } | |
| 1091 | ||
| 1092 | required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } | |
| 1093 | ||
| 1094 | override func draw(_ rect: CGRect) { | |
| 1095 | let path = UIBezierPath() | |
| 1096 | for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) } | |
| 1097 | color.setFill() | |
| 1098 | path.fill() | |
| 1099 | } | |
| 1100 | } | |
| 1101 | ||
| 1102 | /// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded | |
| 1103 | /// line's ellipsis, a block's band across the view, an image under an image link, and pretty | |
| 1104 | /// entities' characters where the entities' last (invisible) characters sit. | |
| 1105 | final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 1106 | var folded = false | |
| 1107 | var band: (color: UIColor, width: CGFloat)? | |
| 1108 | var image: InlineImageBox? | |
| 1109 | /// For a block's lines: where the fragment starts, and where the selection is read. | |
| 1110 | var start = 0 | |
| 1111 | var style: FragmentStyle? | |
| 1112 | ||
| 1113 | static func image(_ string: NSAttributedString) -> InlineImageBox? { | |
| 1114 | var found: InlineImageBox? | |
| 1115 | string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in | |
| 1116 | if let box = value as? InlineImageBox { found = box; stop.pointee = true } | |
| 1117 | } | |
| 1118 | return found | |
| 1119 | } | |
| 1120 | ||
| 1121 | static func hasEntities(_ string: NSAttributedString) -> Bool { | |
| 1122 | var found = false | |
| 1123 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in | |
| 1124 | if value != nil { found = true; stop.pointee = true } | |
| 1125 | } | |
| 1126 | return found | |
| 1127 | } | |
| 1128 | ||
| 1129 | private var bandRect: CGRect? { | |
| 1130 | guard let band else { return nil } | |
| 1131 | // Not under the empty line TextKit adds after a final newline. | |
| 1132 | let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height | |
| 1133 | // The width as it is now: the view may have been laid out since this fragment was made. | |
| 1134 | let width = style?.blockBand.width ?? band.width | |
| 1135 | return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height) | |
| 1136 | } | |
| 1137 | ||
| 1138 | private var imageRect: CGRect? { | |
| 1139 | guard let image, let line = textLineFragments.first else { return nil } | |
| 1140 | return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height) | |
| 1141 | } | |
| 1142 | ||
| 1143 | override var renderingSurfaceBounds: CGRect { | |
| 1144 | var bounds = super.renderingSurfaceBounds | |
| 1145 | if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) } | |
| 1146 | for rect in [bandRect, imageRect].compactMap({ $0 }) { bounds = bounds.union(rect) } | |
| 1147 | return bounds | |
| 1148 | } | |
| 1149 | ||
| 1150 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 1151 | if let band, let rect = bandRect { | |
| 1152 | context.saveGState() | |
| 1153 | context.setFillColor(band.color.cgColor) | |
| 1154 | context.fill(rect.offsetBy(dx: point.x, dy: point.y)) | |
| 1155 | context.restoreGState() | |
| 1156 | drawSelection(at: point, in: context, bandRect: rect) | |
| 1157 | } | |
| 1158 | super.draw(at: point, in: context) | |
| 1159 | UIGraphicsPushContext(context) | |
| 1160 | defer { UIGraphicsPopContext() } | |
| 1161 | drawEntities(at: point) | |
| 1162 | if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) } | |
| 1163 | if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first { | |
| 1164 | let bounds = line.typographicBounds | |
| 1165 | let ellipsis = NSAttributedString(string: " …", attributes: [ | |
| 1166 | .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular), | |
| 1167 | .foregroundColor: UIColor.secondaryLabel, | |
| 1168 | ]) | |
| 1169 | ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY)) | |
| 1170 | } | |
| 1171 | } | |
| 1172 | ||
| 1173 | /// The selected part of each line, over the band; a selection running past a line's end | |
| 1174 | /// fills to the band's edge. | |
| 1175 | private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) { | |
| 1176 | guard let selection = style?.selection else { return } | |
| 1177 | context.saveGState() | |
| 1178 | context.setFillColor(selection.color.cgColor) | |
| 1179 | for line in textLineFragments where line.characterRange.length > 0 { | |
| 1180 | let lineStart = start + line.characterRange.location | |
| 1181 | let lineEnd = lineStart + line.characterRange.length | |
| 1182 | let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd) | |
| 1183 | guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue } | |
| 1184 | let bounds = line.typographicBounds | |
| 1185 | // From the margin when the selection began on an earlier line, as the system draws it. | |
| 1186 | let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0) | |
| 1187 | let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x | |
| 1188 | let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x | |
| 1189 | context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height)) | |
| 1190 | } | |
| 1191 | context.restoreGState() | |
| 1192 | } | |
| 1193 | ||
| 1194 | private func drawEntities(at point: CGPoint) { | |
| 1195 | guard let string = (textElement as? NSTextParagraph)?.attributedString else { return } | |
| 1196 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in | |
| 1197 | guard let display = value as? String, | |
| 1198 | let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return } | |
| 1199 | var attributes = string.attributes(at: range.location, effectiveRange: nil) | |
| 1200 | attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label | |
| 1201 | attributes[.orgEntityDisplay] = nil | |
| 1202 | attributes[.orgEntityColor] = nil | |
| 1203 | let x = line.locationForCharacter(at: range.location).x | |
| 1204 | let bounds = line.typographicBounds | |
| 1205 | NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY)) | |
| 1206 | } | |
| 1207 | } | |
| 1208 | } | |
| 1209 | 531 | #endif |
Sources/OrgstarMobile/MobileFragments.swift added +248
| @@ -0,0 +1,248 @@ | ||
| 1 | #if os(iOS) | |
| 2 | import OrgApp | |
| 3 | import OrgCore | |
| 4 | import OrgDocument | |
| 5 | import OrgHighlight | |
| 6 | import OrgPresentation | |
| 7 | import UIKit | |
| 8 | ||
| 9 | /// Ranges read by TextKit's delegate callbacks. | |
| 10 | final class LockedRanges: @unchecked Sendable { | |
| 11 | private let lock = NSLock() | |
| 12 | private var ranges: [Range<Int>] = [] | |
| 13 | private var starts: Set<Int> = [] | |
| 14 | ||
| 15 | func set(_ new: [Range<Int>], folded: Set<Int>) { lock.withLock { ranges = new; starts = folded } } | |
| 16 | var all: [Range<Int>] { lock.withLock { ranges } } | |
| 17 | func covers(_ start: Int, _ end: Int) -> Bool { lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } } } | |
| 18 | func isFolded(_ start: Int) -> Bool { lock.withLock { starts.contains(start) } } | |
| 19 | var folded: Set<Int> { lock.withLock { starts } } | |
| 20 | func containing(_ offset: Int) -> Range<Int>? { lock.withLock { ranges.first { $0.contains(offset) } } } | |
| 21 | } | |
| 22 | ||
| 23 | /// What layout fragments draw beyond the text, read by TextKit's delegate callbacks. | |
| 24 | final class FragmentStyle: @unchecked Sendable { | |
| 25 | private let lock = NSLock() | |
| 26 | private var band: (color: UIColor, width: CGFloat) = (.clear, 0) | |
| 27 | private var selected: (range: Range<Int>, color: UIColor)? | |
| 28 | ||
| 29 | func set(blockBackground color: UIColor, width: CGFloat) { lock.withLock { band = (color, width) } } | |
| 30 | var blockBand: (color: UIColor, width: CGFloat) { lock.withLock { band } } | |
| 31 | /// The selection, which a block's fragment draws over its band, as the Mac's fragments do. | |
| 32 | func set(selection range: Range<Int>?, color: UIColor) { lock.withLock { selected = range.map { ($0, color) } } } | |
| 33 | var selection: (range: Range<Int>, color: UIColor)? { lock.withLock { selected } } | |
| 34 | } | |
| 35 | ||
| 36 | /// A text view that offers hardware-keyboard presses to the editor's keymap first. | |
| 37 | final class KeyedTextView: UITextView { | |
| 38 | var keyHandler: ((UIKey) -> Bool)? | |
| 39 | /// Keys the editor took, whose release the text system doesn't see. Optional: made by | |
| 40 | /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values. | |
| 41 | private var handled: Set<UIKeyboardHIDUsage>? | |
| 42 | /// Called after each layout pass, as the view's size settles. | |
| 43 | var onLayout: (() -> Void)? | |
| 44 | /// The text container's width while lines are truncated. | |
| 45 | static let truncatedWidth: CGFloat = 100_000 | |
| 46 | ||
| 47 | /// Long lines run off the right edge and the view scrolls sideways. | |
| 48 | var truncates: Bool { | |
| 49 | get { !textContainer.widthTracksTextView } | |
| 50 | set { | |
| 51 | textContainer.widthTracksTextView = !newValue | |
| 52 | if newValue { | |
| 53 | textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude) | |
| 54 | } else { | |
| 55 | textContainer.size = CGSize(width: bounds.width - textContainerInset.left - textContainerInset.right, height: CGFloat.greatestFiniteMagnitude) | |
| 56 | contentOffset.x = 0 | |
| 57 | } | |
| 58 | showsHorizontalScrollIndicator = newValue | |
| 59 | setNeedsLayout() | |
| 60 | } | |
| 61 | } | |
| 62 | ||
| 63 | override func layoutSubviews() { | |
| 64 | // The text view sets its container's width to its own when it lays out. | |
| 65 | if truncates, textContainer.size.width != Self.truncatedWidth { | |
| 66 | textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude) | |
| 67 | } | |
| 68 | super.layoutSubviews() | |
| 69 | // The text view sizes its content to its own width; truncated lines need the widest | |
| 70 | // laid-out line's. | |
| 71 | if truncates, let manager = textLayoutManager { | |
| 72 | let width = ceil(manager.usageBoundsForTextContainer.maxX + textContainerInset.left + textContainerInset.right) | |
| 73 | if contentSize.width < width { contentSize.width = width } | |
| 74 | } | |
| 75 | onLayout?() | |
| 76 | } | |
| 77 | ||
| 78 | override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { | |
| 79 | var rest: Set<UIPress> = [] | |
| 80 | for press in presses { | |
| 81 | if let key = press.key, keyHandler?(key) == true { | |
| 82 | handled = (handled ?? []).union([key.keyCode]) | |
| 83 | } else { | |
| 84 | rest.insert(press) | |
| 85 | } | |
| 86 | } | |
| 87 | if !rest.isEmpty { super.pressesBegan(rest, with: event) } | |
| 88 | } | |
| 89 | ||
| 90 | override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) { | |
| 91 | let rest = presses.filter { press in | |
| 92 | guard let code = press.key?.keyCode, handled?.contains(code) == true else { return true } | |
| 93 | handled?.remove(code) | |
| 94 | return false | |
| 95 | } | |
| 96 | if !rest.isEmpty { super.pressesEnded(rest, with: event) } | |
| 97 | } | |
| 98 | } | |
| 99 | ||
| 100 | extension NSAttributedString.Key { | |
| 101 | /// The character an entity shows as, on the entity's last character. | |
| 102 | static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay") | |
| 103 | /// The color the entity's character is drawn in. | |
| 104 | static let orgEntityColor = NSAttributedString.Key("OrgEntityColor") | |
| 105 | /// The image an image link's line shows under it. | |
| 106 | static let orgImage = NSAttributedString.Key("OrgImage") | |
| 107 | } | |
| 108 | ||
| 109 | final class InlineImageBox: NSObject, @unchecked Sendable { | |
| 110 | let image: UIImage | |
| 111 | let size: CGSize | |
| 112 | init(image: UIImage, size: CGSize) { | |
| 113 | self.image = image | |
| 114 | self.size = size | |
| 115 | } | |
| 116 | } | |
| 117 | ||
| 118 | /// Selected text's background, in one color however the rects overlap. | |
| 119 | final class SelectionHighlightView: UIView, UITextSelectionHighlightView { | |
| 120 | var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } } | |
| 121 | var color: UIColor = .clear { didSet { setNeedsDisplay() } } | |
| 122 | ||
| 123 | override init(frame: CGRect) { | |
| 124 | super.init(frame: frame) | |
| 125 | isOpaque = false | |
| 126 | backgroundColor = .clear | |
| 127 | isUserInteractionEnabled = false | |
| 128 | registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() } | |
| 129 | } | |
| 130 | ||
| 131 | required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } | |
| 132 | ||
| 133 | override func draw(_ rect: CGRect) { | |
| 134 | let path = UIBezierPath() | |
| 135 | for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) } | |
| 136 | color.setFill() | |
| 137 | path.fill() | |
| 138 | } | |
| 139 | } | |
| 140 | ||
| 141 | /// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded | |
| 142 | /// line's ellipsis, a block's band across the view, an image under an image link, and pretty | |
| 143 | /// entities' characters where the entities' last (invisible) characters sit. | |
| 144 | final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable { | |
| 145 | var folded = false | |
| 146 | var band: (color: UIColor, width: CGFloat)? | |
| 147 | var image: InlineImageBox? | |
| 148 | /// For a block's lines: where the fragment starts, and where the selection is read. | |
| 149 | var start = 0 | |
| 150 | var style: FragmentStyle? | |
| 151 | ||
| 152 | static func image(_ string: NSAttributedString) -> InlineImageBox? { | |
| 153 | var found: InlineImageBox? | |
| 154 | string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in | |
| 155 | if let box = value as? InlineImageBox { found = box; stop.pointee = true } | |
| 156 | } | |
| 157 | return found | |
| 158 | } | |
| 159 | ||
| 160 | static func hasEntities(_ string: NSAttributedString) -> Bool { | |
| 161 | var found = false | |
| 162 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in | |
| 163 | if value != nil { found = true; stop.pointee = true } | |
| 164 | } | |
| 165 | return found | |
| 166 | } | |
| 167 | ||
| 168 | var bandRect: CGRect? { | |
| 169 | guard let band else { return nil } | |
| 170 | // Not under the empty line TextKit adds after a final newline. | |
| 171 | let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height | |
| 172 | // The width as it is now: the view may have been laid out since this fragment was made. | |
| 173 | let width = style?.blockBand.width ?? band.width | |
| 174 | return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height) | |
| 175 | } | |
| 176 | ||
| 177 | private var imageRect: CGRect? { | |
| 178 | guard let image, let line = textLineFragments.first else { return nil } | |
| 179 | return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height) | |
| 180 | } | |
| 181 | ||
| 182 | override var renderingSurfaceBounds: CGRect { | |
| 183 | var bounds = super.renderingSurfaceBounds | |
| 184 | if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) } | |
| 185 | for rect in [bandRect, imageRect].compactMap({ $0 }) { bounds = bounds.union(rect) } | |
| 186 | return bounds | |
| 187 | } | |
| 188 | ||
| 189 | override func draw(at point: CGPoint, in context: CGContext) { | |
| 190 | if let band, let rect = bandRect { | |
| 191 | context.saveGState() | |
| 192 | context.setFillColor(band.color.cgColor) | |
| 193 | context.fill(rect.offsetBy(dx: point.x, dy: point.y)) | |
| 194 | context.restoreGState() | |
| 195 | drawSelection(at: point, in: context, bandRect: rect) | |
| 196 | } | |
| 197 | super.draw(at: point, in: context) | |
| 198 | UIGraphicsPushContext(context) | |
| 199 | defer { UIGraphicsPopContext() } | |
| 200 | drawEntities(at: point) | |
| 201 | if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) } | |
| 202 | if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first { | |
| 203 | let bounds = line.typographicBounds | |
| 204 | let ellipsis = NSAttributedString(string: " …", attributes: [ | |
| 205 | .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular), | |
| 206 | .foregroundColor: UIColor.secondaryLabel, | |
| 207 | ]) | |
| 208 | ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY)) | |
| 209 | } | |
| 210 | } | |
| 211 | ||
| 212 | /// The selected part of each line, over the band; a selection running past a line's end | |
| 213 | /// fills to the band's edge. | |
| 214 | private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) { | |
| 215 | guard let selection = style?.selection else { return } | |
| 216 | context.saveGState() | |
| 217 | context.setFillColor(selection.color.cgColor) | |
| 218 | for line in textLineFragments where line.characterRange.length > 0 { | |
| 219 | let lineStart = start + line.characterRange.location | |
| 220 | let lineEnd = lineStart + line.characterRange.length | |
| 221 | let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd) | |
| 222 | guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue } | |
| 223 | let bounds = line.typographicBounds | |
| 224 | // From the margin when the selection began on an earlier line, as the system draws it. | |
| 225 | let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0) | |
| 226 | let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x | |
| 227 | let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x | |
| 228 | context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height)) | |
| 229 | } | |
| 230 | context.restoreGState() | |
| 231 | } | |
| 232 | ||
| 233 | private func drawEntities(at point: CGPoint) { | |
| 234 | guard let string = (textElement as? NSTextParagraph)?.attributedString else { return } | |
| 235 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in | |
| 236 | guard let display = value as? String, | |
| 237 | let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return } | |
| 238 | var attributes = string.attributes(at: range.location, effectiveRange: nil) | |
| 239 | attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label | |
| 240 | attributes[.orgEntityDisplay] = nil | |
| 241 | attributes[.orgEntityColor] = nil | |
| 242 | let x = line.locationForCharacter(at: range.location).x | |
| 243 | let bounds = line.typographicBounds | |
| 244 | NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY)) | |
| 245 | } | |
| 246 | } | |
| 247 | } | |
| 248 | #endif | |
docs/design.md +1
| @@ -329,6 +329,7 @@ Fidelity is checked against Emacs itself, using the same oracle pattern as orgo' | ||
| 329 | 329 | - Encoding fixtures (BOM, CRLF, mixed endings, invalid UTF-8, non-BMP, combining characters) are public, in the repo. |
| 330 | 330 | - Save fault-injection tests replace the file on disk at each step of the save sequence. |
| 331 | 331 | - Personal org files are a second, private corpus run locally; phase gates use the public corpus. |
| 332 | - `scripts/check-file-sizes.sh` fails when a hand-written Swift file is over 1,000 lines; run it beside `swift test`. The generated `CharFold.swift` and `Queries.swift` are exempt. | |
| 332 | 333 | |
| 333 | 334 | ## Phases |
| 334 | 335 | |
scripts/check-file-sizes.sh added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | #!/bin/sh | |
| 2 | # Lists hand-written Swift files over 1,000 lines and exits 1 when there are any. | |
| 3 | # Generated files (scripts/update-char-fold.sh, scripts/update-highlight-queries.sh) are exempt. | |
| 4 | # Usage: scripts/check-file-sizes.sh | |
| 5 | set -eu | |
| 6 | cd "$(dirname "$0")/.." | |
| 7 | limit=1000 | |
| 8 | over="$(find Sources -name '*.swift' \ | |
| 9 | ! -path 'Sources/OrgCore/Keymap/CharFold.swift' ! -path 'Sources/OrgHighlight/Queries.swift' \ | |
| 10 | -exec wc -l {} + | awk -v limit="$limit" '$2 != "total" && $1 > limit { printf "%6d %s\n", $1, $2 }')" | |
| 11 | [ -z "$over" ] || { echo "Swift files over $limit lines:"; echo "$over"; exit 1; } | |
| 12 | echo "No hand-written Swift file over $limit lines." | |