8000 GitHub - erogol/colonel: System-wide emoji and snippet inserter for macOS. Type :: anywhere. · GitHub
[go: up one dir, main page]

Skip to content
erogolPublic

About

System-wide emoji and snippet inserter for macOS. Type :: anywhere.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Colonel

Colonel icon

Made by Keche License: MIT

A system-wide emoji and snippet inserter for macOS. Type :: anywhere, keep typing, hit ⏎. The name is the trigger: two colons.

        ┌──────────────────────────────┐
Hey ::ta│ ::ta                  ↑↓ ⏎ ⎋ │        Hey 🎉
        │ 🎉  tada               :tada │   ⏎→
        │ 🌮  taco               :taco │
        │ 🍊  tangerine     :tangerine │
        └──────────────────────────────┘

No Dock icon, no window, no account, no telemetry. One menu-bar ::, ~2 kLOC of Swift, MIT.

Colonel is an original, independently written open-source emoji and snippet inserter. The emoji catalog is generated from public MIT-licensed datasets (see THIRD_PARTY_NOTICES.md).


Build

Requirements: macOS 13+, Xcode Command Line Tools (Swift 5.9 or newer). No package manager, no dependencies.

git clone <this repo> && cd colonel
make test      # headless self-test — 106 checks, no permissions needed
make app       # assembles build/Colonel.app
make run       # …and launches it from build/

make on its own builds the app bundle. make help lists the targets. For day-to-day use install it properly — see below.

First run

Once, in this order:

make sign-cert     # create the local signing identity and trust it
make install       # copy the app to /Applications
make login-item    # start it at login (optional)
open /Applications/Colonel.app

Then grant two permissions in System Settings → Privacy & Security:

  • Accessibility — to insert text into other apps and to find the caret.
  • Input Monitoring — to receive the keystrokes in the first place. Without it CGEvent.tapCreate still hands you a tap that reports itself as enabled, and your callback is simply never called. That failure mode is completely silent, which is why colonel --doctor reports both.

The app polls until both land, so there is no need to relaunch. Do not skip make sign-cert: without it the grant you just gave dies on the next rebuild, for the reason below.

Why sign-cert exists — granting once, not on every rebuild

macOS binds a permission grant to the app's designated requirement (bundle identifier + signing certificate), not to the binary. An ad-hoc signature is just a hash of the binary, so every rebuild looks like a brand-new app and macOS re-asks. You cannot auto-grant the permission itself — TCC forbids that by design — but you can make the grant stick.

make sign-cert does two things, neither of which needs sudo:

  1. Creates a stable, local, self-signed certificate ("Colonel Self-Signed") in your login keychain. Every make app signs with it, so the designated requirement stops changing.

  2. Marks that certificate as a trusted code-signing root in the user domain:

    security add-trusted-cert -r trustRoot -p codeSign \
        -k ~/Library/Keychains/login.keychain-db <cert.pem>

    This half matters as much as the first. TCC only stores the designated requirement if it can validate the signature against a trust anchor. An untrusted self-signed certificate is not one, so TCC pins the binary's cdhash instead — and that changes on every rebuild.

Check the result; it must exit 0:

codesign --verify -R="anchor trusted" /Applications/Colonel.app

The script is idempotent — run it again on an existing identity and it only adds the trust setting if it is missing.

If you had already granted the permission before the certificate was trusted, that grant is still a cdhash pin and has to be re-issued exactly once:

make install
make reset-permission
open /Applications/Colonel.app

Turn both switches back on. TCC now records identifier "net.colonel.Colonel" and certificate leaf = H"…" instead of a hash, and the grant survives rebuilds — verified across four rebuilds with four different CDHashes.

No Apple Developer account is needed; the certificate is self-signed and local. If you do have an Apple cert, CODESIGN_IDENTITY="Apple Development: …" make app takes precedence.

Start at login

make login-item             # install and load the LaunchAgent
make uninstall-login-item   # remove it

The template lives in the repo at Resources/net.colonel.agent.plist. The script copies it to ~/Library/LaunchAgents/net.colonel.agent.plist and loads it with launchctl bootstrap gui/$(id -u). It launches the binary inside /Applications/Colonel.app, so the process stays TCC-attributed to the app bundle and keeps its permissions.

launchctl kickstart -k gui/$(id -u)/net.colonel.agent   # restart it
launchctl bootout    gui/$(id -u)/net.colonel.agent     # stop it now

KeepAlive is false, so quitting from the menu bar keeps it quit until the next login.

Use

Keys
:: arm the picker (anywhere, in any app)
letters, digits, -, _ search as you type
↑ ↓ or ⌃P ⌃N move the selection
⏎ or ⇥ insert, replacing the ::query you typed
⎋, space, or any other key give up, leave your text alone
⌘1…⌘5 set the skin tone of the highlighted emoji — and remember it
⌘0 back to the neutral tone

:: with nothing after it shows your recents.

Ranking is fuzzy-match quality + how often you use something + how recently (one-week half-life). ::thmbs finds 👍. It is usable from the first keystroke and better after a week.

Snippets

colonel --add-snippet sig 'Cheers,{cursor}
— sent {date}'
colonel --list-snippets
colonel --rm-snippet sig

or use Add Snippet… in the menu bar. Then type ::sig. Variables are expanded when the snippet is inserted:

token
{date} 2026-07-27
{time} 13:07
{datetime} ISO 8601
{clipboard} current clipboard text
{uuid} a fresh UUID
{cursor} where the caret ends up
{{ a literal {

GIF links

Named URLs you can insert by name, from the same :: trigger. They live in a plain text file you edit yourself, ~/.config/colonel/gifs.txt, one entry per line:

name<TAB>url<TAB>space separated tags
shrug	https://example.com/shrug.gif	idk whatever confused

Lines starting with # are ignored, so are blank ones. Only http:// and https:// are accepted; a malformed line is skipped and reported by colonel --gifs, never fatal. Duplicate names resolve last one wins, so a corrected line appended to the end of the file overrides the earlier one. The file is created for you, with the example commented out, on first run (Resources/gifs.example.txt is the same content).

colonel --gifs                                                  # list them
colonel --add-gif shrug https://example.com/shrug.gif idk lol   # append one

::shrug then matches on the name and on any tag — ::idk finds it too — and the row carries a GIF badge so it cannot be mistaken for an emoji. An exact emoji name still wins: ::tada is 🎉 even if you own a GIF called tada. What gets inserted is the URL as plain text, through the same insertion path as everything else, so the Leave result on clipboard preference applies. The menu bar has a GIFs submenu with Reveal GIFs file in Finder and Reload GIFs; the file is also re-read automatically whenever it changed and you open the picker.

Colonel never fetches the URL: no thumbnail, no preview, no request, ever. Two consequences worth knowing: a hotlinked URL can rot at any time and Colonel will not notice, and a destination that does not unfurl into a preview will just show up as a bare URL wherever you pasted it.

From the shell

The same binary is a CLI, so emoji search is pipeable:

$ colonel -s tada
🎉	:tada	tada

$ colonel -s prty | head -1 | cut -f1 | pbcopy
$ colonel --gifs
$ colonel --stats
$ colonel --selftest
$ colonel --doctor     # catalog, store, permission, tap — in one screen

--type and --press post real keystrokes into the frontmost app, so they drive Colonel itself — which is how the end-to-end path gets tested without a human. Both need Accessibility, and a binary run straight from a terminal does not have it (see Troubleshooting), so go through the app bundle:

$ open -n /Applications/Colonel.app --args --type '::tada'
$ open -n /Applications/Colonel.app --args --press return     # → 🎉

Everything else — -s, --stats, --doctor, --selftest, the snippet and GIF commands — needs no permissions and runs fine as colonel ….

Troubleshooting

The app logs to ~/Library/Logs/Colonel.log and colonel --doctor prints catalog, store, permissions and tap state in one screen. Start with those two.

Nothing happens when you type ::. Run --doctor first. If it reports both permissions granted and the tap alive, suspect Secure Keyboard Entry: while any process holds it, every event tap in the session receives zero keystrokes. There is no error and nothing in the log. Find the holder:

ioreg -l -d 1 -w 0 -k IOConsoleUsers | grep -o 'kCGSSessionSecureInputPID"=[0-9]*'

A non-zero PID means that process has it; ps -p <pid> names it. Terminals and password fields enable it legitimately and normally release it, but it does get stuck — we saw loginwindow (PID 615) hold it. Logging out and back in, or a reboot, clears it.

System Settings shows the permission as granted, but the app says it is not. The grant was recorded as a cdhash pin rather than an identity requirement, and the rebuild changed the hash. Fix the cause and re-issue the grant once:

make sign-cert          # adds the trust setting if it is missing
make install
make reset-permission
open /Applications/Colonel.app

Then turn Accessibility and Input Monitoring on again. Confirm the cause is gone with codesign --verify -R="anchor trusted" /Applications/Colonel.app — exit 0 means TCC can validate the signature and will store the identity requirement.

Running the CLI from a terminal says it needs Accessibility. It does, and it cannot have it: a process launched from a terminal is TCC-attributed to the terminal, not to the app bundle, so it inherits the terminal's permissions rather than the app's. Granting Accessibility to your terminal would fix it and is a bad trade. Drive the installed bundle instead:

open -n /Applications/Colonel.app --args --type '::tada'

The permission is fine but the app is not running after login. Check the agent with launchctl print gui/$(id -u)/net.colonel.agent. If it is missing, run make login-item; the agent points at /Applications/Colonel.app, so it needs make install first.

What it does differently

Compared with the original:

  • Sticky skin tone per emoji, not one global setting. 👋🏽 stays 👋🏽 while 🤝 stays neutral.
  • Recency-aware ranking. Frequency alone means a word you hammered once in 2019 outranks the one you used this morning, forever.
  • Snippet variables, free, documented, in one file.
  • GIF links as plain text, from a text file you own — searchable by name and by tag, with no fetching, no thumbnails and no image pasteboard.
  • A real CLI, so the picker is scriptable and the pure logic is testable headlessly.
  • Nothing phones home. No update feed, no licence server, no analytics. A program that sees every keystroke you type should be one you can read and build yourself.

Not included, on purpose: sticker content, downloadable packs, licensing, auto-update, localisation, per-website suppression. See DESIGN.md §6 for the full list and the reasoning.

Online GIF search

::gif <query> enters online mode: the typed query is sent to Giphy's search API and the results appear in a 2-column x 3-row preview grid of six thumbnail cells (169x88 px each, aspect-fit). The selected cell gets a 2pt accent border and a small return affordance. The required Powered By GIPHY attribution is visible in every setup, loading, result, empty, and error state. This is opt-in:

  • No key, no network. Without a Giphy API key stored in the Keychain, ::gif <query> shows contextual setup instead of silently falling back to local search. The setup window links to GIPHY, validates the key before saving it, stores it in Keychain, then resumes the pending query. No socket is opened until the user explicitly verifies a candidate key.
  • The key is yours. Store it without exposing it in shell history with pbpaste | colonel --set-gif-key -; remove it with colonel --rm-gif-key. The key lives in the Keychain, never in a config file or defaults.
  • What is sent. The typed search query goes to https://api.giphy.com/v1/gifs/search with the key and a content-rating parameter (default g, work-safe). Nothing else — no cookies, no cache on disk, no analytics.
  • Quota discipline. 250 ms debounce per keystroke, in-memory query cache (15 min), backoff on HTTP 429, and auto-save of chosen GIFs into ~/.config/colonel/gifs.txt so repeats never hit the network.
  • Insertion. By default the GIF bytes are placed on the pasteboard under public.gif + com.compuserve.gif and pasted with ⌘V (your previous pasteboard is restored). A preference can switch to plain-URL insertion for chat apps that unfurl links.
  • Provider protocol. Giphy is the only provider shipped (Tenor is closed to new API clients). The GifProvider protocol is there so Klipy or a revived Tenor can be added later without touching the trigger engine.
  • Navigation. The grid is a sliding six-cell viewport. Colonel fetches 12 candidates initially; left/right move one cell, up/down or the mouse wheel move one row. Near the loaded end it appends another 12 using GIPHY's offset pagination (up to 60 per query), while only the visible six previews load. Existing results stay usable if load-more fails. Local emoji/snippet results keep their original list navigation.
  • Status. colonel --doctor shows whether a Giphy key is set, the content rating, and the insertion mode.

How it works

CGEventTap (keyDown)  →  TriggerEngine (:: state machine)  →  SearchIndex
                                                         ↓
                                                  OnlineGifSearch (opt-in, Giphy)
                                                                  ↓
        Inserter (⌫ ⌫ then unicode key events)  ←  PickerPanel (caret-anchored)
  • KeyTap.swift — a CGEventTapCreate session tap. A tap rather than an NSEvent global monitor because only a tap can swallow ↑↓⏎⎋ while the popup is open. keyboardGetUnicodeString decodes each key through the active input source, so Dvorak/AZERTY/QWERTZ work.
  • TriggerEngine.swift — a pure state machine over key events. No AppKit, no I/O, fully covered by --selftest.
  • CaretLocator.swift — system-wide AXUIElement → focused element → kAXBoundsForRange to find the caret; falls back to the mouse.
  • Inserter.swift — n synthetic ⌫ to erase what you typed, then the payload as unicode key events; pasteboard + ⌘V (with restore) for long or multi-line text.
  • GifCatalog.swift — the local GIF list: parse, validate, append and a one-stat freshness check. No network code, by construction.
  • GifProvider.swift / GiphyClient.swift / OnlineGifSearch.swift — the opt-in online GIF search: provider protocol, Giphy client, debounce/cache/ timeout coordinator. No key means no network.
  • GifPreviewCell.swift / GifPreviewGrid.swift -- the 2x3 online preview grid: NSImageView cells with async load, cancel, stale-URL guard, and selection border. No dependencies, no SwiftUI, no disk cache.
  • GifKeychain.swift — Keychain storage for the Giphy API key.
  • Store.swift — two SQLite tables in ~/Library/Application Support/Colonel/store.sqlite. Open it yourself.

Files, ordered by how much of the app they are: TriggerEngine, Controller, SearchIndex, KeyTap, Inserter, PickerPanel, CaretLocator, SkinTone, Fuzzy, Store, Catalog, SnippetExpander, StatusItemController, Preferences, CLI, GifPreviewGrid, GifPreviewCell, GifCatalog, SelfTest.

Updating the emoji catalog

make data     # re-fetches iamcal/emoji-data + github/gemoji and regenerates

The generated Sources/Colonel/Resources/emoji.json is committed so the build never needs the network.

Regenerating the icon

python3 Tools/make_icon.py

Redraws Resources/branding/icon.png, the .iconset ladder and Colonel.icns. The mark is :: set in Futura Bold on a rounded square, flat, no gradient. The compiled .icns is committed, so building the app needs neither Python nor Pillow. The menu-bar mark is a separate thing: it is drawn in code in StatusItemController.swift as a template image, which is what lets macOS tint it for a light or dark menu bar.

Privacy

Colonel sees every key-down in your session — that is how the trigger works. It keeps the last few characters you typed after :: in memory and nothing else. It writes only to its own SQLite file and the GIF list you edit. It opens no sockets — GIF entries are URLs it inserts as text, never fetches. Read KeyTap.swift and Controller.swift; between them they are under 300 lines.

Licence

MIT — see LICENSE.

About

System-wide emoji and snippet inserter for macOS. Type :: anywhere.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0