Skip to content

armgit / chops

Public Imported from GitHub
0

Your AI agent skills, finally organized. A macOS app to browse, edit, and manage skills across Claude Code, Cursor, Codex, Windsurf, and Amp.

feat: rewrite markdown editor with NSTextView, syntax highlighting, and formatting commands (#65)

Josh Pigford224fe4f58922
diff --git a/Chops.xcodeproj/project.pbxproj b/Chops.xcodeproj/project.pbxproj
index c08c940..da51d83 100644
--- a/Chops.xcodeproj/project.pbxproj
+++ b/Chops.xcodeproj/project.pbxproj
@@ -25,14 +25,17 @@
801A39D725B59A2F2BAF5DF2 /* cmark in Frameworks */ = {isa = PBXBuildFile; productRef = 9F4BE66CFE1E8401894FEF1F /* cmark */; };
846B58F3B105D1734DC6FA75 /* SkillRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FC9D3E83D8640CC258CF361 /* SkillRegistry.swift */; };
87A469B631CC80C89B14B1C7 /* SkillMetadataBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C812515FD8DC222B89745F2 /* SkillMetadataBar.swift */; };
+ 91EA572FCA75A2EA848C3429 /* ChopsTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A58EBE34E8A678FC897DFCB /* ChopsTextView.swift */; };
95163AEB7980654C901EC693 /* Skill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27D6ED655F951177D2152351 /* Skill.swift */; };
98434D3DDFEEC7239F6F7B79 /* RegistrySheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FCD6C2A8BE68F553A9CA392 /* RegistrySheet.swift */; };
99EE8F6124FE91AC9576D6FD /* FileWatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAD26AA4787A2E0CDC86AADC /* FileWatcher.swift */; };
A99BA179E0520DCDC98E1382 /* AppLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45D5C8E8C732B2F4A867E43 /* AppLogger.swift */; };
AAC4A3CBF2A9B4DF50608948 /* SSHService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6797D4AC1970DB9ACB5ACA73 /* SSHService.swift */; };
AFDC3DAB708B352A7606F119 /* DiagnosticExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5D3C2567FBF8DBA4DE957B3 /* DiagnosticExporter.swift */; };
+ B4526ECE136AC044CD3C7603 /* EditorTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = D24B049638C76AC6248FD5D2 /* EditorTheme.swift */; };
B5B95B9DA63A734F25470FF5 /* SchemaVersions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1F8AA042D5D8A9F92F35CA3 /* SchemaVersions.swift */; };
BD584933CCE2B650345C4CF1 /* ToolSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5487D9027B97F7E9EE9A1F4A /* ToolSource.swift */; };
+ BFF9964529E6C48F4F7BCB97 /* MarkdownSyntaxHighlighter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 135976FA0E8358E099157DE1 /* MarkdownSyntaxHighlighter.swift */; };
C30BEAE03E54BD36F257A925 /* ToolFilterView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A5774429CCE83C2AFBE046C /* ToolFilterView.swift */; };
C6CFF37CC0B155E8846344A4 /* ChopsIcon.icon in Resources */ = {isa = PBXBuildFile; fileRef = 04C3C644B72DD508A7CBC403 /* ChopsIcon.icon */; };
CBD8FECF1C5A453C8B021665 /* FrontmatterParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C77C5B30E6C885B39444E5B /* FrontmatterParser.swift */; };
@@ -49,6 +52,7 @@
/* Begin PBXFileReference section */
04C3C644B72DD508A7CBC403 /* ChopsIcon.icon */ = {isa = PBXFileReference; lastKnownFileType = wrapper.icon; path = ChopsIcon.icon; sourceTree = "<group>"; };
+ 135976FA0E8358E099157DE1 /* MarkdownSyntaxHighlighter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownSyntaxHighlighter.swift; sourceTree = "<group>"; };
168E103488DEA623E712852B /* SkillDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillDetailView.swift; sourceTree = "<group>"; };
17F7FE50C96124BA4EE43A6F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
231C267216AF1BCA8628B667 /* AppState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppState.swift; sourceTree = "<group>"; };
@@ -68,6 +72,7 @@
7C77C5B30E6C885B39444E5B /* FrontmatterParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FrontmatterParser.swift; sourceTree = "<group>"; };
7FCD6C2A8BE68F553A9CA392 /* RegistrySheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RegistrySheet.swift; sourceTree = "<group>"; };
7FFC47BDE92105F4736B379F /* SearchService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SearchService.swift; sourceTree = "<group>"; };
+ 8A58EBE34E8A678FC897DFCB /* ChopsTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChopsTextView.swift; sourceTree = "<group>"; };
8C812515FD8DC222B89745F2 /* SkillMetadataBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillMetadataBar.swift; sourceTree = "<group>"; };
907E59B064AB8366B60BF611 /* AgentTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTarget.swift; sourceTree = "<group>"; };
9A5774429CCE83C2AFBE046C /* ToolFilterView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolFilterView.swift; sourceTree = "<group>"; };
@@ -79,6 +84,7 @@
B3F5CF5BB1FC8455FDDB004A /* Chops.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Chops.app; sourceTree = BUILT_PRODUCTS_DIR; };
C9AFE1AF02B0F8057791C2A9 /* Collection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Collection.swift; sourceTree = "<group>"; };
CAD26AA4787A2E0CDC86AADC /* FileWatcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileWatcher.swift; sourceTree = "<group>"; };
+ D24B049638C76AC6248FD5D2 /* EditorTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EditorTheme.swift; sourceTree = "<group>"; };
D5D3C2567FBF8DBA4DE957B3 /* DiagnosticExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticExporter.swift; sourceTree = "<group>"; };
E684304D1723CA691F40335B /* RemoteServersSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteServersSettingsView.swift; sourceTree = "<group>"; };
E6A5B26D335C1AFB6CDE8207 /* SkillScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillScanner.swift; sourceTree = "<group>"; };
@@ -214,6 +220,9 @@
96A2A820C082754BBFB0237D /* Detail */ = {
isa = PBXGroup;
children = (
+ 8A58EBE34E8A678FC897DFCB /* ChopsTextView.swift */,
+ D24B049638C76AC6248FD5D2 /* EditorTheme.swift */,
+ 135976FA0E8358E099157DE1 /* MarkdownSyntaxHighlighter.swift */,
168E103488DEA623E712852B /* SkillDetailView.swift */,
31B4DB87833D5160A11E39C9 /* SkillEditorView.swift */,
8C812515FD8DC222B89745F2 /* SkillMetadataBar.swift */,
@@ -319,14 +328,17 @@
A99BA179E0520DCDC98E1382 /* AppLogger.swift in Sources */,
25A4FB387DB5BD96DB630C14 /* AppState.swift in Sources */,
309B12E0B72A22C9772BBC99 /* ChopsApp.swift in Sources */,
+ 91EA572FCA75A2EA848C3429 /* ChopsTextView.swift in Sources */,
7A17C99C5EFAE3AA9E788D50 /* Collection.swift in Sources */,
7EC6156934D559226BC78859 /* CollectionListView.swift in Sources */,
D4C107BE303FC07CAF9C66AF /* ContentView.swift in Sources */,
AFDC3DAB708B352A7606F119 /* DiagnosticExporter.swift in Sources */,
+ B4526ECE136AC044CD3C7603 /* EditorTheme.swift in Sources */,
99EE8F6124FE91AC9576D6FD /* FileWatcher.swift in Sources */,
CBD8FECF1C5A453C8B021665 /* FrontmatterParser.swift in Sources */,
7FD1DE6640F9339D5E97E09A /* MDCParser.swift in Sources */,
E7ED248D6F94C1B1DEF1E8BA /* MarkdownRenderer.swift in Sources */,
+ BFF9964529E6C48F4F7BCB97 /* MarkdownSyntaxHighlighter.swift in Sources */,
71E92A838AB4D1D6DC6174AF /* NewSkillSheet.swift in Sources */,
98434D3DDFEEC7239F6F7B79 /* RegistrySheet.swift in Sources */,
5B81DED237A60776ADB04134 /* RemoteServer.swift in Sources */,
diff --git a/Chops/Views/Detail/ChopsTextView.swift b/Chops/Views/Detail/ChopsTextView.swift
new file mode 100644
index 0000000..516781a
--- /dev/null
+++ b/Chops/Views/Detail/ChopsTextView.swift
@@ -0,0 +1,232 @@
+import AppKit
+
+final class ChopsTextView: NSTextView {
+
+ // MARK: - Cursor
+
+ override func didAddSubview(_ subview: NSView) {
+ super.didAddSubview(subview)
+ if let indicator = subview as? NSTextInsertionIndicator {
+ indicator.displayMode = .hidden
+ }
+ }
+
+ override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) {
+ var adjusted = rect
+ adjusted.size.width = 2
+ super.drawInsertionPoint(in: adjusted, color: color, turnedOn: flag)
+ }
+
+ override func setNeedsDisplay(_ rect: NSRect, avoidAdditionalLayout flag: Bool) {
+ var rect = rect
+ rect.size.width += 2
+ super.setNeedsDisplay(rect, avoidAdditionalLayout: flag)
+ }
+
+ // MARK: - Find
+
+ @objc func showFindPanel(_ sender: Any?) {
+ let item = NSMenuItem()
+ item.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
+ performFindPanelAction(item)
+ }
+
+ override func performKeyEquivalent(with event: NSEvent) -> Bool {
+ guard event.modifierFlags.contains(.command) else {
+ return super.performKeyEquivalent(with: event)
+ }
+ if event.charactersIgnoringModifiers == "f" {
+ showFindPanel(nil)
+ return true
+ }
+ return super.performKeyEquivalent(with: event)
+ }
+
+ // MARK: - Markdown Formatting
+
+ @objc func toggleBold(_ sender: Any?) {
+ wrapSelection(prefix: "**", suffix: "**", placeholder: "bold text")
+ }
+
+ @objc func toggleItalic(_ sender: Any?) {
+ wrapSelection(prefix: "*", suffix: "*", placeholder: "italic text")
+ }
+
+ @objc func insertLink(_ sender: Any?) {
+ let range = selectedRange()
+ let selected = (string as NSString).substring(with: range)
+ if selected.isEmpty {
+ insertText("[link text](url)", replacementRange: range)
+ let urlStart = range.location + "[link text](".utf16.count
+ setSelectedRange(NSRange(location: urlStart, length: "url".utf16.count))
+ } else {
+ insertText("[\(selected)](url)", replacementRange: range)
+ let urlStart = range.location + "[\(selected)](".utf16.count
+ setSelectedRange(NSRange(location: urlStart, length: "url".utf16.count))
+ }
+ }
+
+ @objc func insertHeading(_ sender: Any?) {
+ let range = selectedRange()
+ let lineRange = (string as NSString).lineRange(for: range)
+ let line = (string as NSString).substring(with: lineRange)
+
+ let trimmed = line.drop(while: { $0 == "#" || $0 == " " })
+ let hashes = line.prefix(while: { $0 == "#" })
+
+ let newLine: String
+ switch hashes.count {
+ case 0: newLine = "# \(trimmed)"
+ case 1: newLine = "## \(trimmed)"
+ case 2: newLine = "### \(trimmed)"
+ default: newLine = String(trimmed)
+ }
+
+ insertText(newLine, replacementRange: lineRange)
+ }
+
+ @objc func toggleStrikethrough(_ sender: Any?) {
+ wrapSelection(prefix: "~~", suffix: "~~", placeholder: "strikethrough text")
+ }
+
+ @objc func toggleBulletList(_ sender: Any?) {
+ toggleLinePrefix(prefix: "- ", placeholder: "list item")
+ }
+
+ @objc func toggleNumberedList(_ sender: Any?) {
+ let range = selectedRange()
+ let selected = (string as NSString).substring(with: range)
+ if selected.isEmpty {
+ insertText("1. list item", replacementRange: range)
+ let start = range.location + "1. ".utf16.count
+ setSelectedRange(NSRange(location: start, length: "list item".utf16.count))
+ return
+ }
+ let lineRange = (string as NSString).lineRange(for: range)
+ let block = (string as NSString).substring(with: lineRange)
+ let lines = block.components(separatedBy: "\n")
+ var result: [String] = []
+ var num = 1
+ for line in lines {
+ if line.isEmpty {
+ result.append(line)
+ } else {
+ result.append("\(num). \(line)")
+ num += 1
+ }
+ }
+ insertText(result.joined(separator: "\n"), replacementRange: lineRange)
+ }
+
+ @objc func toggleTodoList(_ sender: Any?) {
+ toggleLinePrefix(prefix: "- [ ] ", placeholder: "task")
+ }
+
+ @objc func toggleBlockquote(_ sender: Any?) {
+ toggleLinePrefix(prefix: "> ", placeholder: "quote")
+ }
+
+ @objc func insertHorizontalRule(_ sender: Any?) {
+ let range = selectedRange()
+ insertText("\n\n---\n\n", replacementRange: range)
+ }
+
+ @objc func insertMarkdownTable(_ sender: Any?) {
+ let range = selectedRange()
+ let table = "| Column 1 | Column 2 | Column 3 |\n| --- | --- | --- |\n| Cell | Cell | Cell |"
+ insertText(table, replacementRange: range)
+ }
+
+ @objc func toggleInlineCode(_ sender: Any?) {
+ wrapSelection(prefix: "`", suffix: "`", placeholder: "code")
+ }
+
+ @objc func insertCodeBlock(_ sender: Any?) {
+ let range = selectedRange()
+ let selected = (string as NSString).substring(with: range)
+ if selected.isEmpty {
+ let snippet = "```\ncode\n```"
+ insertText(snippet, replacementRange: range)
+ let start = range.location + "```\n".utf16.count
+ setSelectedRange(NSRange(location: start, length: "code".utf16.count))
+ } else {
+ insertText("```\n\(selected)\n```", replacementRange: range)
+ }
+ }
+
+ // MARK: - Context Menu
+
+ override func menu(for event: NSEvent) -> NSMenu? {
+ let menu = super.menu(for: event) ?? NSMenu()
+
+ let formatMenu = NSMenu(title: "Text Format")
+
+ formatMenu.addItem(withTitle: "Headers", action: #selector(insertHeading(_:)), keyEquivalent: "")
+ formatMenu.addItem(.separator())
+
+ let boldItem = formatMenu.addItem(withTitle: "Bold", action: #selector(toggleBold(_:)), keyEquivalent: "b")
+ boldItem.keyEquivalentModifierMask = .command
+ let italicItem = formatMenu.addItem(withTitle: "Italic", action: #selector(toggleItalic(_:)), keyEquivalent: "i")
+ italicItem.keyEquivalentModifierMask = .command
+ let strikeItem = formatMenu.addItem(withTitle: "Strikethrough", action: #selector(toggleStrikethrough(_:)), keyEquivalent: "x")
+ strikeItem.keyEquivalentModifierMask = [.command, .shift]
+ formatMenu.addItem(.separator())
+
+ formatMenu.addItem(withTitle: "Insert Link", action: #selector(insertLink(_:)), keyEquivalent: "")
+ formatMenu.addItem(.separator())
+
+ formatMenu.addItem(withTitle: "List", action: #selector(toggleBulletList(_:)), keyEquivalent: "")
+ formatMenu.addItem(withTitle: "Ordered List", action: #selector(toggleNumberedList(_:)), keyEquivalent: "")
+ formatMenu.addItem(withTitle: "Todo", action: #selector(toggleTodoList(_:)), keyEquivalent: "")
+ formatMenu.addItem(.separator())
+
+ formatMenu.addItem(withTitle: "Quote", action: #selector(toggleBlockquote(_:)), keyEquivalent: "")
+ formatMenu.addItem(withTitle: "Horizontal Rule", action: #selector(insertHorizontalRule(_:)), keyEquivalent: "")
+ formatMenu.addItem(withTitle: "Table", action: #selector(insertMarkdownTable(_:)), keyEquivalent: "")
+ formatMenu.addItem(.separator())
+
+ formatMenu.addItem(withTitle: "Code", action: #selector(toggleInlineCode(_:)), keyEquivalent: "")
+ formatMenu.addItem(withTitle: "Code Block", action: #selector(insertCodeBlock(_:)), keyEquivalent: "")
+
+ let formatItem = NSMenuItem(title: "Text Format", action: nil, keyEquivalent: "")
+ formatItem.submenu = formatMenu
+
+ menu.insertItem(.separator(), at: 0)
+ menu.insertItem(formatItem, at: 0)
+
+ return menu
+ }
+
+ // MARK: - Helpers
+
+ private func toggleLinePrefix(prefix: String, placeholder: String) {
+ let range = selectedRange()
+ let selected = (string as NSString).substring(with: range)
+ if selected.isEmpty {
+ let text = "\(prefix)\(placeholder)"
+ insertText(text, replacementRange: range)
+ let start = range.location + prefix.utf16.count
+ setSelectedRange(NSRange(location: start, length: placeholder.utf16.count))
+ return
+ }
+ let lineRange = (string as NSString).lineRange(for: range)
+ let block = (string as NSString).substring(with: lineRange)
+ let lines = block.components(separatedBy: "\n")
+ let result = lines.map { $0.isEmpty ? $0 : "\(prefix)\($0)" }
+ insertText(result.joined(separator: "\n"), replacementRange: lineRange)
+ }
+
+ private func wrapSelection(prefix: String, suffix: String, placeholder: String) {
+ let range = selectedRange()
+ let selected = (string as NSString).substring(with: range)
+ if selected.isEmpty {
+ let text = "\(prefix)\(placeholder)\(suffix)"
+ insertText(text, replacementRange: range)
+ let placeholderStart = range.location + prefix.utf16.count
+ setSelectedRange(NSRange(location: placeholderStart, length: placeholder.utf16.count))
+ } else {
+ let text = "\(prefix)\(selected)\(suffix)"
+ insertText(text, replacementRange: range)
+ }
+ }
+}
diff --git a/Chops/Views/Detail/EditorTheme.swift b/Chops/Views/Detail/EditorTheme.swift
new file mode 100644
index 0000000..b02d1f5
--- /dev/null
+++ b/Chops/Views/Detail/EditorTheme.swift
@@ -0,0 +1,90 @@
+import AppKit
+
+enum EditorTheme {
+ // MARK: - Editor Font
+
+ static let editorFontSize: CGFloat = 13
+ static let editorFont = NSFont.monospacedSystemFont(ofSize: editorFontSize, weight: .regular)
+
+ // MARK: - Margins
+
+ static let editorInsetX: CGFloat = 48
+ static let editorInsetTop: CGFloat = 12
+
+ // MARK: - Line Spacing
+
+ static let lineSpacing: CGFloat = 6
+
+ static var editorLineHeight: CGFloat {
+ let font = editorFont
+ return ceil(font.ascender - font.descender + font.leading) + lineSpacing
+ }
+
+ static var editorBaselineOffset: CGFloat {
+ let font = editorFont
+ let naturalHeight = ceil(font.ascender - font.descender + font.leading)
+ return (editorLineHeight - naturalHeight) / 2
+ }
+
+ // MARK: - Dynamic Colors
+
+ static let textColor = NSColor(name: "editorText") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.878, green: 0.878, blue: 0.878, alpha: 1)
+ : NSColor(red: 0.133, green: 0.133, blue: 0.133, alpha: 1)
+ }
+
+ static let syntaxColor = NSColor(name: "editorSyntax") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.45, green: 0.45, blue: 0.45, alpha: 1)
+ : NSColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
+ }
+
+ static let headingColor = NSColor(name: "editorHeading") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
+ : NSColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1)
+ }
+
+ static let boldColor = NSColor(name: "editorBold") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
+ : NSColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1)
+ }
+
+ static let italicColor = NSColor(name: "editorItalic") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1)
+ : NSColor(red: 0.25, green: 0.25, blue: 0.25, alpha: 1)
+ }
+
+ static let codeColor = NSColor(name: "editorCode") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.9, green: 0.45, blue: 0.45, alpha: 1)
+ : NSColor(red: 0.75, green: 0.2, blue: 0.2, alpha: 1)
+ }
+
+ static let linkColor = NSColor(name: "editorLink") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.4, green: 0.6, blue: 0.9, alpha: 1)
+ : NSColor(red: 0.2, green: 0.4, blue: 0.7, alpha: 1)
+ }
+
+ static let blockquoteColor = NSColor(name: "editorBlockquote") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
+ : NSColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1)
+ }
+
+ static let frontmatterColor = NSColor(name: "editorFrontmatter") { appearance in
+ appearance.isDark
+ ? NSColor(red: 0.55, green: 0.55, blue: 0.65, alpha: 1)
+ : NSColor(red: 0.35, green: 0.35, blue: 0.5, alpha: 1)
+ }
+}
+
+extension NSAppearance {
+ var isDark: Bool {
+ bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ }
+}
diff --git a/Chops/Views/Detail/MarkdownSyntaxHighlighter.swift b/Chops/Views/Detail/MarkdownSyntaxHighlighter.swift
new file mode 100644
index 0000000..d5544c2
--- /dev/null
+++ b/Chops/Views/Detail/MarkdownSyntaxHighlighter.swift
@@ -0,0 +1,258 @@
+import AppKit
+
+final class MarkdownSyntaxHighlighter: NSObject {
+
+ private var isHighlighting = false
+
+ // MARK: - Regex Patterns
+
+ private static let frontmatterKeyRegex: NSRegularExpression? = try? NSRegularExpression(
+ pattern: "^([\\w][\\w\\s.-]*)(:)",
+ options: .anchorsMatchLines
+ )
+
+ private static let patterns: [(NSRegularExpression, HighlightStyle)] = {
+ var result: [(NSRegularExpression, HighlightStyle)] = []
+
+ func add(_ pattern: String, _ style: HighlightStyle, options: NSRegularExpression.Options = []) {
+ if let regex = try? NSRegularExpression(pattern: pattern, options: options) {
+ result.append((regex, style))
+ }
+ }
+
+ // Frontmatter (--- ... ---) at very start of file
+ add("\\A---[ \\t]*\\n([\\s\\S]*?)\\n---[ \\t]*(?:\\n|\\z)", .frontmatter)
+
+ // Fenced code blocks (``` ... ```)
+ add("^(`{3,})(.*?)\\n([\\s\\S]*?)^\\1\\s*$", .codeBlock, options: .anchorsMatchLines)
+
+ // Headings: # Heading
+ add("^(#{1,6}\\s+)(.+)$", .heading, options: .anchorsMatchLines)
+
+ // Bold: **text** or __text__
+ add("(\\*\\*|__)(.+?)(\\1)", .bold)
+
+ // Italic: *text* or _text_
+ add("(?<![\\w*])(\\*|_)(?!\\s)(.+?)(?<!\\s)\\1(?![\\w*])", .italic)
+
+ // Strikethrough: ~~text~~
+ add("(~~)(.+?)(~~)", .strikethrough)
+
+ // Inline code: `code`
+ add("(`+)(.+?)(\\1)", .inlineCode)
+
+ // Links: [text](url)
+ add("(\\[)(.+?)(\\]\\(.+?\\))", .link)
+
+ // Blockquotes: > text
+ add("^(>+\\s?)(.*)$", .blockquote, options: .anchorsMatchLines)
+
+ // Unordered list markers: - or * or +
+ add("^(\\s*[-*+]\\s)", .listMarker, options: .anchorsMatchLines)
+
+ // Ordered list markers: 1.
+ add("^(\\s*\\d+\\.\\s)", .listMarker, options: .anchorsMatchLines)
+
+ // Task list: - [ ] or - [x]
+ add("^(\\s*[-*+]\\s\\[[ xX]\\]\\s)", .listMarker, options: .anchorsMatchLines)
+
+ // Horizontal rule
+ add("^([-*_]{3,})\\s*$", .syntax, options: .anchorsMatchLines)
+
+ return result
+ }()
+
+ // MARK: - Highlight Styles
+
+ private enum HighlightStyle {
+ case heading
+ case bold
+ case italic
+ case strikethrough
+ case inlineCode
+ case codeBlock
+ case link
+ case blockquote
+ case listMarker
+ case syntax
+ case frontmatter
+ }
+
+ // MARK: - Highlighting
+
+ func highlightAll(_ textStorage: NSTextStorage) {
+ guard !isHighlighting else { return }
+ isHighlighting = true
+ defer { isHighlighting = false }
+
+ textStorage.beginEditing()
+ let fullRange = NSRange(location: 0, length: textStorage.length)
+ let text = textStorage.string
+
+ // Reset to default style
+ let paragraph = NSMutableParagraphStyle()
+ paragraph.minimumLineHeight = EditorTheme.editorLineHeight
+ paragraph.maximumLineHeight = EditorTheme.editorLineHeight
+
+ textStorage.setAttributes([
+ .font: EditorTheme.editorFont,
+ .foregroundColor: EditorTheme.textColor,
+ .paragraphStyle: paragraph,
+ .baselineOffset: EditorTheme.editorBaselineOffset
+ ], range: fullRange)
+
+ // Track code/frontmatter block ranges to skip inner highlighting
+ var codeBlockRanges: [NSRange] = []
+
+ for (regex, style) in Self.patterns {
+ regex.enumerateMatches(in: text, range: fullRange) { match, _, _ in
+ guard let match = match else { return }
+
+ // Skip if inside a protected block (unless this IS a protected block pattern)
+ if style != .codeBlock && style != .frontmatter {
+ let matchRange = match.range
+ if codeBlockRanges.contains(where: { NSIntersectionRange($0, matchRange).length > 0 }) {
+ return
+ }
+ }
+
+ switch style {
+ case .heading:
+ if match.numberOfRanges >= 3 {
+ let syntaxRange = match.range(at: 1)
+ let contentRange = match.range(at: 2)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: syntaxRange)
+ textStorage.addAttributes([
+ .foregroundColor: EditorTheme.headingColor,
+ .font: NSFont.monospacedSystemFont(ofSize: EditorTheme.editorFontSize + 4, weight: .bold)
+ ], range: contentRange)
+ }
+
+ case .bold:
+ if match.numberOfRanges >= 4 {
+ let openRange = match.range(at: 1)
+ let contentRange = match.range(at: 2)
+ let closeRange = match.range(at: 3)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: openRange)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: closeRange)
+ textStorage.addAttributes([
+ .foregroundColor: EditorTheme.boldColor,
+ .font: NSFont.monospacedSystemFont(ofSize: EditorTheme.editorFontSize, weight: .bold)
+ ], range: contentRange)
+ }
+
+ case .italic:
+ if match.numberOfRanges >= 3 {
+ let syntaxRange = match.range(at: 1)
+ let contentRange = match.range(at: 2)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: syntaxRange)
+ let closingStart = match.range(at: 2).upperBound
+ let closingRange = NSRange(location: closingStart, length: match.range(at: 1).length)
+ if closingRange.upperBound <= textStorage.length {
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: closingRange)
+ }
+ let italicFont = NSFontManager.shared.convert(EditorTheme.editorFont, toHaveTrait: .italicFontMask)
+ textStorage.addAttributes([
+ .foregroundColor: EditorTheme.italicColor,
+ .font: italicFont
+ ], range: contentRange)
+ }
+
+ case .strikethrough:
+ if match.numberOfRanges >= 4 {
+ let openRange = match.range(at: 1)
+ let contentRange = match.range(at: 2)
+ let closeRange = match.range(at: 3)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: openRange)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: closeRange)
+ textStorage.addAttributes([
+ .strikethroughStyle: NSUnderlineStyle.single.rawValue,
+ .foregroundColor: EditorTheme.syntaxColor
+ ], range: contentRange)
+ }
+
+ case .inlineCode:
+ if match.numberOfRanges >= 4 {
+ let openRange = match.range(at: 1)
+ let contentRange = match.range(at: 2)
+ let closeRange = match.range(at: 3)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: openRange)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: closeRange)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.codeColor, range: contentRange)
+ }
+
+ case .codeBlock:
+ codeBlockRanges.append(match.range)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.codeColor, range: match.range)
+ if match.numberOfRanges >= 2 {
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: match.range(at: 1))
+ }
+
+ case .link:
+ if match.numberOfRanges >= 4 {
+ let bracketRange = match.range(at: 1)
+ let textRange = match.range(at: 2)
+ let urlPartRange = match.range(at: 3)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: bracketRange)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.linkColor, range: textRange)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: urlPartRange)
+ }
+
+ case .blockquote:
+ if match.numberOfRanges >= 3 {
+ let markerRange = match.range(at: 1)
+ let contentRange = match.range(at: 2)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: markerRange)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.blockquoteColor, range: contentRange)
+ }
+
+ case .listMarker:
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: match.range)
+
+ case .syntax:
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: match.range)
+
+ case .frontmatter:
+ guard matchedText(text, range: match.range).hasPrefix("---") else { return }
+ codeBlockRanges.append(match.range)
+ let nsText = text as NSString
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.frontmatterColor, range: match.range)
+ // Color the opening --- delimiter
+ let openLineEnd = nsText.range(of: "\n", range: NSRange(location: match.range.location, length: match.range.length))
+ if openLineEnd.location != NSNotFound {
+ let openRange = NSRange(location: match.range.location, length: openLineEnd.location - match.range.location)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: openRange)
+ }
+ // Color the closing --- delimiter
+ let matchStr = nsText.substring(with: match.range) as NSString
+ let lastNewline = matchStr.range(of: "\n", options: .backwards)
+ if lastNewline.location != NSNotFound {
+ let closeStart = match.range.location + lastNewline.location + 1
+ let closeLen = match.range.location + match.range.length - closeStart
+ if closeLen > 0 {
+ let closeRange = NSRange(location: closeStart, length: closeLen)
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: closeRange)
+ }
+ }
+ // Color YAML keys within the body
+ if match.numberOfRanges >= 2 {
+ let bodyRange = match.range(at: 1)
+ if bodyRange.location != NSNotFound, let keyRegex = Self.frontmatterKeyRegex {
+ keyRegex.enumerateMatches(in: text, range: bodyRange) { keyMatch, _, _ in
+ guard let keyMatch = keyMatch, keyMatch.numberOfRanges >= 3 else { return }
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.headingColor, range: keyMatch.range(at: 1))
+ textStorage.addAttribute(.foregroundColor, value: EditorTheme.syntaxColor, range: keyMatch.range(at: 2))
+ }
+ }
+ }
+ }
+ }
+ }
+
+ textStorage.endEditing()
+ }
+
+ private func matchedText(_ text: String, range: NSRange) -> String {
+ (text as NSString).substring(with: range)
+ }
+}
diff --git a/Chops/Views/Detail/SkillEditorView.swift b/Chops/Views/Detail/SkillEditorView.swift
index 596b0ed..db1e707 100644
--- a/Chops/Views/Detail/SkillEditorView.swift
+++ b/Chops/Views/Detail/SkillEditorView.swift
@@ -227,163 +227,145 @@ extension Notification.Name {
struct HighlightedTextEditor: NSViewRepresentable {
@Binding var text: String
+ @Environment(\.colorScheme) private var colorScheme
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeNSView(context: Context) -> NSScrollView {
- let scrollView = NSTextView.scrollableTextView()
- let textView = scrollView.documentView as! NSTextView
+ let scrollView = NSScrollView()
+ scrollView.hasVerticalScroller = true
+ scrollView.hasHorizontalScroller = false
+ scrollView.drawsBackground = false
+ scrollView.autohidesScrollers = true
- textView.font = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
- textView.isEditable = true
- textView.isSelectable = true
- textView.allowsUndo = true
+ let textView = ChopsTextView()
textView.isRichText = false
- textView.usesFindBar = true
- textView.isIncrementalSearchingEnabled = true
+ textView.allowsUndo = true
+ textView.usesFindPanel = true
textView.isAutomaticQuoteSubstitutionEnabled = false
textView.isAutomaticDashSubstitutionEnabled = false
textView.isAutomaticTextReplacementEnabled = false
textView.isAutomaticSpellingCorrectionEnabled = false
- textView.textContainerInset = NSSize(width: 12, height: 12)
+
+ // Font & colors
+ textView.font = EditorTheme.editorFont
+ textView.textColor = EditorTheme.textColor
textView.backgroundColor = .clear
- textView.delegate = context.coordinator
+ // Line height with baseline centering
+ let paragraph = NSMutableParagraphStyle()
+ paragraph.minimumLineHeight = EditorTheme.editorLineHeight
+ paragraph.maximumLineHeight = EditorTheme.editorLineHeight
+ textView.defaultParagraphStyle = paragraph
+ textView.typingAttributes = [
+ .font: EditorTheme.editorFont,
+ .foregroundColor: EditorTheme.textColor,
+ .paragraphStyle: paragraph,
+ .baselineOffset: EditorTheme.editorBaselineOffset
+ ]
+
+ // Insets
+ textView.textContainerInset = NSSize(width: EditorTheme.editorInsetX, height: EditorTheme.editorInsetTop)
+ textView.textContainer?.lineFragmentPadding = 0
+
+ // Layout
+ textView.isVerticallyResizable = true
+ textView.isHorizontallyResizable = false
+ textView.autoresizingMask = [.width]
+ textView.textContainer?.widthTracksTextView = true
+ textView.layoutManager?.allowsNonContiguousLayout = true
+
+ textView.insertionPointColor = EditorTheme.textColor
+
+ // Set up highlighter and coordinator
+ let highlighter = MarkdownSyntaxHighlighter()
+ context.coordinator.highlighter = highlighter
context.coordinator.textView = textView
+ // Set text BEFORE attaching delegate to avoid triggering textDidChange during setup
textView.string = text
- MarkdownHighlighter.highlight(textView)
+ textView.delegate = context.coordinator
+
+ scrollView.documentView = textView
+
+ // Initial highlight
+ highlighter.highlightAll(textView.textStorage!)
return scrollView
}
func updateNSView(_ scrollView: NSScrollView, context: Context) {
- let textView = scrollView.documentView as! NSTextView
- if textView.string != text {
+ guard let textView = scrollView.documentView as? ChopsTextView else { return }
+
+ context.coordinator.parent = self
+
+ // Re-highlight on appearance change
+ let currentScheme = colorScheme
+ if context.coordinator.lastColorScheme != currentScheme {
+ context.coordinator.lastColorScheme = currentScheme
+ textView.insertionPointColor = EditorTheme.textColor
+
+ let paragraph = NSMutableParagraphStyle()
+ paragraph.minimumLineHeight = EditorTheme.editorLineHeight
+ paragraph.maximumLineHeight = EditorTheme.editorLineHeight
+ textView.typingAttributes = [
+ .font: EditorTheme.editorFont,
+ .foregroundColor: EditorTheme.textColor,
+ .paragraphStyle: paragraph,
+ .baselineOffset: EditorTheme.editorBaselineOffset
+ ]
+
+ context.coordinator.isHighlightingInProgress = true
+ context.coordinator.highlighter?.highlightAll(textView.textStorage!)
+ context.coordinator.isHighlightingInProgress = false
+ }
+
+ // Only update text if it changed externally (not from user typing)
+ if !context.coordinator.isUpdating && textView.string != text {
+ context.coordinator.isUpdating = true
let selectedRanges = textView.selectedRanges
textView.string = text
- MarkdownHighlighter.highlight(textView)
+ context.coordinator.isHighlightingInProgress = true
+ context.coordinator.highlighter?.highlightAll(textView.textStorage!)
+ context.coordinator.isHighlightingInProgress = false
textView.selectedRanges = selectedRanges
+ context.coordinator.isUpdating = false
}
}
+ // MARK: - Coordinator
+
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: HighlightedTextEditor
- weak var textView: NSTextView?
- private var isUpdating = false
+ var isUpdating = false
+ var isHighlightingInProgress = false
+ var highlighter: MarkdownSyntaxHighlighter?
+ weak var textView: ChopsTextView?
+ var lastColorScheme: ColorScheme?
init(_ parent: HighlightedTextEditor) {
self.parent = parent
}
func textDidChange(_ notification: Notification) {
- guard !isUpdating, let textView else { return }
- isUpdating = true
- parent.text = textView.string
- MarkdownHighlighter.highlight(textView)
- isUpdating = false
- }
- }
-}
-
-// MARK: - Markdown + YAML Frontmatter Highlighter
-
-enum MarkdownHighlighter {
- private static let muted = NSColor.secondaryLabelColor
- private static let faintBg = NSColor.quaternaryLabelColor
- static func highlight(_ textView: NSTextView) {
- let text = textView.string
- let fullRange = NSRange(location: 0, length: (text as NSString).length)
- guard let storage = textView.textStorage else { return }
-
- storage.beginEditing()
-
- let baseFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
- storage.setAttributes([
- .font: baseFont,
- .foregroundColor: NSColor.labelColor
- ], range: fullRange)
-
- let lines = text.components(separatedBy: "\n")
- var offset = 0
- var inFrontmatter = false
- var inCodeBlock = false
-
- for (index, line) in lines.enumerated() {
- let lineRange = NSRange(location: offset, length: (line as NSString).length)
-
- // Frontmatter — just dim the whole block
- if line.trimmingCharacters(in: .whitespaces) == "---" {
- if index == 0 {
- inFrontmatter = true
- storage.addAttribute(.foregroundColor, value: muted, range: lineRange)
- offset += line.count + 1
- continue
- } else if inFrontmatter {
- inFrontmatter = false
- storage.addAttribute(.foregroundColor, value: muted, range: lineRange)
- offset += line.count + 1
- continue
- }
+ guard let textView = notification.object as? NSTextView else { return }
+ if isUpdating { return }
+
+ // Highlight synchronously so colors appear on the same frame
+ isHighlightingInProgress = true
+ highlighter?.highlightAll(textView.textStorage!)
+ isHighlightingInProgress = false
+
+ // Update binding asynchronously to prevent re-entrant updateNSView
+ let newText = textView.string
+ DispatchQueue.main.async { [weak self] in
+ guard let self else { return }
+ self.isUpdating = true
+ self.parent.text = newText
+ self.isUpdating = false
}
-
- if inFrontmatter {
- storage.addAttribute(.foregroundColor, value: muted, range: lineRange)
- offset += line.count + 1
- continue
- }
-
- // Code blocks — subtle background, no color change
- if line.hasPrefix("```") {
- inCodeBlock.toggle()
- storage.addAttribute(.foregroundColor, value: muted, range: lineRange)
- offset += line.count + 1
- continue
- }
-
- if inCodeBlock {
- storage.addAttribute(.backgroundColor, value: faintBg, range: lineRange)
- offset += line.count + 1
- continue
- }
-
- // Headings — just bold + sized, same color
- if line.hasPrefix("#") {
- let level = line.prefix(while: { $0 == "#" }).count
- if level <= 6 && (line.count == level || line[line.index(line.startIndex, offsetBy: level)] == " ") {
- let size: CGFloat = [18, 16, 14, 13, 13, 13][min(level - 1, 5)]
- storage.addAttribute(.font, value: NSFont.monospacedSystemFont(ofSize: size, weight: .bold), range: lineRange)
- offset += line.count + 1
- continue
- }
- }
-
- // Inline: bold gets bold, inline code gets faint bg, that's it
- let nsLine = line as NSString
- applyRegex(#"\*\*(.+?)\*\*"#, to: nsLine, lineOffset: lineRange.location, storage: storage, attrs: [
- .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .bold)
- ])
- applyRegex(#"__(.+?)__"#, to: nsLine, lineOffset: lineRange.location, storage: storage, attrs: [
- .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .bold)
- ])
- applyRegex(#"`([^`]+)`"#, to: nsLine, lineOffset: lineRange.location, storage: storage, attrs: [
- .backgroundColor: faintBg
- ])
-
- offset += line.count + 1
- }
-
- storage.endEditing()
- }
-
- private static func applyRegex(_ pattern: String, to nsLine: NSString, lineOffset: Int, storage: NSTextStorage, attrs: [NSAttributedString.Key: Any]) {
- guard let regex = try? NSRegularExpression(pattern: pattern) else { return }
- let lineRange = NSRange(location: 0, length: nsLine.length)
- for match in regex.matches(in: nsLine as String, range: lineRange) {
- let matchRange = NSRange(location: lineOffset + match.range.location, length: match.range.length)
- storage.addAttributes(attrs, range: matchRange)
}
}
}