]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-wash.el
d6db4fa290970dd9bf851bd002f08f5e06fdc77d
[notmuch] / emacs / notmuch-wash.el
1 ;; notmuch-wash.el --- cleaning up message bodies
2 ;;
3 ;; Copyright © Carl Worth
4 ;; Copyright © David Edmondson
5 ;;
6 ;; This file is part of Notmuch.
7 ;;
8 ;; Notmuch is free software: you can redistribute it and/or modify it
9 ;; under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12 ;;
13 ;; Notmuch is distributed in the hope that it will be useful, but
14 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 ;; General Public License for more details.
17 ;;
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with Notmuch.  If not, see <http://www.gnu.org/licenses/>.
20 ;;
21 ;; Authors: Carl Worth <cworth@cworth.org>
22 ;;          David Edmondson <dme@dme.org>
23
24 (require 'coolj)
25
26 (declare-function notmuch-show-insert-bodypart "notmuch-show" (msg part depth))
27
28 ;;
29
30 (defvar notmuch-wash-signature-regexp
31   "^\\(-- ?\\|_+\\)$"
32   "Pattern to match a line that separates content from signature.")
33
34 (defvar notmuch-wash-citation-regexp
35   "\\(^[[:space:]]*>.*\n\\)+"
36   "Pattern to match citation lines.")
37
38 (defvar notmuch-wash-original-regexp "^\\(--+\s?[oO]riginal [mM]essage\s?--+\\)$"
39   "Pattern to match a line that separates original message from reply in top-posted message.")
40
41 (defvar notmuch-wash-button-signature-hidden-format
42   "[ %d-line signature. Click/Enter to show. ]"
43   "String used to construct button text for hidden signatures.
44 Can use up to one integer format parameter, i.e. %d")
45
46 (defvar notmuch-wash-button-signature-visible-format
47   "[ %d-line signature. Click/Enter to hide. ]"
48   "String used to construct button text for visible signatures.
49 Can use up to one integer format parameter, i.e. %d")
50
51 (defvar notmuch-wash-button-citation-hidden-format
52   "[ %d more citation lines. Click/Enter to show. ]"
53   "String used to construct button text for hidden citations.
54 Can use up to one integer format parameter, i.e. %d")
55
56 (defvar notmuch-wash-button-citation-visible-format
57   "[ %d more citation lines. Click/Enter to hide. ]"
58   "String used to construct button text for visible citations.
59 Can use up to one integer format parameter, i.e. %d")
60
61 (defvar notmuch-wash-button-original-hidden-format
62   "[ %d-line hidden original message. Click/Enter to show. ]"
63   "String used to construct button text for hidden citations.
64 Can use up to one integer format parameter, i.e. %d")
65
66 (defvar notmuch-wash-button-original-visible-format
67   "[ %d-line original message. Click/Enter to hide. ]"
68   "String used to construct button text for visible citations.
69 Can use up to one integer format parameter, i.e. %d")
70
71 (defvar notmuch-wash-signature-lines-max 12
72   "Maximum length of signature that will be hidden by default.")
73
74 (defvar notmuch-wash-citation-lines-prefix 3
75   "Always show at least this many lines from the start of a citation.
76
77 If there is one more line than the sum of
78 `notmuch-wash-citation-lines-prefix' and
79 `notmuch-wash-citation-lines-suffix', show that, otherwise
80 collapse the remaining lines into a button.")
81
82 (defvar notmuch-wash-citation-lines-suffix 3
83   "Always show at least this many lines from the end of a citation.
84
85 If there is one more line than the sum of
86 `notmuch-wash-citation-lines-prefix' and
87 `notmuch-wash-citation-lines-suffix', show that, otherwise
88 collapse the remaining lines into a button.")
89
90 (defvar notmuch-wash-wrap-lines-length nil
91   "Wrap line after at most this many characters.
92
93 If this is nil, lines in messages will be wrapped to fit in the
94 current window. If this is a number, lines will be wrapped after
95 this many characters or at the window width (whichever one is
96 lower).")
97
98 (defun notmuch-wash-toggle-invisible-action (cite-button)
99   ;; Toggle overlay visibility
100   (let ((overlay (button-get cite-button 'overlay)))
101     (overlay-put overlay 'invisible (not (overlay-get overlay 'invisible))))
102   ;; Update button text
103   (let* ((new-start (button-start cite-button))
104          (overlay (button-get cite-button 'overlay))
105          (button-label (notmuch-wash-button-label overlay))
106          (old-point (point))
107          (inhibit-read-only t))
108     (goto-char new-start)
109     (insert button-label)
110     (let ((old-end (button-end cite-button)))
111       (move-overlay cite-button new-start (point))
112       (delete-region (point) old-end))
113     (goto-char (min old-point (1- (button-end cite-button))))))
114
115 (define-button-type 'notmuch-wash-button-invisibility-toggle-type
116   'action 'notmuch-wash-toggle-invisible-action
117   'follow-link t
118   'face 'font-lock-comment-face)
119
120 (define-button-type 'notmuch-wash-button-citation-toggle-type
121   'help-echo "mouse-1, RET: Show citation"
122   :supertype 'notmuch-wash-button-invisibility-toggle-type)
123
124 (define-button-type 'notmuch-wash-button-signature-toggle-type
125   'help-echo "mouse-1, RET: Show signature"
126   :supertype 'notmuch-wash-button-invisibility-toggle-type)
127
128 (define-button-type 'notmuch-wash-button-original-toggle-type
129   'help-echo "mouse-1, RET: Show original message"
130   :supertype 'notmuch-wash-button-invisibility-toggle-type)
131
132 (defun notmuch-wash-region-isearch-show (overlay)
133   (notmuch-wash-toggle-invisible-action
134    (overlay-get overlay 'notmuch-wash-button)))
135
136 (defun notmuch-wash-button-label (overlay)
137   (let* ((type (overlay-get overlay 'type))
138          (invis-spec (overlay-get overlay 'invisible))
139          (state (if (invisible-p invis-spec) "hidden" "visible"))
140          (label-format (symbol-value (intern-soft (concat "notmuch-wash-button-"
141                                                           type "-" state "-format"))))
142          (lines-count (count-lines (overlay-start overlay) (overlay-end overlay))))
143     (format label-format lines-count)))
144
145 (defun notmuch-wash-region-to-button (msg beg end type &optional prefix)
146   "Auxiliary function to do the actual making of overlays and buttons
147
148 BEG and END are buffer locations. TYPE should a string, either
149 \"citation\" or \"signature\". Optional PREFIX is some arbitrary
150 text to insert before the button, probably for indentation.  Note
151 that PREFIX should not include a newline."
152
153   ;; This uses some slightly tricky conversions between strings and
154   ;; symbols because of the way the button code works. Note that
155   ;; replacing intern-soft with make-symbol will cause this to fail,
156   ;; since the newly created symbol has no plist.
157
158   (let ((overlay (make-overlay beg end))
159         (button-type (intern-soft (concat "notmuch-wash-button-"
160                                           type "-toggle-type"))))
161     (overlay-put overlay 'invisible t)
162     (overlay-put overlay 'isearch-open-invisible #'notmuch-wash-region-isearch-show)
163     (overlay-put overlay 'type type)
164     (goto-char (1+ end))
165     (save-excursion
166       (goto-char beg)
167       (if prefix
168           (insert-before-markers prefix))
169       (let ((button-beg (point)))
170         (insert-before-markers (notmuch-wash-button-label overlay) "\n")
171         (let ((button (make-button button-beg (1- (point))
172                                    'overlay overlay
173                                    :type button-type)))
174           (overlay-put overlay 'notmuch-wash-button button))))))
175
176 (defun notmuch-wash-excerpt-citations (msg depth)
177   "Excerpt citations and up to one signature."
178   (goto-char (point-min))
179   (beginning-of-line)
180   (if (and (< (point) (point-max))
181            (re-search-forward notmuch-wash-original-regexp nil t))
182       (let* ((msg-start (match-beginning 0))
183              (msg-end (point-max))
184              (msg-lines (count-lines msg-start msg-end)))
185         (notmuch-wash-region-to-button
186          msg msg-start msg-end "original")))
187   (while (and (< (point) (point-max))
188               (re-search-forward notmuch-wash-citation-regexp nil t))
189     (let* ((cite-start (match-beginning 0))
190            (cite-end (match-end 0))
191            (cite-lines (count-lines cite-start cite-end)))
192       (overlay-put (make-overlay cite-start cite-end) 'face 'message-cited-text)
193       (when (> cite-lines (+ notmuch-wash-citation-lines-prefix
194                              notmuch-wash-citation-lines-suffix
195                              1))
196         (goto-char cite-start)
197         (forward-line notmuch-wash-citation-lines-prefix)
198         (let ((hidden-start (point-marker)))
199           (goto-char cite-end)
200           (forward-line (- notmuch-wash-citation-lines-suffix))
201           (notmuch-wash-region-to-button
202            msg hidden-start (point-marker)
203            "citation")))))
204   (if (and (not (eobp))
205            (re-search-forward notmuch-wash-signature-regexp nil t))
206       (let* ((sig-start (match-beginning 0))
207              (sig-end (match-end 0))
208              (sig-lines (count-lines sig-start (point-max))))
209         (if (<= sig-lines notmuch-wash-signature-lines-max)
210             (let ((sig-start-marker (make-marker))
211                   (sig-end-marker (make-marker)))
212               (set-marker sig-start-marker sig-start)
213               (set-marker sig-end-marker (point-max))
214               (overlay-put (make-overlay sig-start-marker sig-end-marker) 'face 'message-cited-text)
215               (notmuch-wash-region-to-button
216                msg sig-start-marker sig-end-marker
217                "signature"))))))
218
219 ;;
220
221 (defun notmuch-wash-elide-blank-lines (msg depth)
222   "Elide leading, trailing and successive blank lines."
223
224   ;; Algorithm derived from `article-strip-multiple-blank-lines' in
225   ;; `gnus-art.el'.
226
227   ;; Make all blank lines empty.
228   (goto-char (point-min))
229   (while (re-search-forward "^[[:space:]\t]+$" nil t)
230     (replace-match "" nil t))
231
232   ;; Replace multiple empty lines with a single empty line.
233   (goto-char (point-min))
234   (while (re-search-forward "^\n\\(\n+\\)" nil t)
235     (delete-region (match-beginning 1) (match-end 1)))
236
237   ;; Remove a leading blank line.
238   (goto-char (point-min))
239   (if (looking-at "\n")
240       (delete-region (match-beginning 0) (match-end 0)))
241
242   ;; Remove a trailing blank line.
243   (goto-char (point-max))
244   (if (looking-at "\n")
245       (delete-region (match-beginning 0) (match-end 0))))
246
247 ;;
248
249 (defun notmuch-wash-tidy-citations (msg depth)
250   "Improve the display of cited regions of a message.
251
252 Perform several transformations on the message body:
253
254 - Remove lines of repeated citation leaders with no other
255   content,
256 - Remove citation leaders standing alone before a block of cited
257   text,
258 - Remove citation trailers standing alone after a block of cited
259   text."
260
261   ;; Remove lines of repeated citation leaders with no other content.
262   (goto-char (point-min))
263   (while (re-search-forward "\\(^>[> ]*\n\\)\\{2,\\}" nil t)
264     (replace-match "\\1"))
265
266   ;; Remove citation leaders standing alone before a block of cited
267   ;; text.
268   (goto-char (point-min))
269   (while (re-search-forward "\\(\n\\|^[^>].*\\)\n\\(^>[> ]*\n\\)" nil t)
270     (replace-match "\\1\n"))
271
272   ;; Remove citation trailers standing alone after a block of cited
273   ;; text.
274   (goto-char (point-min))
275   (while (re-search-forward "\\(^>[> ]*\n\\)\\(^$\\|^[^>].*\\)" nil t)
276     (replace-match "\\2")))
277
278 ;;
279
280 (defun notmuch-wash-wrap-long-lines (msg depth)
281   "Wrap long lines in the message.
282
283 If `notmuch-wash-wrap-lines-length' is a number, this will wrap
284 the message lines to the minimum of the width of the window or
285 its value. Otherwise, this function will wrap long lines in the
286 message at the window width. When doing so, citation leaders in
287 the wrapped text are maintained."
288
289   (let* ((coolj-wrap-follows-window-size nil)
290          (limit (if (numberp notmuch-wash-wrap-lines-length)
291                     (min notmuch-wash-wrap-lines-length
292                          (window-width))
293                   (window-width)))
294          (fill-column (- limit
295                          depth
296                          ;; 2 to avoid poor interaction with
297                          ;; `word-wrap'.
298                          2)))
299     (coolj-wrap-region (point-min) (point-max))))
300
301 ;;
302
303 (require 'diff-mode)
304
305 (defvar diff-file-header-re) ; From `diff-mode.el'.
306
307 (defun notmuch-wash-subject-to-filename (subject &optional maxlen)
308   "Convert a mail SUBJECT into a filename.
309
310 The resulting filename is similar to the names generated by \"git
311 format-patch\", without the leading patch sequence number
312 \"0001-\" and \".patch\" extension. Any leading \"[PREFIX]\"
313 style strings are removed prior to conversion.
314
315 Optional argument MAXLEN is the maximum length of the resulting
316 filename, before trimming any trailing . and - characters."
317   (let* ((s (replace-regexp-in-string "^ *\\(\\[[^]]*\\] *\\)*" "" subject))
318          (s (replace-regexp-in-string "[^A-Za-z0-9._]+" "-" s))
319          (s (replace-regexp-in-string "\\.+" "." s))
320          (s (if maxlen (substring s 0 (min (length s) maxlen)) s))
321          (s (replace-regexp-in-string "[.-]*$" "" s)))
322     s))
323
324 (defun notmuch-wash-subject-to-patch-sequence-number (subject)
325   "Convert a patch mail SUBJECT into a patch sequence number.
326
327 Return the patch sequence number N from the last \"[PATCH N/M]\"
328 style prefix in SUBJECT, or nil if such a prefix can't be found."
329   (when (string-match
330          "^ *\\(\\[[^]]*\\] *\\)*\\[[^]]*?\\([0-9]+\\)/[0-9]+[^]]*\\].*"
331          subject)
332       (string-to-number (substring subject (match-beginning 2) (match-end 2)))))
333
334 (defun notmuch-wash-subject-to-patch-filename (subject)
335   "Convert a patch mail SUBJECT into a filename.
336
337 The resulting filename is similar to the names generated by \"git
338 format-patch\". If the patch mail was generated and sent using
339 \"git format-patch/send-email\", this should re-create the
340 original filename the sender had."
341   (format "%04d-%s.patch"
342           (or (notmuch-wash-subject-to-patch-sequence-number subject) 1)
343           (notmuch-wash-subject-to-filename subject 52)))
344
345 (defun notmuch-wash-convert-inline-patch-to-part (msg depth)
346   "Convert an inline patch into a fake 'text/x-diff' attachment.
347
348 Given that this function guesses whether a buffer includes a
349 patch and then guesses the extent of the patch, there is scope
350 for error."
351
352   (goto-char (point-min))
353   (when (re-search-forward diff-file-header-re nil t)
354     (beginning-of-line -1)
355     (let ((patch-start (point))
356           (patch-end (point-max))
357           part)
358       (goto-char patch-start)
359       (if (or
360            ;; Patch ends with signature.
361            (re-search-forward notmuch-wash-signature-regexp nil t)
362            ;; Patch ends with bugtraq comment.
363            (re-search-forward "^\\*\\*\\* " nil t))
364           (setq patch-end (match-beginning 0)))
365       (save-restriction
366         (narrow-to-region patch-start patch-end)
367         (setq part (plist-put part :content-type "inline-patch-fake-part"))
368         (setq part (plist-put part :content (buffer-string)))
369         (setq part (plist-put part :id -1))
370         (setq part (plist-put part :filename
371                               (notmuch-wash-subject-to-patch-filename
372                                (plist-get
373                                 (plist-get msg :headers) :Subject))))
374         (delete-region (point-min) (point-max))
375         (notmuch-show-insert-bodypart nil part depth)))))
376
377 ;;
378
379 (provide 'notmuch-wash)