// SPDX-License-Identifier: GPL-3.0-or-later import AppKit enum CMOCEditorAction: String, CaseIterable { case indent = "Indent", outdent = "Outdent", comment = "Toggle Line Comment", match = "Go to Matching Bracket" } /// Small source edits, not a formatter. Coordinates and selections use UTF-16. enum CMOCEditing { struct Edit { let range: NSRange; let text: String; let selection: NSRange } static func lineEdit(_ text: String, selection: NSRange, action: CMOCEditorAction) -> Edit? { let source = text as NSString guard selection.location <= source.length, selection.length <= source.length - selection.location, text.utf8.count <= 1_048_576, action != .match else { return nil } let first = source.lineRange(for: NSRange(location: selection.location, length: 0)).location let last = selection.length == 0 ? selection.location : NSMaxRange(selection) - 1 let end = NSMaxRange(source.lineRange(for: NSRange(location: last, length: 0))) let range = NSRange(location: first, length: end - first) let original = source.substring(with: range) as NSString var lines: [(offset: Int, text: String)] = [], cursor = 0 repeat { let line = original.lineRange(for: NSRange(location: cursor, length: 0)) lines.append((cursor, original.substring(with: line))) cursor = NSMaxRange(line) } while cursor < original.length let uncomment = action == .comment && lines.filter { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } .allSatisfy { $0.text.trimmingCharacters(in: .whitespaces).hasPrefix("//") } var output = "", caret = selection.location - first for line in lines { let units = Array(line.text.utf16) let leading = units.prefix { $0 == 32 || $0 == 9 }.count let blank = line.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty var at = 0, remove = 0, insert = "" switch action { case .indent: insert = " " case .outdent: remove = units.first == 9 ? 1 : units.prefix { $0 == 32 }.prefix(4).count case .comment: if !blank { at = leading; if uncomment { remove = 2 + ((leading + 2 < units.count && units[leading + 2] == 32) ? 1 : 0) } else { insert = "// " } } case .match: break } if selection.length == 0, line.offset + at <= selection.location - first { caret += insert.utf16.count - min(remove, max(0, selection.location - first - line.offset - at)) } output += (line.text as NSString).replacingCharacters(in: NSRange(location: at, length: remove), with: insert) } guard output != original as String else { return nil } let selected = selection.length == 0 ? NSRange(location: first + caret, length: 0) : NSRange(location: first, length: output.utf16.count) return .init(range: range, text: output, selection: selected) } /// Pair only C code delimiters; literals, comments and directives are opaque. static func bracketPairs(_ text: String) -> [Int: Int] { guard text.utf8.count <= 1_048_576 else { return [:] } let u = Array(text.utf16); var i = 0, stack: [(UInt16, Int)] = [], pairs: [Int: Int] = [:], lineStart = true while i < u.count { let c = u[i], next: UInt16 = i + 1 < u.count ? u[i + 1] : 0 if c == 10 || c == 13 { lineStart = true; i += 1; continue } if c == 32 || c == 9 { i += 1; continue } if (lineStart && c == 35) || (c == 47 && next == 47) { while i < u.count { if u[i] == 10 { let previous = i > 0 && u[i - 1] == 13 ? i - 2 : i - 1 if previous < 0 || u[previous] != 92 { break } } i += 1 }; continue } if c == 47 && next == 42 { i += 2 while i < u.count { if u[i] == 42 && i + 1 < u.count && u[i + 1] == 47 { i += 2; break } if u[i] == 10 { lineStart = true }; i += 1 }; continue } lineStart = false if c == 34 || c == 39 { let quote = c; i += 1 while i < u.count { if u[i] == 92 { i += min(2, u.count - i); continue } if u[i] == quote { i += 1; break }; i += 1 }; continue } if [UInt16(40), 91, 123].contains(c) { guard stack.count < 512 else { return [:] }; stack.append((c, i)) } else if [UInt16(41), 93, 125].contains(c) { let expected: UInt16 = c == 41 ? 40 : c == 93 ? 91 : 123 if let top = stack.last, top.0 == expected { pairs[top.1] = i; pairs[i] = top.1; stack.removeLast() } else { stack.removeAll() } } i += 1 } return pairs } static func newline(_ text: String, selection: NSRange) -> String { let s = text as NSString guard selection.location <= s.length else { return "\n" } let range = s.lineRange(for: NSRange(location: selection.location, length: 0)) let before = s.substring(with: NSRange(location: range.location, length: selection.location - range.location)) let indent = String(before.prefix { $0 == " " || $0 == "\t" }) let trimmed = before.trimmingCharacters(in: .whitespaces) // A temporary closing brace lets the same lexer recognize an unmatched // opening brace without mistaking a brace in a literal/comment for code. let prefix = s.substring(to: selection.location).trimmingCharacters(in: .whitespaces) let opensBlock = trimmed.hasSuffix("{") && bracketPairs(prefix + "}")[prefix.utf16.count] == prefix.utf16.count - 1 let ending = text.contains("\r\n") ? "\r\n" : "\n" return ending + indent + (opensBlock ? (indent.contains("\t") ? "\t" : " ") : "") } } class CMOCEditingTextView: CMOCCompletionTextView { var sourceEditingEnabled = true private var pairedText: String? private var pairs: [Int: Int] = [:] private var highlighted: [Int] = [] func refreshBracketHighlight() { guard let layoutManager else { return } // Edits can shift old temporary ranges; clear this editor's bracket // overlay before painting the new pair. Execution-line color lives in // text storage and is unaffected. layoutManager.removeTemporaryAttribute(.backgroundColor, forCharacterRange: NSRange(location: 0, length: (string as NSString).length)) highlighted = [] guard sourceEditingEnabled, !hasMarkedText(), selectedRange().length == 0 else { return } if pairedText != string { pairedText = string; pairs = CMOCEditing.bracketPairs(string) } let caret = selectedRange().location guard let origin = pairs[caret] != nil ? caret : (caret > 0 && pairs[caret - 1] != nil ? caret - 1 : nil), let mate = pairs[origin] else { return } highlighted = [origin, mate] for offset in highlighted { layoutManager.addTemporaryAttribute(.backgroundColor, value: NSColor.controlAccentColor.withAlphaComponent(0.3), forCharacterRange: NSRange(location: offset, length: 1)) } } @objc func indentSource(_ sender: Any?) { performSourceAction(.indent) } @objc func outdentSource(_ sender: Any?) { performSourceAction(.outdent) } @objc func toggleSourceComment(_ sender: Any?) { performSourceAction(.comment) } @objc func matchSourceBracket(_ sender: Any?) { performSourceAction(.match) } func performSourceAction(_ action: CMOCEditorAction) { guard sourceEditingEnabled, !hasMarkedText(), selectedRanges.count == 1 else { return } invalidateCompletion() if action == .match { refreshBracketHighlight() if highlighted.count == 2 { let target = highlighted[1] setSelectedRange(NSRange(location: target, length: 0)); scrollRangeToVisible(NSRange(location: target, length: 1)) } else { completionStatus?("Place the insertion point beside a matched code bracket: ( ), [ ] or { }.") } return } guard isEditable, let edit = CMOCEditing.lineEdit(string, selection: selectedRange(), action: action) else { return } breakUndoCoalescing(); insertText(edit.text, replacementRange: edit.range) setSelectedRange(edit.selection); breakUndoCoalescing(); undoManager?.setActionName(action.rawValue) refreshBracketHighlight() } override func insertTab(_ sender: Any?) { guard sourceEditingEnabled, isEditable, !hasMarkedText() else { super.insertTab(sender); return } if selectedRange().length > 0 { performSourceAction(.indent) } else { insertText(" ", replacementRange: selectedRange()) } } override func insertBacktab(_ sender: Any?) { if sourceEditingEnabled { performSourceAction(.outdent) } else { super.insertBacktab(sender) } } override func insertNewline(_ sender: Any?) { guard sourceEditingEnabled, isEditable, !hasMarkedText() else { super.insertNewline(sender); return } let value = CMOCEditing.newline(string, selection: selectedRange()) breakUndoCoalescing(); insertText(value, replacementRange: selectedRange()); breakUndoCoalescing() } override func performKeyEquivalent(with event: NSEvent) -> Bool { guard sourceEditingEnabled else { return super.performKeyEquivalent(with: event) } let flags = event.modifierFlags.intersection([.command, .control, .shift, .option]) let key = event.charactersIgnoringModifiers if flags == [.command], key == "/" { performSourceAction(.comment); return true } if flags == [.control], key == "]" { performSourceAction(.indent); return true } if flags == [.control], key == "[" { performSourceAction(.outdent); return true } if flags == [.control], key?.lowercased() == "m" { performSourceAction(.match); return true } return super.performKeyEquivalent(with: event) } }