Native autocorrect for macOS.
Fast, dictionary-backed autocorrect and predictive ghost text for every application. Runs 100% on-device in native C++20 with zero telemetry, sub-microsecond latency, and single-key undo.
Thanks for downloading Inline. Since Inline has zero telemetry, would you like to send a quick email so I can officially add +1 to the public download counter?
This editor runs Inline's full 83k-word dictionary and 243k-bigram ranker locally. Type normally and press Space to fix typos, Tab to accept ghost text, or Backspace right after a correction to undo it.
Architecture & Pipeline Overview
Every keystroke is evaluated through a synchronous, lock-free C++20 pipeline. Interception runs on a dedicated high-priority event thread (≤ 2 μs) to guarantee zero perceptible typing lag.
Hardware Keystroke
│
▼
[ CGEventTap (kCGSessionEventTap) ] ── (isSyntheticEvent?) ──► [ Loopback Drop ]
│
▼ (Pass Key / Append Buffer)
[ Password & PIN Classifier ] ── (AXSecureTextField?) ──► [ Dormant Bypass ]
│
▼
┌─────────────────────────────┬─────────────────────────────┐
│ Space / Delimiter Pressed │ Typing Pause (> 40ms) │
▼ ▼ ▼
[ SymSpell Tier 1 Lookup ] [ Tier 0 n-gram Trie ] [ Tier 1 SmolLM2-135M ]
(Damerau-Levenshtein ≤ 2) (Synchronous < 1ms) (2 CPU Threads, KV Cache)
│ │
▼ ▼
[ Undo State Machine ] [ NSPanel Overlay Window ]
(Single-Key Revert) (Sub-0.2ms advanceLayout)
How it works under the hood
1. Event Interception & Loopback Elimination
Inline hooks into the operating system at the session level using macOS CGEventTap (kCGSessionEventTap, inserted at kCGTailAppendEventTap) listening exclusively for kCGEventKeyDown. This ensures mouse clicks across macOS are never routed through our tap, preserving native window responsiveness.
When Inline injects replacement keystrokes to fix a typo or accept ghost text, those synthesized events would normally re-trigger our own hook, causing an infinite loop. To eliminate this without locks or sleep delays, every synthesized event is tagged with a custom 64-bit integer signature in kCGEventSourceUserData. The tap checks this field in under 0.001 ms and immediately drops synthetic loopback events.
// Low-latency CGEventTap callback running on real-time QOS thread CGEventRef MacKeyboardHook::eventTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) { // 1. Drop our own synthetic events FIRST (< 0.001 ms) int64_t tag = CGEventGetIntegerValueField(event, kCGEventSourceUserData); if (isSyntheticEvent(tag)) { return event; // Pass through without re-processing } // 2. Zero-allocation event extraction RawKeyEvent raw; raw.keyCode = CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode); raw.flags = CGEventGetFlags(event); raw.timestampNs = CGEventGetTimestamp(event); // 3. Conditional Tab swallow if Ghost Text prediction is visible bool swallow = (type == kCGEventKeyDown && raw.keyCode == 48 /* Tab */ && self->shouldInterceptTab_ && self->shouldInterceptTab_()); if (self->filterCallback_ && self->filterCallback_(raw, activeTap)) { swallow = true; } return swallow ? nullptr : event; }
2. Caret Localization Across Native and Web Apps
To render ghost text flush against the insertion point, Inline queries the focused UI element's Accessibility attributes via kAXSelectedTextRangeAttribute and maps the range to screen coordinates using kAXBoundsForRangeParameterizedAttribute.
Web browsers like Google Chrome, Vivaldi, and Brave present an asynchronous selection lag: during rapid bursts of typing, Chromium's internal accessibility thread lags behind DOM changes, returning dummy zero-sized bounds (such as (0.0, 1329.0, 0.0, 0.0)) or outdated coordinates. To prevent ghost text from jumping behind the cursor or rendering in microscopic fonts on web search bars, Inline runs a 4-tier localization ladder.
Caret Localization Ladder:
Focused UI Element (PID, kAXRoleAttribute)
│
├──► Tier 1: AXSelectedTextRange + AXBoundsForRange
│ (Standard Cocoa apps, TextEdit, Notes, Safari)
│
├──► Tier 2: Chromium effectiveLoc Ladder
│ (Google Chrome, Vivaldi, YouTube, Amazon search)
│ Probes [textLength - 1, 1] when selection range is outdated
│
├──► Tier 3: WebKit AXSelectedTextMarkerRange
│ (Safari contenteditable & rich web editors)
│
└──► Tier 4: Vertical Baseline Centering & Forward Monotonicity
(Aligns center Y on single-line inputs; prevents cursor overlap)
// Multi-tier bounds resolution with Chromium anomaly rejection static bool getAXRectForRange(AXUIElementRef elem, CFIndex loc, CFIndex len, CGRect& outRect) { CFRange r = CFRangeMake(loc, len); AXValueRef rangeVal = AXValueCreate(kAXValueTypeCFRange, &r); CFTypeRef boundsVal = nullptr; AXError err = AXUIElementCopyParameterizedAttributeValue( elem, kAXBoundsForRangeParameterizedAttribute, rangeVal, &boundsVal); CFRelease(rangeVal); if (err != kAXErrorSuccess || !boundsVal) return false; bool ok = AXValueGetValue((AXValueRef)boundsVal, kAXValueTypeCGRect, &outRect); CFRelease(boundsVal); // Reject dummy/empty bounds emitted by Chromium asynchronous threads if (outRect.origin.x <= 1.0 && outRect.size.width <= 1.0) return false; if (outRect.size.width == 0.0 && outRect.size.height == 0.0) return false; // Enforce standard single-line baseline height if (len == 0 && outRect.size.height < 4.0) { outRect.size.height = 18.0; } return outRect.size.height >= 4.0 && outRect.size.height <= 240.0; }
3. SymSpell Typo Correction & Bigram Ranking
Typo correction triggers on word delimiters (Space or punctuation). Inline uses the SymSpell Symmetric Delete algorithm: by precomputing deletions for words in the dictionary, candidate lookups only require deleting characters from the input word rather than calculating all transpositions and insertions at runtime.
The dictionary contains 82,765 unigrams and 243,342 bigrams. When multiple candidates exist within Damerau-Levenshtein distance ≤ 2, bigram frequencies conditioned on the previous word are evaluated using logarithmic probability scoring to resolve homophones (e.g. "their" vs "there").
// Word evaluation with Damerau-Levenshtein ≤ 2 and bigram context scoring CorrectionResult correctWord(const std::wstring& typed, const SymSpellDict& dict, const AppConfig& cfg, bool isSentenceStart, const std::wstring& prevWord) { if (dict.isProtected(typed)) { return {false, typed}; // Developer jargon and slang preserved } auto candidates = dict.lookup(typed, cfg.maxDictionaryEditDistance); if (candidates.empty()) return {false, typed}; // Rank candidate matches using log-frequency bigram context auto best = rankByBigramContext(candidates, prevWord, dict); return {true, best.term}; }
4. Run-Together Word Splitting
Fast typing often results in accidentally skipped spaces. When a typed token is not found in the dictionary, Inline tests segmentation points using dynamic programming.
For each candidate split (e.g. whenI → when + I), the engine verifies that both parts exist in the unigram dictionary, computes their combined frequency score, and adds an explicit bonus if the boundary matches a user's CamelCase transition.
// Dynamic programming segmentation for concatenated words if (cfg.splitRunTogetherWords && isAllAlpha && lowerTyped.size() >= 3) { for (size_t split = 1; split < lowerTyped.size(); ++split) { std::wstring w1 = lowerTyped.substr(0, split); std::wstring w2 = lowerTyped.substr(split); int64_t c1 = dict.getUnigramFrequency(w1); int64_t c2 = dict.getUnigramFrequency(w2); if (c1 > 0 && c2 > 0) { double splitScore = std::log10(c1) + std::log10(c2); int64_t biFreq = dict.getBigramFrequency(w1, w2); if (biFreq > 0) splitScore += std::log10(biFreq) * 1.5; if (isCamelAtSplit) splitScore += 6.0; // Explicit capitalization bonus if (splitScore > bestSplitScore) { bestSplitScore = splitScore; bestSplit = {w1, w2}; } } } }
5. Deterministic Single-Key Undo
Autocorrect should never fight the user. Whenever Inline replaces a word, the change is recorded in an internal state machine.
If Backspace (kVK_Delete) is pressed immediately following a correction, the engine emits the exact number of backspaces needed and retypes the user's raw keystrokes. Crucially, the reverted word is automatically marked as rejected for that context, preventing recursive autocorrect loops.
Undo State Machine Transitions:
Typo Autocorrected / Ghost Accepted
┌──────────────────────────────────────────┐
│ ▼
[ IDLE ] ◄────────────── [ ELIGIBLE FOR UNDO ]
▲ Other Key / │
│ Space │ Backspace (kVK_Delete)
│ ▼
└───────────── [ REVERT RAW KEYSTROKES ]
(Suppresses re-correction for word)
// Atomic single-key undo triggered on Backspace UndoActionResult UndoStateMachine::onBackspace() { if (state_ == State::EligibleForUndo) { state_ = State::Idle; suppressedWord_ = lastOriginal_; // Prevent re-correcting in same context return { .type = UndoAction::RevertCorrection, .revertedText = lastOriginal_, .correctedText = lastCorrected_ }; } state_ = State::Idle; return { .type = UndoAction::NormalDelete }; }
6. Dual-Tier Predictive Ghost Text & One Word Mode
Ghost text predictions combine sub-millisecond n-gram trie lookups with an out-of-process 4-bit neural model (SmolLM2-135M) running via llama.cpp over 2 CPU threads. Predictions are debounced by 40 ms after the last keypress so they never flicker during rapid typing.
In One Word Mode, Inline computes completions only for the active token being typed at the cursor (for example, typing tha suggests nk). Pressing Tab accepts the word, automatically triggers layout advancement, and immediately cues the next word of the sentence continuation for seamless, infinite Tab-chaining without window flicker.
// Sub-0.2ms horizontal shift as user types matching continuation letters void GhostOverlay::advanceLayout(double deltaX, const std::wstring& remainingText) { if (deltaX <= 0.0 || remainingText.empty()) return; std::wstring textCopy = remainingText; dispatch_async(dispatch_get_main_queue(), ^{ @autoreleasepool { GhostLayoutResult updated = [gGhostView layoutData]; if (!updated.lines.empty()) { updated.lines[0].text = textCopy; updated.lines[0].x += deltaX; updated.boundingBox.x += deltaX; updated.boundingBox.width = std::max(4.0, updated.boundingBox.width - deltaX); [gGhostView setLayoutData:updated]; [gGhostPanel setFrame:newFrame display:YES]; } } }); }
7. Out-of-Process Neural Service & IPC Architecture
To guarantee that on-device language modeling never interrupts real-time keyboard interception, neural inference runs in an independent helper binary (InlinePredictor). Communication occurs across a private local Unix domain socket using length-prefixed binary message framing.
Requests carry an atomic monotonic generation counter (generation_). If the user types a new character while background inference is computing, the generation counter increments and the incoming response is instantly discarded, preventing stale text from ever flashing on screen.
// Binary IPC request dispatch with atomic generation counter bool PredictorClient::sendRequest(const std::string& context, const std::string& partial, uint8_t maxWords) { if (socketFd_ < 0) return false; uint64_t gen = ++generation_; ClientReqHeader hdr; hdr.magic = 0x494E4C50; // "INLP" hdr.op = 1; hdr.maxWords = maxWords; hdr.generation = gen; hdr.contextLen = (uint32_t)context.size(); hdr.partialLen = (uint32_t)partial.size(); // Write framed header followed by payload bytes if (!writeAll(socketFd_, &hdr, sizeof(hdr))) return false; if (!writeAll(socketFd_, context.data(), context.size())) return false; if (!writeAll(socketFd_, partial.data(), partial.size())) return false; return true; }
PowerMonitor actively checks macOS thermal state via NSProcessInfoThermalState and battery status via IOPowerSources. When the system enters Low Power Mode or thermal state Serious / Critical, the neural helper suspends itself automatically, allowing Tier 0 N-grams to handle completions with zero battery drain.
// Dynamic thermal regulation and Low Power Mode detection EngineMode PowerMonitor::currentEngineMode() { bool onBattery = isOnBatteryPower(); ThermalState thermal = currentThermalState(); bool lowPower = isLowPowerModeEnabled(); // Fallback to Tier 0 trie when battery or cooling is constrained return decideEngineMode(onBattery, thermal, lowPower); }
8. Security, Privacy & Zero-Disk Invariants
Inline creates zero network sockets, sends zero telemetry pings, and writes zero keystrokes to disk. Before processing input, Inline queries kAXSubroleAttribute: if an element is an AXSecureTextField (such as a password or credit card input), the engine enters a dormant state where all keystrokes pass unmodified. Keystroke buffers in RAM are purged after 30 seconds of typing inactivity.
// Automatic dormant bypass in password and PIN inputs bool isSecureFieldActive(AXUIElementRef focusedElem) { CFTypeRef subrole = nullptr; if (AXUIElementCopyAttributeValue(focusedElem, kAXSubroleAttribute, &subrole) == kAXErrorSuccess) { bool isSecure = CFEqual(subrole, kAXSecureTextFieldSubrole); CFRelease(subrole); if (isSecure) return true; // Completely bypass tracking } return false; }
Key Delimiters & Typing Behavior
Inline respects standard macOS cursor behavior. Keystrokes are handled deterministically according to strict delimiter rules:
| Key / Event | Behavior | Technical Action |
|---|---|---|
Space |
Word delimiter | Triggers SymSpell lookup on previous token, checks Damerau-Levenshtein distance ≤ 2, applies bigram context ranking, and replaces typos. |
Tab |
Accept Ghost Text | If a ghost text suggestion is currently visible, swallows Tab and injects the continuation. If no suggestion is visible, passes Tab straight through without modifying text. |
Enter / Return |
Pass-through commit | Never autocorrects. Commits whatever raw text was typed, immediately clears the active word buffer, resets sentence state, and forwards the Return key to the app. |
Backspace |
Single-Key Undo | If pressed immediately following an autocorrection or Tab accept, restores the exact raw characters typed. If pressed while typing, pops the last buffered character. |
. ! ? |
Sentence boundary | Sets the sentence start flag. The initial letter of the following word is automatically capitalized, alongside standalone i → I. |
| Case Preservation | Casing pattern mirror | Replicates typed case: lowercase (teh → the), Title Case (Teh → The), Uppercase (TEH → THE). CamelCase words remain untouched. |
Global Keyboard Shortcuts
System-wide shortcuts allow quick toggles without opening settings:
| Shortcut | Action | Scope |
|---|---|---|
|
⌘
⌥
⇧
K
|
Toggle Autocorrect Engine On / Off | System-Wide |
|
⌘
⌥
⇧
G
|
Toggle Ghost Text Predictions On / Off | System-Wide |
|
Tab
|
Accept visible ghost text continuation | Active Input |
|
Delete
|
Single-key undo: revert last autocorrection or accepted suggestion | Active Input |
Slang & Developer Jargon Whitelist
Engineers, designers, and daily writers frequently use acronyms, command-line arguments, and informal abbreviations that traditional spellcheckers destroy. Inline incorporates a 180+ term protected whitelist directly into the SymSpell dictionary:
| Category | Protected Terms (Never Mangled) |
|---|---|
| Developer Terms | repo, dev, pr, cli, sdk, api, auth, async, stdout, stdin, stderr, config, util, impl, const, param |
| Internet Acronyms | gng, brb, ttyl, idk, ngl, tbh, fwiw, imo, imho, afaik, omw, smh, rn, fr, wip, lgtm |
| Bigram Context | 243,342 real-world bigram pairs score technical combinations (e.g. git commit, npm run, pull request) ensuring natural disambiguation without false positives. |
Application Compatibility Matrix
Inline is tested and verified daily across standard macOS applications:
| Category | Supported Applications | Caret Mechanism |
|---|---|---|
| Notes, Pages, Safari, Mail, TextEdit, Finder, Reminders | AXSelectedTextRange | |
| Google Chrome, Vivaldi, Brave, Microsoft Edge | Chromium effectiveLoc | |
| Visual Studio Code, Antigravity, Terminal, iTerm2 | Native EventTap | |
| Slack, Discord, Telegram, WhatsApp, Messages | Electron AX Bounds | |
| Notion, Obsidian, Linear, Google Docs, Gmail | Blink Selection Sync |
Subsystem Performance & Latency
Every component is profiled against strict real-time thresholds:
| Subsystem | Measured Latency | Constraint & Implementation Details |
|---|---|---|
| Keystroke Interception | ≤ 2 μs |
Real-time QOS thread in CGEventTap. Human tactile perception threshold is ~50 ms. |
| SymSpell Unigram Lookup | < 40 μs |
Precomputed symmetric delete hashes over 82,765 words with distance ≤ 2. |
| Bigram Disambiguation | < 25 μs |
Log-probability scoring over 243,342 contextual bigram pairs. |
| Tier 0 Prefix Trie | < 100 μs |
Lock-free prefix tree lookup for instant active word completion. |
| Ghost Layout Advance | < 0.2 ms |
Main thread translation of NSPanel frame without accessibility tree query. |
| Tier 1 Neural Model | ~15 ms |
Quantized SmolLM2-135M executed locally via llama.cpp on 2 efficiency cores. |
| Memory Footprint | < 120 MB |
Active RSS footprint across both UI and helper process (< 5 MB for autocorrect engine alone). |
| Idle CPU Drain | 0.0% |
Pure event-driven architecture with zero background polling loops. |
Configuration & System Settings
Inline follows Apple's modern System Settings visual language with rounded card containers, monochrome vector badges, and responsive layouts:
| Setting | Default | Description |
|---|---|---|
| Autocorrect Engine | Enabled | System-wide typo detection and replacement on Spacebar. |
| Ghost Text Predictions | Disabled (Beta) | Inline cursor suggestions. Experimental beta under testing. |
| Single-Key Undo | Enabled | Immediate one-touch reversion to raw typed keystrokes on Backspace. |
| Suggestion Length | Balanced (2-3 words) | Configurable between One word only (current word), Short, Balanced, or Long. |
| Run-Together Splitting | Enabled | Automatically segments concatenated tokens (e.g. twowords → two words). |
| Sentence Capitalization | Enabled | Capitalizes initial character of sentences after punctuation. |
| Adaptive Menu Bar Contrast | Permanent | Renders pure white (#FFFFFF) line on dark menu bars, dark charcoal (#18181B) on light menu bars, with an emerald (#22C55E) dot. |
| Custom Ignored Words | Configurable | User-defined dictionary of proprietary names, identifiers, or project terms. |
| Disabled Applications | Configurable | Bundle identifiers where Inline stays dormant (e.g. games or virtual machines). |
Building from Source & Unit Tests
Inline compiles natively on Apple Silicon and Intel Macs with CMake, Ninja, and Qt 6:
# 1. Clone the repository git clone https://github.com/LaxExe/Inline-MacOS-Win32Build.git cd Inline-MacOS-Win32Build git checkout mac-branch # 2. Configure release build with Ninja cmake -B build_release -DCMAKE_BUILD_TYPE=Release -G Ninja # 3. Compile app bundle and neural helper cmake --build build_release --target Inline InlinePredictor # 4. Ad-hoc codesign codesign --force --deep --sign - -i com.inline.mac build_release/gui/Inline.app # 5. Run test harness ctest --test-dir build_release --output-on-failure
The automated test suite verifies 100% of core engine functionality across 5 dedicated test binaries:
test_tier1: SymSpell dictionary lookup, Damerau-Levenshtein distance ≤ 2, and slang preservation.test_ghost_text: N-gram trie prefix generation, layout metrics, and token healing.test_settings_binding: Two-way binding between Qt controls and JSON configuration.test_word_boundary: Boundary parsing, delimiter detection, and whitespace normalization.test_undo_state_machine: Transition verification, single-key revert, and re-correction suppression.
Windows support (beta): A native Windows port using WH_KEYBOARD_LL and SendInput is currently in beta and is actively being built on the windows-branch on GitHub.