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