### Build and Install Apfel Quick from Source Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt Clone the repository, build the release binary, and install the application locally. Includes commands for running tests. ```bash git clone https://github.com/Arthur-Ficial/apfel-quick.git cd apfel-quick swift test # Run 168+ tests swift build -c release # Build release binary make install # Install to /Applications ``` -------------------------------- ### Install apfel-quick with Homebrew Source: https://github.com/arthur-ficial/apfel-quick/blob/main/README.md Use Homebrew to install apfel-quick. This is the recommended installation method. To update later, use `brew upgrade apfel-quick`. ```bash brew install Arthur-Ficial/tap/apfel-quick # Update later brew upgrade apfel-quick ``` -------------------------------- ### Build and Test apfel-quick Source: https://github.com/arthur-ficial/apfel-quick/blob/main/README.md Commands for building, testing, and installing apfel-quick from source. Includes running the test suite, building a release binary, and installing the application. ```bash swift test # run the full 168-test suite ``` ```bash swift build -c release # release binary ``` ```bash make install # build the .app and copy to /Applications ``` ```bash ./scripts/release.sh # full release: test, build, sign, notarise, tag, publish ``` -------------------------------- ### Install Apfel Quick via Homebrew Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt Install the Apfel Quick CLI tool using Homebrew for easy management. Includes commands for initial installation and subsequent upgrades. ```bash # Install via Homebrew (recommended) brew install Arthur-Ficial/tap/apfel-quick brew upgrade apfel-quick # Update later ``` -------------------------------- ### Build and Install apfel-quick from Source Source: https://github.com/arthur-ficial/apfel-quick/blob/main/README.md Build and install apfel-quick directly from its source code repository. This method requires Xcode command-line tools and the `apfel` AI engine to be on your PATH. ```bash git clone https://github.com/Arthur-Ficial/apfel-quick.git cd apfel-quick make install ``` -------------------------------- ### Math Shortcut Examples Source: https://github.com/arthur-ficial/apfel-quick/blob/main/README.md Demonstrates the math shortcut feature of apfel-quick, showing how it evaluates mathematical expressions locally. Supports European decimal commas, various functions, constants, and operators. ```text 54,34*6-(435353) → -435026,96 ``` ```text sqrt(2)^2 → 2 ``` ```text (1+2)*3 - 4/2 → 7 ``` ```text sin(pi/2) → 1 ``` -------------------------------- ### Manage apfel Server Process with ServerManager Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt Use ServerManager to start, stop, and monitor the apfel server process. It handles port discovery, reusing existing instances, and checking server health. Static helpers are available for port and binary management. ```swift import Foundation @MainActor func startServer() async { let manager = ServerManager(settings: QuickSettings.load()) // Start the server (spawns apfel --serve or connects to existing) if let port = await manager.start() { print("Server running on port \(port)") // Check server state switch manager.state { case .running(let port, _): print("Active on port \(port)") case .failed(let message): print("Failed: \(message)") default: break } } // Static helpers for port management let available = ServerManager.isPortAvailable(11450) print("Port 11450 available: \(available)") let port = ServerManager.findAvailablePort(startingAt: 11450) print("First available port: \(port)") // 11450-11459 range // Find apfel binary if let binary = ServerManager.findApfelBinary() { print("apfel binary at: \(binary)") } // Stop the server manager.stop() } ``` -------------------------------- ### Initialize and Use QuickViewModel Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt Initialize the QuickViewModel with settings, a service, and the current version. Submit prompts to process either natural language queries via AI or mathematical expressions. ```swift import Foundation // Initialize the view model with settings and optional service injection let viewModel = QuickViewModel( settings: QuickSettings.load(), service: ApfelQuickService(port: 11450), currentVersion: "1.0.7" ) // Submit a prompt - automatically detects math expressions vs AI queries Task { viewModel.input = "What is the capital of France?" await viewModel.submit() // Output streams in token-by-token, auto-copied to clipboard when complete print(viewModel.output) // "Paris" } // Math expressions bypass AI entirely for instant evaluation Task { viewModel.input = "sqrt(144) + 2^3" await viewModel.submit() print(viewModel.output) // "20" } // Cancel an in-progress stream viewModel.cancel() // Manually copy output to clipboard viewModel.copyOutput() // Check for updates Task { await viewModel.checkForUpdateManual() switch viewModel.updateState { case .updateAvailable(let version): print("New version available: \(version)") viewModel.installUpdate() // Runs `brew upgrade` or opens GitHub releases case .upToDate: print("Already on latest version") default: break } } ``` -------------------------------- ### Load, Configure, and Save User Preferences Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt Load existing settings or create defaults using QuickSettings. Configure hotkey bindings, behavior settings like auto-copy and launch at login, and appearance. Settings are persisted to UserDefaults. ```swift import Foundation // Load existing settings or create defaults var settings = QuickSettings.load() // Configure hotkey (Option+Space by default) settings.hotkeyKeyCode = 49 // Space bar settings.hotkeyModifiers = 524288 // Option key // Validate hotkey (must include Ctrl, Option, or Cmd) let valid = QuickSettings.isValidHotkey( keyCode: settings.hotkeyKeyCode, modifiers: settings.hotkeyModifiers ) print("Valid hotkey: \(valid)") // Display name for current hotkey print(settings.hotkeyDisplayName) // "\u2325Space" // Behavior settings settings.autoCopy = true // Copy result to clipboard automatically settings.launchAtLogin = true // Start at login settings.showMenuBar = true // Show menu bar icon settings.checkForUpdatesOnLaunch = true // Appearance settings.appearance = .system // .light, .dark, or .system // Saved prompt prefix (default "/") settings.savedPromptPrefix = "/" // Save changes settings.save() // Settings are stored under "QuickSettings" key in UserDefaults print(QuickSettings.defaultsKey) // "QuickSettings" ``` -------------------------------- ### Apfel Quick Release Workflow Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt Execute the release script to automate testing, building, signing, notarizing, tagging, and publishing of the application. ```bash ./scripts/release.sh # Test, build, sign, notarize, tag, publish ``` -------------------------------- ### Stream AI Chat Completions with ApfelQuickService Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt Initialize ApfelQuickService with a port or base URL to communicate with a local apfel server. Stream responses using async/await and handle potential errors like connection failures or server issues. ```swift import Foundation // Initialize with server port let service = ApfelQuickService(port: 11450) // Or with full URL let serviceWithURL = ApfelQuickService( baseURL: URL(string: "http://127.0.0.1:11450")!, modelName: "apple-foundationmodel" ) // Stream a chat completion let stream = service.send(prompt: "Explain closures in Swift") Task { do { for try await delta in stream { if let text = delta.text { print(text, terminator: "") // Tokens arrive one at a time } if delta.finishReason == "stop" { print("\n[Stream complete]") } } } catch let error as QuickServiceError { switch error { case .connectionFailed(let msg): print("Connection failed: \(msg)") case .serverError(let msg): print("Server error: \(msg)") case .streamError(let msg): print("Stream error: \(msg)") } } } // Health check Task { let healthy = try await service.healthCheck() print("Server healthy: \(healthy)") // true if modelAvailable } ``` -------------------------------- ### Spawn Ohr Subprocess for Voice Transcription Source: https://github.com/arthur-ficial/apfel-quick/blob/main/docs/learnings/voice-input-ohr.md Illustrates the architectural flow where the main application spawns the 'ohr' subprocess to handle voice transcription. 'ohr' listens for audio input and outputs transcribed text as JSON. ```text ┌────────────────────────┐ spawn ┌──────────────────────────┐ │ apfel-quick (GUI .app) │ ────────────► │ ohr --listen -o json │ │ - NSPanel overlay │ stdout/JSON │ --language en-US │ │ - QuickViewModel │ ◄──────────── │ --quiet │ │ - VoiceTranscriber │ │ (on-device Speech fwk) │ └────────────────────────┘ └──────────────────────────┘ ``` -------------------------------- ### Math Calculation: Local Parser Source: https://github.com/arthur-ficial/apfel-quick/blob/main/site/index.html Apfel Quick performs mathematical calculations locally using a dedicated parser, ensuring speed and efficiency for operations like arithmetic. ```math 54,34*6-(435353) → -435026.96 with Copied badge ``` -------------------------------- ### Add Copy Functionality to Preformatted Text Blocks Source: https://github.com/arthur-ficial/apfel-quick/blob/main/site/index.html This JavaScript code iterates through all `
` elements on a page, wraps them in a `div` with a 'pre-wrap' class, and appends a 'Copy' button. Clicking the button copies the text content of the `
` block to the clipboard and provides visual feedback.

```javascript
document.querySelectorAll('pre').forEach(function(pre) {
 var wrap = document.createElement('div');
 wrap.className = 'pre-wrap';
 pre.parentNode.insertBefore(wrap, pre);
 wrap.appendChild(pre);
 var btn = document.createElement('button');
 btn.className = 'copy-btn';
 btn.textContent = 'Copy';
 btn.addEventListener('click', function() {
  navigator.clipboard.writeText(pre.textContent.trim()).then(function() {
   btn.textContent = 'Copied!';
   btn.classList.add('copied');
   setTimeout(function() {
    btn.textContent = 'Copy';
    btn.classList.remove('copied');
   }, 2000);
  });
 });
 wrap.appendChild(btn);
});
```

--------------------------------

### Manage Saved Prompts and Resolve Aliases

Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt

Utilize default saved prompts or create custom ones with aliases. The SavedPromptResolver can resolve aliases to full prompts, supporting autocomplete suggestions as the user types.

```swift
import Foundation

// Default saved prompts included out of the box
let defaults = SavedPrompt.defaults
// ["/translate", "/grammar", "/tldr", "/explain", "/email"]

// Create custom saved prompt
let customPrompt = SavedPrompt(
    alias: "code",
    prompt: "Write clean, well-documented code for the following. Include error handling."
)

// Resolve alias to full prompt
let resolved = SavedPromptResolver.resolve(
    input: "/translate Hello, world!",
    prefix: "/",
    savedPrompts: SavedPrompt.defaults
)
// Returns: "Translate the following text to English. Return only the translation, no preamble.\n\nHello, world!"

// Alias alone (no context)
let aliasOnly = SavedPromptResolver.resolve(
    input: "/grammar",
    prefix: "/",
    savedPrompts: SavedPrompt.defaults
)
// Returns: "Fix grammar and spelling. Return only the corrected text, no explanations."

// Autocomplete matches while typing
let matches = SavedPromptResolver.matches(
    input: "/tr",
    prefix: "/",
    savedPrompts: SavedPrompt.defaults
)
// Returns: [SavedPrompt(alias: "translate", ...)]

// No matches once user types space (committed to sending)
let noMatches = SavedPromptResolver.matches(
    input: "/translate some text",
    prefix: "/",
    savedPrompts: SavedPrompt.defaults
)
// Returns: []
```

--------------------------------

### Fetch GitHub Releases and Update Download Links

Source: https://github.com/arthur-ficial/apfel-quick/blob/main/site/index.html

This JavaScript code fetches release information from the GitHub API to dynamically update download buttons and display total download counts. It's designed to be used on a webpage to provide users with the latest download information for the apfel-quick application.

```javascript
fetch('https://api.github.com/repos/Arthur-Ficial/apfel-quick/releases')
 .then(function(r) { return r.json(); })
 .then(function(releases) {
  if (!releases || !releases.length) return;
  var latest = releases[0];
  var tag = latest.tag_name;
  if (!tag) return;
  var url = 'https://github.com/Arthur-Ficial/apfel-quick/releases/download/' + tag + '/apfel-quick-' + tag + '-macos-arm64.zip';
  var total = 0;
  releases.forEach(function(rel) {
   (rel.assets || []).forEach(function(a) {
    if (a.name.indexOf('.zip') !== -1) total += (a.download_count || 0);
   });
  });
  ['download-btn','download-btn-2'].forEach(function(id){
   var btn = document.getElementById(id);
   if (btn) btn.href = url;
  });
  var text = 'Download ' + tag;
  if (total > 0) text += ' · ' + total.toLocaleString() + ' downloads';
  ['download-label','download-label-2'].forEach(function(id){
   var label = document.getElementById(id);
   if (label) label.textContent = text;
  });
 })
 .catch(function() {});
```

--------------------------------

### Entitlement for Network Client

Source: https://github.com/arthur-ficial/apfel-quick/blob/main/docs/learnings/voice-input-ohr.md

Specifies the entitlement required for network client access. This is often included alongside device-specific entitlements.

```xml
com.apple.security.network.client
```

--------------------------------

### Request Microphone Access

Source: https://github.com/arthur-ficial/apfel-quick/blob/main/docs/learnings/voice-input-ohr.md

Demonstrates the necessary call to request microphone access before spawning a subprocess that requires it. This is crucial for macOS TCC (Transparency, Consent, and Control) to prompt the user and grant permission to the application.

```swift
AVCaptureDevice.requestAccess(for: .audio)
```

--------------------------------

### Entitlement for Audio Input

Source: https://github.com/arthur-ficial/apfel-quick/blob/main/docs/learnings/voice-input-ohr.md

Specifies the required entitlement for accessing audio input devices. This key must be present in the application's entitlements plist when using Hardened Runtime to allow microphone access.

```xml
com.apple.security.device.audio-input
```

--------------------------------

### Evaluate Mathematical Expressions with MathCalculator

Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt

Use MathCalculator to evaluate mathematical expressions locally. It supports basic arithmetic, scientific functions, constants, European decimal commas, and power operations. Error handling for division by zero and unknown functions is included.

```swift
import Foundation

// Basic arithmetic with operator precedence
let result1 = try MathCalculator.evaluate("(1+2)*3 - 4/2")
print(MathCalculator.format(result1)) // "7"

// Scientific functions and constants
let result2 = try MathCalculator.evaluate("sin(pi/2)")
print(MathCalculator.format(result2)) // "1"

let result3 = try MathCalculator.evaluate("sqrt(2)^2")
print(MathCalculator.format(result3)) // "2"

let result4 = try MathCalculator.evaluate("ln(e)")
print(MathCalculator.format(result4)) // "1"

// European decimal comma support (3,14 = 3.14)
let result5 = try MathCalculator.evaluate("54,34*6-(435353)")
print(MathCalculator.format(result5)) // "-435026.96"

// Power operations (right-associative)
let result6 = try MathCalculator.evaluate("2^3^2")
print(MathCalculator.format(result6)) // "512" (2^(3^2) = 2^9)

// Error handling
do {
    _ = try MathCalculator.evaluate("10/0")
} catch MathCalculatorError.divisionByZero {
    print("Cannot divide by zero")
}

do {
    _ = try MathCalculator.evaluate("unknown(5)")
} catch MathCalculatorError.unknownFunction(let name) {
    print("Unknown function: \(name)")
}
```

--------------------------------

### Swift: Sort Array of Strings Alphabetically

Source: https://github.com/arthur-ficial/apfel-quick/blob/main/site/index.html

This snippet demonstrates how to sort an array of strings alphabetically in Swift. Ensure the array is mutable if you intend to sort it in place.

```swift
let strings = ["banana", "apple", "cherry"]
let sortedStrings = strings.sorted()
print(sortedStrings) // Output: ["apple", "banana", "cherry"]
```

--------------------------------

### Classify Math Expressions with MathExpressionDetector

Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt

Use MathExpressionDetector.isMathExpression to determine if input is a pure mathematical expression or a natural language prompt. Pure math expressions return true, while natural language or incomplete expressions return false.

```swift
import Foundation

// Pure math expressions return true
MathExpressionDetector.isMathExpression("2+2")           // true
MathExpressionDetector.isMathExpression("sqrt(16)")      // true
MathExpressionDetector.isMathExpression("3,14*2")        // true (European decimal)
MathExpressionDetector.isMathExpression("sin(pi/4)")     // true
MathExpressionDetector.isMathExpression("(1+2)*(3-4)")   // true

// Natural language returns false - requires AI
MathExpressionDetector.isMathExpression("What is 2+2?")  // false
MathExpressionDetector.isMathExpression("Calculate pi")  // false
MathExpressionDetector.isMathExpression("hello world")   // false

// Just a number without operators returns false (no computation needed)
MathExpressionDetector.isMathExpression("42")            // false
MathExpressionDetector.isMathExpression("pi")            // false (constant alone)

// Unknown identifiers make it non-math
MathExpressionDetector.isMathExpression("x+5")           // false (unknown variable)
```

--------------------------------

### Single-line Entitlement Comment

Source: https://github.com/arthur-ficial/apfel-quick/blob/main/docs/learnings/voice-input-ohr.md

Shows the correct format for comments within the entitlements XML blob for codesigning. Multi-line comments were found to cause issues with the AMFI XML parser.

```xml

```

--------------------------------

### Render Markdown to Attributed String

Source: https://context7.com/arthur-ficial/apfel-quick/llms.txt

Convert markdown strings into NSAttributedString for rich display. The MarkdownRenderer supports various markdown elements including headings, lists, code blocks, and links.

```swift
import Foundation
import AppKit

// Render markdown to attributed string
let markdown = """
# Hello World

This is **bold** and *italic* text with `inline code`.

```swift
let x = 42
```

- Item one
- Item two

> A blockquote
"""

let attributedString = MarkdownRenderer.render(markdown)

// Use in NSTextView or SwiftUI Text
// The renderer handles:
// - Headings (H1-H6 with appropriate font sizes)
// - Bold, italic, strikethrough
// - Inline code with monospace font and background
// - Code blocks with syntax highlighting background
// - Ordered and unordered lists with proper indentation
// - Checkboxes in task lists
// - Links (clickable)
// - Block quotes (secondary color)
// - Tables (tab-separated columns)
// - Images (shows alt text with image icon)
```

--------------------------------

### Regex: Email Pattern

Source: https://github.com/arthur-ficial/apfel-quick/blob/main/site/index.html

This is a common regular expression pattern used to validate email addresses. It checks for a typical structure of username@domain.tld.

```regex
working regex pattern
```

=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.