Skip to contentSkip to conversation

Improve email quote trimming

PATCH Applied Jason Gunthorpe 2 participants 6 messages Sep 7 – Sep 15

lore
Share & tools
lore
#0 lore raw

v2 cover Improve email quote trimming

Patches to make the automatic trimming more versatile and work in more cases.

I would, broadly, like to edit the messages without editing or removing any of the existing quoting. This is because I tend to make a few passes at things and once quoted text is deleted it is a huge PITA to bring it back.

Introduce a >--cut-- marker which tells b4 to cut the quoting and then b4 can reassemble the message similarly to if the editor macros had been used.

Along the way fix a few corner cases in the email construction that resulted in sub optimal email generation.

It took a while to get this generating emails the way I think it should, I've included several of the cases that didn't obviously work as permanent tests.

Include some very basic support for emacs to generate and highlight the cut marker.

I've opted to leave the existing editor support for cutting out quoted lines alone, but I think it would be better if it could use editor folding and the cut marker instead. That's far beyond me though :)

v2:
- Rebase
- Change cut to >--cut--
- Add some basic emacs support
- Consider mixed > and | quotes when trimming the reply for a trailer
v1: https://patch.msgid.link/r/[email protected]

Jason Gunthorpe (4):
review: trim trailing quoted when adding a tag
review: discard blank lines between | and > quotes when trimming
review: add >--cut-- inline marker to snip quoted reply context
review: emacs: highlighting and keystroke for >--cut--

 docs/maintainer/review.rst       |  24 +++
 docs/releases.rst                |   9 +-
 misc/emacs/b4-review-mode.el     |  32 ++++
 src/b4/review/_review.py         | 150 ++++++++++++---
 src/b4/review_tui/_review_app.py |  10 +-
 src/tests/test_review.py         | 317 +++++++++++++++++++++++++++++++
 src/tests/test_tui_review.py     |  69 +++++++
 7 files changed, 586 insertions(+), 25 deletions(-)

base-commit: c363dd22f0f87689b63d6d32fb65bf07b73d6e66

Signature · 1 line
2.43.0
#1 lore raw

PATCH v2 1/4 review: trim trailing quoted when adding a tag

If some comments are added and then a review tag is placed the trailing quote that is normally trimmed is instead retained with the trailer landing at the end of the message. Instead place it right after the last user comment. Skip both > and | quoted sections.

Assisted-by LLM
---
 src/b4/review/_review.py | 18 +++++++++++++++---
 src/tests/test_review.py | 34 ++++++++++++++++++++++++++++++++++
 2 files changed, 49 insertions(+), 3 deletions(-)
src/b4/review/_review.py +15 -3
index a37533230f484a..96f3e5bbd54130 100644
@@ -3297,13 +3297,25 @@ def _insert_trailer_in_reply(reply_text: str, trailer: str) -> str:
     """Append *trailer* as its own bare line in the reply buffer.
 
     The line is added at the end of the maintainer's content, before any
-    trailing ``-- `` signature, grouped with any trailers already there.  The
-    maintainer can move it afterwards — placement is just a sensible default.
+    trailing quoted context or ``-- `` signature, grouped with any trailers
+    already there.  Keeping a trailing quote below the trailer lets the
+    ordinary send-time trimming discard it.  The maintainer can move the
+    trailer afterwards — placement is just a sensible default.
     """
     lines = _normalize_line_endings(reply_text).split('\n')
     sig_idx = next((i for i, ln in enumerate(lines) if ln == '-- '), len(lines))
     head = lines[:sig_idx]
     tail = lines[sig_idx:]
+    quoted_tail: List[str] = []
+    quote_start = len(head)
+    while quote_start and (
+        head[quote_start - 1].startswith(('>', '|'))
+        or not head[quote_start - 1].strip()
+    ):
+        quote_start -= 1
+    if any(line.startswith('>') for line in head[quote_start:]):
+        quoted_tail = head[quote_start:]
+        head = head[:quote_start]
     while head and not head[-1].strip():
         head.pop()
     # Separate from non-trailer content with a blank line so the trailers
@@ -3311,7 +3323,7 @@ def _insert_trailer_in_reply(reply_text: str, trailer: str) -> str:
     if head and not _BARE_TRAILER_RE.match(head[-1]):
         head.append('')
     head.append(trailer)
-    return '\n'.join(head + tail)
+    return '\n'.join(head + quoted_tail + tail)
 
 
 def _remove_trailer_from_reply(reply_text: str, name: str) -> str:
src/tests/test_review.py +34 -0
index 460cfb9b65196d..eb7e36c52eeebb 100644
@@ -909,6 +909,40 @@ class TestReplyTrailerEditing:
         # No blank line inserted between the two trailers.
         assert 'Reviewed-by: Me <[email protected]>\nTested-by: Me <[email protected]>' in out
 
+    def test_insert_before_trailing_quote(self) -> None:
+        buf = 'Please fix this.\n\n> context left below my message\n> +old code\n'
+        trailer = 'Reviewed-by: Me <[email protected]>'
+        out = review._insert_trailer_in_reply(buf, trailer)
+        assert out == (
+            'Please fix this.\n\n'
+            'Reviewed-by: Me <[email protected]>\n'
+            '\n'
+            '> context left below my message\n'
+            '> +old code\n'
+        )
+        assert review._trim_quoted_reply(out) == 'Please fix this.\n\n' + trailer
+
+    def test_insert_before_trailing_quote_with_external_review(self) -> None:
+        buf = (
+            'Please fix this.\n'
+            '\n'
+            '> context before external feedback\n'
+            '\n'
+            '| Bot <[email protected]>:\n'
+            '|\n'
+            '| An external finding.\n'
+            '\n'
+            '> context after external feedback\n'
+        )
+        trailer = 'Reviewed-by: Me <[email protected]>'
+
+        out = review._insert_trailer_in_reply(buf, trailer)
+
+        # The external-review block is scaffolding inside one trailing quoted
+        # run.  Adding a trailer must not split that run and make the quoted
+        # context before the external finding survive send-time trimming.
+        assert review._trim_quoted_reply(out) == 'Please fix this.\n\n' + trailer
+
     def test_remove_drops_matching_bare_line(self) -> None:
         buf = 'Thanks!\n\nReviewed-by: Me <[email protected]>\nAcked-by: Me <[email protected]>'
         out = review._remove_trailer_from_reply(buf, 'reviewed-by')
Signature · 1 line
2.43.0
#2 lore raw

PATCH v2 2/4 review: discard blank lines between | and > quotes when trimming

In reply to Jason Gunthorpe

When b4 constructs the email to respond to it inserts the | quoted (eg sashiko) text in the > flow with blank lines between sections. When it generates the final email it strips the | quoted text but retains the blank lines it added. Thus the email ends up with random blank lines inside the quoted text blocks.

Remove the blank lines along with the | blocks, being careful not to disturb user text.

Assisted-by LLM
---
 src/b4/review/_review.py | 52 +++++++++++++++++++++++++++++++++++++---
 src/tests/test_review.py | 26 ++++++++++++++++++++
 2 files changed, 75 insertions(+), 3 deletions(-)
src/b4/review/_review.py +49 -3
index 96f3e5bbd54130..054be896053e87 100644
@@ -3383,6 +3383,54 @@ def _sync_reply_trailers(reply_text: str, selected: List[str], identity: str) ->
     return reply_text
 
 
+def _strip_external_reviewer_lines(lines: List[str]) -> List[str]:
+    """Remove read-only external-review blocks without leaving quote gaps.
+
+    Rendering puts bare blank separators around ``|``-prefixed external
+    comments.  When both sides of a separator are quoted diff, it belongs to
+    that presentation block and must leave with the comment.  A separator
+    after maintainer text is retained exactly, since it is part of their reply
+    layout rather than the external review's quote padding.
+    """
+    result: List[str] = []
+    index = 0
+    while index < len(lines):
+        if not lines[index].startswith('|'):
+            result.append(lines[index])
+            index += 1
+            continue
+
+        # A leading separator belongs to an external block only when it
+        # separates that block from quoted diff.  Do not alter the same blank
+        # after the maintainer's own text.
+        previous = len(result) - 1
+        while previous >= 0 and not result[previous].strip():
+            previous -= 1
+        if previous >= 0 and result[previous].startswith('>'):
+            del result[previous + 1 :]
+
+        # Treat adjacent external blocks as one block.  Their intervening
+        # blanks are presentation padding too.
+        while index < len(lines) and lines[index].startswith('|'):
+            index += 1
+            blank_end = index
+            while blank_end < len(lines) and not lines[blank_end].strip():
+                blank_end += 1
+            if blank_end < len(lines) and lines[blank_end].startswith('|'):
+                index = blank_end
+                continue
+            if blank_end < len(lines) and lines[blank_end].startswith('>'):
+                # The following quoted context is already separated by its
+                # quote prefix; do not leave the external block's gap behind.
+                index = blank_end
+            else:
+                result.extend(lines[index:blank_end])
+                index = blank_end
+            break
+
+    return result
+
+
 def _trim_quoted_reply(buffer: str) -> str:
     """Prepare a hand-edited reply buffer for sending.
 
@@ -3395,9 +3443,7 @@ def _trim_quoted_reply(buffer: str) -> str:
     maintainer left in place anywhere above their final comment is kept
     exactly as written; nothing is collapsed, reordered, or relocated.
     """
-    lines = [
-        line for line in _strip_instruction_header(buffer) if not line.startswith('|')
-    ]
+    lines = _strip_external_reviewer_lines(_strip_instruction_header(buffer))
     # Drop the trailing quoted/blank run below the maintainer's last comment.
     end = len(lines)
     while end > 0 and (lines[end - 1].startswith('>') or not lines[end - 1].strip()):
src/tests/test_review.py +26 -0
index eb7e36c52eeebb..a2c8703024674c 100644
@@ -861,6 +861,32 @@ class TestTrimQuotedReply:
     def test_empty_buffer(self) -> None:
         assert review._trim_quoted_reply('') == ''
 
+    def test_removes_external_gaps_inside_quoted_diff(self) -> None:
+        buffer = (
+            '> first quoted line\n'
+            '\n'
+            '| sashiko.dev <[email protected]>:\n'
+            '|\n'
+            '| An external finding.\n'
+            '|\n'
+            '| via: https://sashiko.dev/#/message/example\n'
+            '\n'
+            '> second quoted line\n'
+            '\n'
+            '| another reviewer <[email protected]>:\n'
+            '|\n'
+            '| Another external finding.\n'
+            '\n'
+            '> third quoted line\n'
+            'My maintainer comment.\n'
+        )
+        assert review._trim_quoted_reply(buffer) == (
+            '> first quoted line\n'
+            '> second quoted line\n'
+            '> third quoted line\n'
+            'My maintainer comment.'
+        )
+
 
 class TestParseReplyTrailers:
     """Tests for _parse_reply_trailers() — derived trailer display index."""
Signature · 1 line
2.43.0
#3 lore raw

PATCH v2 3/4 review: add >--cut-- inline marker to snip quoted reply context

In reply to Jason Gunthorpe

When adding review comments to a message it is very inconvenient to permanently lose the quotable text. Often I will make several passes over a series and the nice b4 behavior of keeping everything in draft encourages coming back and making revisions and further comments.

However, if the quoted text has been erased that isn't possible.

Instead of erasing in the editor provide a full line marker '>--cut--' for b4 to automagically do the trimming similar to how it trims unused quote at the end. Trailing text after user lines and till the marker is removed similar to the trailing text.

This way the message can be sliced and minimally quoted appropriately with no loss of quoted text. Everything can be selectively undone by the user.

Assisted-by LLM
---
 docs/maintainer/review.rst       |  24 +++
 docs/releases.rst                |   9 +-
 src/b4/review/_review.py         |  82 ++++++++--
 src/b4/review_tui/_review_app.py |  10 +-
 src/tests/test_review.py         | 257 +++++++++++++++++++++++++++++++
 src/tests/test_tui_review.py     |  69 +++++++++
 6 files changed, 431 insertions(+), 20 deletions(-)
docs/maintainer/review.rst +24 -0
index ca0632696b1b0b..7ac39322ea2b0c 100644
@@ -584,6 +584,30 @@ cyan, external ``|`` comments visually bracketed, and your own comments
 in the default foreground. Spell checking is limited to your own
 comment lines.
 
+**Trimming quoted context (any editor)**
+
+No editor plugin is required to prune a run of quoted context. Put the
+following marker alone on a line after the quoted lines you want to discard::
+
+    >--cut--
+
+When the reply is sent, b4 removes the contiguous run of quoted lines above
+the marker, stopping at your last unquoted note, and replaces it with the
+same breadcrumb used by the Vim and Emacs trimming commands::
+
+    > [ ... 42 lines skipped ... ]
+
+Quoted context below the marker is left untouched. Only ``>``-quoted lines
+contribute to the count, so your own notes are always boundaries and can
+never be discarded. If you type the marker while the cursor is still in the
+quoted flow, ``> >--cut--`` is accepted as an equivalent spelling.
+
+Hand-typed markers and the Vim/Emacs commands produce identical output and
+coalesce with each other. If a plugin-generated breadcrumb is immediately
+above ``>--cut--``, its recorded count is absorbed into the new breadcrumb instead
+of leaving two markers. This works in both the main review reply editor and
+the follow-up quick-reply editor.
+
 *Vim*
 
 Copy or symlink the files into your Vim configuration::
docs/releases.rst +8 -1
index 4bff1b05645728..2b16efb72d7ace 100644
@@ -40,6 +40,14 @@ the full reference.
 Several notable improvements to the ``b4 review`` workflow shipped this
 cycle, building on the v0.15 foundation.
 
+**Inline snip markers in review replies**
+
+In any editor, put ``>--cut--`` alone on a line to discard the run of quoted
+context above it back to your last note. B4 replaces the run with the same
+``> [ ... NN lines skipped ... ]`` breadcrumb produced by the Vim and Emacs
+review helpers. The marker also works in follow-up quick replies, and existing
+breadcrumbs coalesce into its skipped-line count.
+
 **Manual revision linking**
 
 When automatic revision discovery fails — for example, a submitter sent
@@ -628,4 +636,3 @@ reviewing patches, testing, and contributing code:
 - Rob Herring
 - Tamir Duberstein
 - Toke Høiland-Jørgensen
-
src/b4/review/_review.py +65 -17

125 lines not on this page · raw message

src/b4/review_tui/_review_app.py +8 -2
index e1082e94c54f4a..d7a6bda1c3b4e5 100644
@@ -1850,7 +1850,12 @@ class ReviewApp(LoreNodeShutdownMixin, CheckRunnerMixin, App[None]):
             orig_author = entry.get('fromname', '') or entry.get('fromemail', '')
             body = entry.get('body', '')
             quoted = '\n'.join(f'> {line}' for line in body.splitlines())
-            editor_text = f'On {orig_date}, {orig_author} wrote:\n{quoted}\n\n'
+            editor_text = (
+                '# Put ">--cut--" alone on a line to discard quoted context above it\n'
+                '# back to your last note; b4 resolves it when you send.\n'
+                '#\n'
+                f'On {orig_date}, {orig_author} wrote:\n{quoted}\n\n'
+            )
 
         result = suspend_and_edit(
             self, editor_text.encode(), 'reply.eml', topdir=self._topdir
@@ -1872,7 +1877,8 @@ class ReviewApp(LoreNodeShutdownMixin, CheckRunnerMixin, App[None]):
 
     def _send_followup_reply(self, entry: Dict[str, Any], text: str) -> None:
         """Build and immediately send a quick reply to a follow-up message."""
-        msg = entry['lmsg'].make_reply(text)
+        reply_text = b4.review._trim_quoted_reply(text)
+        msg = entry['lmsg'].make_reply(reply_text)
         try:
             with self.suspend():
                 smtp, fromaddr = b4.get_smtp(dryrun=self._email_dryrun)
src/tests/test_review.py +257 -0

269 lines not on this page · raw message

src/tests/test_tui_review.py +69 -0

81 lines not on this page · raw message

Signature · 1 line
2.43.0
#4 lore raw

PATCH v2 4/4 review: emacs: highlighting and keystroke for >--cut--

In reply to Jason Gunthorpe

Add a default highlighting in yellow for the cut marker and bind an automatic insertion to C-c C-x.

---
 misc/emacs/b4-review-mode.el | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
misc/emacs/b4-review-mode.el +32 -0
index c2342ff29bdf4b..81b49079efd630 100644
@@ -111,6 +111,11 @@ whole-line deletion worth a breadcrumb.")
   "Face for instruction lines (# ...)."
   :group 'b4-review)
 
+(defface b4-review-cut-marker
+  '((t :foreground "yellow" :weight bold))
+  "Face for a \">--cut--\" snip marker line."
+  :group 'b4-review)
+
 (defface b4-review-quote-background
   '((t :inherit default :extend t))
   "Background face for prefixed lines (`> ' quotes, `| ' external comments,
@@ -125,6 +130,17 @@ on every line — without it, the fill stops at the last character."
   "Background face for the reviewer's own, unprefixed comment lines."
   :group 'b4-review)
 
+(defface b4-review-cut-background
+  '((t :inherit default :extend t))
+  "Background face for a \">--cut--\" snip marker line.
+Applied the same way as `b4-review-quote-background' /
+`b4-review-own-background' so the marker line can be set off with its own
+background, e.g.:
+
+  (custom-set-faces
+   \\='(b4-review-cut-background ((t :background \"dark red\"))))"
+  :group 'b4-review)
+
 (defvar b4-review-font-lock-keywords
   `(
     ;; Order matters — earlier rules take priority in Emacs font-lock
@@ -153,6 +169,10 @@ on every line — without it, the fill stops at the last character."
      (2 'b4-review-diff-file)
      (3 'b4-review-diff-file))
 
+    ;; Snip marker, quoted or bare — checked before the plain-quoted catch-all
+    ;; below so it isn't swallowed by that more general rule.
+    ("^\\(?:> \\)?>--cut--[ \t]*$" (0 'b4-review-cut-marker))
+
     ;; Plain quoted lines (catch-all for > lines not matched above)
     ("^\\(> \\)\\(.*\\)$"
      (1 'b4-review-quote-prefix)
@@ -173,6 +193,9 @@ on every line — without it, the fill stops at the last character."
     ;; itself, and `:extend t' on these two faces (see their defface above)
     ;; is what makes the display fill the rest of the line's width with that
     ;; face's background instead of stopping at the last glyph.
+    ;; Checked ahead of the general quote-background rule below so its
+    ;; :background wins over `b4-review-quote-background' on the marker line.
+    ("^\\(?:> \\)?>--cut--[ \t]*\n?" (0 'b4-review-cut-background append))
     ("^>.*\n?" (0 'b4-review-quote-background append))
     ("^|.*\n?" (0 'b4-review-quote-background append))
     ("^#.*\n?" (0 'b4-review-quote-background append))
@@ -419,11 +442,20 @@ the comment text in place under the same diff line, ready to edit."
       (when lines
         (insert (mapconcat #'identity lines "\n") "\n")))))
 
+(defun b4-review-add-cut ()
+  "Insert a cut marker that will remove itself and everything
+before until the previous user comment. The current line is
+placed in the removed area before the cut marker."
+  (interactive)
+  (end-of-line)
+  (insert "\n>--cut--"))
+
 (defvar b4-review-mode-map
   (let ((map (make-sparse-keymap)))
     (define-key map (kbd "C-c C-k") #'b4-review-delete-hunk)
     (define-key map (kbd "C-c C-b") #'b4-review-delete-hunks-before)
     (define-key map (kbd "C-c C-a") #'b4-review-adopt-comment)
+    (define-key map (kbd "C-c C-x") #'b4-review-add-cut)
     map)
   "Keymap for `b4-review-mode'.")
 
Signature · 1 line
2.43.0
#5 lore raw
In reply to Jason Gunthorpe
Quoted 11 lines · Jason Gunthorpe

Improve email quote trimming

Patches to make the automatic trimming more versatile and work in more cases.

I would, broadly, like to edit the messages without editing or removing any of the existing quoting. This is because I tend to make a few passes at things and once quoted text is deleted it is a huge PITA to bring it back.

[...]

Applied, thanks!

[1/4] review: trim trailing quoted when adding a tag

      commit: e00132591ea197066d91ba5c544d13b74e130131
[2/4] review: discard blank lines between | and > quotes when trimming
      commit: edc429c7b94a0c2f8df29cfcc00cf098d1761e55
[3/4] review: add >--cut-- inline marker to snip quoted reply context
      commit: 2a08c80c79db82a195ec88481a2ca9ff93f1e810
[4/4] review: emacs: highlighting and keystroke for >--cut--
      commit: 3386befc548a13bbe4b743b7d831267f5569cfd4

Best regards,

Signature · 1 line
Konstantin Ryabitsev <[email protected]>