2005-09-24 Emilio C. Lopes <eclig@gmx.net>
[bpt/emacs.git] / lisp / mh-e / mh-utils.el
CommitLineData
bdcfe844 1;;; mh-utils.el --- MH-E code needed for both sending and reading
c26cf6c8 2
e495eaec 3;; Copyright (C) 1993, 1995, 1997,
44d55491 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]+\\)"
f0d73c14
BW
89 "This regexp is used to extract the message number from a scan line.
90Note that the message number must be placed in a parenthesized expression as
91in the default of \"^ *\\\\([0-9]+\\\\)\".")
c26cf6c8 92
3d7ca223 93(defvar mh-scan-msg-overflow-regexp "^[?0-9][0-9]"
f0d73c14 94 "This regexp matches scan lines in which the message number overflowed.")
bdcfe844
BW
95
96(defvar mh-scan-msg-format-regexp "%\\([0-9]*\\)(msg)"
f0d73c14
BW
97 "This regexp is used to find the message number width in a scan format.
98Note that the message number must be placed in a parenthesized expression as
99in the default of \"%\\\\([0-9]*\\\\)(msg)\".")
bdcfe844
BW
100
101(defvar mh-scan-msg-format-string "%d"
f0d73c14 102 "This is a format string for width of the message number in a scan format.
bdcfe844
BW
103Use `0%d' for zero-filled message numbers.")
104
a1b4049d 105(defvar mh-scan-msg-search-regexp "^[^0-9]*%d[^0-9]"
f0d73c14
BW
106 "This format string regexp matches the scan line for a particular message.
107Use `%d' to represent the location of the message number within the
108expression as in the default of \"^[^0-9]*%d[^0-9]\".")
109
110(defvar mh-cmd-note 4
111 "This is the number of characters to skip over before inserting notation.
112This variable should be set with the function `mh-set-cmd-note'. This variable
113may be updated dynamically if `mh-adaptive-cmd-note-flag' is non-nil and
114`mh-scan-format-file' is t.")
115(make-variable-buffer-local 'mh-cmd-note)
116
117(defvar mh-note-seq ?%
118 "Messages in a user-defined sequence are marked by this character.
119Messages in the `search' sequence are marked by this character as well.")
120
121\f
b6d4ab05 122
3d7ca223 123(defvar mh-show-buffer-mode-line-buffer-id " {show-%s} %d"
b6d4ab05
KH
124 "Format string to produce `mode-line-buffer-identification' for show buffers.
125First argument is folder name. Second is message number.")
c26cf6c8 126
f0d73c14 127\f
b6d4ab05 128
a1b4049d
BW
129(defvar mh-mail-header-separator "--------"
130 "*Line used by MH to separate headers from text in messages being composed.
131This variable should not be used directly in programs. Programs should use
132`mail-header-separator' instead. `mail-header-separator' is initialized to
133`mh-mail-header-separator' in `mh-letter-mode'; in other contexts, you may
134have to perform this initialization yourself.
135
136Do not make this a regexp as it may be the argument to `insert' and it is
137passed through `regexp-quote' before being used by functions like
138`re-search-forward'.")
139
f0d73c14
BW
140(defvar mh-signature-separator-regexp "^-- $"
141 "Regexp used to find signature separator.
142See `mh-signature-separator'.")
143
144(defvar mh-signature-separator "-- \n"
145 "Text of a signature separator.
146A signature separator is used to separate the body of a message from the
147signature. This can be used by user agents such as MH-E to render the
148signature differently or to suppress the inclusion of the signature in a
149reply.
150Use `mh-signature-separator-regexp' when searching for a separator.")
151
152(defun mh-signature-separator-p ()
153 "Return non-nil if buffer includes \"^-- $\"."
154 (save-excursion
155 (goto-char (point-min))
156 (re-search-forward mh-signature-separator-regexp nil t)))
157
c3d9274a 158;; Variables for MIME display
bdcfe844 159
c3d9274a 160;; Structure to keep track of MIME handles on a per buffer basis.
f0d73c14
BW
161(mh-defstruct (mh-buffer-data (:conc-name mh-mime-)
162 (:constructor mh-make-buffer-data))
c3d9274a
BW
163 (handles ()) ; List of MIME handles
164 (handles-cache (make-hash-table)) ; Cache to avoid multiple decodes of
165 ; nested messages
166 (parts-count 0) ; The button number is generated from
167 ; this number
168 (part-index-hash (make-hash-table))) ; Avoid incrementing the part number
169 ; for nested messages
170;;; This has to be a macro, since we do: (setf (mh-buffer-data) ...)
171(defmacro mh-buffer-data ()
172 "Convenience macro to get the MIME data structures of the current buffer."
173 `(gethash (current-buffer) mh-globals-hash))
bdcfe844 174
bdcfe844
BW
175(defvar mh-globals-hash (make-hash-table)
176 "Keeps track of MIME data on a per buffer basis.")
177
178(defvar mh-gnus-pgp-support-flag (not (not (locate-library "mml2015")))
179 "Non-nil means installed Gnus has PGP support.")
180
181(defvar mh-mm-inline-media-tests
182 `(("image/jpeg"
183 mm-inline-image
184 (lambda (handle)
185 (mm-valid-and-fit-image-p 'jpeg handle)))
186 ("image/png"
187 mm-inline-image
188 (lambda (handle)
189 (mm-valid-and-fit-image-p 'png handle)))
190 ("image/gif"
191 mm-inline-image
192 (lambda (handle)
193 (mm-valid-and-fit-image-p 'gif handle)))
194 ("image/tiff"
195 mm-inline-image
196 (lambda (handle)
197 (mm-valid-and-fit-image-p 'tiff handle)) )
198 ("image/xbm"
199 mm-inline-image
200 (lambda (handle)
201 (mm-valid-and-fit-image-p 'xbm handle)))
202 ("image/x-xbitmap"
203 mm-inline-image
204 (lambda (handle)
205 (mm-valid-and-fit-image-p 'xbm handle)))
206 ("image/xpm"
207 mm-inline-image
208 (lambda (handle)
209 (mm-valid-and-fit-image-p 'xpm handle)))
210 ("image/x-pixmap"
211 mm-inline-image
212 (lambda (handle)
213 (mm-valid-and-fit-image-p 'xpm handle)))
214 ("image/bmp"
215 mm-inline-image
216 (lambda (handle)
217 (mm-valid-and-fit-image-p 'bmp handle)))
218 ("image/x-portable-bitmap"
219 mm-inline-image
220 (lambda (handle)
221 (mm-valid-and-fit-image-p 'pbm handle)))
222 ("text/plain" mm-inline-text identity)
223 ("text/enriched" mm-inline-text identity)
224 ("text/richtext" mm-inline-text identity)
225 ("text/x-patch" mm-display-patch-inline
226 (lambda (handle)
227 (locate-library "diff-mode")))
228 ("application/emacs-lisp" mm-display-elisp-inline identity)
229 ("application/x-emacs-lisp" mm-display-elisp-inline identity)
230 ("text/html"
231 ,(if (fboundp 'mm-inline-text-html) 'mm-inline-text-html 'mm-inline-text)
232 (lambda (handle)
233 (or (and (boundp 'mm-inline-text-html-renderer)
234 mm-inline-text-html-renderer)
235 (and (boundp 'mm-text-html-renderer) mm-text-html-renderer))))
236 ("text/x-vcard"
237 mm-inline-text-vcard
238 (lambda (handle)
239 (or (featurep 'vcard)
240 (locate-library "vcard"))))
241 ("message/delivery-status" mm-inline-text identity)
242 ("message/rfc822" mh-mm-inline-message identity)
c3d9274a
BW
243 ;;("message/partial" mm-inline-partial identity)
244 ;;("message/external-body" mm-inline-external-body identity)
bdcfe844
BW
245 ("text/.*" mm-inline-text identity)
246 ("audio/wav" mm-inline-audio
247 (lambda (handle)
248 (and (or (featurep 'nas-sound) (featurep 'native-sound))
249 (device-sound-enabled-p))))
250 ("audio/au"
251 mm-inline-audio
252 (lambda (handle)
253 (and (or (featurep 'nas-sound) (featurep 'native-sound))
254 (device-sound-enabled-p))))
255 ("application/pgp-signature" ignore identity)
256 ("application/x-pkcs7-signature" ignore identity)
257 ("application/pkcs7-signature" ignore identity)
258 ("application/x-pkcs7-mime" ignore identity)
259 ("application/pkcs7-mime" ignore identity)
260 ("multipart/alternative" ignore identity)
261 ("multipart/mixed" ignore identity)
262 ("multipart/related" ignore identity)
263 ;; Disable audio and image
264 ("audio/.*" ignore ignore)
265 ("image/.*" ignore ignore)
266 ;; Default to displaying as text
267 (".*" mm-inline-text mm-readable-p))
268 "Alist of media types/tests saying whether types can be displayed inline.")
269
c3d9274a
BW
270;; Copy of `goto-address-mail-regexp'
271(defvar mh-address-mail-regexp
a66894d8 272 "[-a-zA-Z0-9._]+@\\([-a-zA-z0-9_]+\\.\\)+[a-zA-Z0-9]+"
c3d9274a
BW
273 "A regular expression probably matching an e-mail address.")
274
275;; From goto-addr.el, which we don't want to force-load on users.
f0d73c14 276
c3d9274a
BW
277(defun mh-goto-address-find-address-at-point ()
278 "Find e-mail address around or before point.
279Then search backwards to beginning of line for the start of an e-mail
280address. If no e-mail address found, return nil."
281 (re-search-backward "[^-_A-z0-9.@]" (line-beginning-position) 'lim)
282 (if (or (looking-at mh-address-mail-regexp) ; already at start
283 (and (re-search-forward mh-address-mail-regexp
284 (line-end-position) 'lim)
285 (goto-char (match-beginning 0))))
286 (match-string-no-properties 0)))
287
924df208
BW
288(defun mh-mail-header-end ()
289 "Substitute for `mail-header-end' that doesn't widen the buffer.
290In MH-E we frequently need to find the end of headers in nested messages, where
291the buffer has been narrowed. This function works in this situation."
292 (save-excursion
f0d73c14
BW
293 ;; XXX: The following replaces a call to rfc822-goto-eoh. Occasionally,
294 ;; mail headers that MH-E has to read contains lines of the form:
295 ;; From xxx@yyy Mon May 10 11:48:07 2004
296 ;; In this situation, rfc822-goto-eoh doesn't go to the end of the
297 ;; header. The replacement allows From_ lines in the mail header.
298 (goto-char (point-min))
299 (loop for p = (re-search-forward
300 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
301 do (cond ((null p) (return))
302 (t (goto-char (match-beginning 0))
303 (unless (looking-at "From ") (return))
304 (goto-char p))))
924df208
BW
305 (point)))
306
a1b4049d 307(defun mh-in-header-p ()
bdcfe844 308 "Return non-nil if the point is in the header of a draft message."
924df208 309 (< (point) (mh-mail-header-end)))
a1b4049d 310
c3d9274a
BW
311(defun mh-header-field-beginning ()
312 "Move to the beginning of the current header field.
313Handles RFC 822 continuation lines."
314 (beginning-of-line)
315 (while (looking-at "^[ \t]")
316 (forward-line -1)))
317
a1b4049d 318(defun mh-header-field-end ()
bdcfe844
BW
319 "Move to the end of the current header field.
320Handles RFC 822 continuation lines."
a1b4049d
BW
321 (forward-line 1)
322 (while (looking-at "^[ \t]")
323 (forward-line 1))
c3d9274a 324 (backward-char 1)) ;to end of previous line
a1b4049d
BW
325
326(defun mh-letter-header-font-lock (limit)
327 "Return the entire mail header to font-lock.
328Argument LIMIT limits search."
329 (if (= (point) limit)
330 nil
924df208 331 (let* ((mail-header-end (save-match-data (mh-mail-header-end)))
a1b4049d
BW
332 (lesser-limit (if (< mail-header-end limit) mail-header-end limit)))
333 (when (mh-in-header-p)
334 (set-match-data (list 1 lesser-limit))
335 (goto-char lesser-limit)
336 t))))
337
338(defun mh-header-field-font-lock (field limit)
339 "Return the value of a header field FIELD to font-lock.
340Argument LIMIT limits search."
341 (if (= (point) limit)
342 nil
924df208 343 (let* ((mail-header-end (mh-mail-header-end))
a1b4049d
BW
344 (lesser-limit (if (< mail-header-end limit) mail-header-end limit))
345 (case-fold-search t))
c3d9274a 346 (when (and (< (point) mail-header-end) ;Only within header
a1b4049d
BW
347 (re-search-forward (format "^%s" field) lesser-limit t))
348 (let ((match-one-b (match-beginning 0))
349 (match-one-e (match-end 0)))
350 (mh-header-field-end)
c3d9274a 351 (if (> (point) limit) ;Don't search for end beyond limit
a1b4049d
BW
352 (goto-char limit))
353 (set-match-data (list match-one-b match-one-e
354 (1+ match-one-e) (point)))
355 t)))))
356
357(defun mh-header-to-font-lock (limit)
bdcfe844
BW
358 "Return the value of a header field To to font-lock.
359Argument LIMIT limits search."
a1b4049d
BW
360 (mh-header-field-font-lock "To:" limit))
361
362(defun mh-header-cc-font-lock (limit)
bdcfe844
BW
363 "Return the value of a header field cc to font-lock.
364Argument LIMIT limits search."
a1b4049d
BW
365 (mh-header-field-font-lock "cc:" limit))
366
367(defun mh-header-subject-font-lock (limit)
bdcfe844
BW
368 "Return the value of a header field Subject to font-lock.
369Argument LIMIT limits search."
a1b4049d
BW
370 (mh-header-field-font-lock "Subject:" limit))
371
bdcfe844
BW
372(eval-and-compile
373 ;; Otherwise byte-compilation fails on `mh-show-font-lock-keywords-with-cite'
374 (defvar mh-show-font-lock-keywords
375 '(("^\\(From:\\|Sender:\\)\\(.*\\)" (1 'default) (2 mh-show-from-face))
376 (mh-header-to-font-lock (0 'default) (1 mh-show-to-face))
377 (mh-header-cc-font-lock (0 'default) (1 mh-show-cc-face))
378 ("^\\(Reply-To:\\|Return-Path:\\)\\(.*\\)$"
c3d9274a 379 (1 'default) (2 mh-show-from-face))
bdcfe844
BW
380 (mh-header-subject-font-lock (0 'default) (1 mh-show-subject-face))
381 ("^\\(Apparently-To:\\|Newsgroups:\\)\\(.*\\)"
c3d9274a 382 (1 'default) (2 mh-show-cc-face))
bdcfe844 383 ("^\\(In-reply-to\\|Date\\):\\(.*\\)$"
c3d9274a 384 (1 'default) (2 mh-show-date-face))
bdcfe844
BW
385 (mh-letter-header-font-lock (0 mh-show-header-face append t)))
386 "Additional expressions to highlight in MH-show mode."))
387
388(defvar mh-show-font-lock-keywords-with-cite
389 (eval-when-compile
390 (let* ((cite-chars "[>|}]")
391 (cite-prefix "A-Za-z")
392 (cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
393 (append
394 mh-show-font-lock-keywords
395 (list
396 ;; Use MATCH-ANCHORED to effectively anchor the regexp left side.
397 `(,cite-chars
398 (,(concat "\\=[ \t]*"
399 "\\(\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
400 "\\(" cite-chars "[ \t]*\\)\\)+"
401 "\\(.*\\)")
402 (beginning-of-line) (end-of-line)
403 (2 font-lock-constant-face nil t)
404 (4 font-lock-comment-face nil t)))))))
405 "Additional expressions to highlight in MH-show mode.")
406
a66894d8
BW
407(defvar mh-letter-font-lock-keywords
408 `(,@mh-show-font-lock-keywords-with-cite
44d55491 409 (mh-font-lock-field-data (1 'mh-letter-header-field prepend t))))
a66894d8 410
bdcfe844
BW
411(defun mh-show-font-lock-fontify-region (beg end loudly)
412 "Limit font-lock in `mh-show-mode' to the header.
413Used when `mh-highlight-citation-p' is set to gnus, leaving the body to be
414dealt with by gnus highlighting. The region between BEG and END is
415given over to be fontified and LOUDLY controls if a user sees a
416message about the fontification operation."
924df208 417 (let ((header-end (mh-mail-header-end)))
bdcfe844
BW
418 (cond
419 ((and (< beg header-end)(< end header-end))
420 (font-lock-default-fontify-region beg end loudly))
421 ((and (< beg header-end)(>= end header-end))
422 (font-lock-default-fontify-region beg header-end loudly))
423 (t
424 nil))))
425
426;; Needed to help shush the byte-compiler.
427(if mh-xemacs-flag
428 (progn
429 (eval-and-compile
c3d9274a
BW
430 (require 'gnus)
431 (require 'gnus-art)
432 (require 'gnus-cite))))
a1b4049d
BW
433
434(defun mh-gnus-article-highlight-citation ()
435 "Highlight cited text in current buffer using gnus."
436 (interactive)
bdcfe844
BW
437 ;; Requiring gnus-cite should have been sufficient. However for Emacs21.1,
438 ;; recursive-load-depth-limit is only 10, so an error occurs. Also it may be
439 ;; better to have an autoload at top-level (though that won't work because
440 ;; of recursive-load-depth-limit). That gets rid of a compiler warning as
441 ;; well.
442 (unless mh-xemacs-flag
443 (require 'gnus-art)
444 (require 'gnus-cite))
445 ;; Don't allow Gnus to create buttons while highlighting, maybe this is bad
446 ;; style?
447 (flet ((gnus-article-add-button (&rest args) nil))
448 (let* ((modified (buffer-modified-p))
c3d9274a
BW
449 (gnus-article-buffer (buffer-name))
450 (gnus-cite-face-list `(,@(cdr gnus-cite-face-list)
451 ,(car gnus-cite-face-list))))
bdcfe844
BW
452 (gnus-article-highlight-citation t)
453 (set-buffer-modified-p modified))))
a1b4049d 454
b6d4ab05
KH
455;;; Internal bookkeeping variables:
456
b6d4ab05 457;; Cached value of the `Path:' component in the user's MH profile.
a1b4049d
BW
458;; User's mail folder directory.
459(defvar mh-user-path nil)
c26cf6c8 460
bdcfe844 461;; An mh-draft-folder of nil means do not use a draft folder.
b6d4ab05 462;; Cached value of the `Draft-Folder:' component in the user's MH profile.
a1b4049d
BW
463;; Name of folder containing draft messages.
464(defvar mh-draft-folder nil)
c26cf6c8 465
b6d4ab05 466;; Cached value of the `Unseen-Sequence:' component in the user's MH profile.
a1b4049d
BW
467;; Name of the Unseen sequence.
468(defvar mh-unseen-seq nil)
c26cf6c8 469
a1b4049d
BW
470;; Cached value of the `Previous-Sequence:' component in the user's MH
471;; profile.
472;; Name of the Previous sequence.
473(defvar mh-previous-seq nil)
c26cf6c8 474
b6d4ab05
KH
475;; Cached value of the `Inbox:' component in the user's MH profile,
476;; or "+inbox" if no such component.
a1b4049d
BW
477;; Name of the Inbox folder.
478(defvar mh-inbox nil)
c26cf6c8 479
3d7ca223
BW
480;; The names of ephemeral buffers have a " *mh-" prefix (so that they are
481;; hidden and can be programmatically removed in mh-quit), and the variable
482;; names have the form mh-temp-.*-buffer.
483(defconst mh-temp-buffer " *mh-temp*") ;scratch
f0d73c14 484(defconst mh-temp-fetch-buffer " *mh-fetch*") ;wget/curl/fetch output
3d7ca223
BW
485
486;; The names of MH-E buffers that are not ephemeral and can be used by the
487;; user (and deleted by the user when no longer needed) have a "*MH-E " prefix
488;; (so they can be programmatically removed in mh-quit), and the variable
489;; names have the form mh-.*-buffer.
f0d73c14 490(defconst mh-aliases-buffer "*MH-E Aliases*") ;alias lookups
3d7ca223 491(defconst mh-folders-buffer "*MH-E Folders*") ;folder list
f0d73c14 492(defconst mh-help-buffer "*MH-E Help*") ;quick help
3d7ca223
BW
493(defconst mh-info-buffer "*MH-E Info*") ;version information buffer
494(defconst mh-log-buffer "*MH-E Log*") ;output of MH commands and so on
f0d73c14 495(defconst mh-mail-delivery-buffer "*MH-E Mail Delivery*") ;mail delivery log
3d7ca223
BW
496(defconst mh-recipients-buffer "*MH-E Recipients*") ;killed when draft sent
497(defconst mh-sequences-buffer "*MH-E Sequences*") ;sequences list
924df208
BW
498
499;; Number of lines to keep in mh-log-buffer.
500(defvar mh-log-buffer-lines 100)
a1b4049d 501
bdcfe844 502;; Window configuration before MH-E command.
a1b4049d
BW
503(defvar mh-previous-window-config nil)
504
505;;Non-nil means next SPC or whatever goes to next undeleted message.
bdcfe844 506(defvar mh-page-to-next-msg-flag nil)
c26cf6c8 507
b6d4ab05 508;;; Internal variables local to a folder.
c26cf6c8 509
a1b4049d
BW
510;; Name of current folder, a string.
511(defvar mh-current-folder nil)
c26cf6c8 512
a1b4049d
BW
513;; Buffer that displays message for this folder.
514(defvar mh-show-buffer nil)
c26cf6c8 515
a1b4049d
BW
516;; Full path of directory for this folder.
517(defvar mh-folder-filename nil)
a1506d29 518
a1b4049d
BW
519;;Number of msgs in buffer.
520(defvar mh-msg-count nil)
c26cf6c8 521
a1b4049d
BW
522;; If non-nil, show the message in a separate window.
523(defvar mh-showing-mode nil)
c26cf6c8 524
bdcfe844
BW
525(defvar mh-show-mode-map (make-sparse-keymap)
526 "Keymap used by the show buffer.")
527
528(defvar mh-show-folder-buffer nil
529 "Keeps track of folder whose message is being displayed.")
530
3d7ca223
BW
531(defvar mh-logo-cache nil)
532
533(defun mh-logo-display ()
534 "Modify mode line to display MH-E logo."
924df208
BW
535 (mh-do-in-gnu-emacs
536 (add-text-properties
537 0 2
538 `(display ,(or mh-logo-cache
539 (setq mh-logo-cache
540 (mh-funcall-if-exists
541 find-image '((:type xpm :ascent center
542 :file "mh-logo.xpm"))))))
543 (car mode-line-buffer-identification)))
544 (mh-do-in-xemacs
545 (setq modeline-buffer-identification
546 (list
547 (if mh-modeline-glyph
548 (cons modeline-buffer-id-left-extent mh-modeline-glyph)
549 (cons modeline-buffer-id-left-extent "XEmacs%N:"))
550 (cons modeline-buffer-id-right-extent " %17b")))))
551
b6d4ab05 552;;; This holds a documentation string used by describe-mode.
a1b4049d
BW
553(defun mh-showing-mode (&optional arg)
554 "Change whether messages should be displayed.
555With arg, display messages iff ARG is positive."
556 (setq mh-showing-mode
c3d9274a
BW
557 (if (null arg)
558 (not mh-showing-mode)
559 (> (prefix-numeric-value arg) 0))))
b6d4ab05 560
a1b4049d
BW
561;; The sequences of this folder. An alist of (seq . msgs).
562(defvar mh-seq-list nil)
b6d4ab05 563
a1b4049d
BW
564;; List of displayed messages to be removed from the Unseen sequence.
565(defvar mh-seen-list nil)
b6d4ab05
KH
566
567;; If non-nil, show buffer contains message with all headers.
568;; If nil, show buffer contains message processed normally.
a1b4049d
BW
569;; Showing message with headers or normally.
570(defvar mh-showing-with-headers nil)
c26cf6c8 571
bdcfe844 572;;; MH-E macros
c919c21a 573
bdcfe844
BW
574(defmacro with-mh-folder-updating (save-modification-flag &rest body)
575 "Format is (with-mh-folder-updating (SAVE-MODIFICATION-FLAG) &body BODY).
576Execute BODY, which can modify the folder buffer without having to
577worry about file locking or the read-only flag, and return its result.
578If SAVE-MODIFICATION-FLAG is non-nil, the buffer's modification
579flag is unchanged, otherwise it is cleared."
580 (setq save-modification-flag (car save-modification-flag)) ; CL style
b787fc05
GM
581 `(prog1
582 (let ((mh-folder-updating-mod-flag (buffer-modified-p))
c3d9274a
BW
583 (buffer-read-only nil)
584 (buffer-file-name nil)) ;don't let the buffer get locked
585 (prog1
586 (progn
587 ,@body)
588 (mh-set-folder-modified-p mh-folder-updating-mod-flag)))
bdcfe844 589 ,@(if (not save-modification-flag)
c3d9274a 590 '((mh-set-folder-modified-p nil)))))
c919c21a 591
924df208 592(put 'with-mh-folder-updating 'lisp-indent-hook 'defun)
c919c21a
RS
593
594(defmacro mh-in-show-buffer (show-buffer &rest body)
bdcfe844
BW
595 "Format is (mh-in-show-buffer (SHOW-BUFFER) &body BODY).
596Display buffer SHOW-BUFFER in other window and execute BODY in it.
597Stronger than `save-excursion', weaker than `save-window-excursion'."
c3d9274a 598 (setq show-buffer (car show-buffer)) ; CL style
b787fc05
GM
599 `(let ((mh-in-show-buffer-saved-window (selected-window)))
600 (switch-to-buffer-other-window ,show-buffer)
bdcfe844 601 (if mh-bury-show-buffer-flag (bury-buffer (current-buffer)))
b787fc05 602 (unwind-protect
c3d9274a 603 (progn
b787fc05
GM
604 ,@body)
605 (select-window mh-in-show-buffer-saved-window))))
c919c21a 606
924df208 607(put 'mh-in-show-buffer 'lisp-indent-hook 'defun)
c919c21a 608
a66894d8
BW
609(defmacro mh-do-at-event-location (event &rest body)
610 "Switch to the location of EVENT and execute BODY.
611After BODY has been executed return to original window. The modification flag
612of the buffer in the event window is preserved."
613 (let ((event-window (make-symbol "event-window"))
614 (event-position (make-symbol "event-position"))
615 (original-window (make-symbol "original-window"))
616 (original-position (make-symbol "original-position"))
617 (modified-flag (make-symbol "modified-flag")))
618 `(save-excursion
619 (let* ((,event-window
620 (or (mh-funcall-if-exists posn-window (event-start ,event))
621 (mh-funcall-if-exists event-window ,event)))
622 (,event-position
623 (or (mh-funcall-if-exists posn-point (event-start ,event))
624 (mh-funcall-if-exists event-closest-point ,event)))
625 (,original-window (selected-window))
626 (,original-position (progn
627 (set-buffer (window-buffer ,event-window))
628 (set-marker (make-marker) (point))))
629 (,modified-flag (buffer-modified-p))
630 (buffer-read-only nil))
631 (unwind-protect (progn
632 (select-window ,event-window)
633 (goto-char ,event-position)
634 ,@body)
635 (set-buffer-modified-p ,modified-flag)
636 (goto-char ,original-position)
637 (set-marker ,original-position nil)
638 (select-window ,original-window))))))
639
640(put 'mh-do-at-event-location 'lisp-indent-hook 'defun)
641
bdcfe844
BW
642(defmacro mh-make-seq (name msgs)
643 "Create sequence NAME with the given MSGS."
644 (list 'cons name msgs))
645
646(defmacro mh-seq-name (sequence)
647 "Extract sequence name from the given SEQUENCE."
648 (list 'car sequence))
649
650(defmacro mh-seq-msgs (sequence)
651 "Extract messages from the given SEQUENCE."
652 (list 'cdr sequence))
653
654(defun mh-recenter (arg)
655 "Like recenter but with three improvements:
656- At the end of the buffer it tries to show fewer empty lines.
657- operates only if the current buffer is in the selected window.
658 (Commands like `save-some-buffers' can make this false.)
659- nil ARG means recenter as if prefix argument had been given."
660 (cond ((not (eq (get-buffer-window (current-buffer)) (selected-window)))
661 nil)
662 ((= (point-max) (save-excursion
663 (forward-line (- (/ (window-height) 2) 2))
664 (point)))
665 (let ((lines-from-end 2))
666 (save-excursion
667 (while (> (point-max) (progn (forward-line) (point)))
668 (incf lines-from-end)))
669 (recenter (- lines-from-end))))
670 ;; '(4) is the same as C-u prefix argument.
671 (t (recenter (or arg '(4))))))
672
673(defun mh-start-of-uncleaned-message ()
674 "Position uninteresting headers off the top of the window."
675 (let ((case-fold-search t))
676 (re-search-forward
677 "^To:\\|^Cc:\\|^From:\\|^Subject:\\|^Date:" nil t)
678 (beginning-of-line)
679 (mh-recenter 0)))
680
681(defun mh-invalidate-show-buffer ()
682 "Invalidate the show buffer so we must update it to use it."
683 (if (get-buffer mh-show-buffer)
684 (save-excursion
c3d9274a
BW
685 (set-buffer mh-show-buffer)
686 (mh-unvisit-file))))
bdcfe844
BW
687
688(defun mh-unvisit-file ()
689 "Separate current buffer from the message file it was visiting."
690 (or (not (buffer-modified-p))
c3d9274a 691 (null buffer-file-name) ;we've been here before
bdcfe844 692 (yes-or-no-p (format "Message %s modified; flush changes? "
c3d9274a 693 (file-name-nondirectory buffer-file-name)))
bdcfe844
BW
694 (error "Flushing changes not confirmed"))
695 (clear-visited-file-modtime)
696 (unlock-buffer)
697 (setq buffer-file-name nil))
a1506d29 698
f0d73c14 699
bdcfe844
BW
700(defun mh-get-msg-num (error-if-no-message)
701 "Return the message number of the displayed message.
702If the argument ERROR-IF-NO-MESSAGE is non-nil, then complain if the cursor is
703not pointing to a message."
704 (save-excursion
705 (beginning-of-line)
706 (cond ((looking-at mh-scan-msg-number-regexp)
e495eaec
BW
707 (string-to-number (buffer-substring (match-beginning 1)
708 (match-end 1))))
c3d9274a
BW
709 (error-if-no-message
710 (error "Cursor not pointing to message"))
711 (t nil))))
bdcfe844
BW
712
713(defun mh-folder-name-p (name)
714 "Return non-nil if NAME is the name of a folder.
715A name (a string or symbol) can be a folder name if it begins with \"+\"."
716 (if (symbolp name)
717 (eq (aref (symbol-name name) 0) ?+)
718 (and (> (length name) 0)
c3d9274a 719 (eq (aref name 0) ?+))))
bdcfe844
BW
720
721
722(defun mh-expand-file-name (filename &optional default)
723 "Expand FILENAME like `expand-file-name', but also handle MH folder names.
724Any filename that starts with '+' is treated as a folder name.
725See `expand-file-name' for description of DEFAULT."
c3d9274a
BW
726 (if (mh-folder-name-p filename)
727 (expand-file-name (substring filename 1) mh-user-path)
728 (expand-file-name filename default)))
b6d4ab05 729
c919c21a 730
bdcfe844
BW
731(defun mh-msg-filename (msg &optional folder)
732 "Return the file name of MSG in FOLDER (default current folder)."
733 (expand-file-name (int-to-string msg)
c3d9274a
BW
734 (if folder
735 (mh-expand-file-name folder)
736 mh-folder-filename)))
c919c21a 737
bdcfe844
BW
738;;; Infrastructure to generate show-buffer functions from folder functions
739;;; XEmacs does not have deactivate-mark? What is the equivalent of
740;;; transient-mark-mode for XEmacs? Should we be restoring the mark in the
741;;; folder buffer after the operation has been carried out.
742(defmacro mh-defun-show-buffer (function original-function
c3d9274a 743 &optional dont-return)
bdcfe844
BW
744 "Define FUNCTION to run ORIGINAL-FUNCTION in folder buffer.
745If the buffer we start in is still visible and DONT-RETURN is nil then switch
746to it after that."
747 `(defun ,function ()
748 ,(format "Calls %s from the message's folder.\n%s\nSee `%s' for more info.\n"
749 original-function
750 (if dont-return ""
751 "When function completes, returns to the show buffer if it is
752still visible.\n")
753 original-function)
754 (interactive)
755 (when (buffer-live-p (get-buffer mh-show-folder-buffer))
756 (let ((config (current-window-configuration))
757 (folder-buffer mh-show-folder-buffer)
758 (normal-exit nil)
759 ,@(if dont-return () '((cur-buffer-name (buffer-name)))))
760 (pop-to-buffer mh-show-folder-buffer nil)
761 (unless (equal (buffer-name
762 (window-buffer (frame-first-window (selected-frame))))
763 folder-buffer)
764 (delete-other-windows))
765 (mh-goto-cur-msg t)
924df208 766 (mh-funcall-if-exists deactivate-mark)
bdcfe844
BW
767 (unwind-protect
768 (prog1 (call-interactively (function ,original-function))
769 (setq normal-exit t))
924df208 770 (mh-funcall-if-exists deactivate-mark)
a66894d8
BW
771 (when (eq major-mode 'mh-folder-mode)
772 (mh-funcall-if-exists hl-line-highlight))
bdcfe844
BW
773 (cond ((not normal-exit)
774 (set-window-configuration config))
775 ,(if dont-return
776 `(t (setq mh-previous-window-config config))
777 `((and (get-buffer cur-buffer-name)
778 (window-live-p (get-buffer-window
779 (get-buffer cur-buffer-name))))
780 (pop-to-buffer (get-buffer cur-buffer-name) nil)))))))))
781
782;;; Generate interactive functions for the show buffer from the corresponding
783;;; folder functions.
784(mh-defun-show-buffer mh-show-previous-undeleted-msg
c3d9274a 785 mh-previous-undeleted-msg)
bdcfe844 786(mh-defun-show-buffer mh-show-next-undeleted-msg
c3d9274a 787 mh-next-undeleted-msg)
bdcfe844
BW
788(mh-defun-show-buffer mh-show-quit mh-quit)
789(mh-defun-show-buffer mh-show-delete-msg mh-delete-msg)
790(mh-defun-show-buffer mh-show-refile-msg mh-refile-msg)
791(mh-defun-show-buffer mh-show-undo mh-undo)
792(mh-defun-show-buffer mh-show-execute-commands mh-execute-commands)
793(mh-defun-show-buffer mh-show-reply mh-reply t)
794(mh-defun-show-buffer mh-show-redistribute mh-redistribute)
795(mh-defun-show-buffer mh-show-forward mh-forward t)
796(mh-defun-show-buffer mh-show-header-display mh-header-display)
797(mh-defun-show-buffer mh-show-refile-or-write-again
c3d9274a 798 mh-refile-or-write-again)
bdcfe844
BW
799(mh-defun-show-buffer mh-show-show mh-show)
800(mh-defun-show-buffer mh-show-write-message-to-file
c3d9274a 801 mh-write-msg-to-file)
bdcfe844 802(mh-defun-show-buffer mh-show-extract-rejected-mail
c3d9274a 803 mh-extract-rejected-mail t)
bdcfe844 804(mh-defun-show-buffer mh-show-delete-msg-no-motion
c3d9274a 805 mh-delete-msg-no-motion)
bdcfe844
BW
806(mh-defun-show-buffer mh-show-first-msg mh-first-msg)
807(mh-defun-show-buffer mh-show-last-msg mh-last-msg)
808(mh-defun-show-buffer mh-show-copy-msg mh-copy-msg)
809(mh-defun-show-buffer mh-show-edit-again mh-edit-again t)
810(mh-defun-show-buffer mh-show-goto-msg mh-goto-msg)
811(mh-defun-show-buffer mh-show-inc-folder mh-inc-folder)
c3d9274a
BW
812(mh-defun-show-buffer mh-show-delete-subject-or-thread
813 mh-delete-subject-or-thread)
814(mh-defun-show-buffer mh-show-delete-subject mh-delete-subject)
bdcfe844
BW
815(mh-defun-show-buffer mh-show-print-msg mh-print-msg)
816(mh-defun-show-buffer mh-show-send mh-send t)
817(mh-defun-show-buffer mh-show-toggle-showing mh-toggle-showing t)
818(mh-defun-show-buffer mh-show-pipe-msg mh-pipe-msg t)
819(mh-defun-show-buffer mh-show-sort-folder mh-sort-folder)
820(mh-defun-show-buffer mh-show-visit-folder mh-visit-folder t)
821(mh-defun-show-buffer mh-show-rescan-folder mh-rescan-folder)
822(mh-defun-show-buffer mh-show-pack-folder mh-pack-folder)
823(mh-defun-show-buffer mh-show-kill-folder mh-kill-folder t)
824(mh-defun-show-buffer mh-show-list-folders mh-list-folders t)
825(mh-defun-show-buffer mh-show-search-folder mh-search-folder t)
826(mh-defun-show-buffer mh-show-undo-folder mh-undo-folder)
827(mh-defun-show-buffer mh-show-delete-msg-from-seq
c3d9274a 828 mh-delete-msg-from-seq)
bdcfe844
BW
829(mh-defun-show-buffer mh-show-delete-seq mh-delete-seq)
830(mh-defun-show-buffer mh-show-list-sequences mh-list-sequences)
831(mh-defun-show-buffer mh-show-narrow-to-seq mh-narrow-to-seq)
832(mh-defun-show-buffer mh-show-put-msg-in-seq mh-put-msg-in-seq)
833(mh-defun-show-buffer mh-show-msg-is-in-seq mh-msg-is-in-seq)
834(mh-defun-show-buffer mh-show-widen mh-widen)
a66894d8
BW
835(mh-defun-show-buffer mh-show-narrow-to-subject mh-narrow-to-subject)
836(mh-defun-show-buffer mh-show-narrow-to-from mh-narrow-to-from)
837(mh-defun-show-buffer mh-show-narrow-to-cc mh-narrow-to-cc)
838(mh-defun-show-buffer mh-show-narrow-to-range mh-narrow-to-range)
839(mh-defun-show-buffer mh-show-narrow-to-to mh-narrow-to-to)
bdcfe844
BW
840(mh-defun-show-buffer mh-show-store-msg mh-store-msg)
841(mh-defun-show-buffer mh-show-page-digest mh-page-digest)
842(mh-defun-show-buffer mh-show-page-digest-backwards
c3d9274a 843 mh-page-digest-backwards)
bdcfe844
BW
844(mh-defun-show-buffer mh-show-burst-digest mh-burst-digest)
845(mh-defun-show-buffer mh-show-page-msg mh-page-msg)
846(mh-defun-show-buffer mh-show-previous-page mh-previous-page)
847(mh-defun-show-buffer mh-show-modify mh-modify t)
848(mh-defun-show-buffer mh-show-next-button mh-next-button)
849(mh-defun-show-buffer mh-show-prev-button mh-prev-button)
850(mh-defun-show-buffer mh-show-toggle-mime-part mh-folder-toggle-mime-part)
851(mh-defun-show-buffer mh-show-save-mime-part mh-folder-save-mime-part)
852(mh-defun-show-buffer mh-show-inline-mime-part mh-folder-inline-mime-part)
853(mh-defun-show-buffer mh-show-toggle-threads mh-toggle-threads)
c3d9274a
BW
854(mh-defun-show-buffer mh-show-thread-delete mh-thread-delete)
855(mh-defun-show-buffer mh-show-thread-refile mh-thread-refile)
bdcfe844 856(mh-defun-show-buffer mh-show-update-sequences mh-update-sequences)
c3d9274a
BW
857(mh-defun-show-buffer mh-show-next-unread-msg mh-next-unread-msg)
858(mh-defun-show-buffer mh-show-previous-unread-msg mh-previous-unread-msg)
859(mh-defun-show-buffer mh-show-thread-ancestor mh-thread-ancestor)
860(mh-defun-show-buffer mh-show-thread-next-sibling mh-thread-next-sibling)
861(mh-defun-show-buffer mh-show-thread-previous-sibling
862 mh-thread-previous-sibling)
863(mh-defun-show-buffer mh-show-index-visit-folder mh-index-visit-folder t)
924df208
BW
864(mh-defun-show-buffer mh-show-toggle-tick mh-toggle-tick)
865(mh-defun-show-buffer mh-show-narrow-to-tick mh-narrow-to-tick)
866(mh-defun-show-buffer mh-show-junk-blacklist mh-junk-blacklist)
867(mh-defun-show-buffer mh-show-junk-whitelist mh-junk-whitelist)
868(mh-defun-show-buffer mh-show-index-new-messages mh-index-new-messages)
a66894d8
BW
869(mh-defun-show-buffer mh-show-index-ticked-messages mh-index-ticked-messages)
870(mh-defun-show-buffer mh-show-index-sequenced-messages
871 mh-index-sequenced-messages)
f0d73c14
BW
872(mh-defun-show-buffer mh-show-catchup mh-catchup)
873(mh-defun-show-buffer mh-show-ps-print-toggle-mime mh-ps-print-toggle-mime)
874(mh-defun-show-buffer mh-show-ps-print-toggle-color mh-ps-print-toggle-color)
875(mh-defun-show-buffer mh-show-ps-print-toggle-faces mh-ps-print-toggle-faces)
876(mh-defun-show-buffer mh-show-ps-print-msg-file mh-ps-print-msg-file)
877(mh-defun-show-buffer mh-show-ps-print-msg mh-ps-print-msg)
878(mh-defun-show-buffer mh-show-ps-print-msg-show mh-ps-print-msg-show)
879(mh-defun-show-buffer mh-show-toggle-mime-buttons mh-toggle-mime-buttons)
880(mh-defun-show-buffer mh-show-display-with-external-viewer
881 mh-display-with-external-viewer)
bdcfe844
BW
882
883;;; Populate mh-show-mode-map
884(gnus-define-keys mh-show-mode-map
885 " " mh-show-page-msg
886 "!" mh-show-refile-or-write-again
924df208 887 "'" mh-show-toggle-tick
bdcfe844
BW
888 "," mh-show-header-display
889 "." mh-show-show
890 ">" mh-show-write-message-to-file
891 "?" mh-help
892 "E" mh-show-extract-rejected-mail
893 "M" mh-show-modify
894 "\177" mh-show-previous-page
895 "\C-d" mh-show-delete-msg-no-motion
896 "\t" mh-show-next-button
897 [backtab] mh-show-prev-button
898 "\M-\t" mh-show-prev-button
899 "\ed" mh-show-redistribute
900 "^" mh-show-refile-msg
901 "c" mh-show-copy-msg
902 "d" mh-show-delete-msg
903 "e" mh-show-edit-again
904 "f" mh-show-forward
905 "g" mh-show-goto-msg
906 "i" mh-show-inc-folder
c3d9274a 907 "k" mh-show-delete-subject-or-thread
bdcfe844
BW
908 "m" mh-show-send
909 "n" mh-show-next-undeleted-msg
c3d9274a 910 "\M-n" mh-show-next-unread-msg
bdcfe844
BW
911 "o" mh-show-refile-msg
912 "p" mh-show-previous-undeleted-msg
c3d9274a 913 "\M-p" mh-show-previous-unread-msg
bdcfe844
BW
914 "q" mh-show-quit
915 "r" mh-show-reply
916 "s" mh-show-send
917 "t" mh-show-toggle-showing
918 "u" mh-show-undo
919 "x" mh-show-execute-commands
c3d9274a 920 "v" mh-show-index-visit-folder
bdcfe844
BW
921 "|" mh-show-pipe-msg)
922
923(gnus-define-keys (mh-show-folder-map "F" mh-show-mode-map)
924 "?" mh-prefix-help
a66894d8 925 "'" mh-index-ticked-messages
bdcfe844 926 "S" mh-show-sort-folder
f0d73c14 927 "c" mh-show-catchup
bdcfe844
BW
928 "f" mh-show-visit-folder
929 "i" mh-index-search
930 "k" mh-show-kill-folder
931 "l" mh-show-list-folders
924df208 932 "n" mh-index-new-messages
bdcfe844 933 "o" mh-show-visit-folder
a66894d8 934 "q" mh-show-index-sequenced-messages
bdcfe844
BW
935 "r" mh-show-rescan-folder
936 "s" mh-show-search-folder
937 "t" mh-show-toggle-threads
938 "u" mh-show-undo-folder
939 "v" mh-show-visit-folder)
940
941(gnus-define-keys (mh-show-sequence-map "S" mh-show-mode-map)
a66894d8 942 "'" mh-show-narrow-to-tick
bdcfe844
BW
943 "?" mh-prefix-help
944 "d" mh-show-delete-msg-from-seq
945 "k" mh-show-delete-seq
946 "l" mh-show-list-sequences
947 "n" mh-show-narrow-to-seq
948 "p" mh-show-put-msg-in-seq
949 "s" mh-show-msg-is-in-seq
950 "w" mh-show-widen)
951
924df208
BW
952(define-key mh-show-mode-map "I" mh-inc-spool-map)
953
954(gnus-define-keys (mh-show-junk-map "J" mh-show-mode-map)
955 "?" mh-prefix-help
956 "b" mh-show-junk-blacklist
957 "w" mh-show-junk-whitelist)
958
f0d73c14
BW
959(gnus-define-keys (mh-show-ps-print-map "P" mh-show-mode-map)
960 "?" mh-prefix-help
961 "A" mh-show-ps-print-toggle-mime
962 "C" mh-show-ps-print-toggle-color
963 "F" mh-show-ps-print-toggle-faces
964 "M" mh-show-ps-print-toggle-mime
965 "f" mh-show-ps-print-msg-file
966 "l" mh-show-print-msg
967 "p" mh-show-ps-print-msg
968 "s" mh-show-ps-print-msg-show)
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
BW
1108 (cond
1109 ((equal mh-highlight-citation-p 'font-lock)
1110 (setq font-lock-defaults '(mh-show-font-lock-keywords-with-cite t)))
1111 ((equal mh-highlight-citation-p '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)
924df208 1123 (mh-funcall-if-exists mh-toolbar-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
c3d9274a
BW
1257 (or mh-decode-mime-flag mhl-formfile
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)
bdcfe844
BW
1559 "Show message at cursor.
1560If optional argument MESSAGE is non-nil, display that message instead.
a66894d8
BW
1561Force a two-window display with the folder window on top (size given by the
1562variable `mh-summary-height') and the show buffer below it.
c919c21a
RS
1563If the message is already visible, display the start of the message.
1564
f0d73c14
BW
1565If REDISPLAY-FLAG is non-nil, the default when called interactively, the
1566message is redisplayed even if the show buffer was already displaying the
1567correct message.
1568
c919c21a 1569Display of the message is controlled by setting the variables
bdcfe844 1570`mh-clean-message-header-flag' and `mhl-formfile'. The default behavior is
c919c21a
RS
1571to scroll uninteresting headers off the top of the window.
1572Type \"\\[mh-header-display]\" to see the message with all its headers."
f0d73c14
BW
1573 (interactive (list nil t))
1574 (when (or redisplay-flag
1575 (and mh-showing-with-headers
1576 (or mhl-formfile mh-clean-message-header-flag)))
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
BW
1637(defun mh-modify (&optional message)
1638 "Edit message at cursor.
1639If optional argument MESSAGE is non-nil, edit that message instead.
a66894d8
BW
1640Force a two-window display with the folder window on top (size given by the
1641value of the variable `mh-summary-height') and the message editing buffer below
1642it.
bdcfe844
BW
1643
1644The message is displayed in raw form."
1645 (interactive)
1646 (let* ((message (or message (mh-get-msg-num t)))
1647 (msg-filename (mh-msg-filename message))
1648 edit-buffer)
1649 (when (not (file-exists-p msg-filename))
1650 (error "Message %d does not exist" message))
1651
1652 ;; Invalidate the show buffer if it is showing the same message that is
1653 ;; to be edited.
1654 (when (and (buffer-live-p (get-buffer mh-show-buffer))
1655 (equal (save-excursion (set-buffer mh-show-buffer)
1656 buffer-file-name)
1657 msg-filename))
1658 (mh-invalidate-show-buffer))
1659
1660 ;; Edit message
1661 (find-file msg-filename)
1662 (setq edit-buffer (current-buffer))
1663
1664 ;; Set buffer properties
1665 (mh-letter-mode)
1666 (use-local-map text-mode-map)
1667
1668 ;; Just show the edit buffer...
1669 (delete-other-windows)
1670 (switch-to-buffer edit-buffer)))
c26cf6c8 1671
a1b4049d 1672(defun mh-show-unquote-From ()
bdcfe844 1673 "Decode >From at beginning of lines for `mh-show-mode'."
a1b4049d
BW
1674 (save-excursion
1675 (let ((modified (buffer-modified-p))
e495eaec
BW
1676 (case-fold-search nil)
1677 (buffer-read-only nil))
924df208 1678 (goto-char (mh-mail-header-end))
a1b4049d
BW
1679 (while (re-search-forward "^>From" nil t)
1680 (replace-match "From"))
1681 (set-buffer-modified-p modified))))
1682
bdcfe844
BW
1683(defun mh-msg-folder (folder-name)
1684 "Return the name of the buffer for FOLDER-NAME."
1685 folder-name)
1686
1687(defun mh-display-msg (msg-num folder-name)
1688 "Display MSG-NUM of FOLDER-NAME.
1689Sets the current buffer to the show buffer."
1690 (let ((folder (mh-msg-folder folder-name)))
1691 (set-buffer folder)
1692 ;; When Gnus uses external displayers it has to keep handles longer. So
1693 ;; we will delete these handles when mh-quit is called on the folder. It
1694 ;; would be nicer if there are weak pointers in emacs lisp, then we could
1695 ;; get the garbage collector to do this for us.
1696 (unless (mh-buffer-data)
1697 (setf (mh-buffer-data) (mh-make-buffer-data)))
1698 ;; Bind variables in folder buffer in case they are local
1699 (let ((formfile mhl-formfile)
1700 (clean-message-header mh-clean-message-header-flag)
f0d73c14
BW
1701 (invisible-headers mh-invisible-header-fields-compiled)
1702 (visible-headers nil)
bdcfe844
BW
1703 (msg-filename (mh-msg-filename msg-num folder-name))
1704 (show-buffer mh-show-buffer)
1705 (mm-inline-media-tests mh-mm-inline-media-tests))
1706 (if (not (file-exists-p msg-filename))
c3d9274a 1707 (error "Message %d does not exist" msg-num))
bdcfe844 1708 (if (and (> mh-show-maximum-size 0)
c3d9274a
BW
1709 (> (elt (file-attributes msg-filename) 7)
1710 mh-show-maximum-size)
1711 (not (y-or-n-p
1712 (format
1713 "Message %d (%d bytes) exceeds %d bytes. Display it? "
1714 msg-num (elt (file-attributes msg-filename) 7)
1715 mh-show-maximum-size))))
1716 (error "Message %d not displayed" msg-num))
bdcfe844
BW
1717 (set-buffer show-buffer)
1718 (cond ((not (equal msg-filename buffer-file-name))
1719 (mh-unvisit-file)
1720 (setq buffer-read-only nil)
1721 (erase-buffer)
1722 ;; Changing contents, so this hook needs to be reinitialized.
1723 ;; pgp.el uses this.
1724 (if (boundp 'write-contents-hooks) ;Emacs 19
c3d9274a 1725 (kill-local-variable 'write-contents-hooks))
bdcfe844 1726 (if formfile
c3d9274a 1727 (mh-exec-lib-cmd-output "mhl" "-nobell" "-noclear"
bdcfe844 1728 (if (stringp formfile)
c3d9274a 1729 (list "-form" formfile))
bdcfe844 1730 msg-filename)
3d7ca223 1731 (insert-file-contents-literally msg-filename))
bdcfe844
BW
1732 ;; Cleanup old mime handles
1733 (mh-mime-cleanup)
1734 ;; Use mm to display buffer
1735 (when (and mh-decode-mime-flag (not formfile))
1736 (mh-add-missing-mime-version-header)
1737 (setf (mh-buffer-data) (mh-make-buffer-data))
1738 (mh-mime-display))
924df208 1739 (mh-show-mode)
bdcfe844
BW
1740 ;; Header cleanup
1741 (goto-char (point-min))
1742 (cond (clean-message-header
1743 (mh-clean-msg-header (point-min)
1744 invisible-headers
1745 visible-headers)
1746 (goto-char (point-min)))
1747 (t
1748 (mh-start-of-uncleaned-message)))
924df208 1749 (mh-decode-message-header)
bdcfe844
BW
1750 ;; the parts of visiting we want to do (no locking)
1751 (or (eq buffer-undo-list t) ;don't save undo info for prev msgs
1752 (setq buffer-undo-list nil))
1753 (set-buffer-auto-saved)
1754 ;; the parts of set-visited-file-name we want to do (no locking)
1755 (setq buffer-file-name msg-filename)
1756 (setq buffer-backed-up nil)
1757 (auto-save-mode 1)
1758 (set-mark nil)
bdcfe844
BW
1759 (unwind-protect
1760 (when (and mh-decode-mime-flag (not formfile))
1761 (setq buffer-read-only nil)
1762 (mh-display-smileys)
1763 (mh-display-emphasis))
1764 (setq buffer-read-only t))
1765 (set-buffer-modified-p nil)
1766 (setq mh-show-folder-buffer folder)
1767 (setq mode-line-buffer-identification
1768 (list (format mh-show-buffer-mode-line-buffer-id
1769 folder-name msg-num)))
3d7ca223 1770 (mh-logo-display)
bdcfe844
BW
1771 (set-buffer folder)
1772 (setq mh-showing-with-headers nil))))))
c26cf6c8
RS
1773
1774(defun mh-clean-msg-header (start invisible-headers visible-headers)
bdcfe844
BW
1775 "Flush extraneous lines in message header.
1776Header is cleaned from START to the end of the message header.
1777INVISIBLE-HEADERS contains a regular expression specifying lines to delete
1778from the header. VISIBLE-HEADERS contains a regular expression specifying the
f0d73c14
BW
1779lines to display. INVISIBLE-HEADERS is ignored if VISIBLE-HEADERS is non-nil.
1780
1781Note that MH-E no longer supports the `mh-visible-headers' variable, so
1782this function could be trimmed of this feature too."
a1b4049d 1783 (let ((case-fold-search t)
924df208 1784 (buffer-read-only nil)
a1b4049d 1785 (after-change-functions nil)) ;Work around emacs-20 font-lock bug
c3d9274a 1786 ;causing an endless loop.
c26cf6c8
RS
1787 (save-restriction
1788 (goto-char start)
1789 (if (search-forward "\n\n" nil 'move)
c3d9274a 1790 (backward-char 1))
c26cf6c8
RS
1791 (narrow-to-region start (point))
1792 (goto-char (point-min))
1793 (if visible-headers
c3d9274a
BW
1794 (while (< (point) (point-max))
1795 (cond ((looking-at visible-headers)
1796 (forward-line 1)
1797 (while (looking-at "[ \t]") (forward-line 1)))
1798 (t
1799 (mh-delete-line 1)
1800 (while (looking-at "[ \t]")
1801 (mh-delete-line 1)))))
1802 (while (re-search-forward invisible-headers nil t)
1803 (beginning-of-line)
1804 (mh-delete-line 1)
1805 (while (looking-at "[ \t]")
a66894d8
BW
1806 (mh-delete-line 1)))))
1807 (let ((mh-compose-skipped-header-fields ()))
1808 (mh-letter-hide-all-skipped-fields))
1809 (unlock-buffer)))
c26cf6c8 1810
c26cf6c8 1811(defun mh-delete-line (lines)
bdcfe844 1812 "Delete the next LINES lines."
b3470e4c 1813 (delete-region (point) (progn (forward-line lines) (point))))
c26cf6c8 1814
c26cf6c8 1815(defun mh-notate (msg notation offset)
bdcfe844 1816 "Mark MSG with the character NOTATION at position OFFSET.
924df208
BW
1817Null MSG means the message at cursor.
1818If NOTATION is nil then no change in the buffer occurs."
c26cf6c8
RS
1819 (save-excursion
1820 (if (or (null msg)
c3d9274a
BW
1821 (mh-goto-msg msg t t))
1822 (with-mh-folder-updating (t)
1823 (beginning-of-line)
1824 (forward-char offset)
f0d73c14 1825 (let* ((change-stack-flag (and (equal offset (1+ mh-cmd-note))
a66894d8
BW
1826 (not (eq notation mh-note-seq))))
1827 (msg (and change-stack-flag (or msg (mh-get-msg-num nil))))
1828 (stack (and msg (gethash msg mh-sequence-notation-history)))
1829 (notation (or notation (char-after))))
1830 (if stack
1831 ;; The presence of the stack tells us that we don't need to
1832 ;; notate the message, since the notation would be replaced
1833 ;; by a sequence notation. So we will just put the notation
1834 ;; at the bottom of the stack. If the sequence is deleted,
1835 ;; the correct notation will be shown.
1836 (setf (gethash msg mh-sequence-notation-history)
f0d73c14 1837 (reverse (cons notation (cdr (reverse stack)))))
a66894d8
BW
1838 ;; Since we don't have any sequence notations in the way, just
1839 ;; notate the scan line.
1840 (delete-char 1)
1841 (insert notation))
1842 (when change-stack-flag
1843 (mh-thread-update-scan-line-map msg notation offset)))))))
c26cf6c8 1844
c26cf6c8
RS
1845(defun mh-goto-msg (number &optional no-error-if-no-message dont-show)
1846 "Position the cursor at message NUMBER.
a1b4049d
BW
1847Optional non-nil second argument NO-ERROR-IF-NO-MESSAGE means return nil
1848instead of signaling an error if message does not exist; in this case, the
1849cursor is positioned near where the message would have been.
1850Non-nil third argument DONT-SHOW means not to show the message."
b6d4ab05 1851 (interactive "NGo to message: ")
bdcfe844
BW
1852 (setq number (prefix-numeric-value number))
1853 (let ((point (point))
1854 (return-value t))
1855 (goto-char (point-min))
1856 (unless (re-search-forward (format "^[ ]*%s[^0-9]+" number) nil t)
1857 (goto-char point)
1858 (unless no-error-if-no-message
1859 (error "No message %d" number))
1860 (setq return-value nil))
1861 (beginning-of-line)
1862 (or dont-show (not return-value) (mh-maybe-show number))
1863 return-value))
c26cf6c8 1864
b6d4ab05 1865(defun mh-get-profile-field (field)
bdcfe844
BW
1866 "Find and return the value of FIELD in the current buffer.
1867Returns nil if the field is not in the buffer."
b6d4ab05
KH
1868 (let ((case-fold-search t))
1869 (goto-char (point-min))
1870 (cond ((not (re-search-forward (format "^%s" field) nil t)) nil)
c3d9274a
BW
1871 ((looking-at "[\t ]*$") nil)
1872 (t
1873 (re-search-forward "[\t ]*\\([^\t \n].*\\)$" nil t)
1874 (let ((start (match-beginning 1)))
1875 (end-of-line)
1876 (buffer-substring start (point)))))))
b6d4ab05 1877
7c3b9c62
RS
1878(defvar mh-find-path-run nil
1879 "Non-nil if `mh-find-path' has been run already.")
b6d4ab05 1880
c26cf6c8 1881(defun mh-find-path ()
f0d73c14 1882 "Set variables from user's MH profile.
bdcfe844
BW
1883Set `mh-user-path', `mh-draft-folder', `mh-unseen-seq', `mh-previous-seq',
1884`mh-inbox' from user's MH profile.
1885The value of `mh-find-path-hook' is a list of functions to be called, with no
1886arguments, after these variable have been set."
f0d73c14 1887 (mh-variants)
7c3b9c62
RS
1888 (unless mh-find-path-run
1889 (setq mh-find-path-run t)
f0d73c14
BW
1890 (save-excursion
1891 ;; Be sure profile is fully expanded before switching buffers
1892 (let ((profile (expand-file-name (or (getenv "MH") "~/.mh_profile"))))
1893 (set-buffer (get-buffer-create mh-temp-buffer))
1894 (setq buffer-offer-save nil) ;for people who set default to t
1895 (erase-buffer)
1896 (condition-case err
1897 (insert-file-contents profile)
1898 (file-error
1899 (mh-install profile err)))
1900 (setq mh-user-path (mh-get-profile-field "Path:"))
1901 (if (not mh-user-path)
1902 (setq mh-user-path "Mail"))
1903 (setq mh-user-path
1904 (file-name-as-directory
1905 (expand-file-name mh-user-path (expand-file-name "~"))))
1906 (unless mh-x-image-cache-directory
1907 (setq mh-x-image-cache-directory
1908 (expand-file-name ".mhe-x-image-cache" mh-user-path)))
1909 (setq mh-draft-folder (mh-get-profile-field "Draft-Folder:"))
1910 (if mh-draft-folder
1911 (progn
1912 (if (not (mh-folder-name-p mh-draft-folder))
1913 (setq mh-draft-folder (format "+%s" mh-draft-folder)))
1914 (if (not (file-exists-p (mh-expand-file-name mh-draft-folder)))
1915 (error
1916 "Draft folder \"%s\" not found. Create it and try again"
1917 (mh-expand-file-name mh-draft-folder)))))
1918 (setq mh-inbox (mh-get-profile-field "Inbox:"))
1919 (cond ((not mh-inbox)
1920 (setq mh-inbox "+inbox"))
1921 ((not (mh-folder-name-p mh-inbox))
1922 (setq mh-inbox (format "+%s" mh-inbox))))
1923 (setq mh-unseen-seq (mh-get-profile-field "Unseen-Sequence:"))
1924 (if mh-unseen-seq
1925 (setq mh-unseen-seq (intern mh-unseen-seq))
1926 (setq mh-unseen-seq 'unseen)) ;old MH default?
1927 (setq mh-previous-seq (mh-get-profile-field "Previous-Sequence:"))
1928 (if mh-previous-seq
1929 (setq mh-previous-seq (intern mh-previous-seq)))
1930 (run-hooks 'mh-find-path-hook)
1931 (mh-collect-folder-names)))))
c26cf6c8 1932
f209429d
RS
1933(defun mh-file-command-p (file)
1934 "Return t if file FILE is the name of a executable regular file."
1935 (and (file-regular-p file) (file-executable-p file)))
1936
c3d9274a 1937(defvar mh-no-install nil) ;do not run install-mh
b3470e4c 1938
c26cf6c8 1939(defun mh-install (profile error-val)
bdcfe844
BW
1940 "Initialize the MH environment.
1941This is called if we fail to read the PROFILE file. ERROR-VAL is the error
1942that made this call necessary."
c26cf6c8 1943 (if (or (getenv "MH")
c3d9274a
BW
1944 (file-exists-p profile)
1945 mh-no-install)
b3470e4c 1946 (signal (car error-val)
c3d9274a
BW
1947 (list (format "Cannot read MH profile \"%s\"" profile)
1948 (car (cdr (cdr error-val))))))
c26cf6c8
RS
1949 ;; The "install-mh" command will output a short note which
1950 ;; mh-exec-cmd will display to the user.
b6d4ab05
KH
1951 ;; The MH 5 version of install-mh might try prompt the user
1952 ;; for information, which would fail here.
ae3864d7 1953 (mh-exec-cmd (expand-file-name "install-mh" mh-lib-progs) "-auto")
c26cf6c8
RS
1954 ;; now try again to read the profile file
1955 (erase-buffer)
1956 (condition-case err
1957 (insert-file-contents profile)
1958 (file-error
c3d9274a
BW
1959 (signal (car err) ;re-signal with more specific msg
1960 (list (format "Cannot read MH profile \"%s\"" profile)
1961 (car (cdr (cdr err))))))))
c26cf6c8 1962
c26cf6c8 1963(defun mh-set-folder-modified-p (flag)
bdcfe844 1964 "Mark current folder as modified or unmodified according to FLAG."
c26cf6c8
RS
1965 (set-buffer-modified-p flag))
1966
bdcfe844
BW
1967(defun mh-find-seq (name)
1968 "Return sequence NAME."
1969 (assoc name mh-seq-list))
c26cf6c8 1970
c26cf6c8 1971(defun mh-seq-to-msgs (seq)
bdcfe844 1972 "Return a list of the messages in SEQ."
c26cf6c8
RS
1973 (mh-seq-msgs (mh-find-seq seq)))
1974
bdcfe844
BW
1975(defun mh-update-scan-format (fmt width)
1976 "Return a scan format with the (msg) width in the FMT replaced with WIDTH.
1977
1978The message number width portion of the format is discovered using
1979`mh-scan-msg-format-regexp'. Its replacement is controlled with
1980`mh-scan-msg-format-string'."
1981 (or (and
1982 (string-match mh-scan-msg-format-regexp fmt)
1983 (let ((begin (match-beginning 1))
1984 (end (match-end 1)))
1985 (concat (substring fmt 0 begin)
1986 (format mh-scan-msg-format-string width)
1987 (substring fmt end))))
1988 fmt))
a1506d29 1989
bdcfe844
BW
1990(defun mh-message-number-width (folder)
1991 "Return the widest message number in this FOLDER."
1992 (or mh-progs (mh-find-path))
1993 (let ((tmp-buffer (get-buffer-create mh-temp-buffer))
c3d9274a 1994 (width 0))
bdcfe844
BW
1995 (save-excursion
1996 (set-buffer tmp-buffer)
1997 (erase-buffer)
1998 (apply 'call-process
924df208 1999 (expand-file-name mh-scan-prog mh-progs) nil '(t nil) nil
c3d9274a 2000 (list folder "last" "-format" "%(msg)"))
bdcfe844
BW
2001 (goto-char (point-min))
2002 (if (re-search-forward mh-scan-msg-number-regexp nil 0 1)
c3d9274a
BW
2003 (setq width (length (buffer-substring
2004 (match-beginning 1) (match-end 1))))))
bdcfe844 2005 width))
c26cf6c8 2006
3d7ca223 2007(defun mh-add-msgs-to-seq (msgs seq &optional internal-flag dont-annotate-flag)
bdcfe844
BW
2008 "Add MSGS to SEQ.
2009Remove duplicates and keep sequence sorted. If optional INTERNAL-FLAG is
2010non-nil, do not mark the message in the scan listing or inform MH of the
3d7ca223
BW
2011addition.
2012
2013If DONT-ANNOTATE-FLAG is non-nil then the annotations in the folder buffer are
2014not updated."
a66894d8
BW
2015 (let ((entry (mh-find-seq seq))
2016 (internal-seq-flag (mh-internal-seq seq)))
c26cf6c8
RS
2017 (if (and msgs (atom msgs)) (setq msgs (list msgs)))
2018 (if (null entry)
c3d9274a 2019 (setq mh-seq-list
bdcfe844
BW
2020 (cons (mh-make-seq seq (mh-canonicalize-sequence msgs))
2021 mh-seq-list))
2022 (if msgs (setcdr entry (mh-canonicalize-sequence
f0d73c14
BW
2023 (append msgs (mh-seq-msgs entry))))))
2024 (unless internal-flag
2025 (mh-add-to-sequence seq msgs)
2026 (when (not dont-annotate-flag)
2027 (mh-iterate-on-range msg msgs
2028 (unless (memq msg (cdr entry))
2029 (mh-add-sequence-notation msg internal-seq-flag)))))))
c26cf6c8 2030
bdcfe844
BW
2031(defun mh-canonicalize-sequence (msgs)
2032 "Sort MSGS in decreasing order and remove duplicates."
2033 (let* ((sorted-msgs (sort (copy-sequence msgs) '>))
2034 (head sorted-msgs))
2035 (while (cdr head)
2036 (if (= (car head) (cadr head))
2037 (setcdr head (cddr head))
2038 (setq head (cdr head))))
2039 sorted-msgs))
c26cf6c8 2040
3d7ca223 2041(defvar mh-sub-folders-cache (make-hash-table :test #'equal))
924df208 2042(defvar mh-current-folder-name nil)
a66894d8
BW
2043(defvar mh-flists-partial-line "")
2044(defvar mh-flists-process nil)
2045
2046;; Initialize mh-sub-folders-cache...
2047(defun mh-collect-folder-names ()
2048 "Collect folder names by running `flists'."
2049 (unless mh-flists-process
2050 (setq mh-flists-process
2051 (mh-exec-cmd-daemon "folders" 'mh-collect-folder-names-filter
2052 "-recurse" "-fast"))))
2053
2054(defun mh-collect-folder-names-filter (process output)
2055 "Read folder names.
2056PROCESS is the flists process that was run to collect folder names and the
2057function is called when OUTPUT is available."
2058 (let ((position 0)
2059 (prevailing-match-data (match-data))
2060 line-end folder)
2061 (unwind-protect
2062 (while (setq line-end (string-match "\n" output position))
2063 (setq folder (format "+%s%s"
2064 mh-flists-partial-line
2065 (substring output position line-end)))
2066 (setq mh-flists-partial-line "")
2067 (unless (equal (aref folder 1) ?.)
2068 (mh-populate-sub-folders-cache folder))
2069 (setq position (1+ line-end)))
2070 (set-match-data prevailing-match-data))
2071 (setq mh-flists-partial-line (substring output position))))
2072
2073(defun mh-populate-sub-folders-cache (folder)
2074 "Tell `mh-sub-folders-cache' about FOLDER."
2075 (let* ((last-slash (mh-search-from-end ?/ folder))
2076 (child1 (substring folder (1+ (or last-slash 0))))
2077 (parent (and last-slash (substring folder 0 last-slash)))
2078 (parent-slash (and parent (mh-search-from-end ?/ parent)))
2079 (child2 (and parent (substring parent (1+ (or parent-slash 0)))))
2080 (grand-parent (and parent-slash (substring parent 0 parent-slash)))
2081 (cache-entry (gethash parent mh-sub-folders-cache)))
2082 (unless (loop for x in cache-entry when (equal (car x) child1) return t
2083 finally return nil)
2084 (push (list child1) cache-entry)
2085 (setf (gethash parent mh-sub-folders-cache)
2086 (sort cache-entry (lambda (x y) (string< (car x) (car y)))))
2087 (when parent
2088 (loop for x in (gethash grand-parent mh-sub-folders-cache)
2089 when (equal (car x) child2)
2090 do (progn (setf (cdr x) t) (return)))))))
3d7ca223
BW
2091
2092(defun mh-normalize-folder-name (folder &optional empty-string-okay
2093 dont-remove-trailing-slash)
2094 "Normalizes FOLDER name.
2095Makes sure that two '/' characters never occur next to each other. Also all
2096occurrences of \"..\" and \".\" are suitably processed. So \"+inbox/../news\"
2097will be normalized to \"+news\".
2098
2099If optional argument EMPTY-STRING-OKAY is nil then a '+' is added at the
2100front if FOLDER lacks one. If non-nil and FOLDER is the empty string then
2101nothing is added.
2102
2103If optional argument DONT-REMOVE-TRAILING-SLASH is non-nil then a trailing '/'
2104if present is retained (if present), otherwise it is removed."
2105 (when (stringp folder)
2106 ;; Replace two or more consecutive '/' characters with a single '/'
2107 (while (string-match "//" folder)
2108 (setq folder (replace-match "/" nil t folder)))
2109 (let* ((length (length folder))
2110 (trailing-slash-present (and (> length 0)
924df208
BW
2111 (equal (aref folder (1- length)) ?/)))
2112 (leading-slash-present (and (> length 0)
2113 (equal (aref folder 0) ?/))))
2114 (when (and (> length 0) (equal (aref folder 0) ?@)
2115 (stringp mh-current-folder-name))
2116 (setq folder (format "%s/%s/" mh-current-folder-name
2117 (substring folder 1))))
2118 ;; XXX: Purge empty strings from the list that split-string returns. In
2119 ;; XEmacs, (split-string "+foo/" "/") returns ("+foo" "") while in GNU
2120 ;; Emacs it returns ("+foo"). In the code it is assumed that the
2121 ;; components list has no empty strings.
2122 (let ((components (delete "" (split-string folder "/")))
3d7ca223
BW
2123 (result ()))
2124 ;; Remove .. and . from the pathname.
2125 (dolist (component components)
2126 (cond ((and (equal component "..") result)
2127 (pop result))
2128 ((equal component ".."))
2129 ((equal component "."))
2130 (t (push component result))))
2131 (setq folder "")
2132 (dolist (component result)
2133 (setq folder (concat component "/" folder)))
2134 ;; Remove trailing '/' if needed.
2135 (unless (and trailing-slash-present dont-remove-trailing-slash)
2136 (when (not (equal folder ""))
924df208
BW
2137 (setq folder (substring folder 0 (1- (length folder))))))
2138 (when leading-slash-present
2139 (setq folder (concat "/" folder)))))
3d7ca223
BW
2140 (cond ((and empty-string-okay (equal folder "")))
2141 ((equal folder "") (setq folder "+"))
2142 ((not (equal (aref folder 0) ?+)) (setq folder (concat "+" folder)))))
2143 folder)
2144
2145(defun mh-sub-folders (folder &optional add-trailing-slash-flag)
2146 "Find the subfolders of FOLDER.
2147The function avoids running folders unnecessarily by caching the results of
2148the actual folders call.
2149
2150If optional argument ADD-TRAILING-SLASH-FLAG is non-nil then a slash is added
2151to each of the sub-folder names that may have nested folders within them."
2152 (let* ((folder (mh-normalize-folder-name folder))
2153 (match (gethash folder mh-sub-folders-cache 'no-result))
2154 (sub-folders (cond ((eq match 'no-result)
2155 (setf (gethash folder mh-sub-folders-cache)
2156 (mh-sub-folders-actual folder)))
2157 (t match))))
2158 (if add-trailing-slash-flag
2159 (mapcar #'(lambda (x)
2160 (if (cdr x) (cons (concat (car x) "/") (cdr x)) x))
2161 sub-folders)
2162 sub-folders)))
2163
2164(defun mh-sub-folders-actual (folder)
2165 "Execute the command folders to return the sub-folders of FOLDER.
2166Filters out the folder names that start with \".\" so that directories that
2167aren't usually mail folders are hidden."
2168 (let ((arg-list `(,(expand-file-name "folders" mh-progs)
2169 nil (t nil) nil "-noheader" "-norecurse" "-nototal"
2170 ,@(if (stringp folder) (list folder) ())))
2171 (results ())
2172 (current-folder (concat
2173 (with-temp-buffer
2174 (call-process (expand-file-name "folder" mh-progs)
2175 nil '(t nil) nil "-fast")
2176 (buffer-substring (point-min) (1- (point-max))))
2177 "+")))
2178 (with-temp-buffer
2179 (apply #'call-process arg-list)
2180 (goto-char (point-min))
2181 (while (not (and (eolp) (bolp)))
2182 (goto-char (line-end-position))
f0d73c14
BW
2183 (let ((start-pos (line-beginning-position))
2184 (has-pos (search-backward " has " (line-beginning-position) t)))
3d7ca223
BW
2185 (when (integerp has-pos)
2186 (while (equal (char-after has-pos) ? )
2187 (decf has-pos))
2188 (incf has-pos)
f0d73c14
BW
2189 (while (equal (char-after start-pos) ? )
2190 (incf start-pos))
2191 (let* ((name (buffer-substring start-pos has-pos))
3d7ca223
BW
2192 (first-char (aref name 0))
2193 (last-char (aref name (1- (length name)))))
2194 (unless (member first-char '(?. ?# ?,))
2195 (when (and (equal last-char ?+) (equal name current-folder))
2196 (setq name (substring name 0 (1- (length name)))))
2197 (push
2198 (cons name
2199 (search-forward "(others)" (line-end-position) t))
2200 results))))
2201 (forward-line 1))))
2202 (setq results (nreverse results))
2203 (when (stringp folder)
2204 (setq results (cdr results))
2205 (let ((folder-name-len (length (format "%s/" (substring folder 1)))))
2206 (setq results (mapcar (lambda (f)
2207 (cons (substring (car f) folder-name-len)
2208 (cdr f)))
2209 results))))
2210 results))
2211
2212(defun mh-remove-from-sub-folders-cache (folder)
2213 "Remove FOLDER and its parent from `mh-sub-folders-cache'.
2214FOLDER should be unconditionally removed from the cache. Also the last ancestor
2215of FOLDER present in the cache must be removed as well.
2216
2217To see why this is needed assume we have a folder +foo which has a single
2218sub-folder qux. Now we create the folder +foo/bar/baz. Here we will need to
2219invalidate the cached sub-folders of +foo, otherwise completion on +foo won't
2220tell us about the option +foo/bar!"
2221 (remhash folder mh-sub-folders-cache)
2222 (block ancestor-found
2223 (let ((parent folder)
2224 (one-ancestor-found nil)
2225 last-slash)
2226 (while (setq last-slash (mh-search-from-end ?/ parent))
2227 (setq parent (substring parent 0 last-slash))
2228 (unless (eq (gethash parent mh-sub-folders-cache 'none) 'none)
2229 (remhash parent mh-sub-folders-cache)
2230 (if one-ancestor-found
2231 (return-from ancestor-found)
2232 (setq one-ancestor-found t))))
2233 (remhash nil mh-sub-folders-cache))))
2234
bdcfe844
BW
2235(defvar mh-folder-hist nil)
2236(defvar mh-speed-folder-map)
924df208
BW
2237(defvar mh-speed-flists-cache)
2238
2239(defvar mh-allow-root-folder-flag nil
2240 "Non-nil means \"+\" is an acceptable folder name.
2241This variable is used to communicate with `mh-folder-completion-function'. That
2242function can have exactly three arguments so we bind this variable to t or nil.
2243
2244This variable should never be set.")
2245
3d7ca223
BW
2246(defvar mh-folder-completion-map (copy-keymap minibuffer-local-completion-map))
2247(define-key mh-folder-completion-map " " 'minibuffer-complete)
2248
a66894d8
BW
2249(defvar mh-speed-flists-inhibit-flag nil)
2250
924df208
BW
2251(defun mh-speed-flists-active-p ()
2252 "Check if speedbar is running with message counts enabled."
2253 (and (featurep 'mh-speed)
a66894d8 2254 (not mh-speed-flists-inhibit-flag)
924df208
BW
2255 (> (hash-table-count mh-speed-flists-cache) 0)))
2256
3d7ca223
BW
2257(defun mh-folder-completion-function (name predicate flag)
2258 "Programmable completion for folder names.
2259NAME is the partial folder name that has been input. PREDICATE if non-nil is a
2260function that is used to filter the possible choices and FLAG determines
2261whether the completion is over."
2262 (let* ((orig-name name)
2263 (name (mh-normalize-folder-name name nil t))
2264 (last-slash (mh-search-from-end ?/ name))
2265 (last-complete (if last-slash (substring name 0 last-slash) nil))
2266 (remainder (cond (last-complete (substring name (1+ last-slash)))
2267 ((and (> (length name) 0) (equal (aref name 0) ?+))
2268 (substring name 1))
2269 (t ""))))
2270 (cond ((eq flag nil)
2271 (let ((try-res (try-completion
2272 name
2273 (mapcar (lambda (x)
2274 (cons (if (not last-complete)
2275 (concat "+" (car x))
2276 (concat last-complete "/" (car x)))
2277 (cdr x)))
2278 (mh-sub-folders last-complete t))
2279 predicate)))
2280 (cond ((eq try-res nil) nil)
2281 ((and (eq try-res t) (equal name orig-name)) t)
2282 ((eq try-res t) name)
2283 (t try-res))))
2284 ((eq flag t)
2285 (all-completions
2286 remainder (mh-sub-folders last-complete t) predicate))
2287 ((eq flag 'lambda)
924df208
BW
2288 (let ((path (concat mh-user-path
2289 (substring (mh-normalize-folder-name name) 1))))
2290 (cond (mh-allow-root-folder-flag (file-exists-p path))
2291 ((equal path mh-user-path) nil)
2292 (t (file-exists-p path))))))))
2293
2294(defun mh-folder-completing-read (prompt default allow-root-folder-flag)
2295 "Read folder name with PROMPT and default result DEFAULT.
2296If ALLOW-ROOT-FOLDER-FLAG is non-nil then \"+\" is allowed to be a folder name
2297corresponding to `mh-user-path'."
3d7ca223 2298 (mh-normalize-folder-name
f0d73c14
BW
2299 (let ((minibuffer-completing-file-name t)
2300 (completion-root-regexp "^[+/]")
2301 (minibuffer-local-completion-map mh-folder-completion-map)
924df208 2302 (mh-allow-root-folder-flag allow-root-folder-flag))
3d7ca223
BW
2303 (completing-read prompt 'mh-folder-completion-function nil nil nil
2304 'mh-folder-hist default))
2305 t))
bdcfe844
BW
2306
2307(defun mh-prompt-for-folder (prompt default can-create
3d7ca223 2308 &optional default-string allow-root-folder-flag)
bdcfe844
BW
2309 "Prompt for a folder name with PROMPT.
2310Returns the folder's name as a string. DEFAULT is used if the folder exists
2311and the user types return. If the CAN-CREATE flag is t, then a folder is
2312created if it doesn't already exist. If optional argument DEFAULT-STRING is
3d7ca223
BW
2313non-nil, use it in the prompt instead of DEFAULT. If ALLOW-ROOT-FOLDER-FLAG is
2314non-nil then the function will accept the folder +, which means all folders
2315when used in searching."
c26cf6c8
RS
2316 (if (null default)
2317 (setq default ""))
f0d73c14
BW
2318 (let* ((default-string (cond (default-string (format "[%s] " default-string))
2319 ((equal "" default) "")
2320 (t (format "[%s] " default))))
2321 (prompt (format "%s folder: %s" prompt default-string))
924df208 2322 (mh-current-folder-name mh-current-folder)
c3d9274a 2323 read-name folder-name)
924df208
BW
2324 (while (and (setq read-name (mh-folder-completing-read
2325 prompt default allow-root-folder-flag))
c3d9274a
BW
2326 (equal read-name "")
2327 (equal default "")))
3d7ca223
BW
2328 (cond ((or (equal read-name "")
2329 (and (equal read-name "+") (not allow-root-folder-flag)))
c3d9274a
BW
2330 (setq read-name default))
2331 ((not (mh-folder-name-p read-name))
2332 (setq read-name (format "+%s" read-name))))
a1b4049d
BW
2333 (if (or (not read-name) (equal "" read-name))
2334 (error "No folder specified"))
c26cf6c8
RS
2335 (setq folder-name read-name)
2336 (cond ((and (> (length folder-name) 0)
c3d9274a
BW
2337 (eq (aref folder-name (1- (length folder-name))) ?/))
2338 (setq folder-name (substring folder-name 0 -1))))
924df208
BW
2339 (let* ((last-slash (mh-search-from-end ?/ folder-name))
2340 (parent (and last-slash (substring folder-name 0 last-slash)))
2341 (child (if last-slash
2342 (substring folder-name (1+ last-slash))
2343 (substring folder-name 1))))
2344 (unless (member child
2345 (mapcar #'car (gethash parent mh-sub-folders-cache)))
2346 (mh-remove-from-sub-folders-cache folder-name)))
bdcfe844 2347 (let ((new-file-flag
c3d9274a 2348 (not (file-exists-p (mh-expand-file-name folder-name)))))
bdcfe844 2349 (cond ((and new-file-flag
c3d9274a
BW
2350 (y-or-n-p
2351 (format "Folder %s does not exist. Create it? "
2352 folder-name)))
2353 (message "Creating %s" folder-name)
bdcfe844 2354 (mh-exec-cmd-error nil "folder" folder-name)
3d7ca223 2355 (mh-remove-from-sub-folders-cache folder-name)
bdcfe844
BW
2356 (when (boundp 'mh-speed-folder-map)
2357 (mh-speed-add-folder folder-name))
3d7ca223 2358 (message "Creating %s...done" folder-name))
c3d9274a
BW
2359 (new-file-flag
2360 (error "Folder %s is not created" folder-name))
2361 ((not (file-directory-p (mh-expand-file-name folder-name)))
2362 (error "\"%s\" is not a directory"
3d7ca223 2363 (mh-expand-file-name folder-name)))))
c26cf6c8
RS
2364 folder-name))
2365
924df208
BW
2366(defun mh-truncate-log-buffer ()
2367 "If `mh-log-buffer' is too big then truncate it.
2368If the number of lines in `mh-log-buffer' exceeds `mh-log-buffer-lines' then
2369keep only the last `mh-log-buffer-lines'. As a side effect the point is set to
2370the end of the log buffer.
2371
2372The function returns the size of the final size of the log buffer."
2373 (with-current-buffer (get-buffer-create mh-log-buffer)
2374 (goto-char (point-max))
2375 (save-excursion
2376 (when (equal (forward-line (- mh-log-buffer-lines)) 0)
2377 (delete-region (point-min) (point))))
2378 (unless (or (bobp)
2379 (save-excursion
2380 (and (equal (forward-line -1) 0) (equal (char-after) ?\f))))
2381 (insert "\n\f\n"))
2382 (buffer-size)))
2383
c26cf6c8
RS
2384;;; Issue commands to MH.
2385
c26cf6c8 2386(defun mh-exec-cmd (command &rest args)
bdcfe844
BW
2387 "Execute mh-command COMMAND with ARGS.
2388The side effects are what is desired.
2389Any output is assumed to be an error and is shown to the user.
2390The output is not read or parsed by MH-E."
c26cf6c8 2391 (save-excursion
3d7ca223 2392 (set-buffer (get-buffer-create mh-log-buffer))
a66894d8
BW
2393 (let* ((initial-size (mh-truncate-log-buffer))
2394 (start (point))
2395 (args (mh-list-to-string args)))
2396 (apply 'call-process (expand-file-name command mh-progs) nil t nil args)
2397 (when (> (buffer-size) initial-size)
2398 (save-excursion
2399 (goto-char start)
2400 (insert "Errors when executing: " command)
2401 (loop for arg in args do (insert " " arg))
2402 (insert "\n"))
2403 (save-window-excursion
2404 (switch-to-buffer-other-window mh-log-buffer)
2405 (sit-for 5))))))
c26cf6c8 2406
c26cf6c8 2407(defun mh-exec-cmd-error (env command &rest args)
bdcfe844
BW
2408 "In environment ENV, execute mh-command COMMAND with ARGS.
2409ENV is nil or a string of space-separated \"var=value\" elements.
2410Signals an error if process does not complete successfully."
c26cf6c8 2411 (save-excursion
b6d4ab05 2412 (set-buffer (get-buffer-create mh-temp-buffer))
c26cf6c8 2413 (erase-buffer)
924df208
BW
2414 (let ((process-environment process-environment))
2415 ;; XXX: We should purge the list that split-string returns of empty
2416 ;; strings. This can happen in XEmacs if leading or trailing spaces
2417 ;; are present.
2418 (dolist (elem (if (stringp env) (split-string env " ") ()))
2419 (push elem process-environment))
2420 (mh-handle-process-error
2421 command (apply #'call-process (expand-file-name command mh-progs)
2422 nil t nil (mh-list-to-string args))))))
c26cf6c8 2423
3d7ca223
BW
2424(defun mh-exec-cmd-daemon (command filter &rest args)
2425 "Execute MH command COMMAND in the background.
2426
2427If FILTER is non-nil then it is used to process the output otherwise the
2428default filter `mh-process-daemon' is used. See `set-process-filter' for more
2429details of FILTER.
2430
2431ARGS are passed to COMMAND as command line arguments."
c26cf6c8 2432 (save-excursion
3d7ca223 2433 (set-buffer (get-buffer-create mh-log-buffer))
924df208 2434 (mh-truncate-log-buffer))
c26cf6c8 2435 (let* ((process-connection-type nil)
c3d9274a
BW
2436 (process (apply 'start-process
2437 command nil
2438 (expand-file-name command mh-progs)
2439 (mh-list-to-string args))))
a66894d8
BW
2440 (set-process-filter process (or filter 'mh-process-daemon))
2441 process))
c26cf6c8 2442
924df208
BW
2443(defun mh-exec-cmd-env-daemon (env command filter &rest args)
2444 "In ennvironment ENV, execute mh-command COMMAND in the background.
2445
2446ENV is nil or a string of space-separated \"var=value\" elements.
2447Signals an error if process does not complete successfully.
2448
2449If FILTER is non-nil then it is used to process the output otherwise the
2450default filter `mh-process-daemon' is used. See `set-process-filter' for more
2451details of FILTER.
2452
2453ARGS are passed to COMMAND as command line arguments."
2454 (let ((process-environment process-environment))
2455 (dolist (elem (if (stringp env) (split-string env " ") ()))
2456 (push elem process-environment))
2457 (apply #'mh-exec-cmd-daemon command filter args)))
2458
c26cf6c8 2459(defun mh-process-daemon (process output)
3d7ca223
BW
2460 "PROCESS daemon that puts OUTPUT into a temporary buffer.
2461Any output from the process is displayed in an asynchronous pop-up window."
2462 (set-buffer (get-buffer-create mh-log-buffer))
c26cf6c8 2463 (insert-before-markers output)
3d7ca223 2464 (display-buffer mh-log-buffer))
c26cf6c8 2465
c26cf6c8 2466(defun mh-exec-cmd-quiet (raise-error command &rest args)
bdcfe844
BW
2467 "Signal RAISE-ERROR if COMMAND with ARGS fails.
2468Execute MH command COMMAND with ARGS. ARGS is a list of strings.
2469Return at start of mh-temp buffer, where output can be parsed and used.
2470Returns value of `call-process', which is 0 for success, unless RAISE-ERROR is
2471non-nil, in which case an error is signaled if `call-process' returns non-0."
b6d4ab05 2472 (set-buffer (get-buffer-create mh-temp-buffer))
c26cf6c8
RS
2473 (erase-buffer)
2474 (let ((value
c3d9274a
BW
2475 (apply 'call-process
2476 (expand-file-name command mh-progs) nil t nil
2477 args)))
c26cf6c8
RS
2478 (goto-char (point-min))
2479 (if raise-error
c3d9274a 2480 (mh-handle-process-error command value)
c26cf6c8
RS
2481 value)))
2482
c3d9274a
BW
2483(defun mh-profile-component (component)
2484 "Return COMPONENT value from mhparam, or nil if unset."
2485 (save-excursion
2486 (mh-exec-cmd-quiet nil "mhparam" "-components" component)
2487 (mh-get-profile-field (concat component ":"))))
2488
bdcfe844
BW
2489(defun mh-exchange-point-and-mark-preserving-active-mark ()
2490 "Put the mark where point is now, and point where the mark is now.
2491This command works even when the mark is not active, and preserves whether the
2492mark is active or not."
2493 (interactive nil)
2494 (let ((is-active (and (boundp 'mark-active) mark-active)))
2495 (let ((omark (mark t)))
2496 (if (null omark)
2497 (error "No mark set in this buffer"))
2498 (set-mark (point))
2499 (goto-char omark)
2500 (if (boundp 'mark-active)
2501 (setq mark-active is-active))
2502 nil)))
c26cf6c8
RS
2503
2504(defun mh-exec-cmd-output (command display &rest args)
bdcfe844
BW
2505 "Execute MH command COMMAND with DISPLAY flag and ARGS.
2506Put the output into buffer after point. Set mark after inserted text.
2507Output is expected to be shown to user, not parsed by MH-E."
c26cf6c8
RS
2508 (push-mark (point) t)
2509 (apply 'call-process
c3d9274a
BW
2510 (expand-file-name command mh-progs) nil t display
2511 (mh-list-to-string args))
c26cf6c8 2512
bdcfe844
BW
2513 ;; The following is used instead of 'exchange-point-and-mark because the
2514 ;; latter activates the current region (between point and mark), which
2515 ;; turns on highlighting. So prior to this bug fix, doing "inc" would
2516 ;; highlight a region containing the new messages, which is undesirable.
2517 ;; The bug wasn't seen in emacs21 but still occurred in XEmacs21.4.
2518 (mh-exchange-point-and-mark-preserving-active-mark))
c26cf6c8
RS
2519
2520(defun mh-exec-lib-cmd-output (command &rest args)
bdcfe844
BW
2521 "Execute MH library command COMMAND with ARGS.
2522Put the output into buffer after point. Set mark after inserted text."
ae3864d7 2523 (apply 'mh-exec-cmd-output (expand-file-name command mh-lib-progs) nil args))
c26cf6c8 2524
c26cf6c8 2525(defun mh-handle-process-error (command status)
924df208
BW
2526 "Raise error if COMMAND returned non-zero STATUS, otherwise return STATUS."
2527 (if (equal status 0)
2528 status
2529 (goto-char (point-min))
2530 (insert (if (integerp status)
2531 (format "%s: exit code %d\n" command status)
2532 (format "%s: %s\n" command status)))
2533 (save-excursion
2534 (let ((error-message (buffer-substring (point-min) (point-max))))
2535 (set-buffer (get-buffer-create mh-log-buffer))
2536 (mh-truncate-log-buffer)
2537 (insert error-message)))
2538 (error "%s failed, check %s buffer for error message"
2539 command mh-log-buffer)))
c26cf6c8 2540
c26cf6c8 2541(defun mh-list-to-string (l)
bdcfe844 2542 "Flatten the list L and make every element of the new list into a string."
c26cf6c8
RS
2543 (nreverse (mh-list-to-string-1 l)))
2544
2545(defun mh-list-to-string-1 (l)
bdcfe844 2546 "Flatten the list L and make every element of the new list into a string."
c26cf6c8
RS
2547 (let ((new-list nil))
2548 (while l
2549 (cond ((null (car l)))
c3d9274a
BW
2550 ((symbolp (car l))
2551 (setq new-list (cons (symbol-name (car l)) new-list)))
2552 ((numberp (car l))
2553 (setq new-list (cons (int-to-string (car l)) new-list)))
2554 ((equal (car l) ""))
2555 ((stringp (car l)) (setq new-list (cons (car l) new-list)))
2556 ((listp (car l))
2557 (setq new-list (nconc (mh-list-to-string-1 (car l))
2558 new-list)))
2559 (t (error "Bad element in mh-list-to-string: %s" (car l))))
c26cf6c8
RS
2560 (setq l (cdr l)))
2561 new-list))
2562
f0d73c14
BW
2563(defun mh-replace-string (old new)
2564 "Replace all occurrences of OLD with NEW in the current buffer."
2565 (goto-char (point-min))
2566 (let ((case-fold-search t))
2567 (while (search-forward old nil t)
2568 (replace-match new t t))))
2569
a66894d8
BW
2570(defun mh-replace-in-string (regexp newtext string)
2571 "Replace REGEXP with NEWTEXT everywhere in STRING and return result.
2572NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
2573
2574The function body was copied from `dired-replace-in-string' in dired.el.
2575Emacs21 has `replace-regexp-in-string' while XEmacs has `replace-in-string'.
2576Neither is present in Emacs20. The file gnus-util.el in Gnus 5.10.1 and above
2577has `gnus-replace-in-string'. We should use that when we decide to not support
2578older versions of Gnus."
2579 (let ((result "") (start 0) mb me)
2580 (while (string-match regexp string start)
2581 (setq mb (match-beginning 0)
2582 me (match-end 0)
2583 result (concat result (substring string start mb) newtext)
2584 start me))
2585 (concat result (substring string start))))
2586
c26cf6c8
RS
2587(provide 'mh-utils)
2588
bdcfe844 2589;;; Local Variables:
c3d9274a 2590;;; indent-tabs-mode: nil
bdcfe844
BW
2591;;; sentence-end-double-space: nil
2592;;; End:
2593
ab5796a9 2594;;; arch-tag: 1af39fdf-f66f-4b06-9b48-18a7656c8e36
c26cf6c8 2595;;; mh-utils.el ends here