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