]> code.delx.au - gnu-emacs/blob - lisp/mh-e/mh-utils.el
* mh-comp.el (mh-annotate-msg): Use new variable
[gnu-emacs] / lisp / mh-e / mh-utils.el
1 ;;; mh-utils.el --- MH-E code needed for both sending and reading
2
3 ;; Copyright (C) 1993, 1995, 1997,
4 ;; 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
5
6 ;; Author: Bill Wohler <wohler@newt.com>
7 ;; Maintainer: Bill Wohler <wohler@newt.com>
8 ;; Keywords: mail
9 ;; See: mh-e.el
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., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Commentary:
29
30 ;; Internal support for MH-E package.
31
32 ;;; Change Log:
33
34 ;;; Code:
35
36 (defvar recursive-load-depth-limit)
37 (eval-and-compile
38 (if (and (boundp 'recursive-load-depth-limit)
39 (integerp recursive-load-depth-limit)
40 (> 50 recursive-load-depth-limit))
41 (setq recursive-load-depth-limit 50)))
42
43 (eval-when-compile (require 'mh-acros))
44 (mh-require-cl)
45 (require 'gnus-util)
46 (require 'font-lock)
47 (require 'mouse)
48 (load "tool-bar" t t)
49 (require 'mh-loaddefs)
50 (require 'mh-customize)
51 (require 'mh-inc)
52
53 (load "mm-decode" t t) ; Non-fatal dependency
54 (load "mm-view" t t) ; Non-fatal dependency
55 (load "vcard" t t) ; Non-fatal dependency
56 (load "hl-line" t t) ; Non-fatal dependency
57 (load "executable" t t) ; Non-fatal dependency on
58 ; executable-find
59
60 ;; Shush the byte-compiler
61 (defvar font-lock-auto-fontify)
62 (defvar font-lock-defaults)
63 (defvar mark-active)
64
65 ;;; Autoloads
66 (autoload 'gnus-article-highlight-citation "gnus-cite")
67 (autoload 'message-fetch-field "message")
68 (autoload 'message-tokenize-header "message")
69 (require 'sendmail)
70 (unless (fboundp 'make-hash-table)
71 (autoload 'make-hash-table "cl"))
72
73 ;;; CL Replacements
74 (defun mh-search-from-end (char string)
75 "Return the position of last occurrence of CHAR in STRING.
76 If CHAR is not present in STRING then return nil. The function is used in lieu
77 of `search' in the CL package."
78 (loop for index from (1- (length string)) downto 0
79 when (equal (aref string index) char) return index
80 finally return nil))
81
82 ;;; Additional header fields that might someday be added:
83 ;;; "Sender: " "Reply-to: "
84
85 \f
86 ;;; Scan Line Formats
87
88 (defvar mh-scan-msg-number-regexp "^ *\\([0-9]+\\)"
89 "This regular expression extracts the message number.
90 It must match from the beginning of the line. Note that the message number
91 must be placed in a parenthesized expression as in the default of
92 \"^ *\\\\([0-9]+\\\\)\".")
93
94 (defvar mh-scan-msg-overflow-regexp "^[?0-9][0-9]"
95 "This regular expression matches overflowed message numbers.")
96
97 (defvar mh-scan-msg-format-regexp "%\\([0-9]*\\)(msg)"
98 "This regular expression finds the message number width in a scan format.
99 Note that the message number must be placed in a parenthesized expression as
100 in the default of \"%\\\\([0-9]*\\\\)(msg)\". This variable is only consulted
101 if `mh-scan-format-file' is set to \"Use MH-E scan Format\".")
102
103 (defvar mh-scan-msg-format-string "%d"
104 "This is a format string for width of the message number in a scan format.
105 Use `0%d' for zero-filled message numbers. This variable is only consulted if
106 `mh-scan-format-file' is set to \"Use MH-E scan Format\".")
107
108 (defvar mh-scan-msg-search-regexp "^[^0-9]*%d[^0-9]"
109 "This regular expression matches a particular message.
110 It is a format string; use `%d' to represent the location of the message
111 number within the expression as in the default of \"^[^0-9]*%d[^0-9]\".")
112
113 (defvar mh-cmd-note 4
114 "Column for notations.
115 This variable should be set with the function `mh-set-cmd-note'. This variable
116 may be updated dynamically if `mh-adaptive-cmd-note-flag' is on.
117
118 Note that columns in Emacs start with 0.")
119 (make-variable-buffer-local 'mh-cmd-note)
120
121 (defvar mh-note-seq ?%
122 "Messages in a user-defined sequence are marked by this character.
123 Messages in the `search' sequence are marked by this character as well.")
124
125 \f
126
127 (defvar mh-show-buffer-mode-line-buffer-id " {show-%s} %d"
128 "Format string to produce `mode-line-buffer-identification' for show buffers.
129 First argument is folder name. Second is message number.")
130
131 \f
132
133 (defvar mh-mail-header-separator "--------"
134 "*Line used by MH to separate headers from text in messages being composed.
135 This variable should not be used directly in programs. Programs should use
136 `mail-header-separator' instead. `mail-header-separator' is initialized to
137 `mh-mail-header-separator' in `mh-letter-mode'; in other contexts, you may
138 have to perform this initialization yourself.
139
140 Do not make this a regular expression as it may be the argument to `insert'
141 and it is passed through `regexp-quote' before being used by functions like
142 `re-search-forward'.")
143
144 (defvar mh-signature-separator-regexp "^-- $"
145 "This regular expression matches the signature separator.
146 See `mh-signature-separator'.")
147
148 (defvar mh-signature-separator "-- \n"
149 "Text of a signature separator.
150 A signature separator is used to separate the body of a message from the
151 signature. This can be used by user agents such as MH-E to render the
152 signature differently or to suppress the inclusion of the signature in a
153 reply.
154 Use `mh-signature-separator-regexp' when searching for a separator.")
155
156 (defun mh-signature-separator-p ()
157 "Return non-nil if buffer includes \"^-- $\"."
158 (save-excursion
159 (goto-char (point-min))
160 (re-search-forward mh-signature-separator-regexp nil t)))
161
162 ;; Variables for MIME display
163
164 ;; Structure to keep track of MIME handles on a per buffer basis.
165 (mh-defstruct (mh-buffer-data (:conc-name mh-mime-)
166 (:constructor mh-make-buffer-data))
167 (handles ()) ; List of MIME handles
168 (handles-cache (make-hash-table)) ; Cache to avoid multiple decodes of
169 ; nested messages
170 (parts-count 0) ; The button number is generated from
171 ; this number
172 (part-index-hash (make-hash-table))) ; Avoid incrementing the part number
173 ; for nested messages
174 ;;; This has to be a macro, since we do: (setf (mh-buffer-data) ...)
175 (defmacro mh-buffer-data ()
176 "Convenience macro to get the MIME data structures of the current buffer."
177 `(gethash (current-buffer) mh-globals-hash))
178
179 (defvar mh-globals-hash (make-hash-table)
180 "Keeps track of MIME data on a per buffer basis.")
181
182 (defvar mh-pgp-support-flag (not (not (locate-library "mml2015")))
183 "Non-nil means PGP support is available.")
184
185 (defvar mh-mm-inline-media-tests
186 `(("image/jpeg"
187 mm-inline-image
188 (lambda (handle)
189 (mm-valid-and-fit-image-p 'jpeg handle)))
190 ("image/png"
191 mm-inline-image
192 (lambda (handle)
193 (mm-valid-and-fit-image-p 'png handle)))
194 ("image/gif"
195 mm-inline-image
196 (lambda (handle)
197 (mm-valid-and-fit-image-p 'gif handle)))
198 ("image/tiff"
199 mm-inline-image
200 (lambda (handle)
201 (mm-valid-and-fit-image-p 'tiff handle)) )
202 ("image/xbm"
203 mm-inline-image
204 (lambda (handle)
205 (mm-valid-and-fit-image-p 'xbm handle)))
206 ("image/x-xbitmap"
207 mm-inline-image
208 (lambda (handle)
209 (mm-valid-and-fit-image-p 'xbm handle)))
210 ("image/xpm"
211 mm-inline-image
212 (lambda (handle)
213 (mm-valid-and-fit-image-p 'xpm handle)))
214 ("image/x-pixmap"
215 mm-inline-image
216 (lambda (handle)
217 (mm-valid-and-fit-image-p 'xpm handle)))
218 ("image/bmp"
219 mm-inline-image
220 (lambda (handle)
221 (mm-valid-and-fit-image-p 'bmp handle)))
222 ("image/x-portable-bitmap"
223 mm-inline-image
224 (lambda (handle)
225 (mm-valid-and-fit-image-p 'pbm handle)))
226 ("text/plain" mm-inline-text identity)
227 ("text/enriched" mm-inline-text identity)
228 ("text/richtext" mm-inline-text identity)
229 ("text/x-patch" mm-display-patch-inline
230 (lambda (handle)
231 (locate-library "diff-mode")))
232 ("application/emacs-lisp" mm-display-elisp-inline identity)
233 ("application/x-emacs-lisp" mm-display-elisp-inline identity)
234 ("text/html"
235 ,(if (fboundp 'mm-inline-text-html) 'mm-inline-text-html 'mm-inline-text)
236 (lambda (handle)
237 (or (and (boundp 'mm-inline-text-html-renderer)
238 mm-inline-text-html-renderer)
239 (and (boundp 'mm-text-html-renderer) mm-text-html-renderer))))
240 ("text/x-vcard"
241 mm-inline-text-vcard
242 (lambda (handle)
243 (or (featurep 'vcard)
244 (locate-library "vcard"))))
245 ("message/delivery-status" mm-inline-text identity)
246 ("message/rfc822" mh-mm-inline-message identity)
247 ;;("message/partial" mm-inline-partial identity)
248 ;;("message/external-body" mm-inline-external-body identity)
249 ("text/.*" mm-inline-text identity)
250 ("audio/wav" mm-inline-audio
251 (lambda (handle)
252 (and (or (featurep 'nas-sound) (featurep 'native-sound))
253 (device-sound-enabled-p))))
254 ("audio/au"
255 mm-inline-audio
256 (lambda (handle)
257 (and (or (featurep 'nas-sound) (featurep 'native-sound))
258 (device-sound-enabled-p))))
259 ("application/pgp-signature" ignore identity)
260 ("application/x-pkcs7-signature" ignore identity)
261 ("application/pkcs7-signature" ignore identity)
262 ("application/x-pkcs7-mime" ignore identity)
263 ("application/pkcs7-mime" ignore identity)
264 ("multipart/alternative" ignore identity)
265 ("multipart/mixed" ignore identity)
266 ("multipart/related" ignore identity)
267 ;; Disable audio and image
268 ("audio/.*" ignore ignore)
269 ("image/.*" ignore ignore)
270 ;; Default to displaying as text
271 (".*" mm-inline-text mm-readable-p))
272 "Alist of media types/tests saying whether types can be displayed inline.")
273
274 ;; Copy of `goto-address-mail-regexp'
275 (defvar mh-address-mail-regexp
276 "[-a-zA-Z0-9._]+@\\([-a-zA-z0-9_]+\\.\\)+[a-zA-Z0-9]+"
277 "A regular expression probably matching an e-mail address.")
278
279 ;; From goto-addr.el, which we don't want to force-load on users.
280
281 (defun mh-goto-address-find-address-at-point ()
282 "Find e-mail address around or before point.
283 Then search backwards to beginning of line for the start of an e-mail
284 address. If no e-mail address found, return nil."
285 (re-search-backward "[^-_A-z0-9.@]" (line-beginning-position) 'lim)
286 (if (or (looking-at mh-address-mail-regexp) ; already at start
287 (and (re-search-forward mh-address-mail-regexp
288 (line-end-position) 'lim)
289 (goto-char (match-beginning 0))))
290 (match-string-no-properties 0)))
291
292 (defun mh-mail-header-end ()
293 "Substitute for `mail-header-end' that doesn't widen the buffer.
294 In MH-E we frequently need to find the end of headers in nested messages, where
295 the buffer has been narrowed. This function works in this situation."
296 (save-excursion
297 ;; XXX: The following replaces a call to rfc822-goto-eoh. Occasionally,
298 ;; mail headers that MH-E has to read contains lines of the form:
299 ;; From xxx@yyy Mon May 10 11:48:07 2004
300 ;; In this situation, rfc822-goto-eoh doesn't go to the end of the
301 ;; header. The replacement allows From_ lines in the mail header.
302 (goto-char (point-min))
303 (loop for p = (re-search-forward
304 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
305 do (cond ((null p) (return))
306 (t (goto-char (match-beginning 0))
307 (unless (looking-at "From ") (return))
308 (goto-char p))))
309 (point)))
310
311 (defun mh-in-header-p ()
312 "Return non-nil if the point is in the header of a draft message."
313 (< (point) (mh-mail-header-end)))
314
315 (defun mh-header-field-beginning ()
316 "Move to the beginning of the current header field.
317 Handles RFC 822 continuation lines."
318 (beginning-of-line)
319 (while (looking-at "^[ \t]")
320 (forward-line -1)))
321
322 (defun mh-header-field-end ()
323 "Move to the end of the current header field.
324 Handles RFC 822 continuation lines."
325 (forward-line 1)
326 (while (looking-at "^[ \t]")
327 (forward-line 1))
328 (backward-char 1)) ;to end of previous line
329
330 (defun mh-letter-header-font-lock (limit)
331 "Return the entire mail header to font-lock.
332 Argument LIMIT limits search."
333 (if (= (point) limit)
334 nil
335 (let* ((mail-header-end (save-match-data (mh-mail-header-end)))
336 (lesser-limit (if (< mail-header-end limit) mail-header-end limit)))
337 (when (mh-in-header-p)
338 (set-match-data (list 1 lesser-limit))
339 (goto-char lesser-limit)
340 t))))
341
342 (defun mh-header-field-font-lock (field limit)
343 "Return the value of a header field FIELD to font-lock.
344 Argument LIMIT limits search."
345 (if (= (point) limit)
346 nil
347 (let* ((mail-header-end (mh-mail-header-end))
348 (lesser-limit (if (< mail-header-end limit) mail-header-end limit))
349 (case-fold-search t))
350 (when (and (< (point) mail-header-end) ;Only within header
351 (re-search-forward (format "^%s" field) lesser-limit t))
352 (let ((match-one-b (match-beginning 0))
353 (match-one-e (match-end 0)))
354 (mh-header-field-end)
355 (if (> (point) limit) ;Don't search for end beyond limit
356 (goto-char limit))
357 (set-match-data (list match-one-b match-one-e
358 (1+ match-one-e) (point)))
359 t)))))
360
361 (defun mh-header-to-font-lock (limit)
362 "Return the value of a header field To to font-lock.
363 Argument LIMIT limits search."
364 (mh-header-field-font-lock "To:" limit))
365
366 (defun mh-header-cc-font-lock (limit)
367 "Return the value of a header field cc to font-lock.
368 Argument LIMIT limits search."
369 (mh-header-field-font-lock "cc:" limit))
370
371 (defun mh-header-subject-font-lock (limit)
372 "Return the value of a header field Subject to font-lock.
373 Argument LIMIT limits search."
374 (mh-header-field-font-lock "Subject:" limit))
375
376 (eval-and-compile
377 ;; Otherwise byte-compilation fails on `mh-show-font-lock-keywords-with-cite'
378 (defvar mh-show-font-lock-keywords
379 '(("^\\(From:\\|Sender:\\)\\(.*\\)" (1 'default) (2 mh-show-from-face))
380 (mh-header-to-font-lock (0 'default) (1 mh-show-to-face))
381 (mh-header-cc-font-lock (0 'default) (1 mh-show-cc-face))
382 ("^\\(Reply-To:\\|Return-Path:\\)\\(.*\\)$"
383 (1 'default) (2 mh-show-from-face))
384 (mh-header-subject-font-lock (0 'default) (1 mh-show-subject-face))
385 ("^\\(Apparently-To:\\|Newsgroups:\\)\\(.*\\)"
386 (1 'default) (2 mh-show-cc-face))
387 ("^\\(In-reply-to\\|Date\\):\\(.*\\)$"
388 (1 'default) (2 mh-show-date-face))
389 (mh-letter-header-font-lock (0 mh-show-header-face append t)))
390 "Additional expressions to highlight in MH-show mode."))
391
392 (defvar mh-show-font-lock-keywords-with-cite
393 (eval-when-compile
394 (let* ((cite-chars "[>|}]")
395 (cite-prefix "A-Za-z")
396 (cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
397 (append
398 mh-show-font-lock-keywords
399 (list
400 ;; Use MATCH-ANCHORED to effectively anchor the regexp left side.
401 `(,cite-chars
402 (,(concat "\\=[ \t]*"
403 "\\(\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
404 "\\(" cite-chars "[ \t]*\\)\\)+"
405 "\\(.*\\)")
406 (beginning-of-line) (end-of-line)
407 (2 font-lock-constant-face nil t)
408 (4 font-lock-comment-face nil t)))))))
409 "Additional expressions to highlight in MH-show mode.")
410
411 (defvar mh-letter-font-lock-keywords
412 `(,@mh-show-font-lock-keywords-with-cite
413 (mh-font-lock-field-data (1 'mh-letter-header-field prepend t))))
414
415 (defun mh-show-font-lock-fontify-region (beg end loudly)
416 "Limit font-lock in `mh-show-mode' to the header.
417 Used when `mh-highlight-citation-p' is set to \"'gnus\", leaving the body to
418 be dealt with by gnus highlighting. The region between BEG and END is given
419 over to be fontified and LOUDLY controls if a user sees a message about the
420 fontification operation."
421 (let ((header-end (mh-mail-header-end)))
422 (cond
423 ((and (< beg header-end)(< end header-end))
424 (font-lock-default-fontify-region beg end loudly))
425 ((and (< beg header-end)(>= end header-end))
426 (font-lock-default-fontify-region beg header-end loudly))
427 (t
428 nil))))
429
430 ;; Needed to help shush the byte-compiler.
431 (if mh-xemacs-flag
432 (progn
433 (eval-and-compile
434 (require 'gnus)
435 (require 'gnus-art)
436 (require 'gnus-cite))))
437
438 (defun mh-gnus-article-highlight-citation ()
439 "Highlight cited text in current buffer using Gnus."
440 (interactive)
441 ;; Requiring gnus-cite should have been sufficient. However for Emacs21.1,
442 ;; recursive-load-depth-limit is only 10, so an error occurs. Also it may be
443 ;; better to have an autoload at top-level (though that won't work because
444 ;; of recursive-load-depth-limit). That gets rid of a compiler warning as
445 ;; well.
446 (unless mh-xemacs-flag
447 (require 'gnus-art)
448 (require 'gnus-cite))
449 ;; Don't allow Gnus to create buttons while highlighting, maybe this is bad
450 ;; style?
451 (flet ((gnus-article-add-button (&rest args) nil))
452 (let* ((modified (buffer-modified-p))
453 (gnus-article-buffer (buffer-name))
454 (gnus-cite-face-list `(,@(cdr gnus-cite-face-list)
455 ,(car gnus-cite-face-list))))
456 (gnus-article-highlight-citation t)
457 (set-buffer-modified-p modified))))
458
459 ;;; Internal bookkeeping variables:
460
461 ;; Cached value of the `Path:' component in the user's MH profile.
462 ;; User's mail folder directory.
463 (defvar mh-user-path nil)
464
465 ;; An mh-draft-folder of nil means do not use a draft folder.
466 ;; Cached value of the `Draft-Folder:' component in the user's MH profile.
467 ;; Name of folder containing draft messages.
468 (defvar mh-draft-folder nil)
469
470 ;; Cached value of the `Unseen-Sequence:' component in the user's MH profile.
471 ;; Name of the Unseen sequence.
472 (defvar mh-unseen-seq nil)
473
474 ;; Cached value of the `Previous-Sequence:' component in the user's MH
475 ;; profile.
476 ;; Name of the Previous sequence.
477 (defvar mh-previous-seq nil)
478
479 ;; Cached value of the `Inbox:' component in the user's MH profile,
480 ;; or "+inbox" if no such component.
481 ;; Name of the Inbox folder.
482 (defvar mh-inbox nil)
483
484 ;; The names of ephemeral buffers have a " *mh-" prefix (so that they are
485 ;; hidden and can be programmatically removed in mh-quit), and the variable
486 ;; names have the form mh-temp-.*-buffer.
487 (defconst mh-temp-buffer " *mh-temp*") ;scratch
488 (defconst mh-temp-fetch-buffer " *mh-fetch*") ;wget/curl/fetch output
489
490 ;; The names of MH-E buffers that are not ephemeral and can be used by the
491 ;; user (and deleted by the user when no longer needed) have a "*MH-E " prefix
492 ;; (so they can be programmatically removed in mh-quit), and the variable
493 ;; names have the form mh-.*-buffer.
494 (defconst mh-aliases-buffer "*MH-E Aliases*") ;alias lookups
495 (defconst mh-folders-buffer "*MH-E Folders*") ;folder list
496 (defconst mh-help-buffer "*MH-E Help*") ;quick help
497 (defconst mh-info-buffer "*MH-E Info*") ;version information buffer
498 (defconst mh-log-buffer "*MH-E Log*") ;output of MH commands and so on
499 (defconst mh-mail-delivery-buffer "*MH-E Mail Delivery*") ;mail delivery log
500 (defconst mh-recipients-buffer "*MH-E Recipients*") ;killed when draft sent
501 (defconst mh-sequences-buffer "*MH-E Sequences*") ;sequences list
502
503 ;; Number of lines to keep in mh-log-buffer.
504 (defvar mh-log-buffer-lines 100)
505
506 ;; Window configuration before MH-E command.
507 (defvar mh-previous-window-config nil)
508
509 ;;Non-nil means next SPC or whatever goes to next undeleted message.
510 (defvar mh-page-to-next-msg-flag nil)
511
512 ;;; Internal variables local to a folder.
513
514 ;; Name of current folder, a string.
515 (defvar mh-current-folder nil)
516
517 ;; Buffer that displays message for this folder.
518 (defvar mh-show-buffer nil)
519
520 ;; Full path of directory for this folder.
521 (defvar mh-folder-filename nil)
522
523 ;;Number of msgs in buffer.
524 (defvar mh-msg-count nil)
525
526 ;; If non-nil, show the message in a separate window.
527 (defvar mh-showing-mode nil)
528
529 (defvar mh-show-mode-map (make-sparse-keymap)
530 "Keymap used by the show buffer.")
531
532 (defvar mh-show-folder-buffer nil
533 "Keeps track of folder whose message is being displayed.")
534
535 (defvar mh-logo-cache nil)
536
537 (defun mh-logo-display ()
538 "Modify mode line to display MH-E logo."
539 (mh-do-in-gnu-emacs
540 (add-text-properties
541 0 2
542 `(display ,(or mh-logo-cache
543 (setq mh-logo-cache
544 (mh-funcall-if-exists
545 find-image '((:type xpm :ascent center
546 :file "mh-logo.xpm"))))))
547 (car mode-line-buffer-identification)))
548 (mh-do-in-xemacs
549 (setq modeline-buffer-identification
550 (list
551 (if mh-modeline-glyph
552 (cons modeline-buffer-id-left-extent mh-modeline-glyph)
553 (cons modeline-buffer-id-left-extent "XEmacs%N:"))
554 (cons modeline-buffer-id-right-extent " %17b")))))
555
556 ;;; This holds a documentation string used by describe-mode.
557 (defun mh-showing-mode (&optional arg)
558 "Change whether messages should be displayed.
559 With arg, display messages iff ARG is positive."
560 (setq mh-showing-mode
561 (if (null arg)
562 (not mh-showing-mode)
563 (> (prefix-numeric-value arg) 0))))
564
565 ;; The sequences of this folder. An alist of (seq . msgs).
566 (defvar mh-seq-list nil)
567
568 ;; List of displayed messages to be removed from the Unseen sequence.
569 (defvar mh-seen-list nil)
570
571 ;; If non-nil, show buffer contains message with all headers.
572 ;; If nil, show buffer contains message processed normally.
573 ;; Showing message with headers or normally.
574 (defvar mh-showing-with-headers nil)
575
576 ;;; MH-E macros
577
578 (defmacro with-mh-folder-updating (save-modification-flag &rest body)
579 "Format is (with-mh-folder-updating (SAVE-MODIFICATION-FLAG) &body BODY).
580 Execute BODY, which can modify the folder buffer without having to
581 worry about file locking or the read-only flag, and return its result.
582 If SAVE-MODIFICATION-FLAG is non-nil, the buffer's modification
583 flag is unchanged, otherwise it is cleared."
584 (setq save-modification-flag (car save-modification-flag)) ; CL style
585 `(prog1
586 (let ((mh-folder-updating-mod-flag (buffer-modified-p))
587 (buffer-read-only nil)
588 (buffer-file-name nil)) ;don't let the buffer get locked
589 (prog1
590 (progn
591 ,@body)
592 (mh-set-folder-modified-p mh-folder-updating-mod-flag)))
593 ,@(if (not save-modification-flag)
594 '((mh-set-folder-modified-p nil)))))
595
596 (put 'with-mh-folder-updating 'lisp-indent-hook 'defun)
597
598 (defmacro mh-in-show-buffer (show-buffer &rest body)
599 "Format is (mh-in-show-buffer (SHOW-BUFFER) &body BODY).
600 Display buffer SHOW-BUFFER in other window and execute BODY in it.
601 Stronger than `save-excursion', weaker than `save-window-excursion'."
602 (setq show-buffer (car show-buffer)) ; CL style
603 `(let ((mh-in-show-buffer-saved-window (selected-window)))
604 (switch-to-buffer-other-window ,show-buffer)
605 (if mh-bury-show-buffer-flag (bury-buffer (current-buffer)))
606 (unwind-protect
607 (progn
608 ,@body)
609 (select-window mh-in-show-buffer-saved-window))))
610
611 (put 'mh-in-show-buffer 'lisp-indent-hook 'defun)
612
613 (defmacro mh-do-at-event-location (event &rest body)
614 "Switch to the location of EVENT and execute BODY.
615 After BODY has been executed return to original window. The modification flag
616 of the buffer in the event window is preserved."
617 (let ((event-window (make-symbol "event-window"))
618 (event-position (make-symbol "event-position"))
619 (original-window (make-symbol "original-window"))
620 (original-position (make-symbol "original-position"))
621 (modified-flag (make-symbol "modified-flag")))
622 `(save-excursion
623 (let* ((,event-window
624 (or (mh-funcall-if-exists posn-window (event-start ,event))
625 (mh-funcall-if-exists event-window ,event)))
626 (,event-position
627 (or (mh-funcall-if-exists posn-point (event-start ,event))
628 (mh-funcall-if-exists event-closest-point ,event)))
629 (,original-window (selected-window))
630 (,original-position (progn
631 (set-buffer (window-buffer ,event-window))
632 (set-marker (make-marker) (point))))
633 (,modified-flag (buffer-modified-p))
634 (buffer-read-only nil))
635 (unwind-protect (progn
636 (select-window ,event-window)
637 (goto-char ,event-position)
638 ,@body)
639 (set-buffer-modified-p ,modified-flag)
640 (goto-char ,original-position)
641 (set-marker ,original-position nil)
642 (select-window ,original-window))))))
643
644 (put 'mh-do-at-event-location 'lisp-indent-hook 'defun)
645
646 (defmacro mh-make-seq (name msgs)
647 "Create sequence NAME with the given MSGS."
648 (list 'cons name msgs))
649
650 (defmacro mh-seq-name (sequence)
651 "Extract sequence name from the given SEQUENCE."
652 (list 'car sequence))
653
654 (defmacro mh-seq-msgs (sequence)
655 "Extract messages from the given SEQUENCE."
656 (list 'cdr sequence))
657
658 (defun mh-recenter (arg)
659 "Like recenter but with three improvements:
660 - At the end of the buffer it tries to show fewer empty lines.
661 - operates only if the current buffer is in the selected window.
662 (Commands like `save-some-buffers' can make this false.)
663 - nil ARG means recenter as if prefix argument had been given."
664 (cond ((not (eq (get-buffer-window (current-buffer)) (selected-window)))
665 nil)
666 ((= (point-max) (save-excursion
667 (forward-line (- (/ (window-height) 2) 2))
668 (point)))
669 (let ((lines-from-end 2))
670 (save-excursion
671 (while (> (point-max) (progn (forward-line) (point)))
672 (incf lines-from-end)))
673 (recenter (- lines-from-end))))
674 ;; '(4) is the same as C-u prefix argument.
675 (t (recenter (or arg '(4))))))
676
677 (defun mh-start-of-uncleaned-message ()
678 "Position uninteresting headers off the top of the window."
679 (let ((case-fold-search t))
680 (re-search-forward
681 "^To:\\|^Cc:\\|^From:\\|^Subject:\\|^Date:" nil t)
682 (beginning-of-line)
683 (mh-recenter 0)))
684
685 (defun mh-invalidate-show-buffer ()
686 "Invalidate the show buffer so we must update it to use it."
687 (if (get-buffer mh-show-buffer)
688 (save-excursion
689 (set-buffer mh-show-buffer)
690 (mh-unvisit-file))))
691
692 (defun mh-unvisit-file ()
693 "Separate current buffer from the message file it was visiting."
694 (or (not (buffer-modified-p))
695 (null buffer-file-name) ;we've been here before
696 (yes-or-no-p (format "Message %s modified; flush changes? "
697 (file-name-nondirectory buffer-file-name)))
698 (error "Flushing changes not confirmed"))
699 (clear-visited-file-modtime)
700 (unlock-buffer)
701 (setq buffer-file-name nil))
702
703
704 (defun mh-get-msg-num (error-if-no-message)
705 "Return the message number of the displayed message.
706 If the argument ERROR-IF-NO-MESSAGE is non-nil, then complain if the cursor is
707 not pointing to a message."
708 (save-excursion
709 (beginning-of-line)
710 (cond ((looking-at mh-scan-msg-number-regexp)
711 (string-to-number (buffer-substring (match-beginning 1)
712 (match-end 1))))
713 (error-if-no-message
714 (error "Cursor not pointing to message"))
715 (t nil))))
716
717 (defun mh-folder-name-p (name)
718 "Return non-nil if NAME is the name of a folder.
719 A name (a string or symbol) can be a folder name if it begins with \"+\"."
720 (if (symbolp name)
721 (eq (aref (symbol-name name) 0) ?+)
722 (and (> (length name) 0)
723 (eq (aref name 0) ?+))))
724
725
726 (defun mh-expand-file-name (filename &optional default)
727 "Expand FILENAME like `expand-file-name', but also handle MH folder names.
728 Any filename that starts with '+' is treated as a folder name.
729 See `expand-file-name' for description of DEFAULT."
730 (if (mh-folder-name-p filename)
731 (expand-file-name (substring filename 1) mh-user-path)
732 (expand-file-name filename default)))
733
734
735 (defun mh-msg-filename (msg &optional folder)
736 "Return the file name of MSG in FOLDER (default current folder)."
737 (expand-file-name (int-to-string msg)
738 (if folder
739 (mh-expand-file-name folder)
740 mh-folder-filename)))
741
742 ;;; Infrastructure to generate show-buffer functions from folder functions
743 ;;; XEmacs does not have deactivate-mark? What is the equivalent of
744 ;;; transient-mark-mode for XEmacs? Should we be restoring the mark in the
745 ;;; folder buffer after the operation has been carried out.
746 (defmacro mh-defun-show-buffer (function original-function
747 &optional dont-return)
748 "Define FUNCTION to run ORIGINAL-FUNCTION in folder buffer.
749 If the buffer we start in is still visible and DONT-RETURN is nil then switch
750 to it after that."
751 `(defun ,function ()
752 ,(format "Calls %s from the message's folder.\n%s\nSee `%s' for more info.\n"
753 original-function
754 (if dont-return ""
755 "When function completes, returns to the show buffer if it is
756 still visible.\n")
757 original-function)
758 (interactive)
759 (when (buffer-live-p (get-buffer mh-show-folder-buffer))
760 (let ((config (current-window-configuration))
761 (folder-buffer mh-show-folder-buffer)
762 (normal-exit nil)
763 ,@(if dont-return () '((cur-buffer-name (buffer-name)))))
764 (pop-to-buffer mh-show-folder-buffer nil)
765 (unless (equal (buffer-name
766 (window-buffer (frame-first-window (selected-frame))))
767 folder-buffer)
768 (delete-other-windows))
769 (mh-goto-cur-msg t)
770 (mh-funcall-if-exists deactivate-mark)
771 (unwind-protect
772 (prog1 (call-interactively (function ,original-function))
773 (setq normal-exit t))
774 (mh-funcall-if-exists deactivate-mark)
775 (when (eq major-mode 'mh-folder-mode)
776 (mh-funcall-if-exists hl-line-highlight))
777 (cond ((not normal-exit)
778 (set-window-configuration config))
779 ,(if dont-return
780 `(t (setq mh-previous-window-config config))
781 `((and (get-buffer cur-buffer-name)
782 (window-live-p (get-buffer-window
783 (get-buffer cur-buffer-name))))
784 (pop-to-buffer (get-buffer cur-buffer-name) nil)))))))))
785
786 ;;; Generate interactive functions for the show buffer from the corresponding
787 ;;; folder functions.
788 (mh-defun-show-buffer mh-show-previous-undeleted-msg
789 mh-previous-undeleted-msg)
790 (mh-defun-show-buffer mh-show-next-undeleted-msg
791 mh-next-undeleted-msg)
792 (mh-defun-show-buffer mh-show-quit mh-quit)
793 (mh-defun-show-buffer mh-show-delete-msg mh-delete-msg)
794 (mh-defun-show-buffer mh-show-refile-msg mh-refile-msg)
795 (mh-defun-show-buffer mh-show-undo mh-undo)
796 (mh-defun-show-buffer mh-show-execute-commands mh-execute-commands)
797 (mh-defun-show-buffer mh-show-reply mh-reply t)
798 (mh-defun-show-buffer mh-show-redistribute mh-redistribute)
799 (mh-defun-show-buffer mh-show-forward mh-forward t)
800 (mh-defun-show-buffer mh-show-header-display mh-header-display)
801 (mh-defun-show-buffer mh-show-refile-or-write-again
802 mh-refile-or-write-again)
803 (mh-defun-show-buffer mh-show-show mh-show)
804 (mh-defun-show-buffer mh-show-write-message-to-file
805 mh-write-msg-to-file)
806 (mh-defun-show-buffer mh-show-extract-rejected-mail
807 mh-extract-rejected-mail t)
808 (mh-defun-show-buffer mh-show-delete-msg-no-motion
809 mh-delete-msg-no-motion)
810 (mh-defun-show-buffer mh-show-first-msg mh-first-msg)
811 (mh-defun-show-buffer mh-show-last-msg mh-last-msg)
812 (mh-defun-show-buffer mh-show-copy-msg mh-copy-msg)
813 (mh-defun-show-buffer mh-show-edit-again mh-edit-again t)
814 (mh-defun-show-buffer mh-show-goto-msg mh-goto-msg)
815 (mh-defun-show-buffer mh-show-inc-folder mh-inc-folder)
816 (mh-defun-show-buffer mh-show-delete-subject-or-thread
817 mh-delete-subject-or-thread)
818 (mh-defun-show-buffer mh-show-delete-subject mh-delete-subject)
819 (mh-defun-show-buffer mh-show-print-msg mh-print-msg)
820 (mh-defun-show-buffer mh-show-send mh-send t)
821 (mh-defun-show-buffer mh-show-toggle-showing mh-toggle-showing t)
822 (mh-defun-show-buffer mh-show-pipe-msg mh-pipe-msg t)
823 (mh-defun-show-buffer mh-show-sort-folder mh-sort-folder)
824 (mh-defun-show-buffer mh-show-visit-folder mh-visit-folder t)
825 (mh-defun-show-buffer mh-show-rescan-folder mh-rescan-folder)
826 (mh-defun-show-buffer mh-show-pack-folder mh-pack-folder)
827 (mh-defun-show-buffer mh-show-kill-folder mh-kill-folder t)
828 (mh-defun-show-buffer mh-show-list-folders mh-list-folders t)
829 (mh-defun-show-buffer mh-show-search-folder mh-search-folder t)
830 (mh-defun-show-buffer mh-show-undo-folder mh-undo-folder)
831 (mh-defun-show-buffer mh-show-delete-msg-from-seq
832 mh-delete-msg-from-seq)
833 (mh-defun-show-buffer mh-show-delete-seq mh-delete-seq)
834 (mh-defun-show-buffer mh-show-list-sequences mh-list-sequences)
835 (mh-defun-show-buffer mh-show-narrow-to-seq mh-narrow-to-seq)
836 (mh-defun-show-buffer mh-show-put-msg-in-seq mh-put-msg-in-seq)
837 (mh-defun-show-buffer mh-show-msg-is-in-seq mh-msg-is-in-seq)
838 (mh-defun-show-buffer mh-show-widen mh-widen)
839 (mh-defun-show-buffer mh-show-narrow-to-subject mh-narrow-to-subject)
840 (mh-defun-show-buffer mh-show-narrow-to-from mh-narrow-to-from)
841 (mh-defun-show-buffer mh-show-narrow-to-cc mh-narrow-to-cc)
842 (mh-defun-show-buffer mh-show-narrow-to-range mh-narrow-to-range)
843 (mh-defun-show-buffer mh-show-narrow-to-to mh-narrow-to-to)
844 (mh-defun-show-buffer mh-show-store-msg mh-store-msg)
845 (mh-defun-show-buffer mh-show-page-digest mh-page-digest)
846 (mh-defun-show-buffer mh-show-page-digest-backwards
847 mh-page-digest-backwards)
848 (mh-defun-show-buffer mh-show-burst-digest mh-burst-digest)
849 (mh-defun-show-buffer mh-show-page-msg mh-page-msg)
850 (mh-defun-show-buffer mh-show-previous-page mh-previous-page)
851 (mh-defun-show-buffer mh-show-modify mh-modify t)
852 (mh-defun-show-buffer mh-show-next-button mh-next-button)
853 (mh-defun-show-buffer mh-show-prev-button mh-prev-button)
854 (mh-defun-show-buffer mh-show-toggle-mime-part mh-folder-toggle-mime-part)
855 (mh-defun-show-buffer mh-show-save-mime-part mh-folder-save-mime-part)
856 (mh-defun-show-buffer mh-show-inline-mime-part mh-folder-inline-mime-part)
857 (mh-defun-show-buffer mh-show-toggle-threads mh-toggle-threads)
858 (mh-defun-show-buffer mh-show-thread-delete mh-thread-delete)
859 (mh-defun-show-buffer mh-show-thread-refile mh-thread-refile)
860 (mh-defun-show-buffer mh-show-update-sequences mh-update-sequences)
861 (mh-defun-show-buffer mh-show-next-unread-msg mh-next-unread-msg)
862 (mh-defun-show-buffer mh-show-previous-unread-msg mh-previous-unread-msg)
863 (mh-defun-show-buffer mh-show-thread-ancestor mh-thread-ancestor)
864 (mh-defun-show-buffer mh-show-thread-next-sibling mh-thread-next-sibling)
865 (mh-defun-show-buffer mh-show-thread-previous-sibling
866 mh-thread-previous-sibling)
867 (mh-defun-show-buffer mh-show-index-visit-folder mh-index-visit-folder t)
868 (mh-defun-show-buffer mh-show-toggle-tick mh-toggle-tick)
869 (mh-defun-show-buffer mh-show-narrow-to-tick mh-narrow-to-tick)
870 (mh-defun-show-buffer mh-show-junk-blacklist mh-junk-blacklist)
871 (mh-defun-show-buffer mh-show-junk-whitelist mh-junk-whitelist)
872 (mh-defun-show-buffer mh-show-index-new-messages mh-index-new-messages)
873 (mh-defun-show-buffer mh-show-index-ticked-messages mh-index-ticked-messages)
874 (mh-defun-show-buffer mh-show-index-sequenced-messages
875 mh-index-sequenced-messages)
876 (mh-defun-show-buffer mh-show-catchup mh-catchup)
877 (mh-defun-show-buffer mh-show-ps-print-toggle-mime mh-ps-print-toggle-mime)
878 (mh-defun-show-buffer mh-show-ps-print-toggle-color mh-ps-print-toggle-color)
879 (mh-defun-show-buffer mh-show-ps-print-toggle-faces mh-ps-print-toggle-faces)
880 (mh-defun-show-buffer mh-show-ps-print-msg-file mh-ps-print-msg-file)
881 (mh-defun-show-buffer mh-show-ps-print-msg mh-ps-print-msg)
882 (mh-defun-show-buffer mh-show-ps-print-msg-show mh-ps-print-msg-show)
883 (mh-defun-show-buffer mh-show-toggle-mime-buttons mh-toggle-mime-buttons)
884 (mh-defun-show-buffer mh-show-display-with-external-viewer
885 mh-display-with-external-viewer)
886
887 ;;; Populate mh-show-mode-map
888 (gnus-define-keys mh-show-mode-map
889 " " mh-show-page-msg
890 "!" mh-show-refile-or-write-again
891 "'" mh-show-toggle-tick
892 "," mh-show-header-display
893 "." mh-show-show
894 ">" mh-show-write-message-to-file
895 "?" mh-help
896 "E" mh-show-extract-rejected-mail
897 "M" mh-show-modify
898 "\177" mh-show-previous-page
899 "\C-d" mh-show-delete-msg-no-motion
900 "\t" mh-show-next-button
901 [backtab] mh-show-prev-button
902 "\M-\t" mh-show-prev-button
903 "\ed" mh-show-redistribute
904 "^" mh-show-refile-msg
905 "c" mh-show-copy-msg
906 "d" mh-show-delete-msg
907 "e" mh-show-edit-again
908 "f" mh-show-forward
909 "g" mh-show-goto-msg
910 "i" mh-show-inc-folder
911 "k" mh-show-delete-subject-or-thread
912 "m" mh-show-send
913 "n" mh-show-next-undeleted-msg
914 "\M-n" mh-show-next-unread-msg
915 "o" mh-show-refile-msg
916 "p" mh-show-previous-undeleted-msg
917 "\M-p" mh-show-previous-unread-msg
918 "q" mh-show-quit
919 "r" mh-show-reply
920 "s" mh-show-send
921 "t" mh-show-toggle-showing
922 "u" mh-show-undo
923 "x" mh-show-execute-commands
924 "v" mh-show-index-visit-folder
925 "|" mh-show-pipe-msg)
926
927 (gnus-define-keys (mh-show-folder-map "F" mh-show-mode-map)
928 "?" mh-prefix-help
929 "'" mh-index-ticked-messages
930 "S" mh-show-sort-folder
931 "c" mh-show-catchup
932 "f" mh-show-visit-folder
933 "i" mh-index-search
934 "k" mh-show-kill-folder
935 "l" mh-show-list-folders
936 "n" mh-index-new-messages
937 "o" mh-show-visit-folder
938 "q" mh-show-index-sequenced-messages
939 "r" mh-show-rescan-folder
940 "s" mh-show-search-folder
941 "t" mh-show-toggle-threads
942 "u" mh-show-undo-folder
943 "v" mh-show-visit-folder)
944
945 (gnus-define-keys (mh-show-sequence-map "S" mh-show-mode-map)
946 "'" mh-show-narrow-to-tick
947 "?" mh-prefix-help
948 "d" mh-show-delete-msg-from-seq
949 "k" mh-show-delete-seq
950 "l" mh-show-list-sequences
951 "n" mh-show-narrow-to-seq
952 "p" mh-show-put-msg-in-seq
953 "s" mh-show-msg-is-in-seq
954 "w" mh-show-widen)
955
956 (define-key mh-show-mode-map "I" mh-inc-spool-map)
957
958 (gnus-define-keys (mh-show-junk-map "J" mh-show-mode-map)
959 "?" mh-prefix-help
960 "b" mh-show-junk-blacklist
961 "w" mh-show-junk-whitelist)
962
963 (gnus-define-keys (mh-show-ps-print-map "P" mh-show-mode-map)
964 "?" mh-prefix-help
965 "A" mh-show-ps-print-toggle-mime
966 "C" mh-show-ps-print-toggle-color
967 "F" mh-show-ps-print-toggle-faces
968 "M" mh-show-ps-print-toggle-mime
969 "f" mh-show-ps-print-msg-file
970 "l" mh-show-print-msg
971 "p" mh-show-ps-print-msg
972 "s" mh-show-ps-print-msg-show)
973
974 (gnus-define-keys (mh-show-thread-map "T" mh-show-mode-map)
975 "?" mh-prefix-help
976 "u" mh-show-thread-ancestor
977 "p" mh-show-thread-previous-sibling
978 "n" mh-show-thread-next-sibling
979 "t" mh-show-toggle-threads
980 "d" mh-show-thread-delete
981 "o" mh-show-thread-refile)
982
983 (gnus-define-keys (mh-show-limit-map "/" mh-show-mode-map)
984 "'" mh-show-narrow-to-tick
985 "?" mh-prefix-help
986 "c" mh-show-narrow-to-cc
987 "f" mh-show-narrow-to-from
988 "r" mh-show-narrow-to-range
989 "s" mh-show-narrow-to-subject
990 "t" mh-show-narrow-to-to
991 "w" mh-show-widen)
992
993 (gnus-define-keys (mh-show-extract-map "X" mh-show-mode-map)
994 "?" mh-prefix-help
995 "s" mh-show-store-msg
996 "u" mh-show-store-msg)
997
998 ;; Untested...
999 (gnus-define-keys (mh-show-digest-map "D" mh-show-mode-map)
1000 "?" mh-prefix-help
1001 " " mh-show-page-digest
1002 "\177" mh-show-page-digest-backwards
1003 "b" mh-show-burst-digest)
1004
1005 (gnus-define-keys (mh-show-mime-map "K" mh-show-mode-map)
1006 "?" mh-prefix-help
1007 "a" mh-mime-save-parts
1008 "e" mh-show-display-with-external-viewer
1009 "v" mh-show-toggle-mime-part
1010 "o" mh-show-save-mime-part
1011 "i" mh-show-inline-mime-part
1012 "t" mh-show-toggle-mime-buttons
1013 "\t" mh-show-next-button
1014 [backtab] mh-show-prev-button
1015 "\M-\t" mh-show-prev-button)
1016
1017 (easy-menu-define
1018 mh-show-sequence-menu mh-show-mode-map "Menu for MH-E folder-sequence."
1019 '("Sequence"
1020 ["Add Message to Sequence..." mh-show-put-msg-in-seq t]
1021 ["List Sequences for Message" mh-show-msg-is-in-seq t]
1022 ["Delete Message from Sequence..." mh-show-delete-msg-from-seq t]
1023 ["List Sequences in Folder..." mh-show-list-sequences t]
1024 ["Delete Sequence..." mh-show-delete-seq t]
1025 ["Narrow to Sequence..." mh-show-narrow-to-seq t]
1026 ["Widen from Sequence" mh-show-widen t]
1027 "--"
1028 ["Narrow to Subject Sequence" mh-show-narrow-to-subject t]
1029 ["Narrow to Tick Sequence" mh-show-narrow-to-tick
1030 (save-excursion
1031 (set-buffer mh-show-folder-buffer)
1032 (and mh-tick-seq (mh-seq-msgs (mh-find-seq mh-tick-seq))))]
1033 ["Delete Rest of Same Subject" mh-show-delete-subject t]
1034 ["Toggle Tick Mark" mh-show-toggle-tick t]
1035 "--"
1036 ["Push State Out to MH" mh-show-update-sequences t]))
1037
1038 (easy-menu-define
1039 mh-show-message-menu mh-show-mode-map "Menu for MH-E folder-message."
1040 '("Message"
1041 ["Show Message" mh-show-show t]
1042 ["Show Message with Header" mh-show-header-display t]
1043 ["Next Message" mh-show-next-undeleted-msg t]
1044 ["Previous Message" mh-show-previous-undeleted-msg t]
1045 ["Go to First Message" mh-show-first-msg t]
1046 ["Go to Last Message" mh-show-last-msg t]
1047 ["Go to Message by Number..." mh-show-goto-msg t]
1048 ["Modify Message" mh-show-modify t]
1049 ["Delete Message" mh-show-delete-msg t]
1050 ["Refile Message" mh-show-refile-msg t]
1051 ["Undo Delete/Refile" mh-show-undo t]
1052 ["Process Delete/Refile" mh-show-execute-commands t]
1053 "--"
1054 ["Compose a New Message" mh-send t]
1055 ["Reply to Message..." mh-show-reply t]
1056 ["Forward Message..." mh-show-forward t]
1057 ["Redistribute Message..." mh-show-redistribute t]
1058 ["Edit Message Again" mh-show-edit-again t]
1059 ["Re-edit a Bounced Message" mh-show-extract-rejected-mail t]
1060 "--"
1061 ["Copy Message to Folder..." mh-show-copy-msg t]
1062 ["Print Message" mh-show-print-msg t]
1063 ["Write Message to File..." mh-show-write-msg-to-file t]
1064 ["Pipe Message to Command..." mh-show-pipe-msg t]
1065 ["Unpack Uuencoded Message..." mh-show-store-msg t]
1066 ["Burst Digest Message" mh-show-burst-digest t]))
1067
1068 (easy-menu-define
1069 mh-show-folder-menu mh-show-mode-map "Menu for MH-E folder."
1070 '("Folder"
1071 ["Incorporate New Mail" mh-show-inc-folder t]
1072 ["Toggle Show/Folder" mh-show-toggle-showing t]
1073 ["Execute Delete/Refile" mh-show-execute-commands t]
1074 ["Rescan Folder" mh-show-rescan-folder t]
1075 ["Thread Folder" mh-show-toggle-threads t]
1076 ["Pack Folder" mh-show-pack-folder t]
1077 ["Sort Folder" mh-show-sort-folder t]
1078 "--"
1079 ["List Folders" mh-show-list-folders t]
1080 ["Visit a Folder..." mh-show-visit-folder t]
1081 ["View New Messages" mh-show-index-new-messages t]
1082 ["Search a Folder..." mh-show-search-folder t]
1083 ["Indexed Search..." mh-index-search t]
1084 "--"
1085 ["Quit MH-E" mh-quit t]))
1086
1087
1088 ;;; Ensure new buffers won't get this mode if default-major-mode is nil.
1089 (put 'mh-show-mode 'mode-class 'special)
1090
1091 ;; Avoid compiler warnings in XEmacs and Emacs 20
1092 (eval-when-compile
1093 (defvar tool-bar-mode)
1094 (defvar tool-bar-map))
1095
1096 (define-derived-mode mh-show-mode text-mode "MH-Show"
1097 "Major mode for showing messages in MH-E.\\<mh-show-mode-map>
1098 The value of `mh-show-mode-hook' is a list of functions to
1099 be called, with no arguments, upon entry to this mode.
1100 See also `mh-folder-mode'.
1101
1102 \\{mh-show-mode-map}"
1103 (set (make-local-variable 'mail-header-separator) mh-mail-header-separator)
1104 (setq paragraph-start (default-value 'paragraph-start))
1105 (mh-show-unquote-From)
1106 (mh-show-xface)
1107 (mh-show-addr)
1108 (setq buffer-invisibility-spec '((vanish . t) t))
1109 (set (make-local-variable 'line-move-ignore-invisible) t)
1110 (make-local-variable 'font-lock-defaults)
1111 ;;(set (make-local-variable 'font-lock-support-mode) nil)
1112 (cond
1113 ((equal mh-highlight-citation-p 'font-lock)
1114 (setq font-lock-defaults '(mh-show-font-lock-keywords-with-cite t)))
1115 ((equal mh-highlight-citation-p 'gnus)
1116 (setq font-lock-defaults '((mh-show-font-lock-keywords)
1117 t nil nil nil
1118 (font-lock-fontify-region-function
1119 . mh-show-font-lock-fontify-region)))
1120 (mh-gnus-article-highlight-citation))
1121 (t
1122 (setq font-lock-defaults '(mh-show-font-lock-keywords t))))
1123 (if (and mh-xemacs-flag
1124 font-lock-auto-fontify)
1125 (turn-on-font-lock))
1126 (set (make-local-variable 'tool-bar-map) mh-show-tool-bar-map)
1127 (mh-funcall-if-exists mh-toolbar-init :show)
1128 (when mh-decode-mime-flag
1129 (mh-make-local-hook 'kill-buffer-hook)
1130 (add-hook 'kill-buffer-hook 'mh-mime-cleanup nil t))
1131 (easy-menu-add mh-show-sequence-menu)
1132 (easy-menu-add mh-show-message-menu)
1133 (easy-menu-add mh-show-folder-menu)
1134 (make-local-variable 'mh-show-folder-buffer)
1135 (buffer-disable-undo)
1136 (setq buffer-read-only t)
1137 (use-local-map mh-show-mode-map))
1138
1139 (defun mh-show-addr ()
1140 "Use `goto-address'."
1141 (when mh-show-use-goto-addr-flag
1142 (if (not (featurep 'goto-addr))
1143 (load "goto-addr" t t))
1144 (if (fboundp 'goto-address)
1145 (goto-address))))
1146
1147 \f
1148
1149 ;; X-Face and Face display
1150 (defvar mh-show-xface-function
1151 (cond ((and mh-xemacs-flag (locate-library "x-face") (not (featurep 'xface)))
1152 (load "x-face" t t)
1153 #'mh-face-display-function)
1154 ((>= emacs-major-version 21)
1155 #'mh-face-display-function)
1156 (t #'ignore))
1157 "Determine at run time what function should be called to display X-Face.")
1158
1159 (defvar mh-uncompface-executable
1160 (and (fboundp 'executable-find) (executable-find "uncompface")))
1161
1162 (defun mh-face-to-png (data)
1163 "Convert base64 encoded DATA to png image."
1164 (with-temp-buffer
1165 (insert data)
1166 (ignore-errors (base64-decode-region (point-min) (point-max)))
1167 (buffer-string)))
1168
1169 (defun mh-uncompface (data)
1170 "Run DATA through `uncompface' to generate bitmap."
1171 (with-temp-buffer
1172 (insert data)
1173 (when (and mh-uncompface-executable
1174 (equal (call-process-region (point-min) (point-max)
1175 mh-uncompface-executable t '(t nil))
1176 0))
1177 (mh-icontopbm)
1178 (buffer-string))))
1179
1180 (defun mh-icontopbm ()
1181 "Elisp substitute for `icontopbm'."
1182 (goto-char (point-min))
1183 (let ((end (point-max)))
1184 (while (re-search-forward "0x\\(..\\)\\(..\\)," nil t)
1185 (save-excursion
1186 (goto-char (point-max))
1187 (insert (string-to-number (match-string 1) 16))
1188 (insert (string-to-number (match-string 2) 16))))
1189 (delete-region (point-min) end)
1190 (goto-char (point-min))
1191 (insert "P4\n48 48\n")))
1192
1193 (mh-do-in-xemacs (defvar default-enable-multibyte-characters))
1194
1195 (defun mh-face-display-function ()
1196 "Display a Face, X-Face, or X-Image-URL header field.
1197 If more than one of these are present, then the first one found in this order
1198 is used."
1199 (save-restriction
1200 (goto-char (point-min))
1201 (re-search-forward "\n\n" (point-max) t)
1202 (narrow-to-region (point-min) (point))
1203 (let* ((case-fold-search t)
1204 (default-enable-multibyte-characters nil)
1205 (face (message-fetch-field "face" t))
1206 (x-face (message-fetch-field "x-face" t))
1207 (url (message-fetch-field "x-image-url" t))
1208 raw type)
1209 (cond (face (setq raw (mh-face-to-png face)
1210 type 'png))
1211 (x-face (setq raw (mh-uncompface x-face)
1212 type 'pbm))
1213 (url (setq type 'url))
1214 (t (multiple-value-setq (type raw) (mh-picon-get-image))))
1215 (when type
1216 (goto-char (point-min))
1217 (when (re-search-forward "^from:" (point-max) t)
1218 ;; GNU Emacs
1219 (mh-do-in-gnu-emacs
1220 (if (eq type 'url)
1221 (mh-x-image-url-display url)
1222 (mh-funcall-if-exists
1223 insert-image (create-image
1224 raw type t
1225 :foreground (face-foreground 'mh-show-xface)
1226 :background (face-background 'mh-show-xface))
1227 " ")))
1228 ;; XEmacs
1229 (mh-do-in-xemacs
1230 (cond
1231 ((eq type 'url)
1232 (mh-x-image-url-display url))
1233 ((eq type 'png)
1234 (when (featurep 'png)
1235 (set-extent-begin-glyph
1236 (make-extent (point) (point))
1237 (make-glyph (vector 'png ':data (mh-face-to-png face))))))
1238 ;; Try internal xface support if available...
1239 ((and (eq type 'pbm) (featurep 'xface))
1240 (set-glyph-face
1241 (set-extent-begin-glyph
1242 (make-extent (point) (point))
1243 (make-glyph (vector 'xface ':data (concat "X-Face: " x-face))))
1244 'mh-show-xface))
1245 ;; Otherwise try external support with x-face...
1246 ((and (eq type 'pbm)
1247 (fboundp 'x-face-xmas-wl-display-x-face)
1248 (fboundp 'executable-find) (executable-find "uncompface"))
1249 (mh-funcall-if-exists x-face-xmas-wl-display-x-face))
1250 ;; Picon display
1251 ((and raw (member type '(xpm xbm gif)))
1252 (when (featurep type)
1253 (set-extent-begin-glyph
1254 (make-extent (point) (point))
1255 (make-glyph (vector type ':data raw))))))
1256 (when raw (insert " "))))))))
1257
1258 (defun mh-show-xface ()
1259 "Display X-Face."
1260 (when (and window-system mh-show-use-xface-flag
1261 (or mh-decode-mime-flag mhl-formfile
1262 mh-clean-message-header-flag))
1263 (funcall mh-show-xface-function)))
1264
1265 \f
1266
1267 ;; Picon display
1268
1269 ;;; XXX: This should be customizable. As a side-effect of setting this
1270 ;;; variable, arrange to reset mh-picon-existing-directory-list to 'unset.
1271 (defvar mh-picon-directory-list
1272 '("~/.picons" "~/.picons/users" "~/.picons/usenix" "~/.picons/news"
1273 "~/.picons/domains" "~/.picons/misc"
1274 "/usr/share/picons/" "/usr/share/picons/users" "/usr/share/picons/usenix"
1275 "/usr/share/picons/news" "/usr/share/picons/domains"
1276 "/usr/share/picons/misc")
1277 "List of directories where picons reside.
1278 The directories are searched for in the order they appear in the list.")
1279
1280 (defvar mh-picon-existing-directory-list 'unset
1281 "List of directories to search in.")
1282
1283 (defvar mh-picon-cache (make-hash-table :test #'equal))
1284
1285 (defvar mh-picon-image-types
1286 (loop for type in '(xpm xbm gif)
1287 when (or (mh-do-in-gnu-emacs
1288 (ignore-errors
1289 (mh-funcall-if-exists image-type-available-p type)))
1290 (mh-do-in-xemacs (featurep type)))
1291 collect type))
1292
1293 (defun mh-picon-set-directory-list ()
1294 "Update `mh-picon-existing-directory-list' if needed."
1295 (when (eq mh-picon-existing-directory-list 'unset)
1296 (setq mh-picon-existing-directory-list
1297 (loop for x in mh-picon-directory-list
1298 when (file-directory-p x) collect x))))
1299
1300 (defun* mh-picon-get-image ()
1301 "Find the best possible match and return contents."
1302 (mh-picon-set-directory-list)
1303 (save-restriction
1304 (let* ((from-field (ignore-errors (car (message-tokenize-header
1305 (mh-get-header-field "from:")))))
1306 (from (car (ignore-errors
1307 (mh-funcall-if-exists ietf-drums-parse-address
1308 from-field))))
1309 (host (and from
1310 (string-match "\\([^+]*\\)\\(+.*\\)?@\\(.*\\)" from)
1311 (downcase (match-string 3 from))))
1312 (user (and host (downcase (match-string 1 from))))
1313 (canonical-address (format "%s@%s" user host))
1314 (cached-value (gethash canonical-address mh-picon-cache))
1315 (host-list (and host (delete "" (split-string host "\\."))))
1316 (match nil))
1317 (cond (cached-value (return-from mh-picon-get-image cached-value))
1318 ((not host-list) (return-from mh-picon-get-image nil)))
1319 (setq match
1320 (block 'loop
1321 ;; u@h search
1322 (loop for dir in mh-picon-existing-directory-list
1323 do (loop for type in mh-picon-image-types
1324 ;; [path]user@host
1325 for file1 = (format "%s/%s.%s"
1326 dir canonical-address type)
1327 when (file-exists-p file1)
1328 do (return-from 'loop file1)
1329 ;; [path]user
1330 for file2 = (format "%s/%s.%s" dir user type)
1331 when (file-exists-p file2)
1332 do (return-from 'loop file2)
1333 ;; [path]host
1334 for file3 = (format "%s/%s.%s" dir host type)
1335 when (file-exists-p file3)
1336 do (return-from 'loop file3)))
1337 ;; facedb search
1338 ;; Search order for user@foo.net:
1339 ;; [path]net/foo/user
1340 ;; [path]net/foo/user/face
1341 ;; [path]net/user
1342 ;; [path]net/user/face
1343 ;; [path]net/foo/unknown
1344 ;; [path]net/foo/unknown/face
1345 ;; [path]net/unknown
1346 ;; [path]net/unknown/face
1347 (loop for u in (list user "unknown")
1348 do (loop for dir in mh-picon-existing-directory-list
1349 do (loop for x on host-list by #'cdr
1350 for y = (mh-picon-generate-path x u dir)
1351 do (loop for type in mh-picon-image-types
1352 for z1 = (format "%s.%s" y type)
1353 when (file-exists-p z1)
1354 do (return-from 'loop z1)
1355 for z2 = (format "%s/face.%s"
1356 y type)
1357 when (file-exists-p z2)
1358 do (return-from 'loop z2)))))))
1359 (setf (gethash canonical-address mh-picon-cache)
1360 (mh-picon-file-contents match)))))
1361
1362 (defun mh-picon-file-contents (file)
1363 "Return details about FILE.
1364 A list of consisting of a symbol for the type of the file and the file
1365 contents as a string is returned. If FILE is nil, then both elements of the
1366 list are nil."
1367 (if (stringp file)
1368 (with-temp-buffer
1369 (let ((type (and (string-match ".*\\.\\(...\\)$" file)
1370 (intern (match-string 1 file)))))
1371 (insert-file-contents-literally file)
1372 (values type (buffer-string))))
1373 (values nil nil)))
1374
1375 (defun mh-picon-generate-path (host-list user directory)
1376 "Generate the image file path.
1377 HOST-LIST is the parsed host address of the email address, USER the username
1378 and DIRECTORY is the directory relative to which the path is generated."
1379 (loop with acc = ""
1380 for elem in host-list
1381 do (setq acc (format "%s/%s" elem acc))
1382 finally return (format "%s/%s%s" directory acc user)))
1383
1384 \f
1385
1386 ;; X-Image-URL display
1387
1388 (defvar mh-x-image-cache-directory nil
1389 "Directory where X-Image-URL images are cached.")
1390 (defvar mh-x-image-scaling-function
1391 (cond ((executable-find "convert")
1392 'mh-x-image-scale-with-convert)
1393 ((and (executable-find "anytopnm") (executable-find "pnmscale")
1394 (executable-find "pnmtopng"))
1395 'mh-x-image-scale-with-pnm)
1396 (t 'ignore))
1397 "Function to use to scale image to proper size.")
1398 (defvar mh-wget-executable nil)
1399 (defvar mh-wget-choice
1400 (or (and (setq mh-wget-executable (executable-find "wget")) 'wget)
1401 (and (setq mh-wget-executable (executable-find "fetch")) 'fetch)
1402 (and (setq mh-wget-executable (executable-find "curl")) 'curl)))
1403 (defvar mh-wget-option
1404 (cdr (assoc mh-wget-choice '((curl . "-o") (fetch . "-o") (wget . "-O")))))
1405 (defvar mh-x-image-temp-file nil)
1406 (defvar mh-x-image-url nil)
1407 (defvar mh-x-image-marker nil)
1408 (defvar mh-x-image-url-cache-file nil)
1409
1410 ;; Functions to scale image to proper size
1411 (defun mh-x-image-scale-with-pnm (input output)
1412 "Scale image in INPUT file and write to OUTPUT file using pnm tools."
1413 (let ((res (shell-command-to-string
1414 (format "anytopnm < %s | pnmscale -xysize 96 48 | pnmtopng > %s"
1415 input output))))
1416 (unless (equal res "")
1417 (delete-file output))))
1418
1419 (defun mh-x-image-scale-with-convert (input output)
1420 "Scale image in INPUT file and write to OUTPUT file using ImageMagick."
1421 (call-process "convert" nil nil nil "-geometry" "96x48" input output))
1422
1423 (defun mh-x-image-url-cache-canonicalize (url)
1424 "Canonicalize URL.
1425 Replace the ?/ character with a ?! character and append .png."
1426 (format "%s/%s.png" mh-x-image-cache-directory
1427 (with-temp-buffer
1428 (insert url)
1429 (mh-replace-string "/" "!")
1430 (buffer-string))))
1431
1432 (defun mh-x-image-set-download-state (file data)
1433 "Setup a symbolic link from FILE to DATA."
1434 (if data
1435 (make-symbolic-link (symbol-name data) file t)
1436 (delete-file file)))
1437
1438 (defun mh-x-image-get-download-state (file)
1439 "Check the state of FILE by following any symbolic links."
1440 (unless (file-exists-p mh-x-image-cache-directory)
1441 (call-process "mkdir" nil nil nil mh-x-image-cache-directory))
1442 (cond ((file-symlink-p file)
1443 (intern (file-name-nondirectory (file-chase-links file))))
1444 ((not (file-exists-p file)) nil)
1445 (t 'ok)))
1446
1447 (defun mh-x-image-url-fetch-image (url cache-file marker sentinel)
1448 "Fetch and display the image specified by URL.
1449 After the image is fetched, it is stored in CACHE-FILE. It will be displayed
1450 in a buffer and position specified by MARKER. The actual display is carried
1451 out by the SENTINEL function."
1452 (if mh-wget-executable
1453 (let ((buffer (get-buffer-create (generate-new-buffer-name
1454 mh-temp-fetch-buffer)))
1455 (filename (or (mh-funcall-if-exists make-temp-file "mhe-fetch")
1456 (expand-file-name (make-temp-name "~/mhe-fetch")))))
1457 (save-excursion
1458 (set-buffer buffer)
1459 (set (make-local-variable 'mh-x-image-url-cache-file) cache-file)
1460 (set (make-local-variable 'mh-x-image-marker) marker)
1461 (set (make-local-variable 'mh-x-image-temp-file) filename))
1462 (set-process-sentinel
1463 (start-process "*mh-x-image-url-fetch*" buffer
1464 mh-wget-executable mh-wget-option filename url)
1465 sentinel))
1466 ;; Temporary failure
1467 (mh-x-image-set-download-state cache-file 'try-again)))
1468
1469 (defun mh-x-image-display (image marker)
1470 "Display IMAGE at MARKER."
1471 (save-excursion
1472 (set-buffer (marker-buffer marker))
1473 (let ((buffer-read-only nil)
1474 (default-enable-multibyte-characters nil)
1475 (buffer-modified-flag (buffer-modified-p)))
1476 (unwind-protect
1477 (when (and (file-readable-p image) (not (file-symlink-p image))
1478 (eq marker mh-x-image-marker))
1479 (goto-char marker)
1480 (mh-do-in-gnu-emacs
1481 (mh-funcall-if-exists insert-image (create-image image 'png)))
1482 (mh-do-in-xemacs
1483 (when (featurep 'png)
1484 (set-extent-begin-glyph
1485 (make-extent (point) (point))
1486 (make-glyph
1487 (vector 'png ':data (with-temp-buffer
1488 (insert-file-contents-literally image)
1489 (buffer-string))))))))
1490 (set-buffer-modified-p buffer-modified-flag)))))
1491
1492 (defun mh-x-image-scale-and-display (process change)
1493 "When the wget PROCESS terminates scale and display image.
1494 The argument CHANGE is ignored."
1495 (when (eq (process-status process) 'exit)
1496 (let (marker temp-file cache-filename wget-buffer)
1497 (save-excursion
1498 (set-buffer (setq wget-buffer (process-buffer process)))
1499 (setq marker mh-x-image-marker
1500 cache-filename mh-x-image-url-cache-file
1501 temp-file mh-x-image-temp-file))
1502 (cond
1503 ;; Check if we have `convert'
1504 ((eq mh-x-image-scaling-function 'ignore)
1505 (message "The `convert' program is needed to display X-Image-URL")
1506 (mh-x-image-set-download-state cache-filename 'try-again))
1507 ;; Scale fetched image
1508 ((and (funcall mh-x-image-scaling-function temp-file cache-filename)
1509 nil))
1510 ;; Attempt to display image if we have it
1511 ((file-exists-p cache-filename)
1512 (mh-x-image-display cache-filename marker))
1513 ;; We didn't find the image. Should we try to display it the next time?
1514 (t (mh-x-image-set-download-state cache-filename 'try-again)))
1515 (ignore-errors
1516 (set-marker marker nil)
1517 (delete-process process)
1518 (kill-buffer wget-buffer)
1519 (delete-file temp-file)))))
1520
1521 (defun mh-x-image-url-sane-p (url)
1522 "Check if URL is something sensible."
1523 (let ((len (length url)))
1524 (cond ((< len 5) nil)
1525 ((not (equal (substring url 0 5) "http:")) nil)
1526 ((> len 100) nil)
1527 (t t))))
1528
1529 (defun mh-x-image-url-display (url)
1530 "Display image from location URL.
1531 If the URL isn't present in the cache then it is fetched with wget."
1532 (let* ((cache-filename (mh-x-image-url-cache-canonicalize url))
1533 (state (mh-x-image-get-download-state cache-filename))
1534 (marker (set-marker (make-marker) (point))))
1535 (set (make-local-variable 'mh-x-image-marker) marker)
1536 (cond ((not (mh-x-image-url-sane-p url)))
1537 ((eq state 'ok)
1538 (mh-x-image-display cache-filename marker))
1539 ((or (not mh-wget-executable)
1540 (eq mh-x-image-scaling-function 'ignore)))
1541 ((eq state 'never))
1542 ((not mh-fetch-x-image-url)
1543 (set-marker marker nil))
1544 ((eq state 'try-again)
1545 (mh-x-image-set-download-state cache-filename nil)
1546 (mh-x-image-url-fetch-image url cache-filename marker
1547 'mh-x-image-scale-and-display))
1548 ((and (eq mh-fetch-x-image-url 'ask)
1549 (not (y-or-n-p (format "Fetch %s? " url))))
1550 (mh-x-image-set-download-state cache-filename 'never))
1551 ((eq state nil)
1552 (mh-x-image-url-fetch-image url cache-filename marker
1553 'mh-x-image-scale-and-display)))))
1554
1555 \f
1556
1557 (defun mh-maybe-show (&optional msg)
1558 "Display message at cursor, but only if in show mode.
1559 If optional arg MSG is non-nil, display that message instead."
1560 (if mh-showing-mode (mh-show msg)))
1561
1562 (defun mh-show (&optional message redisplay-flag)
1563 "Show message at cursor.
1564 If optional argument MESSAGE is non-nil, display that message instead.
1565 Force a two-window display with the folder window on top (size given by the
1566 variable `mh-summary-height') and the show buffer below it.
1567 If the message is already visible, display the start of the message.
1568
1569 If REDISPLAY-FLAG is non-nil, the default when called interactively, the
1570 message is redisplayed even if the show buffer was already displaying the
1571 correct message.
1572
1573 Display of the message is controlled by setting the variables
1574 `mh-clean-message-header-flag' and `mhl-formfile'. The default behavior is
1575 to scroll uninteresting headers off the top of the window.
1576 Type \"\\[mh-header-display]\" to see the message with all its headers."
1577 (interactive (list nil t))
1578 (when (or redisplay-flag
1579 (and mh-showing-with-headers
1580 (or mhl-formfile mh-clean-message-header-flag)))
1581 (mh-invalidate-show-buffer))
1582 (mh-show-msg message))
1583
1584 (defun mh-show-mouse (event)
1585 "Move point to mouse EVENT and show message."
1586 (interactive "e")
1587 (mouse-set-point event)
1588 (mh-show))
1589
1590 (defun mh-summary-height ()
1591 "Return ideal value for the variable `mh-summary-height'.
1592 The current frame height is taken into consideration."
1593 (or (and (fboundp 'frame-height)
1594 (> (frame-height) 24)
1595 (min 10 (/ (frame-height) 6)))
1596 4))
1597
1598 (defun mh-show-msg (msg)
1599 "Show MSG.
1600 The value of `mh-show-hook' is a list of functions to be called, with no
1601 arguments, after the message has been displayed."
1602 (if (not msg)
1603 (setq msg (mh-get-msg-num t)))
1604 (mh-showing-mode t)
1605 (setq mh-page-to-next-msg-flag nil)
1606 (let ((folder mh-current-folder)
1607 (folders (list mh-current-folder))
1608 (clean-message-header mh-clean-message-header-flag)
1609 (show-window (get-buffer-window mh-show-buffer))
1610 (display-mime-buttons-flag mh-display-buttons-for-inline-parts-flag))
1611 (if (not (eq (next-window (minibuffer-window)) (selected-window)))
1612 (delete-other-windows)) ; force ourself to the top window
1613 (mh-in-show-buffer (mh-show-buffer)
1614 (setq mh-display-buttons-for-inline-parts-flag display-mime-buttons-flag)
1615 (if (and show-window
1616 (equal (mh-msg-filename msg folder) buffer-file-name))
1617 (progn ;just back up to start
1618 (goto-char (point-min))
1619 (if (not clean-message-header)
1620 (mh-start-of-uncleaned-message)))
1621 (mh-display-msg msg folder)))
1622 (if (not (= (1+ (window-height)) (frame-height))) ;not horizontally split
1623 (shrink-window (- (window-height) (or mh-summary-height
1624 (mh-summary-height)))))
1625 (mh-recenter nil)
1626 ;; The following line is a nop which forces update of the scan line so
1627 ;; that font-lock will update it (if needed)...
1628 (mh-notate nil nil mh-cmd-note)
1629 (if (not (memq msg mh-seen-list))
1630 (setq mh-seen-list (cons msg mh-seen-list)))
1631 (when mh-update-sequences-after-mh-show-flag
1632 (mh-update-sequences)
1633 (when mh-index-data
1634 (setq folders
1635 (append (mh-index-delete-from-sequence mh-unseen-seq (list msg))
1636 folders)))
1637 (when (mh-speed-flists-active-p)
1638 (apply #'mh-speed-flists t folders)))
1639 (run-hooks 'mh-show-hook)))
1640
1641 (defun mh-modify (&optional message)
1642 "Edit message at cursor.
1643 If optional argument MESSAGE is non-nil, edit that message instead.
1644 Force a two-window display with the folder window on top (size given by the
1645 value of the variable `mh-summary-height') and the message editing buffer below
1646 it.
1647
1648 The message is displayed in raw form."
1649 (interactive)
1650 (let* ((message (or message (mh-get-msg-num t)))
1651 (msg-filename (mh-msg-filename message))
1652 edit-buffer)
1653 (when (not (file-exists-p msg-filename))
1654 (error "Message %d does not exist" message))
1655
1656 ;; Invalidate the show buffer if it is showing the same message that is
1657 ;; to be edited.
1658 (when (and (buffer-live-p (get-buffer mh-show-buffer))
1659 (equal (save-excursion (set-buffer mh-show-buffer)
1660 buffer-file-name)
1661 msg-filename))
1662 (mh-invalidate-show-buffer))
1663
1664 ;; Edit message
1665 (find-file msg-filename)
1666 (setq edit-buffer (current-buffer))
1667
1668 ;; Set buffer properties
1669 (mh-letter-mode)
1670 (use-local-map text-mode-map)
1671
1672 ;; Just show the edit buffer...
1673 (delete-other-windows)
1674 (switch-to-buffer edit-buffer)))
1675
1676 (defun mh-show-unquote-From ()
1677 "Decode >From at beginning of lines for `mh-show-mode'."
1678 (save-excursion
1679 (let ((modified (buffer-modified-p))
1680 (case-fold-search nil)
1681 (buffer-read-only nil))
1682 (goto-char (mh-mail-header-end))
1683 (while (re-search-forward "^>From" nil t)
1684 (replace-match "From"))
1685 (set-buffer-modified-p modified))))
1686
1687 (defun mh-msg-folder (folder-name)
1688 "Return the name of the buffer for FOLDER-NAME."
1689 folder-name)
1690
1691 (defun mh-display-msg (msg-num folder-name)
1692 "Display MSG-NUM of FOLDER-NAME.
1693 Sets the current buffer to the show buffer."
1694 (let ((folder (mh-msg-folder folder-name)))
1695 (set-buffer folder)
1696 ;; When Gnus uses external displayers it has to keep handles longer. So
1697 ;; we will delete these handles when mh-quit is called on the folder. It
1698 ;; would be nicer if there are weak pointers in emacs lisp, then we could
1699 ;; get the garbage collector to do this for us.
1700 (unless (mh-buffer-data)
1701 (setf (mh-buffer-data) (mh-make-buffer-data)))
1702 ;; Bind variables in folder buffer in case they are local
1703 (let ((formfile mhl-formfile)
1704 (clean-message-header mh-clean-message-header-flag)
1705 (invisible-headers mh-invisible-header-fields-compiled)
1706 (visible-headers nil)
1707 (msg-filename (mh-msg-filename msg-num folder-name))
1708 (show-buffer mh-show-buffer)
1709 (mm-inline-media-tests mh-mm-inline-media-tests))
1710 (if (not (file-exists-p msg-filename))
1711 (error "Message %d does not exist" msg-num))
1712 (if (and (> mh-show-maximum-size 0)
1713 (> (elt (file-attributes msg-filename) 7)
1714 mh-show-maximum-size)
1715 (not (y-or-n-p
1716 (format
1717 "Message %d (%d bytes) exceeds %d bytes. Display it? "
1718 msg-num (elt (file-attributes msg-filename) 7)
1719 mh-show-maximum-size))))
1720 (error "Message %d not displayed" msg-num))
1721 (set-buffer show-buffer)
1722 (cond ((not (equal msg-filename buffer-file-name))
1723 (mh-unvisit-file)
1724 (setq buffer-read-only nil)
1725 ;; Cleanup old mime handles
1726 (mh-mime-cleanup)
1727 (erase-buffer)
1728 ;; Changing contents, so this hook needs to be reinitialized.
1729 ;; pgp.el uses this.
1730 (if (boundp 'write-contents-hooks) ;Emacs 19
1731 (kill-local-variable 'write-contents-hooks))
1732 (if formfile
1733 (mh-exec-lib-cmd-output "mhl" "-nobell" "-noclear"
1734 (if (stringp formfile)
1735 (list "-form" formfile))
1736 msg-filename)
1737 (insert-file-contents-literally msg-filename))
1738 ;; Use mm to display buffer
1739 (when (and mh-decode-mime-flag (not formfile))
1740 (mh-add-missing-mime-version-header)
1741 (setf (mh-buffer-data) (mh-make-buffer-data))
1742 (mh-mime-display))
1743 (mh-show-mode)
1744 ;; Header cleanup
1745 (goto-char (point-min))
1746 (cond (clean-message-header
1747 (mh-clean-msg-header (point-min)
1748 invisible-headers
1749 visible-headers)
1750 (goto-char (point-min)))
1751 (t
1752 (mh-start-of-uncleaned-message)))
1753 (mh-decode-message-header)
1754 ;; the parts of visiting we want to do (no locking)
1755 (or (eq buffer-undo-list t) ;don't save undo info for prev msgs
1756 (setq buffer-undo-list nil))
1757 (set-buffer-auto-saved)
1758 ;; the parts of set-visited-file-name we want to do (no locking)
1759 (setq buffer-file-name msg-filename)
1760 (setq buffer-backed-up nil)
1761 (auto-save-mode 1)
1762 (set-mark nil)
1763 (unwind-protect
1764 (when (and mh-decode-mime-flag (not formfile))
1765 (setq buffer-read-only nil)
1766 (mh-display-smileys)
1767 (mh-display-emphasis))
1768 (setq buffer-read-only t))
1769 (set-buffer-modified-p nil)
1770 (setq mh-show-folder-buffer folder)
1771 (setq mode-line-buffer-identification
1772 (list (format mh-show-buffer-mode-line-buffer-id
1773 folder-name msg-num)))
1774 (mh-logo-display)
1775 (set-buffer folder)
1776 (setq mh-showing-with-headers nil))))))
1777
1778 (defun mh-clean-msg-header (start invisible-headers visible-headers)
1779 "Flush extraneous lines in message header.
1780 Header is cleaned from START to the end of the message header.
1781 INVISIBLE-HEADERS contains a regular expression specifying lines to delete
1782 from the header. VISIBLE-HEADERS contains a regular expression specifying the
1783 lines to display. INVISIBLE-HEADERS is ignored if VISIBLE-HEADERS is non-nil.
1784
1785 Note that MH-E no longer supports the `mh-visible-headers' variable, so
1786 this function could be trimmed of this feature too."
1787 (let ((case-fold-search t)
1788 (buffer-read-only nil)
1789 (after-change-functions nil)) ;Work around emacs-20 font-lock bug
1790 ;causing an endless loop.
1791 (save-restriction
1792 (goto-char start)
1793 (if (search-forward "\n\n" nil 'move)
1794 (backward-char 1))
1795 (narrow-to-region start (point))
1796 (goto-char (point-min))
1797 (if visible-headers
1798 (while (< (point) (point-max))
1799 (cond ((looking-at visible-headers)
1800 (forward-line 1)
1801 (while (looking-at "[ \t]") (forward-line 1)))
1802 (t
1803 (mh-delete-line 1)
1804 (while (looking-at "[ \t]")
1805 (mh-delete-line 1)))))
1806 (while (re-search-forward invisible-headers nil t)
1807 (beginning-of-line)
1808 (mh-delete-line 1)
1809 (while (looking-at "[ \t]")
1810 (mh-delete-line 1)))))
1811 (let ((mh-compose-skipped-header-fields ()))
1812 (mh-letter-hide-all-skipped-fields))
1813 (unlock-buffer)))
1814
1815 (defun mh-delete-line (lines)
1816 "Delete the next LINES lines."
1817 (delete-region (point) (progn (forward-line lines) (point))))
1818
1819 (defun mh-notate (msg notation offset)
1820 "Mark MSG with the character NOTATION at position OFFSET.
1821 Null MSG means the message at cursor.
1822 If NOTATION is nil then no change in the buffer occurs."
1823 (save-excursion
1824 (if (or (null msg)
1825 (mh-goto-msg msg t t))
1826 (with-mh-folder-updating (t)
1827 (beginning-of-line)
1828 (forward-char offset)
1829 (let* ((change-stack-flag
1830 (and (equal offset
1831 (+ mh-cmd-note mh-scan-field-destination-offset))
1832 (not (eq notation mh-note-seq))))
1833 (msg (and change-stack-flag (or msg (mh-get-msg-num nil))))
1834 (stack (and msg (gethash msg mh-sequence-notation-history)))
1835 (notation (or notation (char-after))))
1836 (if stack
1837 ;; The presence of the stack tells us that we don't need to
1838 ;; notate the message, since the notation would be replaced
1839 ;; by a sequence notation. So we will just put the notation
1840 ;; at the bottom of the stack. If the sequence is deleted,
1841 ;; the correct notation will be shown.
1842 (setf (gethash msg mh-sequence-notation-history)
1843 (reverse (cons notation (cdr (reverse stack)))))
1844 ;; Since we don't have any sequence notations in the way, just
1845 ;; notate the scan line.
1846 (delete-char 1)
1847 (insert notation))
1848 (when change-stack-flag
1849 (mh-thread-update-scan-line-map msg notation offset)))))))
1850
1851 (defun mh-goto-msg (number &optional no-error-if-no-message dont-show)
1852 "Position the cursor at message NUMBER.
1853 Optional non-nil second argument NO-ERROR-IF-NO-MESSAGE means return nil
1854 instead of signaling an error if message does not exist; in this case, the
1855 cursor is positioned near where the message would have been.
1856 Non-nil third argument DONT-SHOW means not to show the message."
1857 (interactive "NGo to message: ")
1858 (setq number (prefix-numeric-value number))
1859 (let ((point (point))
1860 (return-value t))
1861 (goto-char (point-min))
1862 (unless (re-search-forward (format mh-scan-msg-search-regexp number) nil t)
1863 (goto-char point)
1864 (unless no-error-if-no-message
1865 (error "No message %d" number))
1866 (setq return-value nil))
1867 (beginning-of-line)
1868 (or dont-show (not return-value) (mh-maybe-show number))
1869 return-value))
1870
1871 (defun mh-get-profile-field (field)
1872 "Find and return the value of FIELD in the current buffer.
1873 Returns nil if the field is not in the buffer."
1874 (let ((case-fold-search t))
1875 (goto-char (point-min))
1876 (cond ((not (re-search-forward (format "^%s" field) nil t)) nil)
1877 ((looking-at "[\t ]*$") nil)
1878 (t
1879 (re-search-forward "[\t ]*\\([^\t \n].*\\)$" nil t)
1880 (let ((start (match-beginning 1)))
1881 (end-of-line)
1882 (buffer-substring start (point)))))))
1883
1884 (defvar mh-find-path-run nil
1885 "Non-nil if `mh-find-path' has been run already.")
1886
1887 (defun mh-find-path ()
1888 "Set variables from user's MH profile.
1889 Set `mh-user-path', `mh-draft-folder', `mh-unseen-seq', `mh-previous-seq',
1890 `mh-inbox' from user's MH profile.
1891 The value of `mh-find-path-hook' is a list of functions to be called, with no
1892 arguments, after these variable have been set."
1893 (mh-variants)
1894 (unless mh-find-path-run
1895 (setq mh-find-path-run t)
1896 (save-excursion
1897 ;; Be sure profile is fully expanded before switching buffers
1898 (let ((profile (expand-file-name (or (getenv "MH") "~/.mh_profile"))))
1899 (set-buffer (get-buffer-create mh-temp-buffer))
1900 (setq buffer-offer-save nil) ;for people who set default to t
1901 (erase-buffer)
1902 (condition-case err
1903 (insert-file-contents profile)
1904 (file-error
1905 (mh-install profile err)))
1906 (setq mh-user-path (mh-get-profile-field "Path:"))
1907 (if (not mh-user-path)
1908 (setq mh-user-path "Mail"))
1909 (setq mh-user-path
1910 (file-name-as-directory
1911 (expand-file-name mh-user-path (expand-file-name "~"))))
1912 (unless mh-x-image-cache-directory
1913 (setq mh-x-image-cache-directory
1914 (expand-file-name ".mhe-x-image-cache" mh-user-path)))
1915 (setq mh-draft-folder (mh-get-profile-field "Draft-Folder:"))
1916 (if mh-draft-folder
1917 (progn
1918 (if (not (mh-folder-name-p mh-draft-folder))
1919 (setq mh-draft-folder (format "+%s" mh-draft-folder)))
1920 (if (not (file-exists-p (mh-expand-file-name mh-draft-folder)))
1921 (error
1922 "Draft folder \"%s\" not found. Create it and try again"
1923 (mh-expand-file-name mh-draft-folder)))))
1924 (setq mh-inbox (mh-get-profile-field "Inbox:"))
1925 (cond ((not mh-inbox)
1926 (setq mh-inbox "+inbox"))
1927 ((not (mh-folder-name-p mh-inbox))
1928 (setq mh-inbox (format "+%s" mh-inbox))))
1929 (setq mh-unseen-seq (mh-get-profile-field "Unseen-Sequence:"))
1930 (if mh-unseen-seq
1931 (setq mh-unseen-seq (intern mh-unseen-seq))
1932 (setq mh-unseen-seq 'unseen)) ;old MH default?
1933 (setq mh-previous-seq (mh-get-profile-field "Previous-Sequence:"))
1934 (if mh-previous-seq
1935 (setq mh-previous-seq (intern mh-previous-seq)))
1936 (run-hooks 'mh-find-path-hook)
1937 (mh-collect-folder-names)))))
1938
1939 (defun mh-file-command-p (file)
1940 "Return t if file FILE is the name of a executable regular file."
1941 (and (file-regular-p file) (file-executable-p file)))
1942
1943 (defvar mh-no-install nil) ;do not run install-mh
1944
1945 (defun mh-install (profile error-val)
1946 "Initialize the MH environment.
1947 This is called if we fail to read the PROFILE file. ERROR-VAL is the error
1948 that made this call necessary."
1949 (if (or (getenv "MH")
1950 (file-exists-p profile)
1951 mh-no-install)
1952 (signal (car error-val)
1953 (list (format "Cannot read MH profile \"%s\"" profile)
1954 (car (cdr (cdr error-val))))))
1955 ;; The "install-mh" command will output a short note which
1956 ;; mh-exec-cmd will display to the user.
1957 ;; The MH 5 version of install-mh might try prompt the user
1958 ;; for information, which would fail here.
1959 (mh-exec-cmd (expand-file-name "install-mh" mh-lib-progs) "-auto")
1960 ;; now try again to read the profile file
1961 (erase-buffer)
1962 (condition-case err
1963 (insert-file-contents profile)
1964 (file-error
1965 (signal (car err) ;re-signal with more specific msg
1966 (list (format "Cannot read MH profile \"%s\"" profile)
1967 (car (cdr (cdr err))))))))
1968
1969 (defun mh-set-folder-modified-p (flag)
1970 "Mark current folder as modified or unmodified according to FLAG."
1971 (set-buffer-modified-p flag))
1972
1973 (defun mh-find-seq (name)
1974 "Return sequence NAME."
1975 (assoc name mh-seq-list))
1976
1977 (defun mh-seq-to-msgs (seq)
1978 "Return a list of the messages in SEQ."
1979 (mh-seq-msgs (mh-find-seq seq)))
1980
1981 (defun mh-update-scan-format (fmt width)
1982 "Return a scan format with the (msg) width in the FMT replaced with WIDTH.
1983
1984 The message number width portion of the format is discovered using
1985 `mh-scan-msg-format-regexp'. Its replacement is controlled with
1986 `mh-scan-msg-format-string'."
1987 (or (and
1988 (string-match mh-scan-msg-format-regexp fmt)
1989 (let ((begin (match-beginning 1))
1990 (end (match-end 1)))
1991 (concat (substring fmt 0 begin)
1992 (format mh-scan-msg-format-string width)
1993 (substring fmt end))))
1994 fmt))
1995
1996 (defun mh-msg-num-width (folder)
1997 "Return the width of the largest message number in this FOLDER."
1998 (or mh-progs (mh-find-path))
1999 (let ((tmp-buffer (get-buffer-create mh-temp-buffer))
2000 (width 0))
2001 (save-excursion
2002 (set-buffer tmp-buffer)
2003 (erase-buffer)
2004 (apply 'call-process
2005 (expand-file-name mh-scan-prog mh-progs) nil '(t nil) nil
2006 (list folder "last" "-format" "%(msg)"))
2007 (goto-char (point-min))
2008 (if (re-search-forward mh-scan-msg-number-regexp nil 0 1)
2009 (setq width (length (buffer-substring
2010 (match-beginning 1) (match-end 1))))))
2011 width))
2012
2013 (defun mh-add-msgs-to-seq (msgs seq &optional internal-flag dont-annotate-flag)
2014 "Add MSGS to SEQ.
2015 Remove duplicates and keep sequence sorted. If optional INTERNAL-FLAG is
2016 non-nil, do not mark the message in the scan listing or inform MH of the
2017 addition.
2018
2019 If DONT-ANNOTATE-FLAG is non-nil then the annotations in the folder buffer are
2020 not updated."
2021 (let ((entry (mh-find-seq seq))
2022 (internal-seq-flag (mh-internal-seq seq)))
2023 (if (and msgs (atom msgs)) (setq msgs (list msgs)))
2024 (if (null entry)
2025 (setq mh-seq-list
2026 (cons (mh-make-seq seq (mh-canonicalize-sequence msgs))
2027 mh-seq-list))
2028 (if msgs (setcdr entry (mh-canonicalize-sequence
2029 (append msgs (mh-seq-msgs entry))))))
2030 (unless internal-flag
2031 (mh-add-to-sequence seq msgs)
2032 (when (not dont-annotate-flag)
2033 (mh-iterate-on-range msg msgs
2034 (unless (memq msg (cdr entry))
2035 (mh-add-sequence-notation msg internal-seq-flag)))))))
2036
2037 (defun mh-canonicalize-sequence (msgs)
2038 "Sort MSGS in decreasing order and remove duplicates."
2039 (let* ((sorted-msgs (sort (copy-sequence msgs) '>))
2040 (head sorted-msgs))
2041 (while (cdr head)
2042 (if (= (car head) (cadr head))
2043 (setcdr head (cddr head))
2044 (setq head (cdr head))))
2045 sorted-msgs))
2046
2047 (defvar mh-sub-folders-cache (make-hash-table :test #'equal))
2048 (defvar mh-current-folder-name nil)
2049 (defvar mh-flists-partial-line "")
2050 (defvar mh-flists-process nil)
2051
2052 ;; Initialize mh-sub-folders-cache...
2053 (defun mh-collect-folder-names ()
2054 "Collect folder names by running `flists'."
2055 (unless mh-flists-process
2056 (setq mh-flists-process
2057 (mh-exec-cmd-daemon "folders" 'mh-collect-folder-names-filter
2058 "-recurse" "-fast"))))
2059
2060 (defun mh-collect-folder-names-filter (process output)
2061 "Read folder names.
2062 PROCESS is the flists process that was run to collect folder names and the
2063 function is called when OUTPUT is available."
2064 (let ((position 0)
2065 (prevailing-match-data (match-data))
2066 line-end folder)
2067 (unwind-protect
2068 (while (setq line-end (string-match "\n" output position))
2069 (setq folder (format "+%s%s"
2070 mh-flists-partial-line
2071 (substring output position line-end)))
2072 (setq mh-flists-partial-line "")
2073 (unless (equal (aref folder 1) ?.)
2074 (mh-populate-sub-folders-cache folder))
2075 (setq position (1+ line-end)))
2076 (set-match-data prevailing-match-data))
2077 (setq mh-flists-partial-line (substring output position))))
2078
2079 (defun mh-populate-sub-folders-cache (folder)
2080 "Tell `mh-sub-folders-cache' about FOLDER."
2081 (let* ((last-slash (mh-search-from-end ?/ folder))
2082 (child1 (substring folder (1+ (or last-slash 0))))
2083 (parent (and last-slash (substring folder 0 last-slash)))
2084 (parent-slash (and parent (mh-search-from-end ?/ parent)))
2085 (child2 (and parent (substring parent (1+ (or parent-slash 0)))))
2086 (grand-parent (and parent-slash (substring parent 0 parent-slash)))
2087 (cache-entry (gethash parent mh-sub-folders-cache)))
2088 (unless (loop for x in cache-entry when (equal (car x) child1) return t
2089 finally return nil)
2090 (push (list child1) cache-entry)
2091 (setf (gethash parent mh-sub-folders-cache)
2092 (sort cache-entry (lambda (x y) (string< (car x) (car y)))))
2093 (when parent
2094 (loop for x in (gethash grand-parent mh-sub-folders-cache)
2095 when (equal (car x) child2)
2096 do (progn (setf (cdr x) t) (return)))))))
2097
2098 (defun mh-normalize-folder-name (folder &optional empty-string-okay
2099 dont-remove-trailing-slash)
2100 "Normalizes FOLDER name.
2101 Makes sure that two '/' characters never occur next to each other. Also all
2102 occurrences of \"..\" and \".\" are suitably processed. So \"+inbox/../news\"
2103 will be normalized to \"+news\".
2104
2105 If optional argument EMPTY-STRING-OKAY is nil then a '+' is added at the
2106 front if FOLDER lacks one. If non-nil and FOLDER is the empty string then
2107 nothing is added.
2108
2109 If optional argument DONT-REMOVE-TRAILING-SLASH is non-nil then a trailing '/'
2110 if present is retained (if present), otherwise it is removed."
2111 (when (stringp folder)
2112 ;; Replace two or more consecutive '/' characters with a single '/'
2113 (while (string-match "//" folder)
2114 (setq folder (replace-match "/" nil t folder)))
2115 (let* ((length (length folder))
2116 (trailing-slash-present (and (> length 0)
2117 (equal (aref folder (1- length)) ?/)))
2118 (leading-slash-present (and (> length 0)
2119 (equal (aref folder 0) ?/))))
2120 (when (and (> length 0) (equal (aref folder 0) ?@)
2121 (stringp mh-current-folder-name))
2122 (setq folder (format "%s/%s/" mh-current-folder-name
2123 (substring folder 1))))
2124 ;; XXX: Purge empty strings from the list that split-string returns. In
2125 ;; XEmacs, (split-string "+foo/" "/") returns ("+foo" "") while in GNU
2126 ;; Emacs it returns ("+foo"). In the code it is assumed that the
2127 ;; components list has no empty strings.
2128 (let ((components (delete "" (split-string folder "/")))
2129 (result ()))
2130 ;; Remove .. and . from the pathname.
2131 (dolist (component components)
2132 (cond ((and (equal component "..") result)
2133 (pop result))
2134 ((equal component ".."))
2135 ((equal component "."))
2136 (t (push component result))))
2137 (setq folder "")
2138 (dolist (component result)
2139 (setq folder (concat component "/" folder)))
2140 ;; Remove trailing '/' if needed.
2141 (unless (and trailing-slash-present dont-remove-trailing-slash)
2142 (when (not (equal folder ""))
2143 (setq folder (substring folder 0 (1- (length folder))))))
2144 (when leading-slash-present
2145 (setq folder (concat "/" folder)))))
2146 (cond ((and empty-string-okay (equal folder "")))
2147 ((equal folder "") (setq folder "+"))
2148 ((not (equal (aref folder 0) ?+)) (setq folder (concat "+" folder)))))
2149 folder)
2150
2151 (defun mh-sub-folders (folder &optional add-trailing-slash-flag)
2152 "Find the subfolders of FOLDER.
2153 The function avoids running folders unnecessarily by caching the results of
2154 the actual folders call.
2155
2156 If optional argument ADD-TRAILING-SLASH-FLAG is non-nil then a slash is added
2157 to each of the sub-folder names that may have nested folders within them."
2158 (let* ((folder (mh-normalize-folder-name folder))
2159 (match (gethash folder mh-sub-folders-cache 'no-result))
2160 (sub-folders (cond ((eq match 'no-result)
2161 (setf (gethash folder mh-sub-folders-cache)
2162 (mh-sub-folders-actual folder)))
2163 (t match))))
2164 (if add-trailing-slash-flag
2165 (mapcar #'(lambda (x)
2166 (if (cdr x) (cons (concat (car x) "/") (cdr x)) x))
2167 sub-folders)
2168 sub-folders)))
2169
2170 (defun mh-sub-folders-actual (folder)
2171 "Execute the command folders to return the sub-folders of FOLDER.
2172 Filters out the folder names that start with \".\" so that directories that
2173 aren't usually mail folders are hidden."
2174 (let ((arg-list `(,(expand-file-name "folders" mh-progs)
2175 nil (t nil) nil "-noheader" "-norecurse" "-nototal"
2176 ,@(if (stringp folder) (list folder) ())))
2177 (results ())
2178 (current-folder (concat
2179 (with-temp-buffer
2180 (call-process (expand-file-name "folder" mh-progs)
2181 nil '(t nil) nil "-fast")
2182 (buffer-substring (point-min) (1- (point-max))))
2183 "+")))
2184 (with-temp-buffer
2185 (apply #'call-process arg-list)
2186 (goto-char (point-min))
2187 (while (not (and (eolp) (bolp)))
2188 (goto-char (line-end-position))
2189 (let ((start-pos (line-beginning-position))
2190 (has-pos (search-backward " has " (line-beginning-position) t)))
2191 (when (integerp has-pos)
2192 (while (equal (char-after has-pos) ? )
2193 (decf has-pos))
2194 (incf has-pos)
2195 (while (equal (char-after start-pos) ? )
2196 (incf start-pos))
2197 (let* ((name (buffer-substring start-pos has-pos))
2198 (first-char (aref name 0))
2199 (last-char (aref name (1- (length name)))))
2200 (unless (member first-char '(?. ?# ?,))
2201 (when (and (equal last-char ?+) (equal name current-folder))
2202 (setq name (substring name 0 (1- (length name)))))
2203 (push
2204 (cons name
2205 (search-forward "(others)" (line-end-position) t))
2206 results))))
2207 (forward-line 1))))
2208 (setq results (nreverse results))
2209 (when (stringp folder)
2210 (setq results (cdr results))
2211 (let ((folder-name-len (length (format "%s/" (substring folder 1)))))
2212 (setq results (mapcar (lambda (f)
2213 (cons (substring (car f) folder-name-len)
2214 (cdr f)))
2215 results))))
2216 results))
2217
2218 (defun mh-remove-from-sub-folders-cache (folder)
2219 "Remove FOLDER and its parent from `mh-sub-folders-cache'.
2220 FOLDER should be unconditionally removed from the cache. Also the last ancestor
2221 of FOLDER present in the cache must be removed as well.
2222
2223 To see why this is needed assume we have a folder +foo which has a single
2224 sub-folder qux. Now we create the folder +foo/bar/baz. Here we will need to
2225 invalidate the cached sub-folders of +foo, otherwise completion on +foo won't
2226 tell us about the option +foo/bar!"
2227 (remhash folder mh-sub-folders-cache)
2228 (block ancestor-found
2229 (let ((parent folder)
2230 (one-ancestor-found nil)
2231 last-slash)
2232 (while (setq last-slash (mh-search-from-end ?/ parent))
2233 (setq parent (substring parent 0 last-slash))
2234 (unless (eq (gethash parent mh-sub-folders-cache 'none) 'none)
2235 (remhash parent mh-sub-folders-cache)
2236 (if one-ancestor-found
2237 (return-from ancestor-found)
2238 (setq one-ancestor-found t))))
2239 (remhash nil mh-sub-folders-cache))))
2240
2241 (defvar mh-folder-hist nil)
2242 (defvar mh-speed-folder-map)
2243 (defvar mh-speed-flists-cache)
2244
2245 (defvar mh-allow-root-folder-flag nil
2246 "Non-nil means \"+\" is an acceptable folder name.
2247 This variable is used to communicate with `mh-folder-completion-function'. That
2248 function can have exactly three arguments so we bind this variable to t or nil.
2249
2250 This variable should never be set.")
2251
2252 (defvar mh-folder-completion-map (copy-keymap minibuffer-local-completion-map))
2253 (define-key mh-folder-completion-map " " 'minibuffer-complete)
2254
2255 (defvar mh-speed-flists-inhibit-flag nil)
2256
2257 (defun mh-speed-flists-active-p ()
2258 "Check if speedbar is running with message counts enabled."
2259 (and (featurep 'mh-speed)
2260 (not mh-speed-flists-inhibit-flag)
2261 (> (hash-table-count mh-speed-flists-cache) 0)))
2262
2263 (defun mh-folder-completion-function (name predicate flag)
2264 "Programmable completion for folder names.
2265 NAME is the partial folder name that has been input. PREDICATE if non-nil is a
2266 function that is used to filter the possible choices and FLAG determines
2267 whether the completion is over."
2268 (let* ((orig-name name)
2269 (name (mh-normalize-folder-name name nil t))
2270 (last-slash (mh-search-from-end ?/ name))
2271 (last-complete (if last-slash (substring name 0 last-slash) nil))
2272 (remainder (cond (last-complete (substring name (1+ last-slash)))
2273 ((and (> (length name) 0) (equal (aref name 0) ?+))
2274 (substring name 1))
2275 (t ""))))
2276 (cond ((eq flag nil)
2277 (let ((try-res (try-completion
2278 name
2279 (mapcar (lambda (x)
2280 (cons (if (not last-complete)
2281 (concat "+" (car x))
2282 (concat last-complete "/" (car x)))
2283 (cdr x)))
2284 (mh-sub-folders last-complete t))
2285 predicate)))
2286 (cond ((eq try-res nil) nil)
2287 ((and (eq try-res t) (equal name orig-name)) t)
2288 ((eq try-res t) name)
2289 (t try-res))))
2290 ((eq flag t)
2291 (all-completions
2292 remainder (mh-sub-folders last-complete t) predicate))
2293 ((eq flag 'lambda)
2294 (let ((path (concat mh-user-path
2295 (substring (mh-normalize-folder-name name) 1))))
2296 (cond (mh-allow-root-folder-flag (file-exists-p path))
2297 ((equal path mh-user-path) nil)
2298 (t (file-exists-p path))))))))
2299
2300 (defun mh-folder-completing-read (prompt default allow-root-folder-flag)
2301 "Read folder name with PROMPT and default result DEFAULT.
2302 If ALLOW-ROOT-FOLDER-FLAG is non-nil then \"+\" is allowed to be a folder name
2303 corresponding to `mh-user-path'."
2304 (mh-normalize-folder-name
2305 (let ((minibuffer-completing-file-name t)
2306 (completion-root-regexp "^[+/]")
2307 (minibuffer-local-completion-map mh-folder-completion-map)
2308 (mh-allow-root-folder-flag allow-root-folder-flag))
2309 (completing-read prompt 'mh-folder-completion-function nil nil nil
2310 'mh-folder-hist default))
2311 t))
2312
2313 (defun mh-prompt-for-folder (prompt default can-create
2314 &optional default-string allow-root-folder-flag)
2315 "Prompt for a folder name with PROMPT.
2316 Returns the folder's name as a string. DEFAULT is used if the folder exists
2317 and the user types return. If the CAN-CREATE flag is t, then a folder is
2318 created if it doesn't already exist. If optional argument DEFAULT-STRING is
2319 non-nil, use it in the prompt instead of DEFAULT. If ALLOW-ROOT-FOLDER-FLAG is
2320 non-nil then the function will accept the folder +, which means all folders
2321 when used in searching."
2322 (if (null default)
2323 (setq default ""))
2324 (let* ((default-string (cond (default-string (format " (default %s)" default-string))
2325 ((equal "" default) "")
2326 (t (format " (default %s)" default))))
2327 (prompt (format "%s folder%s: " prompt default-string))
2328 (mh-current-folder-name mh-current-folder)
2329 read-name folder-name)
2330 (while (and (setq read-name (mh-folder-completing-read
2331 prompt default allow-root-folder-flag))
2332 (equal read-name "")
2333 (equal default "")))
2334 (cond ((or (equal read-name "")
2335 (and (equal read-name "+") (not allow-root-folder-flag)))
2336 (setq read-name default))
2337 ((not (mh-folder-name-p read-name))
2338 (setq read-name (format "+%s" read-name))))
2339 (if (or (not read-name) (equal "" read-name))
2340 (error "No folder specified"))
2341 (setq folder-name read-name)
2342 (cond ((and (> (length folder-name) 0)
2343 (eq (aref folder-name (1- (length folder-name))) ?/))
2344 (setq folder-name (substring folder-name 0 -1))))
2345 (let* ((last-slash (mh-search-from-end ?/ folder-name))
2346 (parent (and last-slash (substring folder-name 0 last-slash)))
2347 (child (if last-slash
2348 (substring folder-name (1+ last-slash))
2349 (substring folder-name 1))))
2350 (unless (member child
2351 (mapcar #'car (gethash parent mh-sub-folders-cache)))
2352 (mh-remove-from-sub-folders-cache folder-name)))
2353 (let ((new-file-flag
2354 (not (file-exists-p (mh-expand-file-name folder-name)))))
2355 (cond ((and new-file-flag
2356 (y-or-n-p
2357 (format "Folder %s does not exist. Create it? "
2358 folder-name)))
2359 (message "Creating %s" folder-name)
2360 (mh-exec-cmd-error nil "folder" folder-name)
2361 (mh-remove-from-sub-folders-cache folder-name)
2362 (when (boundp 'mh-speed-folder-map)
2363 (mh-speed-add-folder folder-name))
2364 (message "Creating %s...done" folder-name))
2365 (new-file-flag
2366 (error "Folder %s is not created" folder-name))
2367 ((not (file-directory-p (mh-expand-file-name folder-name)))
2368 (error "\"%s\" is not a directory"
2369 (mh-expand-file-name folder-name)))))
2370 folder-name))
2371
2372 (defun mh-truncate-log-buffer ()
2373 "If `mh-log-buffer' is too big then truncate it.
2374 If the number of lines in `mh-log-buffer' exceeds `mh-log-buffer-lines' then
2375 keep only the last `mh-log-buffer-lines'. As a side effect the point is set to
2376 the end of the log buffer.
2377
2378 The function returns the size of the final size of the log buffer."
2379 (with-current-buffer (get-buffer-create mh-log-buffer)
2380 (goto-char (point-max))
2381 (save-excursion
2382 (when (equal (forward-line (- mh-log-buffer-lines)) 0)
2383 (delete-region (point-min) (point))))
2384 (unless (or (bobp)
2385 (save-excursion
2386 (and (equal (forward-line -1) 0) (equal (char-after) ?\f))))
2387 (insert "\n\f\n"))
2388 (buffer-size)))
2389
2390 ;;; Issue commands to MH.
2391
2392 (defun mh-exec-cmd (command &rest args)
2393 "Execute mh-command COMMAND with ARGS.
2394 The side effects are what is desired.
2395 Any output is assumed to be an error and is shown to the user.
2396 The output is not read or parsed by MH-E."
2397 (save-excursion
2398 (set-buffer (get-buffer-create mh-log-buffer))
2399 (let* ((initial-size (mh-truncate-log-buffer))
2400 (start (point))
2401 (args (mh-list-to-string args)))
2402 (apply 'call-process (expand-file-name command mh-progs) nil t nil args)
2403 (when (> (buffer-size) initial-size)
2404 (save-excursion
2405 (goto-char start)
2406 (insert "Errors when executing: " command)
2407 (loop for arg in args do (insert " " arg))
2408 (insert "\n"))
2409 (save-window-excursion
2410 (switch-to-buffer-other-window mh-log-buffer)
2411 (sit-for 5))))))
2412
2413 (defun mh-exec-cmd-error (env command &rest args)
2414 "In environment ENV, execute mh-command COMMAND with ARGS.
2415 ENV is nil or a string of space-separated \"var=value\" elements.
2416 Signals an error if process does not complete successfully."
2417 (save-excursion
2418 (set-buffer (get-buffer-create mh-temp-buffer))
2419 (erase-buffer)
2420 (let ((process-environment process-environment))
2421 ;; XXX: We should purge the list that split-string returns of empty
2422 ;; strings. This can happen in XEmacs if leading or trailing spaces
2423 ;; are present.
2424 (dolist (elem (if (stringp env) (split-string env " ") ()))
2425 (push elem process-environment))
2426 (mh-handle-process-error
2427 command (apply #'call-process (expand-file-name command mh-progs)
2428 nil t nil (mh-list-to-string args))))))
2429
2430 (defun mh-exec-cmd-daemon (command filter &rest args)
2431 "Execute MH command COMMAND in the background.
2432
2433 If FILTER is non-nil then it is used to process the output otherwise the
2434 default filter `mh-process-daemon' is used. See `set-process-filter' for more
2435 details of FILTER.
2436
2437 ARGS are passed to COMMAND as command line arguments."
2438 (save-excursion
2439 (set-buffer (get-buffer-create mh-log-buffer))
2440 (mh-truncate-log-buffer))
2441 (let* ((process-connection-type nil)
2442 (process (apply 'start-process
2443 command nil
2444 (expand-file-name command mh-progs)
2445 (mh-list-to-string args))))
2446 (set-process-filter process (or filter 'mh-process-daemon))
2447 process))
2448
2449 (defun mh-exec-cmd-env-daemon (env command filter &rest args)
2450 "In ennvironment ENV, execute mh-command COMMAND in the background.
2451
2452 ENV is nil or a string of space-separated \"var=value\" elements.
2453 Signals an error if process does not complete successfully.
2454
2455 If FILTER is non-nil then it is used to process the output otherwise the
2456 default filter `mh-process-daemon' is used. See `set-process-filter' for more
2457 details of FILTER.
2458
2459 ARGS are passed to COMMAND as command line arguments."
2460 (let ((process-environment process-environment))
2461 (dolist (elem (if (stringp env) (split-string env " ") ()))
2462 (push elem process-environment))
2463 (apply #'mh-exec-cmd-daemon command filter args)))
2464
2465 (defun mh-process-daemon (process output)
2466 "PROCESS daemon that puts OUTPUT into a temporary buffer.
2467 Any output from the process is displayed in an asynchronous pop-up window."
2468 (set-buffer (get-buffer-create mh-log-buffer))
2469 (insert-before-markers output)
2470 (display-buffer mh-log-buffer))
2471
2472 (defun mh-exec-cmd-quiet (raise-error command &rest args)
2473 "Signal RAISE-ERROR if COMMAND with ARGS fails.
2474 Execute MH command COMMAND with ARGS. ARGS is a list of strings.
2475 Return at start of mh-temp buffer, where output can be parsed and used.
2476 Returns value of `call-process', which is 0 for success, unless RAISE-ERROR is
2477 non-nil, in which case an error is signaled if `call-process' returns non-0."
2478 (set-buffer (get-buffer-create mh-temp-buffer))
2479 (erase-buffer)
2480 (let ((value
2481 (apply 'call-process
2482 (expand-file-name command mh-progs) nil t nil
2483 args)))
2484 (goto-char (point-min))
2485 (if raise-error
2486 (mh-handle-process-error command value)
2487 value)))
2488
2489 (defun mh-profile-component (component)
2490 "Return COMPONENT value from mhparam, or nil if unset."
2491 (save-excursion
2492 (mh-exec-cmd-quiet nil "mhparam" "-components" component)
2493 (mh-get-profile-field (concat component ":"))))
2494
2495 (defun mh-exchange-point-and-mark-preserving-active-mark ()
2496 "Put the mark where point is now, and point where the mark is now.
2497 This command works even when the mark is not active, and preserves whether the
2498 mark is active or not."
2499 (interactive nil)
2500 (let ((is-active (and (boundp 'mark-active) mark-active)))
2501 (let ((omark (mark t)))
2502 (if (null omark)
2503 (error "No mark set in this buffer"))
2504 (set-mark (point))
2505 (goto-char omark)
2506 (if (boundp 'mark-active)
2507 (setq mark-active is-active))
2508 nil)))
2509
2510 (defun mh-exec-cmd-output (command display &rest args)
2511 "Execute MH command COMMAND with DISPLAY flag and ARGS.
2512 Put the output into buffer after point. Set mark after inserted text.
2513 Output is expected to be shown to user, not parsed by MH-E."
2514 (push-mark (point) t)
2515 (apply 'call-process
2516 (expand-file-name command mh-progs) nil t display
2517 (mh-list-to-string args))
2518
2519 ;; The following is used instead of 'exchange-point-and-mark because the
2520 ;; latter activates the current region (between point and mark), which
2521 ;; turns on highlighting. So prior to this bug fix, doing "inc" would
2522 ;; highlight a region containing the new messages, which is undesirable.
2523 ;; The bug wasn't seen in emacs21 but still occurred in XEmacs21.4.
2524 (mh-exchange-point-and-mark-preserving-active-mark))
2525
2526 (defun mh-exec-lib-cmd-output (command &rest args)
2527 "Execute MH library command COMMAND with ARGS.
2528 Put the output into buffer after point. Set mark after inserted text."
2529 (apply 'mh-exec-cmd-output (expand-file-name command mh-lib-progs) nil args))
2530
2531 (defun mh-handle-process-error (command status)
2532 "Raise error if COMMAND returned non-zero STATUS, otherwise return STATUS."
2533 (if (equal status 0)
2534 status
2535 (goto-char (point-min))
2536 (insert (if (integerp status)
2537 (format "%s: exit code %d\n" command status)
2538 (format "%s: %s\n" command status)))
2539 (save-excursion
2540 (let ((error-message (buffer-substring (point-min) (point-max))))
2541 (set-buffer (get-buffer-create mh-log-buffer))
2542 (mh-truncate-log-buffer)
2543 (insert error-message)))
2544 (error "%s failed, check %s buffer for error message"
2545 command mh-log-buffer)))
2546
2547 (defun mh-list-to-string (l)
2548 "Flatten the list L and make every element of the new list into a string."
2549 (nreverse (mh-list-to-string-1 l)))
2550
2551 (defun mh-list-to-string-1 (l)
2552 "Flatten the list L and make every element of the new list into a string."
2553 (let ((new-list nil))
2554 (while l
2555 (cond ((null (car l)))
2556 ((symbolp (car l))
2557 (setq new-list (cons (symbol-name (car l)) new-list)))
2558 ((numberp (car l))
2559 (setq new-list (cons (int-to-string (car l)) new-list)))
2560 ((equal (car l) ""))
2561 ((stringp (car l)) (setq new-list (cons (car l) new-list)))
2562 ((listp (car l))
2563 (setq new-list (nconc (mh-list-to-string-1 (car l))
2564 new-list)))
2565 (t (error "Bad element in mh-list-to-string: %s" (car l))))
2566 (setq l (cdr l)))
2567 new-list))
2568
2569 (defun mh-replace-string (old new)
2570 "Replace all occurrences of OLD with NEW in the current buffer."
2571 (goto-char (point-min))
2572 (let ((case-fold-search t))
2573 (while (search-forward old nil t)
2574 (replace-match new t t))))
2575
2576 (defun mh-replace-in-string (regexp newtext string)
2577 "Replace REGEXP with NEWTEXT everywhere in STRING and return result.
2578 NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
2579
2580 The function body was copied from `dired-replace-in-string' in dired.el.
2581 Emacs21 has `replace-regexp-in-string' while XEmacs has `replace-in-string'.
2582 Neither is present in Emacs20. The file gnus-util.el in Gnus 5.10.1 and above
2583 has `gnus-replace-in-string'. We should use that when we decide to not support
2584 older versions of Gnus."
2585 (let ((result "") (start 0) mb me)
2586 (while (string-match regexp string start)
2587 (setq mb (match-beginning 0)
2588 me (match-end 0)
2589 result (concat result (substring string start mb) newtext)
2590 start me))
2591 (concat result (substring string start))))
2592
2593 (provide 'mh-utils)
2594
2595 ;;; Local Variables:
2596 ;;; indent-tabs-mode: nil
2597 ;;; sentence-end-double-space: nil
2598 ;;; End:
2599
2600 ;;; arch-tag: 1af39fdf-f66f-4b06-9b48-18a7656c8e36
2601 ;;; mh-utils.el ends here