import AppKit import PlakCore /// The editor over a code block: the same font, colours and place as the block, highlighted while you type. final class CodeEditorView: NSTextView, ObjectEditor { let kind: FenceKind private let original: String /// Its own undo, so that edits in the code never mix with the undo of the page. private let ownUndo = UndoManager() var onEnd: ((EditorExit) -> Void)? var onResize: (() -> Void)? var onChange: (() -> Void)? init(kind: FenceKind, body: String, font: NSFont) { self.kind = kind original = body let storage = NSTextStorage() let layout = NSLayoutManager() storage.addLayoutManager(layout) let container = NSTextContainer(size: NSSize(width: 100, height: CGFloat.greatestFiniteMagnitude)) container.widthTracksTextView = true container.lineFragmentPadding = 0 layout.addTextContainer(container) super.init(frame: NSRect(x: 0, y: 0, width: 100, height: 100), textContainer: container) isRichText = false importsGraphics = false usesFontPanel = false usesRuler = false allowsUndo = true isVerticallyResizable = false isHorizontallyResizable = false drawsBackground = true backgroundColor = Theme.codePaper wantsLayer = true layer?.cornerRadius = PageMetrics.codeCornerRadius layer?.masksToBounds = true textContainerInset = NSSize(width: PageMetrics.codePadding, height: PageMetrics.codePadding) isAutomaticQuoteSubstitutionEnabled = false isAutomaticDashSubstitutionEnabled = false isAutomaticTextReplacementEnabled = false isAutomaticSpellingCorrectionEnabled = false isAutomaticLinkDetectionEnabled = false isAutomaticDataDetectionEnabled = false isContinuousSpellCheckingEnabled = false smartInsertDeleteEnabled = false insertionPointColor = Theme.accent selectedTextAttributes = [.backgroundColor: Theme.selection] storage.setAttributedString(NSAttributedString(string: body, attributes: CodeStyle.attributes(font))) typingAttributes = CodeStyle.attributes(font) colorize() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } var view: NSView { self } var focusView: NSView { self } override var undoManager: UndoManager? { ownUndo } func size(available width: CGFloat) -> NSSize { if frame.width != width { setFrameSize(NSSize(width: width, height: frame.height)) } guard let layoutManager, let textContainer else { return NSSize(width: width, height: frame.height) } layoutManager.ensureLayout(for: textContainer) return NSSize(width: width, height: ceil(layoutManager.usedRect(for: textContainer).height) + textContainerInset.height * 2) } func setFont(_ font: NSFont) { typingAttributes = CodeStyle.attributes(font) textStorage?.setAttributes(typingAttributes, range: NSRange(location: 0, length: textStorage?.length ?? 0)) colorize() onResize?() } func edit() -> ObjectEdit { let body = PageFile.unixNewlines(string) if body == original { return .unchanged } if PageFile.isBlank(body) { return .removed } return .replaced(kind, body) } private func colorize() { guard let layoutManager else { return } CodeStyle.colorize(layoutManager, text: string, kind: kind) } /// A composition keeps its marked-text look until it is committed. override func didChangeText() { super.didChangeText() if !hasMarkedText() { colorize() } onResize?() onChange?() } // MARK: Keys /// A key command the editor does not know beeps, so it never reaches the page behind it. override func doCommand(by selector: Selector) { if responds(to: selector) { super.doCommand(by: selector) } else { NSSound.beep() } } override func insertTab(_ sender: Any?) { insertText(" ", replacementRange: selectedRange()) } /// Esc closes the editor and never hides Plak; during an input-method composition it only cancels that. override func cancelOperation(_ sender: Any?) { if hasMarkedText() { inputContext?.discardMarkedText() unmarkText() } else { onEnd?(.after) } } override func moveUp(_ sender: Any?) { isOnLine(first: true) ? onEnd?(.above) : super.moveUp(sender) } override func moveDown(_ sender: Any?) { isOnLine(first: false) ? onEnd?(.below) : super.moveDown(sender) } /// Whether the caret is on the first or the last laid-out line. private func isOnLine(first: Bool) -> Bool { guard let layoutManager, let textContainer, selectedRange().length == 0 else { return false } layoutManager.ensureLayout(for: textContainer) let length = (string as NSString).length guard length > 0 else { return true } let caret = lineRect(at: selectedRange().location) let edge = first ? lineRect(at: 0) : lineRect(at: length) return abs(caret.minY - edge.minY) < 0.5 } private func lineRect(at location: Int) -> NSRect { guard let layoutManager else { return .zero } let length = (string as NSString).length if location >= length, !layoutManager.extraLineFragmentRect.isEmpty { return layoutManager.extraLineFragmentRect } let glyph = layoutManager.glyphIndexForCharacter(at: min(location, length - 1)) return layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) } // MARK: Undo @objc func undo(_ sender: Any?) { ownUndo.undo() } @objc func redo(_ sender: Any?) { ownUndo.redo() } override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { switch item.action { case #selector(undo(_:)): ownUndo.canUndo case #selector(redo(_:)): ownUndo.canRedo default: super.validateUserInterfaceItem(item) } } }