| @@ -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 |