README.md

  1# plugin
  2
  3Lua-based plugin system for extending Matcha. Plugins are loaded from `~/.config/matcha/plugins/` and run inside a sandboxed Lua VM (no `os`, `io`, or `debug` libraries).
  4
  5## How it works
  6
  7The `Manager` creates a Lua VM at startup, registers the `matcha` module, and loads all plugins from the user's plugins directory. Plugins can be either a single `.lua` file or a directory with an `init.lua` entry point.
  8
  9Plugins interact with Matcha by registering callbacks on hooks:
 10
 11```lua
 12local matcha = require("matcha")
 13
 14matcha.on("email_received", function(email)
 15    matcha.log("New email from: " .. email.from)
 16    matcha.notify("New mail!", 3)
 17end)
 18```
 19
 20## Lua API (`matcha` module)
 21
 22| Function | Description |
 23|----------|-------------|
 24| `matcha.on(event, callback)` | Register a callback for a hook event |
 25| `matcha.log(msg)` | Log a message to stderr |
 26| `matcha.notify(msg [, seconds])` | Show a temporary notification in the TUI (default 2s) |
 27| `matcha.set_status(area, text)` | Set a persistent status string for a view area (`"inbox"`, `"composer"`, `"email_view"`) |
 28| `matcha.set_compose_field(field, value)` | Set a compose field value (`"to"`, `"cc"`, `"bcc"`, `"subject"`, `"body"`) |
 29| `matcha.bind_key(key, area, description, callback)` | Register a custom keyboard shortcut for a view area (`"inbox"`, `"email_view"`, `"composer"`) |
 30| `matcha.http(options)` | Make an HTTP request (see below) |
 31| `matcha.prompt(placeholder, callback)` | Open a text input overlay in the composer (see below) |
 32| `matcha.style(text, opts)` | Wrap `text` in lipgloss styling and return an ANSI-styled string (see below) |
 33| `matcha.settings(spec)` | Declare configurable settings; returns a read-only proxy table for live values (see below) |
 34| `matcha.get_setting(key [, plugin])` | Look up a setting value by key (defaults to current plugin) |
 35
 36## Hook events
 37
 38| Event | Callback argument | Description |
 39|-------|-------------------|-------------|
 40| `startup` | — | Matcha has started |
 41| `shutdown` | — | Matcha is exiting |
 42| `email_received` | Lua table with `uid`, `from`, `to`, `subject`, `date`, `is_read`, `account_id`, `folder` | New email arrived |
 43| `email_viewed` | Same as `email_received` | User opened an email |
 44| `email_send_before` | Table with `to`, `cc`, `subject`, `account_id` | About to send an email |
 45| `email_send_after` | Same as `email_send_before` | Email sent successfully |
 46| `folder_changed` | Folder name (string) | User switched folders |
 47| `composer_updated` | Table with `body`, `body_len`, `subject`, `to`, `cc`, `bcc` | Composer content changed |
 48| `email_body_render` | `(email_table, rendered, raw)` — return a string to replace the rendered body, or `nil` to keep it | About to display an email body. `rendered` is the ANSI-styled display string; `raw` is the original message source (HTML or plain text). Use for recoloring, bold/italic, removing parts, or fully replacing the displayed body with parsed output |
 49
 50## HTTP requests
 51
 52`matcha.http(options)` makes an HTTP request and returns `(response, err)`. Options is a table with:
 53
 54- `url` (string, required) — only `http` and `https` schemes
 55- `method` (string, optional, default `"GET"`)
 56- `headers` (table, optional)
 57- `body` (string, optional)
 58
 59The response table has `status` (number), `body` (string), and `headers` (table with lowercase keys).
 60
 61Safety limits: 10s timeout, 1 MB response body cap.
 62
 63```lua
 64local res, err = matcha.http({
 65    url     = "https://api.example.com/webhook",
 66    method  = "POST",
 67    headers = { ["Content-Type"] = "application/json" },
 68    body    = '{"text":"hello"}',
 69})
 70if err then
 71    matcha.log("error: " .. err)
 72    return
 73end
 74matcha.log("status: " .. res.status)
 75```
 76
 77## User input prompts
 78
 79`matcha.prompt(placeholder, callback)` opens a text input overlay in the composer. When the user presses Enter, the callback receives their input string. Pressing Esc cancels without calling the callback.
 80
 81Only works inside a `bind_key` callback for the `"composer"` area.
 82
 83```lua
 84matcha.bind_key("ctrl+r", "composer", "rewrite", function(state)
 85    matcha.prompt("Enter instruction:", function(input)
 86        -- input is the user's text
 87        matcha.log("User typed: " .. input)
 88    end)
 89end)
 90```
 91
 92## Body rendering
 93
 94`matcha.on("email_body_render", function(email, rendered, raw) ... end)` runs
 95after the email body has been converted to its final ANSI-styled form and
 96before it is placed in the viewport. The callback receives:
 97
 98- `email`: the same table as `email_viewed`
 99- `rendered`: the current display string (ANSI-styled, post-HTML→terminal)
100- `raw`: the original message body (HTML or plain text) — useful for parsing
101  the source instead of the rendered output
102
103Return a new string to replace the rendered body, or `nil` to leave it
104unchanged. Multiple registered callbacks chain in registration order; each
105subsequent callback sees the previous callback's rendered output, but always
106the same raw source.
107
108`matcha.style(text, opts)` wraps `text` in lipgloss styling. `opts` keys (all
109optional):
110
111- `color`, `bg`: string color (hex `"#rrggbb"`, named like `"red"`, or ANSI 256 number as string)
112- `bold`, `italic`, `underline`, `strikethrough`, `faint`, `blink`, `reverse`: bool
113
114```lua
115local matcha = require("matcha")
116
117matcha.on("email_body_render", function(email, rendered, raw)
118    -- highlight TODO in red bold (operates on rendered)
119    rendered = rendered:gsub("TODO", function(m)
120        return matcha.style(m, { color = "#ff0000", bold = true })
121    end)
122    -- italicize anything in *asterisks*
123    rendered = rendered:gsub("%*([^%*]+)%*", function(m)
124        return matcha.style(m, { italic = true })
125    end)
126    -- strip a tracking footer entirely
127    rendered = rendered:gsub("%-%-%-%s*Sent via Tracker.*$", "")
128    return rendered
129end)
130
131-- Parse the raw source and prepend a summary; works regardless of HTML markup.
132matcha.on("email_body_render", function(email, rendered, raw)
133    local urls = {}
134    for url in raw:gmatch("https?://[%w%-_%.~%?=&/%%#:]+") do
135        urls[#urls + 1] = url
136    end
137    local header = matcha.style("URLs: " .. #urls, { bold = true }) .. "\n\n"
138    return header .. rendered
139end)
140```
141
142Caveats:
143
144- The `rendered` string already contains ANSI escape sequences from the
145  HTML→terminal conversion. Patterns that straddle existing escapes will not
146  match — match plain text spans for predictable behavior, or operate on `raw`.
147- Returning a fully replaced string fully takes over the displayed body. To
148  build styled output from scratch, compose with `matcha.style` and join with
149  newlines.
150
151## User-configurable settings
152
153`matcha.settings(spec)` declares configurable options for a plugin. Call it
154once at the top level of the plugin file. `spec` is a table mapping a setting
155key to `{ type, default, label, description }`. Supported types:
156
157- `"boolean"` — toggled in the TUI with a checkbox-style on/off selector
158- `"number"` — edited with a numeric input
159- `"string"` — edited with a text input
160
161The function returns a read-only proxy table whose fields reflect the
162currently saved value (or the default when unset). Read fields anywhere,
163including inside hook callbacks:
164
165```lua
166local matcha = require("matcha")
167
168local cfg = matcha.settings({
169    threshold  = { type = "number",  default = 5,    label = "Subject length threshold" },
170    enabled    = { type = "boolean", default = true, label = "Enable warnings" },
171    suffix     = { type = "string",  default = "!",  label = "Notification suffix" },
172})
173
174matcha.on("email_received", function(email)
175    if cfg.enabled and #email.subject > cfg.threshold then
176        matcha.notify("Long subject" .. cfg.suffix, 3)
177    end
178end)
179```
180
181Values are persisted in `~/.config/matcha/config.json` under
182`plugin_settings`. Edit them in **Settings → Plugins** in the TUI; booleans
183toggle with `enter`/`space`, numbers and strings open a text editor.
184
185## Available plugins
186
187The following example plugins ship in `~/.config/matcha/plugins/`:
188
189- `email_age.lua`
190- `recipient_counter.lua`
191
192## Files
193
194| File | Description |
195|------|-------------|
196| `plugin.go` | Plugin manager — Lua VM setup, plugin discovery and loading, notification/status state |
197| `hooks.go` | Hook definitions, callback registration, and hook invocation helpers |
198| `api.go` | `matcha` Lua module registration (`on`, `log`, `notify`, `set_status`, `set_compose_field`, `bind_key`, `http`, `prompt`, `style`) |
199| `http.go` | `matcha.http()` implementation — HTTP client with timeout and body size limits |
200| `prompt.go` | `matcha.prompt()` implementation — user input overlay for the composer |