viper -- Update and prettify package-info.in provides.
[packages] / xemacs-packages / mh-e / mh-e.el
1 ;;; mh-e.el --- GNU Emacs interface to the MH mail system
2
3 ;; Copyright (C) 1985, 86, 87, 88, 90, 92, 93, 94, 95, 97, 1999,
4 ;;  2000, 01, 02, 2003 Free Software Foundation, Inc.
5
6 ;; Author: Bill Wohler <wohler@newt.com>
7 ;; Maintainer: Bill Wohler <wohler@newt.com>
8 ;; Version: 7.4.2
9 ;; Keywords: mail
10
11 ;; This file is part of GNU Emacs.
12
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)
16 ;; any later version.
17
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.
22
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., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;; How to Use:
31 ;;   M-x mh-rmail to read mail.  Type C-h m there for a list of commands.
32 ;;   C-u M-x mh-rmail to visit any folder.
33 ;;   M-x mh-smail to send mail.  From within the mail reader, "m" works, too.
34
35 ;; Your .emacs might benefit from these bindings:
36 ;;   (global-set-key "\C-cr" 'mh-rmail)
37 ;;   (global-set-key "\C-xm" 'mh-smail)
38 ;;   (global-set-key "\C-x4m" 'mh-smail-other-window)
39
40 ;; MH (Message Handler) is a powerful mail reader.
41
42 ;; The MH newsgroup is comp.mail.mh; the mailing list is mh-users@ics.uci.edu
43 ;; (send to mh-users-request to be added). See the monthly Frequently Asked
44 ;; Questions posting there for information on getting MH and MH-E:
45 ;;   http://www.faqs.org/faqs/mail/mh-faq/part1/preamble.html
46
47 ;; N.B. MH must have been compiled with the MHE compiler flag or several
48 ;; features necessary for MH-E will be missing from MH commands, specifically
49 ;; the -build switch to repl and forw.
50
51 ;; MH-E is an Emacs interface to the MH mail system.
52
53 ;; MH-E is supported in GNU Emacs 20 and 21, with MH 6.8.4 and nmh 1.0.4.
54
55 ;; Mailing Lists:
56 ;;   mh-e-users@lists.sourceforge.net
57 ;;   mh-e-announce@lists.sourceforge.net
58 ;;   mh-e-devel@lists.sourceforge.net
59 ;;
60 ;;   Subscribe by sending a "subscribe" message to
61 ;;   <list>-request@lists.sourceforge.net, or by using the web interface at
62 ;;   https://sourceforge.net/mail/?group_id=13357
63
64 ;; Bug Reports:
65 ;;   https://sourceforge.net/tracker/?group_id=13357&atid=113357
66 ;;   Include the output of M-x mh-version in any bug report.
67
68 ;; Feature Requests:
69 ;;   https://sourceforge.net/tracker/?atid=363357&group_id=13357&func=browse
70
71 ;; Support:
72 ;;   https://sourceforge.net/tracker/?group_id=13357&atid=213357
73
74 ;;; Change Log:
75
76 ;; Original version for Gosling emacs by Brian Reid, Stanford, 1982.
77 ;; Modified by James Larus, BBN, July 1984 and UCB, 1984 & 1985.
78 ;; Rewritten for GNU Emacs, James Larus 1985.  larus@ginger.berkeley.edu
79 ;; Modified by Stephen Gildea 1988.  gildea@lcs.mit.edu
80 ;; Maintenance picked up by Bill Wohler <wohler@newt.com> and the
81 ;; SourceForge Crew <http://mh-e.sourceforge.net/>. 2001.
82
83 ;;; Code:
84
85 (provide 'mh-e)
86 (require 'cl)
87
88 (defvar recursive-load-depth-limit)
89 (eval-when (compile load eval)
90   (if (and (boundp 'recursive-load-depth-limit)
91            (integerp recursive-load-depth-limit)
92            (> 50 recursive-load-depth-limit))
93       (setq recursive-load-depth-limit 50)))
94
95 (require 'mh-inc)
96 (require 'mh-utils)
97 (require 'gnus-util)
98 (require 'easymenu)
99 (if mh-xemacs-flag
100     (require 'mh-xemacs-compat))
101
102 ;; Have compiled 21.4 code also work on XEmacs binaries with real support
103 ;; for multiple values, by avoiding runtime calls to #'values: 
104 (eval-when-compile (when (eq 'list (symbol-function 'values))
105                      (define-compiler-macro values (&rest args)
106                        `(list ,@args))))
107
108 ;; Shush the byte-compiler
109 (defvar font-lock-auto-fontify)
110 (defvar font-lock-defaults)
111
112 (defconst mh-version "7.4.2" "Version number of MH-E.")
113
114 ;;; Autoloads
115 (autoload 'Info-goto-node "info")
116
117 \f
118
119 (defvar mh-note-deleted "D"
120   "String whose first character is used to notate deleted messages.")
121
122 (defvar mh-note-refiled "^"
123   "String whose first character is used to notate refiled messages.")
124
125 (defvar mh-note-cur "+"
126   "String whose first character is used to notate the current message.")
127
128 (defvar mh-partial-folder-mode-line-annotation "select"
129   "Annotation when displaying part of a folder.
130 The string is displayed after the folder's name.  nil for no annotation.")
131
132 ;;; Parameterize MH-E to work with different scan formats.  The defaults work
133 ;;; with the standard MH scan listings, in which the first 4 characters on
134 ;;; the line are the message number, followed by two places for notations.
135
136 ;; The following scan formats are passed to the scan program if the
137 ;; setting of `mh-scan-format-file' above is nil.  They are identical
138 ;; except the later one makes use of the nmh `decode' function to
139 ;; decode RFC 2047 encodings. If you just want to change the width of
140 ;; the msg number, use the `mh-set-cmd-note' function.
141
142 (defvar mh-scan-format-mh
143   (concat
144    "%4(msg)"
145    "%<(cur)+%| %>"
146    "%<{replied}-"
147    "%?(nonnull(comp{to}))%<(mymbox{to})t%>"
148    "%?(nonnull(comp{cc}))%<(mymbox{cc})c%>"
149    "%?(nonnull(comp{bcc}))%<(mymbox{bcc})b%>"
150    "%?(nonnull(comp{newsgroups}))n%>"
151    "%<(zero) %>"
152    "%02(mon{date})/%02(mday{date})%<{date} %|*%>"
153    "%<(mymbox{from})%<{to}To:%14(friendly{to})%>%>"
154    "%<(zero)%17(friendly{from})%>  "
155    "%{subject}%<{body}<<%{body}%>")
156   "*Scan format string for MH, provided to the scan program via the -format arg.
157 This format is identical to the default except that additional hints for
158 fontification have been added to the fifth column (remember that in Emacs, the
159 first column is 0).
160
161 The values of the fifth column, in priority order, are: `-' if the
162 message has been replied to, t if an address on the To: line matches
163 one of the mailboxes of the current user, `c' if the Cc: line matches,
164 `b' if the Bcc: line matches, and `n' if a non-empty Newsgroups: header
165 is present.")
166
167 (defvar mh-scan-format-nmh
168   (concat
169    "%4(msg)"
170    "%<(cur)+%| %>"
171    "%<{replied}-"
172    "%?(nonnull(comp{to}))%<(mymbox{to})t%>"
173    "%?(nonnull(comp{cc}))%<(mymbox{cc})c%>"
174    "%?(nonnull(comp{bcc}))%<(mymbox{bcc})b%>"
175    "%?(nonnull(comp{newsgroups}))n%>"
176    "%<(zero) %>"
177    "%02(mon{date})/%02(mday{date})%<{date} %|*%>"
178    "%<(mymbox{from})%<{to}To:%14(decode(friendly{to}))%>%>"
179    "%<(zero)%17(decode(friendly{from}))%>  "
180    "%(decode{subject})%<{body}<<%{body}%>")
181   "*Scan format string for nmh.
182 This string is passed to the scan program via the -format arg.
183 This format is identical to the default except that additional hints for
184 fontification have been added to the fifth column (remember that in Emacs, the
185 first column is 0).
186
187 The values of the fifth column, in priority order, are: `-' if the
188 message has been replied to, t if an address on the To: line matches
189 one of the mailboxes of the current user, `c' if the Cc: line matches,
190 `b' if the Bcc: line matches, and `n' if a non-empty Newsgroups: header
191 is present.")
192
193 (defvar mh-scan-good-msg-regexp  "^\\( *[0-9]+\\)[^D^0-9]"
194   "Regexp specifying the scan lines that are 'good' messages.
195 The default `mh-folder-font-lock-keywords' expects this expression to contain
196 at least one parenthesized expression which matches the message number.")
197
198 (defvar mh-scan-deleted-msg-regexp "^\\( *[0-9]+\\)D"
199   "Regexp matching scan lines of deleted messages.
200 The default `mh-folder-font-lock-keywords' expects this expression to contain
201 at least one parenthesized expression which matches the message number.")
202
203 (defvar mh-scan-refiled-msg-regexp  "^\\( *[0-9]+\\)\\^"
204   "Regexp matching scan lines of refiled messages.
205 The default `mh-folder-font-lock-keywords' expects this expression to contain
206 at least one parenthesized expression which matches the message number.")
207
208 (defvar mh-scan-valid-regexp "^ *[0-9]"
209   "Regexp matching scan lines for messages (not error messages).")
210
211 (defvar mh-scan-cur-msg-number-regexp "^\\( *[0-9]+\\+\\).*"
212   "Regexp matching scan line for the current message.
213 The default `mh-folder-font-lock-keywords' expects this expression to contain
214 at least one parenthesized expression which matches the message number.
215 Don't disable this regexp as it's needed by non fontifying functions.")
216
217 (defvar mh-scan-cur-msg-regexp "^\\( *[0-9]+\\+DISABLED.*\\)"
218   "Regexp matching scan line for the current message.
219 The default `mh-folder-font-lock-keywords' expects this expression to contain
220 at least one parenthesized expression which matches the whole line.
221 To enable this feature, remove the string DISABLED from the regexp.")
222
223 (defvar mh-scan-date-regexp "\\([0-9][0-9]/[0-9][0-9]\\)"
224   "Regexp matching a valid date in scan lines.
225 The default `mh-folder-font-lock-keywords' expects this expression to contain
226 only one parenthesized expression which matches the date field
227 \(see `mh-scan-format-regexp').")
228
229 (defvar mh-scan-rcpt-regexp  "\\(To:\\)\\(..............\\)"
230   "Regexp specifying the recipient in scan lines for messages we sent.
231 The default `mh-folder-font-lock-keywords' expects this expression to contain
232 two parenthesized expressions.  The first is expected to match the To:
233 that the default scan format file generates.  The second is expected to match
234 the recipient's name.")
235
236 (defvar mh-scan-body-regexp "\\(<<\\([^\n]+\\)?\\)"
237   "Regexp matching the message body beginning displayed in scan lines.
238 The default `mh-folder-font-lock-keywords' expects this expression to contain
239 at least one parenthesized expression which matches the body text.")
240
241 (defvar mh-scan-subject-regexp
242   ;;"^ *[0-9]+........[ ]*...................\\([Rr][Ee]:\\s-*\\)*\\([^<\n]*\\)"
243   "^ *[0-9]+........[ ]*...................\\([Rr][Ee]\\(\\[[0-9]+\\]\\)?:\\s-*\\)*\\([^<\n]*\\)"
244   "*Regexp matching the subject string in MH folder mode.
245 The default `mh-folder-font-lock-keywords' expects this expression to contain
246 at least tree parenthesized expressions. The first is expected to match the Re:
247 string, if any. The second matches an optional bracketed number after Re,
248 such as in Re[2]: and the third is expected to match the subject line itself.")
249
250 (defvar mh-scan-format-regexp
251   (concat "\\([bct]\\)" mh-scan-date-regexp " *\\(..................\\)")
252   "Regexp matching the output of scan.
253 The default value is based upon the default values of either
254 `mh-scan-format-mh' or `mh-scan-format-nmh'.
255 The default `mh-folder-font-lock-keywords' expects this expression to contain
256 at least three parenthesized expressions. The first should match the
257 fontification hint, the second is found in `mh-scan-date-regexp', and the
258 third should match the user name.")
259
260 \f
261
262 (defvar mh-folder-font-lock-keywords
263   (list
264    ;; Folders when displaying index buffer
265    (list "^\\+.*"
266          '(0 mh-index-folder-face))
267    ;; Marked for deletion
268    (list (concat mh-scan-deleted-msg-regexp ".*")
269          '(0 mh-folder-deleted-face))
270    ;; Marked for refile
271    (list (concat mh-scan-refiled-msg-regexp ".*")
272          '(0 mh-folder-refiled-face))
273    ;;after subj
274    (list mh-scan-body-regexp '(1 mh-folder-body-face nil t))
275    '(mh-folder-font-lock-subject
276      (1 mh-folder-followup-face append t)
277      (2 mh-folder-subject-face append t))
278    ;;current msg
279    (list mh-scan-cur-msg-number-regexp
280          '(1 mh-folder-cur-msg-number-face))
281    (list mh-scan-good-msg-regexp
282          '(1 mh-folder-msg-number-face)) ;; Msg number
283    (list mh-scan-date-regexp '(1 mh-folder-date-face)) ;; Date
284    (list mh-scan-rcpt-regexp
285          '(1 mh-folder-to-face) ;; To:
286          '(2 mh-folder-address-face)) ;; address
287    ;; scan font-lock name
288    (list mh-scan-format-regexp
289          '(1 mh-folder-date-face)
290          '(3 mh-folder-scan-format-face))
291    ;; Current message line
292    (list mh-scan-cur-msg-regexp
293          '(1 mh-folder-cur-msg-face prepend t)))
294   "Regexp keywords used to fontify the MH-Folder buffer.")
295
296 (defvar mh-scan-cmd-note-width 1
297   "Number of columns consumed by the cmd-note field in `mh-scan-format'.
298 This column will have one of the values: ` ', `D', `^', `+' and where
299 ` ' is the default value,
300 `D' is the `mh-note-deleted' character,
301 `^' is the `mh-note-refiled' character, and
302 `+' is the `mh-note-cur' character.")
303
304 (defvar mh-scan-destination-width 1
305   "Number of columns consumed by the destination field in `mh-scan-format'.
306 This column will have one of ' ', '%', '-', 't', 'c', 'b', or `n' in it.
307 A ' ' blank space is the default character.
308 A '%' indicates that the message in in a named MH sequence.
309 A '-' indicates that the message has been annotated with a replied field.
310 A 't' indicates that the message contains mymbox in the To: field.
311 A 'c' indicates that the message contains mymbox in the Cc: field.
312 A 'b' indicates that the message contains mymbox in the Bcc: field.
313 A 'n' indicates that the message contains a Newsgroups: field.")
314
315 (defvar mh-scan-date-width 5
316   "Number of columns consumed by the date field in `mh-scan-format'.
317 This column will typically be of the form mm/dd.")
318
319 (defvar mh-scan-date-flag-width 1
320   "Number of columns consumed to flag (in)valid dates in `mh-scan-format'.
321 This column will have ` ' for valid and `*' for invalid or missing dates.")
322
323 (defvar mh-scan-from-mbox-width 17
324   "Number of columns consumed with the \"From:\" line in `mh-scan-format'.
325 This column will have a friendly name or e-mail address of the
326 originator, or a \"To: address\" for outgoing e-mail messages.")
327
328 (defvar mh-scan-from-mbox-sep-width 2
329   "Number of columns consumed by whitespace after from-mbox in `mh-scan-format'.
330 This column will only ever have spaces in it.")
331
332 (defvar mh-scan-field-from-start-offset
333   (+ mh-scan-cmd-note-width
334      mh-scan-destination-width
335      mh-scan-date-width
336      mh-scan-date-flag-width)
337   "The offset from the `mh-cmd-note' to find the start of \"From:\" address.")
338
339 (defvar mh-scan-field-from-end-offset
340   (+ mh-scan-field-from-start-offset mh-scan-from-mbox-width)
341   "The offset from the `mh-cmd-note' to find the end of \"From:\" address.")
342
343 (defvar mh-scan-field-subject-start-offset
344   (+ mh-scan-cmd-note-width
345      mh-scan-destination-width
346      mh-scan-date-width
347      mh-scan-date-flag-width
348      mh-scan-from-mbox-width
349      mh-scan-from-mbox-sep-width)
350   "The offset from the `mh-cmd-note' to find the start of the subject.")
351
352 (defun mh-folder-font-lock-subject (limit)
353   "Return MH-E scan subject strings to font-lock between point and LIMIT."
354   (if (not (re-search-forward mh-scan-subject-regexp limit t))
355       nil
356     (if (match-beginning 1)
357         (set-match-data (list (match-beginning 1) (match-end 3)
358                               (match-beginning 1) (match-end 3) nil nil))
359       (set-match-data (list (match-beginning 3) (match-end 3)
360                             nil nil (match-beginning 3) (match-end 3))))
361     t))
362
363 \f
364
365 ;; Fontifify unseen mesages in bold.
366
367 (defvar mh-folder-unseen-seq-name nil
368   "Name of unseen sequence.
369 The default for this is provided by the function `mh-folder-unseen-seq-name'
370 On nmh systems.")
371
372 (defun mh-folder-unseen-seq-name ()
373   "Provide name of unseen sequence from mhparam."
374   (or mh-progs (mh-find-path))
375   (save-excursion
376     (let ((unseen-seq-name "unseen"))
377       (with-temp-buffer
378         (unwind-protect
379             (progn
380               (call-process (expand-file-name "mhparam" mh-progs)
381                             nil '(t t) nil "-component" "Unseen-Sequence")
382               (goto-char (point-min))
383               (if (re-search-forward "Unseen-Sequence: \\(.*\\)$" nil t)
384                   (setq unseen-seq-name (match-string 1))))))
385       unseen-seq-name)))
386
387 (defun mh-folder-unseen-seq-list ()
388   "Return a list of unseen message numbers for current folder."
389   (if (not mh-folder-unseen-seq-name)
390       (setq mh-folder-unseen-seq-name (mh-folder-unseen-seq-name)))
391   (cond
392    ((not mh-folder-unseen-seq-name)
393     nil)
394    (t
395     (let ((folder mh-current-folder))
396       (save-excursion
397         (with-temp-buffer
398           (unwind-protect
399               (progn
400                 (call-process (expand-file-name "mark" mh-progs)
401                               nil '(t t) nil
402                               folder "-seq" mh-folder-unseen-seq-name
403                               "-list")
404                 (goto-char (point-min))
405                 (sort (mh-read-msg-list) '<)))))))))
406
407 (defmacro mh-generate-sequence-font-lock (seq prefix face)
408   "Generate the appropriate code to fontify messages in SEQ.
409 PREFIX is used to generate unique names for the variables and functions
410 defined by the macro. So a different prefix should be provided for every
411 invocation.
412 FACE is the font-lock face used to display the matching scan lines."
413   (let ((cache (intern (format "mh-folder-%s-seq-cache" prefix)))
414         (func (intern (format "mh-folder-font-lock-%s" prefix))))
415     `(progn
416        (defvar ,cache nil
417          "Internal cache variable used for font-lock in MH-E.
418 Should only be non-nil through font-lock stepping, and nil once font-lock
419 is done highlighting.")
420        (make-variable-buffer-local ',cache)
421
422        (defun ,func (limit)
423          "Return unseen message lines to font-lock between point and LIMIT."
424          (if (not ,cache) (setq ,cache (mh-seq-msgs (mh-find-seq ,seq))))
425          (let ((cur-msg (mh-get-msg-num nil)))
426            (cond ((not ,cache)
427                   nil)
428                  ((>= (point) limit)              ;Presumably at end of buffer
429                   (setq ,cache nil)
430                   nil)
431                  ((member cur-msg ,cache)
432                   (let ((bpoint (progn (beginning-of-line)(point)))
433                         (epoint (progn (forward-line 1)(point))))
434                     (if (<= limit (point)) (setq  ,cache nil))
435                     (set-match-data (list bpoint epoint bpoint epoint))
436                     t))
437                  (t
438                   ;; move forward one line at a time, checking each message
439                   (while (and (= 0 (forward-line 1))
440                               (> limit (point))
441                               (not (member (mh-get-msg-num nil) ,cache))))
442                   ;; Examine how we must have exited the loop...
443                   (let ((cur-msg (mh-get-msg-num nil)))
444                     (cond ((or (<= limit (point))
445                                (not (member cur-msg ,cache)))
446                            (setq ,cache nil)
447                            nil)
448                           ((member cur-msg ,cache)
449                            (let ((bpoint (progn (beginning-of-line) (point)))
450                                  (epoint (progn (forward-line 1) (point))))
451                              (if (<= limit (point)) (setq ,cache nil))
452                              (set-match-data
453                               (list bpoint epoint bpoint epoint))
454                              t))))))))
455
456        (setq mh-folder-font-lock-keywords
457              (append mh-folder-font-lock-keywords
458                      (list (list ',func (list 1 '',face 'prepend t))))))))
459
460 (mh-generate-sequence-font-lock mh-unseen-seq unseen bold)
461 (mh-generate-sequence-font-lock mh-tick-seq tick mh-folder-tick-face)
462
463 \f
464
465 ;;; Internal variables:
466
467 (defvar mh-last-destination nil)        ;Destination of last refile or write
468                                         ;command.
469 (defvar mh-last-destination-folder nil) ;Destination of last refile command.
470 (defvar mh-last-destination-write nil)  ;Destination of last write command.
471
472 (defvar mh-folder-mode-map (make-keymap)
473   "Keymap for MH folders.")
474
475 (defvar mh-arrow-marker nil)            ;Marker for arrow display in fringe.
476
477 (defvar mh-delete-list nil)             ;List of msg numbers to delete.
478
479 (defvar mh-refile-list nil)             ;List of folder names in mh-seq-list.
480
481 (defvar mh-next-direction 'forward)     ;Direction to move to next message.
482
483 (defvar mh-view-ops ())                 ;Stack of ops that change the folder
484                                         ;view (such as narrowing or threading).
485 (defvar mh-folder-view-stack ())        ;Stack of previous folder views.
486
487 (defvar mh-index-data nil)              ;Info about index search results
488 (defvar mh-index-previous-search nil)
489 (defvar mh-index-msg-checksum-map nil)
490 (defvar mh-index-checksum-origin-map nil)
491 (defvar mh-index-sequence-search-flag nil)
492
493 (defvar mh-first-msg-num nil)           ;Number of first msg in buffer.
494
495 (defvar mh-last-msg-num nil)            ;Number of last msg in buffer.
496
497 (defvar mh-mode-line-annotation nil)    ;Message range displayed in buffer.
498
499 (defvar mh-sequence-notation-history nil)
500                                         ;Rememeber original notation that
501                                         ;is overwritten by `mh-note-seq'.
502
503 ;;; Macros and generic functions:
504
505 (defun mh-mapc (function list)
506   "Apply FUNCTION to each element of LIST for side effects only."
507   (while list
508     (funcall function (car list))
509     (setq list (cdr list))))
510
511 (defun mh-scan-format ()
512   "Return the output format argument for the scan program."
513   (if (equal mh-scan-format-file t)
514       (list "-format" (if mh-nmh-flag
515                           (list (mh-update-scan-format
516                                  mh-scan-format-nmh mh-cmd-note))
517                         (list (mh-update-scan-format
518                                mh-scan-format-mh mh-cmd-note))))
519     (if (not (equal mh-scan-format-file nil))
520         (list "-form" mh-scan-format-file))))
521
522 \f
523
524 ;;; Entry points:
525
526 ;;;###autoload
527 (defun mh-rmail (&optional arg)
528   "Inc(orporate) new mail with MH.
529 Scan an MH folder if ARG is non-nil. This function is an entry point to MH-E,
530 the Emacs front end to the MH mail system."
531   (interactive "P")
532   (mh-find-path)
533   (if arg
534       (call-interactively 'mh-visit-folder)
535     (unless (get-buffer mh-inbox)
536       (mh-visit-folder mh-inbox (symbol-name mh-unseen-seq)))
537     (mh-inc-folder)))
538
539 ;;;###autoload
540 (defun mh-nmail (&optional arg)
541   "Check for new mail in inbox folder.
542 Scan an MH folder if ARG is non-nil. This function is an entry point to MH-E,
543 the Emacs front end to the MH mail system."
544   (interactive "P")
545   (mh-find-path)                        ; init mh-inbox
546   (if arg
547       (call-interactively 'mh-visit-folder)
548     (mh-visit-folder mh-inbox)))
549
550 \f
551
552 ;;; User executable MH-E commands:
553
554 (defun mh-delete-msg (range)
555   "Mark the specified RANGE for subsequent deletion and move to the next.
556 Default is the displayed message.
557
558 Check the documentation of `mh-interactive-range' to see how RANGE is read in
559 interactive use."
560   (interactive (list (mh-interactive-range "Delete")))
561   (mh-delete-msg-no-motion range)
562   (if (looking-at mh-scan-deleted-msg-regexp) (mh-next-msg)))
563
564 (defun mh-delete-msg-no-motion (range)
565   "Mark the specified RANGE for subsequent deletion.
566
567 Check the documentation of `mh-interactive-range' to see how RANGE is read in
568 interactive use."
569   (interactive (list (mh-interactive-range "Delete")))
570   (mh-iterate-on-range () range
571     (mh-delete-a-msg nil)))
572
573 (defun mh-execute-commands ()
574   "Process outstanding delete and refile requests."
575   (interactive)
576   (if mh-folder-view-stack (mh-widen t))
577   (mh-process-commands mh-current-folder)
578   (mh-set-scan-mode)
579   (mh-goto-cur-msg)                    ; after mh-set-scan-mode for efficiency
580   (mh-make-folder-mode-line)
581   t)                                    ; return t for write-file-functions
582
583 (defun mh-first-msg ()
584   "Move to the first message."
585   (interactive)
586   (goto-char (point-min))
587   (while (and (not (eobp)) (not (looking-at mh-scan-valid-regexp)))
588     (forward-line 1)))
589
590 (defun mh-header-display ()
591   "Show the current message with all its headers.
592 Displays headers that might have been suppressed by setting the
593 variables `mh-clean-message-header-flag' or `mhl-formfile', or by the fallback
594 behavior of scrolling uninteresting headers off the top of the window.
595 Type \"\\[mh-show]\" to show the message normally again."
596   (interactive)
597   (and (not mh-showing-with-headers)
598        (or mhl-formfile mh-clean-message-header-flag)
599        (mh-invalidate-show-buffer))
600   (let ((mh-decode-mime-flag nil)
601         (mhl-formfile nil)
602         (mh-clean-message-header-flag nil))
603     (mh-show-msg nil)
604     (mh-in-show-buffer (mh-show-buffer)
605       (goto-char (point-min))
606       (mh-recenter 0))
607     (setq mh-showing-with-headers t)))
608
609 (defun mh-inc-folder (&optional maildrop-name folder)
610   "Inc(orporate)s new mail into the Inbox folder.
611 Optional argument MAILDROP-NAME specifies an alternate maildrop from the
612 default. The optional argument FOLDER specifies where to incorporate mail
613 instead of the default named by `mh-inbox'.
614 The value of `mh-inc-folder-hook' is a list of functions to be called, with no
615 arguments, after incorporating new mail.
616 Do not call this function from outside MH-E; use \\[mh-rmail] instead."
617   (interactive (list (if current-prefix-arg
618                          (expand-file-name
619                           (read-file-name "inc mail from file: "
620                                           mh-user-path)))
621                      (if current-prefix-arg
622                          (mh-prompt-for-folder "inc mail into" mh-inbox t))))
623   (if (not folder)
624       (setq folder mh-inbox))
625   (let ((threading-needed-flag nil))
626     (let ((config (current-window-configuration)))
627       (cond ((not (get-buffer folder))
628              (mh-make-folder folder)
629              (setq threading-needed-flag mh-show-threads-flag)
630              (setq mh-previous-window-config config))
631             ((not (eq (current-buffer) (get-buffer folder)))
632              (switch-to-buffer folder)
633              (setq mh-previous-window-config config))))
634     (mh-get-new-mail maildrop-name)
635     (when (and threading-needed-flag
636                (save-excursion
637                  (goto-char (point-min))
638                  (or (null mh-large-folder)
639                      (not (equal (forward-line (1+ mh-large-folder)) 0))
640                      (and (message "Not threading since the number of messages exceeds `mh-large-folder'")
641                           nil))))
642       (mh-toggle-threads))
643     (beginning-of-line)
644     (if (and mh-showing-mode (looking-at mh-scan-valid-regexp)) (mh-show))
645     (run-hooks 'mh-inc-folder-hook)))
646
647 (defun mh-last-msg ()
648   "Move to the last message."
649   (interactive)
650   (goto-char (point-max))
651   (while (and (not (bobp)) (not (looking-at mh-scan-valid-regexp)))
652     (forward-line -1))
653   (mh-recenter nil))
654
655 (defun mh-next-undeleted-msg (&optional arg wait-after-complaining-flag)
656   "Move to the next undeleted message ARG in window.
657 If optional argument WAIT-AFTER-COMPLAINING-FLAG is non-nil and we are at the
658 last undeleted message then pause for a second after printing message."
659   (interactive "p")
660   (setq mh-next-direction 'forward)
661   (forward-line 1)
662   (cond ((re-search-forward mh-scan-good-msg-regexp nil t arg)
663          (beginning-of-line)
664          (mh-maybe-show))
665         (t (forward-line -1)
666            (message "No more undeleted messages")
667            (if wait-after-complaining-flag (sit-for 1)))))
668
669 (defun mh-folder-from-address ()
670   "Determine folder name from address in From field.
671 Takes the address in the From: header field, and returns one of:
672
673   a) The folder name associated with the address in the alist
674      `mh-default-folder-list'.  If the `Check Recipient' boolean
675       is set, then the `mh-default-folder-list' addresses are
676       checked against the recipient instead of the originator
677       (making possible to use this feature for mailing lists).
678       The first match found in `mh-default-folder-list' is used.
679
680   b) The address' corresponding alias from the user's personal
681      aliases file prefixed by `mh-default-folder-prefix'.
682
683 Returns nil if the address was not found in either place or if the variable
684 `mh-default-folder-must-exist-flag' is nil and the folder does not exist."
685   ;; Loop for all entries in mh-default-folder-list
686   (save-restriction
687     (goto-char (point-min))
688     (re-search-forward "\n\n" nil t)
689     (narrow-to-region (point-min) (point))
690     (let ((to/cc (concat (or (message-fetch-field "to") "") ", "
691                          (or (message-fetch-field "cc") "")))
692           (from (or (message-fetch-field "from") ""))
693           folder-name)
694       (setq folder-name
695             (loop for list in mh-default-folder-list
696                   when (string-match (nth 0 list) (if (nth 2 list) to/cc from))
697                   return (nth 1 list)
698                   finally return nil))
699
700       ;; Make sure a result from `mh-default-folder-list' begins with "+"
701       ;; since 'mh-expand-file-name below depends on it
702       (when (and folder-name (not (eq (aref folder-name 0) ?+)))
703         (setq folder-name (concat "+" folder-name)))
704
705       ;; If not, is there an alias for the address?
706       (when (not folder-name)
707         (let* ((from-header (mh-extract-from-header-value))
708                (address (and from-header
709                              (nth 1 (mail-extract-address-components
710                                      from-header))))
711                (alias (and address (mh-alias-address-to-alias address))))
712           (when alias
713             (setq folder-name
714                   (and alias (concat "+" mh-default-folder-prefix alias))))))
715
716       ;; If mh-default-folder-must-exist-flag set, check that folder exists.
717       (if (and folder-name
718                (or (not mh-default-folder-must-exist-flag)
719                    (file-exists-p (mh-expand-file-name folder-name))))
720           folder-name))))
721
722 (defun mh-prompt-for-refile-folder ()
723   "Prompt the user for a folder in which the message should be filed.
724 The folder is returned as a string.
725
726 If `mh-default-folder-for-message-function' is a function then the message
727 being refiled is yanked into a temporary buffer and the function is called to
728 intelligently guess where the message is to be refiled.
729
730 Otherwise, a default folder name is generated by `mh-folder-from-address'."
731   (mh-prompt-for-folder
732    "Destination"
733    (let ((refile-file (mh-msg-filename (mh-get-msg-num t))))
734      (save-excursion
735        (set-buffer (get-buffer-create mh-temp-buffer))
736        (erase-buffer)
737        (insert-file-contents refile-file)
738        (or (and mh-default-folder-for-message-function
739                 (let ((buffer-file-name refile-file))
740                   (funcall mh-default-folder-for-message-function)))
741            (mh-folder-from-address)
742            (and (eq 'refile (car mh-last-destination-folder))
743                 (symbol-name (cdr mh-last-destination-folder)))
744            "")))
745    t))
746
747 (defun mh-refile-msg (range folder &optional dont-update-last-destination-flag)
748   "Refile RANGE into FOLDER.
749
750 Check the documentation of `mh-interactive-range' to see how RANGE is read in
751 interactive use.
752
753 If optional argument DONT-UPDATE-LAST-DESTINATION-FLAG is non-nil then the
754 variables `mh-last-destination' and `mh-last-destination-folder' are not
755 updated."
756   (interactive (list (mh-interactive-range "Refile")
757                      (intern (mh-prompt-for-refile-folder))))
758   (unless dont-update-last-destination-flag
759     (setq mh-last-destination (cons 'refile folder)
760           mh-last-destination-folder mh-last-destination))
761   (mh-iterate-on-range () range
762     (mh-refile-a-msg nil folder))
763   (when (looking-at mh-scan-refiled-msg-regexp) (mh-next-msg)))
764
765 (defun mh-refile-or-write-again (message)
766   "Re-execute the last refile or write command on the given MESSAGE.
767 Default is the displayed message. Use the same folder or file as the previous
768 refile or write command."
769   (interactive (list (mh-get-msg-num t)))
770   (if (null mh-last-destination)
771       (error "No previous refile or write"))
772   (let (output)
773     (setq output
774           (cond ((eq (car mh-last-destination) 'refile)
775                  (mh-refile-a-msg message (cdr mh-last-destination))
776                  (format "Destination folder: %s" (cdr mh-last-destination)))
777                 (t
778                  (apply 'mh-write-msg-to-file message (cdr mh-last-destination))
779                  (format "Destination: %s" (cdr mh-last-destination)))))
780     (mh-next-msg (interactive-p))
781     (message output)))
782
783 (defun mh-quit ()
784   "Quit the current MH-E folder.
785 Restore the previous window configuration, if one exists.
786 The value of `mh-before-quit-hook' is a list of functions to be called, with
787 no arguments, immediately upon entry to this function.
788 The value of `mh-quit-hook' is a list of functions to be called, with no
789 arguments, upon exit of this function.
790 MH-E working buffers (whose name begins with \" *mh-\" or \"*MH-E \") are
791 killed."
792   (interactive)
793   (run-hooks 'mh-before-quit-hook)
794   (let ((show-buffer (get-buffer mh-show-buffer)))
795     (when show-buffer
796       (kill-buffer show-buffer)))
797   (mh-update-sequences)
798   (mh-destroy-postponed-handles)
799   (bury-buffer (current-buffer))
800
801   ;; Delete all MH-E temporary and working buffers.
802   (dolist (buffer (buffer-list))
803     (when (or (string-match "^ \\*mh-" (buffer-name buffer))
804               (string-match "^\\*MH-E " (buffer-name buffer)))
805       (kill-buffer buffer)))
806
807   (if mh-previous-window-config
808       (set-window-configuration mh-previous-window-config))
809   (run-hooks 'mh-quit-hook))
810
811 (defun mh-page-msg (&optional arg)
812   "Page the displayed message forwards.
813 Scrolls ARG lines or a full screen if no argument is supplied. Show buffer
814 first if not displayed. Show the next undeleted message if looking at the
815 bottom of the current message."
816   (interactive "P")
817   (if mh-showing-mode
818       (if mh-page-to-next-msg-flag
819           (if (equal mh-next-direction 'backward)
820               (mh-previous-undeleted-msg)
821             (mh-next-undeleted-msg))
822         (if (mh-in-show-buffer (mh-show-buffer)
823               (pos-visible-in-window-p (point-max)))
824             (progn
825               (message (format
826                         "End of message (Type %s to read %s undeleted message)"
827                         (single-key-description last-input-event)
828                         (if (equal mh-next-direction 'backward)
829                             "previous"
830                           "next")))
831               (setq mh-page-to-next-msg-flag t))
832           (scroll-other-window arg)))
833     (mh-show)))
834
835 (defun mh-previous-page (&optional arg)
836   "Page the displayed message backwards.
837 Scrolls ARG lines or a full screen if no argument is supplied."
838   (interactive "P")
839   (mh-in-show-buffer (mh-show-buffer)
840     (scroll-down arg)))
841
842 (defun mh-previous-undeleted-msg (&optional arg wait-after-complaining-flag)
843   "Move to the previous undeleted message ARG in window.
844 If optional argument WAIT-AFTER-COMPLAINING-FLAG is non-nil and we are at the
845 first undeleted message then pause for a second after printing message."
846   (interactive "p")
847   (setq mh-next-direction 'backward)
848   (beginning-of-line)
849   (cond ((re-search-backward mh-scan-good-msg-regexp nil t arg)
850          (mh-maybe-show))
851         (t (message "No previous undeleted message")
852            (if wait-after-complaining-flag (sit-for 1)))))
853
854 (defun mh-previous-unread-msg (&optional count)
855   "Move to previous unread message.
856 With optional argument COUNT, COUNT-1 unread messages before current message
857 are skipped."
858   (interactive "p")
859   (unless (> count 0)
860     (error "The function mh-previous-unread-msg expects positive argument"))
861   (setq count (1- count))
862   (let ((unread-sequence (cdr (assoc mh-unseen-seq mh-seq-list)))
863         (cur-msg (mh-get-msg-num nil)))
864     (cond ((and (not cur-msg) (not (bobp))
865                 ;; If we are at the end of the buffer back up one line and go
866                 ;; to unread message after that.
867                 (progn
868                   (forward-line -1)
869                   (setq cur-msg (mh-get-msg-num nil)))
870                 nil))
871           ((or (null unread-sequence) (not cur-msg))
872            ;; No unread message or there aren't any messages in buffer...
873            (message "No more unread messages"))
874           ((progn
875              ;; Skip count messages...
876              (while (and unread-sequence (>= (car unread-sequence) cur-msg))
877                (setq unread-sequence (cdr unread-sequence)))
878              (while (> count 0)
879                (setq unread-sequence (cdr unread-sequence))
880                (setq count (1- count)))
881              (not (car unread-sequence)))
882            (message "No more unread messages"))
883           (t (mh-goto-msg (car unread-sequence))))))
884
885 (defun mh-goto-next-button (backward-flag &optional criterion)
886   "Search for next button satisfying criterion.
887 If BACKWARD-FLAG is non-nil search backward in the buffer for a mime button. If
888 CRITERION is a function or a symbol which has a function binding then that
889 function must return non-nil at the button we stop."
890   (unless (or (and (symbolp criterion) (fboundp criterion))
891               (functionp criterion))
892     (setq criterion (lambda (x) t)))
893   ;; Move to the next button in the buffer satisfying criterion
894   (goto-char (or (save-excursion
895                    (beginning-of-line)
896                    ;; Find point before current button
897                    (let ((point-before-current-button
898                           (save-excursion
899                             (while (get-text-property (point) 'mh-data)
900                               (unless (= (forward-line
901                                           (if backward-flag 1 -1))
902                                          0)
903                                 (if backward-flag
904                                     (goto-char (point-min))
905                                   (goto-char (point-max)))))
906                             (point))))
907                      ;; Skip over current button
908                      (while (and (get-text-property (point) 'mh-data)
909                                  (not (if backward-flag (bobp) (eobp))))
910                        (forward-line (if backward-flag -1 1)))
911                      ;; Stop at next MIME button if any exists.
912                      (block loop
913                        (while (/= (progn
914                                     (unless (= (forward-line
915                                                 (if backward-flag -1 1))
916                                                0)
917                                       (if backward-flag
918                                           (goto-char (point-max))
919                                         (goto-char (point-min)))
920                                       (beginning-of-line))
921                                     (point))
922                                   point-before-current-button)
923                          (when (and (get-text-property (point) 'mh-data)
924                                     (funcall criterion (point)))
925                            (return-from loop (point))))
926                        nil)))
927                  (point))))
928
929 (defun mh-next-button (&optional backward-flag)
930   "Go to the next MIME button.
931 Advance point to the next MIME button in the show buffer. If the end
932 of buffer is reached then the search wraps over to the start of the
933 buffer. With prefix argument, BACKWARD-FLAG the point will move to the
934 previous MIME button."
935   (interactive (list current-prefix-arg))
936   (unless mh-showing-mode
937     (mh-show))
938   (mh-in-show-buffer (mh-show-buffer)
939     (mh-goto-next-button backward-flag)))
940
941 (defun mh-prev-button ()
942   "Go to the prev MIME button.
943 Move point to the previous MIME button in the show buffer. If the beginning
944 of the buffer is reached then the search wraps over to the end of the
945 buffer."
946   (interactive)
947   (mh-next-button t))
948
949 (defun mh-folder-mime-action (part-index action include-security-flag)
950   "Go to PART-INDEX and carry out ACTION.
951 If PART-INDEX is nil then go to the next part in the buffer. The search for
952 the next buffer wraps around if end of buffer is reached. If argument
953 INCLUDE-SECURITY-FLAG is non-nil then include security info buttons when
954 searching for a suitable parts."
955   (unless mh-showing-mode
956     (mh-show))
957   (mh-in-show-buffer (mh-show-buffer)
958     (let ((criterion
959            (cond (part-index
960                   (lambda (p)
961                     (let ((part (get-text-property p 'mh-part)))
962                       (and (integerp part) (= part part-index)))))
963                  (t (lambda (p)
964                       (if include-security-flag
965                           (get-text-property p 'mh-data)
966                         (integerp (get-text-property p 'mh-part)))))))
967           (point (point)))
968       (cond ((and (get-text-property point 'mh-part)
969                   (or (null part-index)
970                       (= (get-text-property point 'mh-part) part-index)))
971              (funcall action))
972             ((and (get-text-property point 'mh-data)
973                   include-security-flag
974                   (null part-index))
975              (funcall action))
976             (t
977              (mh-goto-next-button nil criterion)
978              (if (= (point) point)
979                  (message "No matching MIME part found")
980                (funcall action)))))))
981
982 (defun mh-folder-toggle-mime-part (part-index)
983   "Toggle display of button.
984 If point in show buffer is at a button then that part is toggled.
985 If not at a button and PART-INDEX is non-nil point is moved to that part.
986 With nil PART-INDEX find the first button after point (search wraps around if
987 end of buffer is reached) and toggle it."
988   (interactive "P")
989   (when (consp part-index) (setq part-index (car part-index)))
990   (mh-folder-mime-action part-index #'mh-press-button t))
991
992 (defun mh-folder-inline-mime-part (part-index)
993   "Show the raw bytes of MIME part inline.
994 If point in show buffer is at a mime part then that part is inlined.
995 If not at a mime-part and PART-INDEX is non-nil point is moved to that part.
996 With nil PART-INDEX find the first button after point (search wraps around if
997 end of buffer is reached) and inline it."
998   (interactive "P")
999   (when (consp part-index) (setq part-index (car part-index)))
1000   (mh-folder-mime-action part-index #'mh-mime-inline-part nil))
1001
1002 (defun mh-folder-save-mime-part (part-index)
1003   "Save MIME part.
1004 If point in show buffer is at a mime part then that part is saved.
1005 If not at a mime-part and PART-INDEX is non-nil point is moved to that part.
1006 With nil PART-INDEX find the first button after point (search wraps around if
1007 end of buffer is reached) and save it."
1008   (interactive "P")
1009   (when (consp part-index) (setq part-index (car part-index)))
1010   (mh-folder-mime-action part-index #'mh-mime-save-part nil))
1011
1012 (defvar mh-thread-scan-line-map-stack)
1013
1014 (defun mh-reset-threads-and-narrowing ()
1015   "Reset all variables pertaining to threads and narrowing.
1016 Also removes all content from the folder buffer."
1017   (setq mh-view-ops ())
1018   (setq mh-folder-view-stack ())
1019   (setq mh-thread-scan-line-map-stack ())
1020   (let ((buffer-read-only nil)) (erase-buffer)))
1021
1022 (defun mh-rescan-folder (&optional range dont-exec-pending)
1023   "Rescan a folder after optionally processing the outstanding commands.
1024 If optional prefix argument RANGE is provided, prompt for the range of
1025 messages to display. Otherwise show the entire folder.
1026 If optional argument DONT-EXEC-PENDING is non-nil then pending deletes and
1027 refiles aren't carried out."
1028   (interactive (list (if current-prefix-arg
1029                          (mh-read-range "Rescan" mh-current-folder t nil t
1030                                         mh-interpret-number-as-range-flag)
1031                        nil)))
1032   (setq mh-next-direction 'forward)
1033   (let ((threaded-flag (memq 'unthread mh-view-ops)))
1034     (mh-scan-folder mh-current-folder (or range "all") dont-exec-pending)
1035     (cond (threaded-flag (mh-toggle-threads))
1036           (mh-index-data (mh-index-insert-folder-headers)))))
1037
1038 (defun mh-write-msg-to-file (msg file no-headers)
1039   "Append MSG to the end of a FILE.
1040 If prefix argument NO-HEADERS is provided, write only the message body.
1041 Otherwise send the entire message including the headers."
1042   (interactive
1043    (list (mh-get-msg-num t)
1044          (let ((default-dir (if (eq 'write (car mh-last-destination-write))
1045                                 (file-name-directory
1046                                  (car (cdr mh-last-destination-write)))
1047                               default-directory)))
1048            (read-file-name (format "Save message%s in file: "
1049                                    (if current-prefix-arg " body" ""))
1050                            default-dir
1051                            (if (eq 'write (car mh-last-destination-write))
1052                                (car (cdr mh-last-destination-write))
1053                              (expand-file-name "mail.out" default-dir))))
1054          current-prefix-arg))
1055   (let ((msg-file-to-output (mh-msg-filename msg))
1056         (output-file (mh-expand-file-name file)))
1057     (setq mh-last-destination (list 'write file (if no-headers 'no-headers))
1058           mh-last-destination-write mh-last-destination)
1059     (save-excursion
1060       (set-buffer (get-buffer-create mh-temp-buffer))
1061       (erase-buffer)
1062       (insert-file-contents msg-file-to-output)
1063       (goto-char (point-min))
1064       (if no-headers (search-forward "\n\n"))
1065       (append-to-file (point) (point-max) output-file))))
1066
1067 (defun mh-toggle-showing ()
1068   "Toggle the scanning mode/showing mode of displaying messages."
1069   (interactive)
1070   (if mh-showing-mode
1071       (mh-set-scan-mode)
1072     (mh-show)))
1073
1074 (defun mh-undo (range)
1075   "Undo the pending deletion or refile of the specified RANGE.
1076
1077 Check the documentation of `mh-interactive-range' to see how RANGE is read in
1078 interactive use."
1079   (interactive (list (mh-interactive-range "Undo")))
1080   (cond ((numberp range)
1081          (let ((original-position (point)))
1082            (beginning-of-line)
1083            (while (not (or (looking-at mh-scan-deleted-msg-regexp)
1084                            (looking-at mh-scan-refiled-msg-regexp)
1085                            (and (eq mh-next-direction 'forward) (bobp))
1086                            (and (eq mh-next-direction 'backward)
1087                                 (save-excursion (forward-line) (eobp)))))
1088              (forward-line (if (eq mh-next-direction 'forward) -1 1)))
1089            (if (or (looking-at mh-scan-deleted-msg-regexp)
1090                    (looking-at mh-scan-refiled-msg-regexp))
1091                (progn
1092                  (mh-undo-msg (mh-get-msg-num t))
1093                  (mh-maybe-show))
1094              (goto-char original-position)
1095              (error "Nothing to undo"))))
1096         (t (mh-iterate-on-range () range
1097              (mh-undo-msg nil))))
1098   (if (not (mh-outstanding-commands-p))
1099       (mh-set-folder-modified-p nil)))
1100
1101 ;;;###mh-autoload
1102 (defun mh-folder-line-matches-show-buffer-p ()
1103   "Return t if the message under point in folder-mode is in the show buffer.
1104 Return nil in any other circumstance (no message under point, no show buffer,
1105 the message in the show buffer doesn't match."
1106   (and (eq major-mode 'mh-folder-mode)
1107        (mh-get-msg-num nil)
1108        mh-show-buffer
1109        (get-buffer mh-show-buffer)
1110        (buffer-file-name (get-buffer mh-show-buffer))
1111        (string-match ".*/\\([0-9]+\\)$"
1112                      (buffer-file-name (get-buffer mh-show-buffer)))
1113        (string-equal
1114         (match-string 1 (buffer-file-name (get-buffer mh-show-buffer)))
1115         (int-to-string (mh-get-msg-num nil)))))
1116
1117 (eval-when-compile (require 'gnus))
1118
1119 (defmacro mh-macro-expansion-time-gnus-version ()
1120   "Return Gnus version available at macro expansion time.
1121 The macro evaluates the Gnus version at macro expansion time. If MH-E was
1122 compiled then macro expansion happens at compile time."
1123   gnus-version)
1124
1125 (defun mh-run-time-gnus-version ()
1126   "Return Gnus version available at run time."
1127   (require 'gnus)
1128   gnus-version)
1129
1130 ;;;###autoload
1131 (defun mh-version ()
1132   "Display version information about MH-E and the MH mail handling system."
1133   (interactive)
1134   (mh-find-progs)
1135   (set-buffer (get-buffer-create mh-info-buffer))
1136   (erase-buffer)
1137   ;; MH-E version.
1138   (insert "MH-E " mh-version "\n\n")
1139   ;; MH-E compilation details.
1140   (insert "MH-E compilation details:\n")
1141   (let* ((compiled-mhe (byte-code-function-p (symbol-function 'mh-version)))
1142          (gnus-compiled-version (if compiled-mhe
1143                                     (mh-macro-expansion-time-gnus-version)
1144                                   "N/A")))
1145     (insert " Byte compiled:\t\t" (if compiled-mhe "yes" "no") "\n"
1146             " Gnus (compile-time):\t" gnus-compiled-version "\n"
1147             " Gnus (run-time):\t" (mh-run-time-gnus-version) "\n\n"))
1148   ;; Emacs version.
1149   (insert (emacs-version) "\n\n")
1150   ;; MH version.
1151   (let ((help-start (point)))
1152     (condition-case err-data
1153         (mh-exec-cmd-output "inc" nil (if mh-nmh-flag "-version" "-help"))
1154       (file-error (insert (mapconcat 'concat (cdr err-data) ": ") "\n")))
1155     (goto-char help-start)
1156     (if mh-nmh-flag
1157         (search-forward "inc -- " nil t)
1158       (search-forward "version: " nil t))
1159     (delete-region help-start (point)))
1160   (goto-char (point-max))
1161   (insert " mh-progs:\t" mh-progs "\n"
1162           " mh-lib:\t" mh-lib "\n"
1163           " mh-lib-progs:\t" mh-lib-progs "\n\n")
1164   ;; Linux version.
1165   (condition-case ()
1166       (call-process "uname" nil t nil "-a")
1167     (file-error))
1168   (goto-char (point-min))
1169   (display-buffer mh-info-buffer))
1170
1171 (defun mh-parse-flist-output-line (line &optional current-folder)
1172   "Parse LINE to generate folder name, unseen messages and total messages.
1173 If CURRENT-FOLDER is non-nil then it contains the current folder name and it is
1174 used to avoid problems in corner cases involving folders whose names end with a
1175 '+' character."
1176   (with-temp-buffer
1177     (insert line)
1178     (goto-char (point-max))
1179     (let (folder unseen total p)
1180       (when (search-backward " out of " (point-min) t)
1181         (setq total (read-from-string
1182                      (buffer-substring-no-properties
1183                       (match-end 0) (line-end-position))))
1184         (when (search-backward " in sequence " (point-min) t)
1185           (setq p (point))
1186           (when (search-backward " has " (point-min) t)
1187             (setq unseen (read-from-string (buffer-substring-no-properties
1188                                             (match-end 0) p)))
1189             (while (eq (char-after) ? )
1190               (backward-char))
1191             (setq folder (buffer-substring-no-properties
1192                           (point-min) (1+ (point))))
1193             (when (and (equal (aref folder (1- (length folder))) ?+)
1194                        (equal current-folder folder))
1195               (setq folder (substring folder 0 (1- (length folder)))))
1196             (values (format "+%s" folder) (car unseen) (car total))))))))
1197
1198 (defun mh-folder-size-folder (folder)
1199   "Find size of FOLDER using `folder'."
1200   (with-temp-buffer
1201     (let ((u (length (cdr (assoc mh-unseen-seq
1202                                  (mh-read-folder-sequences folder nil))))))
1203       (call-process (expand-file-name "folder" mh-progs) nil t nil
1204                     "-norecurse" folder)
1205       (goto-char (point-min))
1206       (if (re-search-forward " has \\([0-9]+\\) " nil t)
1207           (values (car (read-from-string (match-string 1))) u folder)
1208         (values 0 u folder)))))
1209
1210 (defun mh-folder-size-flist (folder)
1211   "Find size of FOLDER using `flist'."
1212   (with-temp-buffer
1213     (call-process (expand-file-name "flist" mh-progs) nil t nil
1214                   "-norecurse" folder "-sequence" (symbol-name mh-unseen-seq))
1215     (goto-char (point-min))
1216     (multiple-value-bind (folder unseen total)
1217         (mh-parse-flist-output-line
1218          (buffer-substring (point) (line-end-position)))
1219       (values total unseen folder))))
1220
1221 (defun mh-folder-size (folder)
1222   "Find size of FOLDER."
1223   (if mh-flists-present-flag
1224       (mh-folder-size-flist folder)
1225     (mh-folder-size-folder folder)))
1226
1227 (defun mh-visit-folder (folder &optional range index-data)
1228   "Visit FOLDER and display RANGE of messages.
1229 Do not call this function from outside MH-E; see \\[mh-rmail] instead.
1230
1231 If RANGE is nil (the default if it is omitted when called non-interactively),
1232 then all messages in FOLDER are displayed.
1233
1234 If an index buffer is being created then INDEX-DATA is used to initialize the
1235 index buffer specific data structures.
1236
1237 A prefix argument will cause a prompt for the RANGE of messages
1238 regardless of the size of the `mh-large-folder' variable."
1239   (interactive (let ((folder-name (mh-prompt-for-folder "Visit" mh-inbox t)))
1240                  (list folder-name
1241                        (mh-read-range "Scan" folder-name t nil
1242                                       current-prefix-arg
1243                                       mh-interpret-number-as-range-flag))))
1244   (let ((config (current-window-configuration))
1245         (current-buffer (current-buffer))
1246         (threaded-view-flag mh-show-threads-flag))
1247     (save-excursion
1248       (when (get-buffer folder)
1249         (set-buffer folder)
1250         (setq threaded-view-flag (memq 'unthread mh-view-ops))))
1251     (when index-data
1252       (mh-make-folder folder)
1253       (setq mh-index-data (car index-data)
1254             mh-index-msg-checksum-map (make-hash-table :test #'equal)
1255             mh-index-checksum-origin-map (make-hash-table :test #'equal))
1256       (mh-index-update-maps folder (cadr index-data))
1257       (mh-index-create-sequences))
1258     (mh-scan-folder folder (or range "all"))
1259     (cond ((and threaded-view-flag
1260                 (save-excursion
1261                   (goto-char (point-min))
1262                   (or (null mh-large-folder)
1263                       (not (equal (forward-line (1+ mh-large-folder)) 0))
1264                       (and (message "Not threading since the number of messages exceeds `mh-large-folder'")
1265                            nil))))
1266            (mh-toggle-threads))
1267           (mh-index-data
1268            (mh-index-insert-folder-headers)))
1269     (unless mh-showing-mode (delete-other-windows))
1270     (unless (eq current-buffer (current-buffer))
1271       (setq mh-previous-window-config config)))
1272   nil)
1273
1274 ;;;###mh-autoload
1275 (defun mh-update-sequences ()
1276   "Update MH's Unseen-Sequence and current folder and message.
1277 Flush MH-E's state out to MH. The message at the cursor becomes current."
1278   (interactive)
1279   ;; mh-update-sequences is the opposite of mh-read-folder-sequences,
1280   ;; which updates MH-E's state from MH.
1281   (let ((folder-set (mh-update-unseen))
1282         (new-cur (mh-get-msg-num nil)))
1283     (if new-cur
1284         (let ((seq-entry (mh-find-seq 'cur)))
1285           (mh-remove-cur-notation)
1286           (setcdr seq-entry
1287                   (list new-cur))       ;delete-seq-locally, add-msgs-to-seq
1288           (mh-define-sequence 'cur (list new-cur))
1289           (beginning-of-line)
1290           (if (looking-at mh-scan-good-msg-regexp)
1291               (mh-notate-cur)))
1292       (or folder-set
1293           (save-excursion
1294             ;; psg - mh-current-folder is nil if mh-summary-height < 4 !
1295             ;;       So I added this sanity check.
1296             (if (stringp mh-current-folder)
1297                 (mh-exec-cmd-quiet t "folder" mh-current-folder "-fast")
1298               (mh-exec-cmd-quiet t "folder" "-fast")))))))
1299
1300 \f
1301
1302 ;;; Support routines.
1303
1304 (defun mh-delete-a-msg (msg)
1305   "Delete the MSG.
1306 If MSG is nil then the message at point is deleted.
1307
1308 The value of `mh-delete-msg-hook' is a list of functions to be called, with no
1309 arguments, after the message has been deleted."
1310   (save-excursion
1311     (if (numberp msg)
1312         (mh-goto-msg msg nil t)
1313       (beginning-of-line)
1314       (setq msg (mh-get-msg-num t)))
1315     (if (looking-at mh-scan-refiled-msg-regexp)
1316         (error "Message %d is refiled.  Undo refile before deleting" msg))
1317     (if (looking-at mh-scan-deleted-msg-regexp)
1318         nil
1319       (mh-set-folder-modified-p t)
1320       (setq mh-delete-list (cons msg mh-delete-list))
1321       (mh-notate nil mh-note-deleted mh-cmd-note)
1322       (run-hooks 'mh-delete-msg-hook))))
1323
1324 (defun mh-refile-a-msg (msg folder)
1325   "Refile MSG in FOLDER.
1326 If MSG is nil then the message at point is refiled.
1327
1328 Folder is a symbol, not a string.
1329 The value of `mh-refile-msg-hook' is a list of functions to be called, with no
1330 arguments, after the message has been refiled."
1331   (save-excursion
1332     (if (numberp msg)
1333         (mh-goto-msg msg nil t)
1334       (beginning-of-line)
1335       (setq msg (mh-get-msg-num t)))
1336     (cond ((looking-at mh-scan-deleted-msg-regexp)
1337            (error "Message %d is deleted.  Undo delete before moving" msg))
1338           ((looking-at mh-scan-refiled-msg-regexp)
1339            (if (y-or-n-p
1340                 (format "Message %d already refiled.  Copy to %s as well? "
1341                         msg folder))
1342                (mh-exec-cmd "refile" (mh-get-msg-num t) "-link"
1343                             "-src" mh-current-folder
1344                             (symbol-name folder))
1345              (message "Message not copied.")))
1346           (t
1347            (mh-set-folder-modified-p t)
1348            (cond ((null (assoc folder mh-refile-list))
1349                   (push (list folder msg) mh-refile-list))
1350                  ((not (member msg (cdr (assoc folder mh-refile-list))))
1351                   (push msg (cdr (assoc folder mh-refile-list)))))
1352            (mh-notate nil mh-note-refiled mh-cmd-note)
1353            (run-hooks 'mh-refile-msg-hook)))))
1354
1355 (defun mh-next-msg (&optional wait-after-complaining-flag)
1356   "Move backward or forward to the next undeleted message in the buffer.
1357 If optional argument WAIT-AFTER-COMPLAINING-FLAG is non-nil and we are at the
1358 last message, then wait for a second after telling the user that there aren't
1359 any more unread messages."
1360   (if (eq mh-next-direction 'forward)
1361       (mh-next-undeleted-msg 1 wait-after-complaining-flag)
1362     (mh-previous-undeleted-msg 1 wait-after-complaining-flag)))
1363
1364 (defun mh-next-unread-msg (&optional count)
1365   "Move to next unread message.
1366 With optional argument COUNT, COUNT-1 unread messages are skipped."
1367   (interactive "p")
1368   (unless (> count 0)
1369     (error "The function mh-next-unread-msg expects positive argument"))
1370   (setq count (1- count))
1371   (let ((unread-sequence (reverse (cdr (assoc mh-unseen-seq mh-seq-list))))
1372         (cur-msg (mh-get-msg-num nil)))
1373     (cond ((and (not cur-msg) (not (bobp))
1374                 ;; If we are at the end of the buffer back up one line and go
1375                 ;; to unread message after that.
1376                 (progn
1377                   (forward-line -1)
1378                   (setq cur-msg (mh-get-msg-num nil)))
1379                 nil))
1380           ((or (null unread-sequence) (not cur-msg))
1381            ;; No unread message or there aren't any messages in buffer...
1382            (message "No more unread messages"))
1383           ((progn
1384              ;; Skip messages
1385              (while (and unread-sequence (>= cur-msg (car unread-sequence)))
1386                (setq unread-sequence (cdr unread-sequence)))
1387              (while (> count 0)
1388                (setq unread-sequence (cdr unread-sequence))
1389                (setq count (1- count)))
1390              (not (car unread-sequence)))
1391            (message "No more unread messages"))
1392           (t (mh-goto-msg (car unread-sequence))))))
1393
1394 (defun mh-set-scan-mode ()
1395   "Display the scan listing buffer, but do not show a message."
1396   (if (get-buffer mh-show-buffer)
1397       (delete-windows-on mh-show-buffer))
1398   (mh-showing-mode 0)
1399   (force-mode-line-update)
1400   (if mh-recenter-summary-flag
1401       (mh-recenter nil)))
1402
1403 (defun mh-undo-msg (msg)
1404   "Undo the deletion or refile of one MSG.
1405 If MSG is nil then act on the message at point"
1406   (save-excursion
1407     (if (numberp msg)
1408         (mh-goto-msg msg t t)
1409       (beginning-of-line)
1410       (setq msg (mh-get-msg-num t)))
1411     (cond ((memq msg mh-delete-list)
1412            (setq mh-delete-list (delq msg mh-delete-list)))
1413           (t
1414            (dolist (folder-msg-list mh-refile-list)
1415              (setf (cdr folder-msg-list) (remove msg (cdr folder-msg-list))))
1416            (setq mh-refile-list (loop for x in mh-refile-list
1417                                       unless (null (cdr x)) collect x))))
1418     (mh-notate nil ?  mh-cmd-note)))
1419
1420 \f
1421
1422 ;;; The folder data abstraction.
1423
1424 (defvar mh-index-data-file ".mhe_index"
1425   "MH-E specific file where index seach info is stored.")
1426
1427 (defun mh-make-folder (name)
1428   "Create a new mail folder called NAME.
1429 Make it the current folder."
1430   (switch-to-buffer name)
1431   (setq buffer-read-only nil)
1432   (erase-buffer)
1433   (if mh-adaptive-cmd-note-flag
1434       (mh-set-cmd-note (mh-message-number-width name)))
1435   (setq buffer-read-only t)
1436   (mh-folder-mode)
1437   (mh-set-folder-modified-p nil)
1438   (setq buffer-file-name mh-folder-filename)
1439   (when (and (not mh-index-data)
1440              (file-exists-p (concat buffer-file-name mh-index-data-file)))
1441     (mh-index-read-data))
1442   (mh-make-folder-mode-line))
1443
1444 ;;; Ensure new buffers won't get this mode if default-major-mode is nil.
1445 (put 'mh-folder-mode 'mode-class 'special)
1446
1447 \f
1448
1449 ;;; Menu extracted from mh-menubar.el V1.1 (31 July 2001)
1450 ;;; Menus for folder mode: folder, message, sequence (in that order)
1451 ;;; folder-mode "Sequence" menu
1452 (easy-menu-define
1453   mh-folder-sequence-menu mh-folder-mode-map "Menu for MH-E folder-sequence."
1454   '("Sequence"
1455     ["Add Message to Sequence..."       mh-put-msg-in-seq (mh-get-msg-num nil)]
1456     ["List Sequences for Message"       mh-msg-is-in-seq (mh-get-msg-num nil)]
1457     ["Delete Message from Sequence..."  mh-delete-msg-from-seq
1458      (mh-get-msg-num nil)]
1459     ["List Sequences in Folder..."      mh-list-sequences t]
1460     ["Delete Sequence..."               mh-delete-seq t]
1461     ["Narrow to Sequence..."            mh-narrow-to-seq t]
1462     ["Widen from Sequence"              mh-widen mh-folder-view-stack]
1463     "--"
1464     ["Narrow to Subject Sequence"       mh-narrow-to-subject t]
1465     ["Narrow to Tick Sequence"          mh-narrow-to-tick
1466      (and mh-tick-seq (mh-seq-msgs (mh-find-seq mh-tick-seq)))]
1467     ["Delete Rest of Same Subject"      mh-delete-subject t]
1468     ["Toggle Tick Mark"                 mh-toggle-tick t]
1469     "--"
1470     ["Push State Out to MH"             mh-update-sequences t]))
1471
1472 ;;; folder-mode "Message" menu
1473 (easy-menu-define
1474   mh-folder-message-menu mh-folder-mode-map "Menu for MH-E folder-message."
1475   '("Message"
1476     ["Show Message"                     mh-show (mh-get-msg-num nil)]
1477     ["Show Message with Header"         mh-header-display (mh-get-msg-num nil)]
1478     ["Next Message"                     mh-next-undeleted-msg t]
1479     ["Previous Message"                 mh-previous-undeleted-msg t]
1480     ["Go to First Message"              mh-first-msg t]
1481     ["Go to Last Message"               mh-last-msg t]
1482     ["Go to Message by Number..."       mh-goto-msg t]
1483     ["Modify Message"                   mh-modify]
1484     ["Delete Message"                   mh-delete-msg (mh-get-msg-num nil)]
1485     ["Refile Message"                   mh-refile-msg (mh-get-msg-num nil)]
1486     ["Undo Delete/Refile"               mh-undo t]
1487     ["Process Delete/Refile"            mh-execute-commands
1488      (or mh-refile-list mh-delete-list)]
1489     "--"
1490     ["Compose a New Message"            mh-send t]
1491     ["Reply to Message..."              mh-reply (mh-get-msg-num nil)]
1492     ["Forward Message..."               mh-forward (mh-get-msg-num nil)]
1493     ["Redistribute Message..."          mh-redistribute (mh-get-msg-num nil)]
1494     ["Edit Message Again"               mh-edit-again (mh-get-msg-num nil)]
1495     ["Re-edit a Bounced Message"        mh-extract-rejected-mail t]
1496     "--"
1497     ["Copy Message to Folder..."        mh-copy-msg (mh-get-msg-num nil)]
1498     ["Print Message"                    mh-print-msg (mh-get-msg-num nil)]
1499     ["Write Message to File..."         mh-write-msg-to-file
1500      (mh-get-msg-num nil)]
1501     ["Pipe Message to Command..."       mh-pipe-msg (mh-get-msg-num nil)]
1502     ["Unpack Uuencoded Message..."      mh-store-msg (mh-get-msg-num nil)]
1503     ["Burst Digest Message"             mh-burst-digest (mh-get-msg-num nil)]))
1504
1505 ;;; folder-mode "Folder" menu
1506 (easy-menu-define
1507   mh-folder-folder-menu mh-folder-mode-map  "Menu for MH-E folder."
1508   '("Folder"
1509     ["Incorporate New Mail"             mh-inc-folder t]
1510     ["Toggle Show/Folder"               mh-toggle-showing t]
1511     ["Execute Delete/Refile"            mh-execute-commands
1512      (or mh-refile-list mh-delete-list)]
1513     ["Rescan Folder"                    mh-rescan-folder t]
1514     ["Thread Folder"                    mh-toggle-threads
1515      (not (memq 'unthread mh-view-ops))]
1516     ["Pack Folder"                      mh-pack-folder t]
1517     ["Sort Folder"                      mh-sort-folder t]
1518     "--"
1519     ["List Folders"                     mh-list-folders t]
1520     ["Visit a Folder..."                mh-visit-folder t]
1521     ["View New Messages"                mh-index-new-messages t]
1522     ["Search a Folder..."               mh-search-folder t]
1523     ["Indexed Search..."                mh-index-search t]
1524     "--"
1525     ["Quit MH-E"                        mh-quit t]))
1526
1527 \f
1528
1529 (defmacro mh-remove-xemacs-horizontal-scrollbar ()
1530   "Get rid of the horizontal scrollbar that XEmacs insists on putting in."
1531   (when mh-xemacs-flag
1532     `(if (and (featurep 'scrollbar)
1533               (fboundp 'set-specifier))
1534          (set-specifier horizontal-scrollbar-visible-p nil
1535                         (cons (current-buffer) nil)))))
1536
1537 ;; Avoid compiler warnings in XEmacs and GNU Emacs 20
1538 (eval-when-compile (defvar tool-bar-mode))
1539
1540 (defmacro mh-write-file-functions-compat ()
1541   "Return `write-file-functions' if it exists.
1542 Otherwise return `local-write-file-hooks'. This macro exists purely for
1543 compatibility. The former symbol is used in Emacs 21.4 onward while the latter
1544 is used in previous versions and XEmacs."
1545   (if (boundp 'write-file-functions)
1546       ''write-file-functions            ;Emacs 21.4
1547     ''local-write-file-hooks))          ;<Emacs 21.4, XEmacs
1548
1549 ;; Avoid compiler warnings in XEmacs and Emacs 20
1550 (eval-when-compile
1551   (defvar tool-bar-mode)
1552   (defvar tool-bar-map))
1553
1554 (define-derived-mode mh-folder-mode fundamental-mode "MH-Folder"
1555   "Major MH-E mode for \"editing\" an MH folder scan listing.\\<mh-folder-mode-map>
1556
1557 You can show the message the cursor is pointing to, and step through the
1558 messages.  Messages can be marked for deletion or refiling into another
1559 folder; these commands are executed all at once with a separate command.
1560
1561 A prefix argument (\\[universal-argument]) to delete, refile, list, or undo
1562 applies the action to a message sequence. If `transient-mark-mode',
1563 is non-nil, the action is applied to the region.
1564
1565 Options that control this mode can be changed with \\[customize-group];
1566 specify the \"mh\" group. In particular, please see the `mh-scan-format-file'
1567 option if you wish to modify scan's format.
1568
1569 When a folder is visited, the hook `mh-folder-mode-hook' is run.
1570
1571 \\{mh-folder-mode-map}"
1572
1573   (make-local-variable 'font-lock-defaults)
1574   (setq font-lock-defaults '(mh-folder-font-lock-keywords t))
1575   (mh-make-local-vars
1576    'mh-current-folder (buffer-name)     ; Name of folder, a string
1577    'mh-show-buffer (format "show-%s" (buffer-name)) ; Buffer that displays msgs
1578    'mh-folder-filename                  ; e.g. "/usr/foobar/Mail/inbox/"
1579    (file-name-as-directory (mh-expand-file-name (buffer-name)))
1580    'mh-arrow-marker (make-marker)       ; Marker where arrow is displayed
1581    'overlay-arrow-position nil          ; Allow for simultaneous display in
1582    'overlay-arrow-string ">"            ;  different MH-E buffers.
1583    'mh-showing-mode nil                 ; Show message also?
1584    'mh-delete-list nil                  ; List of msgs nums to delete
1585    'mh-refile-list nil                  ; List of folder names in mh-seq-list
1586    'mh-seq-list nil                     ; Alist of (seq . msgs) nums
1587    'mh-seen-list nil                    ; List of displayed messages
1588    'mh-next-direction 'forward          ; Direction to move to next message
1589    'mh-view-ops ()                      ; Stack that keeps track of the order
1590                                         ; in which narrowing/threading has been
1591                                         ; carried out.
1592    'mh-folder-view-stack ()             ; Stack of previous views of the
1593                                         ; folder.
1594    'mh-index-data nil                   ; If the folder was created by a call
1595                                         ; to mh-index-search this contains info
1596                                         ; about the search results.
1597    'mh-index-previous-search nil        ; Previous folder and search-regexp
1598    'mh-index-msg-checksum-map nil       ; msg -> checksum map
1599    'mh-index-checksum-origin-map nil    ; checksum -> ( orig-folder, orig-msg )
1600    'mh-index-sequence-search-flag nil   ; folder resulted from sequence search
1601    'mh-first-msg-num nil                ; Number of first msg in buffer
1602    'mh-last-msg-num nil                 ; Number of last msg in buffer
1603    'mh-msg-count nil                    ; Number of msgs in buffer
1604    'mh-mode-line-annotation nil         ; Indicates message range
1605    'mh-sequence-notation-history (make-hash-table)
1606                                         ; Remember what is overwritten by
1607                                         ; mh-note-seq.
1608    'mh-previous-window-config nil)      ; Previous window configuration
1609   (mh-remove-xemacs-horizontal-scrollbar)
1610   (setq truncate-lines t)
1611   (auto-save-mode -1)
1612   (setq buffer-offer-save t)
1613   (mh-make-local-hook (mh-write-file-functions-compat))
1614   (add-hook (mh-write-file-functions-compat) 'mh-execute-commands nil t)
1615   (make-local-variable 'revert-buffer-function)
1616   (make-local-variable 'hl-line-mode)   ; avoid pollution
1617   (mh-funcall-if-exists hl-line-mode 1)
1618   (setq revert-buffer-function 'mh-undo-folder)
1619   (or (assq 'mh-showing-mode minor-mode-alist)
1620       (setq minor-mode-alist
1621             (cons '(mh-showing-mode " Show") minor-mode-alist)))
1622   (easy-menu-add mh-folder-sequence-menu)
1623   (easy-menu-add mh-folder-message-menu)
1624   (easy-menu-add mh-folder-folder-menu)
1625   (set (make-local-variable 'tool-bar-map) mh-folder-tool-bar-map)
1626   (mh-funcall-if-exists mh-toolbar-init :folder)
1627   (if (and mh-xemacs-flag
1628            font-lock-auto-fontify)
1629       (turn-on-font-lock)))             ; Force font-lock in XEmacs.
1630
1631 (defun mh-make-local-vars (&rest pairs)
1632   "Initialize local variables according to the variable-value PAIRS."
1633
1634   (while pairs
1635     (set (make-local-variable (car pairs)) (car (cdr pairs)))
1636     (setq pairs (cdr (cdr pairs)))))
1637
1638 (defun mh-scan-folder (folder range &optional dont-exec-pending)
1639   "Scan the FOLDER over the RANGE.
1640 If the optional argument DONT-EXEC-PENDING is non-nil then pending deletes and
1641 refiles aren't carried out.
1642 Return in the folder's buffer."
1643   (cond ((null (get-buffer folder))
1644          (mh-make-folder folder))
1645         (t
1646          (unless dont-exec-pending
1647            (mh-process-or-undo-commands folder)
1648            (mh-reset-threads-and-narrowing))
1649          (switch-to-buffer folder)))
1650   (mh-regenerate-headers range)
1651   (if (zerop (buffer-size))
1652       (if (equal range "all")
1653           (message "Folder %s is empty" folder)
1654         (message "No messages in %s, range %s" folder range))
1655     (mh-goto-cur-msg))
1656   (when (mh-outstanding-commands-p)
1657     (mh-notate-deleted-and-refiled)))
1658
1659 (defun mh-set-cmd-note (width)
1660   "Set `mh-cmd-note' to WIDTH characters (minimum of 2).
1661
1662 If `mh-scan-format-file' specifies nil or a filename, then this function
1663 will NOT update `mh-cmd-note'."
1664   ;; Add one to the width to always have whitespace in column zero.
1665   (setq width (max (1+ width) 2))
1666   (if (and (equal mh-scan-format-file t)
1667            (not (eq mh-cmd-note width)))
1668       (setq mh-cmd-note width))
1669   mh-cmd-note)
1670
1671 (defun mh-regenerate-headers (range &optional update)
1672   "Scan folder over range RANGE.
1673 If UPDATE, append the scan lines, otherwise replace."
1674   (let ((folder mh-current-folder)
1675         (range (if (and range (atom range)) (list range) range))
1676         scan-start)
1677     (message "Scanning %s..." folder)
1678     (mh-remove-all-notation)
1679     (with-mh-folder-updating (nil)
1680       (if update
1681           (goto-char (point-max))
1682         (delete-region (point-min) (point-max))
1683         (if mh-adaptive-cmd-note-flag
1684             (mh-set-cmd-note (mh-message-number-width folder))))
1685       (setq scan-start (point))
1686       (apply #'mh-exec-cmd-output
1687              mh-scan-prog nil
1688              (mh-scan-format)
1689              "-noclear" "-noheader"
1690              "-width" (window-width)
1691              folder range)
1692       (goto-char scan-start)
1693       (cond ((looking-at "scan: no messages in")
1694              (keep-lines mh-scan-valid-regexp)) ; Flush random scan lines
1695             ((looking-at "scan: bad message list ")
1696              (keep-lines mh-scan-valid-regexp))
1697             ((looking-at "scan: "))     ; Keep error messages
1698             (t
1699              (keep-lines mh-scan-valid-regexp))) ; Flush random scan lines
1700       (setq mh-seq-list (mh-read-folder-sequences folder nil))
1701       (mh-notate-user-sequences)
1702       (or update
1703           (setq mh-mode-line-annotation
1704                 (if (equal range '("all"))
1705                     nil
1706                   mh-partial-folder-mode-line-annotation)))
1707       (mh-make-folder-mode-line))
1708     (message "Scanning %s...done" folder)))
1709
1710 (defun mh-generate-new-cmd-note (folder)
1711   "Fix the `mh-cmd-note' value for this FOLDER.
1712
1713 After doing an `mh-get-new-mail' operation in this FOLDER, at least
1714 one line that looks like a truncated message number was found.
1715
1716 Remove the text added by the last `mh-inc' command. It should be the
1717 messages cur-last. Call `mh-set-cmd-note' with the widest message number
1718 in FOLDER.
1719
1720 Reformat the message number width on each line in the buffer and trim
1721 the line length to fit in the window.
1722
1723 Rescan the FOLDER in the range cur-last in order to display the
1724 messages that were removed earlier. They should all fit in the scan
1725 line now with no message truncation."
1726   (save-excursion
1727     (let ((maxcol (1- (window-width)))
1728           (old-cmd-note mh-cmd-note)
1729           mh-cmd-note-fmt
1730           msgnum)
1731       ;; Nuke all of the lines just added by the last inc
1732       (delete-char (- (point-max) (point)))
1733       ;; Update the current buffer to reflect the new mh-cmd-note
1734       ;; value needed to display messages.
1735       (mh-set-cmd-note (mh-message-number-width folder))
1736       (setq mh-cmd-note-fmt (concat "%" (format "%d" mh-cmd-note) "d"))
1737       ;; Cleanup the messages that are in the buffer right now
1738       (goto-char (point-min))
1739       (cond ((memq 'unthread mh-view-ops)
1740              (mh-thread-add-spaces (- mh-cmd-note old-cmd-note)))
1741             (t (while (re-search-forward mh-scan-msg-number-regexp nil 0 1)
1742                  ;; reformat the number to fix in mh-cmd-note columns
1743                  (setq msgnum (string-to-number
1744                                (buffer-substring
1745                                 (match-beginning 1) (match-end 1))))
1746                  (replace-match (format mh-cmd-note-fmt msgnum))
1747                  ;; trim the line to fix in the window
1748                  (end-of-line)
1749                  (let ((eol (point)))
1750                    (move-to-column maxcol)
1751                    (if (<= (point) eol)
1752                        (delete-char (- eol (point))))))))
1753       ;; now re-read the lost messages
1754       (goto-char (point-max))
1755       (prog1 (point)
1756         (mh-regenerate-headers "cur-last" t)))))
1757
1758 (defun mh-get-new-mail (maildrop-name)
1759   "Read new mail from MAILDROP-NAME into the current buffer.
1760 Return in the current buffer."
1761   (let ((point-before-inc (point))
1762         (folder mh-current-folder)
1763         (new-mail-flag nil))
1764     (with-mh-folder-updating (t)
1765       (if maildrop-name
1766           (message "inc %s -file %s..." folder maildrop-name)
1767         (message "inc %s..." folder))
1768       (setq mh-next-direction 'forward)
1769       (goto-char (point-max))
1770       (mh-remove-all-notation)
1771       (let ((start-of-inc (point)))
1772         (if maildrop-name
1773             ;; I think MH 5 used "-ms-file" instead of "-file",
1774             ;; which would make inc'ing from maildrops fail.
1775             (mh-exec-cmd-output mh-inc-prog nil folder
1776                                 (mh-scan-format)
1777                                 "-file" (expand-file-name maildrop-name)
1778                                 "-width" (window-width)
1779                                 "-truncate")
1780           (mh-exec-cmd-output mh-inc-prog nil
1781                               (mh-scan-format)
1782                               "-width" (window-width)))
1783         (if maildrop-name
1784             (message "inc %s -file %s...done" folder maildrop-name)
1785           (message "inc %s...done" folder))
1786         (goto-char start-of-inc)
1787         (cond ((save-excursion
1788                  (re-search-forward "^inc: no mail" nil t))
1789                (message "No new mail%s%s" (if maildrop-name " in " "")
1790                         (if maildrop-name maildrop-name "")))
1791               ((and (when mh-folder-view-stack
1792                       (let ((saved-text (buffer-substring-no-properties
1793                                          start-of-inc (point-max))))
1794                         (delete-region start-of-inc (point-max))
1795                         (unwind-protect (mh-widen t)
1796                           (mh-remove-all-notation)
1797                           (goto-char (point-max))
1798                           (setq start-of-inc (point))
1799                           (insert saved-text)
1800                           (goto-char start-of-inc))))
1801                     nil))
1802               ((re-search-forward "^inc:" nil t) ; Error messages
1803                (error "Error incorporating mail"))
1804               ((and
1805                 (equal mh-scan-format-file t)
1806                 mh-adaptive-cmd-note-flag
1807                 ;; Have we reached an edge condition?
1808                 (save-excursion
1809                   (re-search-forward mh-scan-msg-overflow-regexp nil 0 1))
1810                 (setq start-of-inc (mh-generate-new-cmd-note folder))
1811                 nil))
1812               (t
1813                (setq new-mail-flag t)))
1814         (keep-lines mh-scan-valid-regexp) ; Flush random scan lines
1815         (setq mh-seq-list (mh-read-folder-sequences folder t))
1816         (when (equal (point-max) start-of-inc)
1817           (mh-notate-cur))
1818         (if new-mail-flag
1819             (progn
1820               (mh-make-folder-mode-line)
1821               (when (mh-speed-flists-active-p)
1822                 (mh-speed-flists t mh-current-folder))
1823               (when (memq 'unthread mh-view-ops)
1824                 (mh-thread-inc folder start-of-inc))
1825               (mh-goto-cur-msg))
1826           (goto-char point-before-inc))
1827         (mh-notate-user-sequences)
1828         (mh-notate-deleted-and-refiled)))))
1829
1830 (defun mh-make-folder-mode-line (&optional ignored)
1831   "Set the fields of the mode line for a folder buffer.
1832 The optional argument is now obsolete and IGNORED. It used to be used to pass
1833 in what is now stored in the buffer-local variable `mh-mode-line-annotation'."
1834   (save-excursion
1835     (save-window-excursion
1836       (mh-first-msg)
1837       (let ((new-first-msg-num (mh-get-msg-num nil)))
1838         (when (or (not (memq 'unthread mh-view-ops))
1839                   (null mh-first-msg-num)
1840                   (null new-first-msg-num)
1841                   (< new-first-msg-num mh-first-msg-num))
1842           (setq mh-first-msg-num new-first-msg-num)))
1843       (mh-last-msg)
1844       (let ((new-last-msg-num (mh-get-msg-num nil)))
1845         (when (or (not (memq 'unthread mh-view-ops))
1846                   (null mh-last-msg-num)
1847                   (null new-last-msg-num)
1848                   (> new-last-msg-num mh-last-msg-num))
1849           (setq mh-last-msg-num new-last-msg-num)))
1850       (setq mh-msg-count (if mh-first-msg-num
1851                              (count-lines (point-min) (point-max))
1852                            0))
1853       (setq mode-line-buffer-identification
1854             (list (format "    {%%b%s} %s msg%s"
1855                           (if mh-mode-line-annotation
1856                               (format "/%s" mh-mode-line-annotation)
1857                             "")
1858                           (if (zerop mh-msg-count)
1859                               "no"
1860                             (format "%d" mh-msg-count))
1861                           (if (zerop mh-msg-count)
1862                               "s"
1863                             (cond ((> mh-msg-count 1)
1864                                    (format "s (%d-%d)" mh-first-msg-num
1865                                            mh-last-msg-num))
1866                                   (mh-first-msg-num
1867                                    (format " (%d)" mh-first-msg-num))
1868                                   (""))))))
1869       (mh-logo-display))))
1870
1871 ;;; XXX: Remove this function, if no one uses it any more...
1872 (defun mh-unmark-all-headers (remove-all-flags)
1873   "Remove all '+' flags from the folder listing.
1874 With non-nil argument REMOVE-ALL-FLAGS, remove all 'D', '^' and '%' flags too.
1875 Optimized for speed (i.e., no regular expressions).
1876
1877 This function is deprecated. Use `mh-remove-all-notation' instead."
1878   (save-excursion
1879     (let ((case-fold-search nil)
1880           (last-line (1- (point-max)))
1881           char)
1882       (mh-first-msg)
1883       (while (<= (point) last-line)
1884         (forward-char mh-cmd-note)
1885         (setq char (following-char))
1886         (if (or (and remove-all-flags
1887                      (or (= char (aref mh-note-deleted 0))
1888                          (= char (aref mh-note-refiled 0))))
1889                 (= char (aref mh-note-cur 0)))
1890             (progn
1891               (delete-char 1)
1892               (insert " ")))
1893         (if remove-all-flags
1894             (progn
1895               (forward-char 1)
1896               (if (= (following-char) (aref mh-note-seq 0))
1897                   (progn
1898                     (delete-char 1)
1899                     (insert " ")))))
1900         (forward-line)))))
1901
1902 (defun mh-add-sequence-notation (msg internal-seq-flag)
1903   "Add sequence notation to the MSG on the current line.
1904 If INTERNAL-SEQ-FLAG is non-nil, then just remove text properties from the
1905 current line, so that font-lock would automatically refontify it."
1906   (with-mh-folder-updating (t)
1907     (save-excursion
1908       (beginning-of-line)
1909       (if internal-seq-flag
1910           (mh-notate nil nil mh-cmd-note)
1911         (forward-char (1+ mh-cmd-note))
1912         (let ((stack (gethash msg mh-sequence-notation-history)))
1913           (setf (gethash msg mh-sequence-notation-history)
1914                 (cons (char-after) stack)))
1915         (mh-notate nil mh-note-seq (1+ mh-cmd-note))))))
1916
1917 (defun mh-remove-sequence-notation (msg internal-seq-flag &optional all)
1918   "Remove sequence notation from the MSG on the current line.
1919 If INTERNAL-SEQ-FLAG is non-nil, then `font-lock' was used to highlight the
1920 sequence. In that case, no notation needs to be removed. Otherwise the effect
1921 of inserting `mh-note-seq' needs to be reversed.
1922 If ALL is non-nil, then all sequence marks on the scan line are removed."
1923   (with-mh-folder-updating (t)
1924     ;; This takes care of internal sequences...
1925     (mh-notate nil nil mh-cmd-note)
1926     (unless internal-seq-flag
1927       ;; ... and this takes care of user sequences.
1928       (let ((stack (gethash msg mh-sequence-notation-history)))
1929         (while (and all (cdr stack))
1930           (setq stack (cdr stack)))
1931         (when stack
1932           (mh-notate nil (car stack) (1+ mh-cmd-note)))
1933         (setf (gethash msg mh-sequence-notation-history) (cdr stack))))))
1934
1935 (defun mh-remove-cur-notation ()
1936   "Remove old cur notation."
1937   (let ((cur-msg (car (mh-seq-to-msgs 'cur))))
1938     (save-excursion
1939       (when (and cur-msg
1940                  (mh-goto-msg cur-msg t t)
1941                  (looking-at mh-scan-cur-msg-number-regexp))
1942         (mh-notate nil ?  mh-cmd-note)
1943         (setq overlay-arrow-position nil)))))
1944
1945 (defun mh-remove-all-notation ()
1946   "Remove all notations on all scan lines that MH-E introduces."
1947   (save-excursion
1948     (setq overlay-arrow-position nil)
1949     (goto-char (point-min))
1950     (mh-iterate-on-range msg (cons (point-min) (point-max))
1951       (mh-notate nil ?  mh-cmd-note)
1952       (mh-remove-sequence-notation msg nil t))
1953     (clrhash mh-sequence-notation-history)))
1954
1955 ;;;###mh-autoload
1956 (defun mh-goto-cur-msg (&optional minimal-changes-flag)
1957   "Position the cursor at the current message.
1958 When optional argument MINIMAL-CHANGES-FLAG is non-nil, the function doesn't
1959 recenter the folder buffer."
1960   (let ((cur-msg (car (mh-seq-to-msgs 'cur))))
1961     (cond ((and cur-msg
1962                 (mh-goto-msg cur-msg t t))
1963            (unless minimal-changes-flag
1964              (mh-notate-cur)
1965              (mh-recenter 0)
1966              (mh-maybe-show cur-msg)))
1967           (t
1968            (setq overlay-arrow-position nil)
1969            (message "No current message")))))
1970
1971 (defun mh-process-or-undo-commands (folder)
1972   "If FOLDER has outstanding commands, then either process or discard them.
1973 Called by functions like `mh-sort-folder', so also invalidate show buffer."
1974   (set-buffer folder)
1975   (if (mh-outstanding-commands-p)
1976       (if (or mh-do-not-confirm-flag
1977               (y-or-n-p
1978                "Process outstanding deletes and refiles? "))
1979           (mh-process-commands folder)
1980         (set-buffer folder)
1981         (mh-undo-folder)))
1982   (mh-update-unseen)
1983   (mh-invalidate-show-buffer))
1984
1985 (defun mh-process-commands (folder)
1986   "Process outstanding commands for FOLDER.
1987 The value of `mh-folder-updated-hook' is a list of functions to be called,
1988 with no arguments, before the commands are processed."
1989   (message "Processing deletes and refiles for %s..." folder)
1990   (set-buffer folder)
1991   (with-mh-folder-updating (nil)
1992     ;; Run the hook while the lists are still valid
1993     (run-hooks 'mh-folder-updated-hook)
1994
1995     ;; Update the unseen sequence if it exists
1996     (mh-update-unseen)
1997
1998     (let ((redraw-needed-flag mh-index-data)
1999           (folders-changed (list mh-current-folder))
2000           (seq-map (and mh-refile-list mh-refile-preserves-sequences-flag
2001                         (mh-create-sequence-map mh-seq-list)))
2002           (dest-map (and mh-refile-list mh-refile-preserves-sequences-flag
2003                          (make-hash-table))))
2004       ;; Remove invalid scan lines if we are in an index folder and then remove
2005       ;; the real messages
2006       (when mh-index-data
2007         (mh-index-delete-folder-headers)
2008         (setq folders-changed
2009               (append folders-changed (mh-index-execute-commands))))
2010
2011       ;; Then refile messages
2012       (mh-mapc #'(lambda (folder-msg-list)
2013                    (let* ((dest-folder (symbol-name (car folder-msg-list)))
2014                           (last (car (mh-translate-range dest-folder "last")))
2015                           (msgs (cdr folder-msg-list)))
2016                      (push dest-folder folders-changed)
2017                      (setq redraw-needed-flag t)
2018                      (apply #'mh-exec-cmd
2019                             "refile" "-src" folder dest-folder
2020                             (mh-coalesce-msg-list msgs))
2021                      (mh-delete-scan-msgs msgs)
2022                      ;; Preserve sequences in destination folder...
2023                      (when (and mh-refile-preserves-sequences-flag
2024                                 (numberp last))
2025                        (clrhash dest-map)
2026                        (loop for i from (1+ last)
2027                              for msg in (sort (copy-sequence msgs) #'<)
2028                              do (loop for seq-name in (gethash msg seq-map)
2029                                       do (push i (gethash seq-name dest-map))))
2030                        (maphash
2031                         #'(lambda (seq msgs)
2032                             ;; Run it in the background, since we don't care
2033                             ;; about the results.
2034                             (apply #'mh-exec-cmd-daemon "mark" #'ignore
2035                                    "-sequence" (symbol-name seq) dest-folder
2036                                    "-add" (mapcar #'(lambda (x) (format "%s" x))
2037                                                   (mh-coalesce-msg-list msgs))))
2038                         dest-map))))
2039                mh-refile-list)
2040       (setq mh-refile-list ())
2041
2042       ;; Now delete messages
2043       (cond (mh-delete-list
2044              (setq redraw-needed-flag t)
2045              (apply 'mh-exec-cmd "rmm" folder
2046                     (mh-coalesce-msg-list mh-delete-list))
2047              (mh-delete-scan-msgs mh-delete-list)
2048              (setq mh-delete-list nil)))
2049
2050       ;; Don't need to remove sequences since delete and refile do so.
2051       ;; Mark cur message
2052       (if (> (buffer-size) 0)
2053           (mh-define-sequence 'cur (list (or (mh-get-msg-num nil) "last"))))
2054
2055       ;; Redraw folder buffer if needed
2056       (when (and redraw-needed-flag)
2057         (when (mh-speed-flists-active-p)
2058           (apply #'mh-speed-flists t folders-changed))
2059         (cond ((memq 'unthread mh-view-ops) (mh-thread-inc folder (point-max)))
2060               (mh-index-data (mh-index-insert-folder-headers)))))
2061
2062     (and (buffer-file-name (get-buffer mh-show-buffer))
2063          (not (file-exists-p (buffer-file-name (get-buffer mh-show-buffer))))
2064          ;; If "inc" were to put a new msg in this file,
2065          ;; we would not notice, so mark it invalid now.
2066          (mh-invalidate-show-buffer))
2067
2068     (setq mh-seq-list (mh-read-folder-sequences mh-current-folder nil))
2069     (mh-remove-all-notation)
2070     (mh-notate-user-sequences)
2071     (message "Processing deletes and refiles for %s...done" folder)))
2072
2073 (defun mh-update-unseen ()
2074   "Synchronize the unseen sequence with MH.
2075 Return non-nil iff the MH folder was set.
2076 The value of `mh-unseen-updated-hook' is a list of functions to be called,
2077 with no arguments, after the unseen sequence is updated."
2078   (if mh-seen-list
2079       (let* ((unseen-seq (mh-find-seq mh-unseen-seq))
2080              (unseen-msgs (mh-seq-msgs unseen-seq)))
2081         (if unseen-msgs
2082             (progn
2083               (mh-undefine-sequence mh-unseen-seq mh-seen-list)
2084               (run-hooks 'mh-unseen-updated-hook)
2085               (while mh-seen-list
2086                 (setq unseen-msgs (delq (car mh-seen-list) unseen-msgs))
2087                 (setq mh-seen-list (cdr mh-seen-list)))
2088               (setcdr unseen-seq unseen-msgs)
2089               t)                        ;since we set the folder
2090           (setq mh-seen-list nil)))))
2091
2092 (defun mh-delete-scan-msgs (msgs)
2093   "Delete the scan listing lines for MSGS."
2094   (save-excursion
2095     (while msgs
2096       (when (mh-goto-msg (car msgs) t t)
2097         (when (memq 'unthread mh-view-ops)
2098           (mh-thread-forget-message (car msgs)))
2099         (mh-delete-line 1))
2100       (setq msgs (cdr msgs)))))
2101
2102 (defun mh-outstanding-commands-p ()
2103   "Return non-nil if there are outstanding deletes or refiles."
2104   (or mh-delete-list mh-refile-list))
2105
2106 (defun mh-coalesce-msg-list (messages)
2107   "Given a list of MESSAGES, return a list of message number ranges.
2108 This is the inverse of `mh-read-msg-list', which expands ranges.
2109 Message lists passed to MH programs should be processed by this function
2110 to avoid exceeding system command line argument limits."
2111   (let ((msgs (sort (copy-sequence messages) 'mh-greaterp))
2112         (range-high nil)
2113         (prev -1)
2114         (ranges nil))
2115     (while prev
2116       (if range-high
2117           (if (or (not (numberp prev))
2118                   (not (equal (car msgs) (1- prev))))
2119               (progn                    ;non-sequential, flush old range
2120                 (if (eq prev range-high)
2121                     (setq ranges (cons range-high ranges))
2122                   (setq ranges (cons (format "%s-%s" prev range-high) ranges)))
2123                 (setq range-high nil))))
2124       (or range-high
2125           (setq range-high (car msgs))) ;start new or first range
2126       (setq prev (car msgs))
2127       (setq msgs (cdr msgs)))
2128     ranges))
2129
2130 (defun mh-greaterp (msg1 msg2)
2131   "Return the greater of two message indicators MSG1 and MSG2.
2132 Strings are \"smaller\" than numbers.
2133 Legal values are things like \"cur\", \"last\", 1, and 1820."
2134   (if (numberp msg1)
2135       (if (numberp msg2)
2136           (> msg1 msg2)
2137         t)
2138     (if (numberp msg2)
2139         nil
2140       (string-lessp msg2 msg1))))
2141
2142 (defun mh-lessp (msg1 msg2)
2143   "Return the lesser of two message indicators MSG1 and MSG2.
2144 Strings are \"smaller\" than numbers.
2145 Legal values are things like \"cur\", \"last\", 1, and 1820."
2146   (not (mh-greaterp msg1 msg2)))
2147
2148 \f
2149
2150 ;;; Basic sequence handling
2151
2152 (defun mh-delete-seq-locally (seq)
2153   "Remove MH-E's record of SEQ."
2154   (let ((entry (mh-find-seq seq)))
2155     (setq mh-seq-list (delq entry mh-seq-list))))
2156
2157 (defun mh-read-folder-sequences (folder save-refiles)
2158   "Read and return the predefined sequences for a FOLDER.
2159 If SAVE-REFILES is non-nil, then keep the sequences
2160 that note messages to be refiled."
2161   (let ((seqs ()))
2162     (cond (save-refiles
2163            (mh-mapc (function (lambda (seq) ; Save the refiling sequences
2164                                 (if (mh-folder-name-p (mh-seq-name seq))
2165                                     (setq seqs (cons seq seqs)))))
2166                     mh-seq-list)))
2167     (save-excursion
2168       (if (eq 0 (mh-exec-cmd-quiet nil "mark" folder "-list"))
2169           (progn
2170             ;; look for name in line of form "cur: 4" or "myseq (private): 23"
2171             (while (re-search-forward "^[^: ]+" nil t)
2172               (setq seqs (cons (mh-make-seq (intern (buffer-substring
2173                                                      (match-beginning 0)
2174                                                      (match-end 0)))
2175                                             (mh-read-msg-list))
2176                                seqs)))
2177             (delete-region (point-min) (point))))) ; avoid race with
2178                                         ; mh-process-daemon
2179     seqs))
2180
2181 (defun mh-read-msg-list ()
2182   "Return a list of message numbers from point to the end of the line.
2183 Expands ranges into set of individual numbers."
2184   (let ((msgs ())
2185         (end-of-line (save-excursion (end-of-line) (point)))
2186         num)
2187     (while (re-search-forward "[0-9]+" end-of-line t)
2188       (setq num (string-to-int (buffer-substring (match-beginning 0)
2189                                                  (match-end 0))))
2190       (cond ((looking-at "-")           ; Message range
2191              (forward-char 1)
2192              (re-search-forward "[0-9]+" end-of-line t)
2193              (let ((num2 (string-to-int (buffer-substring (match-beginning 0)
2194                                                           (match-end 0)))))
2195                (if (< num2 num)
2196                    (error "Bad message range: %d-%d" num num2))
2197                (while (<= num num2)
2198                  (setq msgs (cons num msgs))
2199                  (setq num (1+ num)))))
2200             ((not (zerop num))          ;"pick" outputs "0" to mean no match
2201              (setq msgs (cons num msgs)))))
2202     msgs))
2203
2204 (defun mh-notate-user-sequences (&optional range)
2205   "Mark user-defined sequences in the messages specified by RANGE.
2206 The optional argument RANGE can be a message number, a list of message
2207 numbers, a sequence, a region in a cons cell. If nil all messages are notated."
2208   (unless range
2209     (setq range (cons (point-min) (point-max))))
2210   (let ((seqs mh-seq-list)
2211         (msg-hash (make-hash-table)))
2212     (dolist (seq seqs)
2213       (dolist (msg (mh-seq-msgs seq))
2214         (push (car seq) (gethash msg msg-hash))))
2215     (mh-iterate-on-range msg range
2216       (loop for seq in (gethash msg msg-hash)
2217             do (mh-add-sequence-notation msg (mh-internal-seq seq))))))
2218
2219 (defvar mh-internal-seqs '(answered cur deleted forwarded printed))
2220
2221 (defun mh-internal-seq (name)
2222   "Return non-nil if NAME is the name of an internal MH-E sequence."
2223   (or (memq name mh-internal-seqs)
2224       (eq name mh-unseen-seq)
2225       (and mh-tick-seq (eq name mh-tick-seq))
2226       (eq name mh-previous-seq)
2227       (mh-folder-name-p name)))
2228
2229 (defun mh-valid-seq-p (name)
2230   "Return non-nil if NAME is a valid MH sequence name."
2231   (and (symbolp name)
2232        (string-match "^[a-zA-Z][a-zA-Z0-9]*$" (symbol-name name))))
2233
2234 (defun mh-delete-msg-from-seq (range sequence &optional internal-flag)
2235   "Delete RANGE from SEQUENCE.
2236
2237 Check the documentation of `mh-interactive-range' to see how RANGE is read in
2238 interactive use.
2239
2240 Optional third arg INTERNAL-FLAG non-nil means do not inform MH of the
2241 change."
2242   (interactive (list (mh-interactive-range "Delete")
2243                      (mh-read-seq-default "Delete from" t)
2244                      nil))
2245   (let ((entry (mh-find-seq sequence))
2246         (user-sequence-flag (not (mh-internal-seq sequence)))
2247         (folders-changed (list mh-current-folder))
2248         (msg-list ()))
2249     (when entry
2250       (mh-iterate-on-range msg range
2251         (push msg msg-list)
2252         ;; Calling "mark" repeatedly takes too long. So we will pretend here
2253         ;; that we are just modifying an internal sequence...
2254         (when (memq msg (cdr entry))
2255           (mh-remove-sequence-notation msg (not user-sequence-flag)))
2256         (mh-delete-a-msg-from-seq msg sequence t))
2257       ;; ... and here we will "mark" all the messages at one go.
2258       (unless internal-flag (mh-undefine-sequence sequence msg-list))
2259       (when (and mh-index-data (not internal-flag))
2260         (setq folders-changed
2261               (append folders-changed
2262                       (mh-index-delete-from-sequence sequence msg-list))))
2263       (when (and (eq sequence mh-unseen-seq) (mh-speed-flists-active-p))
2264         (apply #'mh-speed-flists t folders-changed)))))
2265
2266 (defun mh-delete-a-msg-from-seq (msg sequence internal-flag)
2267   "Delete MSG from SEQUENCE.
2268 If INTERNAL-FLAG is non-nil, then do not inform MH of the change."
2269   (let ((entry (mh-find-seq sequence)))
2270     (when (and entry (memq msg (mh-seq-msgs entry)))
2271       (if (not internal-flag)
2272           (mh-undefine-sequence sequence (list msg)))
2273       (setcdr entry (delq msg (mh-seq-msgs entry))))))
2274
2275 (defun mh-undefine-sequence (seq msgs)
2276   "Remove from the SEQ the list of MSGS."
2277   (when (and (mh-valid-seq-p seq) msgs)
2278     (apply #'mh-exec-cmd "mark" mh-current-folder "-delete"
2279            "-sequence" (symbol-name seq) (mh-coalesce-msg-list msgs))))
2280
2281 (defun mh-define-sequence (seq msgs)
2282   "Define the SEQ to contain the list of MSGS.
2283 Do not mark pseudo-sequences or empty sequences.
2284 Signals an error if SEQ is an illegal name."
2285   (if (and msgs
2286            (mh-valid-seq-p seq)
2287            (not (mh-folder-name-p seq)))
2288       (save-excursion
2289         (mh-exec-cmd-error nil "mark" mh-current-folder "-add" "-zero"
2290                            "-sequence" (symbol-name seq)
2291                            (mh-coalesce-msg-list msgs)))))
2292
2293 (defun mh-map-over-seqs (function seq-list)
2294   "Apply FUNCTION to each sequence in SEQ-LIST.
2295 The sequence name and the list of messages are passed as arguments."
2296   (while seq-list
2297     (funcall function
2298              (mh-seq-name (car seq-list))
2299              (mh-seq-msgs (car seq-list)))
2300     (setq seq-list (cdr seq-list))))
2301
2302 (defun mh-notate-if-in-one-seq (msg character offset seq)
2303   "Notate MSG.
2304 The CHARACTER is placed at the given OFFSET from the beginning of the listing.
2305 The notation is performed if the MSG is only in SEQ."
2306   (let ((in-seqs (mh-seq-containing-msg msg nil)))
2307     (if (and (eq seq (car in-seqs)) (null (cdr in-seqs)))
2308         (mh-notate msg character offset))))
2309
2310 (defun mh-seq-containing-msg (msg &optional include-internal-flag)
2311   "Return a list of the sequences containing MSG.
2312 If INCLUDE-INTERNAL-FLAG non-nil, include MH-E internal sequences in list."
2313   (let ((l mh-seq-list)
2314         (seqs ()))
2315     (while l
2316       (and (memq msg (mh-seq-msgs (car l)))
2317            (or include-internal-flag
2318                (not (mh-internal-seq (mh-seq-name (car l)))))
2319            (setq seqs (cons (mh-seq-name (car l)) seqs)))
2320       (setq l (cdr l)))
2321     seqs))
2322
2323 \f
2324
2325 ;;; Build the folder-mode keymap:
2326
2327 (suppress-keymap mh-folder-mode-map)
2328
2329 ;; Use defalias to make sure the documented primary key bindings
2330 ;; appear in menu lists.
2331 (defalias 'mh-alt-show 'mh-show)
2332 (defalias 'mh-alt-refile-msg 'mh-refile-msg)
2333 (defalias 'mh-alt-send 'mh-send)
2334 (defalias 'mh-alt-visit-folder 'mh-visit-folder)
2335
2336 ;; Save the `b' binding for a future `back'. Maybe?
2337 (gnus-define-keys  mh-folder-mode-map
2338   " "           mh-page-msg
2339   "!"           mh-refile-or-write-again
2340   "'"           mh-toggle-tick
2341   ","           mh-header-display
2342   "."           mh-alt-show
2343   ">"           mh-write-msg-to-file
2344   "?"           mh-help
2345   "E"           mh-extract-rejected-mail
2346   "M"           mh-modify
2347   "\177"        mh-previous-page
2348   "\C-d"        mh-delete-msg-no-motion
2349   "\t"          mh-index-next-folder
2350   [backtab]     mh-index-previous-folder
2351   "\M-\t"       mh-index-previous-folder
2352   "\e<"         mh-first-msg
2353   "\e>"         mh-last-msg
2354   "\ed"         mh-redistribute
2355   "\r"          mh-show
2356   "^"           mh-alt-refile-msg
2357   "c"           mh-copy-msg
2358   "d"           mh-delete-msg
2359   "e"           mh-edit-again
2360   "f"           mh-forward
2361   "g"           mh-goto-msg
2362   "i"           mh-inc-folder
2363   "k"           mh-delete-subject-or-thread
2364   "l"           mh-print-msg
2365   "m"           mh-alt-send
2366   "n"           mh-next-undeleted-msg
2367   "\M-n"        mh-next-unread-msg
2368   "o"           mh-refile-msg
2369   "p"           mh-previous-undeleted-msg
2370   "\M-p"        mh-previous-unread-msg
2371   "q"           mh-quit
2372   "r"           mh-reply
2373   "s"           mh-send
2374   "t"           mh-toggle-showing
2375   "u"           mh-undo
2376   "v"           mh-index-visit-folder
2377   "x"           mh-execute-commands
2378   "|"           mh-pipe-msg)
2379
2380 (gnus-define-keys (mh-folder-map "F" mh-folder-mode-map)
2381   "?"           mh-prefix-help
2382   "'"           mh-index-ticked-messages
2383   "S"           mh-sort-folder
2384   "f"           mh-alt-visit-folder
2385   "i"           mh-index-search
2386   "k"           mh-kill-folder
2387   "l"           mh-list-folders
2388   "n"           mh-index-new-messages
2389   "o"           mh-alt-visit-folder
2390   "p"           mh-pack-folder
2391   "q"           mh-index-sequenced-messages
2392   "r"           mh-rescan-folder
2393   "s"           mh-search-folder
2394   "u"           mh-undo-folder
2395   "v"           mh-visit-folder)
2396
2397 (define-key mh-folder-mode-map "I" mh-inc-spool-map)
2398
2399 (gnus-define-keys (mh-junk-map "J" mh-folder-mode-map)
2400   "?"           mh-prefix-help
2401   "b"           mh-junk-blacklist
2402   "w"           mh-junk-whitelist)
2403
2404 (gnus-define-keys (mh-sequence-map "S" mh-folder-mode-map)
2405   "'"           mh-narrow-to-tick
2406   "?"           mh-prefix-help
2407   "d"           mh-delete-msg-from-seq
2408   "k"           mh-delete-seq
2409   "l"           mh-list-sequences
2410   "n"           mh-narrow-to-seq
2411   "p"           mh-put-msg-in-seq
2412   "s"           mh-msg-is-in-seq
2413   "w"           mh-widen)
2414
2415 (gnus-define-keys (mh-thread-map "T" mh-folder-mode-map)
2416   "?"           mh-prefix-help
2417   "u"           mh-thread-ancestor
2418   "p"           mh-thread-previous-sibling
2419   "n"           mh-thread-next-sibling
2420   "t"           mh-toggle-threads
2421   "d"           mh-thread-delete
2422   "o"           mh-thread-refile)
2423
2424 (gnus-define-keys (mh-limit-map "/" mh-folder-mode-map)
2425   "'"           mh-narrow-to-tick
2426   "?"           mh-prefix-help
2427   "c"           mh-narrow-to-cc
2428   "f"           mh-narrow-to-from
2429   "r"           mh-narrow-to-range
2430   "s"           mh-narrow-to-subject
2431   "t"           mh-narrow-to-to
2432   "w"           mh-widen)
2433
2434 (gnus-define-keys (mh-extract-map "X" mh-folder-mode-map)
2435   "?"           mh-prefix-help
2436   "s"           mh-store-msg            ;shar
2437   "u"           mh-store-msg)           ;uuencode
2438
2439 (gnus-define-keys (mh-digest-map "D" mh-folder-mode-map)
2440   " "           mh-page-digest
2441   "?"           mh-prefix-help
2442   "\177"        mh-page-digest-backwards
2443   "b"           mh-burst-digest)
2444
2445 (gnus-define-keys (mh-mime-map "K" mh-folder-mode-map)
2446   "?"           mh-prefix-help
2447   "a"           mh-mime-save-parts
2448   "i"           mh-folder-inline-mime-part
2449   "o"           mh-folder-save-mime-part
2450   "v"           mh-folder-toggle-mime-part
2451   "\t"          mh-next-button
2452   [backtab]     mh-prev-button
2453   "\M-\t"       mh-prev-button)
2454
2455 (cond
2456  (mh-xemacs-flag
2457   (define-key mh-folder-mode-map [button2] 'mh-show-mouse))
2458  (t
2459   (define-key mh-folder-mode-map [mouse-2] 'mh-show-mouse)))
2460
2461 ;; "C-c /" prefix is used in mh-folder-mode by pgp.el and mailcrypt
2462
2463 \f
2464
2465 ;;; Help Messages
2466
2467 ;;; If you add a new prefix, add appropriate text to the nil key.
2468 ;;;
2469 ;;; In general, messages are grouped logically. Taking the main commands for
2470 ;;; example, the first line is "ways to view messages," the second line is
2471 ;;; "things you can do with messages", and the third is "composing" messages.
2472 ;;;
2473 ;;; When adding a new prefix, ensure that the help message contains "what" the
2474 ;;; prefix is for. For example, if the word "folder" were not present in the
2475 ;;; `F' entry, it would not be clear what these commands operated upon.
2476 (defvar mh-help-messages
2477   '((nil "[i]nc, [.]show, [,]show all, [n]ext, [p]revious,\n"
2478          "[d]elete, [o]refile, e[x]ecute,\n"
2479          "[s]end, [r]eply.\n"
2480          "Prefix characters:\n [F]older, [S]equence, [J]unk, MIME [K]eys,"
2481          "\n [T]hread, [/]limit, e[X]tract, [D]igest, [I]nc spools.")
2482
2483     (?F "[l]ist; [v]isit folder;\n"
2484         "[n]ew messages; [']ticked messages; [s]earch; [i]ndexed search;\n"
2485         "[p]ack; [S]ort; [r]escan; [k]ill")
2486     (?S "[p]ut message in sequence, [n]arrow, [']narrow to ticked, [w]iden,\n"
2487         "[s]equences, [l]ist,\n"
2488         "[d]elete message from sequence, [k]ill sequence")
2489     (?T "[t]oggle, [d]elete, [o]refile thread")
2490     (?/ "Limit to [c]c, [f]rom, [r]ange, [s]ubject, [t]o; [w]iden")
2491     (?X "un[s]har, [u]udecode message")
2492     (?D "[b]urst digest")
2493     (?K "[v]iew, [i]nline, [o]utput/save MIME part; save [a]ll parts; \n"
2494         "[TAB] next; [SHIFT-TAB] previous")
2495     (?J "[b]lacklist, [w]hitelist message"))
2496   "Key binding cheat sheet.
2497
2498 This is an associative array which is used to show the most common commands.
2499 The key is a prefix char. The value is one or more strings which are
2500 concatenated together and displayed in the minibuffer if ? is pressed after
2501 the prefix character. The special key nil is used to display the
2502 non-prefixed commands.
2503
2504 The substitutions described in `substitute-command-keys' are performed as
2505 well.")
2506
2507 \f
2508
2509 (dolist (mess '("^Cursor not pointing to message$"
2510                 "^There is no other window$"))
2511   (add-to-list 'debug-ignored-errors mess))
2512
2513 ;;; Local Variables:
2514 ;;; indent-tabs-mode: nil
2515 ;;; sentence-end-double-space: nil
2516 ;;; End:
2517
2518 ;;; mh-e.el ends here