(mh-process-daemon): Don't change buffer in proc-filter.
[emacs.git] / lisp / mh-e / mh-utils.el
blob9a6c1f488fdbae50f2783d05119c1603ad250e3f
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 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:\\)\\(.*\\)" (1 'default) (2 mh-show-from-face))
406 (mh-header-to-font-lock (0 'default) (1 mh-show-to-face))
407 (mh-header-cc-font-lock (0 'default) (1 mh-show-cc-face))
408 ("^\\(Reply-To:\\|Return-Path:\\)\\(.*\\)$"
409 (1 'default) (2 mh-show-from-face))
410 (mh-header-subject-font-lock (0 'default) (1 mh-show-subject-face))
411 ("^\\(Apparently-To:\\|Newsgroups:\\)\\(.*\\)"
412 (1 'default) (2 mh-show-cc-face))
413 ("^\\(In-reply-to\\|Date\\):\\(.*\\)$"
414 (1 'default) (2 mh-show-date-face))
415 (mh-letter-header-font-lock (0 mh-show-header-face append t)))
416 "Additional expressions to highlight in MH-show mode."))
418 (defvar mh-show-font-lock-keywords-with-cite
419 (eval-when-compile
420 (let* ((cite-chars "[>|}]")
421 (cite-prefix "A-Za-z")
422 (cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
423 (append
424 mh-show-font-lock-keywords
425 (list
426 ;; Use MATCH-ANCHORED to effectively anchor the regexp left side.
427 `(,cite-chars
428 (,(concat "\\=[ \t]*"
429 "\\(\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
430 "\\(" cite-chars "[ \t]*\\)\\)+"
431 "\\(.*\\)")
432 (beginning-of-line) (end-of-line)
433 (2 font-lock-constant-face nil t)
434 (4 font-lock-comment-face nil t)))))))
435 "Additional expressions to highlight in MH-show mode.")
437 (defvar mh-letter-font-lock-keywords
438 `(,@mh-show-font-lock-keywords-with-cite
439 (mh-font-lock-field-data (1 'mh-letter-header-field prepend t))))
441 (defun mh-show-font-lock-fontify-region (beg end loudly)
442 "Limit font-lock in `mh-show-mode' to the header.
444 Used when the option `mh-highlight-citation-style' is set to
445 \"Gnus\", leaving the body to be dealt with by Gnus highlighting.
446 The region between BEG and END is given over to be fontified and
447 LOUDLY controls if a user sees a message about the fontification
448 operation."
449 (let ((header-end (mh-mail-header-end)))
450 (cond
451 ((and (< beg header-end)(< end header-end))
452 (font-lock-default-fontify-region beg end loudly))
453 ((and (< beg header-end)(>= end header-end))
454 (font-lock-default-fontify-region beg header-end loudly))
456 nil))))
458 ;; Needed to help shush the byte-compiler.
459 (if mh-xemacs-flag
460 (progn
461 (eval-and-compile
462 (require 'gnus)
463 (require 'gnus-art)
464 (require 'gnus-cite))))
466 (defun mh-gnus-article-highlight-citation ()
467 "Highlight cited text in current buffer using Gnus."
468 (interactive)
469 ;; Requiring gnus-cite should have been sufficient. However for Emacs21.1,
470 ;; recursive-load-depth-limit is only 10, so an error occurs. Also it may be
471 ;; better to have an autoload at top-level (though that won't work because
472 ;; of recursive-load-depth-limit). That gets rid of a compiler warning as
473 ;; well.
474 (unless mh-xemacs-flag
475 (require 'gnus-art)
476 (require 'gnus-cite))
477 ;; Don't allow Gnus to create buttons while highlighting, maybe this is bad
478 ;; style?
479 (flet ((gnus-article-add-button (&rest args) nil))
480 (let* ((modified (buffer-modified-p))
481 (gnus-article-buffer (buffer-name))
482 (gnus-cite-face-list `(,@(cdr gnus-cite-face-list)
483 ,(car gnus-cite-face-list))))
484 (gnus-article-highlight-citation t)
485 (set-buffer-modified-p modified))))
489 ;;; Internal bookkeeping variables:
491 (defvar mh-user-path nil
492 "Cached value of the \"Path:\" MH profile component.
493 User's mail folder directory.")
495 (defvar mh-draft-folder nil
496 "Cached value of the \"Draft-Folder:\" MH profile component.
497 Name of folder containing draft messages.
498 Nil means do not use a draft folder.")
500 (defvar mh-unseen-seq nil
501 "Cached value of the \"Unseen-Sequence:\" MH profile component.
502 Name of the Unseen sequence.")
504 (defvar mh-previous-seq nil
505 "Cached value of the \"Previous-Sequence:\" MH profile component.
506 Name of the Previous sequence.")
508 (defvar mh-inbox nil
509 "Cached value of the \"Inbox:\" MH profile component.
510 Set to \"+inbox\" if no such component.
511 Name of the Inbox folder.")
513 ;; The names of ephemeral buffers have a " *mh-" prefix (so that they are
514 ;; hidden and can be programmatically removed in mh-quit), and the variable
515 ;; names have the form mh-temp-.*-buffer.
516 (defconst mh-temp-buffer " *mh-temp*") ;scratch
517 (defconst mh-temp-fetch-buffer " *mh-fetch*") ;wget/curl/fetch output
519 ;; The names of MH-E buffers that are not ephemeral and can be used by the
520 ;; user (and deleted by the user when no longer needed) have a "*MH-E " prefix
521 ;; (so they can be programmatically removed in mh-quit), and the variable
522 ;; names have the form mh-.*-buffer.
523 (defconst mh-aliases-buffer "*MH-E Aliases*") ;alias lookups
524 (defconst mh-folders-buffer "*MH-E Folders*") ;folder list
525 (defconst mh-help-buffer "*MH-E Help*") ;quick help
526 (defconst mh-info-buffer "*MH-E Info*") ;version information buffer
527 (defconst mh-log-buffer "*MH-E Log*") ;output of MH commands and so on
528 (defconst mh-mail-delivery-buffer "*MH-E Mail Delivery*") ;mail delivery log
529 (defconst mh-recipients-buffer "*MH-E Recipients*") ;killed when draft sent
530 (defconst mh-sequences-buffer "*MH-E Sequences*") ;sequences list
532 (defvar mh-log-buffer-lines 100
533 "Number of lines to keep in `mh-log-buffer'.")
535 (defvar mh-previous-window-config nil
536 "Window configuration before MH-E command.")
538 (defvar mh-page-to-next-msg-flag nil
539 "Non-nil means next SPC or whatever goes to next undeleted message.")
543 ;;; Internal variables local to a folder.
545 (defvar mh-current-folder nil
546 "Name of current folder, a string.")
548 (defvar mh-show-buffer nil
549 "Buffer that displays message for this folder.")
551 (defvar mh-folder-filename nil
552 "Full path of directory for this folder.")
554 (defvar mh-msg-count nil
555 "Number of msgs in buffer.")
557 (defvar mh-showing-mode nil
558 "If non-nil, show the message in a separate window.")
560 (defvar mh-show-mode-map (make-sparse-keymap)
561 "Keymap used by the show buffer.")
563 (defvar mh-show-folder-buffer nil
564 "Keeps track of folder whose message is being displayed.")
566 (defvar mh-logo-cache nil)
568 (defun mh-logo-display ()
569 "Modify mode line to display MH-E logo."
570 (mh-do-in-gnu-emacs
571 (add-text-properties
573 `(display ,(or mh-logo-cache
574 (setq mh-logo-cache
575 (mh-funcall-if-exists
576 find-image '((:type xpm :ascent center
577 :file "mh-logo.xpm"))))))
578 (car mode-line-buffer-identification)))
579 (mh-do-in-xemacs
580 (setq modeline-buffer-identification
581 (list
582 (if mh-modeline-glyph
583 (cons modeline-buffer-id-left-extent mh-modeline-glyph)
584 (cons modeline-buffer-id-left-extent "XEmacs%N:"))
585 (cons modeline-buffer-id-right-extent " %17b")))))
587 (defun mh-showing-mode (&optional arg)
588 "Change whether messages should be displayed.
590 With ARG, display messages iff ARG is positive."
591 (setq mh-showing-mode
592 (if (null arg)
593 (not mh-showing-mode)
594 (> (prefix-numeric-value arg) 0))))
596 (defvar mh-seq-list nil
597 "Alist of this folder's sequences.
598 Elements have the form (SEQUENCE . MESSAGES).")
600 (defvar mh-seen-list nil
601 "List of displayed messages to be removed from the \"Unseen\" sequence.")
603 (defvar mh-showing-with-headers nil
604 "If non-nil, MH-Show buffer contains message with all header fields.
605 If nil, MH-Show buffer contains message processed normally.")
609 ;;; MH-E macros
611 (defmacro with-mh-folder-updating (save-modification-flag &rest body)
612 "Format is (with-mh-folder-updating (SAVE-MODIFICATION-FLAG) &body BODY).
613 Execute BODY, which can modify the folder buffer without having to
614 worry about file locking or the read-only flag, and return its result.
615 If SAVE-MODIFICATION-FLAG is non-nil, the buffer's modification flag
616 is unchanged, otherwise it is cleared."
617 (setq save-modification-flag (car save-modification-flag)) ; CL style
618 `(prog1
619 (let ((mh-folder-updating-mod-flag (buffer-modified-p))
620 (buffer-read-only nil)
621 (buffer-file-name nil)) ;don't let the buffer get locked
622 (prog1
623 (progn
624 ,@body)
625 (mh-set-folder-modified-p mh-folder-updating-mod-flag)))
626 ,@(if (not save-modification-flag)
627 '((mh-set-folder-modified-p nil)))))
629 (put 'with-mh-folder-updating 'lisp-indent-hook 'defun)
631 (defmacro mh-in-show-buffer (show-buffer &rest body)
632 "Format is (mh-in-show-buffer (SHOW-BUFFER) &body BODY).
633 Display buffer SHOW-BUFFER in other window and execute BODY in it.
634 Stronger than `save-excursion', weaker than `save-window-excursion'."
635 (setq show-buffer (car show-buffer)) ; CL style
636 `(let ((mh-in-show-buffer-saved-window (selected-window)))
637 (switch-to-buffer-other-window ,show-buffer)
638 (if mh-bury-show-buffer-flag (bury-buffer (current-buffer)))
639 (unwind-protect
640 (progn
641 ,@body)
642 (select-window mh-in-show-buffer-saved-window))))
644 (put 'mh-in-show-buffer 'lisp-indent-hook 'defun)
646 (defmacro mh-do-at-event-location (event &rest body)
647 "Switch to the location of EVENT and execute BODY.
648 After BODY has been executed return to original window. The
649 modification flag of the buffer in the event window is
650 preserved."
651 (let ((event-window (make-symbol "event-window"))
652 (event-position (make-symbol "event-position"))
653 (original-window (make-symbol "original-window"))
654 (original-position (make-symbol "original-position"))
655 (modified-flag (make-symbol "modified-flag")))
656 `(save-excursion
657 (let* ((,event-window
658 (or (mh-funcall-if-exists posn-window (event-start ,event))
659 (mh-funcall-if-exists event-window ,event)))
660 (,event-position
661 (or (mh-funcall-if-exists posn-point (event-start ,event))
662 (mh-funcall-if-exists event-closest-point ,event)))
663 (,original-window (selected-window))
664 (,original-position (progn
665 (set-buffer (window-buffer ,event-window))
666 (set-marker (make-marker) (point))))
667 (,modified-flag (buffer-modified-p))
668 (buffer-read-only nil))
669 (unwind-protect (progn
670 (select-window ,event-window)
671 (goto-char ,event-position)
672 ,@body)
673 (set-buffer-modified-p ,modified-flag)
674 (goto-char ,original-position)
675 (set-marker ,original-position nil)
676 (select-window ,original-window))))))
678 (put 'mh-do-at-event-location 'lisp-indent-hook 'defun)
680 (defmacro mh-make-seq (name msgs)
681 "Create sequence NAME with the given MSGS."
682 (list 'cons name msgs))
684 (defmacro mh-seq-name (sequence)
685 "Extract sequence name from the given SEQUENCE."
686 (list 'car sequence))
688 (defmacro mh-seq-msgs (sequence)
689 "Extract messages from the given SEQUENCE."
690 (list 'cdr sequence))
692 (defun mh-recenter (arg)
693 "Like recenter but with three improvements:
695 - At the end of the buffer it tries to show fewer empty lines.
697 - operates only if the current buffer is in the selected window.
698 (Commands like `save-some-buffers' can make this false.)
700 - nil ARG means recenter as if prefix argument had been given."
701 (cond ((not (eq (get-buffer-window (current-buffer)) (selected-window)))
702 nil)
703 ((= (point-max) (save-excursion
704 (forward-line (- (/ (window-height) 2) 2))
705 (point)))
706 (let ((lines-from-end 2))
707 (save-excursion
708 (while (> (point-max) (progn (forward-line) (point)))
709 (incf lines-from-end)))
710 (recenter (- lines-from-end))))
711 ;; '(4) is the same as C-u prefix argument.
712 (t (recenter (or arg '(4))))))
714 (defun mh-start-of-uncleaned-message ()
715 "Position uninteresting headers off the top of the window."
716 (let ((case-fold-search t))
717 (re-search-forward
718 "^To:\\|^Cc:\\|^From:\\|^Subject:\\|^Date:" nil t)
719 (beginning-of-line)
720 (mh-recenter 0)))
722 (defun mh-invalidate-show-buffer ()
723 "Invalidate the show buffer so we must update it to use it."
724 (if (get-buffer mh-show-buffer)
725 (save-excursion
726 (set-buffer mh-show-buffer)
727 (mh-unvisit-file))))
729 (defun mh-unvisit-file ()
730 "Separate current buffer from the message file it was visiting."
731 (or (not (buffer-modified-p))
732 (null buffer-file-name) ;we've been here before
733 (yes-or-no-p (format "Message %s modified; flush changes? "
734 (file-name-nondirectory buffer-file-name)))
735 (error "Flushing changes not confirmed"))
736 (clear-visited-file-modtime)
737 (unlock-buffer)
738 (setq buffer-file-name nil))
741 (defun mh-get-msg-num (error-if-no-message)
742 "Return the message number of the displayed message.
743 If the argument ERROR-IF-NO-MESSAGE is non-nil, then complain if
744 the cursor is not pointing to a message."
745 (save-excursion
746 (beginning-of-line)
747 (cond ((looking-at mh-scan-msg-number-regexp)
748 (string-to-number (buffer-substring (match-beginning 1)
749 (match-end 1))))
750 (error-if-no-message
751 (error "Cursor not pointing to message"))
752 (t nil))))
754 (defun mh-folder-name-p (name)
755 "Return non-nil if NAME is the name of a folder.
756 A name (a string or symbol) can be a folder name if it begins
757 with \"+\"."
758 (if (symbolp name)
759 (eq (aref (symbol-name name) 0) ?+)
760 (and (> (length name) 0)
761 (eq (aref name 0) ?+))))
764 (defun mh-expand-file-name (filename &optional default)
765 "Expand FILENAME like `expand-file-name', but also handle MH folder names.
766 Any filename that starts with '+' is treated as a folder name.
767 See `expand-file-name' for description of DEFAULT."
768 (if (mh-folder-name-p filename)
769 (expand-file-name (substring filename 1) mh-user-path)
770 (expand-file-name filename default)))
773 (defun mh-msg-filename (msg &optional folder)
774 "Return the file name of MSG in FOLDER (default current folder)."
775 (expand-file-name (int-to-string msg)
776 (if folder
777 (mh-expand-file-name folder)
778 mh-folder-filename)))
780 ;; Infrastructure to generate show-buffer functions from folder functions
781 ;; XEmacs does not have deactivate-mark? What is the equivalent of
782 ;; transient-mark-mode for XEmacs? Should we be restoring the mark in the
783 ;; folder buffer after the operation has been carried out.
784 (defmacro mh-defun-show-buffer (function original-function
785 &optional dont-return)
786 "Define FUNCTION to run ORIGINAL-FUNCTION in folder buffer.
787 If the buffer we start in is still visible and DONT-RETURN is nil
788 then switch to it after that."
789 `(defun ,function ()
790 ,(format "Calls %s from the message's folder.\n%s\nSee \"%s\" for more info.\n"
791 original-function
792 (if dont-return ""
793 "When function completes, returns to the show buffer if it is
794 still visible.\n")
795 original-function)
796 (interactive)
797 (when (buffer-live-p (get-buffer mh-show-folder-buffer))
798 (let ((config (current-window-configuration))
799 (folder-buffer mh-show-folder-buffer)
800 (normal-exit nil)
801 ,@(if dont-return () '((cur-buffer-name (buffer-name)))))
802 (pop-to-buffer mh-show-folder-buffer nil)
803 (unless (equal (buffer-name
804 (window-buffer (frame-first-window (selected-frame))))
805 folder-buffer)
806 (delete-other-windows))
807 (mh-goto-cur-msg t)
808 (mh-funcall-if-exists deactivate-mark)
809 (unwind-protect
810 (prog1 (call-interactively (function ,original-function))
811 (setq normal-exit t))
812 (mh-funcall-if-exists deactivate-mark)
813 (when (eq major-mode 'mh-folder-mode)
814 (mh-funcall-if-exists hl-line-highlight))
815 (cond ((not normal-exit)
816 (set-window-configuration config))
817 ,(if dont-return
818 `(t (setq mh-previous-window-config config))
819 `((and (get-buffer cur-buffer-name)
820 (window-live-p (get-buffer-window
821 (get-buffer cur-buffer-name))))
822 (pop-to-buffer (get-buffer cur-buffer-name) nil)))))))))
824 ;; Generate interactive functions for the show buffer from the corresponding
825 ;; folder functions.
826 (mh-defun-show-buffer mh-show-previous-undeleted-msg
827 mh-previous-undeleted-msg)
828 (mh-defun-show-buffer mh-show-next-undeleted-msg
829 mh-next-undeleted-msg)
830 (mh-defun-show-buffer mh-show-quit mh-quit)
831 (mh-defun-show-buffer mh-show-delete-msg mh-delete-msg)
832 (mh-defun-show-buffer mh-show-refile-msg mh-refile-msg)
833 (mh-defun-show-buffer mh-show-undo mh-undo)
834 (mh-defun-show-buffer mh-show-execute-commands mh-execute-commands)
835 (mh-defun-show-buffer mh-show-reply mh-reply t)
836 (mh-defun-show-buffer mh-show-redistribute mh-redistribute)
837 (mh-defun-show-buffer mh-show-forward mh-forward t)
838 (mh-defun-show-buffer mh-show-header-display mh-header-display)
839 (mh-defun-show-buffer mh-show-refile-or-write-again
840 mh-refile-or-write-again)
841 (mh-defun-show-buffer mh-show-show mh-show)
842 (mh-defun-show-buffer mh-show-write-message-to-file
843 mh-write-msg-to-file)
844 (mh-defun-show-buffer mh-show-extract-rejected-mail
845 mh-extract-rejected-mail t)
846 (mh-defun-show-buffer mh-show-delete-msg-no-motion
847 mh-delete-msg-no-motion)
848 (mh-defun-show-buffer mh-show-first-msg mh-first-msg)
849 (mh-defun-show-buffer mh-show-last-msg mh-last-msg)
850 (mh-defun-show-buffer mh-show-copy-msg mh-copy-msg)
851 (mh-defun-show-buffer mh-show-edit-again mh-edit-again t)
852 (mh-defun-show-buffer mh-show-goto-msg mh-goto-msg)
853 (mh-defun-show-buffer mh-show-inc-folder mh-inc-folder)
854 (mh-defun-show-buffer mh-show-delete-subject-or-thread
855 mh-delete-subject-or-thread)
856 (mh-defun-show-buffer mh-show-delete-subject mh-delete-subject)
857 (mh-defun-show-buffer mh-show-print-msg mh-print-msg)
858 (mh-defun-show-buffer mh-show-send mh-send t)
859 (mh-defun-show-buffer mh-show-toggle-showing mh-toggle-showing t)
860 (mh-defun-show-buffer mh-show-pipe-msg mh-pipe-msg t)
861 (mh-defun-show-buffer mh-show-sort-folder mh-sort-folder)
862 (mh-defun-show-buffer mh-show-visit-folder mh-visit-folder t)
863 (mh-defun-show-buffer mh-show-rescan-folder mh-rescan-folder)
864 (mh-defun-show-buffer mh-show-pack-folder mh-pack-folder)
865 (mh-defun-show-buffer mh-show-kill-folder mh-kill-folder t)
866 (mh-defun-show-buffer mh-show-list-folders mh-list-folders t)
867 (mh-defun-show-buffer mh-show-search-folder mh-search-folder t)
868 (mh-defun-show-buffer mh-show-undo-folder mh-undo-folder)
869 (mh-defun-show-buffer mh-show-delete-msg-from-seq
870 mh-delete-msg-from-seq)
871 (mh-defun-show-buffer mh-show-delete-seq mh-delete-seq)
872 (mh-defun-show-buffer mh-show-list-sequences mh-list-sequences)
873 (mh-defun-show-buffer mh-show-narrow-to-seq mh-narrow-to-seq)
874 (mh-defun-show-buffer mh-show-put-msg-in-seq mh-put-msg-in-seq)
875 (mh-defun-show-buffer mh-show-msg-is-in-seq mh-msg-is-in-seq)
876 (mh-defun-show-buffer mh-show-widen mh-widen)
877 (mh-defun-show-buffer mh-show-narrow-to-subject mh-narrow-to-subject)
878 (mh-defun-show-buffer mh-show-narrow-to-from mh-narrow-to-from)
879 (mh-defun-show-buffer mh-show-narrow-to-cc mh-narrow-to-cc)
880 (mh-defun-show-buffer mh-show-narrow-to-range mh-narrow-to-range)
881 (mh-defun-show-buffer mh-show-narrow-to-to mh-narrow-to-to)
882 (mh-defun-show-buffer mh-show-store-msg mh-store-msg)
883 (mh-defun-show-buffer mh-show-page-digest mh-page-digest)
884 (mh-defun-show-buffer mh-show-page-digest-backwards
885 mh-page-digest-backwards)
886 (mh-defun-show-buffer mh-show-burst-digest mh-burst-digest)
887 (mh-defun-show-buffer mh-show-page-msg mh-page-msg)
888 (mh-defun-show-buffer mh-show-previous-page mh-previous-page)
889 (mh-defun-show-buffer mh-show-modify mh-modify t)
890 (mh-defun-show-buffer mh-show-next-button mh-next-button)
891 (mh-defun-show-buffer mh-show-prev-button mh-prev-button)
892 (mh-defun-show-buffer mh-show-toggle-mime-part mh-folder-toggle-mime-part)
893 (mh-defun-show-buffer mh-show-save-mime-part mh-folder-save-mime-part)
894 (mh-defun-show-buffer mh-show-inline-mime-part mh-folder-inline-mime-part)
895 (mh-defun-show-buffer mh-show-toggle-threads mh-toggle-threads)
896 (mh-defun-show-buffer mh-show-thread-delete mh-thread-delete)
897 (mh-defun-show-buffer mh-show-thread-refile mh-thread-refile)
898 (mh-defun-show-buffer mh-show-update-sequences mh-update-sequences)
899 (mh-defun-show-buffer mh-show-next-unread-msg mh-next-unread-msg)
900 (mh-defun-show-buffer mh-show-previous-unread-msg mh-previous-unread-msg)
901 (mh-defun-show-buffer mh-show-thread-ancestor mh-thread-ancestor)
902 (mh-defun-show-buffer mh-show-thread-next-sibling mh-thread-next-sibling)
903 (mh-defun-show-buffer mh-show-thread-previous-sibling
904 mh-thread-previous-sibling)
905 (mh-defun-show-buffer mh-show-index-visit-folder mh-index-visit-folder t)
906 (mh-defun-show-buffer mh-show-toggle-tick mh-toggle-tick)
907 (mh-defun-show-buffer mh-show-narrow-to-tick mh-narrow-to-tick)
908 (mh-defun-show-buffer mh-show-junk-blacklist mh-junk-blacklist)
909 (mh-defun-show-buffer mh-show-junk-whitelist mh-junk-whitelist)
910 (mh-defun-show-buffer mh-show-index-new-messages mh-index-new-messages)
911 (mh-defun-show-buffer mh-show-index-ticked-messages mh-index-ticked-messages)
912 (mh-defun-show-buffer mh-show-index-sequenced-messages
913 mh-index-sequenced-messages)
914 (mh-defun-show-buffer mh-show-catchup mh-catchup)
915 (mh-defun-show-buffer mh-show-ps-print-toggle-color mh-ps-print-toggle-color)
916 (mh-defun-show-buffer mh-show-ps-print-toggle-faces mh-ps-print-toggle-faces)
917 (mh-defun-show-buffer mh-show-ps-print-msg-file mh-ps-print-msg-file)
918 (mh-defun-show-buffer mh-show-ps-print-msg mh-ps-print-msg)
919 (mh-defun-show-buffer mh-show-toggle-mime-buttons mh-toggle-mime-buttons)
920 (mh-defun-show-buffer mh-show-display-with-external-viewer
921 mh-display-with-external-viewer)
925 ;;; Build mh-show-mode keymaps
927 (gnus-define-keys mh-show-mode-map
928 " " mh-show-page-msg
929 "!" mh-show-refile-or-write-again
930 "'" mh-show-toggle-tick
931 "," mh-show-header-display
932 "." mh-show-show
933 ">" mh-show-write-message-to-file
934 "?" mh-help
935 "E" mh-show-extract-rejected-mail
936 "M" mh-show-modify
937 "\177" mh-show-previous-page
938 "\C-d" mh-show-delete-msg-no-motion
939 "\t" mh-show-next-button
940 [backtab] mh-show-prev-button
941 "\M-\t" mh-show-prev-button
942 "\ed" mh-show-redistribute
943 "^" mh-show-refile-msg
944 "c" mh-show-copy-msg
945 "d" mh-show-delete-msg
946 "e" mh-show-edit-again
947 "f" mh-show-forward
948 "g" mh-show-goto-msg
949 "i" mh-show-inc-folder
950 "k" mh-show-delete-subject-or-thread
951 "m" mh-show-send
952 "n" mh-show-next-undeleted-msg
953 "\M-n" mh-show-next-unread-msg
954 "o" mh-show-refile-msg
955 "p" mh-show-previous-undeleted-msg
956 "\M-p" mh-show-previous-unread-msg
957 "q" mh-show-quit
958 "r" mh-show-reply
959 "s" mh-show-send
960 "t" mh-show-toggle-showing
961 "u" mh-show-undo
962 "x" mh-show-execute-commands
963 "v" mh-show-index-visit-folder
964 "|" mh-show-pipe-msg)
966 (gnus-define-keys (mh-show-folder-map "F" mh-show-mode-map)
967 "?" mh-prefix-help
968 "'" mh-index-ticked-messages
969 "S" mh-show-sort-folder
970 "c" mh-show-catchup
971 "f" mh-show-visit-folder
972 "i" mh-index-search
973 "k" mh-show-kill-folder
974 "l" mh-show-list-folders
975 "n" mh-index-new-messages
976 "o" mh-show-visit-folder
977 "q" mh-show-index-sequenced-messages
978 "r" mh-show-rescan-folder
979 "s" mh-show-search-folder
980 "t" mh-show-toggle-threads
981 "u" mh-show-undo-folder
982 "v" mh-show-visit-folder)
984 (gnus-define-keys (mh-show-sequence-map "S" mh-show-mode-map)
985 "'" mh-show-narrow-to-tick
986 "?" mh-prefix-help
987 "d" mh-show-delete-msg-from-seq
988 "k" mh-show-delete-seq
989 "l" mh-show-list-sequences
990 "n" mh-show-narrow-to-seq
991 "p" mh-show-put-msg-in-seq
992 "s" mh-show-msg-is-in-seq
993 "w" mh-show-widen)
995 (define-key mh-show-mode-map "I" mh-inc-spool-map)
997 (gnus-define-keys (mh-show-junk-map "J" mh-show-mode-map)
998 "?" mh-prefix-help
999 "b" mh-show-junk-blacklist
1000 "w" mh-show-junk-whitelist)
1002 (gnus-define-keys (mh-show-ps-print-map "P" mh-show-mode-map)
1003 "?" mh-prefix-help
1004 "C" mh-show-ps-print-toggle-color
1005 "F" mh-show-ps-print-toggle-faces
1006 "f" mh-show-ps-print-msg-file
1007 "l" mh-show-print-msg
1008 "p" mh-show-ps-print-msg)
1010 (gnus-define-keys (mh-show-thread-map "T" mh-show-mode-map)
1011 "?" mh-prefix-help
1012 "u" mh-show-thread-ancestor
1013 "p" mh-show-thread-previous-sibling
1014 "n" mh-show-thread-next-sibling
1015 "t" mh-show-toggle-threads
1016 "d" mh-show-thread-delete
1017 "o" mh-show-thread-refile)
1019 (gnus-define-keys (mh-show-limit-map "/" mh-show-mode-map)
1020 "'" mh-show-narrow-to-tick
1021 "?" mh-prefix-help
1022 "c" mh-show-narrow-to-cc
1023 "f" mh-show-narrow-to-from
1024 "r" mh-show-narrow-to-range
1025 "s" mh-show-narrow-to-subject
1026 "t" mh-show-narrow-to-to
1027 "w" mh-show-widen)
1029 (gnus-define-keys (mh-show-extract-map "X" mh-show-mode-map)
1030 "?" mh-prefix-help
1031 "s" mh-show-store-msg
1032 "u" mh-show-store-msg)
1034 ;; Untested...
1035 (gnus-define-keys (mh-show-digest-map "D" mh-show-mode-map)
1036 "?" mh-prefix-help
1037 " " mh-show-page-digest
1038 "\177" mh-show-page-digest-backwards
1039 "b" mh-show-burst-digest)
1041 (gnus-define-keys (mh-show-mime-map "K" mh-show-mode-map)
1042 "?" mh-prefix-help
1043 "a" mh-mime-save-parts
1044 "e" mh-show-display-with-external-viewer
1045 "v" mh-show-toggle-mime-part
1046 "o" mh-show-save-mime-part
1047 "i" mh-show-inline-mime-part
1048 "t" mh-show-toggle-mime-buttons
1049 "\t" mh-show-next-button
1050 [backtab] mh-show-prev-button
1051 "\M-\t" mh-show-prev-button)
1053 (easy-menu-define
1054 mh-show-sequence-menu mh-show-mode-map "Menu for MH-E folder-sequence."
1055 '("Sequence"
1056 ["Add Message to Sequence..." mh-show-put-msg-in-seq t]
1057 ["List Sequences for Message" mh-show-msg-is-in-seq t]
1058 ["Delete Message from Sequence..." mh-show-delete-msg-from-seq t]
1059 ["List Sequences in Folder..." mh-show-list-sequences t]
1060 ["Delete Sequence..." mh-show-delete-seq t]
1061 ["Narrow to Sequence..." mh-show-narrow-to-seq t]
1062 ["Widen from Sequence" mh-show-widen t]
1063 "--"
1064 ["Narrow to Subject Sequence" mh-show-narrow-to-subject t]
1065 ["Narrow to Tick Sequence" mh-show-narrow-to-tick
1066 (save-excursion
1067 (set-buffer mh-show-folder-buffer)
1068 (and mh-tick-seq (mh-seq-msgs (mh-find-seq mh-tick-seq))))]
1069 ["Delete Rest of Same Subject" mh-show-delete-subject t]
1070 ["Toggle Tick Mark" mh-show-toggle-tick t]
1071 "--"
1072 ["Push State Out to MH" mh-show-update-sequences t]))
1074 (easy-menu-define
1075 mh-show-message-menu mh-show-mode-map "Menu for MH-E folder-message."
1076 '("Message"
1077 ["Show Message" mh-show-show t]
1078 ["Show Message with Header" mh-show-header-display t]
1079 ["Next Message" mh-show-next-undeleted-msg t]
1080 ["Previous Message" mh-show-previous-undeleted-msg t]
1081 ["Go to First Message" mh-show-first-msg t]
1082 ["Go to Last Message" mh-show-last-msg t]
1083 ["Go to Message by Number..." mh-show-goto-msg t]
1084 ["Modify Message" mh-show-modify t]
1085 ["Delete Message" mh-show-delete-msg t]
1086 ["Refile Message" mh-show-refile-msg t]
1087 ["Undo Delete/Refile" mh-show-undo t]
1088 ["Process Delete/Refile" mh-show-execute-commands t]
1089 "--"
1090 ["Compose a New Message" mh-send t]
1091 ["Reply to Message..." mh-show-reply t]
1092 ["Forward Message..." mh-show-forward t]
1093 ["Redistribute Message..." mh-show-redistribute t]
1094 ["Edit Message Again" mh-show-edit-again t]
1095 ["Re-edit a Bounced Message" mh-show-extract-rejected-mail t]
1096 "--"
1097 ["Copy Message to Folder..." mh-show-copy-msg t]
1098 ["Print Message" mh-show-print-msg t]
1099 ["Write Message to File..." mh-show-write-msg-to-file t]
1100 ["Pipe Message to Command..." mh-show-pipe-msg t]
1101 ["Unpack Uuencoded Message..." mh-show-store-msg t]
1102 ["Burst Digest Message" mh-show-burst-digest t]))
1104 (easy-menu-define
1105 mh-show-folder-menu mh-show-mode-map "Menu for MH-E folder."
1106 '("Folder"
1107 ["Incorporate New Mail" mh-show-inc-folder t]
1108 ["Toggle Show/Folder" mh-show-toggle-showing t]
1109 ["Execute Delete/Refile" mh-show-execute-commands t]
1110 ["Rescan Folder" mh-show-rescan-folder t]
1111 ["Thread Folder" mh-show-toggle-threads t]
1112 ["Pack Folder" mh-show-pack-folder t]
1113 ["Sort Folder" mh-show-sort-folder t]
1114 "--"
1115 ["List Folders" mh-show-list-folders t]
1116 ["Visit a Folder..." mh-show-visit-folder t]
1117 ["View New Messages" mh-show-index-new-messages t]
1118 ["Search a Folder..." mh-show-search-folder t]
1119 ["Indexed Search..." mh-index-search t]
1120 "--"
1121 ["Quit MH-E" mh-quit t]))
1124 ;; Ensure new buffers won't get this mode if default-major-mode is nil.
1125 (put 'mh-show-mode 'mode-class 'special)
1127 ;; Avoid compiler warnings in XEmacs and Emacs 20
1128 (eval-when-compile
1129 (defvar tool-bar-mode)
1130 (defvar tool-bar-map))
1132 (define-derived-mode mh-show-mode text-mode "MH-Show"
1133 "Major mode for showing messages in MH-E.\\<mh-show-mode-map>
1135 The hook `mh-show-mode-hook' is called upon entry to this mode.
1137 See also `mh-folder-mode'.
1139 \\{mh-show-mode-map}"
1140 (set (make-local-variable 'mail-header-separator) mh-mail-header-separator)
1141 (setq paragraph-start (default-value 'paragraph-start))
1142 (mh-show-unquote-From)
1143 (mh-show-xface)
1144 (mh-show-addr)
1145 (setq buffer-invisibility-spec '((vanish . t) t))
1146 (set (make-local-variable 'line-move-ignore-invisible) t)
1147 (make-local-variable 'font-lock-defaults)
1148 ;;(set (make-local-variable 'font-lock-support-mode) nil)
1149 (cond
1150 ((equal mh-highlight-citation-style 'font-lock)
1151 (setq font-lock-defaults '(mh-show-font-lock-keywords-with-cite t)))
1152 ((equal mh-highlight-citation-style 'gnus)
1153 (setq font-lock-defaults '((mh-show-font-lock-keywords)
1154 t nil nil nil
1155 (font-lock-fontify-region-function
1156 . mh-show-font-lock-fontify-region)))
1157 (mh-gnus-article-highlight-citation))
1159 (setq font-lock-defaults '(mh-show-font-lock-keywords t))))
1160 (if (and mh-xemacs-flag
1161 font-lock-auto-fontify)
1162 (turn-on-font-lock))
1163 (set (make-local-variable 'tool-bar-map) mh-show-tool-bar-map)
1164 (mh-funcall-if-exists mh-tool-bar-init :show)
1165 (when mh-decode-mime-flag
1166 (mh-make-local-hook 'kill-buffer-hook)
1167 (add-hook 'kill-buffer-hook 'mh-mime-cleanup nil t))
1168 (easy-menu-add mh-show-sequence-menu)
1169 (easy-menu-add mh-show-message-menu)
1170 (easy-menu-add mh-show-folder-menu)
1171 (make-local-variable 'mh-show-folder-buffer)
1172 (buffer-disable-undo)
1173 (setq buffer-read-only t)
1174 (use-local-map mh-show-mode-map))
1176 (defun mh-show-addr ()
1177 "Use `goto-address'."
1178 (when mh-show-use-goto-addr-flag
1179 (if (not (featurep 'goto-addr))
1180 (load "goto-addr" t t))
1181 (if (fboundp 'goto-address)
1182 (goto-address))))
1186 ;; X-Face and Face display
1187 (defvar mh-show-xface-function
1188 (cond ((and mh-xemacs-flag (locate-library "x-face") (not (featurep 'xface)))
1189 (load "x-face" t t)
1190 #'mh-face-display-function)
1191 ((>= emacs-major-version 21)
1192 #'mh-face-display-function)
1193 (t #'ignore))
1194 "Determine at run time what function should be called to display X-Face.")
1196 (defvar mh-uncompface-executable
1197 (and (fboundp 'executable-find) (executable-find "uncompface")))
1199 (defun mh-face-to-png (data)
1200 "Convert base64 encoded DATA to png image."
1201 (with-temp-buffer
1202 (insert data)
1203 (ignore-errors (base64-decode-region (point-min) (point-max)))
1204 (buffer-string)))
1206 (defun mh-uncompface (data)
1207 "Run DATA through `uncompface' to generate bitmap."
1208 (with-temp-buffer
1209 (insert data)
1210 (when (and mh-uncompface-executable
1211 (equal (call-process-region (point-min) (point-max)
1212 mh-uncompface-executable t '(t nil))
1214 (mh-icontopbm)
1215 (buffer-string))))
1217 (defun mh-icontopbm ()
1218 "Elisp substitute for `icontopbm'."
1219 (goto-char (point-min))
1220 (let ((end (point-max)))
1221 (while (re-search-forward "0x\\(..\\)\\(..\\)," nil t)
1222 (save-excursion
1223 (goto-char (point-max))
1224 (insert (string-to-number (match-string 1) 16))
1225 (insert (string-to-number (match-string 2) 16))))
1226 (delete-region (point-min) end)
1227 (goto-char (point-min))
1228 (insert "P4\n48 48\n")))
1230 (mh-do-in-xemacs (defvar default-enable-multibyte-characters))
1232 (defun mh-face-display-function ()
1233 "Display a Face, X-Face, or X-Image-URL header field.
1234 If more than one of these are present, then the first one found
1235 in this order is used."
1236 (save-restriction
1237 (goto-char (point-min))
1238 (re-search-forward "\n\n" (point-max) t)
1239 (narrow-to-region (point-min) (point))
1240 (let* ((case-fold-search t)
1241 (default-enable-multibyte-characters nil)
1242 (face (message-fetch-field "face" t))
1243 (x-face (message-fetch-field "x-face" t))
1244 (url (message-fetch-field "x-image-url" t))
1245 raw type)
1246 (cond (face (setq raw (mh-face-to-png face)
1247 type 'png))
1248 (x-face (setq raw (mh-uncompface x-face)
1249 type 'pbm))
1250 (url (setq type 'url))
1251 (t (multiple-value-setq (type raw) (mh-picon-get-image))))
1252 (when type
1253 (goto-char (point-min))
1254 (when (re-search-forward "^from:" (point-max) t)
1255 ;; GNU Emacs
1256 (mh-do-in-gnu-emacs
1257 (if (eq type 'url)
1258 (mh-x-image-url-display url)
1259 (mh-funcall-if-exists
1260 insert-image (create-image
1261 raw type t
1262 :foreground (face-foreground 'mh-show-xface)
1263 :background (face-background 'mh-show-xface))
1264 " ")))
1265 ;; XEmacs
1266 (mh-do-in-xemacs
1267 (cond
1268 ((eq type 'url)
1269 (mh-x-image-url-display url))
1270 ((eq type 'png)
1271 (when (featurep 'png)
1272 (set-extent-begin-glyph
1273 (make-extent (point) (point))
1274 (make-glyph (vector 'png ':data (mh-face-to-png face))))))
1275 ;; Try internal xface support if available...
1276 ((and (eq type 'pbm) (featurep 'xface))
1277 (set-glyph-face
1278 (set-extent-begin-glyph
1279 (make-extent (point) (point))
1280 (make-glyph (vector 'xface ':data (concat "X-Face: " x-face))))
1281 'mh-show-xface))
1282 ;; Otherwise try external support with x-face...
1283 ((and (eq type 'pbm)
1284 (fboundp 'x-face-xmas-wl-display-x-face)
1285 (fboundp 'executable-find) (executable-find "uncompface"))
1286 (mh-funcall-if-exists x-face-xmas-wl-display-x-face))
1287 ;; Picon display
1288 ((and raw (member type '(xpm xbm gif)))
1289 (when (featurep type)
1290 (set-extent-begin-glyph
1291 (make-extent (point) (point))
1292 (make-glyph (vector type ':data raw))))))
1293 (when raw (insert " "))))))))
1295 (defun mh-show-xface ()
1296 "Display X-Face."
1297 (when (and window-system mh-show-use-xface-flag
1298 (or mh-decode-mime-flag mh-mhl-format-file
1299 mh-clean-message-header-flag))
1300 (funcall mh-show-xface-function)))
1304 ;;; Picon display
1306 ;; XXX: This should be customizable. As a side-effect of setting this
1307 ;; variable, arrange to reset mh-picon-existing-directory-list to 'unset.
1308 (defvar mh-picon-directory-list
1309 '("~/.picons" "~/.picons/users" "~/.picons/usenix" "~/.picons/news"
1310 "~/.picons/domains" "~/.picons/misc"
1311 "/usr/share/picons/" "/usr/share/picons/users" "/usr/share/picons/usenix"
1312 "/usr/share/picons/news" "/usr/share/picons/domains"
1313 "/usr/share/picons/misc")
1314 "List of directories where picons reside.
1315 The directories are searched for in the order they appear in the list.")
1317 (defvar mh-picon-existing-directory-list 'unset
1318 "List of directories to search in.")
1320 (defvar mh-picon-cache (make-hash-table :test #'equal))
1322 (defvar mh-picon-image-types
1323 (loop for type in '(xpm xbm gif)
1324 when (or (mh-do-in-gnu-emacs
1325 (ignore-errors
1326 (mh-funcall-if-exists image-type-available-p type)))
1327 (mh-do-in-xemacs (featurep type)))
1328 collect type))
1330 (defun mh-picon-set-directory-list ()
1331 "Update `mh-picon-existing-directory-list' if needed."
1332 (when (eq mh-picon-existing-directory-list 'unset)
1333 (setq mh-picon-existing-directory-list
1334 (loop for x in mh-picon-directory-list
1335 when (file-directory-p x) collect x))))
1337 (defun* mh-picon-get-image ()
1338 "Find the best possible match and return contents."
1339 (mh-picon-set-directory-list)
1340 (save-restriction
1341 (let* ((from-field (ignore-errors (car (message-tokenize-header
1342 (mh-get-header-field "from:")))))
1343 (from (car (ignore-errors
1344 (mh-funcall-if-exists ietf-drums-parse-address
1345 from-field))))
1346 (host (and from
1347 (string-match "\\([^+]*\\)\\(+.*\\)?@\\(.*\\)" from)
1348 (downcase (match-string 3 from))))
1349 (user (and host (downcase (match-string 1 from))))
1350 (canonical-address (format "%s@%s" user host))
1351 (cached-value (gethash canonical-address mh-picon-cache))
1352 (host-list (and host (delete "" (split-string host "\\."))))
1353 (match nil))
1354 (cond (cached-value (return-from mh-picon-get-image cached-value))
1355 ((not host-list) (return-from mh-picon-get-image nil)))
1356 (setq match
1357 (block 'loop
1358 ;; u@h search
1359 (loop for dir in mh-picon-existing-directory-list
1360 do (loop for type in mh-picon-image-types
1361 ;; [path]user@host
1362 for file1 = (format "%s/%s.%s"
1363 dir canonical-address type)
1364 when (file-exists-p file1)
1365 do (return-from 'loop file1)
1366 ;; [path]user
1367 for file2 = (format "%s/%s.%s" dir user type)
1368 when (file-exists-p file2)
1369 do (return-from 'loop file2)
1370 ;; [path]host
1371 for file3 = (format "%s/%s.%s" dir host type)
1372 when (file-exists-p file3)
1373 do (return-from 'loop file3)))
1374 ;; facedb search
1375 ;; Search order for user@foo.net:
1376 ;; [path]net/foo/user
1377 ;; [path]net/foo/user/face
1378 ;; [path]net/user
1379 ;; [path]net/user/face
1380 ;; [path]net/foo/unknown
1381 ;; [path]net/foo/unknown/face
1382 ;; [path]net/unknown
1383 ;; [path]net/unknown/face
1384 (loop for u in (list user "unknown")
1385 do (loop for dir in mh-picon-existing-directory-list
1386 do (loop for x on host-list by #'cdr
1387 for y = (mh-picon-generate-path x u dir)
1388 do (loop for type in mh-picon-image-types
1389 for z1 = (format "%s.%s" y type)
1390 when (file-exists-p z1)
1391 do (return-from 'loop z1)
1392 for z2 = (format "%s/face.%s"
1393 y type)
1394 when (file-exists-p z2)
1395 do (return-from 'loop z2)))))))
1396 (setf (gethash canonical-address mh-picon-cache)
1397 (mh-picon-file-contents match)))))
1399 (defun mh-picon-file-contents (file)
1400 "Return details about FILE.
1401 A list of consisting of a symbol for the type of the file and the
1402 file contents as a string is returned. If FILE is nil, then both
1403 elements of the list are nil."
1404 (if (stringp file)
1405 (with-temp-buffer
1406 (let ((type (and (string-match ".*\\.\\(...\\)$" file)
1407 (intern (match-string 1 file)))))
1408 (insert-file-contents-literally file)
1409 (values type (buffer-string))))
1410 (values nil nil)))
1412 (defun mh-picon-generate-path (host-list user directory)
1413 "Generate the image file path.
1414 HOST-LIST is the parsed host address of the email address, USER
1415 the username and DIRECTORY is the directory relative to which the
1416 path is generated."
1417 (loop with acc = ""
1418 for elem in host-list
1419 do (setq acc (format "%s/%s" elem acc))
1420 finally return (format "%s/%s%s" directory acc user)))
1424 ;; X-Image-URL display
1426 (defvar mh-x-image-cache-directory nil
1427 "Directory where X-Image-URL images are cached.")
1428 (defvar mh-x-image-scaling-function
1429 (cond ((executable-find "convert")
1430 'mh-x-image-scale-with-convert)
1431 ((and (executable-find "anytopnm") (executable-find "pnmscale")
1432 (executable-find "pnmtopng"))
1433 'mh-x-image-scale-with-pnm)
1434 (t 'ignore))
1435 "Function to use to scale image to proper size.")
1436 (defvar mh-wget-executable nil)
1437 (defvar mh-wget-choice
1438 (or (and (setq mh-wget-executable (executable-find "wget")) 'wget)
1439 (and (setq mh-wget-executable (executable-find "fetch")) 'fetch)
1440 (and (setq mh-wget-executable (executable-find "curl")) 'curl)))
1441 (defvar mh-wget-option
1442 (cdr (assoc mh-wget-choice '((curl . "-o") (fetch . "-o") (wget . "-O")))))
1443 (defvar mh-x-image-temp-file nil)
1444 (defvar mh-x-image-url nil)
1445 (defvar mh-x-image-marker nil)
1446 (defvar mh-x-image-url-cache-file nil)
1448 ;; Functions to scale image to proper size
1449 (defun mh-x-image-scale-with-pnm (input output)
1450 "Scale image in INPUT file and write to OUTPUT file using pnm tools."
1451 (let ((res (shell-command-to-string
1452 (format "anytopnm < %s | pnmscale -xysize 96 48 | pnmtopng > %s"
1453 input output))))
1454 (unless (equal res "")
1455 (delete-file output))))
1457 (defun mh-x-image-scale-with-convert (input output)
1458 "Scale image in INPUT file and write to OUTPUT file using ImageMagick."
1459 (call-process "convert" nil nil nil "-geometry" "96x48" input output))
1461 (defun mh-x-image-url-cache-canonicalize (url)
1462 "Canonicalize URL.
1463 Replace the ?/ character with a ?! character and append .png."
1464 (format "%s/%s.png" mh-x-image-cache-directory
1465 (with-temp-buffer
1466 (insert url)
1467 (mh-replace-string "/" "!")
1468 (buffer-string))))
1470 (defun mh-x-image-set-download-state (file data)
1471 "Setup a symbolic link from FILE to DATA."
1472 (if data
1473 (make-symbolic-link (symbol-name data) file t)
1474 (delete-file file)))
1476 (defun mh-x-image-get-download-state (file)
1477 "Check the state of FILE by following any symbolic links."
1478 (unless (file-exists-p mh-x-image-cache-directory)
1479 (call-process "mkdir" nil nil nil mh-x-image-cache-directory))
1480 (cond ((file-symlink-p file)
1481 (intern (file-name-nondirectory (file-chase-links file))))
1482 ((not (file-exists-p file)) nil)
1483 (t 'ok)))
1485 (defun mh-x-image-url-fetch-image (url cache-file marker sentinel)
1486 "Fetch and display the image specified by URL.
1487 After the image is fetched, it is stored in CACHE-FILE. It will
1488 be displayed in a buffer and position specified by MARKER. The
1489 actual display is carried out by the SENTINEL function."
1490 (if mh-wget-executable
1491 (let ((buffer (get-buffer-create (generate-new-buffer-name
1492 mh-temp-fetch-buffer)))
1493 (filename (or (mh-funcall-if-exists make-temp-file "mhe-fetch")
1494 (expand-file-name (make-temp-name "~/mhe-fetch")))))
1495 (save-excursion
1496 (set-buffer buffer)
1497 (set (make-local-variable 'mh-x-image-url-cache-file) cache-file)
1498 (set (make-local-variable 'mh-x-image-marker) marker)
1499 (set (make-local-variable 'mh-x-image-temp-file) filename))
1500 (set-process-sentinel
1501 (start-process "*mh-x-image-url-fetch*" buffer
1502 mh-wget-executable mh-wget-option filename url)
1503 sentinel))
1504 ;; Temporary failure
1505 (mh-x-image-set-download-state cache-file 'try-again)))
1507 (defun mh-x-image-display (image marker)
1508 "Display IMAGE at MARKER."
1509 (save-excursion
1510 (set-buffer (marker-buffer marker))
1511 (let ((buffer-read-only nil)
1512 (default-enable-multibyte-characters nil)
1513 (buffer-modified-flag (buffer-modified-p)))
1514 (unwind-protect
1515 (when (and (file-readable-p image) (not (file-symlink-p image))
1516 (eq marker mh-x-image-marker))
1517 (goto-char marker)
1518 (mh-do-in-gnu-emacs
1519 (mh-funcall-if-exists insert-image (create-image image 'png)))
1520 (mh-do-in-xemacs
1521 (when (featurep 'png)
1522 (set-extent-begin-glyph
1523 (make-extent (point) (point))
1524 (make-glyph
1525 (vector 'png ':data (with-temp-buffer
1526 (insert-file-contents-literally image)
1527 (buffer-string))))))))
1528 (set-buffer-modified-p buffer-modified-flag)))))
1530 (defun mh-x-image-scale-and-display (process change)
1531 "When the wget PROCESS terminates scale and display image.
1532 The argument CHANGE is ignored."
1533 (when (eq (process-status process) 'exit)
1534 (let (marker temp-file cache-filename wget-buffer)
1535 (save-excursion
1536 (set-buffer (setq wget-buffer (process-buffer process)))
1537 (setq marker mh-x-image-marker
1538 cache-filename mh-x-image-url-cache-file
1539 temp-file mh-x-image-temp-file))
1540 (cond
1541 ;; Check if we have `convert'
1542 ((eq mh-x-image-scaling-function 'ignore)
1543 (message "The `convert' program is needed to display X-Image-URL")
1544 (mh-x-image-set-download-state cache-filename 'try-again))
1545 ;; Scale fetched image
1546 ((and (funcall mh-x-image-scaling-function temp-file cache-filename)
1547 nil))
1548 ;; Attempt to display image if we have it
1549 ((file-exists-p cache-filename)
1550 (mh-x-image-display cache-filename marker))
1551 ;; We didn't find the image. Should we try to display it the next time?
1552 (t (mh-x-image-set-download-state cache-filename 'try-again)))
1553 (ignore-errors
1554 (set-marker marker nil)
1555 (delete-process process)
1556 (kill-buffer wget-buffer)
1557 (delete-file temp-file)))))
1559 (defun mh-x-image-url-sane-p (url)
1560 "Check if URL is something sensible."
1561 (let ((len (length url)))
1562 (cond ((< len 5) nil)
1563 ((not (equal (substring url 0 5) "http:")) nil)
1564 ((> len 100) nil)
1565 (t t))))
1567 (defun mh-x-image-url-display (url)
1568 "Display image from location URL.
1569 If the URL isn't present in the cache then it is fetched with wget."
1570 (let* ((cache-filename (mh-x-image-url-cache-canonicalize url))
1571 (state (mh-x-image-get-download-state cache-filename))
1572 (marker (set-marker (make-marker) (point))))
1573 (set (make-local-variable 'mh-x-image-marker) marker)
1574 (cond ((not (mh-x-image-url-sane-p url)))
1575 ((eq state 'ok)
1576 (mh-x-image-display cache-filename marker))
1577 ((or (not mh-wget-executable)
1578 (eq mh-x-image-scaling-function 'ignore)))
1579 ((eq state 'never))
1580 ((not mh-fetch-x-image-url)
1581 (set-marker marker nil))
1582 ((eq state 'try-again)
1583 (mh-x-image-set-download-state cache-filename nil)
1584 (mh-x-image-url-fetch-image url cache-filename marker
1585 'mh-x-image-scale-and-display))
1586 ((and (eq mh-fetch-x-image-url 'ask)
1587 (not (y-or-n-p (format "Fetch %s? " url))))
1588 (mh-x-image-set-download-state cache-filename 'never))
1589 ((eq state nil)
1590 (mh-x-image-url-fetch-image url cache-filename marker
1591 'mh-x-image-scale-and-display)))))
1595 (defun mh-maybe-show (&optional msg)
1596 "Display message at cursor, but only if in show mode.
1597 If optional arg MSG is non-nil, display that message instead."
1598 (if mh-showing-mode (mh-show msg)))
1600 (defun mh-show (&optional message redisplay-flag)
1601 "Display message\\<mh-folder-mode-map>.
1603 If the message under the cursor is already displayed, this command
1604 scrolls to the beginning of the message. MH-E normally hides a lot of
1605 the superfluous header fields that mailers add to a message, but if
1606 you wish to see all of them, use the command \\[mh-header-display].
1608 From a program, optional argument MESSAGE can be used to display an
1609 alternative message. The optional argument REDISPLAY-FLAG forces the
1610 redisplay of the message even if the show buffer was already
1611 displaying the correct message.
1613 See the \"mh-show\" customization group for a litany of options that
1614 control what displayed messages look like."
1615 (interactive (list nil t))
1616 (when (or redisplay-flag
1617 (and mh-showing-with-headers
1618 (or mh-mhl-format-file mh-clean-message-header-flag)))
1619 (mh-invalidate-show-buffer))
1620 (mh-show-msg message))
1622 (defun mh-show-mouse (event)
1623 "Move point to mouse EVENT and show message."
1624 (interactive "e")
1625 (mouse-set-point event)
1626 (mh-show))
1628 (defun mh-summary-height ()
1629 "Return ideal value for the variable `mh-summary-height'.
1630 The current frame height is taken into consideration."
1631 (or (and (fboundp 'frame-height)
1632 (> (frame-height) 24)
1633 (min 10 (/ (frame-height) 6)))
1636 (defun mh-show-msg (msg)
1637 "Show MSG.
1639 The hook `mh-show-hook' is called after the message has been
1640 displayed."
1641 (if (not msg)
1642 (setq msg (mh-get-msg-num t)))
1643 (mh-showing-mode t)
1644 (setq mh-page-to-next-msg-flag nil)
1645 (let ((folder mh-current-folder)
1646 (folders (list mh-current-folder))
1647 (clean-message-header mh-clean-message-header-flag)
1648 (show-window (get-buffer-window mh-show-buffer))
1649 (display-mime-buttons-flag mh-display-buttons-for-inline-parts-flag))
1650 (if (not (eq (next-window (minibuffer-window)) (selected-window)))
1651 (delete-other-windows)) ; force ourself to the top window
1652 (mh-in-show-buffer (mh-show-buffer)
1653 (setq mh-display-buttons-for-inline-parts-flag display-mime-buttons-flag)
1654 (if (and show-window
1655 (equal (mh-msg-filename msg folder) buffer-file-name))
1656 (progn ;just back up to start
1657 (goto-char (point-min))
1658 (if (not clean-message-header)
1659 (mh-start-of-uncleaned-message)))
1660 (mh-display-msg msg folder)))
1661 (if (not (= (1+ (window-height)) (frame-height))) ;not horizontally split
1662 (shrink-window (- (window-height) (or mh-summary-height
1663 (mh-summary-height)))))
1664 (mh-recenter nil)
1665 ;; The following line is a nop which forces update of the scan line so
1666 ;; that font-lock will update it (if needed)...
1667 (mh-notate nil nil mh-cmd-note)
1668 (if (not (memq msg mh-seen-list))
1669 (setq mh-seen-list (cons msg mh-seen-list)))
1670 (when mh-update-sequences-after-mh-show-flag
1671 (mh-update-sequences)
1672 (when mh-index-data
1673 (setq folders
1674 (append (mh-index-delete-from-sequence mh-unseen-seq (list msg))
1675 folders)))
1676 (when (mh-speed-flists-active-p)
1677 (apply #'mh-speed-flists t folders)))
1678 (run-hooks 'mh-show-hook)))
1680 (defun mh-modify (&optional message)
1681 "Edit message.
1683 There are times when you need to edit a message. For example, you
1684 may need to fix a broken Content-Type header field. You can do
1685 this with this command. It displays the raw message in an
1686 editable buffer. When you are done editing, save and kill the
1687 buffer as you would any other.
1689 From a program, edit MESSAGE instead if it is non-nil."
1690 (interactive)
1691 (let* ((message (or message (mh-get-msg-num t)))
1692 (msg-filename (mh-msg-filename message))
1693 edit-buffer)
1694 (when (not (file-exists-p msg-filename))
1695 (error "Message %d does not exist" message))
1697 ;; Invalidate the show buffer if it is showing the same message that is
1698 ;; to be edited.
1699 (when (and (buffer-live-p (get-buffer mh-show-buffer))
1700 (equal (save-excursion (set-buffer mh-show-buffer)
1701 buffer-file-name)
1702 msg-filename))
1703 (mh-invalidate-show-buffer))
1705 ;; Edit message
1706 (find-file msg-filename)
1707 (setq edit-buffer (current-buffer))
1709 ;; Set buffer properties
1710 (mh-letter-mode)
1711 (use-local-map text-mode-map)
1713 ;; Just show the edit buffer...
1714 (delete-other-windows)
1715 (switch-to-buffer edit-buffer)))
1717 (defun mh-show-unquote-From ()
1718 "Decode >From at beginning of lines for `mh-show-mode'."
1719 (save-excursion
1720 (let ((modified (buffer-modified-p))
1721 (case-fold-search nil)
1722 (buffer-read-only nil))
1723 (goto-char (mh-mail-header-end))
1724 (while (re-search-forward "^>From" nil t)
1725 (replace-match "From"))
1726 (set-buffer-modified-p modified))))
1728 (defun mh-msg-folder (folder-name)
1729 "Return the name of the buffer for FOLDER-NAME."
1730 folder-name)
1732 (defun mh-display-msg (msg-num folder-name)
1733 "Display MSG-NUM of FOLDER-NAME.
1734 Sets the current buffer to the show buffer."
1735 (let ((folder (mh-msg-folder folder-name)))
1736 (set-buffer folder)
1737 ;; When Gnus uses external displayers it has to keep handles longer. So
1738 ;; we will delete these handles when mh-quit is called on the folder. It
1739 ;; would be nicer if there are weak pointers in emacs lisp, then we could
1740 ;; get the garbage collector to do this for us.
1741 (unless (mh-buffer-data)
1742 (setf (mh-buffer-data) (mh-make-buffer-data)))
1743 ;; Bind variables in folder buffer in case they are local
1744 (let ((formfile mh-mhl-format-file)
1745 (clean-message-header mh-clean-message-header-flag)
1746 (invisible-headers mh-invisible-header-fields-compiled)
1747 (visible-headers nil)
1748 (msg-filename (mh-msg-filename msg-num folder-name))
1749 (show-buffer mh-show-buffer)
1750 (mm-inline-media-tests mh-mm-inline-media-tests))
1751 (if (not (file-exists-p msg-filename))
1752 (error "Message %d does not exist" msg-num))
1753 (if (and (> mh-show-maximum-size 0)
1754 (> (elt (file-attributes msg-filename) 7)
1755 mh-show-maximum-size)
1756 (not (y-or-n-p
1757 (format
1758 "Message %d (%d bytes) exceeds %d bytes. Display it? "
1759 msg-num (elt (file-attributes msg-filename) 7)
1760 mh-show-maximum-size))))
1761 (error "Message %d not displayed" msg-num))
1762 (set-buffer show-buffer)
1763 (cond ((not (equal msg-filename buffer-file-name))
1764 (mh-unvisit-file)
1765 (setq buffer-read-only nil)
1766 ;; Cleanup old mime handles
1767 (mh-mime-cleanup)
1768 (erase-buffer)
1769 ;; Changing contents, so this hook needs to be reinitialized.
1770 ;; pgp.el uses this.
1771 (if (boundp 'write-contents-hooks) ;Emacs 19
1772 (kill-local-variable 'write-contents-hooks))
1773 (if formfile
1774 (mh-exec-lib-cmd-output "mhl" "-nobell" "-noclear"
1775 (if (stringp formfile)
1776 (list "-form" formfile))
1777 msg-filename)
1778 (insert-file-contents-literally msg-filename))
1779 ;; Use mm to display buffer
1780 (when (and mh-decode-mime-flag (not formfile))
1781 (mh-add-missing-mime-version-header)
1782 (setf (mh-buffer-data) (mh-make-buffer-data))
1783 (mh-mime-display))
1784 (mh-show-mode)
1785 ;; Header cleanup
1786 (goto-char (point-min))
1787 (cond (clean-message-header
1788 (mh-clean-msg-header (point-min)
1789 invisible-headers
1790 visible-headers)
1791 (goto-char (point-min)))
1793 (mh-start-of-uncleaned-message)))
1794 (mh-decode-message-header)
1795 ;; the parts of visiting we want to do (no locking)
1796 (or (eq buffer-undo-list t) ;don't save undo info for prev msgs
1797 (setq buffer-undo-list nil))
1798 (set-buffer-auto-saved)
1799 ;; the parts of set-visited-file-name we want to do (no locking)
1800 (setq buffer-file-name msg-filename)
1801 (setq buffer-backed-up nil)
1802 (auto-save-mode 1)
1803 (set-mark nil)
1804 (unwind-protect
1805 (when (and mh-decode-mime-flag (not formfile))
1806 (setq buffer-read-only nil)
1807 (mh-display-smileys)
1808 (mh-display-emphasis))
1809 (setq buffer-read-only t))
1810 (set-buffer-modified-p nil)
1811 (setq mh-show-folder-buffer folder)
1812 (setq mode-line-buffer-identification
1813 (list (format mh-show-buffer-mode-line-buffer-id
1814 folder-name msg-num)))
1815 (mh-logo-display)
1816 (set-buffer folder)
1817 (setq mh-showing-with-headers nil))))))
1819 (defun mh-clean-msg-header (start invisible-headers visible-headers)
1820 "Flush extraneous lines in message header.
1822 Header is cleaned from START to the end of the message header.
1823 INVISIBLE-HEADERS contains a regular expression specifying lines
1824 to delete from the header. VISIBLE-HEADERS contains a regular
1825 expression specifying the lines to display. INVISIBLE-HEADERS is
1826 ignored if VISIBLE-HEADERS is non-nil."
1827 ;; XXX Note that MH-E no longer supports the `mh-visible-headers'
1828 ;; variable, so this function could be trimmed of this feature too."
1829 (let ((case-fold-search t)
1830 (buffer-read-only nil)
1831 (after-change-functions nil)) ;Work around emacs-20 font-lock bug
1832 ;causing an endless loop.
1833 (save-restriction
1834 (goto-char start)
1835 (if (search-forward "\n\n" nil 'move)
1836 (backward-char 1))
1837 (narrow-to-region start (point))
1838 (goto-char (point-min))
1839 (if visible-headers
1840 (while (< (point) (point-max))
1841 (cond ((looking-at visible-headers)
1842 (forward-line 1)
1843 (while (looking-at "[ \t]") (forward-line 1)))
1845 (mh-delete-line 1)
1846 (while (looking-at "[ \t]")
1847 (mh-delete-line 1)))))
1848 (while (re-search-forward invisible-headers nil t)
1849 (beginning-of-line)
1850 (mh-delete-line 1)
1851 (while (looking-at "[ \t]")
1852 (mh-delete-line 1)))))
1853 (let ((mh-compose-skipped-header-fields ()))
1854 (mh-letter-hide-all-skipped-fields))
1855 (unlock-buffer)))
1857 (defun mh-delete-line (lines)
1858 "Delete the next LINES lines."
1859 (delete-region (point) (progn (forward-line lines) (point))))
1861 (defun mh-notate (msg notation offset)
1862 "Mark MSG with the character NOTATION at position OFFSET.
1863 Null MSG means the message at cursor.
1864 If NOTATION is nil then no change in the buffer occurs."
1865 (save-excursion
1866 (if (or (null msg)
1867 (mh-goto-msg msg t t))
1868 (with-mh-folder-updating (t)
1869 (beginning-of-line)
1870 (forward-char offset)
1871 (let* ((change-stack-flag
1872 (and (equal offset
1873 (+ mh-cmd-note mh-scan-field-destination-offset))
1874 (not (eq notation mh-note-seq))))
1875 (msg (and change-stack-flag (or msg (mh-get-msg-num nil))))
1876 (stack (and msg (gethash msg mh-sequence-notation-history)))
1877 (notation (or notation (char-after))))
1878 (if stack
1879 ;; The presence of the stack tells us that we don't need to
1880 ;; notate the message, since the notation would be replaced
1881 ;; by a sequence notation. So we will just put the notation
1882 ;; at the bottom of the stack. If the sequence is deleted,
1883 ;; the correct notation will be shown.
1884 (setf (gethash msg mh-sequence-notation-history)
1885 (reverse (cons notation (cdr (reverse stack)))))
1886 ;; Since we don't have any sequence notations in the way, just
1887 ;; notate the scan line.
1888 (delete-char 1)
1889 (insert notation))
1890 (when change-stack-flag
1891 (mh-thread-update-scan-line-map msg notation offset)))))))
1893 (defun mh-goto-msg (number &optional no-error-if-no-message dont-show)
1894 "Go to a message\\<mh-folder-mode-map>.
1896 You can enter the message NUMBER either before or after typing
1897 \\[mh-goto-msg]. In the latter case, Emacs prompts you.
1899 In a program, optional non-nil second argument NO-ERROR-IF-NO-MESSAGE
1900 means return nil instead of signaling an error if message does not
1901 exist\; in this case, the cursor is positioned near where the message
1902 would have been. Non-nil third argument DONT-SHOW means not to show
1903 the message."
1904 (interactive "NGo to message: ")
1905 (setq number (prefix-numeric-value number))
1906 (let ((point (point))
1907 (return-value t))
1908 (goto-char (point-min))
1909 (unless (re-search-forward (format mh-scan-msg-search-regexp number) nil t)
1910 (goto-char point)
1911 (unless no-error-if-no-message
1912 (error "No message %d" number))
1913 (setq return-value nil))
1914 (beginning-of-line)
1915 (or dont-show (not return-value) (mh-maybe-show number))
1916 return-value))
1918 (defun mh-get-profile-field (field)
1919 "Find and return the value of FIELD in the current buffer.
1920 Returns nil if the field is not in the buffer."
1921 (let ((case-fold-search t))
1922 (goto-char (point-min))
1923 (cond ((not (re-search-forward (format "^%s" field) nil t)) nil)
1924 ((looking-at "[\t ]*$") nil)
1926 (re-search-forward "[\t ]*\\([^\t \n].*\\)$" nil t)
1927 (let ((start (match-beginning 1)))
1928 (end-of-line)
1929 (buffer-substring start (point)))))))
1931 (defvar mh-find-path-run nil
1932 "Non-nil if `mh-find-path' has been run already.")
1934 (defun mh-find-path ()
1935 "Set variables from user's MH profile.
1937 This function sets `mh-user-path' from your \"Path:\" MH profile
1938 component (but defaults to \"Mail\" if one isn't present),
1939 `mh-draft-folder' from \"Draft-Folder:\", `mh-unseen-seq' from
1940 \"Unseen-Sequence:\", `mh-previous-seq' from
1941 \"Previous-Sequence:\", and `mh-inbox' from \"Inbox:\" (defaults
1942 to \"+inbox\").
1944 The hook `mh-find-path-hook' is run after these variables have
1945 been set. This hook can be used the change the value of these
1946 variables if you need to run with different values between MH and
1947 MH-E."
1948 (mh-variants)
1949 (unless mh-find-path-run
1950 (setq mh-find-path-run t)
1951 (save-excursion
1952 ;; Be sure profile is fully expanded before switching buffers
1953 (let ((profile (expand-file-name (or (getenv "MH") "~/.mh_profile"))))
1954 (set-buffer (get-buffer-create mh-temp-buffer))
1955 (setq buffer-offer-save nil) ;for people who set default to t
1956 (erase-buffer)
1957 (condition-case err
1958 (insert-file-contents profile)
1959 (file-error
1960 (mh-install profile err)))
1961 (setq mh-user-path (mh-get-profile-field "Path:"))
1962 (if (not mh-user-path)
1963 (setq mh-user-path "Mail"))
1964 (setq mh-user-path
1965 (file-name-as-directory
1966 (expand-file-name mh-user-path (expand-file-name "~"))))
1967 (unless mh-x-image-cache-directory
1968 (setq mh-x-image-cache-directory
1969 (expand-file-name ".mhe-x-image-cache" mh-user-path)))
1970 (setq mh-draft-folder (mh-get-profile-field "Draft-Folder:"))
1971 (if mh-draft-folder
1972 (progn
1973 (if (not (mh-folder-name-p mh-draft-folder))
1974 (setq mh-draft-folder (format "+%s" mh-draft-folder)))
1975 (if (not (file-exists-p (mh-expand-file-name mh-draft-folder)))
1976 (error
1977 "Draft folder \"%s\" not found. Create it and try again"
1978 (mh-expand-file-name mh-draft-folder)))))
1979 (setq mh-inbox (mh-get-profile-field "Inbox:"))
1980 (cond ((not mh-inbox)
1981 (setq mh-inbox "+inbox"))
1982 ((not (mh-folder-name-p mh-inbox))
1983 (setq mh-inbox (format "+%s" mh-inbox))))
1984 (setq mh-unseen-seq (mh-get-profile-field "Unseen-Sequence:"))
1985 (if mh-unseen-seq
1986 (setq mh-unseen-seq (intern mh-unseen-seq))
1987 (setq mh-unseen-seq 'unseen)) ;old MH default?
1988 (setq mh-previous-seq (mh-get-profile-field "Previous-Sequence:"))
1989 (if mh-previous-seq
1990 (setq mh-previous-seq (intern mh-previous-seq)))
1991 (run-hooks 'mh-find-path-hook)
1992 (mh-collect-folder-names)))))
1994 (defun mh-file-command-p (file)
1995 "Return t if file FILE is the name of a executable regular file."
1996 (and (file-regular-p file) (file-executable-p file)))
1998 (defvar mh-no-install nil) ;do not run install-mh
2000 (defun mh-install (profile error-val)
2001 "Initialize the MH environment.
2002 This is called if we fail to read the PROFILE file. ERROR-VAL is
2003 the error that made this call necessary."
2004 (if (or (getenv "MH")
2005 (file-exists-p profile)
2006 mh-no-install)
2007 (signal (car error-val)
2008 (list (format "Cannot read MH profile \"%s\"" profile)
2009 (car (cdr (cdr error-val))))))
2010 ;; The "install-mh" command will output a short note which
2011 ;; mh-exec-cmd will display to the user.
2012 ;; The MH 5 version of install-mh might try prompt the user
2013 ;; for information, which would fail here.
2014 (mh-exec-cmd (expand-file-name "install-mh" mh-lib-progs) "-auto")
2015 ;; now try again to read the profile file
2016 (erase-buffer)
2017 (condition-case err
2018 (insert-file-contents profile)
2019 (file-error
2020 (signal (car err) ;re-signal with more specific msg
2021 (list (format "Cannot read MH profile \"%s\"" profile)
2022 (car (cdr (cdr err))))))))
2024 (defun mh-set-folder-modified-p (flag)
2025 "Mark current folder as modified or unmodified according to FLAG."
2026 (set-buffer-modified-p flag))
2028 (defun mh-find-seq (name)
2029 "Return sequence NAME."
2030 (assoc name mh-seq-list))
2032 (defun mh-seq-to-msgs (seq)
2033 "Return a list of the messages in SEQ."
2034 (mh-seq-msgs (mh-find-seq seq)))
2036 (defun mh-update-scan-format (fmt width)
2037 "Return a scan format with the (msg) width in the FMT replaced with WIDTH.
2039 The message number width portion of the format is discovered
2040 using `mh-scan-msg-format-regexp'. Its replacement is controlled
2041 with `mh-scan-msg-format-string'."
2042 (or (and
2043 (string-match mh-scan-msg-format-regexp fmt)
2044 (let ((begin (match-beginning 1))
2045 (end (match-end 1)))
2046 (concat (substring fmt 0 begin)
2047 (format mh-scan-msg-format-string width)
2048 (substring fmt end))))
2049 fmt))
2051 (defun mh-msg-num-width (folder)
2052 "Return the width of the largest message number in this FOLDER."
2053 (or mh-progs (mh-find-path))
2054 (let ((tmp-buffer (get-buffer-create mh-temp-buffer))
2055 (width 0))
2056 (save-excursion
2057 (set-buffer tmp-buffer)
2058 (erase-buffer)
2059 (apply 'call-process
2060 (expand-file-name mh-scan-prog mh-progs) nil '(t nil) nil
2061 (list folder "last" "-format" "%(msg)"))
2062 (goto-char (point-min))
2063 (if (re-search-forward mh-scan-msg-number-regexp nil 0 1)
2064 (setq width (length (buffer-substring
2065 (match-beginning 1) (match-end 1))))))
2066 width))
2068 (defun mh-add-msgs-to-seq (msgs seq &optional internal-flag dont-annotate-flag)
2069 "Add MSGS to SEQ.
2071 Remove duplicates and keep sequence sorted. If optional
2072 INTERNAL-FLAG is non-nil, do not mark the message in the scan
2073 listing or inform MH of the addition.
2075 If DONT-ANNOTATE-FLAG is non-nil then the annotations in the
2076 folder buffer are not updated."
2077 (let ((entry (mh-find-seq seq))
2078 (internal-seq-flag (mh-internal-seq seq)))
2079 (if (and msgs (atom msgs)) (setq msgs (list msgs)))
2080 (if (null entry)
2081 (setq mh-seq-list
2082 (cons (mh-make-seq seq (mh-canonicalize-sequence msgs))
2083 mh-seq-list))
2084 (if msgs (setcdr entry (mh-canonicalize-sequence
2085 (append msgs (mh-seq-msgs entry))))))
2086 (unless internal-flag
2087 (mh-add-to-sequence seq msgs)
2088 (when (not dont-annotate-flag)
2089 (mh-iterate-on-range msg msgs
2090 (unless (memq msg (cdr entry))
2091 (mh-add-sequence-notation msg internal-seq-flag)))))))
2093 (defun mh-canonicalize-sequence (msgs)
2094 "Sort MSGS in decreasing order and remove duplicates."
2095 (let* ((sorted-msgs (sort (copy-sequence msgs) '>))
2096 (head sorted-msgs))
2097 (while (cdr head)
2098 (if (= (car head) (cadr head))
2099 (setcdr head (cddr head))
2100 (setq head (cdr head))))
2101 sorted-msgs))
2103 (defvar mh-sub-folders-cache (make-hash-table :test #'equal))
2104 (defvar mh-current-folder-name nil)
2105 (defvar mh-flists-partial-line "")
2106 (defvar mh-flists-process nil)
2108 ;; Initialize mh-sub-folders-cache...
2109 (defun mh-collect-folder-names ()
2110 "Collect folder names by running \"flists\"."
2111 (unless mh-flists-process
2112 (setq mh-flists-process
2113 (mh-exec-cmd-daemon "folders" 'mh-collect-folder-names-filter
2114 "-recurse" "-fast"))))
2116 (defun mh-collect-folder-names-filter (process output)
2117 "Read folder names.
2118 PROCESS is the flists process that was run to collect folder
2119 names and the function is called when OUTPUT is available."
2120 (let ((position 0)
2121 (prevailing-match-data (match-data))
2122 line-end folder)
2123 (unwind-protect
2124 (while (setq line-end (string-match "\n" output position))
2125 (setq folder (format "+%s%s"
2126 mh-flists-partial-line
2127 (substring output position line-end)))
2128 (setq mh-flists-partial-line "")
2129 (unless (equal (aref folder 1) ?.)
2130 (mh-populate-sub-folders-cache folder))
2131 (setq position (1+ line-end)))
2132 (set-match-data prevailing-match-data))
2133 (setq mh-flists-partial-line (substring output position))))
2135 (defun mh-populate-sub-folders-cache (folder)
2136 "Tell `mh-sub-folders-cache' about FOLDER."
2137 (let* ((last-slash (mh-search-from-end ?/ folder))
2138 (child1 (substring folder (1+ (or last-slash 0))))
2139 (parent (and last-slash (substring folder 0 last-slash)))
2140 (parent-slash (and parent (mh-search-from-end ?/ parent)))
2141 (child2 (and parent (substring parent (1+ (or parent-slash 0)))))
2142 (grand-parent (and parent-slash (substring parent 0 parent-slash)))
2143 (cache-entry (gethash parent mh-sub-folders-cache)))
2144 (unless (loop for x in cache-entry when (equal (car x) child1) return t
2145 finally return nil)
2146 (push (list child1) cache-entry)
2147 (setf (gethash parent mh-sub-folders-cache)
2148 (sort cache-entry (lambda (x y) (string< (car x) (car y)))))
2149 (when parent
2150 (loop for x in (gethash grand-parent mh-sub-folders-cache)
2151 when (equal (car x) child2)
2152 do (progn (setf (cdr x) t) (return)))))))
2154 (defun mh-normalize-folder-name (folder &optional empty-string-okay
2155 dont-remove-trailing-slash)
2156 "Normalizes FOLDER name.
2158 Makes sure that two '/' characters never occur next to each
2159 other. Also all occurrences of \"..\" and \".\" are suitably
2160 processed. So \"+inbox/../news\" will be normalized to \"+news\".
2162 If optional argument EMPTY-STRING-OKAY is nil then a '+' is added
2163 at the front if FOLDER lacks one. If non-nil and FOLDER is the
2164 empty string then nothing is added.
2166 If optional argument DONT-REMOVE-TRAILING-SLASH is non-nil then a
2167 trailing '/' if present is retained (if present), otherwise it is
2168 removed."
2169 (when (stringp folder)
2170 ;; Replace two or more consecutive '/' characters with a single '/'
2171 (while (string-match "//" folder)
2172 (setq folder (replace-match "/" nil t folder)))
2173 (let* ((length (length folder))
2174 (trailing-slash-present (and (> length 0)
2175 (equal (aref folder (1- length)) ?/)))
2176 (leading-slash-present (and (> length 0)
2177 (equal (aref folder 0) ?/))))
2178 (when (and (> length 0) (equal (aref folder 0) ?@)
2179 (stringp mh-current-folder-name))
2180 (setq folder (format "%s/%s/" mh-current-folder-name
2181 (substring folder 1))))
2182 ;; XXX: Purge empty strings from the list that split-string returns. In
2183 ;; XEmacs, (split-string "+foo/" "/") returns ("+foo" "") while in GNU
2184 ;; Emacs it returns ("+foo"). In the code it is assumed that the
2185 ;; components list has no empty strings.
2186 (let ((components (delete "" (split-string folder "/")))
2187 (result ()))
2188 ;; Remove .. and . from the pathname.
2189 (dolist (component components)
2190 (cond ((and (equal component "..") result)
2191 (pop result))
2192 ((equal component ".."))
2193 ((equal component "."))
2194 (t (push component result))))
2195 (setq folder "")
2196 (dolist (component result)
2197 (setq folder (concat component "/" folder)))
2198 ;; Remove trailing '/' if needed.
2199 (unless (and trailing-slash-present dont-remove-trailing-slash)
2200 (when (not (equal folder ""))
2201 (setq folder (substring folder 0 (1- (length folder))))))
2202 (when leading-slash-present
2203 (setq folder (concat "/" folder)))))
2204 (cond ((and empty-string-okay (equal folder "")))
2205 ((equal folder "") (setq folder "+"))
2206 ((not (equal (aref folder 0) ?+)) (setq folder (concat "+" folder)))))
2207 folder)
2209 (defun mh-sub-folders (folder &optional add-trailing-slash-flag)
2210 "Find the subfolders of FOLDER.
2211 The function avoids running folders unnecessarily by caching the
2212 results of the actual folders call.
2214 If optional argument ADD-TRAILING-SLASH-FLAG is non-nil then a
2215 slash is added to each of the sub-folder names that may have
2216 nested folders within them."
2217 (let* ((folder (mh-normalize-folder-name folder))
2218 (match (gethash folder mh-sub-folders-cache 'no-result))
2219 (sub-folders (cond ((eq match 'no-result)
2220 (setf (gethash folder mh-sub-folders-cache)
2221 (mh-sub-folders-actual folder)))
2222 (t match))))
2223 (if add-trailing-slash-flag
2224 (mapcar #'(lambda (x)
2225 (if (cdr x) (cons (concat (car x) "/") (cdr x)) x))
2226 sub-folders)
2227 sub-folders)))
2229 (defun mh-sub-folders-actual (folder)
2230 "Execute the command folders to return the sub-folders of FOLDER.
2231 Filters out the folder names that start with \".\" so that
2232 directories that aren't usually mail folders are hidden."
2233 (let ((arg-list `(,(expand-file-name "folders" mh-progs)
2234 nil (t nil) nil "-noheader" "-norecurse" "-nototal"
2235 ,@(if (stringp folder) (list folder) ())))
2236 (results ())
2237 (current-folder (concat
2238 (with-temp-buffer
2239 (call-process (expand-file-name "folder" mh-progs)
2240 nil '(t nil) nil "-fast")
2241 (buffer-substring (point-min) (1- (point-max))))
2242 "+")))
2243 (with-temp-buffer
2244 (apply #'call-process arg-list)
2245 (goto-char (point-min))
2246 (while (not (and (eolp) (bolp)))
2247 (goto-char (line-end-position))
2248 (let ((start-pos (line-beginning-position))
2249 (has-pos (search-backward " has " (line-beginning-position) t)))
2250 (when (integerp has-pos)
2251 (while (equal (char-after has-pos) ? )
2252 (decf has-pos))
2253 (incf has-pos)
2254 (while (equal (char-after start-pos) ? )
2255 (incf start-pos))
2256 (let* ((name (buffer-substring start-pos has-pos))
2257 (first-char (aref name 0))
2258 (last-char (aref name (1- (length name)))))
2259 (unless (member first-char '(?. ?# ?,))
2260 (when (and (equal last-char ?+) (equal name current-folder))
2261 (setq name (substring name 0 (1- (length name)))))
2262 (push
2263 (cons name
2264 (search-forward "(others)" (line-end-position) t))
2265 results))))
2266 (forward-line 1))))
2267 (setq results (nreverse results))
2268 (when (stringp folder)
2269 (setq results (cdr results))
2270 (let ((folder-name-len (length (format "%s/" (substring folder 1)))))
2271 (setq results (mapcar (lambda (f)
2272 (cons (substring (car f) folder-name-len)
2273 (cdr f)))
2274 results))))
2275 results))
2277 (defun mh-remove-from-sub-folders-cache (folder)
2278 "Remove FOLDER and its parent from `mh-sub-folders-cache'.
2279 FOLDER should be unconditionally removed from the cache. Also the
2280 last ancestor of FOLDER present in the cache must be removed as
2281 well.
2283 To see why this is needed assume we have a folder +foo which has
2284 a single sub-folder qux. Now we create the folder +foo/bar/baz.
2285 Here we will need to invalidate the cached sub-folders of +foo,
2286 otherwise completion on +foo won't tell us about the option
2287 +foo/bar!"
2288 (remhash folder mh-sub-folders-cache)
2289 (block ancestor-found
2290 (let ((parent folder)
2291 (one-ancestor-found nil)
2292 last-slash)
2293 (while (setq last-slash (mh-search-from-end ?/ parent))
2294 (setq parent (substring parent 0 last-slash))
2295 (unless (eq (gethash parent mh-sub-folders-cache 'none) 'none)
2296 (remhash parent mh-sub-folders-cache)
2297 (if one-ancestor-found
2298 (return-from ancestor-found)
2299 (setq one-ancestor-found t))))
2300 (remhash nil mh-sub-folders-cache))))
2302 (defvar mh-folder-hist nil)
2303 (defvar mh-speed-folder-map)
2304 (defvar mh-speed-flists-cache)
2306 (defvar mh-allow-root-folder-flag nil
2307 "Non-nil means \"+\" is an acceptable folder name.
2308 This variable is used to communicate with
2309 `mh-folder-completion-function'. That function can have exactly
2310 three arguments so we bind this variable to t or nil.
2312 This variable should never be set.")
2314 (defvar mh-folder-completion-map (copy-keymap minibuffer-local-completion-map))
2315 (define-key mh-folder-completion-map " " 'minibuffer-complete) ;Why???
2317 (defvar mh-speed-flists-inhibit-flag nil)
2319 (defun mh-speed-flists-active-p ()
2320 "Check if speedbar is running with message counts enabled."
2321 (and (featurep 'mh-speed)
2322 (not mh-speed-flists-inhibit-flag)
2323 (> (hash-table-count mh-speed-flists-cache) 0)))
2325 (defun mh-folder-completion-function (name predicate flag)
2326 "Programmable completion for folder names.
2327 NAME is the partial folder name that has been input. PREDICATE if
2328 non-nil is a function that is used to filter the possible choices
2329 and FLAG determines whether the completion is over."
2330 (let* ((orig-name name)
2331 (name (mh-normalize-folder-name name nil t))
2332 (last-slash (mh-search-from-end ?/ name))
2333 (last-complete (if last-slash (substring name 0 last-slash) nil))
2334 (remainder (cond (last-complete (substring name (1+ last-slash)))
2335 ((and (> (length name) 0) (equal (aref name 0) ?+))
2336 (substring name 1))
2337 (t ""))))
2338 (cond ((eq flag nil)
2339 (let ((try-res (try-completion
2340 name
2341 (mapcar (lambda (x)
2342 (cons (if (not last-complete)
2343 (concat "+" (car x))
2344 (concat last-complete "/" (car x)))
2345 (cdr x)))
2346 (mh-sub-folders last-complete t))
2347 predicate)))
2348 (cond ((eq try-res nil) nil)
2349 ((and (eq try-res t) (equal name orig-name)) t)
2350 ((eq try-res t) name)
2351 (t try-res))))
2352 ((eq flag t)
2353 (all-completions
2354 remainder (mh-sub-folders last-complete t) predicate))
2355 ((eq flag 'lambda)
2356 (let ((path (concat mh-user-path
2357 (substring (mh-normalize-folder-name name) 1))))
2358 (cond (mh-allow-root-folder-flag (file-exists-p path))
2359 ((equal path mh-user-path) nil)
2360 (t (file-exists-p path))))))))
2362 (defun mh-folder-completing-read (prompt default allow-root-folder-flag)
2363 "Read folder name with PROMPT and default result DEFAULT.
2364 If ALLOW-ROOT-FOLDER-FLAG is non-nil then \"+\" is allowed to be
2365 a folder name corresponding to `mh-user-path'."
2366 (mh-normalize-folder-name
2367 (let ((minibuffer-completing-file-name t)
2368 (completion-root-regexp "^[+/]")
2369 (minibuffer-local-completion-map mh-folder-completion-map)
2370 (mh-allow-root-folder-flag allow-root-folder-flag))
2371 (completing-read prompt 'mh-folder-completion-function nil nil nil
2372 'mh-folder-hist default))
2375 (defun mh-prompt-for-folder (prompt default can-create
2376 &optional default-string allow-root-folder-flag)
2377 "Prompt for a folder name with PROMPT.
2378 Returns the folder's name as a string. DEFAULT is used if the
2379 folder exists and the user types return. If the CAN-CREATE flag
2380 is t, then a folder is created if it doesn't already exist. If
2381 optional argument DEFAULT-STRING is non-nil, use it in the prompt
2382 instead of DEFAULT. If ALLOW-ROOT-FOLDER-FLAG is non-nil then the
2383 function will accept the folder +, which means all folders when
2384 used in searching."
2385 ;; FIXME: can-create is unused!
2386 (if (null default)
2387 (setq default ""))
2388 (let* ((default-string (cond (default-string (format " (default %s)" default-string))
2389 ((equal "" default) "")
2390 (t (format " (default %s)" default))))
2391 (prompt (format "%s folder%s: " prompt default-string))
2392 (mh-current-folder-name mh-current-folder)
2393 read-name folder-name)
2394 (while (and (setq read-name (mh-folder-completing-read
2395 prompt default allow-root-folder-flag))
2396 (equal read-name "")
2397 (equal default "")))
2398 (cond ((or (equal read-name "")
2399 (and (equal read-name "+") (not allow-root-folder-flag)))
2400 (setq read-name default))
2401 ((not (mh-folder-name-p read-name))
2402 (setq read-name (format "+%s" read-name))))
2403 (if (or (not read-name) (equal "" read-name))
2404 (error "No folder specified"))
2405 (setq folder-name read-name)
2406 (cond ((and (> (length folder-name) 0)
2407 (eq (aref folder-name (1- (length folder-name))) ?/))
2408 (setq folder-name (substring folder-name 0 -1))))
2409 (let* ((last-slash (mh-search-from-end ?/ folder-name))
2410 (parent (and last-slash (substring folder-name 0 last-slash)))
2411 (child (if last-slash
2412 (substring folder-name (1+ last-slash))
2413 (substring folder-name 1))))
2414 (unless (member child
2415 (mapcar #'car (gethash parent mh-sub-folders-cache)))
2416 (mh-remove-from-sub-folders-cache folder-name)))
2417 (let ((new-file-flag
2418 (not (file-exists-p (mh-expand-file-name folder-name)))))
2419 (cond ((and new-file-flag
2420 (y-or-n-p
2421 (format "Folder %s does not exist. Create it? "
2422 folder-name)))
2423 (message "Creating %s" folder-name)
2424 (mh-exec-cmd-error nil "folder" folder-name)
2425 (mh-remove-from-sub-folders-cache folder-name)
2426 (when (boundp 'mh-speed-folder-map)
2427 (mh-speed-add-folder folder-name))
2428 (message "Creating %s...done" folder-name))
2429 (new-file-flag
2430 (error "Folder %s is not created" folder-name))
2431 ((not (file-directory-p (mh-expand-file-name folder-name)))
2432 (error "\"%s\" is not a directory"
2433 (mh-expand-file-name folder-name)))))
2434 folder-name))
2436 (defun mh-truncate-log-buffer ()
2437 "If `mh-log-buffer' is too big then truncate it.
2438 If the number of lines in `mh-log-buffer' exceeds
2439 `mh-log-buffer-lines' then keep only the last
2440 `mh-log-buffer-lines'. As a side effect the point is set to the
2441 end of the log buffer.
2443 The function returns the size of the final size of the log buffer."
2444 (with-current-buffer (get-buffer-create mh-log-buffer)
2445 (goto-char (point-max))
2446 (save-excursion
2447 (when (equal (forward-line (- mh-log-buffer-lines)) 0)
2448 (delete-region (point-min) (point))))
2449 (unless (or (bobp)
2450 (save-excursion
2451 (and (equal (forward-line -1) 0) (equal (char-after) ?\f))))
2452 (insert "\n\f\n"))
2453 (buffer-size)))
2457 ;;; Issue commands to MH.
2459 (defun mh-exec-cmd (command &rest args)
2460 "Execute mh-command COMMAND with ARGS.
2461 The side effects are what is desired. Any output is assumed to be
2462 an error and is shown to the user. The output is not read or
2463 parsed by MH-E."
2464 (save-excursion
2465 (set-buffer (get-buffer-create mh-log-buffer))
2466 (let* ((initial-size (mh-truncate-log-buffer))
2467 (start (point))
2468 (args (mh-list-to-string args)))
2469 (apply 'call-process (expand-file-name command mh-progs) nil t nil args)
2470 (when (> (buffer-size) initial-size)
2471 (save-excursion
2472 (goto-char start)
2473 (insert "Errors when executing: " command)
2474 (loop for arg in args do (insert " " arg))
2475 (insert "\n"))
2476 (save-window-excursion
2477 (switch-to-buffer-other-window mh-log-buffer)
2478 (sit-for 5))))))
2480 (defun mh-exec-cmd-error (env command &rest args)
2481 "In environment ENV, execute mh-command COMMAND with ARGS.
2482 ENV is nil or a string of space-separated \"var=value\" elements.
2483 Signals an error if process does not complete successfully."
2484 (save-excursion
2485 (set-buffer (get-buffer-create mh-temp-buffer))
2486 (erase-buffer)
2487 (let ((process-environment process-environment))
2488 ;; XXX: We should purge the list that split-string returns of empty
2489 ;; strings. This can happen in XEmacs if leading or trailing spaces
2490 ;; are present.
2491 (dolist (elem (if (stringp env) (split-string env " ") ()))
2492 (push elem process-environment))
2493 (mh-handle-process-error
2494 command (apply #'call-process (expand-file-name command mh-progs)
2495 nil t nil (mh-list-to-string args))))))
2497 (defun mh-exec-cmd-daemon (command filter &rest args)
2498 "Execute MH command COMMAND in the background.
2500 If FILTER is non-nil then it is used to process the output
2501 otherwise the default filter `mh-process-daemon' is used. See
2502 `set-process-filter' for more details of FILTER.
2504 ARGS are passed to COMMAND as command line arguments."
2505 (save-excursion
2506 (set-buffer (get-buffer-create mh-log-buffer))
2507 (mh-truncate-log-buffer))
2508 (let* ((process-connection-type nil)
2509 (process (apply 'start-process
2510 command nil
2511 (expand-file-name command mh-progs)
2512 (mh-list-to-string args))))
2513 (set-process-filter process (or filter 'mh-process-daemon))
2514 process))
2516 (defun mh-exec-cmd-env-daemon (env command filter &rest args)
2517 "In ennvironment ENV, execute mh-command COMMAND in the background.
2519 ENV is nil or a string of space-separated \"var=value\" elements.
2520 Signals an error if process does not complete successfully.
2522 If FILTER is non-nil then it is used to process the output
2523 otherwise the default filter `mh-process-daemon' is used. See
2524 `set-process-filter' for more details of FILTER.
2526 ARGS are passed to COMMAND as command line arguments."
2527 (let ((process-environment process-environment))
2528 (dolist (elem (if (stringp env) (split-string env " ") ()))
2529 (push elem process-environment))
2530 (apply #'mh-exec-cmd-daemon command filter args)))
2532 (defun mh-process-daemon (process output)
2533 "PROCESS daemon that puts OUTPUT into a temporary buffer.
2534 Any output from the process is displayed in an asynchronous
2535 pop-up window."
2536 (with-current-buffer (get-buffer-create mh-log-buffer)
2537 (insert-before-markers output)
2538 (display-buffer mh-log-buffer)))
2540 (defun mh-exec-cmd-quiet (raise-error command &rest args)
2541 "Signal RAISE-ERROR if COMMAND with ARGS fails.
2542 Execute MH command COMMAND with ARGS. ARGS is a list of strings.
2543 Return at start of mh-temp buffer, where output can be parsed and
2544 used.
2545 Returns value of `call-process', which is 0 for success, unless
2546 RAISE-ERROR is non-nil, in which case an error is signaled if
2547 `call-process' returns non-0."
2548 (set-buffer (get-buffer-create mh-temp-buffer))
2549 (erase-buffer)
2550 (let ((value
2551 (apply 'call-process
2552 (expand-file-name command mh-progs) nil t nil
2553 args)))
2554 (goto-char (point-min))
2555 (if raise-error
2556 (mh-handle-process-error command value)
2557 value)))
2559 (defun mh-profile-component (component)
2560 "Return COMPONENT value from mhparam, or nil if unset."
2561 (save-excursion
2562 (mh-exec-cmd-quiet nil "mhparam" "-components" component)
2563 (mh-get-profile-field (concat component ":"))))
2565 (defun mh-exchange-point-and-mark-preserving-active-mark ()
2566 "Put the mark where point is now, and point where the mark is now.
2567 This command works even when the mark is not active, and
2568 preserves whether the mark is active or not."
2569 (interactive nil)
2570 (let ((is-active (and (boundp 'mark-active) mark-active)))
2571 (let ((omark (mark t)))
2572 (if (null omark)
2573 (error "No mark set in this buffer"))
2574 (set-mark (point))
2575 (goto-char omark)
2576 (if (boundp 'mark-active)
2577 (setq mark-active is-active))
2578 nil)))
2580 (defun mh-exec-cmd-output (command display &rest args)
2581 "Execute MH command COMMAND with DISPLAY flag and ARGS.
2582 Put the output into buffer after point.
2583 Set mark after inserted text.
2584 Output is expected to be shown to user, not parsed by MH-E."
2585 (push-mark (point) t)
2586 (apply 'call-process
2587 (expand-file-name command mh-progs) nil t display
2588 (mh-list-to-string args))
2590 ;; The following is used instead of 'exchange-point-and-mark because the
2591 ;; latter activates the current region (between point and mark), which
2592 ;; turns on highlighting. So prior to this bug fix, doing "inc" would
2593 ;; highlight a region containing the new messages, which is undesirable.
2594 ;; The bug wasn't seen in emacs21 but still occurred in XEmacs21.4.
2595 (mh-exchange-point-and-mark-preserving-active-mark))
2597 (defun mh-exec-lib-cmd-output (command &rest args)
2598 "Execute MH library command COMMAND with ARGS.
2599 Put the output into buffer after point.
2600 Set mark after inserted text."
2601 (apply 'mh-exec-cmd-output (expand-file-name command mh-lib-progs) nil args))
2603 (defun mh-handle-process-error (command status)
2604 "Raise error if COMMAND returned non-zero STATUS, otherwise return STATUS."
2605 (if (equal status 0)
2606 status
2607 (goto-char (point-min))
2608 (insert (if (integerp status)
2609 (format "%s: exit code %d\n" command status)
2610 (format "%s: %s\n" command status)))
2611 (save-excursion
2612 (let ((error-message (buffer-substring (point-min) (point-max))))
2613 (set-buffer (get-buffer-create mh-log-buffer))
2614 (mh-truncate-log-buffer)
2615 (insert error-message)))
2616 (error "%s failed, check %s buffer for error message"
2617 command mh-log-buffer)))
2619 (defun mh-list-to-string (l)
2620 "Flatten the list L and make every element of the new list into a string."
2621 (nreverse (mh-list-to-string-1 l)))
2623 (defun mh-list-to-string-1 (l)
2624 "Flatten the list L and make every element of the new list into a string."
2625 (let ((new-list nil))
2626 (while l
2627 (cond ((null (car l)))
2628 ((symbolp (car l))
2629 (setq new-list (cons (symbol-name (car l)) new-list)))
2630 ((numberp (car l))
2631 (setq new-list (cons (int-to-string (car l)) new-list)))
2632 ((equal (car l) ""))
2633 ((stringp (car l)) (setq new-list (cons (car l) new-list)))
2634 ((listp (car l))
2635 (setq new-list (nconc (mh-list-to-string-1 (car l))
2636 new-list)))
2637 (t (error "Bad element in mh-list-to-string: %s" (car l))))
2638 (setq l (cdr l)))
2639 new-list))
2641 (defun mh-replace-string (old new)
2642 "Replace all occurrences of OLD with NEW in the current buffer."
2643 (goto-char (point-min))
2644 (let ((case-fold-search t))
2645 (while (search-forward old nil t)
2646 (replace-match new t t))))
2648 (defun mh-replace-in-string (regexp newtext string)
2649 "Replace REGEXP with NEWTEXT everywhere in STRING and return result.
2650 NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
2652 The function body was copied from `dired-replace-in-string' in
2653 dired.el.
2654 Emacs21 has `replace-regexp-in-string' while XEmacs has
2655 `replace-in-string'.
2656 Neither is present in Emacs20. The file gnus-util.el in Gnus 5.10.1
2657 and above has `gnus-replace-in-string'. We should use that when we
2658 decide to not support older versions of Gnus."
2659 (let ((result "") (start 0) mb me)
2660 (while (string-match regexp string start)
2661 (setq mb (match-beginning 0)
2662 me (match-end 0)
2663 result (concat result (substring string start mb) newtext)
2664 start me))
2665 (concat result (substring string start))))
2667 (provide 'mh-utils)
2669 ;; Local Variables:
2670 ;; indent-tabs-mode: nil
2671 ;; sentence-end-double-space: nil
2672 ;; End:
2674 ;; arch-tag: 1af39fdf-f66f-4b06-9b48-18a7656c8e36
2675 ;;; mh-utils.el ends here