(gnus-blocked-images): Clarify privacy implications
[emacs.git] / lisp / mh-e / mh-utils.el
blob7bda0a684729bfde488b29459f4e8bc58d704c4e
1 ;;; mh-utils.el --- MH-E general utilities
3 ;; Copyright (C) 1993, 1995, 1997, 2000-2018 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 (or mh-variant-in-use (mh-variant-set mh-variant))
181 ;; Sanity checks.
182 (if (and (getenv "MH")
183 (not (file-readable-p (getenv "MH"))))
184 (error "MH environment variable contains unreadable file %s"
185 (getenv "MH")))
186 (if (null (mh-variants))
187 (error "Install MH and run install-mh before running MH-E"))
188 (if (not (or (getenv "MH") (file-readable-p "~/.mh_profile")))
189 (error "Run install-mh before running MH-E"))
190 ;; Read MH profile.
191 (setq mh-user-path (mh-profile-component "Path"))
192 (if (not mh-user-path)
193 (setq mh-user-path "Mail"))
194 (setq mh-user-path
195 (file-name-as-directory
196 (expand-file-name mh-user-path (expand-file-name "~"))))
197 (mh-set-x-image-cache-directory (expand-file-name ".mhe-x-image-cache"
198 mh-user-path))
199 (setq mh-draft-folder (mh-profile-component "Draft-Folder"))
200 (if mh-draft-folder
201 (progn
202 (if (not (mh-folder-name-p mh-draft-folder))
203 (setq mh-draft-folder (format "+%s" mh-draft-folder)))
204 (if (not (file-exists-p (mh-expand-file-name mh-draft-folder)))
205 (error
206 "Draft folder \"%s\" not found; create it and try again"
207 (mh-expand-file-name mh-draft-folder)))))
208 (setq mh-inbox (mh-profile-component "Inbox"))
209 (cond ((not mh-inbox)
210 (setq mh-inbox "+inbox"))
211 ((not (mh-folder-name-p mh-inbox))
212 (setq mh-inbox (format "+%s" mh-inbox))))
213 (setq mh-unseen-seq (mh-profile-component "Unseen-Sequence"))
214 (if mh-unseen-seq
215 (setq mh-unseen-seq (intern mh-unseen-seq))
216 (setq mh-unseen-seq 'unseen)) ;old MH default?
217 (setq mh-previous-seq (mh-profile-component "Previous-Sequence"))
218 (if mh-previous-seq
219 (setq mh-previous-seq (intern mh-previous-seq)))
220 (run-hooks 'mh-find-path-hook)
221 (mh-collect-folder-names)
222 (setq mh-find-path-run t)))
226 ;;; Help Functions
228 ;;;###mh-autoload
229 (defun mh-ephem-message (string)
230 "Display STRING in the minibuffer momentarily."
231 (message "%s" string)
232 (sit-for 5)
233 (message ""))
235 (defvar mh-help-default nil
236 "Mode to use if messages are not present for the current mode.")
238 (defvar mh-help-messages nil
239 "Help messages for all modes.
240 This is an alist of alists. The primary key is a symbol
241 representing the mode; the value is described in `mh-set-help'.")
243 ;;;###mh-autoload
244 (defun mh-set-help (messages &optional default)
245 "Set help messages.
247 The MESSAGES are assumed to be an associative array. It is used
248 to show help for the most common commands in the current mode.
249 The key is a prefix char. The value is one or more strings which
250 are concatenated together and displayed in a help buffer if ? is
251 pressed after the prefix character. The special key nil is used
252 to display the non-prefixed commands.
254 The substitutions described in `substitute-command-keys' are performed as
255 well.
257 If optional argument DEFAULT is non-nil, then these messages will
258 be used if help is asked for an unknown mode."
259 (add-to-list 'mh-help-messages (cons major-mode messages))
260 (if default
261 (setq mh-help-default major-mode)))
263 ;;;###mh-autoload
264 (defun mh-help (&optional help-messages)
265 "Display cheat sheet for the MH-E commands.
266 See `mh-set-help' for setting the help messages.
267 HELP-MESSAGES are used instead if given.
268 This is a list of one or more strings which are concatenated together
269 and displayed in a help buffer."
270 (interactive)
271 (let* ((help (or help-messages
272 (cdr (assoc nil (assoc major-mode mh-help-messages)))))
273 (text (substitute-command-keys (mapconcat 'identity help ""))))
274 (with-electric-help
275 (function
276 (lambda ()
277 (insert text)))
278 mh-help-buffer)))
280 ;;;###mh-autoload
281 (defun mh-prefix-help ()
282 "Display cheat sheet for the commands of the current prefix in minibuffer."
283 (interactive)
284 ;; We got here because the user pressed a "?", but he pressed a prefix key
285 ;; before that. Since the key vector starts at index 0, the index of the
286 ;; last keystroke is length-1 and thus the second to last keystroke is at
287 ;; length-2. We use that information to obtain a suitable prefix character
288 ;; from the recent keys.
289 (let* ((keys (recent-keys))
290 (prefix-char (elt keys (- (length keys) 2)))
291 (help (cdr (assoc prefix-char (assoc major-mode mh-help-messages)))))
292 (mh-help help)))
296 ;;; Message Number Utilities
298 ;;;###mh-autoload
299 (defun mh-coalesce-msg-list (messages)
300 "Given a list of MESSAGES, return a list of message number ranges.
301 This is the inverse of `mh-read-msg-list', which expands ranges.
302 Message lists passed to MH programs should be processed by this
303 function to avoid exceeding system command line argument limits."
304 (let ((msgs (sort (copy-sequence messages) 'mh-greaterp))
305 (range-high nil)
306 (prev -1)
307 (ranges nil))
308 (while prev
309 (if range-high
310 (if (or (not (numberp prev))
311 (not (equal (car msgs) (1- prev))))
312 (progn ;non-sequential, flush old range
313 (if (eq prev range-high)
314 (setq ranges (cons range-high ranges))
315 (setq ranges (cons (format "%s-%s" prev range-high) ranges)))
316 (setq range-high nil))))
317 (or range-high
318 (setq range-high (car msgs))) ;start new or first range
319 (setq prev (car msgs))
320 (setq msgs (cdr msgs)))
321 ranges))
323 (defun mh-greaterp (msg1 msg2)
324 "Return the greater of two message indicators MSG1 and MSG2.
325 Strings are \"smaller\" than numbers.
326 Valid values are things like \"cur\", \"last\", 1, and 1820."
327 (if (numberp msg1)
328 (if (numberp msg2)
329 (> msg1 msg2)
331 (if (numberp msg2)
333 (string-lessp msg2 msg1))))
335 ;;;###mh-autoload
336 (defun mh-lessp (msg1 msg2)
337 "Return the lesser of two message indicators MSG1 and MSG2.
338 Strings are \"smaller\" than numbers.
339 Valid values are things like \"cur\", \"last\", 1, and 1820."
340 (not (mh-greaterp msg1 msg2)))
342 ;;;###mh-autoload
343 (defun mh-get-msg-num (error-if-no-message)
344 "Return the message number of the displayed message.
345 If the argument ERROR-IF-NO-MESSAGE is non-nil, then complain if
346 the cursor is not pointing to a message."
347 (save-excursion
348 (beginning-of-line)
349 (cond ((looking-at (mh-scan-msg-number-regexp))
350 (string-to-number (buffer-substring (match-beginning 1)
351 (match-end 1))))
352 (error-if-no-message
353 (user-error "Cursor not pointing to message"))
354 (t nil))))
358 ;;; Folder Cache and Access
360 (defvar mh-sub-folders-cache (make-hash-table :test #'equal))
361 (defvar mh-current-folder-name nil)
362 (defvar mh-flists-partial-line "")
363 (defvar mh-flists-process nil)
365 ;;;###mh-autoload
366 (defun mh-clear-sub-folders-cache ()
367 "Clear `mh-sub-folders-cache'."
368 (clrhash mh-sub-folders-cache))
370 ;; Initialize mh-sub-folders-cache...
371 (defun mh-collect-folder-names ()
372 "Collect folder names by running \"folders\"."
373 (unless mh-flists-process
374 (setq mh-flists-process
375 (mh-exec-cmd-daemon "folders" 'mh-collect-folder-names-filter
376 "-recurse" "-fast"))))
378 (defun mh-collect-folder-names-filter (process output)
379 "Read folder names.
380 PROCESS is the flists process that was run to collect folder
381 names and the function is called when OUTPUT is available."
382 (let ((position 0)
383 (prevailing-match-data (match-data))
384 line-end folder)
385 (unwind-protect
386 (while (setq line-end (string-match "\n" output position))
387 (setq folder (format "+%s%s"
388 mh-flists-partial-line
389 (substring output position line-end)))
390 (setq mh-flists-partial-line "")
391 (unless (equal (aref folder 1) ?.)
392 (mh-populate-sub-folders-cache folder))
393 (setq position (1+ line-end)))
394 (set-match-data prevailing-match-data))
395 (setq mh-flists-partial-line (substring output position))))
397 (defun mh-populate-sub-folders-cache (folder)
398 "Tell `mh-sub-folders-cache' about FOLDER."
399 (let* ((last-slash (mh-search-from-end ?/ folder))
400 (child1 (substring folder (1+ (or last-slash 0))))
401 (parent (and last-slash (substring folder 0 last-slash)))
402 (parent-slash (and parent (mh-search-from-end ?/ parent)))
403 (child2 (and parent (substring parent (1+ (or parent-slash 0)))))
404 (grand-parent (and parent-slash (substring parent 0 parent-slash)))
405 (cache-entry (gethash parent mh-sub-folders-cache)))
406 (unless (loop for x in cache-entry when (equal (car x) child1) return t
407 finally return nil)
408 (push (list child1) cache-entry)
409 (setf (gethash parent mh-sub-folders-cache)
410 (sort cache-entry (lambda (x y) (string< (car x) (car y)))))
411 (when parent
412 (loop for x in (gethash grand-parent mh-sub-folders-cache)
413 when (equal (car x) child2)
414 do (progn (setf (cdr x) t) (return)))))))
416 (defun mh-normalize-folder-name (folder &optional empty-string-okay
417 dont-remove-trailing-slash
418 return-nil-if-folder-empty)
419 "Normalizes FOLDER name.
421 Makes sure that two `/' characters never occur next to each
422 other. Also all occurrences of `..' and `.' are suitably
423 processed. So \"+inbox/../news\" will be normalized to \"+news\".
425 If optional argument EMPTY-STRING-OKAY is nil then a `+' is added
426 at the front if FOLDER lacks one. If non-nil and FOLDER is the
427 empty string then nothing is added.
429 If optional argument DONT-REMOVE-TRAILING-SLASH is non-nil then a
430 trailing `/' if present is retained (if present), otherwise it is
431 removed.
433 If optional argument RETURN-NIL-IF-FOLDER-EMPTY is non-nil, then
434 return nil if FOLDER is \"\" or \"+\". This is useful when
435 normalizing the folder for the `folders' command which displays
436 the directories in / if passed \"+\". This is usually not
437 desired. If this argument is non-nil, then EMPTY-STRING-OKAY has
438 no effect."
439 (cond
440 ((if (and (or (equal folder "+") (equal folder ""))
441 return-nil-if-folder-empty)
442 (setq folder nil)))
443 ((stringp folder)
444 ;; Replace two or more consecutive '/' characters with a single '/'
445 (while (string-match "//" folder)
446 (setq folder (replace-match "/" nil t folder)))
447 (let* ((length (length folder))
448 (trailing-slash-present (and (> length 0)
449 (equal (aref folder (1- length)) ?/)))
450 (leading-slash-present (and (> length 0)
451 (equal (aref folder 0) ?/))))
452 (when (and (> length 0) (equal (aref folder 0) ?@)
453 (stringp mh-current-folder-name))
454 (setq folder (format "%s/%s/" mh-current-folder-name
455 (substring folder 1))))
456 ;; XXX: Purge empty strings from the list that split-string
457 ;; returns. In XEmacs, (split-string "+foo/" "/") returns
458 ;; ("+foo" "") while in GNU Emacs it returns ("+foo"). In the
459 ;; code it is assumed that the components list has no empty
460 ;; strings.
461 (let ((components (delete "" (split-string folder "/")))
462 (result ()))
463 ;; Remove .. and . from the pathname.
464 (dolist (component components)
465 (cond ((and (equal component "..") result)
466 (pop result))
467 ((equal component ".."))
468 ((equal component "."))
469 (t (push component result))))
470 (setq folder "")
471 (dolist (component result)
472 (setq folder (concat component "/" folder)))
473 ;; Remove trailing '/' if needed.
474 (unless (and trailing-slash-present dont-remove-trailing-slash)
475 (when (not (equal folder ""))
476 (setq folder (substring folder 0 (1- (length folder))))))
477 (when leading-slash-present
478 (setq folder (concat "/" folder)))))
479 (cond ((and empty-string-okay (equal folder "")))
480 ((equal folder "")
481 (setq folder "+"))
482 ((not (equal (aref folder 0) ?+))
483 (setq folder (concat "+" folder))))))
484 folder)
486 (defmacro mh-children-p (folder)
487 "Return t if FOLDER from sub-folders cache has children."
488 ;; The car of folder is the name, and the cdr is either t or some
489 ;; sort of count that I do not understand. It's too small to be the
490 ;; number of messages in the sub-folders and too large to be the
491 ;; number of sub-folders. XXX
492 `(if (cdr ,folder)
494 nil))
496 ;;;###mh-autoload
497 (defun mh-folder-list (folder)
498 "Return FOLDER and its descendants.
499 FOLDER may have a + prefix. Returns a list of strings without the
500 + prefix. If FOLDER is nil, then all folders are considered. For
501 example, if your Mail directory only contains the folders +inbox,
502 +outbox, +lists, and +lists/mh-e, then
504 (mh-folder-list nil)
505 => (\"inbox\" \"lists\" \"lists/mh-e\" \"outbox\")
506 (mh-folder-list \"+lists\")
507 => (\"lists\" \"lists/mh-e\")
509 Respects the value of `mh-recursive-folders-flag'. If this flag
510 is nil, and the sub-folders have not been explicitly viewed, then
511 they will not be returned."
512 (let ((folder-list))
513 ;; Normalize folder. Strip leading + and trailing slash(es). If no
514 ;; folder is specified, ensure it is nil to avoid adding the
515 ;; folder to the folder-list and adding a slash to it.
516 (when folder
517 (setq folder (mh-replace-regexp-in-string "^\\+" "" folder))
518 (setq folder (mh-replace-regexp-in-string "/+$" "" folder))
519 (if (equal folder "")
520 (setq folder nil)))
521 ;; Add provided folder to list, unless all folders are asked for.
522 ;; Then append slash to separate sub-folders.
523 (unless (null folder)
524 (setq folder-list (list folder))
525 (setq folder (concat folder "/")))
526 (loop for f in (mh-sub-folders folder) do
527 (setq folder-list
528 (append folder-list
529 (if (mh-children-p f)
530 (mh-folder-list (concat folder (car f)))
531 (list (concat folder (car f)))))))
532 folder-list))
534 ;;;###mh-autoload
535 (defun mh-sub-folders (folder &optional add-trailing-slash-flag)
536 "Find the subfolders of FOLDER.
537 The function avoids running folders unnecessarily by caching the
538 results of the actual folders call.
540 If optional argument ADD-TRAILING-SLASH-FLAG is non-nil then a
541 slash is added to each of the sub-folder names that may have
542 nested folders within them."
543 (let* ((folder (mh-normalize-folder-name folder nil nil t))
544 (match (gethash folder mh-sub-folders-cache 'no-result))
545 (sub-folders (cond ((eq match 'no-result)
546 (setf (gethash folder mh-sub-folders-cache)
547 (mh-sub-folders-actual folder)))
548 (t match))))
549 (if add-trailing-slash-flag
550 (mapcar #'(lambda (x)
551 (if (cdr x) (cons (concat (car x) "/") (cdr x)) x))
552 sub-folders)
553 sub-folders)))
555 ;; FIXME: This function does not do well if FOLDER does not exist. It
556 ;; then changes the context to that folder which causes problems down
557 ;; the line. Since a folder in the cache could later be deleted, it
558 ;; would be good for mh-sub-folders-actual to return nil in this case
559 ;; so that mh-sub-folders could delete it from the cache. This
560 ;; function could protect itself by using a temporary context.
561 (defun mh-sub-folders-actual (folder)
562 "Execute the command folders to return the sub-folders of FOLDER.
563 Filters out the folder names that start with \".\" so that
564 directories that aren't usually mail folders are hidden.
565 Expects FOLDER to have already been normalized with
566 (mh-normalize-folder-name folder nil nil t)"
567 (let ((arg-list `(,(expand-file-name "folders" mh-progs)
568 nil (t nil) nil "-noheader" "-norecurse" "-nototal"
569 ,@(if (stringp folder) (list folder) ())))
570 (results ())
571 (current-folder (concat
572 (with-temp-buffer
573 (call-process (expand-file-name "folder" mh-progs)
574 nil '(t nil) nil "-fast")
575 (buffer-substring (point-min) (1- (point-max))))
576 "+")))
577 (with-temp-buffer
578 (apply #'call-process arg-list)
579 (goto-char (point-min))
580 (while (not (and (eolp) (bolp)))
581 (goto-char (mh-line-end-position))
582 (let ((start-pos (mh-line-beginning-position))
583 (has-pos (search-backward " has "
584 (mh-line-beginning-position) t)))
585 (when (integerp has-pos)
586 (while (equal (char-after has-pos) ? )
587 (decf has-pos))
588 (incf has-pos)
589 (while (equal (char-after start-pos) ? )
590 (incf start-pos))
591 (let* ((name (buffer-substring start-pos has-pos))
592 (first-char (aref name 0))
593 (last-char (aref name (1- (length name)))))
594 (unless (member first-char '(?. ?# ?,))
595 (when (and (equal last-char ?+) (equal name current-folder))
596 (setq name (substring name 0 (1- (length name)))))
597 (push
598 (cons name
599 (search-forward "(others)" (mh-line-end-position) t))
600 results))))
601 (forward-line 1))))
602 (setq results (nreverse results))
603 (when (stringp folder)
604 (setq results (cdr results))
605 (let ((folder-name-len (length (format "%s/" (substring folder 1)))))
606 (setq results (mapcar (lambda (f)
607 (cons (substring (car f) folder-name-len)
608 (cdr f)))
609 results))))
610 results))
612 ;;;###mh-autoload
613 (defun mh-remove-from-sub-folders-cache (folder)
614 "Remove FOLDER and its parent from `mh-sub-folders-cache'.
615 FOLDER should be unconditionally removed from the cache. Also the
616 last ancestor of FOLDER present in the cache must be removed as
617 well.
619 To see why this is needed assume we have a folder +foo which has
620 a single sub-folder qux. Now we create the folder +foo/bar/baz.
621 Here we will need to invalidate the cached sub-folders of +foo,
622 otherwise completion on +foo won't tell us about the option
623 +foo/bar!"
624 (remhash folder mh-sub-folders-cache)
625 (block ancestor-found
626 (let ((parent folder)
627 (one-ancestor-found nil)
628 last-slash)
629 (while (setq last-slash (mh-search-from-end ?/ parent))
630 (setq parent (substring parent 0 last-slash))
631 (unless (eq (gethash parent mh-sub-folders-cache 'none) 'none)
632 (remhash parent mh-sub-folders-cache)
633 (if one-ancestor-found
634 (return-from ancestor-found)
635 (setq one-ancestor-found t))))
636 (remhash nil mh-sub-folders-cache))))
640 ;;; Folder Utilities
642 ;;;###mh-autoload
643 (defun mh-folder-name-p (name)
644 "Return non-nil if NAME is the name of a folder.
645 A name (a string or symbol) can be a folder name if it begins
646 with \"+\"."
647 (if (symbolp name)
648 (eq (aref (symbol-name name) 0) ?+)
649 (and (> (length name) 0)
650 (eq (aref name 0) ?+))))
652 ;;;###mh-autoload
653 (defun mh-expand-file-name (filename &optional default)
654 "Expand FILENAME like `expand-file-name', but also handle MH folder names.
655 Any filename that starts with `+' is treated as a folder name.
656 See `expand-file-name' for description of DEFAULT."
657 (if (mh-folder-name-p filename)
658 (expand-file-name (substring filename 1) mh-user-path)
659 (expand-file-name filename default)))
661 (defvar mh-folder-hist nil)
663 ;; Shush compiler.
664 (defvar mh-speed-flists-cache)
666 (defvar mh-allow-root-folder-flag nil
667 "Non-nil means \"+\" is an acceptable folder name.
668 This variable is used to communicate with
669 `mh-folder-completion-function'. That function can have exactly
670 three arguments so we bind this variable to t or nil.
672 This variable should never be set.")
674 (defvar mh-folder-completion-map (copy-keymap minibuffer-local-completion-map))
675 (define-key mh-folder-completion-map " " 'minibuffer-complete) ;Why???
677 (defvar mh-speed-flists-inhibit-flag nil)
679 ;;;###mh-autoload
680 (defun mh-speed-flists-active-p ()
681 "Check if speedbar is running with message counts enabled."
682 (and (featurep 'mh-speed)
683 (not mh-speed-flists-inhibit-flag)
684 (> (hash-table-count mh-speed-flists-cache) 0)))
686 ;;;###mh-autoload
687 (defun mh-folder-completion-function (name predicate flag)
688 "Programmable completion for folder names.
689 NAME is the partial folder name that has been input. PREDICATE if
690 non-nil is a function that is used to filter the possible
691 choices. FLAG is nil to indicate `try-completion', t for
692 `all-completions', or the symbol lambda for `test-completion'.
693 See Info node `(elisp) Programmed Completion' for details."
694 (let* ((orig-name name)
695 ;; After normalization, name is nil, +, or +something. If a
696 ;; trailing slash is present, it is preserved.
697 (name (mh-normalize-folder-name name nil t))
698 (last-slash (mh-search-from-end ?/ name))
699 ;; nil if + or +folder; +folder/ if slash present.
700 (last-complete (if last-slash (substring name 0 (1+ last-slash)) nil))
701 ;; Either +folder/remainder, +remainder, or "".
702 (remainder (cond (last-complete (substring name (1+ last-slash)))
703 (name (substring name 1))
704 (t ""))))
705 (cond ((eq (car-safe flag) 'boundaries)
706 (list* 'boundaries
707 (let ((slash (mh-search-from-end ?/ orig-name)))
708 (if slash (1+ slash)
709 (if (string-match "\\`\\+" orig-name) 1 0)))
710 (if (cdr flag) (string-match "/" (cdr flag)))))
711 ((eq flag nil)
712 (let ((try-res
713 (try-completion
714 remainder
715 (mh-sub-folders last-complete t)
716 predicate)))
717 (cond ((eq try-res nil) nil)
718 ((and (eq try-res t) (equal name orig-name)) t)
719 ((eq try-res t) name)
720 (t (concat (or last-complete "+") try-res)))))
721 ((eq flag t)
722 (all-completions
723 remainder (mh-sub-folders last-complete t) predicate))
724 ((eq flag 'lambda)
725 (let ((path (concat (unless (and (> (length name) 1)
726 (eq (aref name 1) ?/))
727 mh-user-path)
728 (substring name 1))))
729 (cond (mh-allow-root-folder-flag (file-directory-p path))
730 ((equal path mh-user-path) nil)
731 (t (file-directory-p path))))))))
733 ;; Shush compiler.
734 (mh-do-in-xemacs
735 (defvar completion-root-regexp))
737 (defun mh-folder-completing-read (prompt default allow-root-folder-flag)
738 "Read folder name with PROMPT and default result DEFAULT.
739 If ALLOW-ROOT-FOLDER-FLAG is non-nil then \"+\" is allowed to be
740 a folder name corresponding to `mh-user-path'."
741 (mh-normalize-folder-name
742 (let ((completion-root-regexp "^[+/]")
743 (minibuffer-local-completion-map mh-folder-completion-map)
744 (mh-allow-root-folder-flag allow-root-folder-flag))
745 (completing-read prompt 'mh-folder-completion-function nil nil nil
746 'mh-folder-hist default))
749 ;;;###mh-autoload
750 (defun mh-prompt-for-folder (prompt default can-create
751 &optional default-string allow-root-folder-flag)
752 "Prompt for a folder name with PROMPT.
753 Returns the folder's name as a string. DEFAULT is used if the
754 folder exists and the user types return. If the CAN-CREATE flag
755 is t, then a folder is created if it doesn't already exist. If
756 optional argument DEFAULT-STRING is non-nil, use it in the prompt
757 instead of DEFAULT. If ALLOW-ROOT-FOLDER-FLAG is non-nil then the
758 function will accept the folder +, which means all folders when
759 used in searching."
760 (if (null default)
761 (setq default ""))
762 (let* ((default-string (cond (default-string (format " (default %s)" default-string))
763 ((equal "" default) "")
764 (t (format " (default %s)" default))))
765 (prompt (format "%s folder%s: " prompt default-string))
766 (mh-current-folder-name mh-current-folder)
767 read-name folder-name)
768 (while (and (setq read-name (mh-folder-completing-read
769 prompt default allow-root-folder-flag))
770 (equal read-name "")
771 (equal default "")))
772 (cond ((or (equal read-name "")
773 (and (equal read-name "+") (not allow-root-folder-flag)))
774 (setq read-name default))
775 ((not (mh-folder-name-p read-name))
776 (setq read-name (format "+%s" read-name))))
777 (if (or (not read-name) (equal "" read-name))
778 (error "No folder specified"))
779 (setq folder-name read-name)
780 (cond ((and (> (length folder-name) 0)
781 (eq (aref folder-name (1- (length folder-name))) ?/))
782 (setq folder-name (substring folder-name 0 -1))))
783 (let* ((last-slash (mh-search-from-end ?/ folder-name))
784 (parent (and last-slash (substring folder-name 0 last-slash)))
785 (child (if last-slash
786 (substring folder-name (1+ last-slash))
787 (substring folder-name 1))))
788 (unless (member child
789 (mapcar #'car (gethash parent mh-sub-folders-cache)))
790 (mh-remove-from-sub-folders-cache folder-name)))
791 (let ((new-file-flag
792 (not (file-exists-p (mh-expand-file-name folder-name)))))
793 (cond ((and new-file-flag
794 can-create
795 (y-or-n-p
796 (format "Folder %s does not exist. Create it? "
797 folder-name)))
798 (message "Creating %s" folder-name)
799 (mh-exec-cmd-error nil "folder" folder-name)
800 (mh-remove-from-sub-folders-cache folder-name)
801 (when (boundp 'mh-speed-folder-map)
802 (mh-speed-add-folder folder-name))
803 (message "Creating %s...done" folder-name))
804 (new-file-flag
805 (error "Folder %s does not exist" folder-name))
806 ((not (file-directory-p (mh-expand-file-name folder-name)))
807 (error "%s is not a directory"
808 (mh-expand-file-name folder-name)))))
809 folder-name))
813 ;;; Message Utilities
815 ;; Functions that would ordinarily be in mh-letter.el that are needed
816 ;; by mh-show.el are found here in order to prevent the loading of
817 ;; mh-letter.el until a message is actually composed.
819 ;;;###mh-autoload
820 (defun mh-in-header-p ()
821 "Return non-nil if the point is in the header of a draft message."
822 (< (point) (mh-mail-header-end)))
824 ;;;###mh-autoload
825 (defun mh-extract-from-header-value ()
826 "Extract From: string from header."
827 (save-excursion
828 (if (not (mh-goto-header-field "From:"))
830 (skip-chars-forward " \t")
831 (buffer-substring-no-properties
832 (point) (progn (mh-header-field-end)(point))))))
834 ;;;###mh-autoload
835 (defun mh-get-header-field (field)
836 "Find and return the body of FIELD in the mail header.
837 Returns the empty string if the field is not in the header of the
838 current buffer."
839 (if (mh-goto-header-field field)
840 (progn
841 (skip-chars-forward " \t") ;strip leading white space in body
842 (let ((start (point)))
843 (mh-header-field-end)
844 (buffer-substring-no-properties start (point))))
845 ""))
847 ;;;###mh-autoload
848 (defun mh-goto-header-field (field)
849 "Move to FIELD in the message header.
850 Move to the end of the FIELD name, which should end in a colon.
851 Returns t if found, nil if not."
852 (goto-char (point-min))
853 (let ((case-fold-search t)
854 (headers-end (save-excursion
855 (mh-goto-header-end 0)
856 (point))))
857 (re-search-forward (format "^%s" field) headers-end t)))
859 ;;;###mh-autoload
860 (defun mh-goto-header-end (arg)
861 "Move the cursor ARG lines after the header."
862 (if (re-search-forward (concat "^\\(" (regexp-quote mh-mail-header-separator)
863 "\\)?$") nil nil)
864 (forward-line arg)))
866 ;;;###mh-autoload
867 (defun mh-mail-header-end ()
868 "Substitute for `mail-header-end' that doesn't widen the buffer.
870 In MH-E we frequently need to find the end of headers in nested
871 messages, where the buffer has been narrowed. This function works
872 in this situation."
873 (save-excursion
874 ;; XXX: The following replaces a call to rfc822-goto-eoh. Occasionally,
875 ;; mail headers that MH-E has to read contains lines of the form:
876 ;; From xxx@yyy Mon May 10 11:48:07 2004
877 ;; In this situation, rfc822-goto-eoh doesn't go to the end of the
878 ;; header. The replacement allows From_ lines in the mail header.
879 (goto-char (point-min))
880 (loop for p = (re-search-forward
881 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
882 do (cond ((null p) (return))
883 (t (goto-char (match-beginning 0))
884 (unless (looking-at "From ") (return))
885 (goto-char p))))
886 (point)))
888 ;;;###mh-autoload
889 (defun mh-header-field-beginning ()
890 "Move to the beginning of the current header field.
891 Handles RFC 822 continuation lines."
892 (beginning-of-line)
893 (while (looking-at "^[ \t]")
894 (forward-line -1)))
896 ;;;###mh-autoload
897 (defun mh-header-field-end ()
898 "Move to the end of the current header field.
899 Handles RFC 822 continuation lines."
900 (forward-line 1)
901 (while (looking-at "^[ \t]")
902 (forward-line 1))
903 (backward-char 1)) ;to end of previous line
905 ;;;###mh-autoload
906 (defun mh-letter-hide-all-skipped-fields ()
907 "Hide all skipped fields."
908 (save-excursion
909 (goto-char (point-min))
910 (save-restriction
911 (narrow-to-region (point) (mh-mail-header-end))
912 (while (re-search-forward mh-letter-header-field-regexp nil t)
913 (if (mh-letter-skipped-header-field-p (match-string 1))
914 (mh-letter-toggle-header-field-display -1)
915 (mh-letter-toggle-header-field-display 'long))
916 (beginning-of-line 2)))))
918 ;;;###mh-autoload
919 (defun mh-letter-skipped-header-field-p (field)
920 "Check if FIELD is to be skipped."
921 (let ((field (downcase field)))
922 (loop for x in mh-compose-skipped-header-fields
923 when (equal (downcase x) field) return t
924 finally return nil)))
926 (defvar mh-hidden-header-keymap
927 (let ((map (make-sparse-keymap)))
928 (mh-do-in-gnu-emacs
929 (define-key map [mouse-2] 'mh-letter-toggle-header-field-display-button))
930 (mh-do-in-xemacs
931 (define-key map '(button2)
932 'mh-letter-toggle-header-field-display-button))
933 map))
935 ;;;###mh-autoload
936 (defun mh-letter-toggle-header-field-display (arg)
937 "Toggle display of header field at point.
939 Use this command to display truncated header fields. This command
940 is a toggle so entering it again will hide the field. This
941 command takes a prefix argument ARG: if negative then the field
942 is hidden, if positive then the field is displayed."
943 (interactive (list nil))
944 (when (and (mh-in-header-p)
945 (progn
946 (end-of-line)
947 (re-search-backward mh-letter-header-field-regexp nil t)))
948 (let ((buffer-read-only nil)
949 (modified-flag (buffer-modified-p))
950 (begin (point))
951 end)
952 (end-of-line)
953 (setq end (1- (if (re-search-forward "^[^ \t]" nil t)
954 (match-beginning 0)
955 (point-max))))
956 (goto-char begin)
957 ;; Make it clickable...
958 (add-text-properties begin end `(keymap ,mh-hidden-header-keymap
959 mouse-face highlight))
960 (unwind-protect
961 (cond ((or (and (not arg)
962 (text-property-any begin end 'invisible 'vanish))
963 (and (numberp arg)
964 (>= arg 0))
965 (and (eq arg 'long)
966 (> (mh-line-beginning-position 5) end)))
967 (remove-text-properties begin end '(invisible nil))
968 (search-forward ":" (mh-line-end-position) t)
969 (mh-letter-skip-leading-whitespace-in-header-field))
970 ;; XXX Redesign to make usable by user. Perhaps use a positive
971 ;; numeric prefix to make that many lines visible.
972 ((eq arg 'long)
973 (end-of-line 4)
974 (mh-letter-truncate-header-field end)
975 (beginning-of-line))
976 (t (end-of-line)
977 (mh-letter-truncate-header-field end)
978 (beginning-of-line)))
979 (set-buffer-modified-p modified-flag)))))
981 ;;;###mh-autoload
982 (defun mh-letter-skip-leading-whitespace-in-header-field ()
983 "Skip leading whitespace in a header field.
984 If the header field doesn't have at least one space after the
985 colon then a space character is added."
986 (let ((need-space t))
987 (while (memq (char-after) '(?\t ?\ ))
988 (forward-char)
989 (setq need-space nil))
990 (when need-space (insert " "))))
992 (defun mh-letter-truncate-header-field (end)
993 "Replace text from current line till END with an ellipsis.
994 If the current line is too long truncate a part of it as well."
995 (let ((max-len (min (window-width) 62)))
996 (when (> (+ (current-column) 4) max-len)
997 (backward-char (- (+ (current-column) 5) max-len)))
998 (when (> end (point))
999 (add-text-properties (point) end '(invisible vanish)))))
1001 ;;;###mh-autoload
1002 (defun mh-signature-separator-p ()
1003 "Return non-nil if buffer includes \"^-- $\"."
1004 (save-excursion
1005 (goto-char (point-min))
1006 (re-search-forward mh-signature-separator-regexp nil t)))
1008 (provide 'mh-utils)
1010 ;; Local Variables:
1011 ;; indent-tabs-mode: nil
1012 ;; sentence-end-double-space: nil
1013 ;; End:
1015 ;;; mh-utils.el ends here