(exec-suffixes): Initialize to a system-dependent value.
[bpt/emacs.git] / lisp / mail / mh-utils.el
1 ;;; mh-utils.el --- mh-e code needed for both sending and reading
2
3 ;; Copyright (C) 1993, 1995, 1997, 2000, 2001 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
7 ;; GNU Emacs is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
10 ;; any later version.
11
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
16
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs; see the file COPYING. If not, write to the
19 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 ;; Boston, MA 02111-1307, USA.
21
22 ;;; Commentary:
23
24 ;; Internal support for mh-e package.
25
26 ;;; Code:
27
28 ;;; Set for local environment:
29 ;;; mh-progs and mh-lib used to be set in paths.el, which tried to
30 ;;; figure out at build time which of several possible directories MH
31 ;;; was installed into. But if you installed MH after building Emacs,
32 ;;; this would almost certainly be wrong, so now we do it at run time.
33
34 (defvar mh-progs nil
35 "Directory containing MH commands, such as inc, repl, and rmm.")
36
37 (defvar mh-lib nil
38 "Directory containing the MH library.
39 This directory contains, among other things,
40 the components file.")
41
42 (defvar mh-lib-progs nil
43 "Directory containing MH helper programs.
44 This directory contains, among other things,
45 the mhl program.")
46
47 (defvar mh-nmh-p nil
48 "Non-nil if nmh is installed on this system instead of MH")
49
50 ;;;###autoload
51 (put 'mh-progs 'risky-local-variable t)
52 ;;;###autoload
53 (put 'mh-lib 'risky-local-variable t)
54 ;;;###autoload
55 (put 'mh-lib-progs 'risky-local-variable t)
56 ;;;###autoload
57 (put 'mh-nmh-p 'risky-local-variable t)
58
59 ;;; User preferences:
60
61 (defgroup mh-buffer nil
62 "Layout of MH-E buffers"
63 :prefix "mh-"
64 :group 'mh)
65
66
67 (defcustom mh-auto-folder-collect t
68 "*Whether to start collecting MH folder names immediately in the background.
69 Non-nil means start a background process collecting the names of all
70 folders as soon as mh-e is loaded."
71 :type 'boolean
72 :group 'mh)
73
74 (defcustom mh-recursive-folders nil
75 "*If non-nil, then commands which operate on folders do so recursively."
76 :type 'boolean
77 :group 'mh)
78
79 (defcustom mh-clean-message-header nil
80 "*Non-nil means clean headers of messages that are displayed or inserted.
81 The variables `mh-visible-headers' and `mh-invisible-headers' control what
82 is removed."
83 :type 'boolean
84 :group 'mh-buffer)
85
86 (defcustom mh-visible-headers nil
87 "*If non-nil, contains a regexp specifying the headers to keep when cleaning.
88 Only used if `mh-clean-message-header' is non-nil. Setting this variable
89 overrides `mh-invisible-headers'."
90 :type '(choice (const nil) regexp)
91 :group 'mh-buffer)
92
93 (defvar mh-invisible-headers
94 "^Received: \\|^Message-Id: \\|^Remailed-\\|^Via: \\|^Mail-from: \\|^Return-Path: \\|^Delivery-Date: \\|^In-Reply-To: \\|^Resent-"
95 "Regexp matching lines in a message header that are not to be shown.
96 If `mh-visible-headers' is non-nil, it is used instead to specify what
97 to keep.")
98
99 (defcustom mh-bury-show-buffer t
100 "*Non-nil means that the displayed show buffer for a folder is buried."
101 :type 'boolean
102 :group 'mh-buffer)
103
104 (defcustom mh-summary-height 4
105 "*Number of lines in MH-Folder window (including the mode line)."
106 :type 'integer
107 :group 'mh-buffer)
108
109 (defvar mh-msg-number-regexp "^ *\\([0-9]+\\)"
110 "Regexp to find the number of a message in a scan line.
111 The message's number must be surrounded with \\( \\)")
112
113 (defvar mh-msg-search-regexp "^[^0-9]*%d[^0-9]"
114 "Format string containing a regexp matching the scan listing for a message.
115 The desired message's number will be an argument to format.")
116
117 (defcustom mhl-formfile nil
118 "*Name of format file to be used by mhl to show and print messages.
119 A value of T means use the default format file.
120 Nil means don't use mhl to format messages when showing; mhl is still used,
121 with the default format file, to format messages when printing them.
122 The format used should specify a non-zero value for overflowoffset so
123 the message continues to conform to RFC 822 and mh-e can parse the headers."
124 :type '(choice (const nil) (const t) string)
125 :group 'mh)
126 (put 'mhl-formfile 'info-file "mh-e")
127
128 (defvar mh-default-folder-for-message-function nil
129 "Function to select a default folder for refiling or Fcc.
130 If set to a function, that function is called with no arguments by
131 `\\[mh-refile-msg]' and `\\[mh-to-fcc]' to get a default when
132 prompting the user for a folder. The function is called from within a
133 save-excursion, with point at the start of the message. It should
134 return the folder to offer as the refile or Fcc folder, as a string
135 with a leading `+' sign. It can also return an empty string to use no
136 default, or NIL to calculate the default the usual way.
137 NOTE: This variable is not an ordinary hook;
138 It may not be a list of functions.")
139
140 (defvar mh-find-path-hook nil
141 "Invoked by mh-find-path while reading the user's MH profile.")
142
143 (defvar mh-folder-list-change-hook nil
144 "Invoked whenever the cached folder list `mh-folder-list' is changed.")
145
146 (defvar mh-show-buffer-mode-line-buffer-id "{show-%s} %d"
147 "Format string to produce `mode-line-buffer-identification' for show buffers.
148 First argument is folder name. Second is message number.")
149
150 (defvar mh-cmd-note 4
151 "Offset to insert notation.")
152
153 (defvar mh-note-seq "%"
154 "String whose first character is used to notate messages in a sequence.")
155
156 ;;; Internal bookkeeping variables:
157
158 ;; The value of `mh-folder-list-change-hook' is called whenever
159 ;; mh-folder-list variable is set.
160 (defvar mh-folder-list nil) ;List of folder names for completion.
161
162 ;; Cached value of the `Path:' component in the user's MH profile.
163 (defvar mh-user-path nil) ;User's mail folder directory.
164
165 ;; An mh-draft-folder of NIL means do not use a draft folder.
166 ;; Cached value of the `Draft-Folder:' component in the user's MH profile.
167 (defvar mh-draft-folder nil) ;Name of folder containing draft messages.
168
169 ;; Cached value of the `Unseen-Sequence:' component in the user's MH profile.
170 (defvar mh-unseen-seq nil) ;Name of the Unseen sequence.
171
172 ;; Cached value of the `Previous-Sequence:' component in the user's MH profile.
173 (defvar mh-previous-seq nil) ;Name of the Previous sequence.
174
175 ;; Cached value of the `Inbox:' component in the user's MH profile,
176 ;; or "+inbox" if no such component.
177 (defvar mh-inbox nil) ;Name of the Inbox folder.
178
179 (defconst mh-temp-buffer " *mh-temp*") ;Name of mh-e scratch buffer.
180
181 (defvar mh-previous-window-config nil) ;Window configuration before mh-e command.
182
183 ;;; Internal variables local to a folder.
184
185 (defvar mh-current-folder nil) ;Name of current folder, a string.
186
187 (defvar mh-show-buffer nil) ;Buffer that displays message for this folder.
188
189 (defvar mh-folder-filename nil) ;Full path of directory for this folder.
190
191 (defvar mh-msg-count nil) ;Number of msgs in buffer.
192
193 (defvar mh-showing nil) ;If non-nil, show the message in a separate window.
194
195 ;;; This holds a documentation string used by describe-mode.
196 (defun mh-showing ()
197 "When moving to a new message in the Folder window,
198 also show it in a separate Show window."
199 nil)
200
201 (defvar mh-seq-list nil) ;The sequences of this folder. An alist of (seq . msgs).
202
203 (defvar mh-seen-list nil) ;List of displayed messages to be removed from the Unseen sequence.
204
205 ;; If non-nil, show buffer contains message with all headers.
206 ;; If nil, show buffer contains message processed normally.
207 (defvar mh-showing-with-headers nil) ;Showing message with headers or normally.
208
209
210 ;;; mh-e macros
211
212 (defmacro with-mh-folder-updating (save-modification-flag-p &rest body)
213 ;; Format is (with-mh-folder-updating (SAVE-MODIFICATION-FLAG-P) &body BODY).
214 ;; Execute BODY, which can modify the folder buffer without having to
215 ;; worry about file locking or the read-only flag, and return its result.
216 ;; If SAVE-MODIFICATION-FLAG-P is non-nil, the buffer's modification
217 ;; flag is unchanged, otherwise it is cleared.
218 (setq save-modification-flag-p (car save-modification-flag-p)) ; CL style
219 `(prog1
220 (let ((mh-folder-updating-mod-flag (buffer-modified-p))
221 (buffer-read-only nil)
222 (buffer-file-name nil)) ;don't let the buffer get locked
223 (prog1
224 (progn
225 ,@body)
226 (mh-set-folder-modified-p mh-folder-updating-mod-flag)))
227 ,@(if (not save-modification-flag-p)
228 '((mh-set-folder-modified-p nil)))))
229
230 (put 'with-mh-folder-updating 'lisp-indent-hook 1)
231
232 (defmacro mh-in-show-buffer (show-buffer &rest body)
233 ;; Format is (mh-in-show-buffer (SHOW-BUFFER) &body BODY).
234 ;; Display buffer SHOW-BUFFER in other window and execute BODY in it.
235 ;; Stronger than save-excursion, weaker than save-window-excursion.
236 (setq show-buffer (car show-buffer)) ; CL style
237 `(let ((mh-in-show-buffer-saved-window (selected-window)))
238 (switch-to-buffer-other-window ,show-buffer)
239 (if mh-bury-show-buffer (bury-buffer (current-buffer)))
240 (unwind-protect
241 (progn
242 ,@body)
243 (select-window mh-in-show-buffer-saved-window))))
244
245 (put 'mh-in-show-buffer 'lisp-indent-hook 1)
246
247 (defmacro mh-make-seq (name msgs) (list 'cons name msgs))
248
249 (defmacro mh-seq-name (pair) (list 'car pair))
250
251 (defmacro mh-seq-msgs (pair) (list 'cdr pair))
252
253
254 ;;; Ensure new buffers won't get this mode if default-major-mode is nil.
255 (put 'mh-show-mode 'mode-class 'special)
256
257 (defun mh-show-mode ()
258 "Major mode for showing messages in mh-e.
259 The value of mh-show-mode-hook is called when a new message is displayed."
260 (kill-all-local-variables)
261 (setq major-mode 'mh-show-mode)
262 (mh-set-mode-name "MH-Show")
263 (run-hooks 'mh-show-mode-hook))
264
265
266 (defun mh-maybe-show (&optional msg)
267 ;; If in showing mode, then display the message pointed to by the cursor.
268 (if mh-showing (mh-show msg)))
269
270 (defun mh-show (&optional message)
271 "Show MESSAGE (default: message at cursor).
272 Force a two-window display with the folder window on top (size
273 mh-summary-height) and the show buffer below it.
274 If the message is already visible, display the start of the message.
275
276 Display of the message is controlled by setting the variables
277 `mh-clean-message-header' and `mhl-formfile'. The default behavior is
278 to scroll uninteresting headers off the top of the window.
279 Type \"\\[mh-header-display]\" to see the message with all its headers."
280 (interactive)
281 (and mh-showing-with-headers
282 (or mhl-formfile mh-clean-message-header)
283 (mh-invalidate-show-buffer))
284 (mh-show-msg message))
285
286
287 (defun mh-show-msg (msg)
288 (if (not msg)
289 (setq msg (mh-get-msg-num t)))
290 (setq mh-showing t)
291 (let ((folder mh-current-folder)
292 (clean-message-header mh-clean-message-header)
293 (show-window (get-buffer-window mh-show-buffer)))
294 (if (not (eq (next-window (minibuffer-window)) (selected-window)))
295 (delete-other-windows)) ; force ourself to the top window
296 (mh-in-show-buffer (mh-show-buffer)
297 (if (and show-window
298 (equal (mh-msg-filename msg folder) buffer-file-name))
299 (progn ;just back up to start
300 (goto-char (point-min))
301 (if (not clean-message-header)
302 (mh-start-of-uncleaned-message)))
303 (mh-display-msg msg folder))))
304 (if (not (= (1+ (window-height)) (screen-height))) ;not horizontally split
305 (shrink-window (- (window-height) mh-summary-height)))
306 (mh-recenter nil)
307 (if (not (memq msg mh-seen-list)) (setq mh-seen-list (cons msg mh-seen-list)))
308 (run-hooks 'mh-show-hook))
309
310
311 (defun mh-display-msg (msg-num folder)
312 ;; Display message NUMBER of FOLDER.
313 ;; Sets the current buffer to the show buffer.
314 (set-buffer folder)
315 ;; Bind variables in folder buffer in case they are local
316 (let ((formfile mhl-formfile)
317 (clean-message-header mh-clean-message-header)
318 (invisible-headers mh-invisible-headers)
319 (visible-headers mh-visible-headers)
320 (msg-filename (mh-msg-filename msg-num))
321 (show-buffer mh-show-buffer))
322 (if (not (file-exists-p msg-filename))
323 (error "Message %d does not exist" msg-num))
324 (set-buffer show-buffer)
325 (cond ((not (equal msg-filename buffer-file-name))
326 (mh-unvisit-file)
327 (erase-buffer)
328 ;; Changing contents, so this hook needs to be reinitialized.
329 ;; pgp.el uses this.
330 (if (boundp 'write-contents-hooks) ;Emacs 19
331 (kill-local-variable 'write-contents-hooks))
332 (if formfile
333 (mh-exec-lib-cmd-output "mhl" "-nobell" "-noclear"
334 (if (stringp formfile)
335 (list "-form" formfile))
336 msg-filename)
337 (insert-file-contents msg-filename))
338 (goto-char (point-min))
339 (cond (clean-message-header
340 (mh-clean-msg-header (point-min)
341 invisible-headers
342 visible-headers)
343 (goto-char (point-min)))
344 (t
345 (mh-start-of-uncleaned-message)))
346 ;; the parts of visiting we want to do (no locking)
347 (or (eq buffer-undo-list t) ;don't save undo info for prev msgs
348 (setq buffer-undo-list nil))
349 (set-buffer-modified-p nil)
350 (set-buffer-auto-saved)
351 ;; the parts of set-visited-file-name we want to do (no locking)
352 (setq buffer-file-name msg-filename)
353 (setq buffer-backed-up nil)
354 (auto-save-mode 1)
355 (set-mark nil)
356 (mh-show-mode)
357 (setq mode-line-buffer-identification
358 (list (format mh-show-buffer-mode-line-buffer-id
359 folder msg-num)))
360 (set-buffer folder)
361 (setq mh-showing-with-headers nil)))))
362
363 (defun mh-start-of-uncleaned-message ()
364 ;; position uninteresting headers off the top of the window
365 (let ((case-fold-search t))
366 (re-search-forward
367 "^To:\\|^Cc:\\|^From:\\|^Subject:\\|^Date:" nil t)
368 (beginning-of-line)
369 (mh-recenter 0)))
370
371
372 (defun mh-invalidate-show-buffer ()
373 ;; Invalidate the show buffer so we must update it to use it.
374 (if (get-buffer mh-show-buffer)
375 (save-excursion
376 (set-buffer mh-show-buffer)
377 (mh-unvisit-file))))
378
379
380 (defun mh-unvisit-file ()
381 ;; Separate current buffer from the message file it was visiting.
382 (or (not (buffer-modified-p))
383 (null buffer-file-name) ;we've been here before
384 (yes-or-no-p (format "Message %s modified; flush changes? "
385 (file-name-nondirectory buffer-file-name)))
386 (error "Flushing changes not confirmed"))
387 (clear-visited-file-modtime)
388 (unlock-buffer)
389 (setq buffer-file-name nil))
390
391
392 (defun mh-get-msg-num (error-if-no-message)
393 ;; Return the message number of the displayed message. If the argument
394 ;; ERROR-IF-NO-MESSAGE is non-nil, then complain if the cursor is not
395 ;; pointing to a message.
396 (save-excursion
397 (beginning-of-line)
398 (cond ((looking-at mh-msg-number-regexp)
399 (string-to-int (buffer-substring (match-beginning 1)
400 (match-end 1))))
401 (error-if-no-message
402 (error "Cursor not pointing to message"))
403 (t nil))))
404
405
406 (defun mh-msg-filename (msg &optional folder)
407 ;; Return the file name of MESSAGE in FOLDER (default current folder).
408 (expand-file-name (int-to-string msg)
409 (if folder
410 (mh-expand-file-name folder)
411 mh-folder-filename)))
412
413
414 (defun mh-clean-msg-header (start invisible-headers visible-headers)
415 ;; Flush extraneous lines in a message header, from the given POINT to the
416 ;; end of the message header. If VISIBLE-HEADERS is non-nil, it contains a
417 ;; regular expression specifying the lines to display, otherwise
418 ;; INVISIBLE-HEADERS contains a regular expression specifying lines to
419 ;; delete from the header.
420 (let ((case-fold-search t))
421 (save-restriction
422 (goto-char start)
423 (if (search-forward "\n\n" nil 'move)
424 (backward-char 1))
425 (narrow-to-region start (point))
426 (goto-char (point-min))
427 (if visible-headers
428 (while (< (point) (point-max))
429 (cond ((looking-at visible-headers)
430 (forward-line 1)
431 (while (looking-at "[ \t]") (forward-line 1)))
432 (t
433 (mh-delete-line 1)
434 (while (looking-at "[ \t]")
435 (mh-delete-line 1)))))
436 (while (re-search-forward invisible-headers nil t)
437 (beginning-of-line)
438 (mh-delete-line 1)
439 (while (looking-at "[ \t]")
440 (mh-delete-line 1))))
441 (unlock-buffer))))
442
443
444 (defun mh-recenter (arg)
445 ;; Like recenter but with two improvements: nil arg means recenter,
446 ;; and only does anything if the current buffer is in the selected
447 ;; window. (Commands like save-some-buffers can make this false.)
448 (if (eq (get-buffer-window (current-buffer))
449 (selected-window))
450 (recenter (if arg arg '(t)))))
451
452
453 (defun mh-delete-line (lines)
454 ;; Delete version of kill-line.
455 (delete-region (point) (progn (forward-line lines) (point))))
456
457
458 (defun mh-notate (msg notation offset)
459 ;; Marks MESSAGE with the character NOTATION at position OFFSET.
460 ;; Null MESSAGE means the message that the cursor points to.
461 (save-excursion
462 (if (or (null msg)
463 (mh-goto-msg msg t t))
464 (with-mh-folder-updating (t)
465 (beginning-of-line)
466 (forward-char offset)
467 (delete-char 1)
468 (insert notation)))))
469
470
471 (defun mh-find-msg-get-num (step)
472 ;; Return the message number of the message on the current scan line
473 ;; or one nearby. Jumps over non-message lines, such as inc errors.
474 ;; STEP tells whether to search forward or backward if we have to search.
475 (or (mh-get-msg-num nil)
476 (let ((msg-num nil)
477 (nreverses 0))
478 (while (and (not msg-num)
479 (< nreverses 2))
480 (cond ((eobp)
481 (setq step -1)
482 (setq nreverses (1+ nreverses)))
483 ((bobp)
484 (setq step 1)
485 (setq nreverses (1+ nreverses))))
486 (forward-line step)
487 (setq msg-num (mh-get-msg-num nil)))
488 msg-num)))
489
490 (defun mh-goto-msg (number &optional no-error-if-no-message dont-show)
491 "Position the cursor at message NUMBER.
492 Optional non-nil second argument means return nil instead of
493 signaling an error if message does not exist; in this case,
494 the cursor is positioned near where the message would have been.
495 Non-nil third argument means not to show the message."
496 (interactive "NGo to message: ")
497 (setq number (prefix-numeric-value number)) ;Emacs 19
498 ;; This basic routine tries to be as fast as possible,
499 ;; using a binary search and minimal regexps.
500 (let ((cur-msg (mh-find-msg-get-num -1))
501 (jump-size mh-msg-count))
502 (while (and (> jump-size 1)
503 cur-msg
504 (not (eq cur-msg number)))
505 (cond ((< cur-msg number)
506 (setq jump-size (min (- number cur-msg)
507 (ash (1+ jump-size) -1)))
508 (forward-line jump-size)
509 (setq cur-msg (mh-find-msg-get-num 1)))
510 (t
511 (setq jump-size (min (- cur-msg number)
512 (ash (1+ jump-size) -1)))
513 (forward-line (- jump-size))
514 (setq cur-msg (mh-find-msg-get-num -1)))))
515 (if (eq cur-msg number)
516 (progn
517 (beginning-of-line)
518 (or dont-show
519 (mh-maybe-show number)
520 t))
521 (if (not no-error-if-no-message)
522 (error "No message %d" number)))))
523
524
525 (defun mh-msg-search-pat (n)
526 ;; Return a search pattern for message N in the scan listing.
527 (format mh-msg-search-regexp n))
528
529
530 (defun mh-get-profile-field (field)
531 ;; Find and return the value of FIELD in the current buffer.
532 ;; Returns NIL if the field is not in the buffer.
533 (let ((case-fold-search t))
534 (goto-char (point-min))
535 (cond ((not (re-search-forward (format "^%s" field) nil t)) nil)
536 ((looking-at "[\t ]*$") nil)
537 (t
538 (re-search-forward "[\t ]*\\([^\t \n].*\\)$" nil t)
539 (let ((start (match-beginning 1)))
540 (end-of-line)
541 (buffer-substring start (point)))))))
542
543 (defvar mail-user-agent)
544 (defvar read-mail-command)
545
546 (defvar mh-find-path-run nil
547 "Non-nil if `mh-find-path' has been run already.")
548
549 (defun mh-find-path ()
550 ;; Set mh-progs, mh-lib, and mh-libs-progs
551 ;; (This step is necessary if MH was installed after this Emacs was dumped.)
552 ;; From profile file, set mh-user-path, mh-draft-folder,
553 ;; mh-unseen-seq, mh-previous-seq, mh-inbox.
554 (mh-find-progs)
555 (unless mh-find-path-run
556 (setq mh-find-path-run t)
557 (setq read-mail-command 'mh-rmail)
558 (setq mail-user-agent 'mh-e-user-agent))
559 (save-excursion
560 ;; Be sure profile is fully expanded before switching buffers
561 (let ((profile (expand-file-name (or (getenv "MH") "~/.mh_profile"))))
562 (set-buffer (get-buffer-create mh-temp-buffer))
563 (setq buffer-offer-save nil) ;for people who set default to t
564 (erase-buffer)
565 (condition-case err
566 (insert-file-contents profile)
567 (file-error
568 (mh-install profile err)))
569 (setq mh-user-path (mh-get-profile-field "Path:"))
570 (if (not mh-user-path)
571 (setq mh-user-path "Mail"))
572 (setq mh-user-path
573 (file-name-as-directory
574 (expand-file-name mh-user-path (expand-file-name "~"))))
575 (setq mh-draft-folder (mh-get-profile-field "Draft-Folder:"))
576 (if mh-draft-folder
577 (progn
578 (if (not (mh-folder-name-p mh-draft-folder))
579 (setq mh-draft-folder (format "+%s" mh-draft-folder)))
580 (if (not (file-exists-p (mh-expand-file-name mh-draft-folder)))
581 (error "Draft folder \"%s\" not found. Create it and try again"
582 (mh-expand-file-name mh-draft-folder)))))
583 (setq mh-inbox (mh-get-profile-field "Inbox:"))
584 (cond ((not mh-inbox)
585 (setq mh-inbox "+inbox"))
586 ((not (mh-folder-name-p mh-inbox))
587 (setq mh-inbox (format "+%s" mh-inbox))))
588 (setq mh-unseen-seq (mh-get-profile-field "Unseen-Sequence:"))
589 (if mh-unseen-seq
590 (setq mh-unseen-seq (intern mh-unseen-seq))
591 (setq mh-unseen-seq 'unseen)) ;old MH default?
592 (setq mh-previous-seq (mh-get-profile-field "Previous-Sequence:"))
593 (if mh-previous-seq
594 (setq mh-previous-seq (intern mh-previous-seq)))
595 (run-hooks 'mh-find-path-hook)))
596 (and mh-auto-folder-collect
597 (let ((mh-no-install t)) ;only get folders if MH installed
598 (condition-case err
599 (mh-make-folder-list-background)
600 (file-error))))) ;so don't complain if not installed
601
602 (defun mh-file-command-p (file)
603 "Return t if file FILE is the name of a executable regular file."
604 (and (file-regular-p file) (file-executable-p file)))
605
606 (defun mh-find-progs ()
607 "Find the `inc' and `mhl' programs of MH.
608 Set the `mh-progs' and `mh-lib', and `mh-lib-progs' variables to the
609 directory names."
610 (or (and mh-progs (mh-file-command-p (expand-file-name "inc" mh-progs)))
611 (setq mh-progs
612 (or (mh-path-search exec-path "inc")
613 (mh-path-search '("/usr/local/bin/mh/"
614 "/usr/local/mh/"
615 "/usr/bin/mh/" ;Ultrix 4.2
616 "/usr/new/mh/" ;Ultrix <4.2
617 "/usr/contrib/mh/bin/" ;BSDI
618 "/usr/pkg/bin/" ; NetBSD
619 "/usr/local/bin/"
620 )
621 "inc"))))
622 (or (null mh-progs)
623 (let ((mh-base mh-progs))
624 (while (let ((dir-name (file-name-nondirectory
625 (directory-file-name mh-base))))
626 (or (string= "mh" dir-name)
627 (string= "bin" dir-name)))
628 (setq mh-base
629 (file-name-directory (directory-file-name mh-base))))
630 (or (and mh-lib
631 (file-exists-p (expand-file-name "components" mh-lib)))
632 (setq mh-lib
633 ;; Look for a lib directory roughly parallel to the bin
634 ;; directory: Strip any trailing `mh' or `bin' path
635 ;; components, then look for lib/mh or mh/lib.
636 (or (mh-path-search
637 (mapcar (lambda (p) (expand-file-name p mh-base))
638 '("lib/mh" "etc/nmh" "/etc/nmh" "mh/lib" "etc" "lib"))
639 "components"
640 'file-exists-p))))
641 (or (and mh-lib-progs
642 (mh-file-command-p (expand-file-name "mhl" mh-lib-progs)))
643 (setq mh-lib-progs
644 (or (mh-path-search
645 (mapcar (lambda (p) (expand-file-name p mh-base))
646 '("lib/mh" "libexec/nmh" "lib/nmh" "mh/lib" "lib"))
647 "mhl")
648 (mh-path-search '("/usr/local/bin/mh/") "mhl")
649 (mh-path-search exec-path "mhl") ;unlikely
650 )))))
651 (unless (and mh-progs mh-lib mh-lib-progs)
652 (error "Cannot find the commands `inc' and `mhl' and the file `components'"))
653 (setq mh-nmh-p (not (null
654 (or (string-match "nmh" mh-lib-progs)
655 (string-match "nmh" mh-lib))))))
656
657 (defun mh-path-search (path file &optional func-p)
658 ;; Search PATH, a list of directory names, for FILE.
659 ;; Returns the element of PATH that contains FILE, or nil if not found.
660 (while (and path
661 (not (funcall (or func-p 'mh-file-command-p)
662 (expand-file-name file (car path)))))
663 (setq path (cdr path)))
664 (car path))
665
666 (defvar mh-no-install nil) ;do not run install-mh
667
668 (defun mh-install (profile error-val)
669 ;; Called to do error recovery if we fail to read the profile file.
670 ;; If possible, initialize the MH environment.
671 (if (or (getenv "MH")
672 (file-exists-p profile)
673 mh-no-install)
674 (signal (car error-val)
675 (list (format "Cannot read MH profile \"%s\"" profile)
676 (car (cdr (cdr error-val))))))
677 ;; The "install-mh" command will output a short note which
678 ;; mh-exec-cmd will display to the user.
679 ;; The MH 5 version of install-mh might try prompt the user
680 ;; for information, which would fail here.
681 (mh-exec-cmd (expand-file-name "install-mh" mh-lib-progs) "-auto")
682 ;; now try again to read the profile file
683 (erase-buffer)
684 (condition-case err
685 (insert-file-contents profile)
686 (file-error
687 (signal (car err) ;re-signal with more specific msg
688 (list (format "Cannot read MH profile \"%s\"" profile)
689 (car (cdr (cdr err))))))))
690
691
692 (defun mh-set-folder-modified-p (flag)
693 ;; Mark current folder as modified or unmodified according to FLAG.
694 (set-buffer-modified-p flag))
695
696
697 (defun mh-find-seq (name) (assoc name mh-seq-list))
698
699 (defun mh-seq-to-msgs (seq)
700 ;; Return a list of the messages in SEQUENCE.
701 (mh-seq-msgs (mh-find-seq seq)))
702
703
704 (defun mh-add-msgs-to-seq (msgs seq &optional internal-flag)
705 ;; Add MESSAGE(s) to the SEQUENCE. If optional FLAG is non-nil, do not mark
706 ;; the message in the scan listing or inform MH of the addition.
707 (let ((entry (mh-find-seq seq)))
708 (if (and msgs (atom msgs)) (setq msgs (list msgs)))
709 (if (null entry)
710 (setq mh-seq-list (cons (mh-make-seq seq msgs) mh-seq-list))
711 (if msgs (setcdr entry (append msgs (mh-seq-msgs entry)))))
712 (cond ((not internal-flag)
713 (mh-add-to-sequence seq msgs)
714 (mh-notate-seq seq mh-note-seq (1+ mh-cmd-note))))))
715
716 (autoload 'mh-add-to-sequence "mh-seq")
717 (autoload 'mh-notate-seq "mh-seq")
718 (autoload 'mh-read-seq-default "mh-seq")
719 (autoload 'mh-map-to-seq-msgs "mh-seq")
720
721
722 (defun mh-set-mode-name (mode-name-string)
723 ;; Set the mode-name and ensure that the mode line is updated.
724 (setq mode-name mode-name-string)
725 (force-mode-line-update t))
726
727 (defvar mh-folder-hist nil)
728
729 (defun mh-prompt-for-folder (prompt default can-create)
730 ;; Prompt for a folder name with PROMPT. Returns the folder's name as a
731 ;; string. DEFAULT is used if the folder exists and the user types return.
732 ;; If the CAN-CREATE flag is t, then a non-existent folder is made.
733 (if (null default)
734 (setq default ""))
735 (let* ((prompt (format "%s folder%s" prompt
736 (if (equal "" default)
737 "? "
738 (format " [%s]? " default))))
739 read-name folder-name)
740 (if (null mh-folder-list)
741 (mh-set-folder-list))
742 (while (and (setq read-name (completing-read prompt mh-folder-list nil nil
743 "+" 'mh-folder-hist default))
744 (equal read-name "")
745 (equal default "")))
746 (cond ((or (equal read-name "") (equal read-name "+"))
747 (setq read-name default))
748 ((not (mh-folder-name-p read-name))
749 (setq read-name (format "+%s" read-name))))
750 (setq folder-name read-name)
751 (cond ((and (> (length folder-name) 0)
752 (eq (aref folder-name (1- (length folder-name))) ?/))
753 (setq folder-name (substring folder-name 0 -1))))
754 (let ((new-file-p (not (file-exists-p (mh-expand-file-name folder-name)))))
755 (cond ((and new-file-p
756 (y-or-n-p
757 (format "Folder %s does not exist. Create it? " folder-name)))
758 (message "Creating %s" folder-name)
759 (call-process "mkdir" nil nil nil (mh-expand-file-name folder-name))
760 (message "Creating %s...done" folder-name)
761 (setq mh-folder-list (cons (list read-name) mh-folder-list))
762 (run-hooks 'mh-folder-list-change-hook))
763 (new-file-p
764 (error "Folder %s is not created" folder-name))
765 ((not (file-directory-p (mh-expand-file-name folder-name)))
766 (error "\"%s\" is not a directory"
767 (mh-expand-file-name folder-name)))
768 ((and (null (assoc read-name mh-folder-list))
769 (null (assoc (concat read-name "/") mh-folder-list)))
770 (setq mh-folder-list (cons (list read-name) mh-folder-list))
771 (run-hooks 'mh-folder-list-change-hook))))
772 folder-name))
773
774
775 (defvar mh-make-folder-list-process nil) ;The background process collecting the folder list.
776
777 (defvar mh-folder-list-temp nil) ;mh-folder-list as it is being built.
778
779 (defvar mh-folder-list-partial-line "") ;Start of last incomplete line from folder process.
780
781 (defun mh-set-folder-list ()
782 ;; Sets mh-folder-list correctly.
783 ;; A useful function for the command line or for when you need to
784 ;; sync by hand. Format is in a form suitable for completing read.
785 (message "Collecting folder names...")
786 (if (not mh-make-folder-list-process)
787 (mh-make-folder-list-background))
788 (while (eq (process-status mh-make-folder-list-process) 'run)
789 (accept-process-output mh-make-folder-list-process))
790 (setq mh-folder-list mh-folder-list-temp)
791 (run-hooks 'mh-folder-list-change-hook)
792 (setq mh-folder-list-temp nil)
793 (delete-process mh-make-folder-list-process)
794 (setq mh-make-folder-list-process nil)
795 (message "Collecting folder names...done"))
796
797 (defun mh-make-folder-list-background ()
798 ;; Start a background process to compute a list of the user's folders.
799 ;; Call mh-set-folder-list to wait for the result.
800 (cond
801 ((not mh-make-folder-list-process)
802 (unless mh-inbox
803 (mh-find-path))
804 (let ((process-connection-type nil))
805 (setq mh-make-folder-list-process
806 (start-process "folders" nil (expand-file-name "folders" mh-progs)
807 "-fast"
808 (if mh-recursive-folders
809 "-recurse"
810 "-norecurse")))
811 (set-process-filter mh-make-folder-list-process
812 'mh-make-folder-list-filter)
813 (process-kill-without-query mh-make-folder-list-process)))))
814
815 (defun mh-make-folder-list-filter (process output)
816 ;; parse output from "folders -fast"
817 (let ((position 0)
818 line-end
819 new-folder
820 (prevailing-match-data (match-data)))
821 (unwind-protect
822 ;; make sure got complete line
823 (while (setq line-end (string-match "\n" output position))
824 (setq new-folder (format "+%s%s"
825 mh-folder-list-partial-line
826 (substring output position line-end)))
827 (setq mh-folder-list-partial-line "")
828 ;; is new folder a subfolder of previous?
829 (if (and mh-folder-list-temp
830 (string-match
831 (regexp-quote
832 (concat (car (car mh-folder-list-temp)) "/"))
833 new-folder))
834 ;; append slash to parent folder for better completion
835 ;; (undone by mh-prompt-for-folder)
836 (setq mh-folder-list-temp
837 (cons
838 (list new-folder)
839 (cons
840 (list (concat (car (car mh-folder-list-temp)) "/"))
841 (cdr mh-folder-list-temp))))
842 (setq mh-folder-list-temp
843 (cons (list new-folder)
844 mh-folder-list-temp)))
845 (setq position (1+ line-end)))
846 (set-match-data prevailing-match-data))
847 (setq mh-folder-list-partial-line (substring output position))))
848
849
850 (defun mh-folder-name-p (name)
851 ;; Return non-NIL if NAME is possibly the name of a folder.
852 ;; A name (a string or symbol) can be a folder name if it begins with "+".
853 (if (symbolp name)
854 (eq (aref (symbol-name name) 0) ?+)
855 (and (> (length name) 0)
856 (eq (aref name 0) ?+))))
857
858
859 ;;; Issue commands to MH.
860
861
862 (defun mh-exec-cmd (command &rest args)
863 ;; Execute mh-command COMMAND with ARGS.
864 ;; The side effects are what is desired.
865 ;; Any output is assumed to be an error and is shown to the user.
866 ;; The output is not read or parsed by mh-e.
867 (save-excursion
868 (set-buffer (get-buffer-create mh-temp-buffer))
869 (erase-buffer)
870 (apply 'call-process
871 (expand-file-name command mh-progs) nil t nil
872 (mh-list-to-string args))
873 (if (> (buffer-size) 0)
874 (save-window-excursion
875 (switch-to-buffer-other-window mh-temp-buffer)
876 (sit-for 5)))))
877
878
879 (defun mh-exec-cmd-error (env command &rest args)
880 ;; In environment ENV, execute mh-command COMMAND with args ARGS.
881 ;; ENV is nil or a string of space-separated "var=value" elements.
882 ;; Signals an error if process does not complete successfully.
883 (save-excursion
884 (set-buffer (get-buffer-create mh-temp-buffer))
885 (erase-buffer)
886 (let ((status
887 (if env
888 ;; the shell hacks necessary here shows just how broken Unix is
889 (apply 'call-process "/bin/sh" nil t nil "-c"
890 (format "%s %s ${1+\"$@\"}"
891 env
892 (expand-file-name command mh-progs))
893 command
894 (mh-list-to-string args))
895 (apply 'call-process
896 (expand-file-name command mh-progs) nil t nil
897 (mh-list-to-string args)))))
898 (mh-handle-process-error command status))))
899
900
901 (defun mh-exec-cmd-daemon (command &rest args)
902 ;; Execute MH command COMMAND with ARGS in the background.
903 ;; Any output from command is displayed in an asynchronous pop-up window.
904 (save-excursion
905 (set-buffer (get-buffer-create mh-temp-buffer))
906 (erase-buffer))
907 (let* ((process-connection-type nil)
908 (process (apply 'start-process
909 command nil
910 (expand-file-name command mh-progs)
911 (mh-list-to-string args))))
912 (set-process-filter process 'mh-process-daemon)))
913
914 (defun mh-process-daemon (process output)
915 ;; Process daemon that puts output into a temporary buffer.
916 (set-buffer (get-buffer-create mh-temp-buffer))
917 (insert-before-markers output)
918 (display-buffer mh-temp-buffer))
919
920
921 (defun mh-exec-cmd-quiet (raise-error command &rest args)
922 ;; Args are RAISE-ERROR, COMMANDS, ARGS....
923 ;; Execute MH command COMMAND with ARGS. ARGS is a list of strings.
924 ;; Return at start of mh-temp buffer, where output can be parsed and used.
925 ;; Returns value of call-process, which is 0 for success,
926 ;; unless RAISE-ERROR is non-nil, in which case an error is signaled
927 ;; if call-process returns non-0.
928 (set-buffer (get-buffer-create mh-temp-buffer))
929 (erase-buffer)
930 (let ((value
931 (apply 'call-process
932 (expand-file-name command mh-progs) nil t nil
933 args)))
934 (goto-char (point-min))
935 (if raise-error
936 (mh-handle-process-error command value)
937 value)))
938
939
940 (defun mh-exec-cmd-output (command display &rest args)
941 ;; Execute MH command COMMAND with DISPLAY flag and ARGS.
942 ;; Put the output into buffer after point. Set mark after inserted text.
943 ;; Output is expected to be shown to user, not parsed by mh-e.
944 (push-mark (point) t)
945 (apply 'call-process
946 (expand-file-name command mh-progs) nil t display
947 (mh-list-to-string args))
948 (exchange-point-and-mark))
949
950
951 (defun mh-exec-lib-cmd-output (command &rest args)
952 ;; Execute MH library command COMMAND with ARGS.
953 ;; Put the output into buffer after point. Set mark after inserted text.
954 (apply 'mh-exec-cmd-output (expand-file-name command mh-lib-progs) nil args))
955
956
957 (defun mh-handle-process-error (command status)
958 ;; Raise error if COMMAND returned non-0 STATUS, otherwise return STATUS.
959 ;; STATUS is return value from call-process.
960 ;; Program output is in current buffer.
961 ;; If output is too long to include in error message, display the buffer.
962 (cond ((eq status 0) ;success
963 status)
964 ((stringp status) ;kill string
965 (error "%s: %s" command status))
966 (t ;exit code
967 (cond
968 ((= (buffer-size) 0) ;program produced no error message
969 (error "%s: exit code %d" command status))
970 (t
971 ;; will error message fit on one line?
972 (goto-line 2)
973 (if (and (< (buffer-size) (screen-width))
974 (eobp))
975 (error "%s"
976 (buffer-substring 1 (progn (goto-char 1)
977 (end-of-line)
978 (point))))
979 (display-buffer (current-buffer))
980 (error "%s failed with status %d. See error message in other window"
981 command status)))))))
982
983
984 (defun mh-expand-file-name (filename &optional default)
985 ;; Just like `expand-file-name', but also handles MH folder names.
986 ;; Assumes that any filename that starts with '+' is a folder name.
987 (if (mh-folder-name-p filename)
988 (expand-file-name (substring filename 1) mh-user-path)
989 (expand-file-name filename default)))
990
991
992 (defun mh-list-to-string (l)
993 ;; Flattens the list L and makes every element of the new list into a string.
994 (nreverse (mh-list-to-string-1 l)))
995
996 (defun mh-list-to-string-1 (l)
997 (let ((new-list nil))
998 (while l
999 (cond ((null (car l)))
1000 ((symbolp (car l))
1001 (setq new-list (cons (symbol-name (car l)) new-list)))
1002 ((numberp (car l))
1003 (setq new-list (cons (int-to-string (car l)) new-list)))
1004 ((equal (car l) ""))
1005 ((stringp (car l)) (setq new-list (cons (car l) new-list)))
1006 ((listp (car l))
1007 (setq new-list (nconc (mh-list-to-string-1 (car l))
1008 new-list)))
1009 (t (error "Bad element in mh-list-to-string: %s" (car l))))
1010 (setq l (cdr l)))
1011 new-list))
1012
1013 (provide 'mh-utils)
1014
1015 ;;; mh-utils.el ends here