* lisp/mail/emacsbug.el (report-emacs-bug): Try "sw_vers" on Darwin.
[emacs.git] / lisp / mh-e / mh-utils.el
blob7cb52ffa9ef95a13804ccc20a04350cc8cc35720
1 ;;; mh-utils.el --- MH-E general utilities
3 ;; Copyright (C) 1993, 1995, 1997, 2000-2017 Free Software Foundation,
4 ;; Inc.
6 ;; Author: Bill Wohler <wohler@newt.com>
7 ;; Maintainer: Bill Wohler <wohler@newt.com>
8 ;; Keywords: mail
9 ;; See: mh-e.el
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;;; Change Log:
30 ;;; Code:
32 (require 'mh-e)
33 (mh-require-cl)
35 (require 'font-lock)
37 ;;; CL Replacements
39 ;;;###mh-autoload
40 (defun mh-search-from-end (char string)
41 "Return the position of last occurrence of CHAR in STRING.
42 If CHAR is not present in STRING then return nil. The function is
43 used in lieu of `search' in the CL package."
44 (loop for index from (1- (length string)) downto 0
45 when (equal (aref string index) char) return index
46 finally return nil))
50 ;;; General Utilities
52 ;;;###mh-autoload
53 (defun mh-beginning-of-word (&optional n)
54 "Return position of the N th word backwards."
55 (unless n (setq n 1))
56 (let ((syntax-table (syntax-table)))
57 (unwind-protect
58 (save-excursion
59 (mh-mail-abbrev-make-syntax-table)
60 (set-syntax-table mail-abbrev-syntax-table)
61 (backward-word n)
62 (point))
63 (set-syntax-table syntax-table))))
65 ;;;###mh-autoload
66 (defun mh-colors-available-p ()
67 "Check if colors are available in the Emacs being used."
68 (or (featurep 'xemacs)
69 (let ((color-cells (mh-display-color-cells)))
70 (and (numberp color-cells) (>= color-cells 8)))))
72 ;;;###mh-autoload
73 (defun mh-colors-in-use-p ()
74 "Check if colors are being used in the folder buffer."
75 (and mh-colors-available-flag font-lock-mode))
77 ;;;###mh-autoload
78 (defun mh-delete-line (lines)
79 "Delete the next LINES lines."
80 (delete-region (point) (progn (forward-line lines) (point))))
82 ;;;###mh-autoload
83 (defun mh-make-local-vars (&rest pairs)
84 "Initialize local variables according to the variable-value PAIRS."
85 (while pairs
86 (set (make-local-variable (car pairs)) (car (cdr pairs)))
87 (setq pairs (cdr (cdr pairs)))))
89 ;;;###mh-autoload
90 (defun mh-mapc (function list)
91 "Apply FUNCTION to each element of LIST for side effects only."
92 (while list
93 (funcall function (car list))
94 (setq list (cdr list))))
96 (defvar mh-pick-regexp-chars ".*$["
97 "List of special characters in pick regular expressions.")
99 ;;;###mh-autoload
100 (defun mh-quote-pick-expr (pick-expr)
101 "Quote `mh-pick-regexp-chars' in PICK-EXPR.
102 PICK-EXPR is a list of strings. Return nil if PICK-EXPR is nil."
103 (let ((quoted-pick-expr))
104 (dolist (string pick-expr)
105 (when (and string
106 (not (string-equal string "")))
107 (loop for i from 0 to (1- (length mh-pick-regexp-chars)) do
108 (let ((s (string ?\\ (aref mh-pick-regexp-chars i))))
109 (setq string (mh-replace-regexp-in-string s s string t t))))
110 (setq quoted-pick-expr (append quoted-pick-expr (list string)))))
111 quoted-pick-expr))
113 ;;;###mh-autoload
114 (defun mh-replace-string (old new)
115 "Replace all occurrences of OLD with NEW in the current buffer.
116 Ignores case when searching for OLD."
117 (goto-char (point-min))
118 (let ((case-fold-search t))
119 (while (search-forward old nil t)
120 (replace-match new t t))))
124 ;;; Logo Display
126 (defvar mh-logo-cache nil)
128 ;; Shush compiler.
129 (defvar image-load-path)
131 ;;;###mh-autoload
132 (defun mh-logo-display ()
133 "Modify mode line to display MH-E logo."
134 (mh-do-in-gnu-emacs
135 (let* ((load-path (mh-image-load-path-for-library "mh-e" "mh-logo.xpm"))
136 (image-load-path (cons (car load-path)
137 (when (boundp 'image-load-path)
138 image-load-path))))
139 (add-text-properties
141 `(display ,(or mh-logo-cache
142 (setq mh-logo-cache
143 (mh-funcall-if-exists
144 find-image '((:type xpm :ascent center
145 :file "mh-logo.xpm"))))))
146 (car mode-line-buffer-identification))))
147 (mh-do-in-xemacs
148 (setq modeline-buffer-identification
149 (list
150 (if mh-modeline-glyph
151 (cons modeline-buffer-id-left-extent mh-modeline-glyph)
152 (cons modeline-buffer-id-left-extent "XEmacs%N:"))
153 (cons modeline-buffer-id-right-extent " %17b")))))
157 ;;; Read MH Profile
159 (defvar mh-find-path-run nil
160 "Non-nil if `mh-find-path' has been run already.
161 Do not access this variable; `mh-find-path' already uses it to
162 avoid running more than once.")
164 ;;;###mh-autoload
165 (defun mh-find-path ()
166 "Set variables from user's MH profile.
168 This function sets `mh-user-path' from your \"Path:\" MH profile
169 component (but defaults to \"Mail\" if one isn't present),
170 `mh-draft-folder' from \"Draft-Folder:\", `mh-unseen-seq' from
171 \"Unseen-Sequence:\", `mh-previous-seq' from
172 \"Previous-Sequence:\", and `mh-inbox' from \"Inbox:\" (defaults
173 to \"+inbox\").
175 The hook `mh-find-path-hook' is run after these variables have
176 been set. This hook can be used the change the value of these
177 variables if you need to run with different values between MH and
178 MH-E."
179 (unless mh-find-path-run
180 ;; Sanity checks.
181 (if (and (getenv "MH")
182 (not (file-readable-p (getenv "MH"))))
183 (error "MH environment variable contains unreadable file %s"
184 (getenv "MH")))
185 (if (null (mh-variants))
186 (error "Install MH and run install-mh before running MH-E"))
187 (if (not (or (getenv "MH") (file-readable-p "~/.mh_profile")))
188 (error "Run install-mh before running MH-E"))
189 ;; Read MH profile.
190 (setq mh-user-path (mh-profile-component "Path"))
191 (if (not mh-user-path)
192 (setq mh-user-path "Mail"))
193 (setq mh-user-path
194 (file-name-as-directory
195 (expand-file-name mh-user-path (expand-file-name "~"))))
196 (mh-set-x-image-cache-directory (expand-file-name ".mhe-x-image-cache"
197 mh-user-path))
198 (setq mh-draft-folder (mh-profile-component "Draft-Folder"))
199 (if mh-draft-folder
200 (progn
201 (if (not (mh-folder-name-p mh-draft-folder))
202 (setq mh-draft-folder (format "+%s" mh-draft-folder)))
203 (if (not (file-exists-p (mh-expand-file-name mh-draft-folder)))
204 (error
205 "Draft folder \"%s\" not found; create it and try again"
206 (mh-expand-file-name mh-draft-folder)))))
207 (setq mh-inbox (mh-profile-component "Inbox"))
208 (cond ((not mh-inbox)
209 (setq mh-inbox "+inbox"))
210 ((not (mh-folder-name-p mh-inbox))
211 (setq mh-inbox (format "+%s" mh-inbox))))
212 (setq mh-unseen-seq (mh-profile-component "Unseen-Sequence"))
213 (if mh-unseen-seq
214 (setq mh-unseen-seq (intern mh-unseen-seq))
215 (setq mh-unseen-seq 'unseen)) ;old MH default?
216 (setq mh-previous-seq (mh-profile-component "Previous-Sequence"))
217 (if mh-previous-seq
218 (setq mh-previous-seq (intern mh-previous-seq)))
219 (run-hooks 'mh-find-path-hook)
220 (mh-collect-folder-names)
221 (setq mh-find-path-run t)))
225 ;;; Help Functions
227 ;;;###mh-autoload
228 (defun mh-ephem-message (string)
229 "Display STRING in the minibuffer momentarily."
230 (message "%s" string)
231 (sit-for 5)
232 (message ""))
234 (defvar mh-help-default nil
235 "Mode to use if messages are not present for the current mode.")
237 (defvar mh-help-messages nil
238 "Help messages for all modes.
239 This is an alist of alists. The primary key is a symbol
240 representing the mode; the value is described in `mh-set-help'.")
242 ;;;###mh-autoload
243 (defun mh-set-help (messages &optional default)
244 "Set help messages.
246 The MESSAGES are assumed to be an associative array. It is used
247 to show help for the most common commands in the current mode.
248 The key is a prefix char. The value is one or more strings which
249 are concatenated together and displayed in a help buffer if ? is
250 pressed after the prefix character. The special key nil is used
251 to display the non-prefixed commands.
253 The substitutions described in `substitute-command-keys' are performed as
254 well.
256 If optional argument DEFAULT is non-nil, then these messages will
257 be used if help is asked for an unknown mode."
258 (add-to-list 'mh-help-messages (cons major-mode messages))
259 (if default
260 (setq mh-help-default major-mode)))
262 ;;;###mh-autoload
263 (defun mh-help (&optional help-messages)
264 "Display cheat sheet for the MH-E commands.
265 See `mh-set-help' for setting the help messages.
266 HELP-MESSAGES are used instead if given.
267 This is a list of one or more strings which are concatenated together
268 and displayed in a help buffer."
269 (interactive)
270 (let* ((help (or help-messages
271 (cdr (assoc nil (assoc major-mode mh-help-messages)))))
272 (text (substitute-command-keys (mapconcat 'identity help ""))))
273 (with-electric-help
274 (function
275 (lambda ()
276 (insert text)))
277 mh-help-buffer)))
279 ;;;###mh-autoload
280 (defun mh-prefix-help ()
281 "Display cheat sheet for the commands of the current prefix in minibuffer."
282 (interactive)
283 ;; We got here because the user pressed a "?", but he pressed a prefix key
284 ;; before that. Since the key vector starts at index 0, the index of the
285 ;; last keystroke is length-1 and thus the second to last keystroke is at
286 ;; length-2. We use that information to obtain a suitable prefix character
287 ;; from the recent keys.
288 (let* ((keys (recent-keys))
289 (prefix-char (elt keys (- (length keys) 2)))
290 (help (cdr (assoc prefix-char (assoc major-mode mh-help-messages)))))
291 (mh-help help)))
295 ;;; Message Number Utilities
297 ;;;###mh-autoload
298 (defun mh-coalesce-msg-list (messages)
299 "Given a list of MESSAGES, return a list of message number ranges.
300 This is the inverse of `mh-read-msg-list', which expands ranges.
301 Message lists passed to MH programs should be processed by this
302 function to avoid exceeding system command line argument limits."
303 (let ((msgs (sort (copy-sequence messages) 'mh-greaterp))
304 (range-high nil)
305 (prev -1)
306 (ranges nil))
307 (while prev
308 (if range-high
309 (if (or (not (numberp prev))
310 (not (equal (car msgs) (1- prev))))
311 (progn ;non-sequential, flush old range
312 (if (eq prev range-high)
313 (setq ranges (cons range-high ranges))
314 (setq ranges (cons (format "%s-%s" prev range-high) ranges)))
315 (setq range-high nil))))
316 (or range-high
317 (setq range-high (car msgs))) ;start new or first range
318 (setq prev (car msgs))
319 (setq msgs (cdr msgs)))
320 ranges))
322 (defun mh-greaterp (msg1 msg2)
323 "Return the greater of two message indicators MSG1 and MSG2.
324 Strings are \"smaller\" than numbers.
325 Valid values are things like \"cur\", \"last\", 1, and 1820."
326 (if (numberp msg1)
327 (if (numberp msg2)
328 (> msg1 msg2)
330 (if (numberp msg2)
332 (string-lessp msg2 msg1))))
334 ;;;###mh-autoload
335 (defun mh-lessp (msg1 msg2)
336 "Return the lesser of two message indicators MSG1 and MSG2.
337 Strings are \"smaller\" than numbers.
338 Valid values are things like \"cur\", \"last\", 1, and 1820."
339 (not (mh-greaterp msg1 msg2)))
341 ;;;###mh-autoload
342 (defun mh-get-msg-num (error-if-no-message)
343 "Return the message number of the displayed message.
344 If the argument ERROR-IF-NO-MESSAGE is non-nil, then complain if
345 the cursor is not pointing to a message."
346 (save-excursion
347 (beginning-of-line)
348 (cond ((looking-at (mh-scan-msg-number-regexp))
349 (string-to-number (buffer-substring (match-beginning 1)
350 (match-end 1))))
351 (error-if-no-message
352 (user-error "Cursor not pointing to message"))
353 (t nil))))
357 ;;; Folder Cache and Access
359 (defvar mh-sub-folders-cache (make-hash-table :test #'equal))
360 (defvar mh-current-folder-name nil)
361 (defvar mh-flists-partial-line "")
362 (defvar mh-flists-process nil)
364 ;;;###mh-autoload
365 (defun mh-clear-sub-folders-cache ()
366 "Clear `mh-sub-folders-cache'."
367 (clrhash mh-sub-folders-cache))
369 ;; Initialize mh-sub-folders-cache...
370 (defun mh-collect-folder-names ()
371 "Collect folder names by running \"folders\"."
372 (unless mh-flists-process
373 (setq mh-flists-process
374 (mh-exec-cmd-daemon "folders" 'mh-collect-folder-names-filter
375 "-recurse" "-fast"))))
377 (defun mh-collect-folder-names-filter (process output)
378 "Read folder names.
379 PROCESS is the flists process that was run to collect folder
380 names and the function is called when OUTPUT is available."
381 (let ((position 0)
382 (prevailing-match-data (match-data))
383 line-end folder)
384 (unwind-protect
385 (while (setq line-end (string-match "\n" output position))
386 (setq folder (format "+%s%s"
387 mh-flists-partial-line
388 (substring output position line-end)))
389 (setq mh-flists-partial-line "")
390 (unless (equal (aref folder 1) ?.)
391 (mh-populate-sub-folders-cache folder))
392 (setq position (1+ line-end)))
393 (set-match-data prevailing-match-data))
394 (setq mh-flists-partial-line (substring output position))))
396 (defun mh-populate-sub-folders-cache (folder)
397 "Tell `mh-sub-folders-cache' about FOLDER."
398 (let* ((last-slash (mh-search-from-end ?/ folder))
399 (child1 (substring folder (1+ (or last-slash 0))))
400 (parent (and last-slash (substring folder 0 last-slash)))
401 (parent-slash (and parent (mh-search-from-end ?/ parent)))
402 (child2 (and parent (substring parent (1+ (or parent-slash 0)))))
403 (grand-parent (and parent-slash (substring parent 0 parent-slash)))
404 (cache-entry (gethash parent mh-sub-folders-cache)))
405 (unless (loop for x in cache-entry when (equal (car x) child1) return t
406 finally return nil)
407 (push (list child1) cache-entry)
408 (setf (gethash parent mh-sub-folders-cache)
409 (sort cache-entry (lambda (x y) (string< (car x) (car y)))))
410 (when parent
411 (loop for x in (gethash grand-parent mh-sub-folders-cache)
412 when (equal (car x) child2)
413 do (progn (setf (cdr x) t) (return)))))))
415 (defun mh-normalize-folder-name (folder &optional empty-string-okay
416 dont-remove-trailing-slash
417 return-nil-if-folder-empty)
418 "Normalizes FOLDER name.
420 Makes sure that two `/' characters never occur next to each
421 other. Also all occurrences of `..' and `.' are suitably
422 processed. So \"+inbox/../news\" will be normalized to \"+news\".
424 If optional argument EMPTY-STRING-OKAY is nil then a `+' is added
425 at the front if FOLDER lacks one. If non-nil and FOLDER is the
426 empty string then nothing is added.
428 If optional argument DONT-REMOVE-TRAILING-SLASH is non-nil then a
429 trailing `/' if present is retained (if present), otherwise it is
430 removed.
432 If optional argument RETURN-NIL-IF-FOLDER-EMPTY is non-nil, then
433 return nil if FOLDER is \"\" or \"+\". This is useful when
434 normalizing the folder for the `folders' command which displays
435 the directories in / if passed \"+\". This is usually not
436 desired. If this argument is non-nil, then EMPTY-STRING-OKAY has
437 no effect."
438 (cond
439 ((if (and (or (equal folder "+") (equal folder ""))
440 return-nil-if-folder-empty)
441 (setq folder nil)))
442 ((stringp folder)
443 ;; Replace two or more consecutive '/' characters with a single '/'
444 (while (string-match "//" folder)
445 (setq folder (replace-match "/" nil t folder)))
446 (let* ((length (length folder))
447 (trailing-slash-present (and (> length 0)
448 (equal (aref folder (1- length)) ?/)))
449 (leading-slash-present (and (> length 0)
450 (equal (aref folder 0) ?/))))
451 (when (and (> length 0) (equal (aref folder 0) ?@)
452 (stringp mh-current-folder-name))
453 (setq folder (format "%s/%s/" mh-current-folder-name
454 (substring folder 1))))
455 ;; XXX: Purge empty strings from the list that split-string
456 ;; returns. In XEmacs, (split-string "+foo/" "/") returns
457 ;; ("+foo" "") while in GNU Emacs it returns ("+foo"). In the
458 ;; code it is assumed that the components list has no empty
459 ;; strings.
460 (let ((components (delete "" (split-string folder "/")))
461 (result ()))
462 ;; Remove .. and . from the pathname.
463 (dolist (component components)
464 (cond ((and (equal component "..") result)
465 (pop result))
466 ((equal component ".."))
467 ((equal component "."))
468 (t (push component result))))
469 (setq folder "")
470 (dolist (component result)
471 (setq folder (concat component "/" folder)))
472 ;; Remove trailing '/' if needed.
473 (unless (and trailing-slash-present dont-remove-trailing-slash)
474 (when (not (equal folder ""))
475 (setq folder (substring folder 0 (1- (length folder))))))
476 (when leading-slash-present
477 (setq folder (concat "/" folder)))))
478 (cond ((and empty-string-okay (equal folder "")))
479 ((equal folder "")
480 (setq folder "+"))
481 ((not (equal (aref folder 0) ?+))
482 (setq folder (concat "+" folder))))))
483 folder)
485 (defmacro mh-children-p (folder)
486 "Return t if FOLDER from sub-folders cache has children."
487 ;; The car of folder is the name, and the cdr is either t or some
488 ;; sort of count that I do not understand. It's too small to be the
489 ;; number of messages in the sub-folders and too large to be the
490 ;; number of sub-folders. XXX
491 `(if (cdr ,folder)
493 nil))
495 ;;;###mh-autoload
496 (defun mh-folder-list (folder)
497 "Return FOLDER and its descendants.
498 FOLDER may have a + prefix. Returns a list of strings without the
499 + prefix. If FOLDER is nil, then all folders are considered. For
500 example, if your Mail directory only contains the folders +inbox,
501 +outbox, +lists, and +lists/mh-e, then
503 (mh-folder-list nil)
504 => (\"inbox\" \"lists\" \"lists/mh-e\" \"outbox\")
505 (mh-folder-list \"+lists\")
506 => (\"lists\" \"lists/mh-e\")
508 Respects the value of `mh-recursive-folders-flag'. If this flag
509 is nil, and the sub-folders have not been explicitly viewed, then
510 they will not be returned."
511 (let ((folder-list))
512 ;; Normalize folder. Strip leading + and trailing slash(es). If no
513 ;; folder is specified, ensure it is nil to avoid adding the
514 ;; folder to the folder-list and adding a slash to it.
515 (when folder
516 (setq folder (mh-replace-regexp-in-string "^\\+" "" folder))
517 (setq folder (mh-replace-regexp-in-string "/+$" "" folder))
518 (if (equal folder "")
519 (setq folder nil)))
520 ;; Add provided folder to list, unless all folders are asked for.
521 ;; Then append slash to separate sub-folders.
522 (unless (null folder)
523 (setq folder-list (list folder))
524 (setq folder (concat folder "/")))
525 (loop for f in (mh-sub-folders folder) do
526 (setq folder-list
527 (append folder-list
528 (if (mh-children-p f)
529 (mh-folder-list (concat folder (car f)))
530 (list (concat folder (car f)))))))
531 folder-list))
533 ;;;###mh-autoload
534 (defun mh-sub-folders (folder &optional add-trailing-slash-flag)
535 "Find the subfolders of FOLDER.
536 The function avoids running folders unnecessarily by caching the
537 results of the actual folders call.
539 If optional argument ADD-TRAILING-SLASH-FLAG is non-nil then a
540 slash is added to each of the sub-folder names that may have
541 nested folders within them."
542 (let* ((folder (mh-normalize-folder-name folder nil nil t))
543 (match (gethash folder mh-sub-folders-cache 'no-result))
544 (sub-folders (cond ((eq match 'no-result)
545 (setf (gethash folder mh-sub-folders-cache)
546 (mh-sub-folders-actual folder)))
547 (t match))))
548 (if add-trailing-slash-flag
549 (mapcar #'(lambda (x)
550 (if (cdr x) (cons (concat (car x) "/") (cdr x)) x))
551 sub-folders)
552 sub-folders)))
554 ;; FIXME: This function does not do well if FOLDER does not exist. It
555 ;; then changes the context to that folder which causes problems down
556 ;; the line. Since a folder in the cache could later be deleted, it
557 ;; would be good for mh-sub-folders-actual to return nil in this case
558 ;; so that mh-sub-folders could delete it from the cache. This
559 ;; function could protect itself by using a temporary context.
560 (defun mh-sub-folders-actual (folder)
561 "Execute the command folders to return the sub-folders of FOLDER.
562 Filters out the folder names that start with \".\" so that
563 directories that aren't usually mail folders are hidden.
564 Expects FOLDER to have already been normalized with
565 (mh-normalize-folder-name folder nil nil t)"
566 (let ((arg-list `(,(expand-file-name "folders" mh-progs)
567 nil (t nil) nil "-noheader" "-norecurse" "-nototal"
568 ,@(if (stringp folder) (list folder) ())))
569 (results ())
570 (current-folder (concat
571 (with-temp-buffer
572 (call-process (expand-file-name "folder" mh-progs)
573 nil '(t nil) nil "-fast")
574 (buffer-substring (point-min) (1- (point-max))))
575 "+")))
576 (with-temp-buffer
577 (apply #'call-process arg-list)
578 (goto-char (point-min))
579 (while (not (and (eolp) (bolp)))
580 (goto-char (mh-line-end-position))
581 (let ((start-pos (mh-line-beginning-position))
582 (has-pos (search-backward " has "
583 (mh-line-beginning-position) t)))
584 (when (integerp has-pos)
585 (while (equal (char-after has-pos) ? )
586 (decf has-pos))
587 (incf has-pos)
588 (while (equal (char-after start-pos) ? )
589 (incf start-pos))
590 (let* ((name (buffer-substring start-pos has-pos))
591 (first-char (aref name 0))
592 (last-char (aref name (1- (length name)))))
593 (unless (member first-char '(?. ?# ?,))
594 (when (and (equal last-char ?+) (equal name current-folder))
595 (setq name (substring name 0 (1- (length name)))))
596 (push
597 (cons name
598 (search-forward "(others)" (mh-line-end-position) t))
599 results))))
600 (forward-line 1))))
601 (setq results (nreverse results))
602 (when (stringp folder)
603 (setq results (cdr results))
604 (let ((folder-name-len (length (format "%s/" (substring folder 1)))))
605 (setq results (mapcar (lambda (f)
606 (cons (substring (car f) folder-name-len)
607 (cdr f)))
608 results))))
609 results))
611 ;;;###mh-autoload
612 (defun mh-remove-from-sub-folders-cache (folder)
613 "Remove FOLDER and its parent from `mh-sub-folders-cache'.
614 FOLDER should be unconditionally removed from the cache. Also the
615 last ancestor of FOLDER present in the cache must be removed as
616 well.
618 To see why this is needed assume we have a folder +foo which has
619 a single sub-folder qux. Now we create the folder +foo/bar/baz.
620 Here we will need to invalidate the cached sub-folders of +foo,
621 otherwise completion on +foo won't tell us about the option
622 +foo/bar!"
623 (remhash folder mh-sub-folders-cache)
624 (block ancestor-found
625 (let ((parent folder)
626 (one-ancestor-found nil)
627 last-slash)
628 (while (setq last-slash (mh-search-from-end ?/ parent))
629 (setq parent (substring parent 0 last-slash))
630 (unless (eq (gethash parent mh-sub-folders-cache 'none) 'none)
631 (remhash parent mh-sub-folders-cache)
632 (if one-ancestor-found
633 (return-from ancestor-found)
634 (setq one-ancestor-found t))))
635 (remhash nil mh-sub-folders-cache))))
639 ;;; Folder Utilities
641 ;;;###mh-autoload
642 (defun mh-folder-name-p (name)
643 "Return non-nil if NAME is the name of a folder.
644 A name (a string or symbol) can be a folder name if it begins
645 with \"+\"."
646 (if (symbolp name)
647 (eq (aref (symbol-name name) 0) ?+)
648 (and (> (length name) 0)
649 (eq (aref name 0) ?+))))
651 ;;;###mh-autoload
652 (defun mh-expand-file-name (filename &optional default)
653 "Expand FILENAME like `expand-file-name', but also handle MH folder names.
654 Any filename that starts with `+' is treated as a folder name.
655 See `expand-file-name' for description of DEFAULT."
656 (if (mh-folder-name-p filename)
657 (expand-file-name (substring filename 1) mh-user-path)
658 (expand-file-name filename default)))
660 (defvar mh-folder-hist nil)
662 ;; Shush compiler.
663 (defvar mh-speed-flists-cache)
665 (defvar mh-allow-root-folder-flag nil
666 "Non-nil means \"+\" is an acceptable folder name.
667 This variable is used to communicate with
668 `mh-folder-completion-function'. That function can have exactly
669 three arguments so we bind this variable to t or nil.
671 This variable should never be set.")
673 (defvar mh-folder-completion-map (copy-keymap minibuffer-local-completion-map))
674 (define-key mh-folder-completion-map " " 'minibuffer-complete) ;Why???
676 (defvar mh-speed-flists-inhibit-flag nil)
678 ;;;###mh-autoload
679 (defun mh-speed-flists-active-p ()
680 "Check if speedbar is running with message counts enabled."
681 (and (featurep 'mh-speed)
682 (not mh-speed-flists-inhibit-flag)
683 (> (hash-table-count mh-speed-flists-cache) 0)))
685 ;;;###mh-autoload
686 (defun mh-folder-completion-function (name predicate flag)
687 "Programmable completion for folder names.
688 NAME is the partial folder name that has been input. PREDICATE if
689 non-nil is a function that is used to filter the possible
690 choices. FLAG is nil to indicate `try-completion', t for
691 `all-completions', or the symbol lambda for `test-completion'.
692 See Info node `(elisp) Programmed Completion' for details."
693 (let* ((orig-name name)
694 ;; After normalization, name is nil, +, or +something. If a
695 ;; trailing slash is present, it is preserved.
696 (name (mh-normalize-folder-name name nil t))
697 (last-slash (mh-search-from-end ?/ name))
698 ;; nil if + or +folder; +folder/ if slash present.
699 (last-complete (if last-slash (substring name 0 (1+ last-slash)) nil))
700 ;; Either +folder/remainder, +remainder, or "".
701 (remainder (cond (last-complete (substring name (1+ last-slash)))
702 (name (substring name 1))
703 (t ""))))
704 (cond ((eq (car-safe flag) 'boundaries)
705 (list* 'boundaries
706 (let ((slash (mh-search-from-end ?/ orig-name)))
707 (if slash (1+ slash)
708 (if (string-match "\\`\\+" orig-name) 1 0)))
709 (if (cdr flag) (string-match "/" (cdr flag)))))
710 ((eq flag nil)
711 (let ((try-res
712 (try-completion
713 remainder
714 (mh-sub-folders last-complete t)
715 predicate)))
716 (cond ((eq try-res nil) nil)
717 ((and (eq try-res t) (equal name orig-name)) t)
718 ((eq try-res t) name)
719 (t (concat (or last-complete "+") try-res)))))
720 ((eq flag t)
721 (all-completions
722 remainder (mh-sub-folders last-complete t) predicate))
723 ((eq flag 'lambda)
724 (let ((path (concat (unless (and (> (length name) 1)
725 (eq (aref name 1) ?/))
726 mh-user-path)
727 (substring name 1))))
728 (cond (mh-allow-root-folder-flag (file-directory-p path))
729 ((equal path mh-user-path) nil)
730 (t (file-directory-p path))))))))
732 ;; Shush compiler.
733 (mh-do-in-xemacs
734 (defvar completion-root-regexp))
736 (defun mh-folder-completing-read (prompt default allow-root-folder-flag)
737 "Read folder name with PROMPT and default result DEFAULT.
738 If ALLOW-ROOT-FOLDER-FLAG is non-nil then \"+\" is allowed to be
739 a folder name corresponding to `mh-user-path'."
740 (mh-normalize-folder-name
741 (let ((completion-root-regexp "^[+/]")
742 (minibuffer-local-completion-map mh-folder-completion-map)
743 (mh-allow-root-folder-flag allow-root-folder-flag))
744 (completing-read prompt 'mh-folder-completion-function nil nil nil
745 'mh-folder-hist default))
748 ;;;###mh-autoload
749 (defun mh-prompt-for-folder (prompt default can-create
750 &optional default-string allow-root-folder-flag)
751 "Prompt for a folder name with PROMPT.
752 Returns the folder's name as a string. DEFAULT is used if the
753 folder exists and the user types return. If the CAN-CREATE flag
754 is t, then a folder is created if it doesn't already exist. If
755 optional argument DEFAULT-STRING is non-nil, use it in the prompt
756 instead of DEFAULT. If ALLOW-ROOT-FOLDER-FLAG is non-nil then the
757 function will accept the folder +, which means all folders when
758 used in searching."
759 (if (null default)
760 (setq default ""))
761 (let* ((default-string (cond (default-string (format " (default %s)" default-string))
762 ((equal "" default) "")
763 (t (format " (default %s)" default))))
764 (prompt (format "%s folder%s: " prompt default-string))
765 (mh-current-folder-name mh-current-folder)
766 read-name folder-name)
767 (while (and (setq read-name (mh-folder-completing-read
768 prompt default allow-root-folder-flag))
769 (equal read-name "")
770 (equal default "")))
771 (cond ((or (equal read-name "")
772 (and (equal read-name "+") (not allow-root-folder-flag)))
773 (setq read-name default))
774 ((not (mh-folder-name-p read-name))
775 (setq read-name (format "+%s" read-name))))
776 (if (or (not read-name) (equal "" read-name))
777 (error "No folder specified"))
778 (setq folder-name read-name)
779 (cond ((and (> (length folder-name) 0)
780 (eq (aref folder-name (1- (length folder-name))) ?/))
781 (setq folder-name (substring folder-name 0 -1))))
782 (let* ((last-slash (mh-search-from-end ?/ folder-name))
783 (parent (and last-slash (substring folder-name 0 last-slash)))
784 (child (if last-slash
785 (substring folder-name (1+ last-slash))
786 (substring folder-name 1))))
787 (unless (member child
788 (mapcar #'car (gethash parent mh-sub-folders-cache)))
789 (mh-remove-from-sub-folders-cache folder-name)))
790 (let ((new-file-flag
791 (not (file-exists-p (mh-expand-file-name folder-name)))))
792 (cond ((and new-file-flag
793 can-create
794 (y-or-n-p
795 (format "Folder %s does not exist. Create it? "
796 folder-name)))
797 (message "Creating %s" folder-name)
798 (mh-exec-cmd-error nil "folder" folder-name)
799 (mh-remove-from-sub-folders-cache folder-name)
800 (when (boundp 'mh-speed-folder-map)
801 (mh-speed-add-folder folder-name))
802 (message "Creating %s...done" folder-name))
803 (new-file-flag
804 (error "Folder %s does not exist" folder-name))
805 ((not (file-directory-p (mh-expand-file-name folder-name)))
806 (error "%s is not a directory"
807 (mh-expand-file-name folder-name)))))
808 folder-name))
812 ;;; Message Utilities
814 ;; Functions that would ordinarily be in mh-letter.el that are needed
815 ;; by mh-show.el are found here in order to prevent the loading of
816 ;; mh-letter.el until a message is actually composed.
818 ;;;###mh-autoload
819 (defun mh-in-header-p ()
820 "Return non-nil if the point is in the header of a draft message."
821 (< (point) (mh-mail-header-end)))
823 ;;;###mh-autoload
824 (defun mh-extract-from-header-value ()
825 "Extract From: string from header."
826 (save-excursion
827 (if (not (mh-goto-header-field "From:"))
829 (skip-chars-forward " \t")
830 (buffer-substring-no-properties
831 (point) (progn (mh-header-field-end)(point))))))
833 ;;;###mh-autoload
834 (defun mh-get-header-field (field)
835 "Find and return the body of FIELD in the mail header.
836 Returns the empty string if the field is not in the header of the
837 current buffer."
838 (if (mh-goto-header-field field)
839 (progn
840 (skip-chars-forward " \t") ;strip leading white space in body
841 (let ((start (point)))
842 (mh-header-field-end)
843 (buffer-substring-no-properties start (point))))
844 ""))
846 ;;;###mh-autoload
847 (defun mh-goto-header-field (field)
848 "Move to FIELD in the message header.
849 Move to the end of the FIELD name, which should end in a colon.
850 Returns t if found, nil if not."
851 (goto-char (point-min))
852 (let ((case-fold-search t)
853 (headers-end (save-excursion
854 (mh-goto-header-end 0)
855 (point))))
856 (re-search-forward (format "^%s" field) headers-end t)))
858 ;;;###mh-autoload
859 (defun mh-goto-header-end (arg)
860 "Move the cursor ARG lines after the header."
861 (if (re-search-forward (concat "^\\(" (regexp-quote mh-mail-header-separator)
862 "\\)?$") nil nil)
863 (forward-line arg)))
865 ;;;###mh-autoload
866 (defun mh-mail-header-end ()
867 "Substitute for `mail-header-end' that doesn't widen the buffer.
869 In MH-E we frequently need to find the end of headers in nested
870 messages, where the buffer has been narrowed. This function works
871 in this situation."
872 (save-excursion
873 ;; XXX: The following replaces a call to rfc822-goto-eoh. Occasionally,
874 ;; mail headers that MH-E has to read contains lines of the form:
875 ;; From xxx@yyy Mon May 10 11:48:07 2004
876 ;; In this situation, rfc822-goto-eoh doesn't go to the end of the
877 ;; header. The replacement allows From_ lines in the mail header.
878 (goto-char (point-min))
879 (loop for p = (re-search-forward
880 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
881 do (cond ((null p) (return))
882 (t (goto-char (match-beginning 0))
883 (unless (looking-at "From ") (return))
884 (goto-char p))))
885 (point)))
887 ;;;###mh-autoload
888 (defun mh-header-field-beginning ()
889 "Move to the beginning of the current header field.
890 Handles RFC 822 continuation lines."
891 (beginning-of-line)
892 (while (looking-at "^[ \t]")
893 (forward-line -1)))
895 ;;;###mh-autoload
896 (defun mh-header-field-end ()
897 "Move to the end of the current header field.
898 Handles RFC 822 continuation lines."
899 (forward-line 1)
900 (while (looking-at "^[ \t]")
901 (forward-line 1))
902 (backward-char 1)) ;to end of previous line
904 ;;;###mh-autoload
905 (defun mh-letter-hide-all-skipped-fields ()
906 "Hide all skipped fields."
907 (save-excursion
908 (goto-char (point-min))
909 (save-restriction
910 (narrow-to-region (point) (mh-mail-header-end))
911 (while (re-search-forward mh-letter-header-field-regexp nil t)
912 (if (mh-letter-skipped-header-field-p (match-string 1))
913 (mh-letter-toggle-header-field-display -1)
914 (mh-letter-toggle-header-field-display 'long))
915 (beginning-of-line 2)))))
917 ;;;###mh-autoload
918 (defun mh-letter-skipped-header-field-p (field)
919 "Check if FIELD is to be skipped."
920 (let ((field (downcase field)))
921 (loop for x in mh-compose-skipped-header-fields
922 when (equal (downcase x) field) return t
923 finally return nil)))
925 (defvar mh-hidden-header-keymap
926 (let ((map (make-sparse-keymap)))
927 (mh-do-in-gnu-emacs
928 (define-key map [mouse-2] 'mh-letter-toggle-header-field-display-button))
929 (mh-do-in-xemacs
930 (define-key map '(button2)
931 'mh-letter-toggle-header-field-display-button))
932 map))
934 ;;;###mh-autoload
935 (defun mh-letter-toggle-header-field-display (arg)
936 "Toggle display of header field at point.
938 Use this command to display truncated header fields. This command
939 is a toggle so entering it again will hide the field. This
940 command takes a prefix argument ARG: if negative then the field
941 is hidden, if positive then the field is displayed."
942 (interactive (list nil))
943 (when (and (mh-in-header-p)
944 (progn
945 (end-of-line)
946 (re-search-backward mh-letter-header-field-regexp nil t)))
947 (let ((buffer-read-only nil)
948 (modified-flag (buffer-modified-p))
949 (begin (point))
950 end)
951 (end-of-line)
952 (setq end (1- (if (re-search-forward "^[^ \t]" nil t)
953 (match-beginning 0)
954 (point-max))))
955 (goto-char begin)
956 ;; Make it clickable...
957 (add-text-properties begin end `(keymap ,mh-hidden-header-keymap
958 mouse-face highlight))
959 (unwind-protect
960 (cond ((or (and (not arg)
961 (text-property-any begin end 'invisible 'vanish))
962 (and (numberp arg)
963 (>= arg 0))
964 (and (eq arg 'long)
965 (> (mh-line-beginning-position 5) end)))
966 (remove-text-properties begin end '(invisible nil))
967 (search-forward ":" (mh-line-end-position) t)
968 (mh-letter-skip-leading-whitespace-in-header-field))
969 ;; XXX Redesign to make usable by user. Perhaps use a positive
970 ;; numeric prefix to make that many lines visible.
971 ((eq arg 'long)
972 (end-of-line 4)
973 (mh-letter-truncate-header-field end)
974 (beginning-of-line))
975 (t (end-of-line)
976 (mh-letter-truncate-header-field end)
977 (beginning-of-line)))
978 (set-buffer-modified-p modified-flag)))))
980 ;;;###mh-autoload
981 (defun mh-letter-skip-leading-whitespace-in-header-field ()
982 "Skip leading whitespace in a header field.
983 If the header field doesn't have at least one space after the
984 colon then a space character is added."
985 (let ((need-space t))
986 (while (memq (char-after) '(?\t ?\ ))
987 (forward-char)
988 (setq need-space nil))
989 (when need-space (insert " "))))
991 (defun mh-letter-truncate-header-field (end)
992 "Replace text from current line till END with an ellipsis.
993 If the current line is too long truncate a part of it as well."
994 (let ((max-len (min (window-width) 62)))
995 (when (> (+ (current-column) 4) max-len)
996 (backward-char (- (+ (current-column) 5) max-len)))
997 (when (> end (point))
998 (add-text-properties (point) end '(invisible vanish)))))
1000 ;;;###mh-autoload
1001 (defun mh-signature-separator-p ()
1002 "Return non-nil if buffer includes \"^-- $\"."
1003 (save-excursion
1004 (goto-char (point-min))
1005 (re-search-forward mh-signature-separator-regexp nil t)))
1007 (provide 'mh-utils)
1009 ;; Local Variables:
1010 ;; indent-tabs-mode: nil
1011 ;; sentence-end-double-space: nil
1012 ;; End:
1014 ;;; mh-utils.el ends here