Metadata-Version: 2.5
Name: ewstui
Version: 0.1.0
Summary: A terminal (TUI) email + calendar client for Microsoft Exchange, talking EWS directly
Project-URL: Homepage, https://github.com/leifdenby/ewstui
Project-URL: Repository, https://github.com/leifdenby/ewstui
Project-URL: Issues, https://github.com/leifdenby/ewstui/issues
Project-URL: Changelog, https://github.com/leifdenby/ewstui/blob/main/CHANGELOG.md
Author: Leif Denby
License-Expression: MIT
License-File: LICENSE
Keywords: calendar,email,ews,exchange,outlook,terminal,tui,vim
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: End Users/Desktop
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Communications :: Email :: Email Clients (MUA)
Classifier: Topic :: Office/Business :: Scheduling
Requires-Python: >=3.10
Requires-Dist: exchangelib>=5.0
Requires-Dist: keyring>=25.7.0
Requires-Dist: markdown-it-py[linkify]>=3.0
Requires-Dist: markdownify>=0.13
Requires-Dist: msal>=1.28
Requires-Dist: pyobjc-framework-localauthentication>=12.2.2; sys_platform == 'darwin'
Requires-Dist: textual>=0.60
Requires-Dist: tomlkit>=0.15.1
Provides-Extra: kerberos
Requires-Dist: requests-gssapi>=1.2; extra == 'kerberos'
Description-Content-Type: text/markdown

# ewstui

A terminal (TUI) email + calendar client for Microsoft Exchange, with
vim-style keybindings — talking **EWS directly**, no IMAP, no CalDAV,
no local gateway process, no JVM.

Built with [Textual](https://textual.textualize.io/) for the UI and
[`exchangelib`](https://github.com/ecederstrand/exchangelib) for the
Exchange side.

![ewstui --demo: mail, threads, links, moving, bulk selection, priority list, room finder, help and themes](https://raw.githubusercontent.com/leifdenby/ewstui/main/docs/demo.gif)

Every screen is fetched live from Exchange when you open it. Nothing
is cached to disk except, optionally, an OAuth2 refresh token — that's
auth-state, not mail-state; delete `~/.config/ewstui/token_cache.bin`
any time and it just re-prompts for login next run.

## Why this exists

If your Exchange server has IMAP disabled (common on locked-down
on-prem/enterprise deployments) but EWS is reachable, tools like
`aerc`/`neomutt` can't talk to it directly, and gateways like DavMail
require running a JVM. `ewstui` is a from-scratch client instead of a
gateway: it speaks EWS as its *only* protocol and renders the result
directly in the terminal, so there's no IMAP/CalDAV emulation layer
to get wrong.

## Install

From PyPI, as a command-line tool:

```bash
uv tool install ewstui        # or: pipx install ewstui
ewstui --demo
```

For `--auth kerberos`, include the optional extra: `uv tool install 'ewstui[kerberos]'`.

From a checkout (to hack on it), `uv sync` and run it with `uv run ewstui`;
the Kerberos extra there is `uv sync --extra kerberos`.

## Try it without a server first

```bash
uv run ewstui --demo
```

This runs the full UI against fake in-memory mail + calendar data —
useful to check the keybindings and layout work in your terminal
before you touch a real mailbox. See `ewstui/demo_backend.py`.
The GIF above is recorded from demo mode by `uv run python scripts/demo_gif.py`
(needs `rsvg-convert` and `ffmpeg`).

## Run against a real mailbox

```bash
uv run ewstui --email you@corp.example --ews-url https://mail.corp.example/EWS/Exchange.asmx --auth auto
```

If you don't know your EWS endpoint, try `--autodiscover` instead of
`--ews-url` (requires Autodiscover to be reachable/working, which is
not a given on locked-down servers — an explicit `--ews-url` is more
reliable if you can get it from IT).

### Choosing `--auth`

| Value      | What it does | Needs |
|---|---|---|
| `oauth2`   | MSAL device-code flow. Prints a URL + code once; approve it in a browser. Refresh token cached to disk. | `--client-id` (Azure AD app registration), usually `--tenant-id` |
| `ntlm`     | Password sent straight through as NTLM. No disk state. | `--username`/`--email` + password (prompted, or `EWSTUI_PASSWORD` env var) |
| `basic`    | Same as ntlm but plain Basic auth. | same as ntlm |
| `kerberos` | Uses your existing ticket cache (`kinit`) via GSSAPI. No password. | system Kerberos + `uv sync --extra kerberos` |
| `auto` (default) | Tries `oauth2` first; if that's unconfigured or the server rejects it, falls back to `ntlm` automatically. | whatever either path needs |

Since you likely don't know in advance whether your on-prem server
supports modern auth (OAuth2 / Hybrid Modern Auth) or only NTLM,
`auto` is the sensible starting point — pass `--client-id`/`--tenant-id`
in case OAuth2 works, and it'll gracefully fall back to an NTLM
password prompt if not.

If your org uses ADFS rather than Azure AD for OAuth2, override the
token endpoint with `--oauth-authority https://adfs.corp.example/adfs`.

### NTLM domain

If your NTLM username needs a domain prefix (`CORP\jdoe` rather than
just `jdoe`), pass `--domain CORP` and it's prepended automatically.

### Password handling

Never pass `--password` on the CLI (it'd be visible in shell history
and `ps`). Either set `EWSTUI_PASSWORD` in the environment for a
scripted/non-interactive run, or just leave it unset — you'll get a
`getpass` prompt at startup.

**macOS Keychain + Touch ID**: after a successful login with a typed
password, ewstui asks whether to save it in your login Keychain
(service `ewstui`, one item per username + EWS URL). On later starts it
asks for Touch ID (or your Mac password if there's no sensor) and uses
the stored password; cancel the dialog to type it instead. If the
server rejects a stored password (e.g. after a password change) the
item is removed and the next run prompts again. `--forget-password`
deletes it; `--no-keychain` skips the Keychain entirely.

**1Password**: if the password lives in 1Password and the
[`op` CLI](https://developer.1password.com/docs/cli/) is installed and
signed in (or connected to the desktop app), point ewstui at the item
with a secret reference:

```toml
[accounts.work]
password_op_ref = "op://Work/Exchange/password"
```

or `--password-op-ref op://Work/Exchange/password` (saved into the
account like other flags when used with `--account`). It's read with
`op read` at startup, before the Keychain; if that fails you're asked
to type the password instead. ewstui only reads the item. If the
server rejects the password, it tells you to update the item and
leaves it as it is.

Note the Touch ID check is enforced by ewstui, not by the Keychain:
OS-level biometric protection needs a signed app with Keychain
entitlements. The item itself is protected like any login Keychain
item (encrypted, unlocked while you're logged in).

### Config file and accounts

Instead of repeating the flags, keep them as a named account in
`~/.config/ewstui/config.toml` (or `$XDG_CONFIG_HOME/ewstui/config.toml`;
override with `--config PATH`). The easiest way to create one is to
run with `--account NAME` plus your flags once — they're saved after
the connection succeeds, and the first account becomes the default:

```bash
uv run ewstui --account work --email you@corp.example \
  --ews-url https://mail.corp.example/EWS/Exchange.asmx --ntlm-no-cbt --domain CORP
uv run ewstui                 # uses default_account from then on
uv run ewstui --account work  # or pick one by name
```

```toml
default_account = "work"

[accounts.work]
email = "you@corp.example"
ews_url = "https://mail.corp.example/EWS/Exchange.asmx"
domain = "CORP"
ntlm_no_cbt = true
```

- Precedence: built-in defaults < the account's settings < flags on
  the command line.
- With `--account NAME`, any other flags you pass are saved into that
  account. Without it (default account), flags only apply to that run.
- Keys are the option names with `_` instead of `-` (`ews_url`,
  `priority_file`, `refresh_interval`, ...). The password, `--debug`,
  `--log-file` and `--demo` are never stored.
- `layout = "stacked"` (or `--layout stacked`) puts the message list
  above the email, both to the right of the folders; the default
  `"columns"` has all three side by side.
- `date_groups = false` (or `--no-date-groups`) drops the Today /
  Yesterday / This week / ... separators from the message list.
- `theme = "nord"` (or `--theme nord`) picks the colour theme. The
  look — palette, header, status bar and help overlay — follows the
  [tuxedo](https://github.com/webstonehq/tuxedo) todo.txt TUI; its
  default **Muted Slate** palette is ewstui's default, and its **Nord**
  palette is the alternative.
- On/off flags like `--ntlm-no-cbt` can only be switched on from the
  command line; edit the file to turn one off. Comments you add to the
  file are kept when ewstui updates it.

### Troubleshooting the connection

Before the UI opens, ewstui checks the connection in plain terminal
output: it probes the EWS URL (reachability, TLS, which auth schemes
the server offers), then fetches the Inbox once with your credentials
(30 s timeout). On failure it exits with the error and hints instead
of opening an empty UI.

- **Log file**: warnings and errors (and, with `--debug`, full EWS
  traffic) go to a per-user log file, not the current directory:
  - macOS: `~/Library/Logs/ewstui/ewstui.log` (also visible in
    Console.app)
  - Linux: `$XDG_STATE_HOME/ewstui/ewstui.log`, i.e.
    `~/.local/state/ewstui/ewstui.log` by default
  - Windows: `%LOCALAPPDATA%\ewstui\Logs\ewstui.log`

  Override it with `--log-file PATH` or the `EWSTUI_LOG_FILE`
  environment variable (`--log-file` wins). `ewstui --help` shows the
  default for your machine, and `--debug` prints the path in use.
- `--debug` prints tracebacks and logs full EWS traffic to the log
  file (it can contain mail content and auth tokens — delete it
  afterwards).
- **NTLM login hangs** (the Inbox check never answers, while
  `--auth basic` at least gets a quick reply): the server is likely
  behind a TLS-terminating proxy/load balancer (e.g. F5) that can't
  handle NTLM channel binding. Add `--ntlm-no-cbt`, e.g.
  `--ntlm-no-cbt --domain PROD --username jdoe`.
- In zsh/bash, quote `DOMAIN\user` (`--username 'PROD\jdoe'`) or the
  backslash is eaten — or use `--domain` instead.
- **NTLM logins stall or time out** behind a gateway (the connection
  indicator sits on `◐ waiting for server`, or requests keep timing
  out): gateways such as F5 can hang on NTLM's multi-step login. Try
  Basic with your *plain* user id — `--auth basic --username B123456`
  (still encrypted over HTTPS, and no handshake to stall on) — and save
  it once with `--account NAME --auth basic --username B123456`.
- **Caching and prefetching**: emails you've opened are kept in memory
  for the session (the most recent 200; nothing is written to disk), so
  going back to one is instant. Exchange's change key — already in the
  message list — tells ewstui when an email changed, so a stale copy is
  never shown. When the cursor rests on an email, the next two are
  downloaded in the background; the status bar shows `⇣ prefetching 2`
  meanwhile. Prefetching never counts as "waiting for server" or as a
  connection problem.
- **Connection indicator**: the right of the status bar shows
  `● connected`, `● working` (a request is running),
  `◐ waiting for server 12s` (a slow or stalled request — the seconds
  count up) or `✕ connection problem (2m ago)` until the next request
  succeeds. ewstui keeps up to 3 connections, so one stalled request
  doesn't hold up the others.
- **Freezes after being idle**: gateways, firewalls and sleep can drop
  idle connections without telling either end. ewstui guards against
  this: TCP keepalive on every connection (probes after 30 s of
  silence), connections unused for over 2 minutes are replaced before
  the next request, requests time out after 30 s (not exchangelib's
  120 s) with one retry for reads, and emails load in the background so
  the UI stays usable. A `connection problem ... retrying` line in
  the log file shows a retry; with `--debug` you also see `session idle
  ... reconnecting` each time a stale connection is replaced.

## Priority list (`2`)

A local, `todo.txt`-formatted list for triaging mail — separate from
any Exchange folder, stored only on your machine at
`~/.local/share/ewstui/priorities.todo.txt` (override with
`--priority-file`). It's a plain [todo.txt](https://github.com/todotxt/todo.txt)
file, so any other todo.txt tool can read/edit it too (they'll just
see the `@email` context and the `id:`, `folder:`, `from:` fields as
ordinary text).

You can point it at the todo.txt you already use (`priority_file =
"..."` in your account): ewstui only shows and changes the entries it
created — those in the `@email` context (entries with the older
`+email` project tag still count, and switch to `@email` when ewstui
next changes them) — and leaves every other line exactly as it was. It re-reads the file whenever it changed on disk, so edits
from another todo.txt app or a sync client show up straight away and
are never overwritten. The priority view's header names the file in
use, and the "Added to priority list" notice shows its full path.

**In the mail list**, the **P** column shows each email's priority
letter, `-` if it's on the list without one yet.

**Add a message to the list**: from the mail view, select a message
and press `P` (shift+p) to add it straight to the priority list with
no priority set yet and no prompt — or `p` to do the same but first
prompt you for a short note, which gets appended to the entry's text
(e.g. "Re: EWS bridge project — waiting on legal sign-off"). Either
way it's an unprioritized todo.txt line (no `(X)` prefix); set its
priority later from the priority view.

**Work the list**: press `2` (or click the **Priority** tab) to
switch to the priority view. It's grouped by priority, tuxedo style —
`(A)` first through `(Z)`, then unprioritized `(-)`, each under a
header row the cursor skips — and by the date added within a group.
Items whose `due:` date has passed are red; items due within two days
are yellow.

- `A`–`Z` on the row under your cursor — reprioritizes just that item.
- `V` — start a visual selection at the current row (vim visual-line
  style); `j`/`k` extend it; pressing a letter applies that priority
  to every selected row at once and exits visual mode; `Esc` cancels
  without changing anything.
- `x` — toggle complete (writes `x <date>` per the todo.txt spec, and
  remembers the old priority as `pri:A` so it's not lost).
- `d` — remove from the priority list (does not touch the actual
  email or Exchange).
- `Enter`/`o` — jump straight to that email (switches to the mail
  view, opens its folder, puts the cursor on it and shows it in the
  reading pane).

**Emails that move**: each entry stores the email's Internet
Message-ID (`msgid:<…>`), which — unlike Exchange's own item id —
never changes. Moving an email with `m`, `A`, `d` (or undoing with
`u`) updates its entry right away. If it was moved elsewhere (Outlook,
a rule), jumping to it searches your mail folders for the Message-ID
(one request), opens it wherever it is now and updates the entry.
Entries made before Message-IDs were stored get theirs the first time
you open the email.

Example line this produces:
```
(A) 2026-09-24 Q3 budget review @email id:AAMkAD...== folder:AAMkAD... from:finance@corp.example msgid:<0978d17921ac@corp.example>
```

## Attachments (`v`)

From the mail view, press `v` on a message to list its attachments
(no-op with a "No attachments" notice if there are none). `j`/`k` to
move, `Enter`/`l` to pick one — it's saved and then opened with the
system's default app (`open` on macOS, the file association on
Windows, `xdg-open` on Linux). If that isn't possible, you still get
the saved path in the notification so you can open it yourself.

Where it's saved: `--attachment-dir` (or `attachment_dir` in the
account's config) if set; otherwise on macOS
`~/Downloads/Attachments/<account>` — the `--account`/default account
name, or your email address when no account profile is in use — and
`~/Downloads/ewstui-attachments` elsewhere.
Re-downloading the same file never overwrites a previous copy — it's
suffixed `(1)`, `(2)`, etc.

To save somewhere else, press `s` on the attachment instead: a fuzzy
folder picker opens on your home folder (folders a few levels deep,
leaving out hidden ones, `Library`, `node_modules` and the like). Type
a few letters of the folder (`invo` for `~/Documents/Work/Invoices`), or
a full path (`~/…`, `/…`), and Enter saves it there (without opening
it). Matches are shown shortest path first. Tab goes into the
highlighted folder: its path goes in the box (`~/Nextcloud/`), the list
becomes that folder's subfolders and typing searches inside it — so any
depth is a few Tabs away; backspacing over the `/` goes back up.
Cmd+Enter (in terminals that pass Cmd on) or Ctrl+O saves there and
then opens the folder (Finder on macOS). If
[fzf](https://github.com/junegunn/fzf) is installed, it does the
matching (`fzf --filter`), which is fast enough to list folders deeper
(6 levels below the folder searched instead of 4). Folders you saved to this session, and the usual attachment
folder, are at the top.

Several at once: `V` starts a selection in the list, `j`/`k` extend it;
then Enter saves and opens all of them, `s` saves all of them to one
folder. Esc ends the selection first.

Only real file attachments are downloadable; an attachment that's
itself an embedded email or calendar item (e.g. a forwarded message)
shows up greyed out in the list since EWS represents those
differently and this doesn't handle that case yet.

## Asking an LLM agent to handle an email (`C`)

Press `C` on an email (in the list or the reading pane), type what you
want done ("draft a short reply saying I'll look at it Monday",
"summarise the attachment and list the deadlines") and press Enter.
ewstui puts the email and its attachments in a folder, then starts an
agent (Claude Code by default) in a new tab of your terminal, with your
instruction as its first prompt. You follow along and approve what it
does there.

The agent works on your mailbox through ewstui's own command line:
`ewstui draft` saves its reply to Drafts (it's told not to `--send`
unless you asked it to), and `ewstui calendar`, `search` and `contacts`
let it look things up.

```toml
[llm-agent]
workdir = "~/Nextcloud/Work/DigitalBrain"  # where the agent starts (default ~/.local/state/ewstui/agent)
email_subdir = "emails/{date}-{slug}"      # where the email + attachments go, inside workdir
command = "claude"                          # the agent; the prompt is passed as its last argument
# terminal = "foot --working-directory {cwd} {command}"  # only if yours isn't detected
```

- `email_subdir` can use `{date}` (2026-11-20), `{time}` (1532),
  `{slug}` (from the subject) and `{account}`. It's always inside
  `workdir`; a folder that already exists gets `-2`, `-3`, ... The
  folder holds `email.md` (headers, Message-ID, text), the attachments
  and `prompt.md` (what the agent was asked).
- The new tab opens in tmux, GNOME Terminal, kitty (with remote
  control on), WezTerm, iTerm2, or Terminal.app (a new window there).
  For any other terminal, set `terminal`: `{cwd}` is the folder,
  `{command}` the agent's command as separate words, and
  `{shell_command}` one shell line with the `cd` (for `bash -c
  {shell_command}`-style launchers). If no terminal is found, the
  command is copied to the clipboard instead.

## Exporting a folder (`ewstui export`)

Copies one mail folder to plain files, for reading and searching outside
ewstui (grep, scripts, an AI assistant), without opening the UI:

```bash
ewstui export "Projects/0 - Proposals/SBEP" --out ~/proposals/sbep/emails --with-sent
ewstui export --update ~/proposals/sbep/emails   # later: fetch what's new
```

- The folder is its path in the folder pane, `/`-separated, any case.
  If there's no such folder, the closest paths are listed.
- `--with-sent` also exports your replies from Sent Items to the
  folder's conversations (matched on Exchange's conversation id, going
  back 30 days before the folder's oldest email).
  `--no-attachments` skips downloading attachments.
- Connection options are the usual ones (`--account`, `--email`,
  `--auth`, ...); with none, the default account is used. Logging in
  works as for the UI (Keychain + Touch ID, or a password prompt).
- Re-running only fetches emails that are new or changed (by Exchange's
  change key); the rest is left as it is. `--update DIR` reads the
  folder, account and options from the earlier export. One directory
  holds one folder of one mailbox: exporting another one into it is
  refused.

What it writes:

```
emails/
  index.json                                        where it came from + one record per email
  2026-10-20_0931_kick-off_1a2b3c4d.md              headers + the email's plain text
  attachments/2026-10-20_0931_kick-off_1a2b3c4d/plan.docx
```

`index.json` (format `ewstui-export/1`) has:
- `source`: the mailbox, account, EWS URL, folder path and id, and the
  options used.
- `exported_by`: the ewstui version, git commit and command line (the
  password is never on the command line).
- `first_synced` and `last_synced`.
- `counts`.
- `emails`, newest first. Each email has its file, date, subject,
  from/to/cc (name and address), the folder it came from, its
  attachments, and `present` (false once it's gone from the folder; its
  file is kept).

Each email also carries the ids to find it on the server again:
- `message_id`, the Internet Message-ID, which never changes, even when
  the email is moved.
- `ews_item_id` and `ews_folder_id`, Exchange's own ids. They're a
  direct lookup, but Exchange gives an email a new id when it's moved.
- `changekey`.

File names end in a hash of the Message-ID, so they stay the same across
runs.

### Searching and exporting single emails (`ewstui search`, `export --message`)

To find an email without opening the UI, and export just it (or its
whole thread) rather than a folder:

```bash
ewstui search Joel CV                       # Inbox + Sent Items, newest first
ewstui search "budget" --folder Archive --folder "Projects/SBEP"
ewstui search "budget" --folder all --json  # every mail folder, as JSON
ewstui export --message "<abc123@mail.example>" --thread --out ~/letters/joel/emails
ewstui export --message "<def456@mail.example>" --out ~/letters/joel/emails   # adds to it
```

- `search` uses Exchange's own search (words in the subject, body and
  people; a word also matches the start of a longer one). Exchange
  searches one folder per request, so each folder is a separate request,
  merged newest first; `--limit` (default 25) caps the hits. Each hit
  is printed with its Message-ID (`@` marks attachments).
- `export --message ID` finds the email in whichever folder it is in.
  Repeat `--message` for more. `--thread` adds the rest of each email's
  conversation from any folder, your replies in Sent Items included.
- The directory's `index.json` has `source.kind: "messages"` and the
  Message-IDs in `source.message_ids`. Exporting more emails into the
  same directory adds to that list. `--update DIR` refreshes them all
  (and their threads, if exported with `--thread`). A directory holds
  either a folder export or selected emails, never both.

### Listing calendar events (`ewstui calendar`)

To list your calendar over a date range without opening the UI (e.g. to
look back over a year's trips):

```bash
ewstui calendar --from 2026-01-01 --to 2026-12-31          # oldest first, one line each
ewstui calendar --from 2026-01-01 --json > calendar.json   # --to defaults to today
```

- Both days are included. The range is fetched a month at a time
  (Exchange caps one calendar view), and an event spanning months is
  listed once.
- Each line shows start, end, Exchange's "show as" status (Busy, OOF,
  WorkingElsewhere, ...), subject and location. `--json` gives the same
  fields plus the organizer.

### Emails written elsewhere (`ewstui draft`)

To write an email in another program — your editor, a script, an AI
assistant — and hand it to Exchange as a new email, a reply or a forward:

```bash
ewstui draft reply.md                 # saved to Drafts (the default)
ewstui draft reply.md --send          # or sent straight away
pbpaste | ewstui draft - --in-reply-to "<abc123@mail.example>" --reply-all   # text from stdin
```

The file is the email's text in Markdown (sent as HTML, as from the
compose view), optionally under a header block between `---` lines:

```markdown
---
in-reply-to: <abc123@mail.example>
reply-all: yes
---
Hi Jane,

Thanks, **that works for me**.
```

- Headers: `to`, `cc` (comma-separated, or one `- address` per line
  below; `Name <address>` works), `subject`, `in-reply-to` (the
  Message-ID of the email you answer, as `ewstui search` and `export`
  print it), `reply-all` (yes/no), `forward` (a Message-ID), `quote`
  (yes/no). An unknown header is an error, so a typo isn't silently
  dropped. Options (`--to`, `--cc`, `--subject`, `--in-reply-to`,
  `--reply-all`, `--forward`, `--no-quote`) override the file's headers.
- A reply is a real reply, found by its Message-ID in any folder: it's
  threaded, and Outlook shows the original as answered. Without `to` /
  `cc` it goes to the sender, or with `reply-all` to everyone but you
  (as `r` / `R` prefill them). The subject defaults to `Re: ` the
  original's. Exchange adds the original below your text, as with
  Outlook's replies; `quote: no` sends only what you wrote (for inline
  answers you quote yourself).
- A forward carries the original and its attachments below your text;
  the subject defaults to `Fwd: ` the original's.
- Attachments: `attach:` lists files, one per line (`attach: report.pdf`
  or `- path` lines below it), relative to the draft file's folder (the
  current one for stdin); `~` works. `--attach PATH` (repeatable) adds
  more, relative to the current folder. They go with a new email, a
  reply or a forward (on top of the forwarded email's own). A reply or
  forward with files is saved to Drafts, the files attached there, then
  sent, as Exchange's reply can't carry files itself.
- A new email needs a subject; sending needs a recipient, saving to
  Drafts doesn't.
- The file is checked before logging in (a missing attachment too). It
  prints what was saved or sent, the email it answers, the recipients
  and the files attached. A draft is then in
  Drafts: open it in ewstui (Enter on it), Outlook or OWA to check,
  change and send it.

## Keybindings

Press `?` inside the app for the full list: a panel with every section
side by side (stacked on narrow terminals; `j`/`k` or `Ctrl+d`/`Ctrl+u`
scroll it, `Esc`/`?`/`q` close it). The status bar at the bottom always
shows the current mode and the most useful keys for the pane you're in.
Summary:

`o` (or `Enter`) opens whatever's under the cursor *and* moves focus
into the next pane over (folders → messages → reading pane). `l`/`h`
do the same moving right/left, vim-style (as do `Tab`/`Shift+Tab`);
`h` moves back without changing what's displayed. The status bar
suggests whichever fits the layout: `l` when the email is to the right
of the list (`columns`), `o` when it's below it (`stacked`). Plain `j`/`k`
navigation never steals focus on its own — moving through the message
list with `j`/`k` just live-updates the reading pane, the same as
mutt/aerc; only an explicit open shifts focus there.

**Global**: `j`/`k` move, `g`/`G` top/bottom, `o`/`Enter` open, `l`/`h`
(or `Tab`/`Shift+Tab`) next/previous pane, `1`/`2`/`3` switch to mail/priority/calendar
view (also shown as clickable mode tabs under the header, with the
active one highlighted), `Ctrl+l` refresh, `q` quit, `?` help.

**HTML emails**: emails written in HTML are shown formatted in the
reading pane: bold, italics, underline, strike-through, text colours and
highlights, links (clickable in terminals with OSC 8 hyperlinks, e.g.
iTerm2, kitty, WezTerm), headings, bulleted / numbered lists, quoted
replies and paragraph breaks; tables become one line per row. Fonts and
sizes can't carry over to a terminal. Colours are adapted to the theme:
greys, black and white use the theme's text colour, and other colours are
lightened (or darkened) until readable on its background. `H` in the
reading pane switches to the email's plain-text version and back.
Replies, forwards, search and export keep using the plain text.

**New mail**: `Ctrl+l` checks for new mail now (in the calendar or
priority view it reloads that view instead). ewstui also checks in the
background every 5 minutes (`--refresh-interval MINUTES`, `0` turns it
off) and shows e.g. "New mail: Inbox (+2)". Fetching happens off the UI
thread, and the cursor and open message stay where they were.

**vim in the text boxes**: the email's text box and the To / Cc fields
have vim's modes, shown at their bottom right. They start in INSERT
(type straight away); Esc goes to NORMAL, and Esc never closes the
window. NORMAL: `h j k l`, `w b e`, `0 ^ $`, `gg G` (with counts: `3j`,
`2dd`), `x X`, `r`{char} (`3rx`), `dd dw de D`, `cc cw C s S`,
`yy yw p P`, `J`, `u` / Ctrl+R, `i a I A o O` into INSERT, `v` / `V`
into VISUAL / V-LINE (move to select; `d`/`x`, `y`, `c`, `r`{char}). Yanked and deleted text also goes to the
system clipboard. `:wq` (or `:x`) saves to Drafts and closes, `:q`
closes a window you haven't written in, `:q!` closes it and throws away
what you wrote. Ctrl+S, Ctrl+Q, Tab and Ctrl+O work in every mode. In
To / Cc, `V` then `j`/`k` and `d` drops whole addresses.

**Writing**: Ctrl+S (or Cmd+Enter) sends; Ctrl+Q (or `:wq`) saves what
you've written to your Drafts folder and closes (a reply stays a reply
to its email; an untouched window just closes). Outside the compose
view Ctrl+Q still quits ewstui. If sending or saving fails, the
window comes back with your text. To go on with a draft, open Drafts
and press Enter / `o` on it: the compose view opens with it filled in;
Ctrl+S sends that draft (a copy goes to Sent Items), Ctrl+Q saves your
changes into it. (Drafts are edited as plain text: formatting from
Outlook doesn't survive an edit here.)

**Markdown**: what you write is sent as an HTML email, with Markdown
formatting: `**bold**`, `*italic*`, `~~strike~~`, `- bullets`,
`1. numbers`, `[text](https://...)`, `> quotes`, `` `code` `` and fenced
code blocks, and tables. Plain text written without Markdown in mind
comes out as typed: every line break is kept, bare URLs become links,
raw HTML is shown as text, and a `--` signature line or indented text
stay as they are (they don't become a heading or code).

**To / Cc**: one recipient per line, either `Name <address>` or just the
address (commas and semicolons also separate). Nothing is selected when
you move into a field, so typing adds to what's there (a reply-all opens
with everyone filled in, one per line). Tab looks the current line up in
your organisation's directory. Type part of a name and press Tab: one
match fills the line in, and with several you pick one (`j`/`k`, Enter).
Tab on an empty line or one that already holds an address moves on to the
next field, so `casey` Tab Tab fills in Casey and moves to Cc. Ctrl+Space
looks up any line, including part of an address, but macOS often takes
it for switching input source. The lookup also searches your own address
book (see below), whose matches come first. A line under each field says
which addresses are in the directory or your contacts and flags the ones
that are in neither ("? not in the directory: …"). Those may be fine
(people outside the organisation), but it catches typos.

**Your address book** (`contacts.toml`, next to `config.toml`) holds the
people the directory doesn't know, e.g. colleagues at other institutes:

```toml
[[contact]]
name = "Heleen ter Pelkwijk"
email = "heleen@knmi.nl"
org = "KNMI"          # optional; also searched
```

It can also be kept in sync from a folder of Markdown notes, one person
per note (e.g. an Obsidian `people/` folder), set in `config.toml`:

```toml
[contacts]
sync_from = ["~/Notes/people"]
# file = "~/elsewhere/contacts.toml"   # if not next to config.toml
```

A note gives its `# Heading` as the name (else the file name), every
address on its `- **Email:** …` line (the first one first) and its
`- **Org:** …`. Subfolders are ignored. ewstui syncs when it starts if a
note changed since the last sync; synced entries carry a `source` and
are rewritten each time, your own entries (no `source`) are never
touched. `ewstui contacts sync` syncs now and lists what changed;
`ewstui contacts find NAME [--json]` searches the address book as Tab does.

Ctrl+O shows your calendar beside the
email, to check when you're free: the working days (Mon–Fri) as columns,
three weeks as rows (from this week, or next week at the weekend), each
day listing its booked time slots; Ctrl+B / Ctrl+F go three weeks back
or forward.

Offering times: Ctrl+O puts you in that calendar (Ctrl+O or Esc takes
you back to writing). `h`/`l` move a working day, `j`/`k` a week (past
the weeks shown, it pages on), Space picks or unpicks a day, `v` selects
a run of days. Enter pastes your free time on the chosen days (or the
day under the cursor) into the email where your cursor was:

    I am currently available these times (CEST):
    - Monday 5th Oct, 1000-1200
    - Tuesday 6th Oct, 1200-1300

Free means within 08:00–17:00, in whole hours (at least one), not
already past, and not overlapping anything shown as Busy, Tentative or
Out of office — an all-day one (a holiday) takes the whole day, while
Free / Working-elsewhere entries don't count.

**Mail**: `r` reply, `R` reply-all (the original is quoted below your
text, as Markdown so its bold, links and lists survive: leave the quote
as it is and Exchange sends the original underneath in its full
formatting; answer inline or trim it and the reply goes out as written),
`f` forward (the original and its attachments go along below what you
write), `w` compose new, `d` delete,
`Space` toggle read/unread, `P` add to priority list (no priority,
no prompt), `p` add to priority list with a note and a priority:
↑ / ↓ in the note dialog go through none, A, B and C while you
type (or click one; not Ctrl+arrows, which macOS uses to switch Spaces); on an email that's already listed, `p` edits that
entry's note and priority instead, `A` archive, `m`
move to folder, `t` thread view, `v` view/save/open attachments, `u`
undo. `r` `R` `f` `d` `A` `m` `P` `p` `v` also work while you're reading the
email (focus in the reading pane), on that email; after a move, archive
or delete you stay in the reading pane, on the next email.

**Search** (`/`): in the message list, searches the folder you're in.
A search bar opens above the list and the list narrows as you type: a
fuzzy match on subject and sender (`budg` finds "Q3 budget review", best
matches first), and, once you pause, Exchange's own search too, which
also looks in the text and in older emails than the ones loaded. Enter
or ↓ goes into the results (open, reply, archive… as usual; the results
stay current), `/` back to the search bar, Esc ends the search.

**Find a folder** (`/` in the folder pane): the folder list narrows to
the folders whose name or path fuzzy-matches what you type (`deod` finds
"Projects/DEODE"), best first. Enter opens the top match, ↓ goes into
the matches to pick one with `j`/`k` and Enter, Esc shows all folders
again.

**Links** (`U`): lists the links in the email shown in the reading
pane (web and `mailto:` links, with the text just before each so you
can tell them apart). `j`/`k` and Enter — or just `1`–`9` — open one in
your default browser; `Esc` cancels. Only `http(s)` and `mailto` links
are ever opened.

**Due dates on the priority list**: in the note (`p`), typing `due:` —
or `t:`, todo.txt's threshold date — opens a month calendar like
tuxedo's: `h`/`l` a day, `j`/`k` a week, `[`/`]` a month, `t` today,
Enter puts the date in (`due:2026-10-01`), Esc goes back to typing.
`dur:` (how long answering will take) opens a row of durations the same
way: 5m · 15m · 30m · 1h · 2h · 4h · 1d, `h`/`l` to choose and Enter, or
`1`–`7` straight away (`dur:30m`). These are saved as todo.txt fields,
and `p` on a listed email shows them with the note to change or remove.

**Recipients** (`e`): the reading pane shows people by name, with a
long To or Cc list folded onto one line ("Anna Berg, Bo Christensen …
+14 more"). `e` — or a click on "+14 more" — lists everyone, one per
line with their address; `e` again folds it. Each new email starts
folded.

**Folders**: the folder pane lists your mail folders (not Calendar,
Contacts, Tasks, …). In it, `V` picks up the folder under the cursor,
`j`/`k` move it among the folders at its level (its subfolders go with
it), and Enter or `V` puts it down; `Esc` puts it back. `H` hides a
folder (and what's in it); `.` shows hidden folders dimmed, where `H`
unhides them. Outlook's housekeeping folders (Sync Issues, Conversation
History, RSS feeds) and the F2 integration folders are hidden to start
with. The order and hidden folders are saved in your account's section
of the config file (`folder_order`, `hidden_folders`, `shown_folders`,
each folder id with its name as a comment).

**Invites** (`i`): meeting invites are tagged `invite ·` in the list,
and the reading pane shows a card above the text: when, where, your
answer so far, what it clashes with in your calendar, and your day as a
strip of half-hour cells (`·` free, `█` busy, `▒` the meeting, `×` the
meeting on top of something else). `i` opens the answer popup with the
same availability: `a` accept, `t` tentative, `d` decline; `s` switches
off sending your response to the organizer (only your calendar
changes); `n` (or Tab) types an optional note to send with it; `p`
types a new time to propose with a tentative or decline (`14` keeps the
meeting's day and length, `thu 10:30`, `tomorrow 9-10:30`; the line
below shows what it read). The organizer gets Outlook's "New time
proposed", which they can accept. A proposal needs the response to be
sent, and the field is absent when the organizer turned proposals off. The
invite email is then archived (`u` brings the email back; your answer
stays). A cancellation (`cancelled ·`) shows the meeting's time and
place, and `i` offers to remove it from your calendar.

**Event from an email** (`c`): for a save-the-date that came as plain
text, without an invite. A panel opens to the right of the email (still
readable; Tab goes between the panel's fields and the email) with the
title taken from the subject (minus "Save the date:"), a month calendar
to pick the day tuxedo-style (`h`/`l` a day, `j`/`k` a week, `[`/`]` a
month, `t` today) and a field to type one (`tomorrow`, `fri`, `+3d`,
`in 2 weeks`, `14 oct`, `2026-10-14`). Dates the email mentions are
marked, the first upcoming one is picked, and `n` jumps to the next; a
time range in the text ("10:00–16:00") fills in the times, otherwise
it's all day. For several days, `v` in the calendar starts selecting
days (the same keys extend it, `v` or Esc ends it): all day covers those
days, a timed event runs from the start time on the first to the end
time on the last; a range in the email ("14–16 October") is selected to
start with. Below, your calendar that day. Ctrl+S adds the event to
your calendar (no invitations), with the email's text in its notes;
Esc closes the panel.

**Teams meetings** (Ctrl+T): Exchange can't make a Teams join link —
only the Teams service can (Outlook's "Teams meeting" button asks Teams
too) — so in the new-event screen (`n` in the calendar, and after
picking rooms in the room finder) and in the event-from-email panel
(`c`), Ctrl+T hands the meeting to Teams instead of saving it: Teams'
own "New meeting" form opens (the Teams app, or teams.microsoft.com if
it isn't installed) with everything filled in: title, times, the
attendees and notes you entered (plus the location, and picked rooms as
attendees). Check it and send it from Teams, which creates the meeting,
its join link and the invites.

On Linux (Microsoft retired the official Teams app there in 2022), an
app registered for `msteams:` links — e.g. teams-for-linux — is used if
there is one (`xdg-mime query default x-scheme-handler/msteams`),
otherwise Teams on the web in your browser (Chrome/Edge work best for
meetings).

`T` on an event in the calendar view: if it's a Teams meeting (a Teams
join link in its text), it opens that meeting in Teams to join. If it
isn't, Teams' New meeting form opens filled in from the event (title,
time, attendees and rooms, location, text) — a new Teams meeting, as
Teams can't turn an existing event into one; the old event stays (`d`
deletes it).

The new-event screen has Attendees (addresses, comma separated) and
Notes fields: with Ctrl+S the attendees get an invitation from Exchange
and the notes become the event's text.

**Several at once** (`V`): starts a selection at the current email;
`j`/`k` grow or shrink it (selected rows are highlighted, and the
status bar shows how many). Then `d` delete, `A` archive, `m` move
(one folder pick for all), `Space` mark read — or unread, if they're
all read already — or `P` add them all to the priority list. The work
runs in the background, one failure doesn't stop the rest, and a single
`u` undoes the whole batch. `Esc` (or `V` again) cancels the selection.

**Thread view** (`t`, or start in it with `threads = true` in your
account / `--threads`): messages in the same conversation are shown
together as an upside-down tree — the newest message on top, the
original at the bottom, and each reply connected to the message it
answers (`┌─`, `├─`, `│`) — placed in the list by the thread's most
recent message. The top row and the original show the subject; replies
in between that keep the thread's subject show just the tree guide.
Every row is still one message, so opening and `r`/`d`/`m`/... work on
exactly the row you're on. Like Outlook, threads include your own
replies from Sent Items, marked `(sent)` — ewstui fetches one page of
recent Sent Items and matches them to the folder's conversations.

**Date separators**: the message list is split into **Today**,
**Yesterday**, **This week**, **Last week**, **This month**, then one
group per month (with the year for earlier years). In thread view a
thread goes under the day of its newest message; search results have
none. The cursor steps over them; `}` jumps to the first email of the
next group, `{` back to the start of this one (or the previous one).
Turn them off with
`date_groups = false` in your account (or `--no-date-groups`).

**Moving mail** (`m`): opens a folder picker for the message under the
cursor. Folders you've moved mail to this session are listed first,
then the rest in folder-pane order. Start typing to fuzzy-filter by
folder path (e.g. `prew` finds `Projects/EWS`); `↓`/`↑` or
`Ctrl+n`/`Ctrl+p` choose, Enter moves, Esc cancels. After a move,
delete or archive the cursor stays on the next message, and `u` puts
the message back.

**Reading pane** (after `o`/`Enter` moves focus into it): `j`/`k`
scroll a line, `Ctrl+d`/`Ctrl+u` half a page, `Ctrl+f`/`Ctrl+b` (or
`Space`) a full page, `g`/`G` top/bottom, `h` back to the list.

**Copying text from an email**: drag over the text in the reading pane
with the mouse to select it (double-click selects the whole email,
header included), then press `y` (or `Ctrl+c`) to copy it; `Y` copies
the whole body of the email shown, as displayed (formatted, or plain
text after `H`). A notice says how many characters were copied (a bell
and a hint if nothing is selected). The text goes to the system
clipboard via `pbcopy` on macOS, and to the terminal's clipboard via
OSC 52 (which works over SSH in terminals that allow it, e.g. iTerm2,
kitty, WezTerm, Ghostty; not macOS Terminal). The selection is ewstui's
own, since the app captures the mouse: to use your terminal's native
selection instead, hold Option (iTerm2), Fn (macOS Terminal) or Shift
(kitty, WezTerm, most Linux terminals) while dragging.

**Deleting and undo**: `d` moves the message to Exchange's **Deleted
Items** folder (same as Delete in Outlook) — nothing is purged. `u`
moves the most recently deleted, archived or moved message back to the folder
it came from; press it repeatedly to walk back further. The undo
history lasts for the session only; after a restart, recover from
Deleted Items by hand. Pressing `d` *inside* Deleted Items soft-deletes
the message (only recoverable via Outlook/OWA's "Recover deleted
items") and can't be undone with `u`.

**Calendar**: `n` new event, `f` find a free meeting room, `d` delete
event, `[`/`]` shift the visible date range.

**Finding a room** (`f` in the Calendar tab): shows one day as a grid —
a row per room in your account's config, a column per half hour of your
working day (taken from your Outlook working hours if the server
provides them, else 08:00–17:00), `███` busy and `·` free; `e` widens
it to 06:00–22:00 to book outside working hours (`e` again to go back). It's one EWS
GetUserAvailability call per day, with no access to the rooms' calendars
needed. `[`/`]` go to the previous/next day (`t` back to today), or Tab
to the date field, type a date and Enter; `j`/`k` pick the room and
`h`/`l` (or `w`/`b`, `←`/`→`) the time. The status line says whether the
room is free for the chosen duration from that slot; Enter opens a new
event prefilled with that slot and room. Or press `v` to start a visual
selection and move to cover the rooms and times you want: Enter books
all selected rooms for that span in one invite (it refuses if any
selected cell is busy, and says which), `v`/`Esc` cancels the
selection. Saving the event invites the room(s) as resources, and each
room's booking assistant accepts or declines it
(check your calendar/inbox for its reply). List the rooms in the config
file, by name or as plain addresses:

```toml
[accounts.work.rooms]
"G-5222 Havgus (8 pers)" = "room-g5222@corp.example"
"Stormen"                = "room-stormen@corp.example"
# or: rooms = ["room-g5222@corp.example", "room-stormen@corp.example"]
```

Or find them from the grid: press `/`, type part of a room's name and
Enter. ewstui searches your organisation's room lists (if your admins
set any up) and the directory; directory hits can also be people, so
each result says where it came from. Pick one with `j`/`k` and Enter:
it's added to the grid and saved to the account's `rooms` in the config
file (needs `--account`/`default_account`; otherwise it's only added
for this session). With no rooms configured, the grid opens empty so
you can start with `/`.

The grid caches each day it has loaded, so paging between days is
instant; press `r` to throw that away and fetch fresh availability.

**Priority list**: `A`-`Z` set priority, `V` visual-select, `x` toggle
complete, `d` remove, `Enter`/`o` jump to email.

**Compose/new-event modals**: `Ctrl+S` send/save. New event: `Esc`
discards. Compose: `Ctrl+Q` / `:wq` save to Drafts and close, `:q!`
discards (Esc is only vim's).
In compose, `Cmd+Enter` also sends — if your terminal passes the Cmd
key through (Ghostty, kitty and WezTerm do; in iTerm2 enable Profiles →
Keys → "Report keys using CSI u"; Terminal.app can't).

## Project layout

```
ewstui/
  config.py        CLI args -> Config dataclass
  auth.py           oauth2 / ntlm / basic / kerberos / auto -> exchangelib.Account
  ews_client.py      Live MailClient + CalendarClient wrapping exchangelib
  demo_backend.py    Fake in-memory stand-ins for --demo (same interface as ews_client)
  keymap.py          Single source of truth for the help-screen text
  screens.py         Modal screens: compose/reply, new event, help
  priority_store.py  Local todo.txt-backed priority list (parse/format/store)
  export.py          `ewstui export`: a folder or selected emails -> files + index.json
  cli_search.py      `ewstui search`: Exchange search over several folders, printed
  cli_draft.py       `ewstui draft`: an email from a Markdown file -> Drafts (or sent)
  app.py             Main Textual App: three-pane mail view + calendar + priority views
  clipboard.py       Copy to the system clipboard (pbcopy on macOS, beside OSC 52)
  contacts.py        Your address book (contacts.toml), synced from person notes; `ewstui contacts`
  ask_agent.py       `C`: an email + its attachments into a folder, an LLM agent started on it in a new tab
  widgets/
    folder_list.py    Left pane
    message_table.py  Middle pane
    preview.py         Right pane
    calendar_view.py   Calendar agenda view
    priority_view.py   Priority list view (visual-select + reprioritize)
```

`app.py` never imports `exchangelib` directly — it only knows the
plain dataclasses in `ews_client.py` (`MessageSummary`, `EventSummary`,
etc.), which is what lets `--demo` swap in fake data with zero changes
to the UI code.

## Known limitations (v1)

- **Folder lookup is O(folders) per call** (`MailClient._folder_by_id`
  walks the folder tree each time) — fine for normal mailbox folder
  counts, but a hot path worth caching if you have hundreds of folders.
- **Embedded-item attachments** (a forwarded email or calendar invite
  attached as an item, rather than a file) aren't downloadable yet —
  `v` will show them in the list greyed out with a note, but selecting
  one just beeps rather than crashing.
- **No search** — `/` is documented as a future binding but not wired
  up yet.
- **No offline/local cache** — by design (see "Why this exists"), but
  it does mean no network = no mail. If you want offline reading,
  that's a different, larger project (sync EWS -> local Maildir, point
  a separate reader at that).
- **Kerberos path is untested** against a real KDC — the plumbing is
  there (`GSSAPI` auth_type via `requests-gssapi`) but wasn't
  exercised against a live server while building this.
- **OAuth2 scope is hardcoded** to
  `https://outlook.office365.com/EWS.AccessAsUser.All` — if your
  Azure AD app registration exposes a different scope, edit
  `DEFAULT_OAUTH_SCOPE` in `auth.py`.

- **`A` (archive) requires a folder literally named "Archive"** in
  your mailbox — `MailClient._find_archive_folder` looks it up by
  name (case-insensitive) under the mailbox root, since on-prem EWS
  doesn't expose a dedicated "online archive" well-known folder the
  way some cloud setups do. If you don't have one, create it once
  (or move a message into a folder called that manually) and archiving
  will find it from then on.

## Testing changes

There's no formal test suite yet, but `--demo` mode plus Textual's
`App.run_test()` (headless pilot testing) is how this was built and
verified — see the project history for example smoke-test patterns:
drive the app with `pilot.press("j")`, `pilot.press("enter")`, etc.,
and assert on `app.current_folder_id` / widget row counts.
