### Send Command Example Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Example demonstrating how to use the send method to send commands to the shell. ```swift state.send("ls -la\n") // Send a command to the shell state.send("clear\n") // Clear the screen ``` -------------------------------- ### Example: Implementing terminalDidAttachSurface Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md An example implementation of the `terminalDidAttachSurface` method to handle surface creation and log its details. ```swift func terminalDidAttachSurface(_ surface: TerminalSurface) { self.surface = surface print("Surface ready: \(surface.size()?.debugSummary ?? \"unknown size\")") } ``` -------------------------------- ### Extend Default Terminal Configuration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/05-terminal-configuration-api.md Example showing how to create a custom configuration by starting with the default settings and then modifying the font size. ```swift let base = TerminalConfiguration.default let custom = TerminalConfiguration(startingFrom: base) { builder in builder.withFontSize(18) } ``` -------------------------------- ### Example: Implementing terminalDidDetachSurface Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md An example implementation of the `terminalDidDetachSurface` method to handle surface destruction and log the event. ```swift func terminalDidDetachSurface() { self.surface = nil print("Surface detached") } ``` -------------------------------- ### Example: Initialize TerminalViewState with Config File Path Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Demonstrates initializing TerminalViewState with a specific configuration file path. ```swift let path = "/Users/user/.config/ghostty/config" let state = TerminalViewState(configFilePath: path) ``` -------------------------------- ### Swift Code Organization Example Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/01-overview.md This example illustrates the directory structure of the Ghostty project, detailing the organization of its Swift source files across different modules. ```swift Sources/ GhosttyKit/ └─ GhosttyKit.swift Re-exports @_exported import libghostty GhosttyTerminal/ ├─ Configuration/ Config models, theme colors, rendering ├─ Controller/ TerminalController + lifecycle, config, surface creation ├─ InMemory/ Host-managed I/O backend ├─ Metrics/ Grid size, viewport, input modifiers ├─ Platform/ │ ├─ Shared/ Cross-platform input handling │ ├─ UIKit/ iOS/Catalyst views, UITextInput, input accessory │ └─ AppKit/ macOS views, NSTextInputClient ├─ State/ TerminalViewState (SwiftUI observable) ├─ Surface/ TerminalSurface, Surface coordinator, delegates └─ View/ SwiftUI TerminalSurfaceView + platform representables GhosttyTheme/ ├─ GhosttyThemeCatalog.swift Theme lookup and search ├─ GhosttyThemeDefinition.swift Theme data model └─ Themes/ Auto-generated theme data (A-Z) ShellCraftKit/ ├─ Definition/ Shell definition, commands, sandboxed demo shell └─ Session/ Shell session management and engine ``` -------------------------------- ### ShellCommand Examples Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/09-shell-craft-api.md Examples demonstrating how to create ShellCommand instances for 'whoami', 'echo', and 'size' commands. These commands utilize the CommandContext to access username, arguments, and terminal size. ```swift ShellCommand("whoami", summary: "Show current user") { context in .output(context.username + "\r\n") } ``` ```swift ShellCommand("echo", summary: "Echo text") { context in .output(context.arguments + "\r\n") } ``` ```swift ShellCommand("size", summary: "Show terminal size") { context in .output("Cols: \(context.terminalSize.columns), Rows: \(context.terminalSize.rows)\r\n") } ``` -------------------------------- ### Convenience Initializers Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/13-exported-symbols.md Provides examples of convenience initializers for creating `TerminalController` instances with different configurations. ```APIDOC ## Convenience Initializers ### Description Examples of convenience initializers for creating `TerminalController` instances. ### Method initializer ### Parameters - **configFilePath** (String?) - Optional - Path to the configuration file. - **configuration** (Theme) - Optional - Configuration object. - **theme** (Theme) - Optional - Theme object. - **configure** (Closure) - Optional - Builder closure for configuration. - **configSource** (ConfigSource) - Optional - Low-level configuration source. ### Request Example ```swift TerminalController() TerminalController(configFilePath: "path/to/config.json") TerminalController(configuration: theme) TerminalController(theme: configure:) TerminalController(configSource:…) ``` ``` -------------------------------- ### Example: Initialize TerminalViewState with Existing Controller Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Demonstrates initializing TerminalViewState by passing an already created TerminalController instance. ```swift let controller = TerminalController(configFilePath: path) let state = TerminalViewState(controller: controller) ``` -------------------------------- ### Example: Initialize TerminalViewState with Explicit Configuration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Shows how to initialize TerminalViewState with custom settings for config source, theme, and terminal configuration. ```swift let config = TerminalConfiguration().fontSize(16) let state = TerminalViewState( configSource: .none, theme: .default, terminalConfiguration: config ) ``` -------------------------------- ### Example Initialization of TerminalGridMetrics Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/10-types-and-enums.md Provides an example of initializing TerminalGridMetrics with specific dimensions and printing the grid and size information. ```swift let metrics = TerminalGridMetrics( columns: 80, rows: 24, widthPixels: 800, heightPixels: 600, cellWidthPixels: 10, cellHeightPixels: 25 ) print("Grid: \(metrics.columns)x\(metrics.rows)") print("Size: \(metrics.widthPixels)x\(metrics.heightPixels)") ``` -------------------------------- ### Initialize TerminalController with Default Configuration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Creates a TerminalController instance using the default terminal configuration and theme. This is the simplest way to get started. ```swift let controller = TerminalController() // Uses default cursor style (block, blinking), font size (14pt on macOS, 10pt on iOS) ``` -------------------------------- ### Swift Example: Opening URL in TerminalSurfaceOpenURLDelegate Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md An example implementation for opening a URL using the system's default browser. Ensure URL validity before attempting to open. ```swift func terminalDidRequestOpenURL(_ url: String, kind: TerminalOpenURLKind) { if let url = URL(string: url) { UIApplication.shared.open(url) } } ``` -------------------------------- ### Example Usage of TerminalSurfaceOptions Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/10-types-and-enums.md Demonstrates how to create a TerminalSurfaceOptions instance with specific configurations for backend, font size, working directory, and context. ```swift let options = TerminalSurfaceOptions( backend: .inMemory(session), fontSize: 14, workingDirectory: FileManager.default.currentDirectoryPath, context: .tab ) ``` -------------------------------- ### CommandResult Examples Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/09-shell-craft-api.md Examples demonstrating how to use the CommandResult enum cases. This includes returning text output, clearing the screen, or exiting the shell. ```swift // Return output .output("Hello, world!\r\n") // Clear screen .clear // Exit .exit ``` -------------------------------- ### Example Usage of TerminalSessionBackend Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/10-types-and-enums.md Demonstrates how to initialize TerminalSessionBackend with an in-memory session and use it to configure terminal surface options. ```swift let backend = TerminalSessionBackend.inMemory(session) let options = TerminalSurfaceOptions(backend: backend) ``` -------------------------------- ### Preview Documentation Locally Source: https://github.com/lakr233/libghostty-spm/blob/main/docs/build.html Serve the static documentation site locally using Python's http.server. Navigate to the `docs` directory and run the command to start the server on port 8000. ```shell cd docs python3 -m http.server 8000 ``` -------------------------------- ### Example Implementation for TerminalSurfaceCommandFinishedDelegate Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md Provides an example of how to implement the terminalDidFinishCommand method to log command completion status and duration. This is useful for user feedback and debugging. ```swift func terminalDidFinishCommand(exitCode: Int?, durationNanos: UInt64) { let durationMs = durationNanos / 1_000_000 let status = exitCode == 0 ? "✓" : "✗" print("\(status) Command completed in \(durationMs)ms (exit: \(exitCode ?? -1))") } ``` -------------------------------- ### ShellDefinition Initialization Example Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/09-shell-craft-api.md Demonstrates how to initialize a ShellDefinition with a custom prompt, welcome message, fallback command handler, and defining shell commands using the @ShellCommandBuilder. ```swift let shell = ShellDefinition( prompt: "myshell> ", welcomeMessage: "Welcome to MyShell!", fallback: { cmd in "'\(cmd)' is not recognized" } ) { ShellCommand("echo", summary: "Print text") { context in .output(context.arguments + "\r\n") } ShellCommand("date", summary: "Show current date") { _ in let formatter = DateFormatter() formatter.dateFormat = "EEE MMM dd HH:mm:ss yyyy" return .output(formatter.string(from: Date()) + "\r\n") } } ``` -------------------------------- ### Swift Example: Handling Text Selection Request on iOS Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md An example implementation for presenting a text view controller to allow users to select and copy text. This is iOS-specific and uses a popover controller. ```swift func terminalDidRequestTextSelection(_ request: TerminalTextSelectionRequest) { let textViewController = UITextViewController() textViewController.text = request.text textViewController.selectedRange = request.anchorRange ?? NSRange(location: 0, length: 0) let popover = UIPopoverController(contentViewController: textViewController) popover.present(from: CGRect(origin: request.sourcePoint, size: CGSize(width: 1, height: 1)), in: self, permittedArrowDirections: .any, animated: true) } ``` -------------------------------- ### Minimal Terminal View Setup Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/12-quick-start-guide.md Integrates a basic `UITerminalView` into a `UIViewController`. Ensure `GhosttyTerminal` is imported. ```swift import UIKit import GhosttyTerminal class TerminalViewController: UIViewController { let terminalView = UITerminalView(frame: .zero) override func viewDidLoad() { super.viewDidLoad() view.addSubview(terminalView) terminalView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ terminalView.topAnchor.constraint(equalTo: view.topAnchor), terminalView.bottomAnchor.constraint(equalTo: view.bottomAnchor), terminalView.leadingAnchor.constraint(equalTo: view.leadingAnchor), terminalView.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) terminalView.controller = TerminalController() } } ``` -------------------------------- ### ShellCommandBuilder Example Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/09-shell-craft-api.md An example showcasing the usage of ShellCommandBuilder within a ShellDefinition. This defines commands like 'echo', 'date', and 'exit' with their respective behaviors. ```swift ShellDefinition( prompt: "$ ", fallback: { cmd in "'\(cmd)' not found" } ) { ShellCommand("echo") { context in .output(context.arguments + "\r\n") } ShellCommand("date") { _ in .output(Date().description + "\r\n") } ShellCommand("exit") { _ in .exit } } ``` -------------------------------- ### Create Theme from Catalog Example Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Shows how to retrieve a theme definition from the catalog by name and use its properties to create a new `GhosttyThemeDefinition`. This is useful for customizing existing themes. ```swift if let dracula = GhosttyThemeCatalog.theme(named: "Dracula") { let def = GhosttyThemeDefinition( name: "MyTheme", background: dracula.background, foreground: dracula.foreground, palette: dracula.palette ) } ``` -------------------------------- ### Configure Terminal Cursor Style Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/10-types-and-enums.md Example of setting the cursor style using a configuration builder. ```swift let config = TerminalConfiguration().cursorStyle(.bar) ``` -------------------------------- ### Example Implementation for TerminalSurfaceCloseDelegate Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md Provides an example of how to implement the terminalDidClose method to log whether the terminal closed normally or unexpectedly. This helps in diagnosing issues with terminal process management. ```swift func terminalDidClose(processAlive: Bool) { if processAlive { print("Terminal closed unexpectedly (process still running)") } else { print("Terminal closed normally") } } ``` -------------------------------- ### Simple Echo Terminal Session Example Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/07-inmemory-session-api.md Demonstrates how to set up and use an InMemoryTerminalSession to simulate terminal input and output. This class handles terminal writes and resize events. ```swift import Foundation import GhosttyTerminal class SimpleTerminal { let session: InMemoryTerminalSession let controller = TerminalController() var hostOutput: [String] = [] init() { session = InMemoryTerminalSession( write: { [weak self] data in self?.handleTerminalOutput(data) }, resize: { [weak self] viewport in self?.handleResize(viewport) } ) } func handleTerminalOutput(_ data: Data) { if let text = String(data: data, encoding: .utf8) { hostOutput.append(text) print("Terminal → Host: \(text)") } } func handleResize(_ viewport: InMemoryTerminalViewport) { print("Terminal resized: \(viewport.columns)x\(viewport.rows) cells") } func executeCommand(_ cmd: String) { // Feed command to terminal session.receive(cmd) // Simulate output (in reality, from actual command execution) let output = "$ \(cmd)\ncommand output here\n" session.receive(output) } func getViewport() -> String? { session.readViewportText() } func finishSession() { let startTime = Date() // Simulate some runtime let duration = UInt64(Date().timeIntervalSince(startTime) * 1000) session.finish(exitCode: 0, runtimeMilliseconds: duration) } } ``` -------------------------------- ### Example Usage of TerminalSurfaceContext Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/10-types-and-enums.md Shows how to create TerminalSurfaceOptions using a specific terminal surface context, like a tab. ```swift let options = TerminalSurfaceOptions(context: .tab) ``` -------------------------------- ### Define a Custom Shell with Commands Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/09-shell-craft-api.md Create a custom shell environment by defining a `ShellDefinition` with a prompt, welcome message, and various commands. This example includes a calculator, a mock file lister, and a system information command. ```swift let customShell = ShellDefinition( prompt: "custom$ ", welcomeMessage: "Custom shell with user commands", fallback: { cmd in "error: unknown command '\(cmd)'" } ) { // Math operations ShellCommand("calc", summary: "Simple calculator") { context in let parts = context.arguments.split(separator: " ").map(String.init) guard parts.count == 3, let a = Int(parts[0]), let b = Int(parts[2]) else { return .output("Usage: calc [+|-|*] \r\n") } let op = parts[1] let result: Int switch op { case "+": result = a + b case "-": result = a - b case "*": result = a * b default: return .output("Unknown operator: \(op)\r\n") } return .output("\(result)\r\n") } // File listing (mock) ShellCommand("ls", summary: "List files (mock)") { _ in let files = "file1.txt\nfile2.txt\ndirectory/\n" return .output(files) } // System info ShellCommand("info", summary: "Show system info") { context in let info = """ Hostname: ghostty-sandbox User: \(context.username) Terminal: \(context.terminalSize.columns)x\(context.terminalSize.rows) \r\n """ return .output(info) } } ``` -------------------------------- ### Build libghostty from Source Source: https://github.com/lakr233/libghostty-spm/blob/main/README.md Use this script to rebuild libghostty from the Ghostty source. Ensure you have the Zig compiler installed. This script applies patches, builds for all target architectures, and assembles the XCFramework. ```bash # Requires: zig compiler ./Script/build.sh ``` -------------------------------- ### Configure Terminal Settings using Builder Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/05-terminal-configuration-api.md Example demonstrating how to use the builder closure to set font size, cursor style, and background opacity for a terminal configuration. ```swift let config = TerminalConfiguration { builder in builder.withFontSize(16) builder.withCursorStyle(.bar) builder.withBackgroundOpacity(0.95) } ``` -------------------------------- ### Initialize Terminal Controller and View State Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/01-overview.md Demonstrates the basic setup for initializing a terminal controller and its corresponding view state for use with SwiftUI. This includes configuring the backend and display options. ```swift // 1. Create a controller (automatically initializes ghostty runtime once) let controller = TerminalController(configFilePath: path, theme: .default) // 2. Create a view state for SwiftUI let state = TerminalViewState(controller: controller) // 3. Configure and attach a backend state.configuration = TerminalSurfaceOptions( backend: .inMemory(session), fontSize: 14 ) // 4. Display the view and assign delegates TerminalSurfaceView(context: state) .onAppear { state.surface?.delegate = self } ``` -------------------------------- ### Set Terminal Color Scheme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/10-types-and-enums.md Example of how to set the color scheme on a controller. Also shows how to check the effective color scheme. ```swift controller.setColorScheme(.dark) if controller.effectiveColorScheme == .light { ... } ``` -------------------------------- ### Terminal Surface Example Usage Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/04-terminal-surface-api.md Shows how to integrate TerminalSurface with a UIViewController, including setting up the controller, handling surface attachment, and sending commands. ```swift class TerminalViewController: UIViewController, TerminalSurfaceViewDelegate { @IBOutlet weak var terminalView: UITerminalView! var surface: TerminalSurface? override func viewDidLoad() { super.viewDidLoad() let controller = TerminalController() terminalView.controller = controller terminalView.delegate = self } func terminalDidAttachSurface(_ surface: TerminalSurface) { self.surface = surface if let metrics = surface.size() { print("Terminal: \(metrics.columns)x\(metrics.rows)") } } func sendCommand() { surface?.sendText("ls -la\n") } func copySelection() { if let text = surface?.readSelection() { UIPasteboard.general.string = text } } } ``` -------------------------------- ### Search and Iterate Themes Example Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Demonstrates searching for themes containing 'dark' in their name and printing the names of the found themes. Useful for discovering available themes. ```swift let darkThemes = GhosttyThemeCatalog.search("dark") print("Found \(darkThemes.count) themes with 'dark' in the name") for theme in darkThemes { print(theme.name) } ``` -------------------------------- ### Using Composition for Delegate Handling Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md An example of using composition with a `TitleHandler` class to manage title changes, demonstrating a flexible delegate pattern. ```swift class TitleHandler: TerminalSurfaceTitleDelegate { var onTitleChange: (String) -> Void = { _ in } func terminalDidChangeTitle(_ title: String) { onTitleChange(title) } } let titleHandler = TitleHandler() titleHandler.onTitleChange = { title in self.navigationItem.title = title } terminalView.delegate = titleHandler ``` -------------------------------- ### Create Empty TerminalConfiguration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/05-terminal-configuration-api.md Initializes an empty terminal configuration. Use this when starting a new configuration from scratch. ```swift public init() ``` -------------------------------- ### Instantiate ShellSession with Default Sandbox Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/09-shell-craft-api.md Example of creating a new ShellSession instance using the pre-built defaultSandboxShell definition. This sets up a ready-to-use sandboxed environment. ```swift let session = ShellSession(definition: defaultSandboxShell) ``` -------------------------------- ### SwiftUI View with TerminalViewState Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Example of integrating `TerminalViewState` into a SwiftUI `View`. It shows how to initialize the state, configure the terminal, display the `TerminalSurfaceView`, and send commands. ```swift import SwiftUI import GhosttyTerminal struct ContentView: View { @StateObject private var terminal = TerminalViewState() var body: some View { VStack { TerminalSurfaceView(context: terminal) .navigationTitle(terminal.title) HStack { Button("Send Command") { terminal.send("ls\n") } Text("Cols: \(terminal.surfaceSize?.columns ?? 0)") } } .onAppear { terminal.configuration = TerminalSurfaceOptions( backend: .inMemory(sessionBackend) ) } } } ``` -------------------------------- ### Create InMemoryTerminalViewport Instance Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/07-inmemory-session-api.md Example of creating an instance of InMemoryTerminalViewport with specific column, row, and pixel dimensions. This demonstrates how to set up the viewport properties. ```swift let viewport = InMemoryTerminalViewport( columns: 80, rows: 24, widthPixels: 800, heightPixels: 480, cellWidthPixels: 10, cellHeightPixels: 20 ) ``` -------------------------------- ### Documentation Navigation Hierarchy Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/_MANIFEST.md Illustrates the hierarchical structure of the project's documentation, starting from the README.md entry point and branching into various sections like use cases, components, platforms, API references, and meta-information. ```markdown README.md (entry point) ↓ 00-index.md (master index) ├─ By use case (7 common tasks) ├─ By component (8 modules) └─ By platform (3 platforms) ↓ 01-overview.md (project context) ↓ 02-13-*.md (API references) ├─ Core: 02-09 (8 modules) ├─ Reference: 10-11 (types, delegates) ├─ Getting started: 12 (quick start) └─ Inventory: 13 (exported symbols) ``` -------------------------------- ### Create a Custom GhosttyThemeDefinition Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Example of creating a custom terminal theme using GhosttyThemeDefinition, specifying basic colors and a partial ANSI palette. ```swift let myTheme = GhosttyThemeDefinition( name: "CustomDark", background: "#1e1e1e", foreground: "#e0e0e0", cursorColor: "#00ff00", palette: [ 0: "#000000", // Black 1: "#ff0000", // Red 2: "#00ff00", // Green 3: "#ffff00", // Yellow // ... etc ] ) ``` -------------------------------- ### Setup TerminalView in UIKit/AppKit Source: https://github.com/lakr233/libghostty-spm/blob/main/docs/guide/uikit-appkit.html Instantiate and configure `TerminalView` by assigning a `TerminalController` and setting `TerminalSurfaceOptions`. The view manages the native input and Metal surface, while the controller handles app lifecycle and configuration. ```swift import GhosttyTerminal let terminalView = TerminalView(frame: .zero) let controller = TerminalController(configuration: .default) terminalView.controller = controller terminalView.configuration = TerminalSurfaceOptions( backend: .inMemory(session) ) terminalView.delegate = coordinator ``` -------------------------------- ### Simulating a Sandboxed Shell with InMemoryTerminalSession Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/07-inmemory-session-api.md Integrate InMemoryTerminalSession into sandboxed applications by handling terminal output and resize events. This example demonstrates feeding input to a simulated shell and finishing the session. ```swift let session = InMemoryTerminalSession( write: { data in processTerminalOutput(data) // e.g., send to network, log, etc. }, resize: { viewport in updateGridLayout(viewport) } ) // Feed shell simulation output session.receive("$ ") session.receive("hello\n") // Finish the session session.finish(exitCode: 0, runtimeMilliseconds: 100) ``` -------------------------------- ### Sandboxed Shell Emulation with SwiftUI Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/12-quick-start-guide.md Implement a sandboxed shell emulation using SwiftUI, GhosttyTerminal, and ShellCraftKit. This example defines custom shell commands and manages terminal state. ```swift import SwiftUI import GhosttyTerminal import ShellCraftKit struct SandboxShellApp: View { @StateObject private var terminal = TerminalViewState() let session: InMemoryTerminalSession let shellSession: ShellSession init() { let shell = ShellDefinition( prompt: "sandbox$ " ) { ShellCommand("hello") { _ in .output("Hello from sandbox!\r\n") } ShellCommand("echo") { context in .output(context.arguments + "\r\n") } ShellCommand("exit") { _ in .exit } } self.shellSession = ShellSession(definition: shell) self.session = InMemoryTerminalSession( write: { data in // Process shell input }, resize: { viewport in // Handle resize } ) _terminal = StateObject(wrappedValue: TerminalViewState()) } var body: some View { TerminalSurfaceView(context: terminal) .onAppear { terminal.configuration = TerminalSurfaceOptions( backend: .inMemory(session) ) } } } ``` -------------------------------- ### init(configFilePath:theme:) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Creates a TerminalController instance that loads its configuration from a file path, with an optional theme. ```APIDOC ## init(configFilePath:theme:) ### Description Creates a controller that loads its configuration from a file. ### Parameters #### Parameters - **configFilePath** (`String?`) - Optional - Path to a ghostty config file; nil uses default config (Defaults to `nil`) - **theme** (`TerminalTheme`) - Optional - Light + dark color variants (Defaults to `.default`) ### Example ```swift let path = "/Users/user/.config/ghostty/config" let controller = TerminalController(configFilePath: path) ``` ``` -------------------------------- ### Set OnClose Closure Example Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Example of how to assign a closure to the onClose property to handle terminal closure events. ```swift state.onClose = { processAlive in print("Terminal closed, process alive: \(processAlive)") } ``` -------------------------------- ### init(configuration:theme:) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Creates a TerminalController instance with a fully custom configuration and an optional theme. ```APIDOC ## init(configuration:theme:) ### Description Creates a controller with a fully custom configuration. ### Parameters #### Parameters - **configuration** (`TerminalConfiguration`) - Required - Terminal config options (font, cursor, colors, opacity, etc.) - **theme** (`TerminalTheme`) - Optional - Light + dark color variants (Defaults to `.default`) ### Example ```swift let config = TerminalConfiguration() .fontSize(16) .cursorStyle(.bar) .backgroundOpacity(0.95) let controller = TerminalController(configuration: config) ``` ``` -------------------------------- ### init(configFilePath:) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Creates a TerminalViewState instance by loading controller configuration from a specified file path. If the path is nil, default configurations are used. ```APIDOC ## init(configFilePath:) ### Description Creates a view state that loads controller configuration from a file. ### Parameters #### Path Parameters - **configFilePath** (`String?`) - Optional - Path to ghostty config file; nil uses defaults ### Example ```swift let path = "/Users/user/.config/ghostty/config" let state = TerminalViewState(configFilePath: path) ``` ``` -------------------------------- ### Swift Example: Updating Status Label on Link Hover Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md An example implementation for updating a status label with the URL under the cursor. Clears the label when the cursor is not over a link. ```swift func terminalDidUpdateHoverLink(_ url: String?) { if let url { statusLabel.text = url } else { statusLabel.text = "" } } ``` -------------------------------- ### init(theme:configure:) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Creates a TerminalController instance by composing additional commands on top of the default configuration using a builder closure. ```APIDOC ## init(theme:configure:) ### Description Creates a controller by composing additional commands on top of the default configuration using a builder closure. ### Parameters #### Parameters - **theme** (`TerminalTheme`) - Optional - Light + dark color variants (Defaults to `.default`) - **configure** (closure) - Required - Closure that modifies a `TerminalConfiguration.Builder` ### Example ```swift let controller = TerminalController { builder.withFontSize(16) builder.withCursorStyleBlink(false) builder.withBackgroundBlur(10) } ``` ``` -------------------------------- ### Search Themes by Name Prefix Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Searches the theme catalog for themes whose names start with a given query string. The search is case-insensitive. Returns an array of matching theme definitions. ```swift public static func search(_ query: String) -> [GhosttyThemeDefinition] ``` -------------------------------- ### Managing Terminal Themes and Configurations Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Demonstrates how to initialize a TerminalController, change its theme, switch color schemes, and apply per-session terminal configurations like font size. Shows that these changes can be made independently. ```swift let controller = TerminalController(configFilePath: path, theme: myTheme) // Change theme let newTheme = TerminalTheme(light: lightDef, dark: darkDef) controller.setTheme(newTheme) // Change color scheme controller.setColorScheme(.dark) // Change font size (terminal config) let config = TerminalConfiguration().fontSize(18) controller.setTerminalConfiguration(config) // All three work independently ``` -------------------------------- ### init() Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Creates a TerminalController instance with the default terminal configuration and theme. ```APIDOC ## init() ### Description Creates a controller with the default terminal configuration. ### Returns `TerminalController` with `TerminalConfiguration.default` and `TerminalTheme.default` ### Example ```swift let controller = TerminalController() ``` ``` -------------------------------- ### terminalConfiguration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Gets the current per-session terminal configuration settings. ```APIDOC ## terminalConfiguration ### Description The current per-session terminal configuration. ### Type TerminalConfiguration (readonly) ``` -------------------------------- ### Get Rendered Configuration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Accesses the current rendered configuration of the terminal as a string. ```swift public var renderedConfig: String { renderedConfigContents } ``` -------------------------------- ### init() Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Creates a TerminalViewState instance with default terminal configuration. This initializer sets up a new terminal controller with default settings. ```APIDOC ## init() ### Description Creates a view state with default terminal configuration. ### Returns `TerminalViewState` with default controller and empty configuration ### Example ```swift @StateObject private var terminal = TerminalViewState() ``` ``` -------------------------------- ### Get Terminal Theme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Provides read-only access to the current theme, forwarded from the controller. ```swift public var theme: TerminalTheme { controller.theme } ``` -------------------------------- ### Get Current Config Source Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Retrieves the current configuration source of the terminal controller. ```swift public var currentConfigSource: ConfigSource { configSource } ``` -------------------------------- ### ShellSession Source: https://github.com/lakr233/libghostty-spm/blob/main/docs/api/shellcraft.html Manages a shell session, initialized with a ShellDefinition and providing a method to start the session. ```APIDOC ## Class ShellSession ### Description Manages the lifecycle of a shell session. ### Properties - **terminalSession** (InMemoryTerminalSession) - The underlying terminal session. ### Initializer ```swift public init(shell: ShellDefinition) ``` ### Methods - **start()**: Starts the shell session. ``` -------------------------------- ### init(configSource:theme:terminalConfiguration:) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Creates a TerminalViewState instance with explicit configuration parameters, allowing for custom settings for config source, theme, and terminal configuration. ```APIDOC ## init(configSource:theme:terminalConfiguration:) ### Description Creates a view state with explicit configuration parameters. ### Parameters #### Path Parameters - **configSource** (`TerminalController.ConfigSource`) - Optional - Config source: `.none`, `.file(path)`, or `.generated(content)` - **theme** (`TerminalTheme`) - Optional - Light + dark color theme - **terminalConfiguration** (`TerminalConfiguration`) - Optional - Per-session config overrides ### Example ```swift let config = TerminalConfiguration().fontSize(16) let state = TerminalViewState( configSource: .none, theme: .default, terminalConfiguration: config ) ``` ``` -------------------------------- ### Get Current Theme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Retrieves the current theme applied to the terminal. This property is read-only after initialization. ```swift public private(set) var theme: TerminalTheme ``` -------------------------------- ### Get Terminal Configuration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Provides read-only access to the current per-session terminal configuration, forwarded from the controller. ```swift public var terminalConfiguration: TerminalConfiguration { controller.terminalConfiguration } ``` -------------------------------- ### Get Effective Color Scheme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Provides read-only access to the current color scheme, forwarded from the controller. ```swift public var effectiveColorScheme: TerminalColorScheme { controller.effectiveColorScheme } ``` -------------------------------- ### Convenience Initializers for TerminalController Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/13-exported-symbols.md Demonstrates various ways to initialize a TerminalController, from default to custom configurations loaded from files or builders. ```swift TerminalController() // Default TerminalController(configFilePath: String?) // From file TerminalController(configuration:theme:) // From config TerminalController(theme:configure:) // Builder TerminalController(configSource:…) // Low-level ``` -------------------------------- ### Get Rendered Configuration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Provides read-only access to the current rendered configuration string, forwarded from the controller. ```swift public var renderedConfig: String { controller.renderedConfig } ``` -------------------------------- ### Get Terminal Configuration Overrides Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Accesses per-session configuration overrides for the terminal. This property is read-only after initialization. ```swift public private(set) var terminalConfiguration: TerminalConfiguration ``` -------------------------------- ### Create a Minimal Shell with Commands Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/09-shell-craft-api.md Define a simple shell with a prompt, welcome message, and custom commands like 'hello' and 'goodbye'. This is useful for creating basic interactive command-line interfaces. ```swift import GhosttyTerminal import ShellCraftKit // Create a simple shell with two commands let myShell = ShellDefinition( prompt: ">> ", welcomeMessage: "Simple shell example" ) { ShellCommand("hello", summary: "Say hello") { _ in .output("Hello, World!\r\n") } ShellCommand("goodbye", summary: "Say goodbye") { _ in .output("Goodbye!\r\n") } } let session = ShellSession(definition: myShell, username: NSUserName()) ``` -------------------------------- ### Get Effective Color Scheme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Retrieves the currently active color scheme. This property is read-only after initialization. ```swift public private(set) var effectiveColorScheme: TerminalColorScheme ``` -------------------------------- ### Initialize TerminalViewState with Defaults Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Create a TerminalViewState with default terminal configuration and an empty configuration. ```swift public convenience init() ``` -------------------------------- ### Configure Colors and Theme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/12-quick-start-guide.md Customize background, foreground, cursor colors, and the color palette. ```swift let config = TerminalConfiguration() .background("#1e1e1e") .foreground("#e0e0e0") .cursorColor("#00ff00") .palette(0, color: "#000000") // Black .palette(1, color: "#ff0000") // Red .palette(2, color: "#00ff00") // Green ``` -------------------------------- ### Initialize TerminalViewState with Explicit Configuration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Create a TerminalViewState with explicit configuration parameters including config source, theme, and terminal configuration overrides. ```swift public init( configSource: TerminalController.ConfigSource = .none, theme: TerminalTheme = .default, terminalConfiguration: TerminalConfiguration = .init() ) ``` -------------------------------- ### Get Last Configuration Issue Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Retrieves the last configuration issue encountered during parsing, if any. This property is internally settable. ```swift public internal(set) var lastConfigurationIssue: String? ``` -------------------------------- ### Initialize TerminalViewState with Config File Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Create a TerminalViewState by loading controller configuration from a specified file path. If the path is nil, default configurations are used. ```swift public convenience init(configFilePath: String?) ``` -------------------------------- ### Check Configuration Issues Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/12-quick-start-guide.md Check for and print any configuration issues encountered by the controller. This is useful for diagnosing setup problems. ```swift if let issue = controller.lastConfigurationIssue { print("Config error: \(issue)") } ``` -------------------------------- ### Run tests Source: https://github.com/lakr233/libghostty-spm/blob/main/CLAUDE.md Execute the project's tests using the Swift Package Manager. ```bash # Run tests swift test ``` -------------------------------- ### Create and Apply TerminalTheme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Demonstrates how to create a custom `TerminalTheme` and apply it to a `TerminalController`. This is the typical usage pattern for integrating custom themes. ```swift let myTheme = TerminalTheme( light: lightDefinition, dark: darkDefinition ) let controller = TerminalController(theme: myTheme) controller.setTheme(myTheme) ``` -------------------------------- ### TerminalDidChangeWorkingDirectory Implementation Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md Example implementation of the terminalDidChangeWorkingDirectory delegate method. This function updates the current path and refreshes the path display. ```swift func terminalDidChangeWorkingDirectory(_ path: String) { currentPath = path updatePathDisplay() } ``` -------------------------------- ### TerminalDidReportProgress Implementation Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/11-delegates-and-callbacks.md Example implementation of the terminalDidReportProgress delegate method. This function updates a progress view based on the reported state and percentage. ```swift func terminalDidReportProgress(state: TerminalProgressState, percent: Int?) { switch state { case .set: progressView.progress = Float(percent ?? 0) / 100.0 case .error: progressView.tintColor = .red case .indeterminate: progressView.startAnimating() case .pause: progressView.pauseAnimation() case .remove: progressView.isHidden = true } } ``` -------------------------------- ### Build XCFramework from Ghostty Source Source: https://github.com/lakr233/libghostty-spm/blob/main/AGENTS.md Builds a full XCFramework from the Ghostty source code. Requires the 'zig' compiler. Platforms and skipping tests can be specified. ```bash ./build.sh ./build.sh --platforms macos,ios --source /path/to/ghostty --skip-tests ``` -------------------------------- ### Build full XCFramework from Ghostty source Source: https://github.com/lakr233/libghostty-spm/blob/main/CLAUDE.md Build the complete XCFramework from the Ghostty source code. This requires the 'zig' compiler. You can specify target platforms and the source path, and optionally skip tests. ```bash # Build full XCFramework from Ghostty source (requires zig) ./build.sh ./build.sh --platforms macos,ios --source /path/to/ghostty --skip-tests ``` -------------------------------- ### Rebuild libghostty Library Source: https://github.com/lakr233/libghostty-spm/blob/main/docs/build.html Build the libghostty library. Use the `--platforms` and `--source` flags to specify target platforms and the source directory, and `--skip-tests` to omit test execution. ```shell ./Script/build.sh ``` ```shell ./Script/build.sh \ --platforms macos,ios \ --source /path/to/ghostty \ --skip-tests ``` -------------------------------- ### Attach Shell to Ghostty Terminal Source: https://github.com/lakr233/libghostty-spm/blob/main/docs/guide/shellcraft.html Starts a ShellSession and configures the terminal's backend to use the in-memory session provided by ShellCraftKit. ```swift let shellSession = ShellSession(shell: shell) shellSession.start() terminal.configuration = TerminalSurfaceOptions( backend: .inMemory(shellSession.terminalSession) ) ``` -------------------------------- ### init(controller:) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Creates a TerminalViewState instance by wrapping an existing TerminalController. This is useful when a controller has already been instantiated and configured. ```APIDOC ## init(controller:) ### Description Creates a view state wrapping an existing `TerminalController`. ### Parameters #### Path Parameters - **controller** (`TerminalController`) - Required - Existing controller instance ### Example ```swift let controller = TerminalController(configFilePath: path) let state = TerminalViewState(controller: controller) ``` ``` -------------------------------- ### Initialize TerminalController from Configuration File Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Creates a TerminalController instance by loading its configuration from a specified file path. If no path is provided, default configurations are used. ```swift let path = "/Users/user/.config/ghostty/config" let controller = TerminalController(configFilePath: path) ``` -------------------------------- ### Enabling and Logging Debug Categories Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/10-types-and-enums.md Example usage for enabling specific debug log categories and logging messages with a category. Requires TerminalDebugCategory OptionSet. ```swift TerminalDebugLog.enable(.input, .output) TerminalDebugLog.log(.input, "Key pressed") ``` -------------------------------- ### init(write:resize:) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/07-inmemory-session-api.md Creates a new InMemoryTerminalSession instance. This initializer takes two closures: one for handling terminal output and another for handling resize events. ```APIDOC ## init(write:resize:) ### Description Creates a session with host-provided callbacks for output and resize events. ### Parameters #### Closure Parameters - **write**: `@escaping @Sendable (Data) -> Void` - Required - Called when terminal outputs bytes. The closure receives terminal output as raw bytes (ANSI sequences, text, etc.). - **resize**: `@escaping @Sendable (InMemoryTerminalViewport) -> Void` - Required - Called when terminal requests grid resize. The closure receives new viewport dimensions (columns, rows, pixels, cell sizes). ### Example ```swift let session = InMemoryTerminalSession( write: { data in print("Terminal output: \(String(data: data, encoding: .utf8) ?? "")") }, resize: { viewport in print("New size: \(viewport.columns)x\(viewport.rows)") } ) ``` ``` -------------------------------- ### UIKit Theme Selection Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Integrate theme selection into a UIKit application using a UITableView. This example shows how to apply a selected theme from the catalog to a UITerminalView. ```swift class ThemeViewController: UITableViewController { let terminalView: UITerminalView let themes = GhosttyThemeCatalog.search("").map(\.name).sorted() override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let themeName = themes[indexPath.row] if let themeDef = GhosttyThemeCatalog.theme(named: themeName) { let theme = TerminalTheme(light: themeDef, dark: themeDef) terminalView.controller?.setTheme(theme) } } } ``` -------------------------------- ### Default TerminalTheme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Provides a predefined default theme using catalogued light and dark variants. This is useful for quick setup when custom themes are not required. ```swift public static let `default` = TerminalTheme( light: GhosttyThemeCatalog.light, dark: GhosttyThemeCatalog.dark ) ``` -------------------------------- ### Builder Methods Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/13-exported-symbols.md Demonstrates builder methods for creating and configuring `TerminalConfiguration` objects. ```APIDOC ## Builder Methods ### Description Demonstrates builder methods for creating and configuring `TerminalConfiguration` objects. ### Method Initializer/Builder ### Parameters - **configure** (Closure) - Optional - Builder closure for configuration. - **startingFrom** (Configuration) - Optional - Existing configuration to extend. ### Request Example ```swift TerminalConfiguration() TerminalConfiguration(configure:) TerminalConfiguration(startingFrom: configure:) ``` ``` -------------------------------- ### Build and Test SPM Package Source: https://github.com/lakr233/libghostty-spm/blob/main/AGENTS.md Standard commands for building and testing the Swift Package Manager project. ```bash swift build ``` ```bash swift test ``` -------------------------------- ### Get Terminal Grid Size Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/04-terminal-surface-api.md Retrieves the current terminal grid size, including columns, rows, and pixel dimensions. Returns nil if no surface is attached. ```swift if let metrics = surface.size() { print("Grid: \(metrics.columns) cols x \(metrics.rows) rows") print("Size: \(metrics.widthPixels)x\(metrics.heightPixels) pixels") } ``` -------------------------------- ### GhosttyKit Input Processing Pipeline (iOS) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/01-overview.md Details the input processing pipeline for iOS, starting from hardware keys to the terminal's event sending mechanism. ```text Hardware Keys (pressesBegan) → TerminalInputAccessory (sticky modifiers) ↓ UITextInput (UIKeyInput) → TerminalTextInputHandler → surface.sendKeyEvent() ↓ Consumed by terminal or fallback (insertText/deleteBackward) ``` -------------------------------- ### Builder Initializers for TerminalConfiguration Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/13-exported-symbols.md Shows how to create and configure TerminalConfiguration objects using different initializer patterns, including empty, builder, and extension methods. ```swift TerminalConfiguration() // Empty TerminalConfiguration(configure:) // Builder TerminalConfiguration(startingFrom:configure:) // Extend ``` -------------------------------- ### Implementing Terminal Delegates in a ViewController Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/06-terminal-views-api.md Example of a UIViewController implementing TerminalSurfaceTitleDelegate and TerminalSurfaceLifecycleDelegate. It sets itself as the delegate for the terminal view and handles title changes and surface lifecycle events. ```swift class MyViewController: UIViewController, TerminalSurfaceTitleDelegate, TerminalSurfaceLifecycleDelegate { override func viewDidLoad() { super.viewDidLoad() terminalView.delegate = self } func terminalDidChangeTitle(_ title: String) { navigationItem.title = title } func terminalDidAttachSurface(_ surface: TerminalSurface) { print("Terminal attached") } func terminalDidDetachSurface() { print("Terminal detached") } } ``` -------------------------------- ### Configure Appearance Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/12-quick-start-guide.md Adjust background opacity, blur, window padding, and minimum contrast. ```swift let config = TerminalConfiguration() .backgroundOpacity(0.95) .backgroundBlur(10) .windowPaddingX(16) .windowPaddingY(8) .minimumContrast(1.5) ``` -------------------------------- ### init(configSource:theme:terminalConfiguration:) Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Low-level initializer for TerminalController providing full control over the configuration source, theme, and terminal configuration overrides. ```APIDOC ## init(configSource:theme:terminalConfiguration:) ### Description Low-level initializer for full control over the config source. ### Parameters #### Parameters - **configSource** (`ConfigSource`) - Optional - `.none` (defaults), `.file(path)`, or `.generated(content)` (Defaults to `.none`) - **theme** (`TerminalTheme`) - Optional - Light + dark color variants (Defaults to `.default`) - **terminalConfiguration** (`TerminalConfiguration`) - Optional - Per-session overrides (Defaults to `TerminalConfiguration()`) ### Enum: ConfigSource ```swift public enum ConfigSource: Sendable, Hashable { case none case file(String) case generated(String) } ``` ``` -------------------------------- ### Get Configuration for TerminalColorScheme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Retrieves the theme configuration commands for a given color scheme (light or dark). This method is used internally to apply the correct theme settings. ```swift func configuration(for scheme: TerminalColorScheme) -> TerminalConfiguration ``` -------------------------------- ### Initialize TerminalController with Custom Configuration and Theme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/02-terminal-controller-api.md Creates a TerminalController instance with a fully custom terminal configuration and an optional theme. Useful for fine-grained control over terminal appearance and behavior. ```swift let config = TerminalConfiguration() .fontSize(16) .cursorStyle(.bar) .backgroundOpacity(0.95) let controller = TerminalController(configuration: config) ``` -------------------------------- ### Built-in Help Command Output Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/09-shell-craft-api.md Displays the output of the built-in 'help' command, listing available commands and their summaries. ```text Available commands: help - Show this help message echo - Echo text back date - Show current date/time whoami - Show current user exit - Exit the terminal ``` -------------------------------- ### Initialize TerminalViewState with Default Controller Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Instantiate a TerminalViewState using the default controller and an empty configuration. ```swift @StateObject private var terminal = TerminalViewState() ``` -------------------------------- ### Initialize TerminalTheme Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/08-ghostty-theme-api.md Initializes a `TerminalTheme` with specific light and dark theme definitions. Use this to create custom themes. ```swift public init( light: GhosttyThemeDefinition, dark: GhosttyThemeDefinition ) ``` -------------------------------- ### Minimal Terminal View on macOS Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/12-quick-start-guide.md Set up a basic terminal view in an NSViewController. Ensure GhosttyTerminal is imported. ```swift import AppKit import GhosttyTerminal class TerminalViewController: NSViewController { let terminalView = AppTerminalView() override func loadView() { view = terminalView } override func viewDidLoad() { super.viewDidLoad() terminalView.controller = TerminalController() } } ``` -------------------------------- ### Initialize TerminalViewState with Existing Controller Source: https://github.com/lakr233/libghostty-spm/blob/main/_autodocs/03-terminal-view-state-api.md Create a TerminalViewState by wrapping an existing TerminalController instance. ```swift public init(controller: TerminalController) ```