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