import CoreGraphics import Foundation import HelderCore /// Line starts of a text as UTF-16 offsets, the unit NSTextView and the tokens use. public struct LineIndex: Equatable, Sendable { /// Offset of the first character of each line; always starts with 0. public private(set) var starts: [Int] public private(set) var length: Int public init(_ text: String) { var starts = [0] var offset = 0 for unit in text.utf16 { offset += 1 if unit == 10 { starts.append(offset) } } self.starts = starts length = offset } /// A text ending in a newline has an empty last line, as the editor shows it. public var lineCount: Int { starts.count } /// The 1-based line holding a UTF-16 offset; offsets past the end land on the last line. public func line(containing offset: Int) -> Int { var low = 0 var high = starts.count - 1 while low < high { let mid = (low + high + 1) / 2 if starts[mid] <= offset { low = mid } else { high = mid - 1 } } return low + 1 } public func isLineStart(_ offset: Int) -> Bool { starts[line(containing: offset) - 1] == offset } /// Offset of the first character of a 1-based line, clamped to the text. public func start(ofLine line: Int) -> Int { starts[min(max(line, 1), starts.count) - 1] } /// The 1-based column of an offset within its line. public func column(of offset: Int) -> Int { offset - start(ofLine: line(containing: offset)) + 1 } /// Offset just past a line: the next line's start, or the end of the text for the last line. public func end(ofLine line: Int) -> Int { line < starts.count ? starts[line] : length } /// Follows one edit without rescanning the whole text: `editedRange` is in the new text, /// `inserted` is the text now in that range, `delta` the change in length. public mutating func applyEdit(editedRange: NSRange, delta: Int, inserted: String) { let location = editedRange.location let oldEnd = NSMaxRange(editedRange) - delta var next = Array(starts.prefix { $0 <= location }) var offset = location for unit in inserted.utf16 { offset += 1 if unit == 10 { next.append(offset) } } next.append(contentsOf: starts.drop { $0 <= oldEnd }.map { $0 + delta }) starts = next length += delta } } /// How one line of an editor pane is marked. public struct CodeLineMark: Equatable, Sendable { public enum Tone: Equatable, Sendable { /// Teal: what the file holds now. case added /// Amber-deep: what it held before. case removed } /// Fill the whole row; false for a gap-only mark. public var tint: Bool /// The 2px left rule and the lifted number; nil for a gap-only mark. public var tone: Tone? /// A removed run owns no line in Actual, so its amber-deep rule sits on this line's edge. public var gap: GapEdge? public init(tint: Bool = false, tone: Tone? = nil, gap: GapEdge? = nil) { self.tint = tint self.tone = tone self.gap = gap } } public enum ChangeMarks { /// Actual: tinted added lines plus the gap rules of pure deletions, keyed by line number. public static func actual(_ lines: [ViewLine]) -> [Int: CodeLineMark] { var marks: [Int: CodeLineMark] = [:] for line in lines { guard let no = line.no else { continue } let added = line.style == .added guard added || line.gap != nil else { continue } marks[no] = CodeLineMark(tint: added, tone: added ? .added : nil, gap: line.gap) } return marks } } public enum GutterNumbers { /// The number each visual row shows: a wrapped line numbers only its first row. public static func labels(rowStarts: [Int], index: LineIndex) -> [Int?] { rowStarts.map { index.isLineStart($0) ? index.line(containing: $0) : nil } } } public enum DiffOverlayLayout { public static let rowHeight: CGFloat = 22 public static let topPadding: CGFloat = 6 /// The split row that shows an updated-side line. public static func rowIndex(forUpdatedLine line: Int, in rows: [SplitRow]) -> Int? { rows.firstIndex { $0.right?.no == line } } /// The scroll offset that puts a row in the middle of the viewport, as near as the file permits. public static func centredOffset(rowIndex: Int, rowCount: Int, viewportHeight: CGFloat, rowHeight: CGFloat = rowHeight, topPadding: CGFloat = topPadding) -> CGFloat { let contentHeight = topPadding * 2 + CGFloat(rowCount) * rowHeight let rowTop = topPadding + CGFloat(rowIndex) * rowHeight let wanted = rowTop - (viewportHeight - rowHeight) / 2 return min(max(0, wanted), max(0, contentHeight - viewportHeight)) } } /// A replacement the Tab key makes, plus where the selection goes afterwards. public struct TextEdit: Equatable, Sendable { public var range: NSRange public var replacement: String public var selection: NSRange } public enum Indentation { /// Tab inserts spaces on one line; over several lines, or with Shift, every touched line /// moves by one level. A selection that stops at column 0 leaves that last line alone. public static func edit(_ text: String, selection: NSRange, tabSize: Int, outdent: Bool) -> TextEdit? { let ns = text as NSString let size = max(1, tabSize) let pad = String(repeating: " ", count: size) let from = selection.location let to = NSMaxRange(selection) if !outdent && !ns.substring(with: selection).contains("\n") { return TextEdit(range: selection, replacement: pad, selection: NSRange(location: from + size, length: 0)) } let previousNewline = ns.range(of: "\n", options: .backwards, range: NSRange(location: 0, length: from)) let start = previousNewline.location == NSNotFound ? 0 : previousNewline.location + 1 let tail = to > from && to > 0 && ns.character(at: to - 1) == 10 ? to - 1 : to let newline = ns.range(of: "\n", options: [], range: NSRange(location: tail, length: ns.length - tail)) let end = newline.location == NSNotFound ? ns.length : newline.location let block = ns.substring(with: NSRange(location: start, length: end - start)) let lines = block.components(separatedBy: "\n") func cut(_ line: String) -> Int { guard outdent else { return 0 } if line.hasPrefix("\t") { return 1 } return min(size, line.prefix { $0 == " " }.count) } let next = lines.map { outdent ? String($0.dropFirst(cut($0))) : pad + $0 }.joined(separator: "\n") if next == block { return nil } let head = outdent ? -cut(lines[0]) : size let total = outdent ? -lines.reduce(0) { $0 + cut($1) } : size * lines.count let newFrom = max(start, from + head) let newTo = max(start, to + total) return TextEdit(range: NSRange(location: start, length: end - start), replacement: next, selection: NSRange(location: newFrom, length: max(0, newTo - newFrom))) } } public enum EditorReference { /// The lines a text selection touches, as the reference names them. public static func lines(of range: NSRange, in index: LineIndex) -> ClosedRange { let first = index.line(containing: range.location) let last = index.line(containing: NSMaxRange(range)) return first...max(first, last) } /// `path:start-end` for a selection, else `path:line` for the clicked line. public static func make(path: String, selectedLines: ClosedRange?, clickedLine: Int) -> AgentReference { if let lines = selectedLines { return AgentReference(path: path, lines: lines) } return AgentReference(path: path, startLine: max(1, clickedLine)) } } public enum HighlightDiff { /// The part of the new text whose colours may be wrong after an edit: the edited range plus /// every token that differs, so a keystroke repaints a line, not the file. An opened block /// comment still repaints everything after it, because every later token differs. public static func repaintRange(old: [Token], new: [Token], edited: NSRange, delta: Int, newLength: Int) -> NSRange { let editedEndOld = NSMaxRange(edited) - delta var prefix = 0 while prefix < old.count, prefix < new.count, old[prefix] == new[prefix], old[prefix].location + old[prefix].length <= edited.location { prefix += 1 } var suffix = 0 while suffix < old.count - prefix, suffix < new.count - prefix { let o = old[old.count - 1 - suffix] let n = new[new.count - 1 - suffix] guard o.location >= editedEndOld, o.location + delta == n.location, o.length == n.length, o.role == n.role else { break } suffix += 1 } var start = edited.location var end = NSMaxRange(edited) for t in old[prefix..<(old.count - suffix)] { let tEnd = t.location + t.length start = min(start, t.location < edited.location ? t.location : t.location + delta) end = max(end, tEnd > editedEndOld ? tEnd + delta : min(tEnd, edited.location)) } for t in new[prefix..<(new.count - suffix)] { start = min(start, t.location) end = max(end, t.location + t.length) } start = max(0, min(start, newLength)) end = max(start, min(end, newLength)) return NSRange(location: start, length: end - start) } }