summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-08-25 09:13:21 +0200
committerDanilo M. <danix@danix.xyz>2026-08-25 09:13:21 +0200
commit3e196bbaf6a5f3ebf6597e0ada1f559d24627ca6 (patch)
tree5d76949bf34ab581826f0f699d60e0fc45b3e175
parentf8d136432466479c892841bc73bd85e58674da86 (diff)
parent0a26961f9a7ae6ab98051e182b92e64165758cf1 (diff)
downloadqtmaildir-3e196bbaf6a5f3ebf6597e0ada1f559d24627ca6.tar.gz
qtmaildir-3e196bbaf6a5f3ebf6597e0ada1f559d24627ca6.zip
Merge branch 'signatures'
Signatures (item 152): one markdown file per signature under ~/.config/qtmaildir/signatures/, spliced into the composer buffer and chosen from a switch on the editor bar. [compose] signature seeds a new message, [account.<key>] signature overrides per account, and [compose] signature_position picks end or above_quote. Also carries three fixes found by hand-testing it: a saved draft is indexed so it appears without a sync (item 158), the Drafts filter lists messages rather than threads so a draft reply can be opened (item 159), and a resumed draft no longer re-seeds its signature on a From: change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UUQS6n3cmsFrsjCNmwNtf8
-rw-r--r--CHANGELOG.md11
-rw-r--r--README.md35
-rw-r--r--docs/superpowers/plans/2026-08-03-post-0.1.0-usability-closed.md175
-rw-r--r--docs/superpowers/plans/2026-08-03-post-0.1.0-usability.md102
-rw-r--r--docs/superpowers/plans/2026-08-24-signatures.md60
-rw-r--r--src/CMakeLists.txt1
-rw-r--r--src/composewindow.cpp168
-rw-r--r--src/composewindow.h44
-rw-r--r--src/config.cpp73
-rw-r--r--src/config.h23
-rw-r--r--src/mainwindow.cpp11
-rw-r--r--src/notmuchworker.cpp93
-rw-r--r--src/notmuchworker.h22
-rw-r--r--src/signatures.cpp229
-rw-r--r--src/signatures.h76
-rw-r--r--tests/CMakeLists.txt2
-rw-r--r--tests/test_composewindow.cpp451
-rw-r--r--tests/test_config.cpp109
-rw-r--r--tests/test_notmuchworker.cpp106
-rw-r--r--tests/test_signatures.cpp294
-rw-r--r--translations/qtmaildir_it_IT.ts16
21 files changed, 1975 insertions, 126 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1144402..fee2199 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,7 +31,9 @@ point at which they are stable.
- **A Drafts filter** in the query row, beside Sent and Trash. It matches each
account's `drafts` folder, so it finds what the composer actually writes
rather than trusting a flag. An account that configures no drafts folder
- contributes nothing and shows no button.
+ contributes nothing and shows no button. Like Sent, it lists messages rather
+ than threads: a draft reply gets a row of its own instead of being folded
+ into the conversation it answers, where it could not be opened.
- `Ctrl+W` closes a composer, the way it closes a window elsewhere. The draft
is saved or discarded exactly as it is when the window is closed by any
other route.
@@ -65,6 +67,13 @@ point at which they are stable.
- The notmuch hooks that auto-tag incoming mail now live in this repository,
under `assets/hooks/`. They moved from the companion `mailctl` project,
which is being retired.
+- Signatures. Markdown files in `~/.config/qtmaildir/signatures/`, one per
+ signature, chosen from a control on the composer's editor bar. One
+ signature serves both the plain-text and the HTML part of a message, since
+ the HTML is rendered from the same markdown. `[compose] signature` seeds a
+ new message, `[account.<key>] signature` overrides it per account, and
+ `[compose] signature_position` puts a new one at the end of the message
+ (the default) or above the quoted text in a reply.
### Changed
diff --git a/README.md b/README.md
index ae51de5..5b10332 100644
--- a/README.md
+++ b/README.md
@@ -516,6 +516,41 @@ that window stops it and returns you to the composer with everything intact.
Nothing has reached the network until the countdown ends;
`[compose] send_delay_ms` sets how long it lasts, and 0 removes it.
+### Signatures
+
+Signatures are markdown files, one per signature, in
+`~/.config/qtmaildir/signatures/`:
+
+```
+~/.config/qtmaildir/signatures/
+├── work.md
+├── personal.md
+└── brief.md
+```
+
+The filename without its extension is the name shown in the composer. There
+is no editor for them inside qtmaildir: the directory is yours to manage with
+your own editor.
+
+Markdown, like the body of a message. `qtmaildir` builds the plain-text part
+of a message from what you typed and the HTML part by rendering the same
+text, so one signature serves both and you never choose a format.
+
+The composer's editor bar carries a **Signature** control listing every file
+plus *None*. Choosing one replaces whichever is already in the message, so
+switching is safe to do repeatedly.
+
+| Key | Default | Meaning |
+|---|---|---|
+| `[compose] signature` | none | The signature seeded on a new message, by name |
+| `[compose] signature_position` | `end` | `end`, or `above_quote` to put it before the quoted text in a reply |
+| `[account.<key>] signature` | none | Seeds this account's messages instead of the `[compose]` value |
+
+A signature is not tied to an account. `[account.<key>] signature` only
+chooses which one a message *starts* with; every signature stays reachable
+from the control whichever account you are sending from, and changing the
+From: account re-seeds it only until you pick one yourself.
+
## Tagging
Archive, delete, spam, mark-important and toggle-unread write fixed tags. For anything
diff --git a/docs/superpowers/plans/2026-08-03-post-0.1.0-usability-closed.md b/docs/superpowers/plans/2026-08-03-post-0.1.0-usability-closed.md
index 7314700..7a52984 100644
--- a/docs/superpowers/plans/2026-08-03-post-0.1.0-usability-closed.md
+++ b/docs/superpowers/plans/2026-08-03-post-0.1.0-usability-closed.md
@@ -7349,6 +7349,81 @@ importing the other.
---
+## 152. Signatures are not managed at all
+
+**Observed (user, 2026-08-24, from the notes):** listed under "some basic
+functionalities not brainstormed which didn't enter the first Send
+implementation", as:
+
+> signatures:
+> - not tied to an account, with a switch in the editor bar UI.
+
+**Specified 2026-08-24.** The design is in
+`docs/superpowers/specs/2026-08-24-signatures-design.md`. Read that rather
+than this section, which records only what the brainstorm settled and why.
+
+**The constraint is the shape of the item, and it survived a second key.**
+Not tied to an account rules out `[account.*] signature` as the whole answer.
+The user then asked for that key anyway, as a convenience, and it does not
+reopen the constraint: the account supplies a STARTING value, the editor-bar
+switch keeps every signature reachable under any account, and changing From:
+stops re-seeding the moment the user touches the switch. Seeding is not
+binding.
+
+**One choice must serve both forms, and that costs nothing.**
+`MessageBuilder` already derives `text/plain` from `markdownBody` verbatim and
+`text/html` from `MarkdownRenderer::toHtml()` over the same string
+(`messagebuilder.cpp:321-324`). A markdown signature in the buffer therefore
+gets both, correctly, with no change to `MessageBuilder` and no second code
+path. The user's "transparent to the user" requirement is a property the
+pipeline already has.
+
+A two-file variant (`work.md` plus an optional `work.html` overriding the
+rendered form) was chosen and then dropped by the user the same session: it
+buys designed HTML signatures at the cost of the signature no longer being
+visible in the editor, since the two parts diverge and the buffer can hold
+only one of them.
+
+**The switch is stateless, by using the delimiter rather than tracking a
+range.** `seedBody()` deliberately refuses to track "my text" and "the quote"
+as separate pieces (`composewindow.cpp:640-644`), and a signature switch is a
+toggle by definition, so it cannot duck that question the way the quote did.
+It answers it without state: the signature is the last `-- ` block not
+followed by quoted lines, found by scanning. Nothing to desync from the undo
+stack, and it survives editing above it.
+
+**`signature_position` covers both placements over one scan.** The user's own
+habit is `end`, which is the default; `above_quote` exists because other
+clients offer it. The scan needed the quote-aware clause for `above_quote`
+anyway, so the key is roughly ten lines rather than one, and a naive tail rule
+would have eaten the quote under the other placement.
+
+**A delimiter alone must not authorise a deletion.** The block after `-- ` is
+replaced only when its text matches one of the signatures on disk; otherwise
+the new one is inserted and nothing is removed. `-- ` can reach the buffer
+pasted in with quoted text from another client, and the unguarded scan would
+have silently deleted everything after it. The failure is now directional: a
+wrong guess adds a visible duplicate rather than losing the user's writing.
+Raised by the user against the first draft of this design.
+
+Two markers were considered for the same problem and refused. A zero-width
+character SHIPS in the sent message, fingerprinting the client in outgoing
+mail, and must survive the draft round trip through GMime, quoted-printable
+and `MimeParser`, which is exactly what normalises such characters away. A
+doubled delimiter (`--` plus two spaces) is not the RFC 3676 separator, so no
+receiving client would fold or strip the signature, and trailing whitespace is
+unreliable through the same pipeline.
+
+**Two things the design refuses.** No signature editor: the directory is
+edited with the user's own editor, and a text editor inside a mail client is
+not this project's to build. And a resumed draft seeds nothing, because the
+saved body already carries whatever signature it was written with, and
+seeding again would put a second one on a message written once.
+
+**Closed 2026-08-24** (unreleased). See the status table row for the outcome.
+
+---
+
## 153. A draft cannot be opened for editing, so it is write-only
**Observed (user, 2026-08-24).** Found the moment item 138 gave drafts a
@@ -7438,3 +7513,103 @@ bump either way: an ignored optional field is not a breaking change.
**Size: S.** Removing a field, two UI affordances and their tests.
**Closed 2026-08-24** (unreleased). See the status table row for the outcome.
+
+---
+
+## 158. A freshly saved draft is invisible until a sync indexes it
+
+**Observed (user, 2026-08-24, by hand).** Composing a new message or resuming
+a draft, then closing the composer, the draft cannot be found again in the
+Drafts view until a sync runs or the cron job fires. "Refresh the search"
+does not bring it back.
+
+**Cause (verified in the code).** Autosave writes the draft to the Maildir
+drafts folder and stops there: `saveDraftNow()` -> `DraftStore::write()` at
+`composewindow.cpp`, with no indexing step. The Drafts view is a notmuch
+query, `Config::allDraftsQuery()` -> `Account::draftsQuery()` ->
+`path:".../Drafts/**"`, and "refresh" re-runs that query against the existing
+index. Only `assets/mailsync.sh` runs `notmuch new`. So the file exists on
+disk and is invisible to the view.
+
+**Outcome.** `saveDraftNow()` emits `draftSaved(path, previousPath)`;
+`MainWindow::openComposer()` connects it to a new
+`NotmuchWorker::indexDraftFile()`, which indexes the one file the way
+`moveMessages()` does and removes the previous revision so a rewrite leaves no
+ghost. The send path unlinks a draft it had indexed while composing, so
+`draftRemoved(path)` -> `removeIndexedFile()` drops that entry.
+
+**Measured, and it makes the fix smaller than the item guessed.**
+`notmuch_database_index_file` assigns NO tags at all, unlike `notmuch new`,
+which would add `draft inbox unread` from `new.tags` and the `:2,D` flag. So
+the "strip whatever index_file assigns" concern is moot: a draft indexed this
+way cannot leak into a `tag:inbox` or `tag:unread` view, and no stripping is
+needed. The drafts view is path-based, so zero tags is exactly enough.
+
+**Size: S.** One worker slot, one signal, and their tests.
+
+**Closed 2026-08-24** (unreleased). See the status table row for the outcome.
+
+
+## 159. The Drafts view lists threads, so a draft is unreachable by double-click
+
+**Observed (user, 2026-08-25):** "drafts should be treated like \"Sent\",
+listing only actual draft messages and not threads, otherwise I can double
+click on a thread message and nothing happens."
+
+**Cause (verified in code):** `Config::builtinFilter()` in `src/config.cpp`
+sets `filter.flat = true` for the `sent` generator only, at line 1011. The
+`drafts` branch below it leaves the default `false` with a comment stating the
+choice explicitly: "NOT flat, like Trash and unlike Sent: a draft reply
+belongs with the conversation it answers." That was item 138's decision and it
+is the thing the note contradicts.
+
+The consequence the user reports follows from it. A thread row stands for
+`ThreadSummary::firstMessageId`, which in a Drafts view is the first MATCHED
+message of the conversation, and that is not necessarily the draft. Item 153
+gated `edit_draft` on the file living in a configured drafts folder precisely
+so that opening ordinary mail this way cannot make the first autosave delete a
+received message, so the row is inert rather than harmful. Inert is still
+"nothing happens".
+
+**Built 2026-08-25**, after confirming the reversal with the user.
+
+**Not one line, and the reason is the part worth keeping.** The obvious fix is
+`filter.flat = true` in the `drafts` branch. That ships a defect: the view mode
+was decided in THREE places that each hardcoded a comparison against `"sent"`,
+and they have to agree.
+
+- `builtinFilter()` sets it for the button.
+- `loadSavedQueries()` reapplies it on read, so a hand-edited or migrated file
+ cannot produce a threaded Sent view.
+- `saveSavedQueries()` SKIPS writing it when the generator already implies it,
+ because a key carrying no information is one a hand-editor must read past.
+
+Setting only the first does not break the save/load pair, and it is worth being
+exact about why: the writer's skip knew only about `sent`, so it would have
+STORED `"flat": true` for drafts, and the reader would have honoured it. That
+round trip survives by accident.
+
+What does NOT survive is a file that carries no `flat` key: one written by an
+older build, migrated from elsewhere, or hand-edited, which is the case the
+reader's fallback exists for. It comes back THREADED against a flat button, and
+the writer then persists that disagreement on the next save. The reader is the
+load-bearing site, and it is the one a per-branch fix leaves untouched.
+
+`generatorIsFlat()` is the fix: one closed set beside `generatorTag()`, called
+from all three sites. `builtinFilter()` sets `filter.flat` once from it rather
+than inside a branch, so the set cannot drift from the labels below it.
+
+**Trash deliberately did not follow.** A deleted message still belongs to its
+conversation, and nothing in the trash has to be reachable for editing. The
+test asserts this, so a future change that flattens every folder filter fails
+rather than passing quietly.
+
+**Testing.** `theDraftsFilterIsThreadedNotFlat` asserted the old behaviour and
+is inverted rather than deleted, keeping the history in its comment. The
+round-trip is covered by extending `aGeneratedEntryWritesNoRedundantKeys`,
+which already asserted exactly that property for `sent`, rather than by a
+second test that would have restated it. Mutation-checked: reverting
+`generatorIsFlat()` to `sent` alone fails both.
+
+Suite 37 of 38; the failure is `undoMovesTheMessageBack`, item 136,
+pre-existing and on an unrelated path.
diff --git a/docs/superpowers/plans/2026-08-03-post-0.1.0-usability.md b/docs/superpowers/plans/2026-08-03-post-0.1.0-usability.md
index 15f8654..4aeff26 100644
--- a/docs/superpowers/plans/2026-08-03-post-0.1.0-usability.md
+++ b/docs/superpowers/plans/2026-08-03-post-0.1.0-usability.md
@@ -205,7 +205,7 @@ taking that too literally.
| 133 | The composer shows no markdown syntax highlighting | v2 | S | open, 2026-08-20, from the item 123 brainstorm. **Blocked on 123.** A `QSyntaxHighlighter` over the composer's editor, so `**bold**` reads as bold while the buffer stays plain markdown. Standard Qt, no dependency. Deliberately after 123's formatting toolbar: agreeing with the grammar about nesting and about code spans suppressing what is inside them is the expensive part, and the toolbar is what makes the feature usable |
| 134 | The busy indicator is built inline and is about to be built twice | maintenance | S | done, 2026-08-20, af902e0. `BusyIndicator` (`src/busyindicator.h`) carries both modes: `MainWindow` uses the indeterminate one, and item 123's send popup takes the determinate half for its undo countdown, switching the same widget over when the command starts. Only the BAR was extracted, not the status label this row paired with it. `m_statusLabel` has 34 uses across `MainWindow` for transient messages, selection counts and sync phases, so it belongs to the window rather than to the indicator, and the send popup owns its own phase text |
| 135 | The formatting toolbar's buttons stack rather than toggle | v2 | S | open, 2026-08-21, asked for by the user during item 123 task 8 and reverted the same session. **A spec change, not a defect**: it conflicts with spec:236 ("deliberately no live toggle") and spec:187-190. Both sites need amending FIRST, and the amendment must resolve what replaces bold-then-italic, which is the gesture spec:187's preserved selection exists to serve and which a toggle makes unreachable. That question is the work; the state machine is understood and written up in the section |
-| 136 | `undoMovesTheMessageBack` fails when run ALONE, passes in the full suite | defect | ? | open, 2026-08-21, re-measured 2026-08-24 and it is not what the row said. Filed as an intermittent race (1 in 6); it is in fact **deterministic on the selection**: 6 failures in 6 when named on the command line, and, as of 2026-08-24, it fails in the FULL run too: measured at 58f13ad with the day's work stashed out, 274 passed and this one failed. The "passes in the suite" half of this row is therefore no longer true, and the selection-dependence it was named for may not be either. Re-measure before theorising. All three of its 15s `QTRY` timeouts expire, giving 45s against a 25s whole-suite run, so undo never moves the file rather than losing a race. A test that needs its predecessors is the likely shape (the `init()` lock-table fixture of item 61 is one candidate), which makes it a TEST defect until shown otherwise. Not caused by item 149 |
+| 136 | `undoMovesTheMessageBack` fails when run ALONE, passes in the full suite | defect | ? | open, 2026-08-21, re-measured 2026-08-24 and it is not what the row said. Filed as an intermittent race (1 in 6); it is in fact **deterministic on the selection**: 6 failures in 6 when named on the command line, and, as of 2026-08-24, it fails in the FULL run too: measured at 58f13ad with the day's work stashed out, 274 passed and this one failed. The "passes in the suite" half of this row is therefore no longer true, and the selection-dependence it was named for may not be either. Re-measure before theorising. All three of its 15s `QTRY` timeouts expire, giving 45s against a 25s whole-suite run, so undo never moves the file rather than losing a race. A test that needs its predecessors is the likely shape (the `init()` lock-table fixture of item 61 is one candidate), which makes it a TEST defect until shown otherwise. Not caused by item 149, and re-confirmed 2026-08-24 as not caused by item 152 either, by running the test at the preceding commit in a throwaway worktree. The assertion that fails names the real question: the restored file is in NEITHER `cur` nor `new` of the account inbox, so establish where it went before theorising about a race |
| 137 | A reply to a message that arrived at two accounts can come from the wrong one | defect | S | open, 2026-08-22, found while building item 123 task 12. `ComposeContextBuilder::accountForReply()` takes `messagePaths` PLURAL to disambiguate, and nothing upstream ever gives it more than one path, so the disambiguation is inert |
| 138 | No Drafts filter beside Sent and Trash | workflow | S | **done** 2026-08-24, unreleased. Smaller than sized: `Account::draftsQuery()` and `Config::allDraftsQuery()` already existed for the placeholder pane's count, so only the `kQueryGenerators` entry, the two `resolvedQuery` branches, the label and an icon were missing, and `builtinFilters()` derives the row from that set. Follows TRASH rather than Sent: folder-matched like both, but NOT flat, since a draft reply belongs with the conversation it answers. An account with no `drafts` key shows no button at all, per item 103's rule, which the existing row test surfaced by failing until its fixture configured one |
| 139 | Forward is reachable only from the Message menu | discoverability | XS | **done** 2026-08-24, unreleased, inside 140/141 as that entry said it would be. Forward is on the message pane's own bar with Compose and Reply |
@@ -221,13 +221,17 @@ taking that too literally.
| 149 | A reply's cursor lands on the attribution line, not on blank space | defect | XS | **done** 2026-08-24, unreleased, in TWO passes. The first fixed the cursor within each branch (`End` under Above, `Start` under Below) and the user still saw the old layout, because the branches were already right and the DEFAULT was wrong: `above` shipped, and the layout asked for is what `below` produces. Default flipped, and the composer now focuses the body whenever To: is already filled, which a Reply and a Forward always are. Both halves were invisible to the existing `theQuotePositionDecidesWhereTheQuoteLands`, which asserts the quote's position and never the cursor's |
| 150 | The receive-only ribbon stays up after the message that raised it is gone | defect | S | **done** 2026-08-24, unreleased. One line in `MessageView::clear()`, beside the blocked-content bar, the stale notice and the attachment bar it already reset by hand. Only `setReceiveOnlyAccount()` hid the ribbon, which every SELECTION change reaches, so a row-to-row move was never the reproducer: it survived the FOUR routes that blank the pane without one (`clear_pane`, `clear_selection`, a new query, a multi-row selection). The first test written for it passed against the defect for exactly that reason |
| 151 | The message-pane bars blend into the UI and carry no severity | presentation | S | **done** 2026-08-24, unreleased. Two severities as the user asked: yellow for a warning that only explains (the receive-only ribbon), blue for one offering an action (remote content blocked, stale thread), each with its own light and dark set read off `QPalette::Base` as `HtmlBuilder` does. The blocked row had to become a WIDGET first: it was a bare `QHBoxLayout`, which has nothing to paint a ground on, and its six `hide()` sites then had to move to the wrapper or a painted empty strip would show. Both action bars put the button right of a stretch |
-| 152 | Signatures are not managed at all | v2 | S | **specified** 2026-08-24, unbuilt. Design in `specs/2026-08-24-signatures-design.md`; read that, not this row. Sized `?` until the brainstorm; it is an S. One markdown file per signature under `~/.config/qtmaildir/signatures/`, spliced into the composer buffer, so `MessageBuilder` needs NO change at all: it already derives both parts from one string, which is the transparency the user asked for. The constraint holds, and the per-account key the user then asked for does not break it: an account SEEDS the choice, the editor-bar switch keeps every signature reachable |
+| 152 | Signatures are not managed at all | v2 | S | **done** 2026-08-24, unreleased. One markdown file per signature under `~/.config/qtmaildir/signatures/`, spliced into the composer buffer by the `Signatures` namespace and chosen from a `QToolButton` switch on the editor bar. `[compose] signature` seeds a new message, `[account.<key>] signature` overrides per account, `[compose] signature_position` picks end or above_quote. `MessageBuilder` is untouched: it already derives both parts from one string, the transparency the user asked for, and the per-account key does not break "not tied to an account", since an account SEEDS the choice while the switch keeps every signature reachable. A hand test caught one guard defect (a trailing newline defeated the replace guard); fixed and regression-tested |
| 153 | A draft cannot be opened for editing, so it is write-only | defect | M | **done** 2026-08-24, unreleased. `ComposeContextBuilder::forDraft()` reads a draft back into a context; a new `Kind::Draft` seeds the fields verbatim, takes the body with no quote framing, and carries `draftPath` so the autosave REPLACES the file instead of leaving a second copy. `MimeParser` gained `bcc`, which nothing read before: `MessageBuilder` writes Bcc into the draft deliberately, so a resumed draft that ignored it would silently drop every blind recipient. Reachable by double-click and by an `edit_draft` action, gated on the file being in a configured drafts folder because opening ordinary mail this way would make the first autosave DELETE a received message. Found a live defect on the way, see the section |
| 154 | No read confirmation | v2 | ? | open, 2026-08-24, from the notes. `Disposition-Notification-To`, which is a header `MessageBuilder` would add and a request the message pane would have to honour or ignore on the receiving side. Unspecified: whether this is send-side only, and what the reader is asked |
| 155 | No urgency switch on an outgoing message | v2 | S | open, 2026-08-24, from the notes: low, regular, high. `X-Priority` and `Importance`, headers `MessageBuilder` adds; regular writes neither. A control in the composer, and the same question item 144 answered for the HTML toggle applies to where it sits |
| 156 | No delivery confirmation | v2 | ? | open, 2026-08-24, from the notes. Distinct from 154: this is a DSN (`Return-Receipt-To`, or the ESMTP NOTIFY parameter), which is the sending server's to honour rather than the reader's client. Whether it can be requested at all depends on the `send_command`, so this may not be this application's to offer |
| 157 | A draft on display offers Reply and Forward, not Edit | workflow | XS | **done** 2026-08-24, unreleased, and the half item 153 did not close. `populateMessageBar()` swaps the reply pair for `edit_draft`, refilled from `updateComposeActions()` so it follows the message. **Took three hand-test rounds, each finding a defect the tests could not see.** First version shipped item 150's trap one level up: it keyed on `currentIndex()`, which a query leaves VALID on a row of the discarded result, so the bar kept the draft button after clicking Inbox and the reply pair after clicking Drafts. It answers from `m_currentMessageId`/`m_currentThreadId` now, which every blanking route clears, refilled from `showPlaceholderPane()` — the one site all five of those routes share. That exposed a THIRD defect nobody had reported and which predates the bar: enablement ran only from the two selection handlers, so Reply and Forward stayed **enabled over a blank pane**, invisible while they sat on the main toolbar among always-on actions. The bar is then HIDDEN over an empty pane (`!m_items.isEmpty()` in `MessageView::setBarActions`): the user first chose a greyed-out bar, then reversed it on sight for a better reason, that the subject and details button already vanish and a persisting bar was the only piece of header furniture that did not. **The hiding half broke the showing half**, found by hand again: `setBarActions` is called from `updateComposeActions()`, which runs BEFORE `showThread()` fills `m_items`, so the first message opened after any blanking left the bar hidden and the second showed it, reading `m_items` still holding the first — one selection behind for the life of the view. `updateHeader()` shows it, beside the details button it rides with. The test missed it by asserting before the render landed, measuring the placeholder; it waits on `showingPlaceholder()` now. Several guards and `hide()` calls were written across the three rounds and then measured dead, and removed |
+| 158 | A freshly saved draft is invisible until a sync indexes it | defect | S | **done** 2026-08-24, unreleased. `saveDraftNow()` emits `draftSaved`, which `MainWindow` connects to a new `NotmuchWorker::indexDraftFile()` that indexes the one file (previous revision removed, so a rewrite leaves no ghost), and `draftRemoved` drops the entry when a sent draft is unlinked. Measured: `index_file` assigns NO tags, so no stripping and no tag:inbox leak. See the section |
+
+| 159 | The Drafts view lists threads, so a draft is unreachable by double-click | defect | S | **done** 2026-08-25, unreleased. Reverses item 138's own decision, confirmed with the user. `generatorIsFlat()` in `config.cpp` is now the single closed set of flat generators, replacing three hardcoded comparisons against `"sent"`: the built-in filter, the reader that reapplies the mode, and the writer that skips storing what the generator implies. Those three had to agree and nothing made them; a `drafts` entry saved and reloaded would otherwise have come back THREADED while the button was flat. `builtinFilter()` sets `flat` once from the helper rather than in a branch, so the set cannot drift from the labels |
+
Sizes are rough: XS under an hour, S a sitting, M a session.
---
@@ -1305,75 +1309,27 @@ converts a real race into a slower green. If the race turns out to be in the
production move rather than the test, this stops being a test-hygiene item and
becomes a mail-safety one.
----
+**Measured again 2026-08-24, and the failure is now DETERMINISTIC.** Found
+incidentally while building item 152, by an agent that checked rather than
+assumed: it built a throwaway worktree at the commit before its own work and
+ran `test_mainwindow` there, failing identically. So the failure predates the
+signatures work, and the "1 run in 6" framing in this entry's own title is
+stale twice over.
+
+The assertion that fails, quoted exactly:
+
+```
+'folderHasMessageFile(root + "/acct/inbox/cur", stem) || folderHasMessageFile(root + "/acct/inbox/new", stem)' returned FALSE
+```
-## 152. Signatures are not managed at all
-
-**Observed (user, 2026-08-24, from the notes):** listed under "some basic
-functionalities not brainstormed which didn't enter the first Send
-implementation", as:
-
-> signatures:
-> - not tied to an account, with a switch in the editor bar UI.
-
-**Specified 2026-08-24.** The design is in
-`docs/superpowers/specs/2026-08-24-signatures-design.md`. Read that rather
-than this section, which records only what the brainstorm settled and why.
-
-**The constraint is the shape of the item, and it survived a second key.**
-Not tied to an account rules out `[account.*] signature` as the whole answer.
-The user then asked for that key anyway, as a convenience, and it does not
-reopen the constraint: the account supplies a STARTING value, the editor-bar
-switch keeps every signature reachable under any account, and changing From:
-stops re-seeding the moment the user touches the switch. Seeding is not
-binding.
-
-**One choice must serve both forms, and that costs nothing.**
-`MessageBuilder` already derives `text/plain` from `markdownBody` verbatim and
-`text/html` from `MarkdownRenderer::toHtml()` over the same string
-(`messagebuilder.cpp:321-324`). A markdown signature in the buffer therefore
-gets both, correctly, with no change to `MessageBuilder` and no second code
-path. The user's "transparent to the user" requirement is a property the
-pipeline already has.
-
-A two-file variant (`work.md` plus an optional `work.html` overriding the
-rendered form) was chosen and then dropped by the user the same session: it
-buys designed HTML signatures at the cost of the signature no longer being
-visible in the editor, since the two parts diverge and the buffer can hold
-only one of them.
-
-**The switch is stateless, by using the delimiter rather than tracking a
-range.** `seedBody()` deliberately refuses to track "my text" and "the quote"
-as separate pieces (`composewindow.cpp:640-644`), and a signature switch is a
-toggle by definition, so it cannot duck that question the way the quote did.
-It answers it without state: the signature is the last `-- ` block not
-followed by quoted lines, found by scanning. Nothing to desync from the undo
-stack, and it survives editing above it.
-
-**`signature_position` covers both placements over one scan.** The user's own
-habit is `end`, which is the default; `above_quote` exists because other
-clients offer it. The scan needed the quote-aware clause for `above_quote`
-anyway, so the key is roughly ten lines rather than one, and a naive tail rule
-would have eaten the quote under the other placement.
-
-**A delimiter alone must not authorise a deletion.** The block after `-- ` is
-replaced only when its text matches one of the signatures on disk; otherwise
-the new one is inserted and nothing is removed. `-- ` can reach the buffer
-pasted in with quoted text from another client, and the unguarded scan would
-have silently deleted everything after it. The failure is now directional: a
-wrong guess adds a visible duplicate rather than losing the user's writing.
-Raised by the user against the first draft of this design.
-
-Two markers were considered for the same problem and refused. A zero-width
-character SHIPS in the sent message, fingerprinting the client in outgoing
-mail, and must survive the draft round trip through GMime, quoted-printable
-and `MimeParser`, which is exactly what normalises such characters away. A
-doubled delimiter (`--` plus two spaces) is not the RFC 3676 separator, so no
-receiving client would fold or strip the signature, and trailing whitespace is
-unreliable through the same pipeline.
-
-**Two things the design refuses.** No signature editor: the directory is
-edited with the user's own editor, and a text editor inside a mail client is
-not this project's to build. And a resumed draft seeds nothing, because the
-saved body already carries whatever signature it was written with, and
-seeding again would put a second one on a message written once.
+That is worth more than the flakiness history, because it says WHAT is wrong
+rather than how often: after the undo, the message file is in neither `cur`
+nor `new` of the account's inbox. The file is not where the restore was
+supposed to put it, so the question this item has to answer narrows to where
+it went instead. Check the trash folder and the account root before
+theorising about a race: a move landing in the wrong folder is the mail-safety
+half of the fork above, and it would look exactly like this.
+
+The 70-second duration recorded above fits a `QTRY_*` waiting for a file that
+is never going to appear, which is consistent with a wrong destination rather
+than a slow one.
diff --git a/docs/superpowers/plans/2026-08-24-signatures.md b/docs/superpowers/plans/2026-08-24-signatures.md
index 93026fc..0d13639 100644
--- a/docs/superpowers/plans/2026-08-24-signatures.md
+++ b/docs/superpowers/plans/2026-08-24-signatures.md
@@ -149,10 +149,10 @@ void TestSignatures::textIsTheFileContent()
QTemporaryDir dir;
QVERIFY(dir.isValid());
write(dir, { { QStringLiteral("work.md"),
- QStringLiteral("Danilo\n**qtmaildir**\n") } });
+ QStringLiteral("Jane Doe\n**qtmaildir**\n") } });
QCOMPARE(Signatures::text(dir.path(), QStringLiteral("work")),
- QStringLiteral("Danilo\n**qtmaildir**\n"));
+ QStringLiteral("Jane Doe\n**qtmaildir**\n"));
}
void TestSignatures::textOfAnUnknownNameIsEmpty()
@@ -396,9 +396,9 @@ void TestSignatures::insertingAtTheEndAppendsAfterADelimiter()
const QString buffer = QStringLiteral("Hello.\n");
const QString result = Signatures::replace(
- buffer, QStringLiteral("Danilo"), {}, Signatures::Position::End);
+ buffer, QStringLiteral("Jane Doe"), {}, Signatures::Position::End);
- QCOMPARE(result, QStringLiteral("Hello.\n\n-- \nDanilo"));
+ QCOMPARE(result, QStringLiteral("Hello.\n\n-- \nJane Doe"));
}
void TestSignatures::insertingAboveTheQuotePutsItBeforeTheFirstQuotedLine()
@@ -411,7 +411,7 @@ void TestSignatures::insertingAboveTheQuotePutsItBeforeTheFirstQuotedLine()
"> second line\n");
const QString result = Signatures::replace(
- buffer, QStringLiteral("Danilo"), {},
+ buffer, QStringLiteral("Jane Doe"), {},
Signatures::Position::AboveQuote);
// Before the QUOTED lines, and the attribution stays with the quote it
@@ -420,7 +420,7 @@ void TestSignatures::insertingAboveTheQuotePutsItBeforeTheFirstQuotedLine()
"My reply.\n"
"\n"
"-- \n"
- "Danilo\n"
+ "Jane Doe\n"
"\n"
"On Mon, someone wrote:\n"
"> the original\n"
@@ -432,10 +432,10 @@ void TestSignatures::insertingAboveTheQuoteWithNoQuoteIsTheSameAsEnd()
const QString buffer = QStringLiteral("A new message.\n");
const QString above = Signatures::replace(
- buffer, QStringLiteral("Danilo"), {},
+ buffer, QStringLiteral("Jane Doe"), {},
Signatures::Position::AboveQuote);
const QString end = Signatures::replace(
- buffer, QStringLiteral("Danilo"), {}, Signatures::Position::End);
+ buffer, QStringLiteral("Jane Doe"), {}, Signatures::Position::End);
QCOMPARE(above, end);
}
@@ -586,27 +586,27 @@ Add the implementations:
```cpp
void TestSignatures::switchingReplacesAKnownSignature()
{
- const QStringList known = { QStringLiteral("Danilo"),
- QStringLiteral("Danilo M.\nqtmaildir") };
- const QString buffer = QStringLiteral("Hello.\n\n-- \nDanilo");
+ const QStringList known = { QStringLiteral("Jane Doe"),
+ QStringLiteral("Jane Doe\nqtmaildir") };
+ const QString buffer = QStringLiteral("Hello.\n\n-- \nJane Doe");
const QString result = Signatures::replace(
- buffer, QStringLiteral("Danilo M.\nqtmaildir"), known,
+ buffer, QStringLiteral("Jane Doe\nqtmaildir"), known,
Signatures::Position::End);
QCOMPARE(result,
- QStringLiteral("Hello.\n\n-- \nDanilo M.\nqtmaildir"));
+ QStringLiteral("Hello.\n\n-- \nJane Doe\nqtmaildir"));
}
void TestSignatures::switchingReplacesAKnownSignatureAboveAQuote()
{
- const QStringList known = { QStringLiteral("Danilo"),
+ const QStringList known = { QStringLiteral("Jane Doe"),
QStringLiteral("Brief") };
const QString buffer = QStringLiteral(
"My reply.\n"
"\n"
"-- \n"
- "Danilo\n"
+ "Jane Doe\n"
"\n"
"On Mon, someone wrote:\n"
"> the original\n");
@@ -627,8 +627,8 @@ void TestSignatures::switchingReplacesAKnownSignatureAboveAQuote()
void TestSignatures::selectingNoneRemovesAKnownSignature()
{
- const QStringList known = { QStringLiteral("Danilo") };
- const QString buffer = QStringLiteral("Hello.\n\n-- \nDanilo");
+ const QStringList known = { QStringLiteral("Jane Doe") };
+ const QString buffer = QStringLiteral("Hello.\n\n-- \nJane Doe");
const QString result = Signatures::replace(
buffer, QString(), known, Signatures::Position::End);
@@ -642,7 +642,7 @@ void TestSignatures::aBlockMatchingNoKnownSignatureIsNotRemoved()
// reaches a buffer without the user ever choosing a signature, pasted in
// with quoted text from another client. Replacing from there would delete
// everything after it silently.
- const QStringList known = { QStringLiteral("Danilo") };
+ const QStringList known = { QStringLiteral("Jane Doe") };
const QString buffer = QStringLiteral(
"Hello.\n"
"\n"
@@ -650,13 +650,13 @@ void TestSignatures::aBlockMatchingNoKnownSignatureIsNotRemoved()
"text the user pasted and wants to keep");
const QString result = Signatures::replace(
- buffer, QStringLiteral("Danilo"), known, Signatures::Position::End);
+ buffer, QStringLiteral("Jane Doe"), known, Signatures::Position::End);
// The user's text survives, and the signature is ADDED. A wrong guess
// produces a visible duplicate, never a deletion.
QVERIFY(result.contains(
QStringLiteral("text the user pasted and wants to keep")));
- QVERIFY(result.endsWith(QStringLiteral("-- \nDanilo")));
+ QVERIFY(result.endsWith(QStringLiteral("-- \nJane Doe")));
}
void TestSignatures::aDelimiterInsideTheQuoteIsNotTheSignature()
@@ -664,7 +664,7 @@ void TestSignatures::aDelimiterInsideTheQuoteIsNotTheSignature()
// The quoted original carries the sender's own signature, quoted. A tail
// rule would find it, and under End it would append after it; the block
// must not be treated as this message's signature whichever way it goes.
- const QStringList known = { QStringLiteral("Danilo") };
+ const QStringList known = { QStringLiteral("Jane Doe") };
const QString buffer = QStringLiteral(
"My reply.\n"
"\n"
@@ -674,10 +674,10 @@ void TestSignatures::aDelimiterInsideTheQuoteIsNotTheSignature()
"> Their Name\n");
const QString result = Signatures::replace(
- buffer, QStringLiteral("Danilo"), known, Signatures::Position::End);
+ buffer, QStringLiteral("Jane Doe"), known, Signatures::Position::End);
QVERIFY(result.contains(QStringLiteral("> -- \n> Their Name")));
- QVERIFY(result.endsWith(QStringLiteral("-- \nDanilo")));
+ QVERIFY(result.endsWith(QStringLiteral("-- \nJane Doe")));
}
```
@@ -1157,7 +1157,7 @@ Config TestComposeWindow::makeConfig(
void TestComposeWindow::aNewMessageSeedsTheComposeSignature()
{
const Config config = makeConfig(
- { { QStringLiteral("work.md"), QStringLiteral("Danilo") } },
+ { { QStringLiteral("work.md"), QStringLiteral("Jane Doe") } },
QStringLiteral("work"));
ComposeContext context;
@@ -1170,7 +1170,7 @@ void TestComposeWindow::aNewMessageSeedsTheComposeSignature()
auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
QVERIFY(body);
- QVERIFY(body->toPlainText().endsWith(QStringLiteral("-- \nDanilo")));
+ QVERIFY(body->toPlainText().endsWith(QStringLiteral("-- \nJane Doe")));
}
void TestComposeWindow::anAccountSignatureOverridesTheComposeOne()
@@ -1196,7 +1196,7 @@ void TestComposeWindow::anAccountSignatureOverridesTheComposeOne()
void TestComposeWindow::aResumedDraftSeedsNoSignature()
{
const Config config = makeConfig(
- { { QStringLiteral("work.md"), QStringLiteral("Danilo") } },
+ { { QStringLiteral("work.md"), QStringLiteral("Jane Doe") } },
QStringLiteral("work"));
// The saved body already carries whatever signature it was written with.
@@ -1204,7 +1204,7 @@ void TestComposeWindow::aResumedDraftSeedsNoSignature()
ComposeContext context;
context.kind = ComposeContext::Kind::Draft;
context.accountKey = QStringLiteral("work");
- context.body = QStringLiteral("Half a thought.\n\n-- \nDanilo");
+ context.body = QStringLiteral("Half a thought.\n\n-- \nJane Doe");
context.draftPath = m_dir->path() + QStringLiteral("/draft");
ComposeWindow window(context, config, m_dir->path());
@@ -1213,13 +1213,13 @@ void TestComposeWindow::aResumedDraftSeedsNoSignature()
auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
QVERIFY(body);
- QCOMPARE(body->toPlainText().count(QStringLiteral("-- \nDanilo")), 1);
+ QCOMPARE(body->toPlainText().count(QStringLiteral("-- \nJane Doe")), 1);
}
void TestComposeWindow::anUnknownSignatureNameSeedsNothing()
{
const Config config = makeConfig(
- { { QStringLiteral("work.md"), QStringLiteral("Danilo") } },
+ { { QStringLiteral("work.md"), QStringLiteral("Jane Doe") } },
QStringLiteral("absent"));
ComposeContext context;
@@ -1239,7 +1239,7 @@ void TestComposeWindow::anUnknownSignatureNameSeedsNothing()
void TestComposeWindow::theSwitchListsEveryFileAndNone()
{
const Config config = makeConfig(
- { { QStringLiteral("work.md"), QStringLiteral("Danilo") },
+ { { QStringLiteral("work.md"), QStringLiteral("Jane Doe") },
{ QStringLiteral("brief.md"), QStringLiteral("Brief") } },
QString());
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 2cebfef..700b185 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -37,6 +37,7 @@ add_library(qtmaildir_lib STATIC
querycompleter.cpp
rulequery.cpp
searchterm.cpp
+ signatures.cpp
)
target_include_directories(qtmaildir_lib
diff --git a/src/composewindow.cpp b/src/composewindow.cpp
index a64736f..c35bb5d 100644
--- a/src/composewindow.cpp
+++ b/src/composewindow.cpp
@@ -25,6 +25,7 @@
#include "mimeparser.h"
#include "messagesender.h"
#include "senddialog.h"
+#include "signatures.h"
#include <QAction>
#include <QCheckBox>
@@ -40,9 +41,11 @@
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
+#include <QMenu>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
+#include <QStandardPaths>
#include <QTextCursor>
#include <QTimer>
#include <QToolBar>
@@ -128,6 +131,7 @@ ComposeWindow::ComposeWindow(const ComposeContext &context,
buildFormatToolbar();
seedFields();
seedBody();
+ seedSignature();
// AFTER buildUi(), which creates m_banner, and BEFORE
// refreshAttachmentList(), which renders m_attachments: extraction appends
@@ -402,8 +406,22 @@ void ComposeWindow::buildUi()
for (QLineEdit *field : { m_to, m_cc, m_bcc, m_subject })
connect(field, &QLineEdit::textChanged, this, &ComposeWindow::markDirty);
connect(m_sendHtml, &QCheckBox::toggled, this, &ComposeWindow::markDirty);
- connect(m_from, &QComboBox::currentIndexChanged, this,
- &ComposeWindow::markDirty);
+ connect(m_from, &QComboBox::currentIndexChanged, this, [this]() {
+ markDirty();
+ // The account SEEDS the signature, so a change to it re-seeds. It
+ // stops the moment the user picks one: re-seeding unconditionally is
+ // the one behaviour that can silently discard a deliberate choice
+ // made a moment earlier. Same shape as send_html, which seeds from
+ // context and is then left alone.
+ if (m_signatureChosen)
+ return;
+ const QString seeded = seededSignatureName();
+ if (!Signatures::names(m_signatureDir).contains(seeded)) {
+ applySignature(QString());
+ return;
+ }
+ applySignature(seeded);
+ });
}
void ComposeWindow::buildFormatToolbar()
@@ -536,6 +554,29 @@ void ComposeWindow::buildFormatToolbar()
m_sendHtml->setIcon(htmlIcon);
m_formatToolbar->addWidget(m_sendHtml);
+ // The signature switch rides at the right end with Attach and the HTML
+ // toggle: item 142 put the controls OF THE EDITOR on this side, as against
+ // the formatting buttons on the left, and choosing a signature is one of
+ // those.
+ //
+ // A QToolButton with a menu rather than a QComboBox, matching the bar's
+ // other controls; a combo would read as a different class of thing. Not
+ // registered in KeyMap: it is parented to this window, exactly as the
+ // formatting actions are, so its scope is the composer and item 132's
+ // reachability rule does not apply.
+ m_signatureSwitch = new QToolButton(m_formatToolbar);
+ m_signatureSwitch->setObjectName(QStringLiteral("signatureSwitch"));
+ m_signatureSwitch->setText(tr("Signature"));
+ m_signatureSwitch->setToolTip(
+ tr("Chooses the signature added to this message."));
+ m_signatureSwitch->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
+ m_signatureSwitch->setPopupMode(QToolButton::InstantPopup);
+ const QIcon signatureIcon = QIcon::fromTheme(QStringLiteral("insert-text"));
+ if (!signatureIcon.isNull())
+ m_signatureSwitch->setIcon(signatureIcon);
+ m_signatureSwitch->setMenu(new QMenu(m_signatureSwitch));
+ m_formatToolbar->addWidget(m_signatureSwitch);
+
// Send is NOT on this row: it is the terminal action, and it lives on the
// button beside the headers. The QAction survives because it carries the
// shortcut and is what the button triggers.
@@ -664,6 +705,122 @@ void ComposeWindow::seedBody()
m_body->document()->clearUndoRedoStacks();
}
+void ComposeWindow::setSignatureDir(const QString &dir)
+{
+ m_signatureDir = dir;
+}
+
+QStringList ComposeWindow::knownSignatures() const
+{
+ QStringList known;
+ const QStringList names = Signatures::names(m_signatureDir);
+ known.reserve(names.size());
+ for (const QString &name : names)
+ known.append(Signatures::text(m_signatureDir, name));
+ return known;
+}
+
+QString ComposeWindow::seededSignatureName() const
+{
+ // The COMBO, not m_context: the context records where the composer opened
+ // and does not follow a From: change, so reading it would seed the
+ // original account's signature for ever.
+ const QString key = m_from->currentData().toString();
+ const Account account =
+ m_config.account(key.isEmpty() ? m_context.accountKey : key);
+ if (!account.signature.isEmpty())
+ return account.signature;
+ return m_config.compose().signature;
+}
+
+void ComposeWindow::applySignature(const QString &name)
+{
+ const QString text =
+ name.isEmpty() ? QString() : Signatures::text(m_signatureDir, name);
+
+ // A QTextCursor replacement rather than setPlainText(), for the reason
+ // recorded at applyEdit(): setPlainText() destroys the document's undo
+ // stack, so a switch would make everything typed before it unrecoverable.
+ const QString replaced = Signatures::replace(
+ m_body->toPlainText(), text, knownSignatures(),
+ m_config.compose().signaturePosition);
+
+ QTextCursor cursor(m_body->document());
+ cursor.select(QTextCursor::Document);
+ cursor.insertText(replaced);
+
+ m_signatureName = name;
+
+ for (QAction *action : m_signatureSwitch->menu()->actions())
+ action->setChecked(action->data().toString() == name);
+}
+
+void ComposeWindow::seedSignature()
+{
+ if (m_signatureDir.isEmpty()) {
+ const QString base =
+ QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
+ m_signatureDir = base + QStringLiteral("/qtmaildir/signatures");
+ }
+
+ QMenu *menu = m_signatureSwitch->menu();
+ menu->clear();
+
+ auto *none = menu->addAction(tr("None"));
+ none->setCheckable(true);
+ none->setData(QString());
+ connect(none, &QAction::triggered, this, [this]() {
+ m_signatureChosen = true;
+ applySignature(QString());
+ markDirty();
+ });
+
+ const QStringList names = Signatures::names(m_signatureDir);
+ for (const QString &name : names) {
+ auto *action = menu->addAction(name);
+ action->setCheckable(true);
+ action->setData(name);
+ connect(action, &QAction::triggered, this, [this, name]() {
+ m_signatureChosen = true;
+ applySignature(name);
+ markDirty();
+ });
+ }
+
+ // A resumed draft is the message ITSELF and already carries whatever
+ // signature it was saved with, exactly as seedBody() takes its body
+ // verbatim. Seeding again would append a second one.
+ if (m_context.kind == ComposeContext::Kind::Draft) {
+ none->setChecked(true);
+ // The draft IS the user's choice: its signature is deliberate prior
+ // state, so a From: change must not follow the new account and
+ // rewrite what was saved. Marking it chosen keeps the same invariant
+ // the switch actions set, without ever having run the switch.
+ m_signatureChosen = true;
+ return;
+ }
+
+ const QString seeded = seededSignatureName();
+ if (seeded.isEmpty()) {
+ none->setChecked(true);
+ return;
+ }
+ if (!names.contains(seeded)) {
+ // Reported by Config as a problem; the composer still opens, with no
+ // signature, and the switch still works.
+ none->setChecked(true);
+ return;
+ }
+
+ applySignature(seeded);
+
+ // The seeded signature is not an edit the user made, so it must not
+ // survive as an undo step: one Ctrl+Z on a fresh composer would otherwise
+ // wipe content they never typed. Same reason seedBody() clears after the
+ // quote.
+ m_body->document()->clearUndoRedoStacks();
+}
+
void ComposeWindow::refreshAttachmentList()
{
m_attachmentList->clear();
@@ -861,6 +1018,7 @@ bool ComposeWindow::saveDraftNow()
const QString folder = QDir(m_mailRoot).absoluteFilePath(
account.maildir + QLatin1Char('/') + account.drafts);
+ const QString previousPath = m_draftPath;
const DraftStore::Result written =
DraftStore::write(folder, built.bytes, QStringLiteral("D"), m_draftPath);
@@ -881,6 +1039,10 @@ bool ComposeWindow::saveDraftNow()
m_dirty = false;
m_saveFailed = false;
m_banner->hide();
+
+ // The write is done and the previous revision already unlinked; hand both
+ // paths up so the owner indexes the new one and drops the old (item 158).
+ emit draftSaved(written.path, previousPath);
return true;
}
@@ -897,6 +1059,7 @@ void ComposeWindow::setInputsEnabled(bool enabled)
m_from->setEnabled(enabled);
m_body->setReadOnly(!enabled);
m_sendHtml->setEnabled(enabled);
+ m_signatureSwitch->setEnabled(enabled);
m_attachmentList->setEnabled(enabled);
m_formatToolbar->setEnabled(enabled);
@@ -1042,6 +1205,7 @@ void ComposeWindow::send()
dialog->setStage(SendDialog::Stage::RemovingDraft);
if (!m_draftPath.isEmpty()) {
QFile::remove(m_draftPath);
+ emit draftRemoved(m_draftPath);
m_draftPath.clear();
}
diff --git a/src/composewindow.h b/src/composewindow.h
index c44fcda..caff011 100644
--- a/src/composewindow.h
+++ b/src/composewindow.h
@@ -96,6 +96,21 @@ public:
/// and quitting therefore loses that text.
bool lastSaveFailed() const { return m_saveFailed; }
+ /// Where the signature files live. Defaults to
+ /// <config>/qtmaildir/signatures; a test points it at its own directory.
+ ///
+ /// A setter rather than a config key: nothing yet suggests the user wants
+ /// a second location, and the tests need to not read the real one.
+ void setSignatureDir(const QString &dir);
+
+ /// Seeds the signature from config and fills the switch.
+ ///
+ /// Public and called by the constructor rather than private, so a test can
+ /// drive it after pointing setSignatureDir() somewhere safe. A resumed
+ /// draft seeds nothing: its body already carries the signature it was
+ /// written with.
+ void seedSignature();
+
/// Writes the current buffer to the drafts folder now. Returns false and
/// leaves the banner up on failure.
///
@@ -153,6 +168,17 @@ signals:
/// pointer before WA_DeleteOnClose destroys the window.
void closed(ComposeWindow *window);
+ /// A draft was written to disk, so the window's owner can index it and it
+ /// appears in the Drafts view without a full sync (item 158).
+ ///
+ /// \p path is the file just written, absolute. \p previousPath is the file
+ /// the write replaced, empty on the first save of a new draft.
+ void draftSaved(const QString &path, const QString &previousPath);
+
+ /// A draft file was unlinked (sent), so its index entry must go too.
+ /// \p path is the file that was removed, absolute.
+ void draftRemoved(const QString &path);
+
protected:
/// The one place the registry is told, whichever route closes the window.
void closeEvent(QCloseEvent *event) override;
@@ -176,6 +202,16 @@ private:
/// a silently wrong send is not among the outcomes.
void extractForwardedAttachments();
void seedBody();
+
+ /// Applies \p name to the buffer, replacing whatever is there.
+ void applySignature(const QString &name);
+
+ /// The text of every signature on disk, for replace()'s guard.
+ QStringList knownSignatures() const;
+
+ /// The signature name this account seeds, falling through to [compose].
+ QString seededSignatureName() const;
+
void refreshAttachmentList();
void setInputsEnabled(bool enabled);
void showSendFailure(const QString &stderrText);
@@ -227,6 +263,14 @@ private:
QComboBox *m_from = nullptr;
QPlainTextEdit *m_body = nullptr;
QToolButton *m_sendHtml = nullptr;
+ QToolButton *m_signatureSwitch = nullptr;
+ QString m_signatureDir;
+ QString m_signatureName; ///< The selected signature, empty for None.
+
+ /// True once the user has used the switch. From then on a From: change
+ /// stops re-seeding, so a deliberate choice is never overwritten. Matches
+ /// how send_html seeds from context and is then left alone.
+ bool m_signatureChosen = false;
QLabel *m_banner = nullptr;
QListWidget *m_attachmentList = nullptr;
QWidget *m_sendLogPane = nullptr;
diff --git a/src/config.cpp b/src/config.cpp
index 23c7364..d91259a 100644
--- a/src/config.cpp
+++ b/src/config.cpp
@@ -80,6 +80,18 @@ QString generatorTag(const QString &generator)
return QString();
}
+/// Whether a generator lists MESSAGES rather than threads. "sent" folds a
+/// user's own message back into the conversation it answers, and "drafts" is
+/// worse: a thread row stands for its first matched message, which for a draft
+/// reply is the message being replied TO, so the draft itself is unreachable.
+/// "trash" stays threaded, since a deleted message still belongs to its
+/// conversation. Closed set, and the one place the three views are decided.
+bool generatorIsFlat(const QString &generator)
+{
+ return generator == QStringLiteral("sent")
+ || generator == QStringLiteral("drafts");
+}
+
} // namespace
QString Account::scopedQuery(const QString &query) const
@@ -459,6 +471,17 @@ void Config::load(const QString &path)
account.sent =
settings.value(QStringLiteral("sent")).toString().trimmed();
+ // Optional, and a STARTING value rather than a binding: the composer's
+ // switch keeps every signature reachable whichever account is
+ // selected. Left empty when absent, so the composer can tell "this
+ // account says nothing" from "this account says none" and fall through
+ // to [compose] signature itself; resolving that here would collapse
+ // the two. Trimmed for the same reason as sent, above: a trailing
+ // space would be carried into a filename lookup and match nothing,
+ // which is invisible in a config file.
+ account.signature =
+ settings.value(QStringLiteral("signature")).toString().trimmed();
+
// Mandatory, unlike sent: Delete moves a file into this folder, so an
// account without one cannot delete at all. Trimmed for the same
// reason as sent, above.
@@ -547,6 +570,31 @@ void Config::load(const QString &path)
m_compose.sendHtml =
settings.value(QStringLiteral("send_html"), true).toBool();
+ // Trimmed for the same reason the account key is: it reaches a filename
+ // lookup, where a trailing space matches nothing invisibly.
+ m_compose.signature =
+ settings.value(QStringLiteral("signature")).toString().trimmed();
+
+ // The same shape as quote_position directly above: an absent key is
+ // silent and the struct default holds, but a PRESENT and malformed value
+ // is reported rather than silently accepted. value(key, default) alone
+ // would read "signature_position = abov" as above_quote.
+ const QString signaturePosition =
+ settings.value(QStringLiteral("signature_position"),
+ QStringLiteral("end"))
+ .toString().trimmed();
+ if (signaturePosition.compare(QStringLiteral("above_quote"),
+ Qt::CaseInsensitive) == 0) {
+ m_compose.signaturePosition = Signatures::Position::AboveQuote;
+ } else if (signaturePosition.compare(QStringLiteral("end"),
+ Qt::CaseInsensitive) == 0) {
+ m_compose.signaturePosition = Signatures::Position::End;
+ } else {
+ addProblem(tr("[compose] signature_position '%1' is not recognised; "
+ "expected end or above_quote. Using end.")
+ .arg(signaturePosition));
+ }
+
// Three numerics, all following the shape already established at
// message_zoom, toolbar_icon_size, mark_read_delay_ms and
// auto_sync_delay_ms elsewhere in this function: a QVariant, a checked
@@ -802,14 +850,14 @@ void Config::loadSavedQueries(const QString &configPath, QSettings &settings)
query.query = object.value(QStringLiteral("query")).toString();
query.account = object.value(QStringLiteral("account")).toString();
query.generated = object.value(QStringLiteral("generated")).toString();
- // A generator carries its own view mode, so "sent" is flat whether or
- // not the file says so. Storing it as a plain field would let a
+ // A generator carries its own view mode, so a flat one is flat whether
+ // or not the file says so. Storing it as a plain field would let a
// hand-edited or migrated-from-elsewhere row produce a THREADED sent
// view, which folds every reply back into the conversation the user
// sent one message into. The file may still set it for an ordinary
// query.
query.flat = object.value(QStringLiteral("flat")).toBool(false)
- || query.generated == QStringLiteral("sent");
+ || generatorIsFlat(query.generated);
if (query.isGenerated()
&& !kQueryGenerators.contains(query.generated)) {
@@ -869,7 +917,7 @@ bool Config::saveSavedQueries() const
object.insert(QStringLiteral("account"), query.account);
// Skipped when the generator already implies it, which loadSavedQueries
// reapplies on the way back in.
- if (query.flat && query.generated != QStringLiteral("sent"))
+ if (query.flat && !generatorIsFlat(query.generated))
object.insert(QStringLiteral("flat"), true);
for (auto it = query.unknown.begin(); it != query.unknown.end(); ++it)
object.insert(it.key(), it.value());
@@ -951,6 +999,9 @@ SavedQuery Config::builtinFilter(const QString &generator)
SavedQuery filter;
filter.generated = generator;
+ // One source for the view mode, shared with the saved-query round trip, so
+ // a branch below cannot disagree with what loadSavedQueries reapplies.
+ filter.flat = generatorIsFlat(generator);
// Translated, because these are the labels on the buttons. The GENERATOR
// name is not: it is stored in queries.json and matched against a closed
@@ -969,16 +1020,18 @@ SavedQuery Config::builtinFilter(const QString &generator)
filter.name = tr("Important");
} else if (generator == QStringLiteral("sent")) {
filter.name = tr("Sent");
- // Messages rather than threads, and the only filter that sets this. A
- // thread would fold the user's sent message back into the conversation
- // it belongs to, which is item 63's finding.
- filter.flat = true;
+ // Flat, per generatorIsFlat(): a thread would fold the user's sent
+ // message back into the conversation it belongs to, item 63's finding.
} else if (generator == QStringLiteral("drafts")) {
// The LABEL is translated; the generator stays `drafts`, which is what
// queries.json stores and what a closed set is matched against.
filter.name = tr("Drafts");
- // NOT flat, like Trash and unlike Sent: a draft reply belongs with the
- // conversation it answers.
+ // Flat, per generatorIsFlat(). Item 138 chose threaded, reasoning that
+ // a draft reply belongs with the conversation it answers; item 159
+ // reversed it on what that cost. A thread row stands for its first
+ // MATCHED message, which for a draft reply is the message being
+ // replied TO, so the draft itself had no row of its own and
+ // double-clicking the conversation opened nothing.
} else if (generator == QStringLiteral("trash")) {
filter.name = tr("Trash");
// NOT flat, unlike Sent. A deleted message still belongs to its
diff --git a/src/config.h b/src/config.h
index 4dcfbf1..02b4038 100644
--- a/src/config.h
+++ b/src/config.h
@@ -26,6 +26,7 @@
#include <QStringList>
#include "completionentry.h"
+#include "signatures.h"
class QSettings;
@@ -58,6 +59,18 @@ struct Account
/// one for the account that has none.
QString sent;
+ /// The signature seeded when composing from this account, by name.
+ ///
+ /// Optional, and it does not tie a signature to the account: the switch on
+ /// the composer's editor bar keeps every signature reachable whichever
+ /// account is selected. This is a STARTING value only, which is why the
+ /// user's "not tied to an account" constraint survives it (item 152).
+ ///
+ /// The fallback to [compose] signature is NOT resolved here. An account
+ /// with no key of its own carries an empty string and the composer falls
+ /// through, so the two values stay distinguishable.
+ QString signature;
+
/// The account's trash folder, relative to maildir.
///
/// MANDATORY, unlike `sent` and `drafts`. Delete moves a file into this
@@ -228,6 +241,16 @@ struct ComposeSettings
/// accounts. Falls through when it names an account that cannot send.
QString defaultAccount;
+ /// The signature seeded when the account carries none, by name. Empty
+ /// means no signature is seeded at all.
+ QString signature;
+
+ /// Where a newly inserted signature goes. End by default, which is the
+ /// user's own habit; above_quote exists because other clients offer the
+ /// choice, and the splice's quote-aware scan is needed for the guard
+ /// either way.
+ Signatures::Position signaturePosition = Signatures::Position::End;
+
qint64 attachmentWarnBytes = 26214400;
};
diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp
index 99eb2a3..af3b817 100644
--- a/src/mainwindow.cpp
+++ b/src/mainwindow.cpp
@@ -1138,6 +1138,17 @@ void MainWindow::openComposer(const ComposeContext &context)
});
});
+ // A saved draft is indexed immediately (item 158): the Drafts view is a
+ // path query, and without this the draft is invisible until the next sync.
+ // The worker lives on another thread, so this is a queued connection and
+ // notmuch stays on its own thread.
+ connect(composer, &ComposeWindow::draftSaved, m_worker,
+ &NotmuchWorker::indexDraftFile);
+
+ // A draft unlinked on send must leave no ghost entry behind.
+ connect(composer, &ComposeWindow::draftRemoved, m_worker,
+ &NotmuchWorker::removeIndexedFile);
+
composer->show();
}
diff --git a/src/notmuchworker.cpp b/src/notmuchworker.cpp
index fca0a5a..16df4ed 100644
--- a/src/notmuchworker.cpp
+++ b/src/notmuchworker.cpp
@@ -820,8 +820,99 @@ void NotmuchWorker::moveMessages(const QStringList &messageIds,
emit messagesMovedFrom(origins, destFolder);
}
+void NotmuchWorker::indexDraftFile(const QString &path,
+ const QString &previousPath)
+{
+ if (path.isEmpty())
+ return;
+
+ // Same ordering as applyTags() and moveMessages(): notmuch allows one open
+ // handle per process, so the read-only one must close before the write.
+ close();
+
+ const QByteArray configPath = configPathArg();
+ notmuch_database_t *db = nullptr;
+ char *error = nullptr;
+ const notmuch_status_t status = notmuch_database_open_with_config(
+ nullptr,
+ NOTMUCH_DATABASE_MODE_READ_WRITE,
+ configPath.isEmpty() ? nullptr : configPath.constData(),
+ nullptr,
+ &db,
+ &error);
+
+ if (status != NOTMUCH_STATUS_SUCCESS) {
+ emit errorOccurred(
+ QStringLiteral("Cannot open database for writing: %1")
+ .arg(QString::fromUtf8(error ? error
+ : notmuch_status_to_string(status))));
+ free(error);
+ return;
+ }
+
+ notmuch_message_t *indexed = nullptr;
+ const notmuch_status_t added = notmuch_database_index_file(
+ db, path.toUtf8().constData(), nullptr, &indexed);
+ if (indexed)
+ notmuch_message_destroy(indexed);
+
+ // DUPLICATE_MESSAGE_ID is success here, exactly as in moveMessages(): the
+ // file reached the database, it is only the id that was already known.
+ if (added != NOTMUCH_STATUS_SUCCESS
+ && added != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
+ notmuch_database_close(db);
+ notmuch_database_destroy(db);
+ emit errorOccurred(
+ QStringLiteral("Cannot index %1: %2")
+ .arg(QFileInfo(path).fileName(),
+ QString::fromUtf8(notmuch_status_to_string(added))));
+ return;
+ }
+
+ // The previous revision, if any, is already unlinked from disk; its entry
+ // must not linger as a ghost draft with a filename that no longer exists.
+ if (!previousPath.isEmpty() && previousPath != path)
+ notmuch_database_remove_message(db, previousPath.toUtf8().constData());
+
+ notmuch_database_close(db);
+ notmuch_database_destroy(db);
+}
+
+void NotmuchWorker::removeIndexedFile(const QString &path)
+{
+ if (path.isEmpty())
+ return;
+
+ close();
+
+ const QByteArray configPath = configPathArg();
+ notmuch_database_t *db = nullptr;
+ char *error = nullptr;
+ const notmuch_status_t status = notmuch_database_open_with_config(
+ nullptr,
+ NOTMUCH_DATABASE_MODE_READ_WRITE,
+ configPath.isEmpty() ? nullptr : configPath.constData(),
+ nullptr,
+ &db,
+ &error);
+
+ if (status != NOTMUCH_STATUS_SUCCESS) {
+ emit errorOccurred(
+ QStringLiteral("Cannot open database for writing: %1")
+ .arg(QString::fromUtf8(error ? error
+ : notmuch_status_to_string(status))));
+ free(error);
+ return;
+ }
+
+ notmuch_database_remove_message(db, path.toUtf8().constData());
+
+ notmuch_database_close(db);
+ notmuch_database_destroy(db);
+}
+
void NotmuchWorker::resolveMessages(const QStringList &messageIds,
- const QString &requestTag)
+ const QString &requestTag)
{
if (messageIds.isEmpty())
return;
diff --git a/src/notmuchworker.h b/src/notmuchworker.h
index 8ed878f..3ccf8e5 100644
--- a/src/notmuchworker.h
+++ b/src/notmuchworker.h
@@ -134,6 +134,28 @@ public slots:
/// it, so removing before indexing loses the message's tags.
void moveMessages(const QStringList &messageIds, const QString &destFolder);
+ /// Indexes one freshly written file, so it appears in a `path:` query
+ /// without a full `notmuch new` (item 158).
+ ///
+ /// The draft-save path writes the file and stops, and the Drafts view is a
+ /// path query, so an unindexed draft is invisible until the next sync. A
+ /// draft rewrite writes a NEW file (MessageBuilder generates a fresh
+ /// Message-ID on every build) and unlinks the old, so \p previousPath is
+ /// removed after the new one is indexed, mirroring moveMessages()'s
+ /// ordering: the old entry must not linger as a ghost draft.
+ ///
+ /// \p path is absolute, as DraftStore::write() returns it. The Maildir
+ /// flags on the file (the "D" flag a draft carries) drive its tags exactly
+ /// as they would on a later `notmuch new`.
+ void indexDraftFile(const QString &path, const QString &previousPath = {});
+
+ /// Removes one file from the index, without touching the file on disk.
+ ///
+ /// The counterpart to indexDraftFile() for the send path: a draft that was
+ /// indexed while being composed is unlinked when it is sent, and its entry
+ /// must not linger as a ghost draft until the next sync.
+ void removeIndexedFile(const QString &path);
+
/// Batch tagging over whole threads. The UI holds thread ids, not message
/// ids, for rows it has not opened, so the resolution happens here where
/// the database handle lives. This is the path the archive/flag/delete
diff --git a/src/signatures.cpp b/src/signatures.cpp
new file mode 100644
index 0000000..ef631d6
--- /dev/null
+++ b/src/signatures.cpp
@@ -0,0 +1,229 @@
+/*
+ * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
+ * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include "signatures.h"
+
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+
+namespace Signatures {
+
+QStringList names(const QString &dir)
+{
+ QDir directory(dir);
+ if (!directory.exists())
+ return {};
+
+ QStringList result;
+ const QStringList files =
+ directory.entryList({ QStringLiteral("*.md") }, QDir::Files, QDir::Name);
+ result.reserve(files.size());
+ for (const QString &file : files)
+ result.append(QFileInfo(file).completeBaseName());
+ return result;
+}
+
+QString text(const QString &dir, const QString &name)
+{
+ // A name arriving from the config file is untrusted input reaching a path.
+ // Stems from names() never contain a separator, so rejecting one costs
+ // nothing and stops a name like `../../.ssh/id_rsa` from being read into a
+ // message the user is about to send.
+ if (name.isEmpty() || name.contains(QLatin1Char('/'))
+ || name.contains(QLatin1Char('\\')))
+ return {};
+
+ QFile file(dir + QStringLiteral("/") + name + QStringLiteral(".md"));
+ if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
+ return {};
+ return QString::fromUtf8(file.readAll());
+}
+
+namespace {
+
+/// The RFC 3676 signature separator: two hyphens, a space, end of line.
+///
+/// The trailing space is part of the standard and is what receiving clients
+/// match on to fold or strip a signature. It is also why `--` typed by hand
+/// does not collide: an editor does not add trailing whitespace on its own.
+const QLatin1String kDelimiter("-- ");
+
+bool isQuoted(const QString &line)
+{
+ return line.startsWith(QLatin1Char('>'));
+}
+
+/// \p text with trailing blank lines removed, the same normalisation the block
+/// scan below applies. text() returns file content verbatim, so a signature
+/// file ends with the newline every editor writes; without this the match
+/// compares a block with no trailing newline against a known entry that has
+/// one, and the guard silently fails, appending a second signature instead of
+/// replacing the first.
+QString stripTrailingBlankLines(const QString &text)
+{
+ QStringList lines = text.split(QLatin1Char('\n'));
+ while (!lines.isEmpty() && lines.last().trimmed().isEmpty())
+ lines.removeLast();
+ return lines.join(QLatin1Char('\n'));
+}
+
+/// The index of the first line of the quote, or -1 when the buffer has none.
+///
+/// The attribution line ("On Mon, someone wrote:") is deliberately NOT
+/// included: it introduces the quote and belongs with it, so a signature
+/// inserted above the quote goes above the attribution too. Returning the
+/// quoted line itself would strand the signature between the attribution and
+/// the text it introduces.
+int quoteStart(const QStringList &lines, int from = 0)
+{
+ for (int i = from; i < lines.size(); ++i) {
+ if (!isQuoted(lines.at(i)))
+ continue;
+ // Walk back over the attribution and the blank line before it, so the
+ // signature lands above the whole block rather than inside it.
+ int start = i;
+ while (start > from && !lines.at(start - 1).trimmed().isEmpty()
+ && !isQuoted(lines.at(start - 1)))
+ --start;
+ return start;
+ }
+ return -1;
+}
+
+/// Where the block introduced by the delimiter at \p delimiter ends: the start
+/// of the quote below it, or the end of the buffer when there is none.
+///
+/// This must use quoteStart() rather than scanning for the first quoted line,
+/// because the ATTRIBUTION is part of the quote. Scanning for `>` alone puts
+/// "On Mon, someone wrote:" inside the signature block, which then matches no
+/// known signature and, when it did, left the attribution stranded above the
+/// removed text. The two boundaries have to be the same one.
+int blockEnd(const QStringList &lines, int delimiter)
+{
+ const int quote = quoteStart(lines, delimiter + 1);
+ return quote < 0 ? lines.size() : quote;
+}
+
+/// The line index of the delimiter introducing an existing signature, or -1.
+///
+/// Two conditions, and both are load-bearing. The delimiter must not be
+/// QUOTED, since the quoted original carries the other party's signature and
+/// it is not this message's to replace. And the block after it must MATCH one
+/// of \p known: finding a delimiter is not authority to delete what follows
+/// it, because "-- " reaches a buffer pasted in with quoted text.
+int existingSignature(const QStringList &lines, const QStringList &known)
+{
+ for (int i = lines.size() - 1; i >= 0; --i) {
+ if (lines.at(i) != kDelimiter)
+ continue;
+
+ // The block runs to the end, or to the quote when the signature sits
+ // above one.
+ const int end = blockEnd(lines, i);
+ // A trailing blank line belongs to the separation, not to the text.
+ int textEnd = end;
+ while (textEnd > i + 1 && lines.at(textEnd - 1).trimmed().isEmpty())
+ --textEnd;
+
+ const QString block =
+ lines.mid(i + 1, textEnd - (i + 1)).join(QLatin1Char('\n'));
+ if (known.contains(block))
+ return i;
+ }
+ return -1;
+}
+
+/// \p lines with the signature at \p delimiter removed, blank separator and
+/// all. The caller has already established that the block is a known one.
+QStringList withoutSignature(const QStringList &lines, int delimiter)
+{
+ const int end = blockEnd(lines, delimiter);
+
+ QStringList head = lines.mid(0, delimiter);
+ while (!head.isEmpty() && head.last().trimmed().isEmpty())
+ head.removeLast();
+
+ QStringList result = head;
+ if (end < lines.size()) {
+ // Something follows (the quote): restore the blank line that
+ // separated it from the signature now being removed.
+ result.append(QString());
+ result.append(lines.mid(end));
+ } else {
+ // The signature ran to the end of the buffer, and the trailing
+ // newline the head lost with its blank line goes back.
+ result.append(QString());
+ }
+ return result;
+}
+
+} // namespace
+
+QString replace(const QString &buffer, const QString &signature,
+ const QStringList &known, Position position)
+{
+ // Normalise known to the same footing the block scan uses, once here rather
+ // than per comparison. knownSignatures() passes text() verbatim, trailing
+ // newline and all, and the match must be newline-insensitive or the guard
+ // treats every on-disk signature as unknown.
+ QStringList normalized;
+ normalized.reserve(known.size());
+ for (const QString &entry : known)
+ normalized.append(stripTrailingBlankLines(entry));
+
+ QStringList lines = buffer.split(QLatin1Char('\n'));
+
+ const int existing = existingSignature(lines, normalized);
+ if (existing >= 0)
+ lines = withoutSignature(lines, existing);
+
+ const QString stripped = lines.join(QLatin1Char('\n'));
+
+ // "None", or nothing to insert: the removal above is the whole operation.
+ if (signature.isEmpty())
+ return stripped;
+
+ const QString block = QStringLiteral("\n") + kDelimiter
+ + QStringLiteral("\n") + signature;
+
+ const int quote =
+ position == Position::AboveQuote ? quoteStart(lines) : -1;
+
+ // No quote to sit above is not a special case: it is the End placement,
+ // which is why a New message needs no branch of its own.
+ if (quote < 0)
+ return stripped + block;
+
+ QStringList head = lines.mid(0, quote);
+ const QStringList tail = lines.mid(quote);
+ // The head ends in however many blank lines separated the reply from the
+ // attribution. Drop them all and let the block supply exactly one, so the
+ // spacing is the same whatever the quote was seeded with.
+ while (!head.isEmpty() && head.last().trimmed().isEmpty())
+ head.removeLast();
+
+ // head.join() has no trailing newline once trimmed, so the terminator for
+ // its last line is supplied here; `block` then opens with the blank line,
+ // which is the same shape as the End placement over a buffer ending in a
+ // newline.
+ return head.join(QLatin1Char('\n')) + QStringLiteral("\n") + block
+ + QStringLiteral("\n\n") + tail.join(QLatin1Char('\n'));
+}
+
+} // namespace Signatures
diff --git a/src/signatures.h b/src/signatures.h
new file mode 100644
index 0000000..e2bfd9c
--- /dev/null
+++ b/src/signatures.h
@@ -0,0 +1,76 @@
+/*
+ * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
+ * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#pragma once
+
+#include <QString>
+#include <QStringList>
+
+/// Signatures, as markdown files spliced into the composer's buffer.
+///
+/// Free functions over values, with no widget anywhere, matching
+/// MarkdownFormat, MessageBuilder and DraftStore. The splice is the part worth
+/// testing and it is testable with no painter.
+///
+/// MARKDOWN, and that is what makes this small: MessageBuilder already builds
+/// text/plain from the buffer verbatim and text/html from MarkdownRenderer
+/// over the same string, so a signature in the buffer yields both forms with
+/// no change there and no second code path. One choice by the user serves both
+/// parts, which is what the feature was asked for.
+namespace Signatures {
+
+/// Where a newly inserted signature goes, from [compose] signature_position.
+enum class Position {
+ End, ///< The end of the buffer. The default and the user's habit.
+ AboveQuote ///< Before the first quoted line, or the end when there is none.
+};
+
+/// The stems of every `*.md` in \p dir, sorted, without the extension.
+///
+/// A missing or unreadable directory yields an empty list. That is not a
+/// misconfiguration: it means the user keeps no signatures, and the switch
+/// then offers only "None".
+QStringList names(const QString &dir);
+
+/// The content of `<dir>/<name>.md`, or empty when it cannot be read.
+///
+/// \p name is a stem from names(), never a path. It is rejected if it contains
+/// a path separator, so a value arriving from the config file cannot reach
+/// outside \p dir.
+QString text(const QString &dir, const QString &name);
+
+/// Returns \p buffer with \p signature spliced in.
+///
+/// Any signature already present is replaced; \p signature empty removes it
+/// and inserts nothing, which is what "None" selects.
+///
+/// \p known is the text of every signature in the directory, and it is what
+/// makes this non-destructive. A `-- ` delimiter is NOT sufficient authority
+/// to delete what follows it: the block is replaced only when its text matches
+/// one of \p known, and otherwise the new signature is INSERTED with nothing
+/// removed. `-- ` reaches a buffer without the user ever choosing a signature,
+/// most plausibly pasted in with quoted text from another client, and the
+/// unguarded rule would silently delete everything after it.
+///
+/// The failure is therefore directional, which is the whole point: a wrong
+/// guess adds a visible second signature, one undo away, rather than losing
+/// the user's own writing.
+QString replace(const QString &buffer, const QString &signature,
+ const QStringList &known, Position position);
+
+} // namespace Signatures
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 1af49bb..5938aeb 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -65,6 +65,7 @@ add_qtmaildir_test(tagdialog)
add_qtmaildir_test(tagrules)
add_qtmaildir_test(rulequery)
add_qtmaildir_test(searchterm)
+add_qtmaildir_test(signatures)
add_qtmaildir_test(busyindicator)
add_qtmaildir_test(tagstrip)
add_qtmaildir_test(messagedetailsdialog)
@@ -74,6 +75,7 @@ add_qtmaildir_test(maildirname)
add_qtmaildir_test(draftstore)
add_qtmaildir_test(messagesender)
add_qtmaildir_test(composecontext)
+add_qtmaildir_test(composewindow)
add_qtmaildir_test(formattoolbar)
add_qtmaildir_test(senddialog)
add_qtmaildir_test(translations)
diff --git a/tests/test_composewindow.cpp b/tests/test_composewindow.cpp
new file mode 100644
index 0000000..472c103
--- /dev/null
+++ b/tests/test_composewindow.cpp
@@ -0,0 +1,451 @@
+/*
+ * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
+ * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include <QtTest>
+#include <QComboBox>
+#include <QDir>
+#include <QFile>
+#include <QMenu>
+#include <QPlainTextEdit>
+#include <QSignalSpy>
+#include <QTemporaryDir>
+#include <QTextStream>
+#include <QToolButton>
+
+#include "composecontext.h"
+#include "composewindow.h"
+#include "config.h"
+#include "signatures.h"
+
+class TestComposeWindow : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void init();
+ void cleanup();
+
+ void aNewMessageSeedsTheComposeSignature();
+ void anAccountSignatureOverridesTheComposeOne();
+ void aResumedDraftSeedsNoSignature();
+ void anUnknownSignatureNameSeedsNothing();
+ void theSwitchListsEveryFileAndNone();
+ void changingTheAccountFollowsItsSignature();
+ void changingTheAccountStopsFollowingOnceTheSwitchIsUsed();
+ void aResumedDraftDoesNotReseedOnAnAccountChange();
+ void savingADraftEmitsItsPathAndTheReplacedOne();
+
+private:
+ /// A config pointing at a signatures directory holding \p files, with one
+ /// account that can send.
+ Config makeConfig(const QList<QPair<QString, QString>> &files,
+ const QString &composeSignature,
+ const QString &accountSignature = {});
+
+ /// QVERIFY cannot appear inside makeConfig(), which returns a value: the
+ /// macro expands to a bare `return;` on failure, which is invalid in a
+ /// non-void function. A void helper keeps the check and sidesteps that.
+ void writeFile(const QString &path, const QString &content);
+
+ QTemporaryDir *m_dir = nullptr;
+ QString m_signatureDir;
+};
+
+void TestComposeWindow::init()
+{
+ m_dir = new QTemporaryDir;
+ QVERIFY(m_dir->isValid());
+ m_signatureDir = m_dir->path() + QStringLiteral("/signatures");
+ QVERIFY(QDir().mkpath(m_signatureDir));
+}
+
+void TestComposeWindow::cleanup()
+{
+ delete m_dir;
+ m_dir = nullptr;
+}
+
+void TestComposeWindow::writeFile(const QString &path, const QString &content)
+{
+ QFile file(path);
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
+ QTextStream out(&file);
+ out << content;
+}
+
+Config TestComposeWindow::makeConfig(
+ const QList<QPair<QString, QString>> &files,
+ const QString &composeSignature, const QString &accountSignature)
+{
+ for (const auto &entry : files)
+ writeFile(m_signatureDir + QStringLiteral("/") + entry.first, entry.second);
+
+ QString conf;
+ {
+ QTextStream out(&conf);
+ out << "[compose]\n"
+ << "signature = " << composeSignature << "\n"
+ << "\n"
+ << "[account.work]\n"
+ << "name = Someone\n"
+ << "address = someone@example.org\n"
+ << "maildir = work\n"
+ << "send_command = /bin/cat\n";
+ if (!accountSignature.isEmpty())
+ out << "signature = " << accountSignature << "\n";
+ }
+ const QString path = m_dir->path() + QStringLiteral("/qtmaildir.conf");
+ writeFile(path, conf);
+
+ Config config;
+ config.load(path);
+ return config;
+}
+
+void TestComposeWindow::aNewMessageSeedsTheComposeSignature()
+{
+ const Config config = makeConfig(
+ { { QStringLiteral("work.md"), QStringLiteral("Jane Doe") } },
+ QStringLiteral("work"));
+
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::New;
+ context.accountKey = QStringLiteral("work");
+
+ ComposeWindow window(context, config, m_dir->path());
+ window.setSignatureDir(m_signatureDir);
+ window.seedSignature();
+
+ auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
+ QVERIFY(body);
+ QVERIFY(body->toPlainText().endsWith(QStringLiteral("-- \nJane Doe")));
+}
+
+void TestComposeWindow::anAccountSignatureOverridesTheComposeOne()
+{
+ const Config config = makeConfig(
+ { { QStringLiteral("work.md"), QStringLiteral("Long one") },
+ { QStringLiteral("brief.md"), QStringLiteral("Brief") } },
+ QStringLiteral("work"), QStringLiteral("brief"));
+
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::New;
+ context.accountKey = QStringLiteral("work");
+
+ ComposeWindow window(context, config, m_dir->path());
+ window.setSignatureDir(m_signatureDir);
+ window.seedSignature();
+
+ auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
+ QVERIFY(body);
+ QVERIFY(body->toPlainText().endsWith(QStringLiteral("-- \nBrief")));
+}
+
+void TestComposeWindow::aResumedDraftSeedsNoSignature()
+{
+ const Config config = makeConfig(
+ { { QStringLiteral("work.md"), QStringLiteral("Jane Doe") } },
+ QStringLiteral("work"));
+
+ // The saved body already carries whatever signature it was written with.
+ // Seeding again would put a SECOND one on a message written once.
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::Draft;
+ context.accountKey = QStringLiteral("work");
+ context.body = QStringLiteral("Half a thought.\n\n-- \nJane Doe");
+ context.draftPath = m_dir->path() + QStringLiteral("/draft");
+
+ ComposeWindow window(context, config, m_dir->path());
+ window.setSignatureDir(m_signatureDir);
+ window.seedSignature();
+
+ auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
+ QVERIFY(body);
+ QCOMPARE(body->toPlainText().count(QStringLiteral("-- \nJane Doe")), 1);
+}
+
+void TestComposeWindow::anUnknownSignatureNameSeedsNothing()
+{
+ const Config config = makeConfig(
+ { { QStringLiteral("work.md"), QStringLiteral("Jane Doe") } },
+ QStringLiteral("absent"));
+
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::New;
+ context.accountKey = QStringLiteral("work");
+
+ ComposeWindow window(context, config, m_dir->path());
+ window.setSignatureDir(m_signatureDir);
+ window.seedSignature();
+
+ auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
+ QVERIFY(body);
+ // No signature, and the composer still opened rather than refusing.
+ QVERIFY(!body->toPlainText().contains(QStringLiteral("-- ")));
+}
+
+void TestComposeWindow::theSwitchListsEveryFileAndNone()
+{
+ const Config config = makeConfig(
+ { { QStringLiteral("work.md"), QStringLiteral("Jane Doe") },
+ { QStringLiteral("brief.md"), QStringLiteral("Brief") } },
+ QString());
+
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::New;
+ context.accountKey = QStringLiteral("work");
+
+ ComposeWindow window(context, config, m_dir->path());
+ window.setSignatureDir(m_signatureDir);
+ window.seedSignature();
+
+ auto *button =
+ window.findChild<QToolButton *>(QStringLiteral("signatureSwitch"));
+ QVERIFY(button);
+ QVERIFY(button->menu());
+ // "None" plus one per file.
+ QCOMPARE(button->menu()->actions().size(), 3);
+}
+
+void TestComposeWindow::changingTheAccountFollowsItsSignature()
+{
+ for (const auto &entry :
+ QList<QPair<QString, QString>>{
+ { QStringLiteral("work.md"), QStringLiteral("Work sig") },
+ { QStringLiteral("home.md"), QStringLiteral("Home sig") } }) {
+ QFile file(m_signatureDir + QStringLiteral("/") + entry.first);
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
+ file.write(entry.second.toUtf8());
+ file.close();
+ }
+
+ const QString path = m_dir->path() + QStringLiteral("/qtmaildir.conf");
+ {
+ QFile file(path);
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
+ QTextStream out(&file);
+ out << "[account.work]\n"
+ << "name = Someone\naddress = someone@example.org\n"
+ << "maildir = work\nsend_command = /bin/cat\n"
+ << "signature = work\n"
+ << "\n[account.home]\n"
+ << "name = Someone\naddress = other@example.org\n"
+ << "maildir = home\nsend_command = /bin/cat\n"
+ << "signature = home\n";
+ }
+ Config config;
+ config.load(path);
+
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::New;
+ context.accountKey = QStringLiteral("work");
+
+ ComposeWindow window(context, config, m_dir->path());
+ window.setSignatureDir(m_signatureDir);
+ window.seedSignature();
+
+ auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
+ auto *from = window.findChild<QComboBox *>(QStringLiteral("from"));
+ QVERIFY(body);
+ QVERIFY(from);
+ QVERIFY(body->toPlainText().contains(QStringLiteral("Work sig")));
+
+ // Select the other account by its key, never by index: the order of the
+ // combo is the config's and an index assertion would pass on the wrong one.
+ const int home = from->findData(QStringLiteral("home"));
+ QVERIFY(home >= 0);
+ from->setCurrentIndex(home);
+
+ QVERIFY(body->toPlainText().contains(QStringLiteral("Home sig")));
+ QVERIFY(!body->toPlainText().contains(QStringLiteral("Work sig")));
+}
+
+void TestComposeWindow::changingTheAccountStopsFollowingOnceTheSwitchIsUsed()
+{
+ for (const auto &entry :
+ QList<QPair<QString, QString>>{
+ { QStringLiteral("work.md"), QStringLiteral("Work sig") },
+ { QStringLiteral("home.md"), QStringLiteral("Home sig") },
+ { QStringLiteral("chosen.md"), QStringLiteral("Chosen sig") } }) {
+ QFile file(m_signatureDir + QStringLiteral("/") + entry.first);
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
+ file.write(entry.second.toUtf8());
+ file.close();
+ }
+
+ const QString path = m_dir->path() + QStringLiteral("/qtmaildir.conf");
+ {
+ QFile file(path);
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
+ QTextStream out(&file);
+ out << "[account.work]\n"
+ << "name = Someone\naddress = someone@example.org\n"
+ << "maildir = work\nsend_command = /bin/cat\n"
+ << "signature = work\n"
+ << "\n[account.home]\n"
+ << "name = Someone\naddress = other@example.org\n"
+ << "maildir = home\nsend_command = /bin/cat\n"
+ << "signature = home\n";
+ }
+ Config config;
+ config.load(path);
+
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::New;
+ context.accountKey = QStringLiteral("work");
+
+ ComposeWindow window(context, config, m_dir->path());
+ window.setSignatureDir(m_signatureDir);
+ window.seedSignature();
+
+ auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
+ auto *from = window.findChild<QComboBox *>(QStringLiteral("from"));
+ auto *button =
+ window.findChild<QToolButton *>(QStringLiteral("signatureSwitch"));
+ QVERIFY(body);
+ QVERIFY(from);
+ QVERIFY(button);
+
+ // The user picks one deliberately.
+ for (QAction *action : button->menu()->actions()) {
+ if (action->data().toString() == QStringLiteral("chosen"))
+ action->trigger();
+ }
+ QVERIFY(body->toPlainText().contains(QStringLiteral("Chosen sig")));
+
+ const int home = from->findData(QStringLiteral("home"));
+ QVERIFY(home >= 0);
+ from->setCurrentIndex(home);
+
+ // The deliberate choice survives the account change. Overwriting it is
+ // the one behaviour that can silently discard something the user just did.
+ QVERIFY(body->toPlainText().contains(QStringLiteral("Chosen sig")));
+ QVERIFY(!body->toPlainText().contains(QStringLiteral("Home sig")));
+}
+
+void TestComposeWindow::aResumedDraftDoesNotReseedOnAnAccountChange()
+{
+ for (const auto &entry :
+ QList<QPair<QString, QString>>{
+ { QStringLiteral("work.md"), QStringLiteral("Work sig") },
+ { QStringLiteral("home.md"), QStringLiteral("Home sig") } }) {
+ QFile file(m_signatureDir + QStringLiteral("/") + entry.first);
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
+ file.write(entry.second.toUtf8());
+ file.close();
+ }
+
+ const QString path = m_dir->path() + QStringLiteral("/qtmaildir.conf");
+ {
+ QFile file(path);
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
+ QTextStream out(&file);
+ out << "[account.work]\n"
+ << "name = Someone\naddress = someone@example.org\n"
+ << "maildir = work\nsend_command = /bin/cat\n"
+ << "signature = work\n"
+ << "\n[account.home]\n"
+ << "name = Someone\naddress = other@example.org\n"
+ << "maildir = home\nsend_command = /bin/cat\n"
+ << "signature = home\n";
+ }
+ Config config;
+ config.load(path);
+
+ // The saved body already carries its own signature, which does not match
+ // any on-disk file. A From: change must not replace it with the new
+ // account's: the draft is the message the user wrote, exactly as
+ // seedBody() takes its body verbatim.
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::Draft;
+ context.accountKey = QStringLiteral("work");
+ context.body = QStringLiteral("Half a thought.\n\n-- \nJane Doe");
+ context.draftPath = m_dir->path() + QStringLiteral("/draft");
+
+ ComposeWindow window(context, config, m_dir->path());
+ window.setSignatureDir(m_signatureDir);
+ window.seedSignature();
+
+ auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
+ auto *from = window.findChild<QComboBox *>(QStringLiteral("from"));
+ QVERIFY(body);
+ QVERIFY(from);
+ QVERIFY(body->toPlainText().contains(QStringLiteral("Jane Doe")));
+
+ const int home = from->findData(QStringLiteral("home"));
+ QVERIFY(home >= 0);
+ from->setCurrentIndex(home);
+
+ QVERIFY(body->toPlainText().contains(QStringLiteral("Jane Doe")));
+ QVERIFY(!body->toPlainText().contains(QStringLiteral("Home sig")));
+}
+
+void TestComposeWindow::savingADraftEmitsItsPathAndTheReplacedOne()
+{
+ // A config whose account has a drafts folder, which makeConfig() does not
+ // set, so the save can actually write somewhere.
+ const QString confPath = m_dir->path() + QStringLiteral("/qtmaildir.conf");
+ {
+ QString conf;
+ QTextStream out(&conf);
+ out << "[account.work]\n"
+ << "name = Someone\n"
+ << "address = someone@example.org\n"
+ << "maildir = work\n"
+ << "drafts = Drafts\n"
+ << "send_command = /bin/cat\n";
+ writeFile(confPath, conf);
+ }
+ Config config;
+ config.load(confPath);
+
+ ComposeContext context;
+ context.kind = ComposeContext::Kind::New;
+ context.accountKey = QStringLiteral("work");
+
+ ComposeWindow window(context, config, m_dir->path());
+ auto *body = window.findChild<QPlainTextEdit *>(QStringLiteral("body"));
+ QVERIFY(body);
+
+ QSignalSpy saved(&window, &ComposeWindow::draftSaved);
+
+ body->setPlainText(QStringLiteral("First revision."));
+ QVERIFY(window.saveDraftNow());
+
+ QCOMPARE(saved.size(), 1);
+ const QString first = saved.first().at(0).toString();
+ const QString firstPrevious = saved.first().at(1).toString();
+ QVERIFY(!first.isEmpty());
+ QVERIFY(firstPrevious.isEmpty());
+ QVERIFY(QFile::exists(first));
+
+ // A rewrite writes a fresh file and unlinks the old; the previous path
+ // comes back so the owner can drop the old index entry.
+ body->setPlainText(QStringLiteral("Second revision."));
+ QVERIFY(window.saveDraftNow());
+
+ QCOMPARE(saved.size(), 2);
+ const QString second = saved.at(1).at(0).toString();
+ const QString secondPrevious = saved.at(1).at(1).toString();
+ QVERIFY(!second.isEmpty());
+ QCOMPARE(secondPrevious, first);
+ QVERIFY2(second != first, "a rewrite reused the old filename");
+}
+
+QTEST_MAIN(TestComposeWindow)
+#include "test_composewindow.moc"
diff --git a/tests/test_config.cpp b/tests/test_config.cpp
index a5dce9a..e69a073 100644
--- a/tests/test_config.cpp
+++ b/tests/test_config.cpp
@@ -25,6 +25,7 @@
#include <QJsonObject>
#include "config.h"
#include "mailsync.h"
+#include "signatures.h"
class TestConfig : public QObject
{
@@ -121,7 +122,7 @@ private slots:
void anAccountWithoutATrashFolderWarns();
void theDraftsFilterComposesPerAccount();
void theDraftsFilterMatchesNothingWithoutAFolder();
- void theDraftsFilterIsThreadedNotFlat();
+ void theDraftsFilterIsFlatLikeSent();
void theTrashFilterComposesPerAccount();
void theTrashFilterMatchesNothingWithoutAFolder();
void anAccountWithoutASendCommandIsReceiveOnly();
@@ -134,6 +135,9 @@ private slots:
void garbageAttachmentWarnBytesIsRejectedNotZero();
void zeroOrNegativeAutosaveIntervalIsClamped();
void unrecognisedQuotePositionWarnsAndFallsBackToBelow();
+ void theSignatureKeysAreRead();
+ void anAccountSignatureOverridesTheComposeDefault();
+ void aMalformedSignaturePositionIsReportedAndFallsBack();
};
static QString writeIni(const QTemporaryDir &dir, const QString &body)
@@ -1072,17 +1076,24 @@ void TestConfig::theDraftsFilterMatchesNothingWithoutAFolder()
Config::matchNothingQuery());
}
-void TestConfig::theDraftsFilterIsThreadedNotFlat()
+void TestConfig::theDraftsFilterIsFlatLikeSent()
{
- // Unlike Sent, and deliberately. Sent is flat because a thread would fold
- // the user's own message back into the conversation it answers, which is
- // item 63's finding. A draft reply belongs with its conversation for the
- // same reason a trashed message does, so drafts follow trash here.
+ // Item 138 shipped this THREADED, reasoning that a draft reply belongs
+ // with the conversation it answers. Item 159 reversed it on what that
+ // cost: a thread row stands for its first MATCHED message, which for a
+ // draft reply is the message being replied TO, so the draft had no row of
+ // its own and double-clicking the conversation opened nothing.
const SavedQuery drafts = Config::builtinFilter(QStringLiteral("drafts"));
- QVERIFY2(!drafts.flat, "the drafts filter is flat, like Sent");
+ QVERIFY2(drafts.flat, "the drafts filter went back to threaded, so a draft "
+ "reply has no row of its own (item 159)");
const SavedQuery sent = Config::builtinFilter(QStringLiteral("sent"));
QVERIFY2(sent.flat, "Sent stopped being flat, which item 63 requires");
+
+ // Trash deliberately did NOT follow. A deleted message still belongs to
+ // its conversation, and nothing has to be reachable for editing there.
+ const SavedQuery trash = Config::builtinFilter(QStringLiteral("trash"));
+ QVERIFY2(!trash.flat, "trash became flat; only sent and drafts should be");
}
void TestConfig::theTrashFilterComposesPerAccount()
@@ -2353,6 +2364,7 @@ void TestConfig::aGeneratedEntryWritesNoRedundantKeys()
"version": 1,
"queries": [
{ "name": "Sent", "generated": "sent", "pinned": true },
+ { "name": "Drafts", "generated": "drafts", "pinned": true },
{ "name": "Inbox", "query": "tag:inbox", "pinned": true }
]
})"));
@@ -2377,18 +2389,28 @@ void TestConfig::aGeneratedEntryWritesNoRedundantKeys()
QVERIFY2(!sent.contains(QStringLiteral("flat")),
"the sent generator implies flat; storing it says nothing");
+ // Drafts is the second flat generator (item 159) and must be skipped by
+ // the same rule, not by a second one that could disagree with it.
+ const QJsonObject drafts = array.at(1).toObject();
+ QCOMPARE(drafts.value(QStringLiteral("generated")).toString(),
+ QStringLiteral("drafts"));
+ QVERIFY2(!drafts.contains(QStringLiteral("flat")),
+ "the drafts generator implies flat; storing it says nothing");
+
// The ordinary entry is untouched by any of that.
- const QJsonObject inbox = array.at(1).toObject();
+ const QJsonObject inbox = array.at(2).toObject();
QCOMPARE(inbox.value(QStringLiteral("query")).toString(),
QStringLiteral("tag:inbox"));
// And it all still reads back the same.
Config reloaded;
reloaded.load(path);
- QCOMPARE(reloaded.savedQueries().size(), 2);
+ QCOMPARE(reloaded.savedQueries().size(), 3);
QVERIFY(reloaded.savedQueries().at(0).isGenerated());
QVERIFY2(reloaded.savedQueries().at(0).flat,
"flat must come back from the generator, not from the file");
+ QVERIFY2(reloaded.savedQueries().at(1).flat,
+ "drafts must come back flat too, from the same rule");
}
void TestConfig::anAccountWithoutASendCommandIsReceiveOnly()
@@ -2577,5 +2599,74 @@ void TestConfig::unrecognisedQuotePositionWarnsAndFallsBackToBelow()
"an unrecognised quote_position was accepted silently");
}
+void TestConfig::theSignatureKeysAreRead()
+{
+ QTemporaryDir dir;
+ Config config;
+ config.load(writeIni(dir, QStringLiteral(
+ "[compose]\n"
+ "signature=work\n"
+ "signature_position=above_quote\n")));
+
+ QCOMPARE(config.compose().signature, QStringLiteral("work"));
+ QVERIFY2(config.compose().signaturePosition
+ == Signatures::Position::AboveQuote,
+ "signature_position=above_quote was not read");
+}
+
+void TestConfig::anAccountSignatureOverridesTheComposeDefault()
+{
+ QTemporaryDir dir;
+ Config config;
+ config.load(writeIni(dir, QStringLiteral(
+ "[compose]\n"
+ "signature=work\n"
+ "\n"
+ "[account.personal]\n"
+ "name=Test User\n"
+ "address=user@example.org\n"
+ "maildir=personal-mail\n"
+ "trash=Trash\n"
+ "signature=brief\n"
+ "\n"
+ "[account.other]\n"
+ "name=Test User\n"
+ "address=other@example.org\n"
+ "maildir=other-mail\n"
+ "trash=Trash\n")));
+
+ // The account SEEDS the choice; it does not own the signature. The key is
+ // a starting value and the switch keeps every signature reachable.
+ QCOMPARE(config.account(QStringLiteral("personal")).signature,
+ QStringLiteral("brief"));
+ // An account with no key of its own carries none, and the caller falls
+ // through to the [compose] default rather than this being resolved here.
+ QVERIFY2(config.account(QStringLiteral("other")).signature.isEmpty(),
+ "an account with no signature key must not inherit the "
+ "[compose] one: the composer resolves the fallback, not Config");
+ QCOMPARE(config.compose().signature, QStringLiteral("work"));
+}
+
+void TestConfig::aMalformedSignaturePositionIsReportedAndFallsBack()
+{
+ // Present and malformed is REPORTED, matching quote_position. A silent
+ // value(key, default) would accept "abov" as above_quote.
+ QTemporaryDir dir;
+ Config config;
+ config.load(writeIni(dir, QStringLiteral(
+ "[compose]\n"
+ "signature_position=abov\n")));
+
+ QVERIFY2(config.compose().signaturePosition == Signatures::Position::End,
+ "an unrecognised signature_position must still fall back to End");
+ bool reported = false;
+ for (const QString &problem : config.problems()) {
+ if (problem.contains(QStringLiteral("signature_position")))
+ reported = true;
+ }
+ QVERIFY2(reported,
+ "an unrecognised signature_position was accepted silently");
+}
+
QTEST_MAIN(TestConfig)
#include "test_config.moc"
diff --git a/tests/test_notmuchworker.cpp b/tests/test_notmuchworker.cpp
index 998696f..d02f8bd 100644
--- a/tests/test_notmuchworker.cpp
+++ b/tests/test_notmuchworker.cpp
@@ -93,6 +93,10 @@ private slots:
void moveMessagesGivesTheFileAFreshMaildirName();
void moveMessagesKeepsTheMaildirFlags();
+ void indexDraftFileMakesAFileFindable();
+ void indexDraftFileRemovesThePreviousFile();
+ void removeIndexedFileDropsTheEntry();
+
void aSplitIndexStillResolvesTheMailRoot();
void aSplitIndexMovesIntoTheMaildirNotTheIndex();
void aSplitIndexListsTheMaildirsFolders();
@@ -103,6 +107,9 @@ private:
/// Each of those takes its own message, because a move is destructive and
/// the fixture database is shared by every test in this class.
bool addMovableMessage(const QString &folder, const QString &messageId);
+ /// Writes a draft file into <folder>/cur with the "D" flag and returns its
+ /// path, WITHOUT indexing it, so a test can index just that file.
+ QString writeDraftFile(const QString &folder, const QString &messageId);
/// The single file backing `messageId`, or an empty string when the
/// database does not know the id.
QString fileOf(const QString &messageId,
@@ -215,6 +222,42 @@ bool TestNotmuchWorker::addMovableMessage(const QString &folder,
return m_fixture.index();
}
+QString TestNotmuchWorker::writeDraftFile(const QString &folder,
+ const QString &messageId)
+{
+ const QString dirPath = m_fixture.maildirPath() + QLatin1Char('/') + folder;
+ QDir dir;
+ if (!dir.mkpath(dirPath + QStringLiteral("/cur"))
+ || !dir.mkpath(dirPath + QStringLiteral("/new"))
+ || !dir.mkpath(dirPath + QStringLiteral("/tmp"))) {
+ return {};
+ }
+
+ // The same filename recipe addMessage() uses, with the draft flag instead
+ // of the seen flag, matching what DraftStore writes.
+ QString base = messageId;
+ base.remove(QLatin1Char('<')).remove(QLatin1Char('>'));
+ base.replace(QLatin1Char('@'), QLatin1Char('.'));
+ base.replace(QLatin1Char('/'), QLatin1Char('.'));
+ base += QStringLiteral(":2,D");
+
+ const QString path = dirPath + QStringLiteral("/cur/") + base;
+ QFile file(path);
+ if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
+ return {};
+ QTextStream out(&file);
+ out << "From: You <you@example.org>\n"
+ << "To: someone@example.org\n"
+ << "Subject: A draft\n"
+ << "Message-ID: <" << messageId << ">\n"
+ << "Date: Sun, 7 Jun 2026 10:00:00 +0000\n"
+ << "\n"
+ << "draft body\n";
+ out.flush();
+ file.close();
+ return path;
+}
+
QString TestNotmuchWorker::fileOf(const QString &messageId,
const QString &configPath)
{
@@ -1383,6 +1426,69 @@ void TestNotmuchWorker::moveMessagesReportsOnlyWhatMoved()
QCOMPARE(inTrash.size(), 1);
}
+void TestNotmuchWorker::indexDraftFileMakesAFileFindable()
+{
+ const QString id = QStringLiteral("draft1@example.org");
+ const QString path = writeDraftFile(QStringLiteral("drafts"), id);
+ QVERIFY(!path.isEmpty());
+
+ // On disk but not indexed: no query sees it, which is item 158's defect.
+ QCOMPARE(runQuery(QStringLiteral("id:%1").arg(id)).size(), 0);
+
+ NotmuchWorker worker(m_fixture.configPath());
+ QSignalSpy errors(&worker, &NotmuchWorker::errorOccurred);
+ worker.indexDraftFile(path);
+ QVERIFY2(errors.isEmpty(), qPrintable(errors.value(0).value(0).toString()));
+
+ QCOMPARE(runQuery(QStringLiteral("id:%1").arg(id)).size(), 1);
+}
+
+void TestNotmuchWorker::indexDraftFileRemovesThePreviousFile()
+{
+ const QString first = QStringLiteral("draft2@example.org");
+ const QString second = QStringLiteral("draft3@example.org");
+ const QString firstPath = writeDraftFile(QStringLiteral("drafts"), first);
+ QVERIFY(!firstPath.isEmpty());
+
+ NotmuchWorker worker(m_fixture.configPath());
+ QSignalSpy errors(&worker, &NotmuchWorker::errorOccurred);
+ worker.indexDraftFile(firstPath);
+ QVERIFY2(errors.isEmpty(), qPrintable(errors.value(0).value(0).toString()));
+ QCOMPARE(runQuery(QStringLiteral("id:%1").arg(first)).size(), 1);
+
+ // A rewrite: a new file (a fresh Message-ID) and the old one unlinked, as
+ // DraftStore does on every autosave. The old entry must not linger.
+ const QString secondPath = writeDraftFile(QStringLiteral("drafts"), second);
+ QVERIFY(!secondPath.isEmpty());
+ QVERIFY(QFile::remove(firstPath));
+
+ worker.indexDraftFile(secondPath, firstPath);
+ QVERIFY2(errors.isEmpty(), qPrintable(errors.value(0).value(0).toString()));
+
+ QCOMPARE(runQuery(QStringLiteral("id:%1").arg(second)).size(), 1);
+ QCOMPARE(runQuery(QStringLiteral("id:%1").arg(first)).size(), 0);
+}
+
+void TestNotmuchWorker::removeIndexedFileDropsTheEntry()
+{
+ const QString id = QStringLiteral("draft4@example.org");
+ const QString path = writeDraftFile(QStringLiteral("drafts"), id);
+ QVERIFY(!path.isEmpty());
+
+ NotmuchWorker worker(m_fixture.configPath());
+ QSignalSpy errors(&worker, &NotmuchWorker::errorOccurred);
+ worker.indexDraftFile(path);
+ QVERIFY2(errors.isEmpty(), qPrintable(errors.value(0).value(0).toString()));
+ QCOMPARE(runQuery(QStringLiteral("id:%1").arg(id)).size(), 1);
+
+ // The send path unlinks the draft and drops its entry, so it does not
+ // linger as a ghost until the next sync.
+ QVERIFY(QFile::remove(path));
+ worker.removeIndexedFile(path);
+ QVERIFY2(errors.isEmpty(), qPrintable(errors.value(0).value(0).toString()));
+ QCOMPARE(runQuery(QStringLiteral("id:%1").arg(id)).size(), 0);
+}
+
// Item 124. notmuch can put the Xapian index outside the mail root
// (`mail_root` + `path`), which is how the index moves to faster storage while
diff --git a/tests/test_signatures.cpp b/tests/test_signatures.cpp
new file mode 100644
index 0000000..47b404b
--- /dev/null
+++ b/tests/test_signatures.cpp
@@ -0,0 +1,294 @@
+/*
+ * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
+ * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include <QtTest>
+#include <QTemporaryDir>
+
+#include "signatures.h"
+
+class TestSignatures : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void namesAreTheFileStemsSorted();
+ void namesIgnoreFilesThatAreNotMarkdown();
+ void aMissingDirectoryHasNoNames();
+ void textIsTheFileContent();
+ void textOfAnUnknownNameIsEmpty();
+ void insertingAtTheEndAppendsAfterADelimiter();
+ void insertingAboveTheQuotePutsItBeforeTheFirstQuotedLine();
+ void insertingAboveTheQuoteWithNoQuoteIsTheSameAsEnd();
+ void insertingNothingLeavesTheBufferAlone();
+ void switchingReplacesAKnownSignature();
+ void switchingReplacesAKnownSignatureAboveAQuote();
+ void selectingNoneRemovesAKnownSignature();
+ void aBlockMatchingNoKnownSignatureIsNotRemoved();
+ void aDelimiterInsideTheQuoteIsNotTheSignature();
+ void aSignatureReadBackFromDiskIsReplaced();
+
+private:
+ /// Writes \p files as name -> content into a fresh temporary directory.
+ static void write(const QTemporaryDir &dir,
+ const QList<QPair<QString, QString>> &files);
+};
+
+void TestSignatures::write(const QTemporaryDir &dir,
+ const QList<QPair<QString, QString>> &files)
+{
+ for (const auto &entry : files) {
+ QFile file(dir.path() + QStringLiteral("/") + entry.first);
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
+ file.write(entry.second.toUtf8());
+ file.close();
+ }
+}
+
+void TestSignatures::namesAreTheFileStemsSorted()
+{
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ write(dir, { { QStringLiteral("work.md"), QStringLiteral("Work") },
+ { QStringLiteral("brief.md"), QStringLiteral("Brief") } });
+
+ QCOMPARE(Signatures::names(dir.path()),
+ QStringList({ QStringLiteral("brief"), QStringLiteral("work") }));
+}
+
+void TestSignatures::namesIgnoreFilesThatAreNotMarkdown()
+{
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ write(dir, { { QStringLiteral("work.md"), QStringLiteral("Work") },
+ { QStringLiteral("notes.txt"), QStringLiteral("Not one") },
+ { QStringLiteral("README"), QStringLiteral("Nor this") } });
+
+ QCOMPARE(Signatures::names(dir.path()),
+ QStringList({ QStringLiteral("work") }));
+}
+
+void TestSignatures::aMissingDirectoryHasNoNames()
+{
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ const QString missing = dir.path() + QStringLiteral("/nothing-here");
+
+ QVERIFY(Signatures::names(missing).isEmpty());
+}
+
+void TestSignatures::textIsTheFileContent()
+{
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ write(dir, { { QStringLiteral("work.md"),
+ QStringLiteral("Jane Doe\n**qtmaildir**\n") } });
+
+ QCOMPARE(Signatures::text(dir.path(), QStringLiteral("work")),
+ QStringLiteral("Jane Doe\n**qtmaildir**\n"));
+}
+
+void TestSignatures::textOfAnUnknownNameIsEmpty()
+{
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+
+ QVERIFY(Signatures::text(dir.path(), QStringLiteral("absent")).isEmpty());
+}
+
+void TestSignatures::insertingAtTheEndAppendsAfterADelimiter()
+{
+ const QString buffer = QStringLiteral("Hello.\n");
+
+ const QString result = Signatures::replace(
+ buffer, QStringLiteral("Jane Doe"), {}, Signatures::Position::End);
+
+ QCOMPARE(result, QStringLiteral("Hello.\n\n-- \nJane Doe"));
+}
+
+void TestSignatures::insertingAboveTheQuotePutsItBeforeTheFirstQuotedLine()
+{
+ const QString buffer = QStringLiteral(
+ "My reply.\n"
+ "\n"
+ "On Mon, someone wrote:\n"
+ "> the original\n"
+ "> second line\n");
+
+ const QString result = Signatures::replace(
+ buffer, QStringLiteral("Jane Doe"), {},
+ Signatures::Position::AboveQuote);
+
+ // Before the QUOTED lines, and the attribution stays with the quote it
+ // introduces: it is the line the quote hangs from, not part of the reply.
+ QCOMPARE(result, QStringLiteral(
+ "My reply.\n"
+ "\n"
+ "-- \n"
+ "Jane Doe\n"
+ "\n"
+ "On Mon, someone wrote:\n"
+ "> the original\n"
+ "> second line\n"));
+}
+
+void TestSignatures::insertingAboveTheQuoteWithNoQuoteIsTheSameAsEnd()
+{
+ const QString buffer = QStringLiteral("A new message.\n");
+
+ const QString above = Signatures::replace(
+ buffer, QStringLiteral("Jane Doe"), {},
+ Signatures::Position::AboveQuote);
+ const QString end = Signatures::replace(
+ buffer, QStringLiteral("Jane Doe"), {}, Signatures::Position::End);
+
+ QCOMPARE(above, end);
+}
+
+void TestSignatures::insertingNothingLeavesTheBufferAlone()
+{
+ const QString buffer = QStringLiteral("Hello.\n");
+
+ QCOMPARE(Signatures::replace(buffer, QString(), {},
+ Signatures::Position::End),
+ buffer);
+}
+
+void TestSignatures::switchingReplacesAKnownSignature()
+{
+ const QStringList known = { QStringLiteral("Jane Doe"),
+ QStringLiteral("Jane Doe\nqtmaildir") };
+ const QString buffer = QStringLiteral("Hello.\n\n-- \nJane Doe");
+
+ const QString result = Signatures::replace(
+ buffer, QStringLiteral("Jane Doe\nqtmaildir"), known,
+ Signatures::Position::End);
+
+ QCOMPARE(result,
+ QStringLiteral("Hello.\n\n-- \nJane Doe\nqtmaildir"));
+}
+
+void TestSignatures::switchingReplacesAKnownSignatureAboveAQuote()
+{
+ const QStringList known = { QStringLiteral("Jane Doe"),
+ QStringLiteral("Brief") };
+ const QString buffer = QStringLiteral(
+ "My reply.\n"
+ "\n"
+ "-- \n"
+ "Jane Doe\n"
+ "\n"
+ "On Mon, someone wrote:\n"
+ "> the original\n");
+
+ const QString result = Signatures::replace(
+ buffer, QStringLiteral("Brief"), known,
+ Signatures::Position::AboveQuote);
+
+ QCOMPARE(result, QStringLiteral(
+ "My reply.\n"
+ "\n"
+ "-- \n"
+ "Brief\n"
+ "\n"
+ "On Mon, someone wrote:\n"
+ "> the original\n"));
+}
+
+void TestSignatures::selectingNoneRemovesAKnownSignature()
+{
+ const QStringList known = { QStringLiteral("Jane Doe") };
+ const QString buffer = QStringLiteral("Hello.\n\n-- \nJane Doe");
+
+ const QString result = Signatures::replace(
+ buffer, QString(), known, Signatures::Position::End);
+
+ QCOMPARE(result, QStringLiteral("Hello.\n"));
+}
+
+void TestSignatures::aBlockMatchingNoKnownSignatureIsNotRemoved()
+{
+ // THE test for the data-loss guard, and it must not be dropped. A "-- "
+ // reaches a buffer without the user ever choosing a signature, pasted in
+ // with quoted text from another client. Replacing from there would delete
+ // everything after it silently.
+ const QStringList known = { QStringLiteral("Jane Doe") };
+ const QString buffer = QStringLiteral(
+ "Hello.\n"
+ "\n"
+ "-- \n"
+ "text the user pasted and wants to keep");
+
+ const QString result = Signatures::replace(
+ buffer, QStringLiteral("Jane Doe"), known, Signatures::Position::End);
+
+ // The user's text survives, and the signature is ADDED. A wrong guess
+ // produces a visible duplicate, never a deletion.
+ QVERIFY(result.contains(
+ QStringLiteral("text the user pasted and wants to keep")));
+ QVERIFY(result.endsWith(QStringLiteral("-- \nJane Doe")));
+}
+
+void TestSignatures::aDelimiterInsideTheQuoteIsNotTheSignature()
+{
+ // The quoted original carries the sender's own signature, quoted. A tail
+ // rule would find it, and under End it would append after it; the block
+ // must not be treated as this message's signature whichever way it goes.
+ //
+ // This test DOCUMENTS the case rather than pinning it, and that is worth
+ // knowing before trying to strengthen it. Two mutations were measured
+ // against it and both stayed green: trimming the delimiter comparison so
+ // that "> -- " matches, and making the quoted text one of the known
+ // signatures so the match guard could not be what refuses the removal.
+ // Neither changes the output, because blockEnd() stops the block at the
+ // quote, so the quoted signature survives whether or not the delimiter
+ // inside it is recognised. The behaviour is correct under both, and no
+ // assertion on the result can separate them.
+ const QStringList known = { QStringLiteral("Jane Doe") };
+ const QString buffer = QStringLiteral(
+ "My reply.\n"
+ "\n"
+ "On Mon, someone wrote:\n"
+ "> the original\n"
+ "> -- \n"
+ "> Their Name\n");
+
+ const QString result = Signatures::replace(
+ buffer, QStringLiteral("Jane Doe"), known, Signatures::Position::End);
+
+ QVERIFY(result.contains(QStringLiteral("> -- \n> Their Name")));
+ QVERIFY(result.endsWith(QStringLiteral("-- \nJane Doe")));
+}
+
+void TestSignatures::aSignatureReadBackFromDiskIsReplaced()
+{
+ // known here is what knownSignatures() produces: text() verbatim, carrying
+ // the trailing newline every editor writes into a file. The block scan
+ // treats a trailing blank line as separation rather than text, so a naive
+ // match compares "Jane Doe" against "Jane Doe\n" and silently fails, and
+ // switching then APPENDS a second signature instead of replacing the first.
+ const QStringList known = { QStringLiteral("Jane Doe\n") };
+ const QString buffer = QStringLiteral("Hello.\n\n-- \nJane Doe\n");
+
+ const QString result = Signatures::replace(
+ buffer, QStringLiteral("Brief"), known, Signatures::Position::End);
+
+ QCOMPARE(result, QStringLiteral("Hello.\n\n-- \nBrief"));
+}
+
+QTEST_MAIN(TestSignatures)
+#include "test_signatures.moc"
diff --git a/translations/qtmaildir_it_IT.ts b/translations/qtmaildir_it_IT.ts
index 1b0e756..a9c0f88 100644
--- a/translations/qtmaildir_it_IT.ts
+++ b/translations/qtmaildir_it_IT.ts
@@ -99,10 +99,22 @@
<translation>Invia il messaggio come testo semplice con una versione HTML a fianco. Il testo semplice è quello che hai scritto.</translation>
</message>
<message>
+ <source>Signature</source>
+ <translation>Firma</translation>
+ </message>
+ <message>
+ <source>Chooses the signature added to this message.</source>
+ <translation>Sceglie la firma da aggiungere a questo messaggio.</translation>
+ </message>
+ <message>
<source>Send</source>
<translation>Invia</translation>
</message>
<message>
+ <source>None</source>
+ <translation>Nessuna</translation>
+ </message>
+ <message>
<source>Large attachment</source>
<translation>Allegato di grandi dimensioni</translation>
</message>
@@ -198,6 +210,10 @@ Il messaggio È stato inviato. Non inviarlo di nuovo.</translation>
<translation>[compose] quote_position &apos;%1&apos; non è riconosciuto; atteso above o below. Uso below.</translation>
</message>
<message>
+ <source>[compose] signature_position &apos;%1&apos; is not recognised; expected end or above_quote. Using end.</source>
+ <translation>[compose] signature_position &apos;%1&apos; non è riconosciuto; atteso end o above_quote. Uso end.</translation>
+ </message>
+ <message>
<source>[compose] autosave_interval_ms &apos;%1&apos; is not a number; using %2.</source>
<translation>[compose] autosave_interval_ms &apos;%1&apos; non è un numero; verrà usato %2.</translation>
</message>