1 ;;; mh-seq.el --- MH-E sequences support
3 ;; Copyright (C) 1993, 1995, 2001, 02, 03, 2004 Free Software Foundation, Inc.
5 ;; Author: Bill Wohler <wohler@newt.com>
6 ;; Maintainer: Bill Wohler <wohler@newt.com>
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; This tries to implement the algorithm described at:
30 ;; http://www.jwz.org/doc/threading.html
31 ;; It is also a start to implementing the IMAP Threading extension RFC. The
32 ;; implementation lacks the reference and subject canonicalization of the
35 ;; In the presentation buffer, children messages are shown indented with
36 ;; either [ ] or < > around them. Square brackets ([ ]) denote that the
37 ;; algorithm can point out some headers which when taken together implies
38 ;; that the unindented message is an ancestor of the indented message. If
39 ;; no such proof exists then angles (< >) are used.
41 ;; Some issues and problems are as follows:
43 ;; (1) Scan truncates the fields at length 512. So longer references:
44 ;; headers get mutilated. The same kind of MH format string works when
45 ;; composing messages. Is there a way to avoid this? My scan command
47 ;; scan +folder -width 10000 \
48 ;; -format "%(msg)\n%{message-id}\n%{references}\n%{subject}\n"
49 ;; I would really appreciate it if someone would help me with this.
51 ;; (2) Implement heuristics to recognize message identifiers in
52 ;; In-Reply-To: header. Right now it just assumes that the last text
53 ;; between angles (< and >) is the message identifier. There is the
54 ;; chance that this will incorrectly use an email address like a
55 ;; message identifier.
57 ;; (3) Error checking of found message identifiers should be done.
59 ;; (4) Since this breaks the assumption that message indices increase as
60 ;; one goes down the buffer, the binary search based mh-goto-msg
61 ;; doesn't work. I have a simpler replacement which may be less
64 ;; (5) Better canonicalizing for message identifier and subject strings.
67 ;; Internal support for MH-E package.
73 (eval-when-compile (require 'mh-acros))
77 ;; Shush the byte-compiler
78 (defvar tool-bar-mode)
80 ;;; Data structures (used in message threading)...
81 (mh-defstruct (mh-thread-message (:conc-name mh-message-)
82 (:constructor mh-thread-make-message))
88 (mh-defstruct (mh-thread-container (:conc-name mh-container-)
89 (:constructor mh-thread-make-container))
90 message parent children
94 ;;; Internal variables:
95 (defvar mh-last-seq-used nil
96 "Name of seq to which a msg was last added.")
98 (defvar mh-non-seq-mode-line-annotation nil
99 "Saved value of `mh-mode-line-annotation' when narrowed to a seq.")
101 ;;; Maps and hashes...
102 (defvar mh-thread-id-hash nil
103 "Hashtable used to canonicalize message identifiers.")
104 (defvar mh-thread-subject-hash nil
105 "Hashtable used to canonicalize subject strings.")
106 (defvar mh-thread-id-table nil
107 "Thread ID table maps from message identifiers to message containers.")
108 (defvar mh-thread-id-index-map nil
109 "Table to look up message index number from message identifier.")
110 (defvar mh-thread-index-id-map nil
111 "Table to look up message identifier from message index.")
112 (defvar mh-thread-scan-line-map nil
113 "Map of message index to various parts of the scan line.")
114 (defvar mh-thread-scan-line-map-stack nil
115 "Old map of message index to various parts of the scan line.
116 This is the original map that is stored when the folder is narrowed.")
117 (defvar mh-thread-subject-container-hash nil
118 "Hashtable used to group messages by subject.")
119 (defvar mh-thread-duplicates nil
120 "Hashtable used to associate messages with the same message identifier.")
121 (defvar mh-thread-history ()
122 "Variable to remember the transformations to the thread tree.
123 When new messages are added, these transformations are rewound, then the
124 links are added from the newly seen messages. Finally the transformations are
125 redone to get the new thread tree. This makes incremental threading easier.")
126 (defvar mh-thread-body-width nil
127 "Width of scan substring that contains subject and body of message.")
129 (make-variable-buffer-local 'mh-thread-id-hash)
130 (make-variable-buffer-local 'mh-thread-subject-hash)
131 (make-variable-buffer-local 'mh-thread-id-table)
132 (make-variable-buffer-local 'mh-thread-id-index-map)
133 (make-variable-buffer-local 'mh-thread-index-id-map)
134 (make-variable-buffer-local 'mh-thread-scan-line-map)
135 (make-variable-buffer-local 'mh-thread-scan-line-map-stack)
136 (make-variable-buffer-local 'mh-thread-subject-container-hash)
137 (make-variable-buffer-local 'mh-thread-duplicates)
138 (make-variable-buffer-local 'mh-thread-history)
141 (defun mh-delete-seq (sequence)
142 "Delete the SEQUENCE."
143 (interactive (list (mh-read-seq-default "Delete" t)))
144 (let ((msg-list (mh-seq-to-msgs sequence))
145 (internal-flag (mh-internal-seq sequence))
146 (folders-changed (list mh-current-folder)))
147 (mh-iterate-on-range msg sequence
148 (mh-remove-sequence-notation msg internal-flag))
149 (mh-undefine-sequence sequence '("all"))
150 (mh-delete-seq-locally sequence)
152 (setq folders-changed
153 (append folders-changed
154 (mh-index-delete-from-sequence sequence msg-list))))
155 (when (and (eq sequence mh-unseen-seq) (mh-speed-flists-active-p))
156 (apply #'mh-speed-flists t folders-changed))))
158 ;; Avoid compiler warnings
159 (defvar view-exit-action)
162 (defun mh-list-sequences ()
163 "List the sequences defined in the folder being visited."
165 (let ((folder mh-current-folder)
166 (temp-buffer mh-sequences-buffer)
167 (seq-list mh-seq-list)
169 (with-output-to-temp-buffer temp-buffer
171 (set-buffer temp-buffer)
173 (message "Listing sequences ...")
174 (insert "Sequences in folder " folder ":\n")
175 (let ((seq-list seq-list))
178 (max (length (symbol-name (mh-seq-name (pop seq-list))))
180 (setq max-len (+ 2 max-len)))
182 (let ((name (mh-seq-name (car seq-list)))
184 (mh-coalesce-msg-list
185 (sort (copy-sequence (mh-seq-msgs (car seq-list))) '<)))
187 (insert (setq name-spec (format (format "%%%ss:" max-len) name)))
188 (while sorted-seq-msgs
189 (let ((next-element (format " %s" (pop sorted-seq-msgs))))
190 (when (>= (+ (current-column) (length next-element))
193 (insert (format (format "%%%ss" (length name-spec)) "")))
194 (insert next-element)))
196 (setq seq-list (cdr seq-list)))
197 (goto-char (point-min))
199 (setq view-exit-action 'kill-buffer)
200 (message "Listing sequences...done")))))
203 (defun mh-msg-is-in-seq (message)
204 "Display the sequences in which the current message appears.
205 Use a prefix argument to display the sequences in which another MESSAGE
209 (setq message (mh-get-msg-num t)))
210 (let* ((dest-folder (loop for seq in mh-refile-list
211 when (member message (cdr seq)) return (car seq)
213 (deleted-flag (unless dest-folder (member message mh-delete-list))))
214 (message "Message %d%s is in sequences: %s"
216 (cond (dest-folder (format " (to be refiled to %s)" dest-folder))
217 (deleted-flag (format " (to be deleted)"))
220 (mh-list-to-string (mh-seq-containing-msg message t))
223 ;; Avoid compiler warning
224 (defvar tool-bar-map)
227 (defun mh-narrow-to-seq (sequence)
228 "Restrict display of this folder to just messages in SEQUENCE.
229 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
230 (interactive (list (mh-read-seq "Narrow to" t)))
231 (with-mh-folder-updating (t)
232 (cond ((mh-seq-to-msgs sequence)
233 (mh-remove-all-notation)
234 (let ((eob (point-max))
235 (msg-at-cursor (mh-get-msg-num nil)))
236 (push mh-thread-scan-line-map mh-thread-scan-line-map-stack)
237 (setq mh-thread-scan-line-map (make-hash-table :test #'eql))
238 (mh-copy-seq-to-eob sequence)
239 (push (buffer-substring-no-properties (point-min) eob)
240 mh-folder-view-stack)
241 (delete-region (point-min) eob)
242 (mh-notate-deleted-and-refiled)
244 (when msg-at-cursor (mh-goto-msg msg-at-cursor t t))
245 (make-variable-buffer-local 'mh-non-seq-mode-line-annotation)
246 (setq mh-non-seq-mode-line-annotation mh-mode-line-annotation)
247 (setq mh-mode-line-annotation (symbol-name sequence))
248 (mh-make-folder-mode-line)
250 (when (and (boundp 'tool-bar-mode) tool-bar-mode)
251 (set (make-local-variable 'tool-bar-map)
252 mh-folder-seq-tool-bar-map)
253 (when (buffer-live-p (get-buffer mh-show-buffer))
255 (set-buffer (get-buffer mh-show-buffer))
256 (set (make-local-variable 'tool-bar-map)
257 mh-show-seq-tool-bar-map))))
258 (push 'widen mh-view-ops)))
260 (error "No messages in sequence `%s'" (symbol-name sequence))))))
263 (defun mh-put-msg-in-seq (range sequence)
264 "Add RANGE to SEQUENCE.
266 Check the documentation of `mh-interactive-range' to see how RANGE is read in
268 (interactive (list (mh-interactive-range "Add messages from")
269 (mh-read-seq-default "Add to" nil)))
270 (unless (mh-valid-seq-p sequence)
271 (error "Can't put message in invalid sequence `%s'" sequence))
272 (let* ((internal-seq-flag (mh-internal-seq sequence))
273 (original-msgs (mh-seq-msgs (mh-find-seq sequence)))
274 (folders (list mh-current-folder))
275 (msg-list (mh-range-to-msg-list range)))
276 (mh-add-msgs-to-seq msg-list sequence nil t)
277 (mh-iterate-on-range m range
278 (unless (memq m original-msgs)
279 (mh-add-sequence-notation m internal-seq-flag)))
280 (if (not internal-seq-flag)
281 (setq mh-last-seq-used sequence))
284 (append folders (mh-index-add-to-sequence sequence msg-list))))
285 (when (and (eq sequence mh-unseen-seq) (mh-speed-flists-active-p))
286 (apply #'mh-speed-flists t folders))))
288 (defun mh-valid-view-change-operation-p (op)
289 "Check if the view change operation can be performed.
290 OP is one of 'widen and 'unthread."
291 (cond ((eq (car mh-view-ops) op)
296 (defun mh-widen (&optional all-flag)
297 "Restore the previous limit.
298 If optional prefix argument ALL-FLAG is non-nil, remove all limits."
300 (let ((msg (mh-get-msg-num nil)))
301 (when mh-folder-view-stack
303 (while (cdr mh-view-ops)
304 (setq mh-view-ops (cdr mh-view-ops)))
305 (when (eq (car mh-view-ops) 'widen)
306 (setq mh-view-ops (cdr mh-view-ops))))
307 ((mh-valid-view-change-operation-p 'widen) nil)
308 ((memq 'widen mh-view-ops)
309 (while (not (eq (car mh-view-ops) 'widen))
310 (setq mh-view-ops (cdr mh-view-ops)))
311 (setq mh-view-ops (cdr mh-view-ops)))
312 (t (error "Widening is not applicable")))
313 ;; If ALL-FLAG is non-nil then rewind stacks
315 (while (cdr mh-thread-scan-line-map-stack)
316 (setq mh-thread-scan-line-map-stack
317 (cdr mh-thread-scan-line-map-stack)))
318 (while (cdr mh-folder-view-stack)
319 (setq mh-folder-view-stack (cdr mh-folder-view-stack))))
320 (setq mh-thread-scan-line-map (pop mh-thread-scan-line-map-stack))
321 (with-mh-folder-updating (t)
322 (delete-region (point-min) (point-max))
323 (insert (pop mh-folder-view-stack))
324 (mh-remove-all-notation)
325 (setq mh-mode-line-annotation mh-non-seq-mode-line-annotation)
326 (mh-make-folder-mode-line))
328 (mh-goto-msg msg t t))
329 (mh-notate-deleted-and-refiled)
330 (mh-notate-user-sequences)
333 (when (and (null mh-folder-view-stack) (boundp 'tool-bar-mode) tool-bar-mode)
334 (set (make-local-variable 'tool-bar-map) mh-folder-tool-bar-map)
335 (when (buffer-live-p (get-buffer mh-show-buffer))
337 (set-buffer (get-buffer mh-show-buffer))
338 (set (make-local-variable 'tool-bar-map) mh-show-tool-bar-map)))))
340 ;; FIXME? We may want to clear all notations and add one for current-message
341 ;; and process user sequences.
343 (defun mh-notate-deleted-and-refiled ()
344 "Notate messages marked for deletion or refiling.
345 Messages to be deleted are given by `mh-delete-list' while messages to be
346 refiled are present in `mh-refile-list'."
347 (let ((refiled-hash (make-hash-table))
348 (deleted-hash (make-hash-table)))
349 (dolist (msg mh-delete-list)
350 (setf (gethash msg deleted-hash) t))
351 (dolist (dest-msg-list mh-refile-list)
352 (dolist (msg (cdr dest-msg-list))
353 (setf (gethash msg refiled-hash) t)))
354 (mh-iterate-on-messages-in-region msg (point-min) (point-max)
355 (cond ((gethash msg refiled-hash)
356 (mh-notate nil mh-note-refiled mh-cmd-note))
357 ((gethash msg deleted-hash)
358 (mh-notate nil mh-note-deleted mh-cmd-note))))))
362 ;;; Commands to manipulate sequences. Sequences are stored in an alist
364 ;;; ((seq-name msgs ...) (seq-name msgs ...) ...)
366 (defvar mh-sequence-history ())
369 (defun mh-read-seq-default (prompt not-empty)
370 "Read and return sequence name with default narrowed or previous sequence.
371 PROMPT is the prompt to use when reading. If NOT-EMPTY is non-nil then a
372 non-empty sequence is read."
373 (mh-read-seq prompt not-empty
375 (car (mh-seq-containing-msg (mh-get-msg-num nil) nil)))))
377 (defun mh-read-seq (prompt not-empty &optional default)
378 "Read and return a sequence name.
379 Prompt with PROMPT, raise an error if the sequence is empty and the NOT-EMPTY
380 flag is non-nil, and supply an optional DEFAULT sequence. A reply of '%'
381 defaults to the first sequence containing the current message."
382 (let* ((input (completing-read (format "%s %s %s" prompt "sequence:"
384 (format "[%s] " default)
386 (mh-seq-names mh-seq-list)
387 nil nil nil 'mh-sequence-history))
388 (seq (cond ((equal input "%")
389 (car (mh-seq-containing-msg (mh-get-msg-num t) nil)))
390 ((equal input "") default)
392 (msgs (mh-seq-to-msgs seq)))
393 (if (and (null msgs) not-empty)
394 (error "No messages in sequence `%s'" seq))
397 ;;; Functions to read ranges with completion...
398 (defvar mh-range-seq-names)
399 (defvar mh-range-history ())
400 (defvar mh-range-completion-map (copy-keymap minibuffer-local-completion-map))
401 (define-key mh-range-completion-map " " 'self-insert-command)
403 (defun mh-range-completion-function (string predicate flag)
404 "Programmable completion of message ranges.
405 STRING is the user input that is to be completed. PREDICATE if non-nil is a
406 function used to filter the possible choices and FLAG determines whether the
408 (let* ((candidates mh-range-seq-names)
409 (last-char (and (not (equal string ""))
410 (aref string (1- (length string)))))
411 (last-word (cond ((null last-char) "")
412 ((memq last-char '(? ?- ?:)) "")
413 (t (car (last (split-string string "[ -:]+"))))))
414 (prefix (substring string 0 (- (length string) (length last-word)))))
416 (let ((res (try-completion last-word candidates predicate)))
417 (cond ((null res) nil)
419 (t (concat prefix res)))))
421 (all-completions last-word candidates predicate))
423 (loop for x in candidates
424 when (equal x last-word) return t
425 finally return nil)))))
428 (defun mh-read-range (prompt &optional folder default
429 expand-flag ask-flag number-as-range-flag)
430 "Read a message range with PROMPT.
432 If FOLDER is non-nil then a range is read from that folder, otherwise use
435 If DEFAULT is a string then use that as default range to return. If DEFAULT is
436 nil then ask user with default answer a range based on the sequences that seem
437 relevant. Finally if DEFAULT is t, try to avoid prompting the user. Unseen
438 messages, if present, are returned. If the folder has fewer than
439 `mh-large-folder' messages then \"all\" messages are returned. Finally as a
440 last resort prompt the user.
442 If EXPAND-FLAG is non-nil then a list of message numbers corresponding to the
443 input is returned. If this list is empty then an error is raised. If
444 EXPAND-FLAG is nil just return the input string. In this case we don't check
445 if the range is empty.
447 If ASK-FLAG is non-nil, then the user is always queried for a range of
448 messages. If ASK-FLAG is nil, then the function checks if the unseen sequence
449 is non-empty. If that is the case, `mh-unseen-seq', or the list of messages in
450 it depending on the value of EXPAND, is returned. Otherwise if the folder has
451 fewer than `mh-large-folder' messages then the list of messages corresponding
452 to \"all\" is returned. If neither of the above holds then as a last resort
453 the user is queried for a range of messages.
455 If NUMBER-AS-RANGE-FLAG is non-nil, then if a number, N is read as input, it
456 is interpreted as the range \"last:N\".
458 This function replaces the existing function `mh-read-msg-range'. Calls to:
459 (mh-read-msg-range folder flag)
460 should be replaced with:
461 (mh-read-range \"Suitable prompt\" folder t nil flag
462 mh-interpret-number-as-range-flag)"
463 (setq default (or default mh-last-seq-used
464 (car (mh-seq-containing-msg (mh-get-msg-num nil) t)))
465 prompt (format "%s range" prompt))
466 (let* ((folder (or folder mh-current-folder))
467 (default (cond ((or (eq default t) (stringp default)) default)
468 ((symbolp default) (symbol-name default))))
469 (guess (eq default t))
470 (counts (and guess (mh-folder-size folder)))
471 (unseen (and counts (> (cadr counts) 0)))
472 (large (and counts mh-large-folder (> (car counts) mh-large-folder)))
473 (str (cond ((and guess large
474 (setq default (format "last:%s" mh-large-folder)
475 prompt (format "%s (folder has %s messages)"
476 prompt (car counts)))
478 ((and guess (not large) (setq default "all") nil))
479 ((eq default nil) "")
480 (t (format "[%s] " default))))
481 (minibuffer-local-completion-map mh-range-completion-map)
482 (seq-list (if (eq folder mh-current-folder)
484 (mh-read-folder-sequences folder nil)))
486 (append '(("first") ("last") ("all") ("prev") ("next"))
487 (mh-seq-names seq-list)))
488 (input (cond ((and (not ask-flag) unseen) (symbol-name mh-unseen-seq))
489 ((and (not ask-flag) (not large)) "all")
490 (t (completing-read (format "%s: %s" prompt str)
491 'mh-range-completion-function nil nil
492 nil 'mh-range-history default))))
494 (when (and number-as-range-flag
495 (string-match "^[ \t]*\\([0-9]+\\)[ \t]*$" input))
496 (setq input (concat "last:" (match-string 1 input))))
497 (cond ((not expand-flag) input)
498 ((assoc (intern input) seq-list)
499 (cdr (assoc (intern input) seq-list)))
500 ((setq msg-list (mh-translate-range folder input)) msg-list)
501 (t (error "No messages in range `%s'" input)))))
504 (defun mh-translate-range (folder expr)
505 "In FOLDER, translate the string EXPR to a list of messages numbers."
507 (let ((strings (delete "" (split-string expr "[ \t\n]")))
510 (apply #'mh-exec-cmd-quiet nil "mhpath" folder strings)
511 (set-buffer mh-temp-buffer)
512 (goto-char (point-min))
513 (while (re-search-forward "/\\([0-9]*\\)$" nil t)
514 (push (car (read-from-string (match-string 1))) result))
515 (nreverse result)))))
517 (defun mh-seq-names (seq-list)
518 "Return an alist containing the names of the SEQ-LIST."
519 (mapcar (lambda (entry) (list (symbol-name (mh-seq-name entry))))
523 (defun mh-rename-seq (sequence new-name)
524 "Rename SEQUENCE to have NEW-NAME."
525 (interactive (list (mh-read-seq "Old" t)
526 (intern (read-string "New sequence name: "))))
527 (let ((old-seq (mh-find-seq sequence)))
529 (error "Sequence %s does not exist" sequence))
530 ;; create new sequence first, since it might raise an error.
531 (mh-define-sequence new-name (mh-seq-msgs old-seq))
532 (mh-undefine-sequence sequence (mh-seq-msgs old-seq))
533 (rplaca old-seq new-name)))
536 (defun mh-notate-cur ()
537 "Mark the MH sequence cur.
538 In addition to notating the current message with `mh-note-cur' the function
539 uses `overlay-arrow-position' to put a marker in the fringe."
540 (let ((cur (car (mh-seq-to-msgs 'cur))))
541 (when (and cur (mh-goto-msg cur t t))
543 (when (looking-at mh-scan-good-msg-regexp)
544 (mh-notate nil mh-note-cur mh-cmd-note))
545 (setq mh-arrow-marker (set-marker mh-arrow-marker (point)))
546 (setq overlay-arrow-position mh-arrow-marker))))
549 (defun mh-add-to-sequence (seq msgs)
550 "The sequence SEQ is augmented with the messages in MSGS."
551 ;; Add to a SEQUENCE each message the list of MSGS.
552 (if (and (mh-valid-seq-p seq) (not (mh-folder-name-p seq)))
554 (apply 'mh-exec-cmd "mark" mh-current-folder "-add"
555 "-sequence" (symbol-name seq)
556 (mh-coalesce-msg-list msgs)))))
558 (defvar mh-thread-last-ancestor)
560 (defun mh-copy-seq-to-eob (seq)
561 "Copy SEQ to the end of the buffer."
562 ;; It is quite involved to write something which will work at any place in
563 ;; the buffer, so we will write something which works only at the end of
564 ;; the buffer. If we ever need to insert sequences in the middle of the
565 ;; buffer, this will need to be fixed.
567 (let* ((msgs (mh-seq-to-msgs seq))
568 (coalesced-msgs (mh-coalesce-msg-list msgs)))
569 (goto-char (point-max))
571 (narrow-to-region (point) (point))
572 (mh-regenerate-headers coalesced-msgs t)
573 (cond ((memq 'unthread mh-view-ops)
574 ;; Populate restricted scan-line map
575 (mh-remove-all-notation)
576 (mh-iterate-on-range msg (cons (point-min) (point-max))
577 (setf (gethash msg mh-thread-scan-line-map)
578 (mh-thread-parse-scan-line)))
579 ;; Remove scan lines and read results from pre-computed tree
580 (delete-region (point-min) (point-max))
581 (mh-thread-print-scan-lines
582 (mh-thread-generate mh-current-folder ()))
583 (mh-notate-user-sequences))
585 (mh-index-insert-folder-headers)))))))
588 (defmacro mh-iterate-on-messages-in-region (var begin end &rest body)
589 "Iterate over region.
590 VAR is bound to the message on the current line as we loop starting from BEGIN
591 till END. In each step BODY is executed.
593 If VAR is nil then the loop is executed without any binding."
594 (unless (symbolp var)
595 (error "Can not bind the non-symbol %s" var))
596 (let ((binding-needed-flag var))
600 (while (and (<= (point) ,end) (not (eobp)))
601 (when (looking-at mh-scan-valid-regexp)
602 (let ,(if binding-needed-flag `((,var (mh-get-msg-num t))) ())
606 (put 'mh-iterate-on-messages-in-region 'lisp-indent-hook 'defun)
609 (defmacro mh-iterate-on-range (var range &rest body)
610 "Iterate an operation over a region or sequence.
612 VAR is bound to each message in turn in a loop over RANGE, which can be a
613 message number, a list of message numbers, a sequence, a region in a cons
614 cell, or a MH range (something like last:20) in a string. In each iteration,
617 The parameter RANGE is usually created with `mh-interactive-range'
618 in order to provide a uniform interface to MH-E functions."
619 (unless (symbolp var)
620 (error "Can not bind the non-symbol %s" var))
621 (let ((binding-needed-flag var)
622 (msgs (make-symbol "msgs"))
623 (seq-hash-table (make-symbol "seq-hash-table")))
624 `(cond ((numberp ,range)
625 (when (mh-goto-msg ,range t t)
626 (let ,(if binding-needed-flag `((,var ,range)) ())
629 (numberp (car ,range)) (numberp (cdr ,range)))
630 (mh-iterate-on-messages-in-region ,var
631 (car ,range) (cdr ,range)
633 (t (let ((,msgs (cond ((and ,range (symbolp ,range))
634 (mh-seq-to-msgs ,range))
636 (mh-translate-range mh-current-folder
639 (,seq-hash-table (make-hash-table)))
641 (setf (gethash msg ,seq-hash-table) t))
642 (mh-iterate-on-messages-in-region v (point-min) (point-max)
643 (when (gethash v ,seq-hash-table)
644 (let ,(if binding-needed-flag `((,var v)) ())
647 (put 'mh-iterate-on-range 'lisp-indent-hook 'defun)
650 (defun mh-range-to-msg-list (range)
651 "Return a list of messages for RANGE.
652 RANGE can be a message number, a list of message numbers, a sequence, or
653 a region in a cons cell."
655 (mh-iterate-on-range msg range
657 (nreverse msg-list)))
660 (defun mh-interactive-range (range-prompt &optional default)
661 "Return interactive specification for message, sequence, range or region.
662 By convention, the name of this argument is RANGE.
664 If variable `transient-mark-mode' is non-nil and the mark is active, then this
665 function returns a cons-cell of the region.
667 If optional prefix argument is provided, then prompt for message range with
668 RANGE-PROMPT. A list of messages in that range is returned.
670 If a MH range is given, say something like last:20, then a list containing
671 the messages in that range is returned.
673 If DEFAULT non-nil then it is returned.
675 Otherwise, the message number at point is returned.
677 This function is usually used with `mh-iterate-on-range' in order to provide
678 a uniform interface to MH-E functions."
679 (cond ((mh-mark-active-p t) (cons (region-beginning) (region-end)))
680 (current-prefix-arg (mh-read-range range-prompt nil nil t t))
682 (t (mh-get-msg-num t))))
686 ;;; Commands to handle new 'subject sequence.
687 ;;; Or "Poor man's threading" by psg.
689 ;;; XXX: The function mh-subject-to-sequence-unthreaded uses the magic number
690 ;;; 41 for the max size of the subject part. Avoiding this would be desirable.
691 (defun mh-subject-to-sequence (all)
692 "Put all following messages with same subject in sequence 'subject.
693 If arg ALL is t, move to beginning of folder buffer to collect all messages.
694 If arg ALL is nil, collect only messages fron current one on forward.
696 Return number of messages put in the sequence:
698 nil -> there was no subject line.
699 0 -> there were no later messages with the same subject (sequence not made)
700 >1 -> the total number of messages including current one."
701 (if (memq 'unthread mh-view-ops)
702 (mh-subject-to-sequence-threaded all)
703 (mh-subject-to-sequence-unthreaded all)))
705 (defun mh-subject-to-sequence-unthreaded (all)
706 "Put all following messages with same subject in sequence 'subject.
707 This function only works with an unthreaded folder. If arg ALL is t, move to
708 beginning of folder buffer to collect all messages. If arg ALL is nil, collect
709 only messages fron current one on forward.
711 Return number of messages put in the sequence:
713 nil -> there was no subject line.
714 0 -> there were no later messages with the same subject (sequence not made)
715 >1 -> the total number of messages including current one."
716 (if (not (eq major-mode 'mh-folder-mode))
717 (error "Not in a folder buffer"))
720 (if (or (not (looking-at mh-scan-subject-regexp))
721 (not (match-string 3))
722 (string-equal "" (match-string 3)))
723 (progn (message "No subject line")
725 (let ((subject (match-string-no-properties 3))
727 (if (> (length subject) 41)
728 (setq subject (substring subject 0 41)))
731 (goto-char (point-min)))
732 (while (re-search-forward mh-scan-subject-regexp nil t)
733 (let ((this-subject (match-string-no-properties 3)))
734 (if (> (length this-subject) 41)
735 (setq this-subject (substring this-subject 0 41)))
736 (if (string-equal this-subject subject)
737 (setq list (cons (mh-get-msg-num t) list))))))
740 ;; If we created a new sequence, add the initial message to it too.
741 (if (not (member (mh-get-msg-num t) list))
742 (setq list (cons (mh-get-msg-num t) list)))
743 (if (assoc 'subject mh-seq-list) (mh-delete-seq 'subject))
744 ;; sort the result into a sequence
745 (let ((sorted-list (sort (copy-sequence list) 'mh-lessp)))
747 (mh-add-msgs-to-seq (car sorted-list) 'subject nil)
748 (setq sorted-list (cdr sorted-list)))
753 (defun mh-subject-to-sequence-threaded (all)
754 "Put all messages with the same subject in the 'subject sequence.
755 This function works when the folder is threaded. In this situation the subject
756 could get truncated and so the normal matching doesn't work.
758 The parameter ALL is non-nil then all the messages in the buffer are
759 considered, otherwise only the messages after the current one are taken into
761 (let* ((cur (mh-get-msg-num nil))
762 (subject (mh-thread-find-msg-subject cur))
765 (and (message "No subject line") nil)
766 (setq region (cons (if all (point-min) (point)) (point-max)))
767 (mh-iterate-on-range msg region
768 (when (eq (mh-thread-find-msg-subject msg) subject)
770 (setq msgs (sort msgs #'mh-lessp))
773 (when (assoc 'subject mh-seq-list)
774 (mh-delete-seq 'subject))
775 (mh-add-msgs-to-seq msgs 'subject)
778 (defun mh-thread-find-msg-subject (msg)
779 "Find canonicalized subject of MSG.
780 This function can only be used the folder is threaded."
783 (mh-container-message (gethash (gethash msg mh-thread-index-id-map)
784 mh-thread-id-table)))))
786 (defun mh-edit-pick-expr (default)
787 "With prefix arg edit a pick expression.
788 If no prefix arg is given, then return DEFAULT."
789 (let ((default-string (loop for x in default concat (format " %s" x))))
790 (if (or current-prefix-arg (equal default-string ""))
791 (delete "" (split-string (read-string "Pick expression: "
796 (defun mh-narrow-to-subject (&optional pick-expr)
797 "Limit to messages with same subject.
798 With a prefix argument, edit PICK-EXPR.
800 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
802 (list (mh-edit-pick-expr (mh-current-message-header-field 'subject))))
803 (mh-narrow-to-header-field 'subject pick-expr))
806 (defun mh-narrow-to-from (&optional pick-expr)
807 "Limit to messages with the same `From:' field.
808 With a prefix argument, edit PICK-EXPR.
810 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
812 (list (mh-edit-pick-expr (mh-current-message-header-field 'from))))
813 (mh-narrow-to-header-field 'from pick-expr))
816 (defun mh-narrow-to-cc (&optional pick-expr)
817 "Limit to messages with the same `Cc:' field.
818 With a prefix argument, edit PICK-EXPR.
820 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
822 (list (mh-edit-pick-expr (mh-current-message-header-field 'cc))))
823 (mh-narrow-to-header-field 'cc pick-expr))
826 (defun mh-narrow-to-to (&optional pick-expr)
827 "Limit to messages with the same `To:' field.
828 With a prefix argument, edit PICK-EXPR.
830 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
832 (list (mh-edit-pick-expr (mh-current-message-header-field 'to))))
833 (mh-narrow-to-header-field 'to pick-expr))
835 (defun mh-narrow-to-header-field (header-field pick-expr)
836 "Limit to messages whose HEADER-FIELD match PICK-EXPR.
837 The MH command pick is used to do the match."
838 (let ((folder mh-current-folder)
839 (original (mh-coalesce-msg-list
840 (mh-range-to-msg-list (cons (point-min) (point-max)))))
843 (apply #'mh-exec-cmd-output "pick" nil folder
844 (append original (list "-list") pick-expr))
845 (goto-char (point-min))
847 (let ((num (read-from-string
848 (buffer-substring (point) (line-end-position)))))
849 (when (numberp (car num)) (push (car num) msg-list))
852 (message "No matches")
853 (when (assoc 'header mh-seq-list) (mh-delete-seq 'header))
854 (mh-add-msgs-to-seq msg-list 'header)
855 (mh-narrow-to-seq 'header))))
857 (defun mh-current-message-header-field (header-field)
858 "Return a pick regexp to match HEADER-FIELD of the message at point."
859 (let ((num (mh-get-msg-num nil)))
861 (let ((folder mh-current-folder))
863 (insert-file-contents-literally (mh-msg-filename num folder))
864 (goto-char (point-min))
865 (when (search-forward "\n\n" nil t)
866 (narrow-to-region (point-min) (point)))
867 (let* ((field (or (message-fetch-field (format "%s" header-field))
869 (field-option (format "-%s" header-field))
870 (patterns (loop for x in (split-string field "[ ]*,[ ]*")
872 collect (if (string-match "<\\(.*@.*\\)>" x)
876 (loop with accum = `(,field-option ,(car patterns))
877 for e in (cdr patterns)
878 do (setq accum `(,field-option ,e "-or" ,@accum))
879 finally return accum))))))))
882 (defun mh-narrow-to-range (range)
883 "Limit to messages in RANGE.
885 Check the documentation of `mh-interactive-range' to see how RANGE is read in
888 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
889 (interactive (list (mh-interactive-range "Narrow to")))
890 (when (assoc 'range mh-seq-list) (mh-delete-seq 'range))
891 (mh-add-msgs-to-seq (mh-range-to-msg-list range) 'range)
892 (mh-narrow-to-seq 'range))
896 (defun mh-delete-subject ()
897 "Mark all following messages with same subject to be deleted.
898 This puts the messages in a sequence named subject. You can undo the last
899 deletion marks using `mh-undo' with a prefix argument and then specifying the
902 (let ((count (mh-subject-to-sequence nil)))
904 ((not count) ; No subject line, delete msg anyway
905 (mh-delete-msg (mh-get-msg-num t)))
906 ((= 0 count) ; No other msgs, delete msg anyway.
907 (message "No other messages with same Subject following this one")
908 (mh-delete-msg (mh-get-msg-num t)))
909 (t ; We have a subject sequence.
910 (message "Marked %d messages for deletion" count)
911 (mh-delete-msg 'subject)))))
914 (defun mh-delete-subject-or-thread ()
915 "Mark messages for deletion intelligently.
916 If the folder is threaded then `mh-thread-delete' is used to mark the current
917 message and all its descendants for deletion. Otherwise `mh-delete-subject' is
918 used to mark the current message and all messages following it with the same
919 subject for deletion."
921 (if (memq 'unthread mh-view-ops)
923 (mh-delete-subject)))
925 ;;; Message threading:
927 (defmacro mh-thread-initialize-hash (var test)
928 "Initialize the hash table in VAR.
929 TEST is the test to use when creating a new hash table."
930 (unless (symbolp var) (error "Expected a symbol: %s" var))
931 `(if ,var (clrhash ,var) (setq ,var (make-hash-table :test ,test))))
933 (defun mh-thread-initialize ()
934 "Make new hash tables, or clear them if already present."
935 (mh-thread-initialize-hash mh-thread-id-hash #'equal)
936 (mh-thread-initialize-hash mh-thread-subject-hash #'equal)
937 (mh-thread-initialize-hash mh-thread-id-table #'eq)
938 (mh-thread-initialize-hash mh-thread-id-index-map #'eq)
939 (mh-thread-initialize-hash mh-thread-index-id-map #'eql)
940 (mh-thread-initialize-hash mh-thread-scan-line-map #'eql)
941 (mh-thread-initialize-hash mh-thread-subject-container-hash #'eq)
942 (mh-thread-initialize-hash mh-thread-duplicates #'eq)
943 (setq mh-thread-history ()))
945 (defsubst mh-thread-id-container (id)
946 "Given ID, return the corresponding container in `mh-thread-id-table'.
947 If no container exists then a suitable container is created and the id-table
951 (or (gethash id mh-thread-id-table)
952 (setf (gethash id mh-thread-id-table)
953 (let ((message (mh-thread-make-message :id id)))
954 (mh-thread-make-container :message message)))))
956 (defsubst mh-thread-remove-parent-link (child)
957 "Remove parent link of CHILD if it exists."
958 (let* ((child-container (if (mh-thread-container-p child)
959 child (mh-thread-id-container child)))
960 (parent-container (mh-container-parent child-container)))
961 (when parent-container
962 (setf (mh-container-children parent-container)
963 (loop for elem in (mh-container-children parent-container)
964 unless (eq child-container elem) collect elem))
965 (setf (mh-container-parent child-container) nil))))
967 (defsubst mh-thread-add-link (parent child &optional at-end-p)
968 "Add links so that PARENT becomes a parent of CHILD.
969 Doesn't make any changes if CHILD is already an ancestor of PARENT. If
970 optional argument AT-END-P is non-nil, the CHILD is added to the end of the
971 children list of PARENT."
972 (let ((parent-container (cond ((null parent) nil)
973 ((mh-thread-container-p parent) parent)
974 (t (mh-thread-id-container parent))))
975 (child-container (if (mh-thread-container-p child)
976 child (mh-thread-id-container child))))
977 (when (and parent-container
978 (not (mh-thread-ancestor-p child-container parent-container))
979 (not (mh-thread-ancestor-p parent-container child-container)))
980 (mh-thread-remove-parent-link child-container)
981 (cond ((not at-end-p)
982 (push child-container (mh-container-children parent-container)))
983 ((null (mh-container-children parent-container))
984 (push child-container (mh-container-children parent-container)))
985 (t (let ((last-child (mh-container-children parent-container)))
986 (while (cdr last-child)
987 (setq last-child (cdr last-child)))
988 (setcdr last-child (cons child-container nil)))))
989 (setf (mh-container-parent child-container) parent-container))
990 (unless parent-container
991 (mh-thread-remove-parent-link child-container))))
993 (defun mh-thread-ancestor-p (ancestor successor)
994 "Return t if ANCESTOR is really an ancestor of SUCCESSOR and nil otherwise.
995 In the limit, the function returns t if ANCESTOR and SUCCESSOR are the same
999 (when (eq ancestor successor) (return t))
1000 (setq successor (mh-container-parent successor)))
1003 (defsubst mh-thread-get-message-container (message)
1004 "Return container which has MESSAGE in it.
1005 If there is no container present then a new container is allocated."
1006 (let* ((id (mh-message-id message))
1007 (container (gethash id mh-thread-id-table)))
1008 (cond (container (setf (mh-container-message container) message)
1010 (t (setf (gethash id mh-thread-id-table)
1011 (mh-thread-make-container :message message))))))
1013 (defsubst mh-thread-get-message (id subject-re-p subject refs)
1014 "Return appropriate message.
1015 Otherwise update message already present to have the proper ID, SUBJECT-RE-P,
1016 SUBJECT and REFS fields."
1017 (let* ((container (gethash id mh-thread-id-table))
1018 (message (if container (mh-container-message container) nil)))
1020 (setf (mh-message-subject-re-p message) subject-re-p)
1021 (setf (mh-message-subject message) subject)
1022 (setf (mh-message-id message) id)
1023 (setf (mh-message-references message) refs)
1026 (setf (mh-container-message container)
1027 (mh-thread-make-message :id id :references refs
1029 :subject-re-p subject-re-p)))
1030 (t (let ((message (mh-thread-make-message :id id :references refs
1031 :subject-re-p subject-re-p
1034 (mh-thread-get-message-container message)))))))
1036 (defsubst mh-thread-canonicalize-id (id)
1037 "Produce canonical string representation for ID.
1038 This allows cheap string comparison with EQ."
1039 (or (and (equal id "") (copy-sequence ""))
1040 (gethash id mh-thread-id-hash)
1041 (setf (gethash id mh-thread-id-hash) id)))
1043 (defsubst mh-thread-prune-subject (subject)
1044 "Prune leading Re:'s, Fwd:'s etc. and trailing (fwd)'s from SUBJECT.
1045 If the result after pruning is not the empty string then it is canonicalized
1046 so that subjects can be tested for equality with eq. This is done so that all
1047 the messages without a subject are not put into a single thread."
1048 (let ((case-fold-search t)
1049 (subject-pruned-flag nil))
1050 ;; Prune subject leader
1051 (while (or (string-match "^[ \t]*\\(re\\|fwd?\\)\\(\\[[0-9]*\\]\\)?:[ \t]*"
1053 (string-match "^[ \t]*\\[[^\\]][ \t]*" subject))
1054 (setq subject-pruned-flag t)
1055 (setq subject (substring subject (match-end 0))))
1056 ;; Prune subject trailer
1057 (while (or (string-match "(fwd)$" subject)
1058 (string-match "[ \t]+$" subject))
1059 (setq subject-pruned-flag t)
1060 (setq subject (substring subject 0 (match-beginning 0))))
1061 ;; Canonicalize subject only if it is non-empty
1062 (cond ((equal subject "") (values subject subject-pruned-flag))
1064 (or (gethash subject mh-thread-subject-hash)
1065 (setf (gethash subject mh-thread-subject-hash) subject))
1066 subject-pruned-flag)))))
1068 (defun mh-thread-container-subject (container)
1069 "Return the subject of CONTAINER.
1070 If CONTAINER is empty return the subject info of one of its children."
1071 (cond ((and (mh-container-message container)
1072 (mh-message-id (mh-container-message container)))
1073 (mh-message-subject (mh-container-message container)))
1075 (dolist (kid (mh-container-children container))
1076 (when (and (mh-container-message kid)
1077 (mh-message-id (mh-container-message kid)))
1078 (let ((kid-message (mh-container-message kid)))
1079 (return (mh-message-subject kid-message)))))
1080 (error "This can't happen!")))))
1082 (defun mh-thread-rewind-pruning ()
1083 "Restore the thread tree to its state before pruning."
1084 (while mh-thread-history
1085 (let ((action (pop mh-thread-history)))
1086 (cond ((eq (car action) 'DROP)
1087 (mh-thread-remove-parent-link (cadr action))
1088 (mh-thread-add-link (caddr action) (cadr action)))
1089 ((eq (car action) 'PROMOTE)
1090 (let ((node (cadr action))
1091 (parent (caddr action))
1092 (children (cdddr action)))
1093 (dolist (child children)
1094 (mh-thread-remove-parent-link child)
1095 (mh-thread-add-link node child))
1096 (mh-thread-add-link parent node)))
1097 ((eq (car action) 'SUBJECT)
1098 (let ((node (cadr action)))
1099 (mh-thread-remove-parent-link node)
1100 (setf (mh-container-real-child-p node) t)))))))
1102 (defun mh-thread-prune-containers (roots)
1103 "Prune empty containers in the containers ROOTS."
1104 (let ((dfs-ordered-nodes ())
1107 (let ((node (pop work-list)))
1108 (dolist (child (mh-container-children node))
1109 (push child work-list))
1110 (push node dfs-ordered-nodes)))
1111 (while dfs-ordered-nodes
1112 (let ((node (pop dfs-ordered-nodes)))
1113 (cond ((gethash (mh-message-id (mh-container-message node))
1114 mh-thread-id-index-map)
1116 (setf (mh-container-children node)
1117 (mh-thread-sort-containers (mh-container-children node))))
1118 ((and (mh-container-children node)
1119 (or (null (cdr (mh-container-children node)))
1120 (mh-container-parent node)))
1122 (let ((children ()))
1123 (dolist (kid (mh-container-children node))
1124 (mh-thread-remove-parent-link kid)
1125 (mh-thread-add-link (mh-container-parent node) kid)
1126 (push kid children))
1127 (push `(PROMOTE ,node ,(mh-container-parent node) ,@children)
1129 (mh-thread-remove-parent-link node)))
1130 ((mh-container-children node)
1131 ;; Promote the first orphan to parent and add the other kids as
1133 (setf (mh-container-children node)
1134 (mh-thread-sort-containers (mh-container-children node)))
1135 (let ((new-parent (car (mh-container-children node)))
1136 (other-kids (cdr (mh-container-children node))))
1137 (mh-thread-remove-parent-link new-parent)
1138 (dolist (kid other-kids)
1139 (mh-thread-remove-parent-link kid)
1140 (setf (mh-container-real-child-p kid) nil)
1141 (mh-thread-add-link new-parent kid t))
1142 (push `(PROMOTE ,node ,(mh-container-parent node)
1143 ,new-parent ,@other-kids)
1145 (mh-thread-remove-parent-link node)))
1148 (push `(DROP ,node ,(mh-container-parent node))
1150 (mh-thread-remove-parent-link node)))))
1152 (maphash #'(lambda (k v)
1153 (declare (ignore k))
1154 (when (and (null (mh-container-parent v))
1155 (gethash (mh-message-id (mh-container-message v))
1156 mh-thread-id-index-map))
1159 (mh-thread-sort-containers results))))
1161 (defun mh-thread-sort-containers (containers)
1162 "Sort a list of message CONTAINERS to be in ascending order wrt index."
1165 (when (and (mh-container-message x) (mh-container-message y))
1166 (let* ((id-x (mh-message-id (mh-container-message x)))
1167 (id-y (mh-message-id (mh-container-message y)))
1168 (index-x (gethash id-x mh-thread-id-index-map))
1169 (index-y (gethash id-y mh-thread-id-index-map)))
1170 (and (integerp index-x) (integerp index-y)
1171 (< index-x index-y)))))))
1173 (defsubst mh-thread-group-by-subject (roots)
1174 "Group the set of message containers, ROOTS based on subject.
1175 Bug: Check for and make sure that something without Re: is made the parent in
1176 preference to something that has it."
1177 (clrhash mh-thread-subject-container-hash)
1179 (dolist (root roots)
1180 (let* ((subject (mh-thread-container-subject root))
1181 (parent (gethash subject mh-thread-subject-container-hash)))
1182 (cond (parent (mh-thread-remove-parent-link root)
1183 (mh-thread-add-link parent root t)
1184 (setf (mh-container-real-child-p root) nil)
1185 (push `(SUBJECT ,root) mh-thread-history))
1187 (setf (gethash subject mh-thread-subject-container-hash) root)
1188 (push root results)))))
1189 (nreverse results)))
1191 (defun mh-thread-process-in-reply-to (reply-to-header)
1192 "Extract message id's from REPLY-TO-HEADER.
1193 Ideally this should have some regexp which will try to guess if a string
1194 between < and > is a message id and not an email address. For now it will
1195 take the last string inside angles."
1196 (let ((end (mh-search-from-end ?> reply-to-header)))
1198 (let ((begin (mh-search-from-end ?< (substring reply-to-header 0 end))))
1199 (when (numberp begin)
1200 (list (substring reply-to-header begin (1+ end))))))))
1202 (defun mh-thread-set-tables (folder)
1203 "Use the tables of FOLDER in current buffer."
1204 (flet ((mh-get-table (symbol)
1207 (symbol-value symbol))))
1208 (setq mh-thread-id-hash (mh-get-table 'mh-thread-id-hash))
1209 (setq mh-thread-subject-hash (mh-get-table 'mh-thread-subject-hash))
1210 (setq mh-thread-id-table (mh-get-table 'mh-thread-id-table))
1211 (setq mh-thread-id-index-map (mh-get-table 'mh-thread-id-index-map))
1212 (setq mh-thread-index-id-map (mh-get-table 'mh-thread-index-id-map))
1213 (setq mh-thread-scan-line-map (mh-get-table 'mh-thread-scan-line-map))
1214 (setq mh-thread-subject-container-hash
1215 (mh-get-table 'mh-thread-subject-container-hash))
1216 (setq mh-thread-duplicates (mh-get-table 'mh-thread-duplicates))
1217 (setq mh-thread-history (mh-get-table 'mh-thread-history))))
1219 (defsubst mh-thread-update-id-index-maps (id index)
1220 "Message with id, ID is the message in INDEX.
1221 The function also checks for duplicate messages (that is multiple messages
1222 with the same ID). These messages are put in the `mh-thread-duplicates' hash
1224 (let ((old-index (gethash id mh-thread-id-index-map)))
1225 (when old-index (push old-index (gethash id mh-thread-duplicates)))
1226 (setf (gethash id mh-thread-id-index-map) index)
1227 (setf (gethash index mh-thread-index-id-map) id)))
1231 ;;; Generate Threads...
1233 (defvar mh-message-id-regexp "^<.*@.*>$"
1234 "Regexp to recognize whether a string is a message identifier.")
1236 (defun mh-thread-generate (folder msg-list)
1237 "Scan FOLDER to get info for threading.
1238 Only information about messages in MSG-LIST are added to the tree."
1240 (mh-thread-set-tables folder)
1243 #'call-process (expand-file-name mh-scan-prog mh-progs) nil '(t nil) nil
1244 "-width" "10000" "-format"
1245 "%(msg)\n%{message-id}\n%{references}\n%{in-reply-to}\n%{subject}\n"
1246 folder (mapcar #'(lambda (x) (format "%s" x)) msg-list)))
1247 (goto-char (point-min))
1249 (case-fold-search t))
1252 (block process-message
1254 (prog1 (buffer-substring (point) (line-end-position))
1256 (index (car (read-from-string index-line)))
1257 (id (prog1 (buffer-substring (point) (line-end-position))
1259 (refs (prog1 (buffer-substring (point) (line-end-position))
1261 (in-reply-to (prog1 (buffer-substring (point)
1262 (line-end-position))
1265 (buffer-substring (point) (line-end-position))
1268 (unless (gethash index mh-thread-scan-line-map)
1269 (return-from process-message))
1270 (unless (integerp index) (return)) ;Error message here
1271 (multiple-value-setq (subject subject-re-p)
1272 (mh-thread-prune-subject subject))
1273 (setq in-reply-to (mh-thread-process-in-reply-to in-reply-to))
1274 (setq refs (loop for x in (append (split-string refs) in-reply-to)
1275 when (string-match mh-message-id-regexp x)
1277 (setq id (mh-thread-canonicalize-id id))
1278 (mh-thread-update-id-index-maps id index)
1279 (setq refs (mapcar #'mh-thread-canonicalize-id refs))
1280 (mh-thread-get-message id subject-re-p subject refs)
1281 (do ((ancestors refs (cdr ancestors)))
1282 ((null (cdr ancestors))
1283 (when (car ancestors)
1284 (mh-thread-remove-parent-link id)
1285 (mh-thread-add-link (car ancestors) id)))
1286 (mh-thread-add-link (car ancestors) (cadr ancestors)))))))
1287 (maphash #'(lambda (k v)
1288 (declare (ignore k))
1289 (when (null (mh-container-parent v))
1292 (setq roots (mh-thread-prune-containers roots))
1293 (prog1 (setq roots (mh-thread-group-by-subject roots))
1294 (let ((history mh-thread-history))
1296 (setq mh-thread-history history))))))
1299 (defun mh-thread-inc (folder start-point)
1300 "Update thread tree for FOLDER.
1301 All messages after START-POINT are added to the thread tree."
1302 (mh-thread-rewind-pruning)
1303 (mh-remove-all-notation)
1304 (goto-char start-point)
1305 (let ((msg-list ()))
1307 (let ((index (mh-get-msg-num nil)))
1308 (when (numberp index)
1309 (push index msg-list)
1310 (setf (gethash index mh-thread-scan-line-map)
1311 (mh-thread-parse-scan-line)))
1313 (let ((thread-tree (mh-thread-generate folder msg-list))
1314 (buffer-read-only nil)
1315 (old-buffer-modified-flag (buffer-modified-p)))
1316 (delete-region (point-min) (point-max))
1317 (mh-thread-print-scan-lines thread-tree)
1318 (mh-notate-deleted-and-refiled)
1320 (set-buffer-modified-p old-buffer-modified-flag))))
1322 (defun mh-thread-generate-scan-lines (tree level)
1323 "Generate scan lines.
1324 TREE is the hierarchical tree of messages, SCAN-LINE-MAP maps message indices
1325 to the corresponding scan lines and LEVEL used to determine indentation of
1327 (cond ((null tree) nil)
1328 ((mh-thread-container-p tree)
1329 (let* ((message (mh-container-message tree))
1330 (id (mh-message-id message))
1331 (index (gethash id mh-thread-id-index-map))
1332 (duplicates (gethash id mh-thread-duplicates))
1333 (new-level (+ level 2))
1335 (force-angle-flag nil)
1336 (increment-level-flag nil))
1337 (dolist (scan-line (mapcar (lambda (x)
1338 (gethash x mh-thread-scan-line-map))
1339 (reverse (cons index duplicates))))
1341 (when (and dupl-flag (equal level 0)
1342 (mh-thread-ancestor-p mh-thread-last-ancestor tree))
1343 (setq level (+ level 2)
1344 new-level (+ new-level 2)
1345 force-angle-flag t))
1346 (when (equal level 0)
1347 (setq mh-thread-last-ancestor tree)
1348 (while (mh-container-parent mh-thread-last-ancestor)
1349 (setq mh-thread-last-ancestor
1350 (mh-container-parent mh-thread-last-ancestor))))
1351 (let* ((lev (if dupl-flag level new-level))
1352 (square-flag (or (and (mh-container-real-child-p tree)
1353 (not force-angle-flag)
1356 (insert (car scan-line)
1357 (format (format "%%%ss" lev) "")
1358 (if square-flag "[" "<")
1360 (if square-flag "]" ">")
1361 (truncate-string-to-width
1362 (caddr scan-line) (- mh-thread-body-width lev))
1364 (setq increment-level-flag t)
1365 (setq dupl-flag nil)))
1366 (unless increment-level-flag (setq new-level level))
1367 (dolist (child (mh-container-children tree))
1368 (mh-thread-generate-scan-lines child new-level))))
1369 (t (let ((nlevel (+ level 2)))
1371 (mh-thread-generate-scan-lines ch nlevel))))))
1373 ;; Another and may be better approach would be to generate all the info from
1374 ;; the scan which generates the threading info. For now this will have to do.
1375 (defun mh-thread-parse-scan-line (&optional string)
1377 If optional argument STRING is given then that is assumed to be the scan line.
1378 Otherwise uses the line at point as the scan line to parse."
1379 (let* ((string (or string
1380 (buffer-substring-no-properties (line-beginning-position)
1381 (line-end-position))))
1382 (address-start (+ mh-cmd-note mh-scan-field-from-start-offset))
1383 (body-start (+ mh-cmd-note mh-scan-field-from-end-offset))
1384 (first-string (substring string 0 address-start)))
1386 (substring string address-start (- body-start 2))
1387 (substring string body-start)
1391 (defun mh-thread-update-scan-line-map (msg notation offset)
1392 "In threaded view update `mh-thread-scan-line-map'.
1393 MSG is the message being notated with NOTATION at OFFSET."
1394 (let* ((msg (or msg (mh-get-msg-num nil)))
1395 (cur-scan-line (and mh-thread-scan-line-map
1396 (gethash msg mh-thread-scan-line-map)))
1397 (old-scan-lines (loop for map in mh-thread-scan-line-map-stack
1398 collect (and map (gethash msg map)))))
1400 (setf (aref (car cur-scan-line) offset) notation))
1401 (dolist (line old-scan-lines)
1402 (when line (setf (aref (car line) offset) notation)))))
1405 (defun mh-thread-add-spaces (count)
1406 "Add COUNT spaces to each scan line in `mh-thread-scan-line-map'."
1407 (let ((spaces (format (format "%%%ss" count) "")))
1409 (let* ((msg-num (mh-get-msg-num nil))
1410 (old-line (nth 3 (gethash msg-num mh-thread-scan-line-map))))
1411 (when (numberp msg-num)
1412 (setf (gethash msg-num mh-thread-scan-line-map)
1413 (mh-thread-parse-scan-line (format "%s%s" spaces old-line)))))
1416 (defun mh-thread-print-scan-lines (thread-tree)
1417 "Print scan lines in THREAD-TREE in threaded mode."
1418 (let ((mh-thread-body-width (- (window-width) mh-cmd-note
1419 (1- mh-scan-field-subject-start-offset)))
1420 (mh-thread-last-ancestor nil))
1421 (if (null mh-index-data)
1422 (mh-thread-generate-scan-lines thread-tree -2)
1423 (loop for x in (mh-index-group-by-folder)
1424 do (let* ((old-map mh-thread-scan-line-map)
1425 (mh-thread-scan-line-map (make-hash-table)))
1426 (setq mh-thread-last-ancestor nil)
1427 (loop for msg in (cdr x)
1428 do (let ((v (gethash msg old-map)))
1430 (setf (gethash msg mh-thread-scan-line-map) v))))
1431 (when (> (hash-table-count mh-thread-scan-line-map) 0)
1432 (insert (if (bobp) "" "\n") (car x) "\n")
1433 (mh-thread-generate-scan-lines thread-tree -2))))
1434 (mh-index-create-imenu-index))))
1436 (defun mh-thread-folder ()
1437 "Generate thread view of folder."
1438 (message "Threading %s..." (buffer-name))
1439 (mh-thread-initialize)
1440 (goto-char (point-min))
1441 (mh-remove-all-notation)
1442 (let ((msg-list ()))
1443 (mh-iterate-on-range msg (cons (point-min) (point-max))
1444 (setf (gethash msg mh-thread-scan-line-map) (mh-thread-parse-scan-line))
1445 (push msg msg-list))
1446 (let* ((range (mh-coalesce-msg-list msg-list))
1447 (thread-tree (mh-thread-generate (buffer-name) range)))
1448 (delete-region (point-min) (point-max))
1449 (mh-thread-print-scan-lines thread-tree)
1450 (mh-notate-user-sequences)
1451 (mh-notate-deleted-and-refiled)
1453 (message "Threading %s...done" (buffer-name)))))
1456 (defun mh-toggle-threads ()
1457 "Toggle threaded view of folder."
1459 (let ((msg-at-point (mh-get-msg-num nil))
1460 (old-buffer-modified-flag (buffer-modified-p))
1461 (buffer-read-only nil))
1462 (cond ((memq 'unthread mh-view-ops)
1463 (unless (mh-valid-view-change-operation-p 'unthread)
1464 (error "Can't unthread folder"))
1465 (let ((msg-list ()))
1466 (goto-char (point-min))
1468 (let ((index (mh-get-msg-num nil)))
1470 (push index msg-list)))
1472 (mh-scan-folder mh-current-folder
1473 (mapcar #'(lambda (x) (format "%s" x))
1474 (mh-coalesce-msg-list msg-list))
1477 (mh-index-insert-folder-headers)
1479 (t (mh-thread-folder)
1480 (push 'unthread mh-view-ops)))
1481 (when msg-at-point (mh-goto-msg msg-at-point t t))
1482 (set-buffer-modified-p old-buffer-modified-flag)
1486 (defun mh-thread-forget-message (index)
1487 "Forget the message INDEX from the threading tables."
1488 (let* ((id (gethash index mh-thread-index-id-map))
1489 (id-index (gethash id mh-thread-id-index-map))
1490 (duplicates (gethash id mh-thread-duplicates)))
1491 (remhash index mh-thread-index-id-map)
1492 (remhash index mh-thread-scan-line-map)
1493 (cond ((and (eql index id-index) (null duplicates))
1494 (remhash id mh-thread-id-index-map))
1495 ((eql index id-index)
1496 (setf (gethash id mh-thread-id-index-map) (car duplicates))
1497 (setf (gethash (car duplicates) mh-thread-index-id-map) id)
1498 (setf (gethash id mh-thread-duplicates) (cdr duplicates)))
1500 (setf (gethash id mh-thread-duplicates)
1501 (remove index duplicates))))))
1505 ;;; Operations on threads
1507 (defun mh-thread-current-indentation-level ()
1508 "Find the number of spaces by which current message is indented."
1510 (let ((address-start-offset (+ mh-cmd-note mh-scan-date-flag-width
1511 mh-scan-date-width 1))
1514 (forward-char address-start-offset)
1515 (while (char-equal (char-after) ? )
1521 (defun mh-thread-next-sibling (&optional previous-flag)
1522 "Jump to next sibling.
1523 With non-nil optional argument PREVIOUS-FLAG jump to the previous sibling."
1525 (cond ((not (memq 'unthread mh-view-ops))
1526 (error "Folder isn't threaded"))
1528 (error "No message at point")))
1530 (let ((point (point))
1532 (my-level (mh-thread-current-indentation-level)))
1533 (while (and (not done)
1534 (equal (forward-line (if previous-flag -1 1)) 0)
1536 (let ((level (mh-thread-current-indentation-level)))
1537 (cond ((equal level my-level)
1538 (setq done 'success))
1540 (message "No %s sibling" (if previous-flag "previous" "next"))
1541 (setq done 'failure)))))
1542 (cond ((eq done 'success) (mh-maybe-show))
1543 ((eq done 'failure) (goto-char point))
1544 (t (message "No %s sibling" (if previous-flag "previous" "next"))
1545 (goto-char point)))))
1548 (defun mh-thread-previous-sibling ()
1549 "Jump to previous sibling."
1551 (mh-thread-next-sibling t))
1553 (defun mh-thread-immediate-ancestor ()
1554 "Jump to immediate ancestor in thread tree."
1556 (let ((point (point))
1557 (ancestor-level (- (mh-thread-current-indentation-level) 2))
1559 (if (< ancestor-level 0)
1561 (while (and (not done) (equal (forward-line -1) 0))
1562 (when (equal ancestor-level (mh-thread-current-indentation-level))
1569 (defun mh-thread-ancestor (&optional thread-root-flag)
1570 "Jump to the ancestor of current message.
1571 If optional argument THREAD-ROOT-FLAG is non-nil then jump to the root of the
1572 thread tree the message belongs to."
1575 (cond ((not (memq 'unthread mh-view-ops))
1576 (error "Folder isn't threaded"))
1578 (error "No message at point")))
1579 (let ((current-level (mh-thread-current-indentation-level)))
1580 (cond (thread-root-flag
1581 (while (mh-thread-immediate-ancestor))
1583 ((equal current-level 1)
1584 (message "Message has no ancestor"))
1585 (t (mh-thread-immediate-ancestor)
1588 (defun mh-thread-find-children ()
1589 "Return a region containing the current message and its children.
1590 The result is returned as a list of two elements. The first is the point at the
1591 start of the region and the second is the point at the end."
1595 (let ((address-start-offset (+ mh-cmd-note mh-scan-date-flag-width
1596 mh-scan-date-width 1))
1597 (level (mh-thread-current-indentation-level))
1599 (setq begin (point))
1600 (setq spaces (format (format "%%%ss" (1+ level)) ""))
1604 (forward-char address-start-offset)
1605 (unless (equal (string-match spaces (buffer-substring-no-properties
1606 (point) (line-end-position)))
1612 (list begin (point)))))
1615 (defun mh-thread-delete ()
1616 "Mark current message and all its children for subsequent deletion."
1618 (cond ((not (memq 'unthread mh-view-ops))
1619 (error "Folder isn't threaded"))
1621 (error "No message at point"))
1622 (t (let ((region (mh-thread-find-children)))
1623 (mh-iterate-on-messages-in-region () (car region) (cadr region)
1624 (mh-delete-a-msg nil))
1628 (defun mh-thread-refile (folder)
1629 "Mark current message and all its children for refiling to FOLDER."
1630 (interactive (list (intern (mh-prompt-for-refile-folder))))
1631 (cond ((not (memq 'unthread mh-view-ops))
1632 (error "Folder isn't threaded"))
1634 (error "No message at point"))
1635 (t (let ((region (mh-thread-find-children)))
1636 (mh-iterate-on-messages-in-region () (car region) (cadr region)
1637 (mh-refile-a-msg nil folder))
1642 ;; Tick mark handling
1645 (defun mh-toggle-tick (range)
1646 "Toggle tick mark of all messages in RANGE."
1647 (interactive (list (mh-interactive-range "Tick")))
1649 (error "Enable ticking by customizing `mh-tick-seq'"))
1650 (let* ((tick-seq (mh-find-seq mh-tick-seq))
1651 (tick-seq-msgs (mh-seq-msgs tick-seq))
1654 (mh-iterate-on-range msg range
1655 (cond ((member msg tick-seq-msgs)
1657 (setcdr tick-seq (delq msg (cdr tick-seq)))
1658 (when (null (cdr tick-seq)) (setq mh-last-seq-used nil))
1659 (mh-remove-sequence-notation msg (mh-colors-in-use-p)))
1662 (setq mh-last-seq-used mh-tick-seq)
1663 (let ((mh-seq-list (cons `(,mh-tick-seq ,msg) mh-seq-list)))
1664 (mh-add-sequence-notation msg (mh-colors-in-use-p))))))
1665 (mh-add-msgs-to-seq ticked mh-tick-seq nil t)
1666 (mh-undefine-sequence mh-tick-seq unticked)
1668 (mh-index-add-to-sequence mh-tick-seq ticked)
1669 (mh-index-delete-from-sequence mh-tick-seq unticked))))
1672 (defun mh-narrow-to-tick ()
1673 "Limit to messages in `mh-tick-seq'.
1675 Use \\<mh-folder-mode-map>\\[mh-widen] to undo this command."
1677 (cond ((not mh-tick-seq)
1678 (error "Enable ticking by customizing `mh-tick-seq'"))
1679 ((null (mh-seq-msgs (mh-find-seq mh-tick-seq)))
1680 (message "No messages in %s sequence" mh-tick-seq))
1681 (t (mh-narrow-to-seq mh-tick-seq))))
1685 ;;; Local Variables:
1686 ;;; indent-tabs-mode: nil
1687 ;;; sentence-end-double-space: nil
1690 ;;; arch-tag: 8e952711-01a2-485b-bf21-c9e3ad4de942
1691 ;;; mh-seq.el ends here