1 ;;; mh-seq.el --- MH-E sequences support
3 ;; Copyright (C) 1993, 1995,
4 ;; 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
6 ;; Author: Bill Wohler <wohler@newt.com>
7 ;; Maintainer: Bill Wohler <wohler@newt.com>
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
30 ;; This tries to implement the algorithm described at:
31 ;; http://www.jwz.org/doc/threading.html
32 ;; It is also a start to implementing the IMAP Threading extension RFC. The
33 ;; implementation lacks the reference and subject canonicalization of the
36 ;; In the presentation buffer, children messages are shown indented with
37 ;; either [ ] or < > around them. Square brackets ([ ]) denote that the
38 ;; algorithm can point out some headers which when taken together implies
39 ;; that the unindented message is an ancestor of the indented message. If
40 ;; no such proof exists then angles (< >) are used.
42 ;; Some issues and problems are as follows:
44 ;; (1) Scan truncates the fields at length 512. So longer references:
45 ;; headers get mutilated. The same kind of MH format string works when
46 ;; composing messages. Is there a way to avoid this? My scan command
48 ;; scan +folder -width 10000 \
49 ;; -format "%(msg)\n%{message-id}\n%{references}\n%{subject}\n"
50 ;; I would really appreciate it if someone would help me with this.
52 ;; (2) Implement heuristics to recognize message identifiers in
53 ;; In-Reply-To: header. Right now it just assumes that the last text
54 ;; between angles (< and >) is the message identifier. There is the
55 ;; chance that this will incorrectly use an email address like a
56 ;; message identifier.
58 ;; (3) Error checking of found message identifiers should be done.
60 ;; (4) Since this breaks the assumption that message indices increase as
61 ;; one goes down the buffer, the binary search based mh-goto-msg
62 ;; doesn't work. I have a simpler replacement which may be less
65 ;; (5) Better canonicalizing for message identifier and subject strings.
68 ;; Internal support for MH-E package.
74 (eval-when-compile (require 'mh-acros))
78 ;; Shush the byte-compiler
79 (defvar tool-bar-mode)
83 ;;; Data structures (used in message threading)...
85 (mh-defstruct (mh-thread-message (:conc-name mh-message-)
86 (:constructor mh-thread-make-message))
92 (mh-defstruct (mh-thread-container (:conc-name mh-container-)
93 (:constructor mh-thread-make-container))
94 message parent children
99 ;;; Internal variables:
101 (defvar mh-last-seq-used nil
102 "Name of seq to which a msg was last added.")
104 (defvar mh-non-seq-mode-line-annotation nil
105 "Saved value of `mh-mode-line-annotation' when narrowed to a seq.")
109 ;;; Maps and hashes...
111 (defvar mh-thread-id-hash nil
112 "Hashtable used to canonicalize message identifiers.")
113 (defvar mh-thread-subject-hash nil
114 "Hashtable used to canonicalize subject strings.")
115 (defvar mh-thread-id-table nil
116 "Thread ID table maps from message identifiers to message containers.")
117 (defvar mh-thread-id-index-map nil
118 "Table to look up message index number from message identifier.")
119 (defvar mh-thread-index-id-map nil
120 "Table to look up message identifier from message index.")
121 (defvar mh-thread-scan-line-map nil
122 "Map of message index to various parts of the scan line.")
123 (defvar mh-thread-scan-line-map-stack nil
124 "Old map of message index to various parts of the scan line.
125 This is the original map that is stored when the folder is
127 (defvar mh-thread-subject-container-hash nil
128 "Hashtable used to group messages by subject.")
129 (defvar mh-thread-duplicates nil
130 "Hashtable used to associate messages with the same message identifier.")
131 (defvar mh-thread-history ()
132 "Variable to remember the transformations to the thread tree.
133 When new messages are added, these transformations are rewound,
134 then the links are added from the newly seen messages. Finally
135 the transformations are redone to get the new thread tree. This
136 makes incremental threading easier.")
137 (defvar mh-thread-body-width nil
138 "Width of scan substring that contains subject and body of message.")
140 (make-variable-buffer-local 'mh-thread-id-hash)
141 (make-variable-buffer-local 'mh-thread-subject-hash)
142 (make-variable-buffer-local 'mh-thread-id-table)
143 (make-variable-buffer-local 'mh-thread-id-index-map)
144 (make-variable-buffer-local 'mh-thread-index-id-map)
145 (make-variable-buffer-local 'mh-thread-scan-line-map)
146 (make-variable-buffer-local 'mh-thread-scan-line-map-stack)
147 (make-variable-buffer-local 'mh-thread-subject-container-hash)
148 (make-variable-buffer-local 'mh-thread-duplicates)
149 (make-variable-buffer-local 'mh-thread-history)
152 (defun mh-delete-seq (sequence)
155 You are prompted for the sequence to delete. Note that this
156 deletes only the sequence, not the messages in the sequence. If
157 you want to delete the messages, use \"\\[universal-argument]
158 \\[mh-delete-msg]\"."
159 (interactive (list (mh-read-seq-default "Delete" t)))
160 (let ((msg-list (mh-seq-to-msgs sequence))
161 (internal-flag (mh-internal-seq sequence))
162 (folders-changed (list mh-current-folder)))
163 (mh-iterate-on-range msg sequence
164 (mh-remove-sequence-notation msg internal-flag))
165 (mh-undefine-sequence sequence '("all"))
166 (mh-delete-seq-locally sequence)
168 (setq folders-changed
169 (append folders-changed
170 (mh-index-delete-from-sequence sequence msg-list))))
171 (when (and (eq sequence mh-unseen-seq) (mh-speed-flists-active-p))
172 (apply #'mh-speed-flists t folders-changed))))
174 ;; Avoid compiler warnings
175 (defvar view-exit-action)
178 (defun mh-list-sequences ()
179 "List all sequences in folder.
180 The list appears in a buffer named \"*MH-E Sequences*\"."
182 (let ((folder mh-current-folder)
183 (temp-buffer mh-sequences-buffer)
184 (seq-list mh-seq-list)
186 (with-output-to-temp-buffer temp-buffer
188 (set-buffer temp-buffer)
190 (message "Listing sequences ...")
191 (insert "Sequences in folder " folder ":\n")
192 (let ((seq-list seq-list))
195 (max (length (symbol-name (mh-seq-name (pop seq-list))))
197 (setq max-len (+ 2 max-len)))
199 (let ((name (mh-seq-name (car seq-list)))
201 (mh-coalesce-msg-list
202 (sort (copy-sequence (mh-seq-msgs (car seq-list))) '<)))
204 (insert (setq name-spec (format (format "%%%ss:" max-len) name)))
205 (while sorted-seq-msgs
206 (let ((next-element (format " %s" (pop sorted-seq-msgs))))
207 (when (>= (+ (current-column) (length next-element))
210 (insert (format (format "%%%ss" (length name-spec)) "")))
211 (insert next-element)))
213 (setq seq-list (cdr seq-list)))
214 (goto-char (point-min))
216 (setq view-exit-action 'kill-buffer)
217 (message "Listing sequences...done")))))
220 (defun mh-msg-is-in-seq (message)
221 "Display the sequences in which the current message appears.
222 Use a prefix argument to display the sequences in which another
226 (setq message (mh-get-msg-num t)))
227 (let* ((dest-folder (loop for seq in mh-refile-list
228 when (member message (cdr seq)) return (car seq)
230 (deleted-flag (unless dest-folder (member message mh-delete-list))))
231 (message "Message %d%s is in sequences: %s"
233 (cond (dest-folder (format " (to be refiled to %s)" dest-folder))
234 (deleted-flag (format " (to be deleted)"))
237 (mh-list-to-string (mh-seq-containing-msg message t))
240 ;; Avoid compiler warning
241 (defvar tool-bar-map)
243 (make-variable-buffer-local 'mh-non-seq-mode-line-annotation)
246 (defun mh-narrow-to-seq (sequence)
247 "Restrict display to messages in SEQUENCE.
249 You are prompted for the name of the sequence. What this command
250 does is show only those messages that are in the selected
251 sequence in the MH-Folder buffer. In addition, it limits further
252 MH-E searches to just those messages.
254 When you want to widen the view to all your messages again, use
256 (interactive (list (mh-read-seq "Narrow to" t)))
257 (with-mh-folder-updating (t)
258 (cond ((mh-seq-to-msgs sequence)
259 (mh-remove-all-notation)
260 (let ((eob (point-max))
261 (msg-at-cursor (mh-get-msg-num nil)))
262 (push mh-thread-scan-line-map mh-thread-scan-line-map-stack)
263 (setq mh-thread-scan-line-map (make-hash-table :test #'eql))
264 (mh-copy-seq-to-eob sequence)
265 (push (buffer-substring-no-properties (point-min) eob)
266 mh-folder-view-stack)
267 (delete-region (point-min) eob)
268 (mh-notate-deleted-and-refiled)
270 (when msg-at-cursor (mh-goto-msg msg-at-cursor t t))
271 (setq mh-non-seq-mode-line-annotation mh-mode-line-annotation)
272 (setq mh-mode-line-annotation (symbol-name sequence))
273 (mh-make-folder-mode-line)
275 (when (and (boundp 'tool-bar-mode) tool-bar-mode)
276 (set (make-local-variable 'tool-bar-map)
277 mh-folder-seq-tool-bar-map)
278 (when (buffer-live-p (get-buffer mh-show-buffer))
280 (set-buffer (get-buffer mh-show-buffer))
281 (set (make-local-variable 'tool-bar-map)
282 mh-show-seq-tool-bar-map))))
283 (push 'widen mh-view-ops)))
285 (error "No messages in sequence \"%s\"" (symbol-name sequence))))))
288 (defun mh-put-msg-in-seq (range sequence)
289 "Add RANGE to SEQUENCE\\<mh-folder-mode-map>.
291 To place a message in a sequence, use this command to do it
292 manually, or use the MH command \"pick\" or the MH-E version of
293 \"pick\", \\[mh-search-folder], which create a sequence
296 Give this command a RANGE and you can add all the messages in a
297 sequence to another sequence (for example,
298 \"\\[universal-argument] \\[mh-put-msg-in-seq] SourceSequence RET
299 DestSequence RET\"). Check the documentation of
300 `mh-interactive-range' to see how RANGE is read in interactive
302 (interactive (list (mh-interactive-range "Add messages from")
303 (mh-read-seq-default "Add to" nil)))
304 (unless (mh-valid-seq-p sequence)
305 (error "Can't put message in invalid sequence \"%s\"" sequence))
306 (let* ((internal-seq-flag (mh-internal-seq sequence))
307 (original-msgs (mh-seq-msgs (mh-find-seq sequence)))
308 (folders (list mh-current-folder))
309 (msg-list (mh-range-to-msg-list range)))
310 (mh-add-msgs-to-seq msg-list sequence nil t)
311 (mh-iterate-on-range m range
312 (unless (memq m original-msgs)
313 (mh-add-sequence-notation m internal-seq-flag)))
314 (if (not internal-seq-flag)
315 (setq mh-last-seq-used sequence))
318 (append folders (mh-index-add-to-sequence sequence msg-list))))
319 (when (and (eq sequence mh-unseen-seq) (mh-speed-flists-active-p))
320 (apply #'mh-speed-flists t folders))))
322 (defun mh-valid-view-change-operation-p (op)
323 "Check if the view change operation can be performed.
324 OP is one of 'widen and 'unthread."
325 (cond ((eq (car mh-view-ops) op)
330 (defun mh-widen (&optional all-flag)
331 "Remove last restriction.
332 If optional prefix argument ALL-FLAG is non-nil, remove all
335 (let ((msg (mh-get-msg-num nil)))
336 (when mh-folder-view-stack
338 (while (cdr mh-view-ops)
339 (setq mh-view-ops (cdr mh-view-ops)))
340 (when (eq (car mh-view-ops) 'widen)
341 (setq mh-view-ops (cdr mh-view-ops))))
342 ((mh-valid-view-change-operation-p 'widen) nil)
343 ((memq 'widen mh-view-ops)
344 (while (not (eq (car mh-view-ops) 'widen))
345 (setq mh-view-ops (cdr mh-view-ops)))
346 (setq mh-view-ops (cdr mh-view-ops)))
347 (t (error "Widening is not applicable")))
348 ;; If ALL-FLAG is non-nil then rewind stacks
350 (while (cdr mh-thread-scan-line-map-stack)
351 (setq mh-thread-scan-line-map-stack
352 (cdr mh-thread-scan-line-map-stack)))
353 (while (cdr mh-folder-view-stack)
354 (setq mh-folder-view-stack (cdr mh-folder-view-stack))))
355 (setq mh-thread-scan-line-map (pop mh-thread-scan-line-map-stack))
356 (with-mh-folder-updating (t)
357 (delete-region (point-min) (point-max))
358 (insert (pop mh-folder-view-stack))
359 (mh-remove-all-notation)
360 (setq mh-mode-line-annotation mh-non-seq-mode-line-annotation)
361 (mh-make-folder-mode-line))
363 (mh-goto-msg msg t t))
364 (mh-notate-deleted-and-refiled)
365 (mh-notate-user-sequences)
368 (when (and (null mh-folder-view-stack) (boundp 'tool-bar-mode) tool-bar-mode)
369 (set (make-local-variable 'tool-bar-map) mh-folder-tool-bar-map)
370 (when (buffer-live-p (get-buffer mh-show-buffer))
372 (set-buffer (get-buffer mh-show-buffer))
373 (set (make-local-variable 'tool-bar-map) mh-show-tool-bar-map)))))
375 ;; FIXME? We may want to clear all notations and add one for current-message
376 ;; and process user sequences.
378 (defun mh-notate-deleted-and-refiled ()
379 "Notate messages marked for deletion or refiling.
380 Messages to be deleted are given by `mh-delete-list' while
381 messages to be refiled are present in `mh-refile-list'."
382 (let ((refiled-hash (make-hash-table))
383 (deleted-hash (make-hash-table)))
384 (dolist (msg mh-delete-list)
385 (setf (gethash msg deleted-hash) t))
386 (dolist (dest-msg-list mh-refile-list)
387 (dolist (msg (cdr dest-msg-list))
388 (setf (gethash msg refiled-hash) t)))
389 (mh-iterate-on-messages-in-region msg (point-min) (point-max)
390 (cond ((gethash msg refiled-hash)
391 (mh-notate nil mh-note-refiled mh-cmd-note))
392 ((gethash msg deleted-hash)
393 (mh-notate nil mh-note-deleted mh-cmd-note))))))
397 ;;; Commands to manipulate sequences.
399 ;; Sequences are stored in an alist of the form:
400 ;; ((seq-name msgs ...) (seq-name msgs ...) ...)
402 (defvar mh-sequence-history ())
405 (defun mh-read-seq-default (prompt not-empty)
406 "Read and return sequence name with default narrowed or previous sequence.
407 PROMPT is the prompt to use when reading. If NOT-EMPTY is non-nil
408 then a non-empty sequence is read."
409 (mh-read-seq prompt not-empty
411 (car (mh-seq-containing-msg (mh-get-msg-num nil) nil)))))
413 (defun mh-read-seq (prompt not-empty &optional default)
414 "Read and return a sequence name.
415 Prompt with PROMPT, raise an error if the sequence is empty and
416 the NOT-EMPTY flag is non-nil, and supply an optional DEFAULT
417 sequence. A reply of '%' defaults to the first sequence
418 containing the current message."
419 (let* ((input (completing-read (format "%s %s %s" prompt "sequence:"
421 (format "[%s] " default)
423 (mh-seq-names mh-seq-list)
424 nil nil nil 'mh-sequence-history))
425 (seq (cond ((equal input "%")
426 (car (mh-seq-containing-msg (mh-get-msg-num t) nil)))
427 ((equal input "") default)
429 (msgs (mh-seq-to-msgs seq)))
430 (if (and (null msgs) not-empty)
431 (error "No messages in sequence \"%s\"" seq))
436 ;;; Functions to read ranges with completion...
438 (defvar mh-range-seq-names)
439 (defvar mh-range-history ())
440 (defvar mh-range-completion-map (copy-keymap minibuffer-local-completion-map))
441 (define-key mh-range-completion-map " " 'self-insert-command)
443 (defun mh-range-completion-function (string predicate flag)
444 "Programmable completion of message ranges.
445 STRING is the user input that is to be completed. PREDICATE if non-nil is a
446 function used to filter the possible choices and FLAG determines whether the
448 (let* ((candidates mh-range-seq-names)
449 (last-char (and (not (equal string ""))
450 (aref string (1- (length string)))))
451 (last-word (cond ((null last-char) "")
452 ((memq last-char '(? ?- ?:)) "")
453 (t (car (last (split-string string "[ -:]+"))))))
454 (prefix (substring string 0 (- (length string) (length last-word)))))
456 (let ((res (try-completion last-word candidates predicate)))
457 (cond ((null res) nil)
459 (t (concat prefix res)))))
461 (all-completions last-word candidates predicate))
463 (loop for x in candidates
464 when (equal x last-word) return t
465 finally return nil)))))
468 (defun mh-read-range (prompt &optional folder default
469 expand-flag ask-flag number-as-range-flag)
470 "Read a message range with PROMPT.
472 If FOLDER is non-nil then a range is read from that folder, otherwise
473 use `mh-current-folder'.
475 If DEFAULT is a string then use that as default range to return. If
476 DEFAULT is nil then ask user with default answer a range based on the
477 sequences that seem relevant. Finally if DEFAULT is t, try to avoid
478 prompting the user. Unseen messages, if present, are returned. If the
479 folder has fewer than `mh-large-folder' messages then \"all\" messages
480 are returned. Finally as a last resort prompt the user.
482 If EXPAND-FLAG is non-nil then a list of message numbers corresponding
483 to the input is returned. If this list is empty then an error is
484 raised. If EXPAND-FLAG is nil just return the input string. In this
485 case we don't check if the range is empty.
487 If ASK-FLAG is non-nil, then the user is always queried for a range of
488 messages. If ASK-FLAG is nil, then the function checks if the unseen
489 sequence is non-empty. If that is the case, `mh-unseen-seq', or the
490 list of messages in it depending on the value of EXPAND, is returned.
491 Otherwise if the folder has fewer than `mh-large-folder' messages then
492 the list of messages corresponding to \"all\" is returned. If neither
493 of the above holds then as a last resort the user is queried for a
496 If NUMBER-AS-RANGE-FLAG is non-nil, then if a number, N is read as
497 input, it is interpreted as the range \"last:N\".
499 This function replaces the existing function `mh-read-msg-range'.
502 (mh-read-msg-range folder flag)
504 should be replaced with:
506 (mh-read-range \"Suitable prompt\" folder t nil flag
507 mh-interpret-number-as-range-flag)"
508 (setq default (or default mh-last-seq-used
509 (car (mh-seq-containing-msg (mh-get-msg-num nil) t)))
510 prompt (format "%s range" prompt))
511 (let* ((folder (or folder mh-current-folder))
512 (default (cond ((or (eq default t) (stringp default)) default)
513 ((symbolp default) (symbol-name default))))
514 (guess (eq default t))
515 (counts (and guess (mh-folder-size folder)))
516 (unseen (and counts (> (cadr counts) 0)))
517 (large (and counts mh-large-folder (> (car counts) mh-large-folder)))
518 (str (cond ((and guess large
519 (setq default (format "last:%s" mh-large-folder)
520 prompt (format "%s (folder has %s messages)"
521 prompt (car counts)))
523 ((and guess (not large) (setq default "all") nil))
524 ((eq default nil) "")
525 (t (format "[%s] " default))))
526 (minibuffer-local-completion-map mh-range-completion-map)
527 (seq-list (if (eq folder mh-current-folder)
529 (mh-read-folder-sequences folder nil)))
531 (append '(("first") ("last") ("all") ("prev") ("next"))
532 (mh-seq-names seq-list)))
533 (input (cond ((and (not ask-flag) unseen) (symbol-name mh-unseen-seq))
534 ((and (not ask-flag) (not large)) "all")
535 (t (completing-read (format "%s: %s" prompt str)
536 'mh-range-completion-function nil nil
537 nil 'mh-range-history default))))
539 (when (and number-as-range-flag
540 (string-match "^[ \t]*\\([0-9]+\\)[ \t]*$" input))
541 (setq input (concat "last:" (match-string 1 input))))
542 (cond ((not expand-flag) input)
543 ((assoc (intern input) seq-list)
544 (cdr (assoc (intern input) seq-list)))
545 ((setq msg-list (mh-translate-range folder input)) msg-list)
546 (t (error "No messages in range \"%s\"" input)))))
549 (defun mh-translate-range (folder expr)
550 "In FOLDER, translate the string EXPR to a list of messages numbers."
552 (let ((strings (delete "" (split-string expr "[ \t\n]")))
555 (apply #'mh-exec-cmd-quiet nil "mhpath" folder strings)
556 (set-buffer mh-temp-buffer)
557 (goto-char (point-min))
558 (while (re-search-forward "/\\([0-9]*\\)$" nil t)
559 (push (car (read-from-string (match-string 1))) result))
560 (nreverse result)))))
562 (defun mh-seq-names (seq-list)
563 "Return an alist containing the names of the SEQ-LIST."
564 (mapcar (lambda (entry) (list (symbol-name (mh-seq-name entry))))
568 (defun mh-rename-seq (sequence new-name)
569 "Rename SEQUENCE to have NEW-NAME."
570 (interactive (list (mh-read-seq "Old" t)
571 (intern (read-string "New sequence name: "))))
572 (let ((old-seq (mh-find-seq sequence)))
574 (error "Sequence %s does not exist" sequence))
575 ;; create new sequence first, since it might raise an error.
576 (mh-define-sequence new-name (mh-seq-msgs old-seq))
577 (mh-undefine-sequence sequence (mh-seq-msgs old-seq))
578 (rplaca old-seq new-name)))
581 (defun mh-notate-cur ()
582 "Mark the MH sequence cur.
583 In addition to notating the current message with `mh-note-cur'
584 the function uses `overlay-arrow-position' to put a marker in the
586 (let ((cur (car (mh-seq-to-msgs 'cur))))
587 (when (and cur (mh-goto-msg cur t t))
589 (when (looking-at mh-scan-good-msg-regexp)
590 (mh-notate nil mh-note-cur mh-cmd-note))
591 (setq mh-arrow-marker (set-marker mh-arrow-marker (point)))
592 (setq overlay-arrow-position mh-arrow-marker))))
595 (defun mh-add-to-sequence (seq msgs)
596 "The sequence SEQ is augmented with the messages in MSGS."
597 ;; Add to a SEQUENCE each message the list of MSGS.
598 (if (and (mh-valid-seq-p seq) (not (mh-folder-name-p seq)))
600 (apply 'mh-exec-cmd "mark" mh-current-folder "-add"
601 "-sequence" (symbol-name seq)
602 (mh-coalesce-msg-list msgs)))))
604 (defvar mh-thread-last-ancestor)
606 (defun mh-copy-seq-to-eob (seq)
607 "Copy SEQ to the end of the buffer."
608 ;; It is quite involved to write something which will work at any place in
609 ;; the buffer, so we will write something which works only at the end of
610 ;; the buffer. If we ever need to insert sequences in the middle of the
611 ;; buffer, this will need to be fixed.
613 (let* ((msgs (mh-seq-to-msgs seq))
614 (coalesced-msgs (mh-coalesce-msg-list msgs)))
615 (goto-char (point-max))
617 (narrow-to-region (point) (point))
618 (mh-regenerate-headers coalesced-msgs t)
619 (cond ((memq 'unthread mh-view-ops)
620 ;; Populate restricted scan-line map
621 (mh-remove-all-notation)
622 (mh-iterate-on-range msg (cons (point-min) (point-max))
623 (setf (gethash msg mh-thread-scan-line-map)
624 (mh-thread-parse-scan-line)))
625 ;; Remove scan lines and read results from pre-computed tree
626 (delete-region (point-min) (point-max))
627 (mh-thread-print-scan-lines
628 (mh-thread-generate mh-current-folder ()))
629 (mh-notate-user-sequences))
631 (mh-index-insert-folder-headers)))))))
634 (defmacro mh-iterate-on-messages-in-region (var begin end &rest body)
635 "Iterate over region.
637 VAR is bound to the message on the current line as we loop
638 starting from BEGIN till END. In each step BODY is executed.
640 If VAR is nil then the loop is executed without any binding."
641 (unless (symbolp var)
642 (error "Can not bind the non-symbol %s" var))
643 (let ((binding-needed-flag var))
647 (while (and (<= (point) ,end) (not (eobp)))
648 (when (looking-at mh-scan-valid-regexp)
649 (let ,(if binding-needed-flag `((,var (mh-get-msg-num t))) ())
653 (put 'mh-iterate-on-messages-in-region 'lisp-indent-hook 'defun)
656 (defmacro mh-iterate-on-range (var range &rest body)
657 "Iterate an operation over a region or sequence.
659 VAR is bound to each message in turn in a loop over RANGE, which
660 can be a message number, a list of message numbers, a sequence, a
661 region in a cons cell, or a MH range (something like last:20) in
662 a string. In each iteration, BODY is executed.
664 The parameter RANGE is usually created with
665 `mh-interactive-range' in order to provide a uniform interface to
667 (unless (symbolp var)
668 (error "Can not bind the non-symbol %s" var))
669 (let ((binding-needed-flag var)
670 (msgs (make-symbol "msgs"))
671 (seq-hash-table (make-symbol "seq-hash-table")))
672 `(cond ((numberp ,range)
673 (when (mh-goto-msg ,range t t)
674 (let ,(if binding-needed-flag `((,var ,range)) ())
677 (numberp (car ,range)) (numberp (cdr ,range)))
678 (mh-iterate-on-messages-in-region ,var
679 (car ,range) (cdr ,range)
681 (t (let ((,msgs (cond ((and ,range (symbolp ,range))
682 (mh-seq-to-msgs ,range))
684 (mh-translate-range mh-current-folder
687 (,seq-hash-table (make-hash-table)))
689 (setf (gethash msg ,seq-hash-table) t))
690 (mh-iterate-on-messages-in-region v (point-min) (point-max)
691 (when (gethash v ,seq-hash-table)
692 (let ,(if binding-needed-flag `((,var v)) ())
695 (put 'mh-iterate-on-range 'lisp-indent-hook 'defun)
698 (defun mh-range-to-msg-list (range)
699 "Return a list of messages for RANGE.
701 Check the documentation of `mh-interactive-range' to see how
702 RANGE is read in interactive use."
704 (mh-iterate-on-range msg range
706 (nreverse msg-list)))
709 (defun mh-interactive-range (range-prompt &optional default)
710 "Return interactive specification for message, sequence, range or region.
711 By convention, the name of this argument is RANGE.
713 If variable `transient-mark-mode' is non-nil and the mark is active,
714 then this function returns a cons-cell of the region.
716 If optional prefix argument is provided, then prompt for message range
717 with RANGE-PROMPT. A list of messages in that range is returned.
719 If a MH range is given, say something like last:20, then a list
720 containing the messages in that range is returned.
722 If DEFAULT non-nil then it is returned.
724 Otherwise, the message number at point is returned.
726 This function is usually used with `mh-iterate-on-range' in order to
727 provide a uniform interface to MH-E functions."
728 (cond ((mh-mark-active-p t) (cons (region-beginning) (region-end)))
729 (current-prefix-arg (mh-read-range range-prompt nil nil t t))
731 (t (mh-get-msg-num t))))
735 ;;; Commands to handle new 'subject sequence ("Poor man's threading" by psg)
737 ;; XXX: The function mh-subject-to-sequence-unthreaded uses the magic number
738 ;; 41 for the max size of the subject part. Avoiding this would be desirable.
739 (defun mh-subject-to-sequence (all)
740 "Put all following messages with same subject in sequence 'subject.
741 If arg ALL is t, move to beginning of folder buffer to collect all
743 If arg ALL is nil, collect only messages fron current one on forward.
745 Return number of messages put in the sequence:
747 nil -> there was no subject line.
749 0 -> there were no later messages with the same
750 subject (sequence not made)
752 >1 -> the total number of messages including current one."
753 (if (memq 'unthread mh-view-ops)
754 (mh-subject-to-sequence-threaded all)
755 (mh-subject-to-sequence-unthreaded all)))
757 (defun mh-subject-to-sequence-unthreaded (all)
758 "Put all following messages with same subject in sequence 'subject.
760 This function only works with an unthreaded folder. If arg ALL is
761 t, move to beginning of folder buffer to collect all messages. If
762 arg ALL is nil, collect only messages fron current one on
765 Return number of messages put in the sequence:
767 nil -> there was no subject line.
768 0 -> there were no later messages with the same
769 subject (sequence not made)
770 >1 -> the total number of messages including current one."
771 (if (not (eq major-mode 'mh-folder-mode))
772 (error "Not in a folder buffer"))
775 (if (or (not (looking-at mh-scan-subject-regexp))
776 (not (match-string 3))
777 (string-equal "" (match-string 3)))
778 (progn (message "No subject line")
780 (let ((subject (match-string-no-properties 3))
782 (if (> (length subject) 41)
783 (setq subject (substring subject 0 41)))
786 (goto-char (point-min)))
787 (while (re-search-forward mh-scan-subject-regexp nil t)
788 (let ((this-subject (match-string-no-properties 3)))
789 (if (> (length this-subject) 41)
790 (setq this-subject (substring this-subject 0 41)))
791 (if (string-equal this-subject subject)
792 (setq list (cons (mh-get-msg-num t) list))))))
795 ;; If we created a new sequence, add the initial message to it too.
796 (if (not (member (mh-get-msg-num t) list))
797 (setq list (cons (mh-get-msg-num t) list)))
798 (if (assoc 'subject mh-seq-list) (mh-delete-seq 'subject))
799 ;; sort the result into a sequence
800 (let ((sorted-list (sort (copy-sequence list) 'mh-lessp)))
802 (mh-add-msgs-to-seq (car sorted-list) 'subject nil)
803 (setq sorted-list (cdr sorted-list)))
808 (defun mh-subject-to-sequence-threaded (all)
809 "Put all messages with the same subject in the 'subject sequence.
811 This function works when the folder is threaded. In this
812 situation the subject could get truncated and so the normal
813 matching doesn't work.
815 The parameter ALL is non-nil then all the messages in the buffer
816 are considered, otherwise only the messages after the current one
817 are taken into account."
818 (let* ((cur (mh-get-msg-num nil))
819 (subject (mh-thread-find-msg-subject cur))
822 (and (message "No subject line") nil)
823 (setq region (cons (if all (point-min) (point)) (point-max)))
824 (mh-iterate-on-range msg region
825 (when (eq (mh-thread-find-msg-subject msg) subject)
827 (setq msgs (sort msgs #'mh-lessp))
830 (when (assoc 'subject mh-seq-list)
831 (mh-delete-seq 'subject))
832 (mh-add-msgs-to-seq msgs 'subject)
835 (defun mh-thread-find-msg-subject (msg)
836 "Find canonicalized subject of MSG.
837 This function can only be used the folder is threaded."
840 (mh-container-message (gethash (gethash msg mh-thread-index-id-map)
841 mh-thread-id-table)))))
843 (defun mh-edit-pick-expr (default)
844 "With prefix arg edit a pick expression.
845 If no prefix arg is given, then return DEFAULT."
846 (let ((default-string (loop for x in default concat (format " %s" x))))
847 (if (or current-prefix-arg (equal default-string ""))
848 (mh-pick-args-list (read-string "Pick expression: "
852 (defun mh-pick-args-list (s)
853 "Form list by grouping elements in string S suitable for pick arguments.
854 For example, the string \"-subject a b c -from Joe User
855 <user@domain.com>\" is converted to (\"-subject\" \"a b c\"
856 \"-from\" \"Joe User <user@domain.com>\""
857 (let ((full-list (split-string s))
858 current-arg collection arg-list)
860 (setq current-arg (car full-list))
861 (if (null (string-match "^-" current-arg))
863 (if (null collection)
865 (format "%s %s" collection current-arg)))
867 (setq arg-list (append arg-list (list collection)))
868 (setq collection nil))
869 (setq arg-list (append arg-list (list current-arg))))
870 (setq full-list (cdr full-list)))
872 (setq arg-list (append arg-list (list collection))))
876 (defun mh-narrow-to-subject (&optional pick-expr)
877 "Limit to messages with same subject.
878 With a prefix argument, edit PICK-EXPR.
880 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
882 (list (mh-edit-pick-expr (mh-current-message-header-field 'subject))))
883 (mh-narrow-to-header-field 'subject pick-expr))
886 (defun mh-narrow-to-from (&optional pick-expr)
887 "Limit to messages with the same \"From:\" field.
888 With a prefix argument, edit PICK-EXPR.
890 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
892 (list (mh-edit-pick-expr (mh-current-message-header-field 'from))))
893 (mh-narrow-to-header-field 'from pick-expr))
896 (defun mh-narrow-to-cc (&optional pick-expr)
897 "Limit to messages with the same \"Cc:\" field.
898 With a prefix argument, edit PICK-EXPR.
900 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
902 (list (mh-edit-pick-expr (mh-current-message-header-field 'cc))))
903 (mh-narrow-to-header-field 'cc pick-expr))
906 (defun mh-narrow-to-to (&optional pick-expr)
907 "Limit to messages with the same \"To:\" field.
908 With a prefix argument, edit PICK-EXPR.
910 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
912 (list (mh-edit-pick-expr (mh-current-message-header-field 'to))))
913 (mh-narrow-to-header-field 'to pick-expr))
915 (defun mh-narrow-to-header-field (header-field pick-expr)
916 "Limit to messages whose HEADER-FIELD match PICK-EXPR.
917 The MH command pick is used to do the match."
918 (let ((folder mh-current-folder)
919 (original (mh-coalesce-msg-list
920 (mh-range-to-msg-list (cons (point-min) (point-max)))))
923 (apply #'mh-exec-cmd-output "pick" nil folder
924 (append original (list "-list") pick-expr))
925 (goto-char (point-min))
927 (let ((num (read-from-string
928 (buffer-substring (point) (line-end-position)))))
929 (when (numberp (car num)) (push (car num) msg-list))
932 (message "No matches")
933 (when (assoc 'header mh-seq-list) (mh-delete-seq 'header))
934 (mh-add-msgs-to-seq msg-list 'header)
935 (mh-narrow-to-seq 'header))))
937 (defun mh-current-message-header-field (header-field)
938 "Return a pick regexp to match HEADER-FIELD of the message at point."
939 (let ((num (mh-get-msg-num nil)))
941 (let ((folder mh-current-folder))
943 (insert-file-contents-literally (mh-msg-filename num folder))
944 (goto-char (point-min))
945 (when (search-forward "\n\n" nil t)
946 (narrow-to-region (point-min) (point)))
947 (let* ((field (or (message-fetch-field (format "%s" header-field))
949 (field-option (format "-%s" header-field))
950 (patterns (loop for x in (split-string field "[ ]*,[ ]*")
952 collect (if (string-match "<\\(.*@.*\\)>" x)
956 (loop with accum = `(,field-option ,(car patterns))
957 for e in (cdr patterns)
958 do (setq accum `(,field-option ,e "-or" ,@accum))
959 finally return accum))))))))
962 (defun mh-narrow-to-range (range)
965 Check the documentation of `mh-interactive-range' to see how
966 RANGE is read in interactive use.
968 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
969 (interactive (list (mh-interactive-range "Narrow to")))
970 (when (assoc 'range mh-seq-list) (mh-delete-seq 'range))
971 (mh-add-msgs-to-seq (mh-range-to-msg-list range) 'range)
972 (mh-narrow-to-seq 'range))
976 (defun mh-delete-subject ()
977 "Delete messages with same subject\\<mh-folder-mode-map>.
979 To delete messages faster, you can use this command to delete all
980 the messages with the same subject as the current message. This
981 command puts these messages in a sequence named \"subject\". You
982 can undo this action by using \\[mh-undo] with a prefix argument
983 and then specifying the \"subject\" sequence."
985 (let ((count (mh-subject-to-sequence nil)))
987 ((not count) ; No subject line, delete msg anyway
988 (mh-delete-msg (mh-get-msg-num t)))
989 ((= 0 count) ; No other msgs, delete msg anyway.
990 (message "No other messages with same Subject following this one")
991 (mh-delete-msg (mh-get-msg-num t)))
992 (t ; We have a subject sequence.
993 (message "Marked %d messages for deletion" count)
994 (mh-delete-msg 'subject)))))
997 (defun mh-delete-subject-or-thread ()
998 "Delete messages with same subject or thread\\<mh-folder-mode-map>.
1000 To delete messages faster, you can use this command to delete all
1001 the messages with the same subject as the current message. This
1002 command puts these messages in a sequence named \"subject\". You
1003 can undo this action by using \\[mh-undo] with a prefix argument
1004 and then specifying the \"subject\" sequence.
1006 However, if the buffer is displaying a threaded view of the
1007 folder then this command behaves like \\[mh-thread-delete]."
1009 (if (memq 'unthread mh-view-ops)
1011 (mh-delete-subject)))
1015 ;;; Message threading:
1017 (defmacro mh-thread-initialize-hash (var test)
1018 "Initialize the hash table in VAR.
1019 TEST is the test to use when creating a new hash table."
1020 (unless (symbolp var) (error "Expected a symbol: %s" var))
1021 `(if ,var (clrhash ,var) (setq ,var (make-hash-table :test ,test))))
1023 (defun mh-thread-initialize ()
1024 "Make new hash tables, or clear them if already present."
1025 (mh-thread-initialize-hash mh-thread-id-hash #'equal)
1026 (mh-thread-initialize-hash mh-thread-subject-hash #'equal)
1027 (mh-thread-initialize-hash mh-thread-id-table #'eq)
1028 (mh-thread-initialize-hash mh-thread-id-index-map #'eq)
1029 (mh-thread-initialize-hash mh-thread-index-id-map #'eql)
1030 (mh-thread-initialize-hash mh-thread-scan-line-map #'eql)
1031 (mh-thread-initialize-hash mh-thread-subject-container-hash #'eq)
1032 (mh-thread-initialize-hash mh-thread-duplicates #'eq)
1033 (setq mh-thread-history ()))
1035 (defsubst mh-thread-id-container (id)
1036 "Given ID, return the corresponding container in `mh-thread-id-table'.
1037 If no container exists then a suitable container is created and
1038 the id-table is updated."
1041 (or (gethash id mh-thread-id-table)
1042 (setf (gethash id mh-thread-id-table)
1043 (let ((message (mh-thread-make-message :id id)))
1044 (mh-thread-make-container :message message)))))
1046 (defsubst mh-thread-remove-parent-link (child)
1047 "Remove parent link of CHILD if it exists."
1048 (let* ((child-container (if (mh-thread-container-p child)
1049 child (mh-thread-id-container child)))
1050 (parent-container (mh-container-parent child-container)))
1051 (when parent-container
1052 (setf (mh-container-children parent-container)
1053 (loop for elem in (mh-container-children parent-container)
1054 unless (eq child-container elem) collect elem))
1055 (setf (mh-container-parent child-container) nil))))
1057 (defsubst mh-thread-add-link (parent child &optional at-end-p)
1058 "Add links so that PARENT becomes a parent of CHILD.
1059 Doesn't make any changes if CHILD is already an ancestor of
1060 PARENT. If optional argument AT-END-P is non-nil, the CHILD is
1061 added to the end of the children list of PARENT."
1062 (let ((parent-container (cond ((null parent) nil)
1063 ((mh-thread-container-p parent) parent)
1064 (t (mh-thread-id-container parent))))
1065 (child-container (if (mh-thread-container-p child)
1066 child (mh-thread-id-container child))))
1067 (when (and parent-container
1068 (not (mh-thread-ancestor-p child-container parent-container))
1069 (not (mh-thread-ancestor-p parent-container child-container)))
1070 (mh-thread-remove-parent-link child-container)
1071 (cond ((not at-end-p)
1072 (push child-container (mh-container-children parent-container)))
1073 ((null (mh-container-children parent-container))
1074 (push child-container (mh-container-children parent-container)))
1075 (t (let ((last-child (mh-container-children parent-container)))
1076 (while (cdr last-child)
1077 (setq last-child (cdr last-child)))
1078 (setcdr last-child (cons child-container nil)))))
1079 (setf (mh-container-parent child-container) parent-container))
1080 (unless parent-container
1081 (mh-thread-remove-parent-link child-container))))
1083 (defun mh-thread-ancestor-p (ancestor successor)
1084 "Return t if ANCESTOR is really an ancestor of SUCCESSOR and nil otherwise.
1085 In the limit, the function returns t if ANCESTOR and SUCCESSOR
1086 are the same containers."
1089 (when (eq ancestor successor) (return t))
1090 (setq successor (mh-container-parent successor)))
1093 (defsubst mh-thread-get-message-container (message)
1094 "Return container which has MESSAGE in it.
1095 If there is no container present then a new container is
1097 (let* ((id (mh-message-id message))
1098 (container (gethash id mh-thread-id-table)))
1099 (cond (container (setf (mh-container-message container) message)
1101 (t (setf (gethash id mh-thread-id-table)
1102 (mh-thread-make-container :message message))))))
1104 (defsubst mh-thread-get-message (id subject-re-p subject refs)
1105 "Return appropriate message.
1106 Otherwise update message already present to have the proper ID,
1107 SUBJECT-RE-P, SUBJECT and REFS fields."
1108 (let* ((container (gethash id mh-thread-id-table))
1109 (message (if container (mh-container-message container) nil)))
1111 (setf (mh-message-subject-re-p message) subject-re-p)
1112 (setf (mh-message-subject message) subject)
1113 (setf (mh-message-id message) id)
1114 (setf (mh-message-references message) refs)
1117 (setf (mh-container-message container)
1118 (mh-thread-make-message :id id :references refs
1120 :subject-re-p subject-re-p)))
1121 (t (let ((message (mh-thread-make-message :id id :references refs
1122 :subject-re-p subject-re-p
1125 (mh-thread-get-message-container message)))))))
1127 (defsubst mh-thread-canonicalize-id (id)
1128 "Produce canonical string representation for ID.
1129 This allows cheap string comparison with EQ."
1130 (or (and (equal id "") (copy-sequence ""))
1131 (gethash id mh-thread-id-hash)
1132 (setf (gethash id mh-thread-id-hash) id)))
1134 (defsubst mh-thread-prune-subject (subject)
1135 "Prune leading Re:'s, Fwd:'s etc. and trailing (fwd)'s from SUBJECT.
1136 If the result after pruning is not the empty string then it is
1137 canonicalized so that subjects can be tested for equality with
1138 eq. This is done so that all the messages without a subject are
1139 not put into a single thread."
1140 (let ((case-fold-search t)
1141 (subject-pruned-flag nil))
1142 ;; Prune subject leader
1143 (while (or (string-match "^[ \t]*\\(re\\|fwd?\\)\\(\\[[0-9]*\\]\\)?:[ \t]*"
1145 (string-match "^[ \t]*\\[[^\\]][ \t]*" subject))
1146 (setq subject-pruned-flag t)
1147 (setq subject (substring subject (match-end 0))))
1148 ;; Prune subject trailer
1149 (while (or (string-match "(fwd)$" subject)
1150 (string-match "[ \t]+$" subject))
1151 (setq subject-pruned-flag t)
1152 (setq subject (substring subject 0 (match-beginning 0))))
1153 ;; Canonicalize subject only if it is non-empty
1154 (cond ((equal subject "") (values subject subject-pruned-flag))
1156 (or (gethash subject mh-thread-subject-hash)
1157 (setf (gethash subject mh-thread-subject-hash) subject))
1158 subject-pruned-flag)))))
1160 (defun mh-thread-container-subject (container)
1161 "Return the subject of CONTAINER.
1162 If CONTAINER is empty return the subject info of one of its
1164 (cond ((and (mh-container-message container)
1165 (mh-message-id (mh-container-message container)))
1166 (mh-message-subject (mh-container-message container)))
1168 (dolist (kid (mh-container-children container))
1169 (when (and (mh-container-message kid)
1170 (mh-message-id (mh-container-message kid)))
1171 (let ((kid-message (mh-container-message kid)))
1172 (return (mh-message-subject kid-message)))))
1173 (error "This can't happen!")))))
1175 (defun mh-thread-rewind-pruning ()
1176 "Restore the thread tree to its state before pruning."
1177 (while mh-thread-history
1178 (let ((action (pop mh-thread-history)))
1179 (cond ((eq (car action) 'DROP)
1180 (mh-thread-remove-parent-link (cadr action))
1181 (mh-thread-add-link (caddr action) (cadr action)))
1182 ((eq (car action) 'PROMOTE)
1183 (let ((node (cadr action))
1184 (parent (caddr action))
1185 (children (cdddr action)))
1186 (dolist (child children)
1187 (mh-thread-remove-parent-link child)
1188 (mh-thread-add-link node child))
1189 (mh-thread-add-link parent node)))
1190 ((eq (car action) 'SUBJECT)
1191 (let ((node (cadr action)))
1192 (mh-thread-remove-parent-link node)
1193 (setf (mh-container-real-child-p node) t)))))))
1195 (defun mh-thread-prune-containers (roots)
1196 "Prune empty containers in the containers ROOTS."
1197 (let ((dfs-ordered-nodes ())
1200 (let ((node (pop work-list)))
1201 (dolist (child (mh-container-children node))
1202 (push child work-list))
1203 (push node dfs-ordered-nodes)))
1204 (while dfs-ordered-nodes
1205 (let ((node (pop dfs-ordered-nodes)))
1206 (cond ((gethash (mh-message-id (mh-container-message node))
1207 mh-thread-id-index-map)
1209 (setf (mh-container-children node)
1210 (mh-thread-sort-containers (mh-container-children node))))
1211 ((and (mh-container-children node)
1212 (or (null (cdr (mh-container-children node)))
1213 (mh-container-parent node)))
1215 (let ((children ()))
1216 (dolist (kid (mh-container-children node))
1217 (mh-thread-remove-parent-link kid)
1218 (mh-thread-add-link (mh-container-parent node) kid)
1219 (push kid children))
1220 (push `(PROMOTE ,node ,(mh-container-parent node) ,@children)
1222 (mh-thread-remove-parent-link node)))
1223 ((mh-container-children node)
1224 ;; Promote the first orphan to parent and add the other kids as
1226 (setf (mh-container-children node)
1227 (mh-thread-sort-containers (mh-container-children node)))
1228 (let ((new-parent (car (mh-container-children node)))
1229 (other-kids (cdr (mh-container-children node))))
1230 (mh-thread-remove-parent-link new-parent)
1231 (dolist (kid other-kids)
1232 (mh-thread-remove-parent-link kid)
1233 (setf (mh-container-real-child-p kid) nil)
1234 (mh-thread-add-link new-parent kid t))
1235 (push `(PROMOTE ,node ,(mh-container-parent node)
1236 ,new-parent ,@other-kids)
1238 (mh-thread-remove-parent-link node)))
1241 (push `(DROP ,node ,(mh-container-parent node))
1243 (mh-thread-remove-parent-link node)))))
1245 (maphash #'(lambda (k v)
1246 (declare (ignore k))
1247 (when (and (null (mh-container-parent v))
1248 (gethash (mh-message-id (mh-container-message v))
1249 mh-thread-id-index-map))
1252 (mh-thread-sort-containers results))))
1254 (defun mh-thread-sort-containers (containers)
1255 "Sort a list of message CONTAINERS to be in ascending order wrt index."
1258 (when (and (mh-container-message x) (mh-container-message y))
1259 (let* ((id-x (mh-message-id (mh-container-message x)))
1260 (id-y (mh-message-id (mh-container-message y)))
1261 (index-x (gethash id-x mh-thread-id-index-map))
1262 (index-y (gethash id-y mh-thread-id-index-map)))
1263 (and (integerp index-x) (integerp index-y)
1264 (< index-x index-y)))))))
1266 (defsubst mh-thread-group-by-subject (roots)
1267 "Group the set of message containers, ROOTS based on subject.
1268 Bug: Check for and make sure that something without Re: is made
1269 the parent in preference to something that has it."
1270 (clrhash mh-thread-subject-container-hash)
1272 (dolist (root roots)
1273 (let* ((subject (mh-thread-container-subject root))
1274 (parent (gethash subject mh-thread-subject-container-hash)))
1275 (cond (parent (mh-thread-remove-parent-link root)
1276 (mh-thread-add-link parent root t)
1277 (setf (mh-container-real-child-p root) nil)
1278 (push `(SUBJECT ,root) mh-thread-history))
1280 (setf (gethash subject mh-thread-subject-container-hash) root)
1281 (push root results)))))
1282 (nreverse results)))
1284 (defun mh-thread-process-in-reply-to (reply-to-header)
1285 "Extract message id's from REPLY-TO-HEADER.
1286 Ideally this should have some regexp which will try to guess if a
1287 string between < and > is a message id and not an email address.
1288 For now it will take the last string inside angles."
1289 (let ((end (mh-search-from-end ?> reply-to-header)))
1291 (let ((begin (mh-search-from-end ?< (substring reply-to-header 0 end))))
1292 (when (numberp begin)
1293 (list (substring reply-to-header begin (1+ end))))))))
1295 (defun mh-thread-set-tables (folder)
1296 "Use the tables of FOLDER in current buffer."
1297 (flet ((mh-get-table (symbol)
1300 (symbol-value symbol))))
1301 (setq mh-thread-id-hash (mh-get-table 'mh-thread-id-hash))
1302 (setq mh-thread-subject-hash (mh-get-table 'mh-thread-subject-hash))
1303 (setq mh-thread-id-table (mh-get-table 'mh-thread-id-table))
1304 (setq mh-thread-id-index-map (mh-get-table 'mh-thread-id-index-map))
1305 (setq mh-thread-index-id-map (mh-get-table 'mh-thread-index-id-map))
1306 (setq mh-thread-scan-line-map (mh-get-table 'mh-thread-scan-line-map))
1307 (setq mh-thread-subject-container-hash
1308 (mh-get-table 'mh-thread-subject-container-hash))
1309 (setq mh-thread-duplicates (mh-get-table 'mh-thread-duplicates))
1310 (setq mh-thread-history (mh-get-table 'mh-thread-history))))
1312 (defsubst mh-thread-update-id-index-maps (id index)
1313 "Message with id, ID is the message in INDEX.
1314 The function also checks for duplicate messages (that is multiple
1315 messages with the same ID). These messages are put in the
1316 `mh-thread-duplicates' hash table."
1317 (let ((old-index (gethash id mh-thread-id-index-map)))
1318 (when old-index (push old-index (gethash id mh-thread-duplicates)))
1319 (setf (gethash id mh-thread-id-index-map) index)
1320 (setf (gethash index mh-thread-index-id-map) id)))
1324 ;;; Generate Threads...
1326 (defvar mh-message-id-regexp "^<.*@.*>$"
1327 "Regexp to recognize whether a string is a message identifier.")
1329 (defun mh-thread-generate (folder msg-list)
1330 "Scan FOLDER to get info for threading.
1331 Only information about messages in MSG-LIST are added to the tree."
1333 (mh-thread-set-tables folder)
1336 #'call-process (expand-file-name mh-scan-prog mh-progs) nil '(t nil) nil
1337 "-width" "10000" "-format"
1338 "%(msg)\n%{message-id}\n%{references}\n%{in-reply-to}\n%{subject}\n"
1339 folder (mapcar #'(lambda (x) (format "%s" x)) msg-list)))
1340 (goto-char (point-min))
1342 (case-fold-search t))
1345 (block process-message
1347 (prog1 (buffer-substring (point) (line-end-position))
1349 (index (car (read-from-string index-line)))
1350 (id (prog1 (buffer-substring (point) (line-end-position))
1352 (refs (prog1 (buffer-substring (point) (line-end-position))
1354 (in-reply-to (prog1 (buffer-substring (point)
1355 (line-end-position))
1358 (buffer-substring (point) (line-end-position))
1361 (unless (gethash index mh-thread-scan-line-map)
1362 (return-from process-message))
1363 (unless (integerp index) (return)) ;Error message here
1364 (multiple-value-setq (subject subject-re-p)
1365 (mh-thread-prune-subject subject))
1366 (setq in-reply-to (mh-thread-process-in-reply-to in-reply-to))
1367 (setq refs (loop for x in (append (split-string refs) in-reply-to)
1368 when (string-match mh-message-id-regexp x)
1370 (setq id (mh-thread-canonicalize-id id))
1371 (mh-thread-update-id-index-maps id index)
1372 (setq refs (mapcar #'mh-thread-canonicalize-id refs))
1373 (mh-thread-get-message id subject-re-p subject refs)
1374 (do ((ancestors refs (cdr ancestors)))
1375 ((null (cdr ancestors))
1376 (when (car ancestors)
1377 (mh-thread-remove-parent-link id)
1378 (mh-thread-add-link (car ancestors) id)))
1379 (mh-thread-add-link (car ancestors) (cadr ancestors)))))))
1380 (maphash #'(lambda (k v)
1381 (declare (ignore k))
1382 (when (null (mh-container-parent v))
1385 (setq roots (mh-thread-prune-containers roots))
1386 (prog1 (setq roots (mh-thread-group-by-subject roots))
1387 (let ((history mh-thread-history))
1389 (setq mh-thread-history history))))))
1392 (defun mh-thread-inc (folder start-point)
1393 "Update thread tree for FOLDER.
1394 All messages after START-POINT are added to the thread tree."
1395 (mh-thread-rewind-pruning)
1396 (mh-remove-all-notation)
1397 (goto-char start-point)
1398 (let ((msg-list ()))
1400 (let ((index (mh-get-msg-num nil)))
1401 (when (numberp index)
1402 (push index msg-list)
1403 (setf (gethash index mh-thread-scan-line-map)
1404 (mh-thread-parse-scan-line)))
1406 (let ((thread-tree (mh-thread-generate folder msg-list))
1407 (buffer-read-only nil)
1408 (old-buffer-modified-flag (buffer-modified-p)))
1409 (delete-region (point-min) (point-max))
1410 (mh-thread-print-scan-lines thread-tree)
1411 (mh-notate-user-sequences)
1412 (mh-notate-deleted-and-refiled)
1414 (set-buffer-modified-p old-buffer-modified-flag))))
1416 (defun mh-thread-generate-scan-lines (tree level)
1417 "Generate scan lines.
1418 TREE is the hierarchical tree of messages, SCAN-LINE-MAP maps
1419 message indices to the corresponding scan lines and LEVEL used to
1420 determine indentation of the message."
1421 (cond ((null tree) nil)
1422 ((mh-thread-container-p tree)
1423 (let* ((message (mh-container-message tree))
1424 (id (mh-message-id message))
1425 (index (gethash id mh-thread-id-index-map))
1426 (duplicates (gethash id mh-thread-duplicates))
1427 (new-level (+ level 2))
1429 (force-angle-flag nil)
1430 (increment-level-flag nil))
1431 (dolist (scan-line (mapcar (lambda (x)
1432 (gethash x mh-thread-scan-line-map))
1433 (reverse (cons index duplicates))))
1435 (when (and dupl-flag (equal level 0)
1436 (mh-thread-ancestor-p mh-thread-last-ancestor tree))
1437 (setq level (+ level 2)
1438 new-level (+ new-level 2)
1439 force-angle-flag t))
1440 (when (equal level 0)
1441 (setq mh-thread-last-ancestor tree)
1442 (while (mh-container-parent mh-thread-last-ancestor)
1443 (setq mh-thread-last-ancestor
1444 (mh-container-parent mh-thread-last-ancestor))))
1445 (let* ((lev (if dupl-flag level new-level))
1446 (square-flag (or (and (mh-container-real-child-p tree)
1447 (not force-angle-flag)
1450 (insert (car scan-line)
1451 (format (format "%%%ss" lev) "")
1452 (if square-flag "[" "<")
1454 (if square-flag "]" ">")
1455 (truncate-string-to-width
1456 (caddr scan-line) (- mh-thread-body-width lev))
1458 (setq increment-level-flag t)
1459 (setq dupl-flag nil)))
1460 (unless increment-level-flag (setq new-level level))
1461 (dolist (child (mh-container-children tree))
1462 (mh-thread-generate-scan-lines child new-level))))
1463 (t (let ((nlevel (+ level 2)))
1465 (mh-thread-generate-scan-lines ch nlevel))))))
1467 ;; Another and may be better approach would be to generate all the info from
1468 ;; the scan which generates the threading info. For now this will have to do.
1469 (defun mh-thread-parse-scan-line (&optional string)
1471 If optional argument STRING is given then that is assumed to be
1472 the scan line. Otherwise uses the line at point as the scan line
1474 (let* ((string (or string
1475 (buffer-substring-no-properties (line-beginning-position)
1476 (line-end-position))))
1477 (address-start (+ mh-cmd-note mh-scan-field-from-start-offset))
1478 (body-start (+ mh-cmd-note mh-scan-field-from-end-offset))
1479 (first-string (substring string 0 address-start)))
1481 (substring string address-start (- body-start 2))
1482 (substring string body-start)
1486 (defun mh-thread-update-scan-line-map (msg notation offset)
1487 "In threaded view update `mh-thread-scan-line-map'.
1488 MSG is the message being notated with NOTATION at OFFSET."
1489 (let* ((msg (or msg (mh-get-msg-num nil)))
1490 (cur-scan-line (and mh-thread-scan-line-map
1491 (gethash msg mh-thread-scan-line-map)))
1492 (old-scan-lines (loop for map in mh-thread-scan-line-map-stack
1493 collect (and map (gethash msg map)))))
1495 (setf (aref (car cur-scan-line) offset) notation))
1496 (dolist (line old-scan-lines)
1497 (when line (setf (aref (car line) offset) notation)))))
1500 (defun mh-thread-add-spaces (count)
1501 "Add COUNT spaces to each scan line in `mh-thread-scan-line-map'."
1502 (let ((spaces (format (format "%%%ss" count) "")))
1504 (let* ((msg-num (mh-get-msg-num nil))
1505 (old-line (nth 3 (gethash msg-num mh-thread-scan-line-map))))
1506 (when (numberp msg-num)
1507 (setf (gethash msg-num mh-thread-scan-line-map)
1508 (mh-thread-parse-scan-line (format "%s%s" spaces old-line)))))
1511 (defun mh-thread-print-scan-lines (thread-tree)
1512 "Print scan lines in THREAD-TREE in threaded mode."
1513 (let ((mh-thread-body-width (- (window-width) mh-cmd-note
1514 (1- mh-scan-field-subject-start-offset)))
1515 (mh-thread-last-ancestor nil))
1516 (if (null mh-index-data)
1517 (mh-thread-generate-scan-lines thread-tree -2)
1518 (loop for x in (mh-index-group-by-folder)
1519 do (let* ((old-map mh-thread-scan-line-map)
1520 (mh-thread-scan-line-map (make-hash-table)))
1521 (setq mh-thread-last-ancestor nil)
1522 (loop for msg in (cdr x)
1523 do (let ((v (gethash msg old-map)))
1525 (setf (gethash msg mh-thread-scan-line-map) v))))
1526 (when (> (hash-table-count mh-thread-scan-line-map) 0)
1527 (insert (if (bobp) "" "\n") (car x) "\n")
1528 (mh-thread-generate-scan-lines thread-tree -2))))
1529 (mh-index-create-imenu-index))))
1531 (defun mh-thread-folder ()
1532 "Generate thread view of folder."
1533 (message "Threading %s..." (buffer-name))
1534 (mh-thread-initialize)
1535 (goto-char (point-min))
1536 (mh-remove-all-notation)
1537 (let ((msg-list ()))
1538 (mh-iterate-on-range msg (cons (point-min) (point-max))
1539 (setf (gethash msg mh-thread-scan-line-map) (mh-thread-parse-scan-line))
1540 (push msg msg-list))
1541 (let* ((range (mh-coalesce-msg-list msg-list))
1542 (thread-tree (mh-thread-generate (buffer-name) range)))
1543 (delete-region (point-min) (point-max))
1544 (mh-thread-print-scan-lines thread-tree)
1545 (mh-notate-user-sequences)
1546 (mh-notate-deleted-and-refiled)
1548 (message "Threading %s...done" (buffer-name)))))
1551 (defun mh-toggle-threads ()
1552 "Toggle threaded view of folder."
1554 (let ((msg-at-point (mh-get-msg-num nil))
1555 (old-buffer-modified-flag (buffer-modified-p))
1556 (buffer-read-only nil))
1557 (cond ((memq 'unthread mh-view-ops)
1558 (unless (mh-valid-view-change-operation-p 'unthread)
1559 (error "Can't unthread folder"))
1560 (let ((msg-list ()))
1561 (goto-char (point-min))
1563 (let ((index (mh-get-msg-num nil)))
1565 (push index msg-list)))
1567 (mh-scan-folder mh-current-folder
1568 (mapcar #'(lambda (x) (format "%s" x))
1569 (mh-coalesce-msg-list msg-list))
1572 (mh-index-insert-folder-headers)
1574 (t (mh-thread-folder)
1575 (push 'unthread mh-view-ops)))
1576 (when msg-at-point (mh-goto-msg msg-at-point t t))
1577 (set-buffer-modified-p old-buffer-modified-flag)
1581 (defun mh-thread-forget-message (index)
1582 "Forget the message INDEX from the threading tables."
1583 (let* ((id (gethash index mh-thread-index-id-map))
1584 (id-index (gethash id mh-thread-id-index-map))
1585 (duplicates (gethash id mh-thread-duplicates)))
1586 (remhash index mh-thread-index-id-map)
1587 (remhash index mh-thread-scan-line-map)
1588 (cond ((and (eql index id-index) (null duplicates))
1589 (remhash id mh-thread-id-index-map))
1590 ((eql index id-index)
1591 (setf (gethash id mh-thread-id-index-map) (car duplicates))
1592 (setf (gethash (car duplicates) mh-thread-index-id-map) id)
1593 (setf (gethash id mh-thread-duplicates) (cdr duplicates)))
1595 (setf (gethash id mh-thread-duplicates)
1596 (remove index duplicates))))))
1600 ;;; Operations on threads
1602 (defun mh-thread-current-indentation-level ()
1603 "Find the number of spaces by which current message is indented."
1605 (let ((address-start-offset (+ mh-cmd-note mh-scan-date-flag-width
1606 mh-scan-date-width 1))
1609 (forward-char address-start-offset)
1610 (while (char-equal (char-after) ? )
1616 (defun mh-thread-next-sibling (&optional previous-flag)
1617 "Display next sibling.
1619 With non-nil optional argument PREVIOUS-FLAG jump to the previous
1622 (cond ((not (memq 'unthread mh-view-ops))
1623 (error "Folder isn't threaded"))
1625 (error "No message at point")))
1627 (let ((point (point))
1629 (my-level (mh-thread-current-indentation-level)))
1630 (while (and (not done)
1631 (equal (forward-line (if previous-flag -1 1)) 0)
1633 (let ((level (mh-thread-current-indentation-level)))
1634 (cond ((equal level my-level)
1635 (setq done 'success))
1637 (message "No %s sibling" (if previous-flag "previous" "next"))
1638 (setq done 'failure)))))
1639 (cond ((eq done 'success) (mh-maybe-show))
1640 ((eq done 'failure) (goto-char point))
1641 (t (message "No %s sibling" (if previous-flag "previous" "next"))
1642 (goto-char point)))))
1645 (defun mh-thread-previous-sibling ()
1646 "Display previous sibling."
1648 (mh-thread-next-sibling t))
1650 (defun mh-thread-immediate-ancestor ()
1651 "Jump to immediate ancestor in thread tree."
1653 (let ((point (point))
1654 (ancestor-level (- (mh-thread-current-indentation-level) 2))
1656 (if (< ancestor-level 0)
1658 (while (and (not done) (equal (forward-line -1) 0))
1659 (when (equal ancestor-level (mh-thread-current-indentation-level))
1666 (defun mh-thread-ancestor (&optional thread-root-flag)
1667 "Display ancestor of current message.
1669 If you do not care for the way a particular thread has turned,
1670 you can move up the chain of messages with this command. This
1671 command can also take a prefix argument THREAD-ROOT-FLAG to jump
1672 to the message that started everything."
1675 (cond ((not (memq 'unthread mh-view-ops))
1676 (error "Folder isn't threaded"))
1678 (error "No message at point")))
1679 (let ((current-level (mh-thread-current-indentation-level)))
1680 (cond (thread-root-flag
1681 (while (mh-thread-immediate-ancestor))
1683 ((equal current-level 1)
1684 (message "Message has no ancestor"))
1685 (t (mh-thread-immediate-ancestor)
1688 (defun mh-thread-find-children ()
1689 "Return a region containing the current message and its children.
1690 The result is returned as a list of two elements. The first is
1691 the point at the start of the region and the second is the point
1696 (let ((address-start-offset (+ mh-cmd-note mh-scan-date-flag-width
1697 mh-scan-date-width 1))
1698 (level (mh-thread-current-indentation-level))
1700 (setq begin (point))
1701 (setq spaces (format (format "%%%ss" (1+ level)) ""))
1705 (forward-char address-start-offset)
1706 (unless (equal (string-match spaces (buffer-substring-no-properties
1707 (point) (line-end-position)))
1713 (list begin (point)))))
1716 (defun mh-thread-delete ()
1719 (cond ((not (memq 'unthread mh-view-ops))
1720 (error "Folder isn't threaded"))
1722 (error "No message at point"))
1723 (t (let ((region (mh-thread-find-children)))
1724 (mh-iterate-on-messages-in-region () (car region) (cadr region)
1725 (mh-delete-a-msg nil))
1729 (defun mh-thread-refile (folder)
1730 "Refile (output) thread into FOLDER."
1731 (interactive (list (intern (mh-prompt-for-refile-folder))))
1732 (cond ((not (memq 'unthread mh-view-ops))
1733 (error "Folder isn't threaded"))
1735 (error "No message at point"))
1736 (t (let ((region (mh-thread-find-children)))
1737 (mh-iterate-on-messages-in-region () (car region) (cadr region)
1738 (mh-refile-a-msg nil folder))
1743 ;; Tick mark handling
1746 (defun mh-toggle-tick (range)
1747 "Toggle tick mark of RANGE.
1749 This command adds messages to the \"tick\" sequence (which you can customize
1750 via the option `mh-tick-seq'). This sequence can be viewed later with the
1751 \\[mh-index-ticked-messages] command.
1753 Check the documentation of `mh-interactive-range' to see how RANGE is read in
1755 (interactive (list (mh-interactive-range "Tick")))
1757 (error "Enable ticking by customizing `mh-tick-seq'"))
1758 (let* ((tick-seq (mh-find-seq mh-tick-seq))
1759 (tick-seq-msgs (mh-seq-msgs tick-seq))
1762 (mh-iterate-on-range msg range
1763 (cond ((member msg tick-seq-msgs)
1765 (setcdr tick-seq (delq msg (cdr tick-seq)))
1766 (when (null (cdr tick-seq)) (setq mh-last-seq-used nil))
1767 (mh-remove-sequence-notation msg (mh-colors-in-use-p)))
1770 (setq mh-last-seq-used mh-tick-seq)
1771 (let ((mh-seq-list (cons `(,mh-tick-seq ,msg) mh-seq-list)))
1772 (mh-add-sequence-notation msg (mh-colors-in-use-p))))))
1773 (mh-add-msgs-to-seq ticked mh-tick-seq nil t)
1774 (mh-undefine-sequence mh-tick-seq unticked)
1776 (mh-index-add-to-sequence mh-tick-seq ticked)
1777 (mh-index-delete-from-sequence mh-tick-seq unticked))))
1780 (defun mh-narrow-to-tick ()
1781 "Limit to ticked messages.
1783 What this command does is show only those messages that are in
1784 the \"tick\" sequence (which you can customize via the
1785 `mh-tick-seq' option) in the MH-Folder buffer. In addition, it
1786 limits further MH-E searches to just those messages. When you
1787 want to widen the view to all your messages again, use
1790 (cond ((not mh-tick-seq)
1791 (error "Enable ticking by customizing `mh-tick-seq'"))
1792 ((null (mh-seq-msgs (mh-find-seq mh-tick-seq)))
1793 (message "No messages in %s sequence" mh-tick-seq))
1794 (t (mh-narrow-to-seq mh-tick-seq))))
1799 ;; indent-tabs-mode: nil
1800 ;; sentence-end-double-space: nil
1803 ;; arch-tag: 8e952711-01a2-485b-bf21-c9e3ad4de942
1804 ;;; mh-seq.el ends here