### Install CodeEditorView Package Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Add the CodeEditorView package to your Xcode project dependencies. Ensure both `CodeEditorView` and `LanguageSupport` products are included in your target's dependencies. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/mchakravarty/CodeEditorView.git", .upToNextMajor(from: "1.0.0")) ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "CodeEditorView", package: "CodeEditorView"), .product(name: "LanguageSupport", package: "CodeEditorView"), ] ) ] ``` -------------------------------- ### Create Inline Diagnostic Messages in Swift Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Demonstrates how to create and manage diagnostic messages for inline display in the CodeEditorView. Includes examples for errors, warnings, and live execution markers. ```swift import LanguageSupport // Create messages at specific source locations var messages: Set> = [] // Error on line 3 (zero-based line 2), column 5 let typeError = TextLocated( location: TextLocation(zeroBasedLine: 2, column: 4), entity: Message( category: .error, length: 12, // highlight 12 characters summary: "Type mismatch: expected 'Int', got 'String'", description: AttributedString("Cannot convert value of type 'String' to expected argument type 'Int'.\nConsider using 'Int(value)' to convert.") ) ) // Warning on line 7 let unusedVar = TextLocated( location: TextLocation(zeroBasedLine: 6, column: 0), entity: Message( category: .warning, length: 5, summary: "Variable 'count' was never used", description: nil ) ) messages.insert(typeError) messages.insert(unusedVar) // Live execution marker (e.g., debugger stepping position) let liveMarker = TextLocated( location: TextLocation(zeroBasedLine: 10, column: 0), entity: Message(category: .live, length: 0, summary: "→", description: nil) ) messages.insert(liveMarker) // Use in the editor view CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) ``` -------------------------------- ### Display Editor State with CodeEditor.Info Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Use CodeEditor.SetInfo to receive editor state like language and selection summary for display in a status bar. This example shows how to bind editorInfo to the environment value and format the status text. ```swift import SwiftUI import CodeEditorView struct EditorView: View { @State private var text = "" @State private var position = CodeEditor.Position() @State private var messages: Set> = [] @State private var editorInfo = CodeEditor.Info() var statusText: String { switch editorInfo.selectionSummary { case .insertionPoint(let line, let col): return "\(editorInfo.language) Ln \(line), Col \(col)" case .characters(let n): return "\(n) characters selected" case .lines(let n): return "\(n) lines selected" case .ranges(let n): return "\(n) ranges selected" } } var body: some View { VStack(spacing: 0) { CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) .environment(\.codeEditorSetInfo, CodeEditor.SetInfo { self.editorInfo = $0 }) Text(statusText) .font(.caption) .frame(maxWidth: .infinity, alignment: .trailing) .padding(.horizontal, 8) } } } ``` -------------------------------- ### Message Initialization for CodeEditor Source: https://github.com/mchakravarty/codeeditorview/blob/main/Documentation/Overview.md Illustrates how to create a message object to be displayed within the CodeEditor. This includes specifying the message category, length, a summary, and an optional detailed description. ```swift init(category: Message.Category, length: Int, summary: String, description: NSAttributedString?) ``` -------------------------------- ### Handle Source Positions with TextLocation in Swift Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Illustrates how to use TextLocation for zero-based and one-based line/column positioning, and TextLocated for associating entities with these positions. Also shows FileLocation for multi-file contexts. ```swift import LanguageSupport import System // Zero-based construction let loc0 = TextLocation(zeroBasedLine: 0, column: 0) // line 1, column 1 in editor // One-based construction (natural for user-visible line numbers) let loc1 = TextLocation(oneBasedLine: 5, column: 12) // line 5, col 12 // Round-trip print(loc1.zeroBasedLine) // 4 print(loc1.oneBasedLine) // 5 print(loc1.oneBasedColumn) // 12 // Locate any entity at a source position let located = TextLocated(location: loc1, entity: "some diagnostic payload") // File-specific location let fileLoc = FileLocation( file: FilePath("/Sources/MyApp/main.swift"), oneBasedLine: 10, column: 3 ) let fileLocated = FileLocated(location: fileLoc, entity: myDiagnostic) ``` -------------------------------- ### Basic CodeEditor Usage in SwiftUI Source: https://github.com/mchakravarty/codeeditorview/blob/main/Documentation/Overview.md Demonstrates the typical integration of the CodeEditor view within a SwiftUI ContentView. It shows how to bind text, edit position, and messages, and how to apply themes based on the color scheme. ```swift struct ContentView: View { @State private var text: String = "My awesome code..." @State private var messages: Set> = Set () @Environment(\.colorScheme) private var colorScheme: ColorScheme @SceneStorage("editPosition") private var editPosition: CodeEditor.Position = CodeEditor.Position() var body: some View { CodeEditor(text: $text, position: $editPosition, messages: $messages, language: .swift) .environment(\.codeEditorTheme, colorScheme == .dark ? Theme.defaultDark : Theme.defaultLight) } } ``` -------------------------------- ### Standard Layout Configuration Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Utilize the predefined `.standard` layout configuration for `CodeEditor.LayoutConfiguration`, which typically enables the minimap and text wrapping. ```swift // Predefined standard layout (minimap on, wrap on) let standard: CodeEditor.LayoutConfiguration = .standard ``` -------------------------------- ### Configure Editor Layout (Minimap and Wrapping) Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Control the editor's layout, including showing the minimap and enabling/disabling text wrapping, using the `CodeEditor.LayoutConfiguration` struct. Inject this configuration via the `codeEditorLayoutConfiguration` environment value. ```swift struct EditorView: View { @State private var text = "" @State private var position = CodeEditor.Position() @State private var messages: Set> = [] var body: some View { CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) // Show minimap; disable line wrapping .environment(\.codeEditorLayoutConfiguration, CodeEditor.LayoutConfiguration(showMinimap: true, wrapText: false)) } } ``` -------------------------------- ### Create Code Completion Items Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Build a code completion item using Completions.Completion. This includes views for the row and documentation panel, insertion details, and an optional async refinement callback. Ensure LanguageSupport is imported. ```swift import LanguageSupport // Build a completion item let item = Completions.Completion( id: 0, rowView: { isSelected in HStack { Image(systemName: "function") Text("greet(name:)") .fontWeight(isSelected ? .bold : .regular) } .eraseToAnyView() }, documentationView: Text("Prints a greeting message for the given name.").eraseToAnyView(), selected: true, sortText: "greet", filterText: "greet", insertText: "greet(name: )", insertRange: NSRange(location: 42, length: 3), // replaces "gre" the user typed commitCharacters: ["("], refine: { // Optionally return an enriched version after async documentation lookup nil } ) let completions = Completions(isIncomplete: false, items: [item]) // Return from LanguageService.completions(at:reason:) ``` -------------------------------- ### Minimal LanguageService Stub Implementation Source: https://context7.com/mchakravarty/codeeditorview/llms.txt A stub implementation of the LanguageService protocol for bridging external language intelligence providers with the editor. It handles document lifecycle events and provides placeholders for LSP server interactions. ```swift import LanguageSupport import Combine // Minimal stub implementation final class MyLanguageService: LanguageService { var isOpen = false let events = PassthroughSubject() let diagnostics = CurrentValueSubject>, Never>([]) let completionTriggerCharacters = CurrentValueSubject<[Character], Never>([".", "("]) let extraActions = CurrentValueSubject<[ExtraAction], Never>([]) func openDocument(with text: String, locationService: LocationService) async throws { isOpen = true // Notify your LSP server: textDocument/didOpen } func documentDidChange(position: Int, changeInLength delta: Int, lineChange deltaLine: Int, columnChange deltaColumn: Int, newText text: String) async throws { // Forward incremental changes: textDocument/didChange } func closeDocument() async throws { isOpen = false // textDocument/didClose } func completions(at location: Int, reason: CompletionTriggerReason) async throws -> Completions { // Fetch from LSP: textDocument/completion return .none } func tokens(for lineRange: Range) async throws -> [[(token: LanguageConfiguration.Token, range: NSRange)]] { return Array(repeating: [], count: lineRange.count) } func info(at location: Int) async throws -> (view: any View, anchor: NSRange?)? { // textDocument/hover — return a SwiftUI view with documentation return nil } func capabilities() async throws -> (any View)? { return nil } } // Attach to a language configuration let service = MyLanguageService() let language = LanguageConfiguration.swift(service) // Publish a diagnostic from the server service.diagnostics.send([ TextLocated( location: TextLocation(zeroBasedLine: 2, column: 0), entity: Message(category: .error, length: 8, summary: "Use of undeclared identifier 'foo'", description: nil) ) ]) ``` -------------------------------- ### Define Language Tokenization Rules with LanguageConfiguration Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Configure language-specific tokenization rules including comment syntax, regex patterns for strings, characters, numbers, identifiers, operators, and reserved keywords. Optionally attach a `LanguageService` for semantic features. Built-in configurations are available for several languages. ```swift import LanguageSupport // Use a built-in configuration let swiftLang = LanguageConfiguration.swift() let haskellLang = LanguageConfiguration.haskell() let pythonLang = LanguageConfiguration.python() let noLang = LanguageConfiguration.none // plain text, no highlighting // Build a custom configuration (e.g., a minimal Lua-like language) let luaLang = LanguageConfiguration( name: "Lua", supportsSquareBrackets: true, supportsCurlyBrackets: true, stringRegex: /"(?:\\"|[^"])*+"/, characterRegex: nil, numberRegex: /[0-9]+(?:\.[0-9]+)?/, singleLineComment: "--", nestedComment: (open: "--[[", close: "]]"), identifierRegex: /[A-Za-z_][A-Za-z0-9_]*/, operatorRegex: nil, reservedIdentifiers: ["and","break","do","else","elseif","end", "false","for","function","if","in", "local","nil","not","or","repeat","return", "then","true","until","while"], reservedOperators: [] ) // Attach a language service (e.g., an LSP bridge) for semantic features let swiftWithLSP = LanguageConfiguration.swift(myLanguageServiceInstance) // Use in the editor CodeEditor(text: $text, position: $position, messages: $messages, language: luaLang) ``` -------------------------------- ### Customize Syntax Highlight Themes in CodeEditor Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Define per-token colors, background, selection, cursor, and invisible colors, along with font name and size. This is injected via the `codeEditorTheme` environment value. Built-in themes are available, or custom themes can be created. ```swift import SwiftUI import CodeEditorView struct EditorView: View { @Environment(\.colorScheme) private var colorScheme @State private var text = "" @State private var position = CodeEditor.Position() @State private var messages: Set> = [] // Built-in themes var theme: Theme { colorScheme == .dark ? Theme.defaultDark : Theme.defaultLight } // Custom theme static let myTheme = Theme( colourScheme: .dark, fontName: "SFMono-Regular", fontSize: 14, textColour: .white, commentColour: .gray, stringColour: .orange, characterColour: .yellow, numberColour: .cyan, identifierColour: .green, operatorColour: .white, keywordColour: .pink, symbolColour: .lightGray, typeColour: .blue, fieldColour: .purple, caseColour: .magenta, backgroundColour: OSColor(red: 0.1, green: 0.1, blue: 0.12, alpha: 1), currentLineColour: OSColor(red: 0.15, green: 0.15, blue: 0.18, alpha: 1), selectionColour: OSColor(red: 0.3, green: 0.4, blue: 0.6, alpha: 1), cursorColour: .white, invisiblesColour: .darkGray ) var body: some View { CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) .environment(\.codeEditorTheme, theme) } } ``` -------------------------------- ### CodeEditor.Actions and CodeEditor.SetActions Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Callbacks for reporting available editor actions (info, completions, language-specific extras) and for the host to enable/disable UI elements dynamically. ```APIDOC ## `CodeEditor.Actions` and `CodeEditor.SetActions` — Available Editor Actions The editor reports which actions are currently available (info, completions, language-specific extras) via a `SetActions` callback injected as an environment value. The host can use this to enable/disable toolbar buttons or menu items dynamically. ```swift import SwiftUI import CodeEditorView struct EditorView: View { @State private var text = "" @State private var position = CodeEditor.Position() @State private var messages: Set> = [] @State private var editorActions = CodeEditor.Actions() var body: some View { VStack { HStack { Button("Info") { editorActions.info?() } .disabled(editorActions.info == nil) Button("Complete") { editorActions.completions?() } .disabled(editorActions.completions == nil) ForEach(editorActions.language.extraActions, id: \.title) { Button(extra.title) { extra.action?() } } } CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) .environment(\.codeEditorSetActions, CodeEditor.SetActions { self.editorActions = $0 }) } } } ``` ``` -------------------------------- ### Basic Code Editor Usage in SwiftUI Source: https://github.com/mchakravarty/codeeditorview/blob/main/README.md Demonstrates the typical integration of CodeEditorView within a SwiftUI view. It requires importing SwiftUI, CodeEditorView, and LanguageSupport. State variables are used to manage the editor's text content, cursor position, and reported messages. The editor's theme is set based on the environment's color scheme. ```swift import SwiftUI import CodeEditorView import LanguageSupport struct ContentView: View { @State private var text: String = "My awesome code..." @State private var position: CodeEditor.Position = CodeEditor.Position() @State private var messages: Set> = Set() @Environment(\.colorScheme) private var colorScheme: ColorScheme var body: some View { CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) .environment(\.codeEditorTheme, colorScheme == .dark ? Theme.defaultDark : Theme.defaultLight) } } ``` -------------------------------- ### Basic CodeEditor View Implementation Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Integrate the `CodeEditor` SwiftUI view into your application. Bind it to your text, cursor position, and message data. Customize the editor's theme using environment values based on the color scheme. ```swift import SwiftUI import CodeEditorView import LanguageSupport struct EditorView: View { @State private var text: String = "func hello() {\n print(\"Hello, world!\")\n}" @State private var position: CodeEditor.Position = CodeEditor.Position() @State private var messages: Set> = [] @Environment(\.colorScheme) private var colorScheme var body: some View { CodeEditor( text: $text, position: $position, messages: $messages, language: .swift() ) .environment(\.codeEditorTheme, colorScheme == .dark ? Theme.defaultDark : Theme.defaultLight) } } ``` -------------------------------- ### macOS Editor Menu Integration with Commands Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Integrates editor-specific commands like Re-Indent, Shift Left/Right, Comment Selection, and Duplicate into the macOS application menu. These commands are dispatched through the responder chain to the focused CodeView. ```swift import SwiftUI import CodeEditorView @main struct MyEditorApp: App { var body: some Scene { WindowGroup { ContentView() } .commands { CodeEditingCommands() } } } // Individual command views can also be embedded anywhere: struct MyToolbar: View { var body: some View { Menu("Edit") { CodeEditingCommandsView() // Re-Indent, Shift Left/Right, Comment CodeEditingDuplicateCommandView() // Duplicate } } } ``` -------------------------------- ### Define Language-Specific Menu Actions Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Implement ExtraAction to allow a LanguageService to publish named actions with optional key shortcuts. These actions can be surfaced in menus or toolbars. Ensure LanguageSupport and SwiftUI are imported. ```swift import LanguageSupport import SwiftUI // Inside a LanguageService implementation let extraActions = CurrentValueSubject<[ExtraAction], Never>([ ExtraAction( title: "Format Document", key: KeyEquivalent("f"), action: { [weak self] in self?.formatDocument() } ), ExtraAction( title: "Organise Imports", key: nil, action: { [weak self] in self?.organiseImports() } ), ]) ``` -------------------------------- ### Dynamic Editor Action Enable/Disable with SetActions Source: https://context7.com/mchakravarty/codeeditorview/llms.txt The editor reports available actions (info, completions, language-specific extras) via a SetActions callback. This allows the host application to dynamically enable or disable UI elements like toolbar buttons or menu items based on current editor capabilities. ```swift import SwiftUI import CodeEditorView struct EditorView: View { @State private var text = "" @State private var position = CodeEditor.Position() @State private var messages: Set> = [] @State private var editorActions = CodeEditor.Actions() var body: some View { VStack { HStack { Button("Info") { editorActions.info?() } .disabled(editorActions.info == nil) Button("Complete") { editorActions.completions?() } .disabled(editorActions.completions == nil) ForEach(editorActions.language.extraActions, id: \.title) { Button(extra.title) { extra.action?() } } } CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) .environment(\.codeEditorSetActions, CodeEditor.SetActions { self.editorActions = $0 }) } } } ``` -------------------------------- ### LanguageService Protocol Source: https://context7.com/mchakravarty/codeeditorview/llms.txt An asynchronous protocol for bridging external language intelligence providers with the editor. Implementations handle document lifecycle events, code completions, semantic tokens, hover information, and diagnostics. ```APIDOC ## `LanguageService` Protocol — Semantic Language Features An asynchronous protocol that bridges an external language intelligence provider (such as an LSP server) with the editor. Implementations supply document-open/change/close lifecycle events, code completions, semantic tokens, identifier hover information, and a Combine-published diagnostics stream. One instance covers a single document. ```swift import LanguageSupport import Combine // Minimal stub implementation final class MyLanguageService: LanguageService { var isOpen = false let events = PassthroughSubject() let diagnostics = CurrentValueSubject>, Never>([]) let completionTriggerCharacters = CurrentValueSubject<[Character], Never>([".", "("]) let extraActions = CurrentValueSubject<[ExtraAction], Never>([]) func openDocument(with text: String, locationService: LocationService) async throws { isOpen = true // Notify your LSP server: textDocument/didOpen } func documentDidChange(position: Int, changeInLength delta: Int, lineChange deltaLine: Int, columnChange deltaColumn: Int, newText text: String) async throws { // Forward incremental changes: textDocument/didChange } func closeDocument() async throws { isOpen = false // textDocument/didClose } func completions(at location: Int, reason: CompletionTriggerReason) async throws -> Completions { // Fetch from LSP: textDocument/completion return .none } func tokens(for lineRange: Range) async throws -> [[(token: LanguageConfiguration.Token, range: NSRange)]] { return Array(repeating: [], count: lineRange.count) } func info(at location: Int) async throws -> (view: any View, anchor: NSRange?)? { // textDocument/hover — return a SwiftUI view with documentation return nil } func capabilities() async throws -> (any View)? { return nil } } // Attach to a language configuration let service = MyLanguageService() let language = LanguageConfiguration.swift(service) // Publish a diagnostic from the server service.diagnostics.send([ TextLocated( location: TextLocation(zeroBasedLine: 2, column: 0), entity: Message(category: .error, length: 8, summary: "Use of undeclared identifier 'foo'", description: nil) ) ]) ``` ``` -------------------------------- ### CodeEditingCommands Source: https://context7.com/mchakravarty/codeeditorview/llms.txt A Commands conformance that adds an Editor menu with various editing actions like Re-Indent, Shift Left/Right, Comment Selection, and Duplicate. ```APIDOC ## `CodeEditingCommands` — macOS Menu Integration A `Commands` conformance that adds an **Editor** menu with Re-Indent, Shift Left (`⌘[`), Shift Right (`⌘]`), and Comment Selection (`⌘/`) items, plus a Duplicate command (`⌘D`) appended after the Pasteboard group. All actions are dispatched through the responder chain to the focused `CodeView`. ```swift import SwiftUI import CodeEditorView @main struct MyEditorApp: App { var body: some Scene { WindowGroup { ContentView() } .commands { CodeEditingCommands() } } } // Individual command views can also be embedded anywhere: struct MyToolbar: View { var body: some View { Menu("Edit") { CodeEditingCommandsView() // Re-Indent, Shift Left/Right, Comment CodeEditingDuplicateCommandView() // Duplicate } } } ``` ``` -------------------------------- ### Configure Indentation Behavior in CodeEditor Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Specify indentation preferences like spaces vs. tabs, tab width, and tab key behavior. This configuration is injected via the `codeEditorIndentationConfiguration` environment value. ```swift struct EditorView: View { @State private var text = "" @State private var position = CodeEditor.Position() @State private var messages: Set> = [] var body: some View { CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) .environment(\.codeEditorIndentationConfiguration, CodeEditor.IndentationConfiguration( preference: .preferSpaces, tabWidth: 4, indentWidth: 4, tabKey: .identsInWhitespace, indentOnReturn: true )) } } ``` -------------------------------- ### Programmatically Jump to Specific Location Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Manually set the cursor position and scroll offset by creating a `CodeEditor.Position` instance. This allows for programmatic navigation within the code editor, such as jumping to a specific line and column. ```swift // Programmatically jump to line 10, column 1 let jumpTarget = CodeEditor.Position( selections: [NSRange(location: 200, length: 0)], // character offset into the string verticalScrollPosition: 0.35 ) ``` -------------------------------- ### TextLocated Wrapper for Message Location Source: https://github.com/mchakravarty/codeeditorview/blob/main/Documentation/Overview.md Shows the structure for locating messages within the code editor. It includes the TextLocation which specifies the zero-based line and column for the message. ```swift struct TextLocated { let location: TextLocation let entity: Entity } struct TextLocation { let zeroBasedLine: Int // starts from line 0 let zeroBasedColumn: Int // starts from column 0 } ``` -------------------------------- ### Persisting Editor Position with SceneStorage Source: https://context7.com/mchakravarty/codeeditorview/llms.txt Use `@SceneStorage` to automatically save and restore the editor's cursor and scroll position across application launches. The `CodeEditor.Position` struct conforms to `Codable` for this purpose. ```swift // Restore position from scene storage across app launches struct EditorView: View { @SceneStorage("editor.position") private var position = CodeEditor.Position() @State private var text = "" @State private var messages: Set> = [] var body: some View { CodeEditor(text: $text, position: $position, messages: $messages, language: .swift()) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.