Sources/OrgEditorAppKit/LineNumbers.swift
57 lines · 2911 bytes
1#if os(macOS)
2import AppKit
3
4/// Line numbers in a margin left of the text, as `display-line-numbers-mode` shows them: one
5/// per line of the file (folded lines skipped, wrapped lines numbered once), the caret's line
6/// bright. Drawn by the text view itself: an `NSRulerView` stops TextKit 2 from drawing text.
7extension OrgTextView {
8 static let lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular)
9
10 /// Width of the margin for the largest line number, or 0 when numbers are off.
11 func updateGutter() {
12 var width: CGFloat = 0
13 if showsLineNumbers {
14 let lines = (string as NSString).components(separatedBy: "\n").count
15 let digits = max(2, String(lines).count)
16 width = ceil(("0" as NSString).size(withAttributes: [.font: Self.lineNumberFont]).width * CGFloat(digits) + 16)
17 }
18 if textContainerInset.width != width {
19 textContainerInset = NSSize(width: width, height: textContainerInset.height)
20 needsDisplay = true
21 }
22 }
23
24 func drawLineNumbers(in rect: NSRect) {
25 guard showsLineNumbers, let layout = textLayoutManager, let content = layout.textContentManager else { return }
26 let gutter = textContainerInset.width
27 guard rect.minX < gutter else { return }
28 let text = string as NSString
29 let caretLine = text.lineRange(for: NSRange(location: min(selectedRange().location, text.length), length: 0)).location
30 let origin = textContainerOrigin
31 let documentStart = content.documentRange.location
32 guard let start = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, rect.minY - origin.y)))?.rangeInElement.location
33 ?? layout.textViewportLayoutController.viewportRange?.location else { return }
34
35 var counted = 0
36 var line = 1
37 layout.enumerateTextLayoutFragments(from: start, options: []) { fragment in
38 let frame = fragment.layoutFragmentFrame
39 if frame.minY + origin.y > rect.maxY { return false }
40 let offset = content.offset(from: documentStart, to: fragment.rangeInElement.location)
41 guard offset <= text.length else { return false }
42 while counted < offset {
43 if text.character(at: counted) == 10 { line += 1 }
44 counted += 1
45 }
46 let label = NSAttributedString(string: "\(line)", attributes: [
47 .font: Self.lineNumberFont,
48 .foregroundColor: offset == caretLine ? NSColor.labelColor : NSColor.tertiaryLabelColor,
49 ])
50 let lineHeight = fragment.textLineFragments.first?.typographicBounds.height ?? frame.height
51 let size = label.size()
52 label.draw(at: NSPoint(x: gutter - size.width - 8, y: frame.minY + origin.y + (lineHeight - size.height) / 2))
53 return true
54 }
55 }
56}
57#endif