Textley / app · textley.ai / Sources / Textley / EditorDocument.swift
| 1 | import AppKit |
| 2 | import Observation |
| 3 | import TextleyCore |
| 4 | |
| 5 | @MainActor @Observable |
| 6 | final class EditorDocument: NSObject, Identifiable, NSTextViewDelegate, @preconcurrency NSTextStorageDelegate { |
| 7 | let id = UUID() |
| 8 | private let isLaunchStarter: Bool |
| 9 | private(set) var url: URL? |
| 10 | private(set) var format: TextFileFormat |
| 11 | private(set) var isDirty = false |
| 12 | private(set) var change = 0 |
| 13 | private(set) var selection = NSRange(location: 0, length: 0) |
| 14 | private(set) var caret = "Ln 1, Col 1" |
| 15 | private(set) var image: NSImage? |
| 16 | private(set) var imageSize = CGSize.zero |
| 17 | private(set) var isImage = false |
| 18 | var languageOverride: SyntaxLanguage? { |
| 19 | didSet { queueColoring(clear: true) } |
| 20 | } |
| 21 | var showsPreview = false |
| 22 | var showsFind = false |
| 23 | var focusFind = 0 |
| 24 | var search = SearchQuery() |
| 25 | var replacement = "" |
| 26 | var findMessage = "" |
| 27 | |
| 28 | @ObservationIgnored let history = UndoManager() |
| 29 | @ObservationIgnored let editor: NSTextView |
| 30 | @ObservationIgnored let scroll: NSScrollView |
| 31 | @ObservationIgnored private var lines: LineIndex |
| 32 | @ObservationIgnored private var savedText: String |
| 33 | @ObservationIgnored private var savedFormat: TextFileFormat |
| 34 | @ObservationIgnored private var savedData: Data? |
| 35 | @ObservationIgnored private var colorTask: Task<Void, Never>? |
| 36 | @ObservationIgnored private var findTask: Task<Void, Never>? |
| 37 | @ObservationIgnored private var matches: [NSTextCheckingResult] = [] |
| 38 | @ObservationIgnored private var matchIndex: Int? |
| 39 | @ObservationIgnored private var emptyMatch: (query: SearchQuery, version: Int, range: NSRange)? |
| 40 | @ObservationIgnored private var lastFindSelection: NSRange? |
| 41 | @ObservationIgnored private var appliedPreferences: EditorPreferences? |
| 42 | |
| 43 | var title: String { url?.lastPathComponent ?? "Untitled" } |
| 44 | var language: SyntaxLanguage { languageOverride ?? SyntaxLanguage.detect(url) } |
| 45 | var isShowingMarkdownPreview: Bool { showsPreview && language == .markdown } |
| 46 | var text: String { editor.string } |
| 47 | |
| 48 | var showsStarterHint: Bool { |
| 49 | isLaunchStarter && url == nil && !isDirty && change == 0 && text.isEmpty && !showsFind |
| 50 | } |
| 51 | |
| 52 | init(url: URL? = nil, data: Data? = nil, isLaunchStarter: Bool = false) throws { |
| 53 | self.isLaunchStarter = isLaunchStarter |
| 54 | let decoded = try data.map(TextFileFormat.decode) |
| 55 | self.url = url |
| 56 | let initialFormat = decoded?.format ?? TextFileFormat() |
| 57 | format = initialFormat |
| 58 | savedFormat = initialFormat |
| 59 | savedData = data |
| 60 | let content = decoded?.text ?? "" |
| 61 | savedText = content |
| 62 | lines = LineIndex(content) |
| 63 | let scrollView = NSTextView.scrollablePlainDocumentContentTextView() |
| 64 | guard let textView = scrollView.documentView as? NSTextView else { |
| 65 | throw CocoaError(.fileReadUnknown) |
| 66 | } |
| 67 | self.scroll = scrollView |
| 68 | editor = textView |
| 69 | textView.layoutManager?.allowsNonContiguousLayout = true |
| 70 | textView.string = content |
| 71 | super.init() |
| 72 | configureEditor() |
| 73 | queueColoring() |
| 74 | } |
| 75 | |
| 76 | convenience init(imageURL: URL) throws { |
| 77 | try self.init(url: imageURL) |
| 78 | isImage = true |
| 79 | refreshImage() |
| 80 | guard image != nil else { |
| 81 | throw CocoaError(.fileReadCorruptFile, userInfo: [NSLocalizedDescriptionKey: "Text Editor couldn’t open this image."]) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | private func refreshImage() { |
| 86 | image = url.flatMap { NSImage(contentsOf: $0) } |
| 87 | if let representation = image?.representations.first { |
| 88 | imageSize = CGSize(width: representation.pixelsWide, height: representation.pixelsHigh) |
| 89 | } else { |
| 90 | imageSize = image?.size ?? .zero |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | func refreshFromFolder() { |
| 95 | guard let url, !isDirty else { return } |
| 96 | if isImage { |
| 97 | refreshImage() |
| 98 | return |
| 99 | } |
| 100 | let version = change |
| 101 | let previous = savedData |
| 102 | Task { [weak self] in |
| 103 | let update = await Task.detached(priority: .utility) { |
| 104 | guard let data = try? TextFileAccess.read(url), data != previous, |
| 105 | let decoded = try? TextFileFormat.decode(data) else { return nil as (Data, String, TextFileFormat)? } |
| 106 | return (data, decoded.text, decoded.format) |
| 107 | }.value |
| 108 | guard let self, self.change == version, self.url == url, self.savedData == previous, !self.isDirty else { return } |
| 109 | if let (data, content, format) = update { |
| 110 | let selection = self.editor.selectedRange() |
| 111 | self.editor.string = content |
| 112 | self.history.removeAllActions() |
| 113 | self.format = format |
| 114 | self.savedFormat = format |
| 115 | self.savedText = content |
| 116 | self.savedData = data |
| 117 | let length = content.utf16.count |
| 118 | let start = min(length, selection.location) |
| 119 | self.editor.setSelectedRange(NSRange(location: start, length: min(selection.length, length - start))) |
| 120 | self.change += 1 |
| 121 | self.updateCaret() |
| 122 | self.queueColoring() |
| 123 | if self.showsFind { self.scheduleFindCount() } |
| 124 | } else if self.isShowingMarkdownPreview { |
| 125 | // Linked images can change even when the Markdown source is identical. |
| 126 | self.previewRevision += 1 |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | private(set) var previewRevision = 0 |
| 132 | |
| 133 | private func configureEditor() { |
| 134 | editor.isRichText = false |
| 135 | editor.importsGraphics = false |
| 136 | editor.allowsUndo = true |
| 137 | editor.isAutomaticQuoteSubstitutionEnabled = false |
| 138 | editor.isAutomaticDashSubstitutionEnabled = false |
| 139 | editor.isAutomaticTextReplacementEnabled = false |
| 140 | editor.isAutomaticLinkDetectionEnabled = false |
| 141 | editor.isContinuousSpellCheckingEnabled = false |
| 142 | editor.isAutomaticSpellingCorrectionEnabled = false |
| 143 | editor.textColor = .textColor |
| 144 | editor.backgroundColor = .textBackgroundColor |
| 145 | editor.textContainerInset = NSSize(width: 10, height: 9) |
| 146 | editor.minSize = NSSize(width: 0, height: 0) |
| 147 | editor.maxSize = NSSize(width: 10_000_000, height: CGFloat.greatestFiniteMagnitude) |
| 148 | editor.isVerticallyResizable = true |
| 149 | editor.autoresizingMask = [.width] |
| 150 | editor.setAccessibilityLabel("Document text") |
| 151 | editor.delegate = self |
| 152 | editor.textStorage?.delegate = self |
| 153 | scroll.hasVerticalScroller = true |
| 154 | scroll.borderType = .noBorder |
| 155 | scroll.autohidesScrollers = true |
| 156 | scroll.contentView.postsBoundsChangedNotifications = true |
| 157 | scroll.verticalRulerView = LineNumberRuler(scrollView: scroll, document: self) |
| 158 | } |
| 159 | |
| 160 | func apply(_ preferences: EditorPreferences) { |
| 161 | guard appliedPreferences != preferences else { return } |
| 162 | let previous = appliedPreferences |
| 163 | appliedPreferences = preferences |
| 164 | if previous?.fontSize != preferences.fontSize { |
| 165 | editor.font = .monospacedSystemFont(ofSize: preferences.fontSize, weight: .regular) |
| 166 | } |
| 167 | if previous?.wrap != preferences.wrap { |
| 168 | scroll.hasHorizontalScroller = !preferences.wrap |
| 169 | editor.isHorizontallyResizable = !preferences.wrap |
| 170 | editor.autoresizingMask = [.width] |
| 171 | editor.textContainer?.widthTracksTextView = preferences.wrap |
| 172 | editor.textContainer?.containerSize = NSSize( |
| 173 | width: preferences.wrap ? max(1, scroll.contentSize.width) : 10_000_000, |
| 174 | height: CGFloat.greatestFiniteMagnitude |
| 175 | ) |
| 176 | if preferences.wrap { |
| 177 | editor.setFrameSize(NSSize(width: max(1, scroll.contentSize.width), height: editor.frame.height)) |
| 178 | scroll.contentView.scroll(to: NSPoint(x: 0, y: scroll.contentView.bounds.minY)) |
| 179 | } |
| 180 | } |
| 181 | scroll.hasVerticalRuler = preferences.lineNumbers |
| 182 | scroll.rulersVisible = preferences.lineNumbers |
| 183 | scroll.verticalRulerView?.needsDisplay = true |
| 184 | } |
| 185 | |
| 186 | func undoManager(for view: NSTextView) -> UndoManager? { history } |
| 187 | |
| 188 | func textView(_ view: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, |
| 189 | replacementString: String?) -> Bool { |
| 190 | guard let replacementString, replacementString.utf8.contains(13) else { return true } |
| 191 | view.insertText(TextFileFormat.normalizeLineEndings(replacementString), replacementRange: affectedCharRange) |
| 192 | return false |
| 193 | } |
| 194 | |
| 195 | func textStorage( |
| 196 | _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, |
| 197 | range editedRange: NSRange, changeInLength delta: Int |
| 198 | ) { |
| 199 | guard editedMask.contains(.editedCharacters) else { return } |
| 200 | lines.update(in: textStorage.string as NSString, editedRange: editedRange, changeInLength: delta) |
| 201 | scroll.verticalRulerView?.needsDisplay = true |
| 202 | } |
| 203 | |
| 204 | func textDidChange(_ notification: Notification) { |
| 205 | change += 1 |
| 206 | refreshDirty() |
| 207 | updateCaret() |
| 208 | queueColoring() |
| 209 | if showsFind { scheduleFindCount() } |
| 210 | } |
| 211 | |
| 212 | func textViewDidChangeSelection(_ notification: Notification) { |
| 213 | selection = editor.selectedRange() |
| 214 | updateCaret() |
| 215 | } |
| 216 | |
| 217 | func save(to destination: URL, copy: Bool = false, force: Bool = false, exclusive: Bool = false) throws { |
| 218 | let currentText = text |
| 219 | let sameFile = url == destination |
| 220 | let encoded: Data |
| 221 | if format == savedFormat, currentText.utf8.elementsEqual(savedText.utf8), let savedData { |
| 222 | encoded = savedData |
| 223 | } else { |
| 224 | encoded = try format.encode(currentText) |
| 225 | } |
| 226 | try TextFileAccess.write(encoded, to: destination, replacing: sameFile ? savedData : nil, force: force, exclusive: exclusive) |
| 227 | if !copy { |
| 228 | let previousLanguage = language |
| 229 | url = destination |
| 230 | savedData = encoded |
| 231 | savedText = currentText |
| 232 | savedFormat = format |
| 233 | isDirty = false |
| 234 | if previousLanguage != language { queueColoring(clear: true) } |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | func changeFormat(_ value: TextFileFormat) { |
| 239 | guard value != format else { return } |
| 240 | let previous = format |
| 241 | history.registerUndo(withTarget: self) { $0.changeFormat(previous) } |
| 242 | history.setActionName("Change File Format") |
| 243 | format = value |
| 244 | refreshDirty() |
| 245 | } |
| 246 | |
| 247 | private func refreshDirty() { |
| 248 | let current = text |
| 249 | isDirty = format != savedFormat || current.utf8.count != savedText.utf8.count |
| 250 | || !current.utf8.elementsEqual(savedText.utf8) |
| 251 | } |
| 252 | |
| 253 | func lineNumber(at offset: Int) -> Int { lines.line(at: offset) } |
| 254 | |
| 255 | func goToLine(_ number: Int) -> Bool { |
| 256 | guard (1...lines.starts.count).contains(number) else { return false } |
| 257 | if isShowingMarkdownPreview { showsPreview = false } |
| 258 | select(NSRange(location: lines.starts[number - 1], length: 0)) |
| 259 | focusEditor() |
| 260 | return true |
| 261 | } |
| 262 | |
| 263 | func focusEditor() { editor.window?.makeFirstResponder(editor) } |
| 264 | |
| 265 | private func updateCaret() { |
| 266 | let offset = min(editor.selectedRange().location, (text as NSString).length) |
| 267 | let line = lines.line(at: offset) |
| 268 | let start = lines.starts[line - 1] |
| 269 | let prefix = (text as NSString).substring(with: NSRange(location: start, length: offset - start)) |
| 270 | caret = "Ln \(line), Col \(prefix.count + 1)" |
| 271 | } |
| 272 | |
| 273 | func apply(_ operation: Cleanup) { |
| 274 | let edit = operation.edit(in: text, selection: editor.selectedRange()) |
| 275 | replace(range: edit.range, with: edit.replacement, action: operation.rawValue) |
| 276 | } |
| 277 | |
| 278 | func applyExternalEdit(range: NSRange, replacement: String) { |
| 279 | replace(range: range, with: replacement, action: "Edit with MCP") |
| 280 | } |
| 281 | |
| 282 | private func replace(range: NSRange, with value: String, action: String) { |
| 283 | let replacement = TextFileFormat.normalizeLineEndings(value) |
| 284 | guard let storage = editor.textStorage, |
| 285 | !storage.attributedSubstring(from: range).string.utf8.elementsEqual(replacement.utf8) else { return } |
| 286 | editor.breakUndoCoalescing() |
| 287 | if editor.shouldChangeText(in: range, replacementString: replacement) { |
| 288 | storage.replaceCharacters(in: range, with: replacement) |
| 289 | editor.didChangeText() |
| 290 | editor.breakUndoCoalescing() |
| 291 | history.setActionName(action) |
| 292 | select(NSRange(location: range.location, length: replacement.utf16.count)) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | private func select(_ range: NSRange) { |
| 297 | editor.setSelectedRange(range) |
| 298 | editor.scrollRangeToVisible(range) |
| 299 | } |
| 300 | |
| 301 | func openFind() { |
| 302 | if isShowingMarkdownPreview { showsPreview = false } |
| 303 | showsFind = true |
| 304 | focusFind += 1 |
| 305 | scheduleFindCount() |
| 306 | } |
| 307 | |
| 308 | func closeFind() { |
| 309 | findTask?.cancel() |
| 310 | showsFind = false |
| 311 | focusEditor() |
| 312 | } |
| 313 | |
| 314 | func scheduleFindCount() { |
| 315 | findTask?.cancel() |
| 316 | matchIndex = nil |
| 317 | lastFindSelection = nil |
| 318 | emptyMatch = nil |
| 319 | let input = text |
| 320 | let query = search |
| 321 | let version = change |
| 322 | guard !query.pattern.isEmpty else { |
| 323 | matches = [] |
| 324 | findMessage = "" |
| 325 | return |
| 326 | } |
| 327 | findTask = Task { [weak self] in |
| 328 | try? await Task.sleep(for: .milliseconds(125)) |
| 329 | guard !Task.isCancelled else { return } |
| 330 | let result = await Task.detached(priority: .userInitiated) { |
| 331 | Result { try query.count(in: input) } |
| 332 | }.value |
| 333 | guard !Task.isCancelled, let self, self.change == version, self.search == query else { return } |
| 334 | switch result { |
| 335 | case .success(let count): self.showMatchCount(count) |
| 336 | case .failure: self.findMessage = "Invalid regular expression" |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | private func showMatchCount(_ count: Int) { |
| 342 | findMessage = count == 0 ? "No matches" : "\(count) " + (count == 1 ? "match" : "matches") |
| 343 | } |
| 344 | |
| 345 | private func showMatches(_ result: Result<[NSTextCheckingResult], Error>) { |
| 346 | switch result { |
| 347 | case .success(let results): |
| 348 | matches = results |
| 349 | showMatchCount(results.count) |
| 350 | case .failure: |
| 351 | matches = [] |
| 352 | findMessage = "Invalid regular expression" |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | private func find(backward: Bool) -> NSTextCheckingResult? { |
| 357 | findTask?.cancel() |
| 358 | showMatches(Result { try search.matches(in: text) }) |
| 359 | guard !matches.isEmpty else { return nil } |
| 360 | let range = editor.selectedRange() |
| 361 | let index: Int? |
| 362 | if let previous = matchIndex, lastFindSelection == range, matches.indices.contains(previous) { |
| 363 | let next = previous + (backward ? -1 : 1) |
| 364 | index = matches.indices.contains(next) ? next : nil |
| 365 | } else if backward { |
| 366 | index = matches.lastIndex { NSMaxRange($0.range) <= range.location } |
| 367 | } else { |
| 368 | index = matches.firstIndex { $0.range.location >= NSMaxRange(range) } |
| 369 | } |
| 370 | guard let resolved = index ?? (search.wraps ? (backward ? matches.count - 1 : 0) : nil) else { |
| 371 | findMessage = backward ? "No earlier match" : "No later match" |
| 372 | return nil |
| 373 | } |
| 374 | let match = matches[resolved] |
| 375 | matchIndex = resolved |
| 376 | lastFindSelection = match.range |
| 377 | emptyMatch = match.range.length == 0 ? (search, change, match.range) : nil |
| 378 | select(match.range) |
| 379 | findMessage = "\(resolved + 1) of \(matches.count)" |
| 380 | return match |
| 381 | } |
| 382 | |
| 383 | func findNext(backward: Bool = false) { |
| 384 | if isShowingMarkdownPreview { showsPreview = false } |
| 385 | _ = find(backward: backward) |
| 386 | } |
| 387 | |
| 388 | func replaceOne() { |
| 389 | let query = search |
| 390 | do { |
| 391 | let range = editor.selectedRange() |
| 392 | let results = try query.matches(in: text) |
| 393 | let isCurrentEmptyMatch = emptyMatch.map { $0.query == query && $0.version == change && $0.range == range } == true |
| 394 | let current = range.length > 0 || isCurrentEmptyMatch ? results.first(where: { $0.range == range }) : nil |
| 395 | guard let match = current ?? find(backward: false) else { return } |
| 396 | let value = try query.replacementText(replacement, for: match, in: text) |
| 397 | replace(range: match.range, with: value, action: "Replace") |
| 398 | _ = find(backward: false) |
| 399 | } catch { findMessage = "Invalid regular expression" } |
| 400 | } |
| 401 | |
| 402 | func replaceAll() { |
| 403 | do { |
| 404 | let result = try search.replacingAll(in: text, with: replacement) |
| 405 | if result.count > 0 { |
| 406 | replace(range: NSRange(location: 0, length: text.utf16.count), with: result.text, action: "Replace All") |
| 407 | } |
| 408 | findTask?.cancel() |
| 409 | findMessage = result.count == 1 ? "1 replaced" : "\(result.count) replaced" |
| 410 | } catch { findMessage = "Invalid regular expression" } |
| 411 | } |
| 412 | |
| 413 | private func queueColoring(clear: Bool = false) { |
| 414 | colorTask?.cancel() |
| 415 | let language = self.language |
| 416 | if clear || language == .plain { applyColors([]) } |
| 417 | guard language != .plain else { return } |
| 418 | let input = text |
| 419 | let version = change |
| 420 | colorTask = Task { [weak self] in |
| 421 | try? await Task.sleep(for: .milliseconds(140)) |
| 422 | guard !Task.isCancelled else { return } |
| 423 | let tokens = await Task.detached(priority: .utility) { language.tokens(in: input) }.value |
| 424 | guard !Task.isCancelled, let self, self.change == version, self.language == language else { return } |
| 425 | self.applyColors(tokens) |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | private func applyColors(_ tokens: [SyntaxLanguage.Token]) { |
| 430 | guard let layout = editor.layoutManager, let storage = editor.textStorage else { return } |
| 431 | layout.removeTemporaryAttribute(.foregroundColor, forCharacterRange: NSRange(location: 0, length: storage.length)) |
| 432 | for token in tokens { |
| 433 | layout.addTemporaryAttribute(.foregroundColor, value: token.kind.color, forCharacterRange: token.range) |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | private extension SyntaxLanguage.TokenKind { |
| 439 | var color: NSColor { |
| 440 | switch self { |
| 441 | case .comment: return .secondaryLabelColor |
| 442 | case .quoted: return .systemRed |
| 443 | case .keyword: return .systemPurple |
| 444 | case .number: return .systemBlue |
| 445 | case .heading: return .systemBlue |
| 446 | case .property: return .systemTeal |
| 447 | } |
| 448 | } |
| 449 | } |