]> code.delx.au - gnu-emacs/blob - lisp/mh-e/mh-utils.el
* mh-compat.el (mh-image-load-path-for-library): Move here from
[gnu-emacs] / lisp / mh-e / mh-utils.el
1 ;;; mh-utils.el --- MH-E general utilities
2
3 ;; Copyright (C) 1993, 1995, 1997,
4 ;; 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: Bill Wohler <wohler@newt.com>
7 ;; Maintainer: Bill Wohler <wohler@newt.com>
8 ;; Keywords: mail
9 ;; See: mh-e.el
10
11 ;; This file is part of GNU Emacs.
12
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 2, or (at your option)
16 ;; any later version.
17
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.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Commentary:
29
30 ;;; Change Log:
31
32 ;;; Code:
33
34 (require 'mh-e)
35 (mh-require-cl)
36
37 (require 'font-lock)
38
39 ;;; CL Replacements
40
41 ;;;###mh-autoload
42 (defun mh-search-from-end (char string)
43 "Return the position of last occurrence of CHAR in STRING.
44 If CHAR is not present in STRING then return nil. The function is
45 used in lieu of `search' in the CL package."
46 (loop for index from (1- (length string)) downto 0
47 when (equal (aref string index) char) return index
48 finally return nil))
49
50 \f
51
52 ;;; General Utilities
53
54 ;;;###mh-autoload
55 (defun mh-beginning-of-word (&optional n)
56 "Return position of the N th word backwards."
57 (unless n (setq n 1))
58 (let ((syntax-table (syntax-table)))
59 (unwind-protect
60 (save-excursion
61 (mh-mail-abbrev-make-syntax-table)
62 (set-syntax-table mail-abbrev-syntax-table)
63 (backward-word n)
64 (point))
65 (set-syntax-table syntax-table))))
66
67 ;;;###mh-autoload
68 (defun mh-colors-available-p ()
69 "Check if colors are available in the Emacs being used."
70 (or mh-xemacs-flag
71 (let ((color-cells (mh-display-color-cells)))
72 (and (numberp color-cells) (>= color-cells 8)))))
73
74 ;;;###mh-autoload
75 (defun mh-colors-in-use-p ()
76 "Check if colors are being used in the folder buffer."
77 (and mh-colors-available-flag font-lock-mode))
78
79 ;;;###mh-autoload
80 (defun mh-delete-line (lines)
81 "Delete the next LINES lines."
82 (delete-region (point) (progn (forward-line lines) (point))))
83
84 ;;;###mh-autoload
85 (defun mh-make-local-vars (&rest pairs)
86 "Initialize local variables according to the variable-value PAIRS."
87 (while pairs
88 (set (make-local-variable (car pairs)) (car (cdr pairs)))
89 (setq pairs (cdr (cdr pairs)))))
90
91 ;;;###mh-autoload
92 (defun mh-mapc (function list)
93 "Apply FUNCTION to each element of LIST for side effects only."
94 (while list
95 (funcall function (car list))
96 (setq list (cdr list))))
97
98 (defvar mh-pick-regexp-chars ".*$["
99 "List of special characters in pick regular expressions.")
100
101 ;;;###mh-autoload
102 (defun mh-quote-pick-expr (pick-expr)
103 "Quote `mh-pick-regexp-chars' in PICK-EXPR.
104 PICK-EXPR is a list of strings. Return nil if PICK-EXPR is nil."
105 (let ((quoted-pick-expr))
106 (dolist (string pick-expr)
107 (when (and string
108 (not (string-equal string "")))
109 (loop for i from 0 to (1- (length mh-pick-regexp-chars)) do
110 (let ((s (string ?\\ (aref mh-pick-regexp-chars i))))
111 (setq string (mh-replace-regexp-in-string s s string t t))))
112 (setq quoted-pick-expr (append quoted-pick-expr (list string)))))
113 quoted-pick-expr))
114
115 ;;;###mh-autoload
116 (defun mh-replace-string (old new)
117 "Replace all occurrences of OLD with NEW in the current buffer.
118 Ignores case when searching for OLD."
119 (goto-char (point-min))
120 (let ((case-fold-search t))
121 (while (search-forward old nil t)
122 (replace-match new t t))))
123
124 \f
125
126 ;;; Logo Display
127
128 (defvar mh-logo-cache nil)
129
130 ;;;###mh-autoload
131 (defun mh-logo-display ()
132 "Modify mode line to display MH-E logo."
133 (mh-do-in-gnu-emacs
134 (let ((load-path (mh-image-load-path-for-library
135 "mh-e" "mh-logo.xpm" 'load-path))
136 (image-load-path (mh-image-load-path-for-library
137 "mh-e" "mh-logo.xpm" 'image-load-path)))
138 (add-text-properties
139 0 2
140 `(display ,(or mh-logo-cache
141 (setq mh-logo-cache
142 (mh-funcall-if-exists
143 find-image '((:type xpm :ascent center
144 :file "mh-logo.xpm"))))))
145 (car mode-line-buffer-identification))))
146 (mh-do-in-xemacs
147 (setq modeline-buffer-identification
148 (list
149 (if mh-modeline-glyph
150 (cons modeline-buffer-id-left-extent mh-modeline-glyph)
151 (cons modeline-buffer-id-left-extent "XEmacs%N:"))
152 (cons modeline-buffer-id-right-extent " %17b")))))
153
154 \f
155
156 ;;; Read MH Profile
157
158 (defvar mh-find-path-run nil
159 "Non-nil if `mh-find-path' has been run already.
160 Do not access this variable; `mh-find-path' already uses it to
161 avoid running more than once.")
162
163 ;;;###mh-autoload
164 (defun mh-find-path ()
165 "Set variables from user's MH profile.
166
167 This function sets `mh-user-path' from your \"Path:\" MH profile
168 component (but defaults to \"Mail\" if one isn't present),
169 `mh-draft-folder' from \"Draft-Folder:\", `mh-unseen-seq' from
170 \"Unseen-Sequence:\", `mh-previous-seq' from
171 \"Previous-Sequence:\", and `mh-inbox' from \"Inbox:\" (defaults
172 to \"+inbox\").
173
174 The hook `mh-find-path-hook' is run after these variables have
175 been set. This hook can be used the change the value of these
176 variables if you need to run with different values between MH and
177 MH-E."
178 (unless mh-find-path-run
179 ;; Sanity checks.
180 (if (and (getenv "MH")
181 (not (file-readable-p (getenv "MH"))))
182 (error "MH environment variable contains unreadable file %s"
183 (getenv "MH")))
184 (if (null (mh-variants))
185 (error "Install MH and run install-mh before running MH-E"))
186 (let ((profile "~/.mh_profile"))
187 (if (not (file-readable-p 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)))
222
223 \f
224
225 ;;; Help Functions
226
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 ""))
233
234 (defvar mh-help-default nil
235 "Mode to use if messages are not present for the current mode.")
236
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'.")
241
242 ;;;###mh-autoload
243 (defun mh-set-help (messages &optional default)
244 "Set help messages.
245
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.
252
253 The substitutions described in `substitute-command-keys' are performed as
254 well.
255
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)))
261
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)))
278
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 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)))
292
293 \f
294
295 ;;; Message Number Utilities
296
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))
321
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)
329 t)
330 (if (numberp msg2)
331 nil
332 (string-lessp msg2 msg1))))
333
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)))
340
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 (error "Cursor not pointing to message"))
353 (t nil))))
354
355 (add-to-list 'debug-ignored-errors "^Cursor not pointing to message$")
356
357 \f
358
359 ;;; Folder Cache and Access
360
361 (defvar mh-sub-folders-cache (make-hash-table :test #'equal))
362 (defvar mh-current-folder-name nil)
363 (defvar mh-flists-partial-line "")
364 (defvar mh-flists-process nil)
365
366 ;;;###mh-autoload
367 (defun mh-clear-sub-folders-cache ()
368 "Clear `mh-sub-folders-cache'."
369 (clrhash mh-sub-folders-cache))
370
371 ;; Initialize mh-sub-folders-cache...
372 (defun mh-collect-folder-names ()
373 "Collect folder names by running \"folders\"."
374 (unless mh-flists-process
375 (setq mh-flists-process
376 (mh-exec-cmd-daemon "folders" 'mh-collect-folder-names-filter
377 "-recurse" "-fast"))))
378
379 (defun mh-collect-folder-names-filter (process output)
380 "Read folder names.
381 PROCESS is the flists process that was run to collect folder
382 names and the function is called when OUTPUT is available."
383 (let ((position 0)
384 (prevailing-match-data (match-data))
385 line-end folder)
386 (unwind-protect
387 (while (setq line-end (string-match "\n" output position))
388 (setq folder (format "+%s%s"
389 mh-flists-partial-line
390 (substring output position line-end)))
391 (setq mh-flists-partial-line "")
392 (unless (equal (aref folder 1) ?.)
393 (mh-populate-sub-folders-cache folder))
394 (setq position (1+ line-end)))
395 (set-match-data prevailing-match-data))
396 (setq mh-flists-partial-line (substring output position))))
397
398 (defun mh-populate-sub-folders-cache (folder)
399 "Tell `mh-sub-folders-cache' about FOLDER."
400 (let* ((last-slash (mh-search-from-end ?/ folder))
401 (child1 (substring folder (1+ (or last-slash 0))))
402 (parent (and last-slash (substring folder 0 last-slash)))
403 (parent-slash (and parent (mh-search-from-end ?/ parent)))
404 (child2 (and parent (substring parent (1+ (or parent-slash 0)))))
405 (grand-parent (and parent-slash (substring parent 0 parent-slash)))
406 (cache-entry (gethash parent mh-sub-folders-cache)))
407 (unless (loop for x in cache-entry when (equal (car x) child1) return t
408 finally return nil)
409 (push (list child1) cache-entry)
410 (setf (gethash parent mh-sub-folders-cache)
411 (sort cache-entry (lambda (x y) (string< (car x) (car y)))))
412 (when parent
413 (loop for x in (gethash grand-parent mh-sub-folders-cache)
414 when (equal (car x) child2)
415 do (progn (setf (cdr x) t) (return)))))))
416
417 (defun mh-normalize-folder-name (folder &optional empty-string-okay
418 dont-remove-trailing-slash
419 return-nil-if-folder-empty)
420 "Normalizes FOLDER name.
421
422 Makes sure that two '/' characters never occur next to each
423 other. Also all occurrences of \"..\" and \".\" are suitably
424 processed. So \"+inbox/../news\" will be normalized to \"+news\".
425
426 If optional argument EMPTY-STRING-OKAY is nil then a '+' is added
427 at the front if FOLDER lacks one. If non-nil and FOLDER is the
428 empty string then nothing is added.
429
430 If optional argument DONT-REMOVE-TRAILING-SLASH is non-nil then a
431 trailing '/' if present is retained (if present), otherwise it is
432 removed.
433
434 If optional argument RETURN-NIL-IF-FOLDER-EMPTY is non-nil, then
435 return nil if FOLDER is \"\" or \"+\". This is useful when
436 normalizing the folder for the \"folders\" command which displays
437 the directories in / if passed \"+\". This is usually not
438 desired. If this argument is non-nil, then EMPTY-STRING-OKAY has
439 no effect."
440 (cond
441 ((if (and (or (equal folder "+") (equal folder ""))
442 return-nil-if-folder-empty)
443 (setq folder nil)))
444 ((stringp folder)
445 ;; Replace two or more consecutive '/' characters with a single '/'
446 (while (string-match "//" folder)
447 (setq folder (replace-match "/" nil t folder)))
448 (let* ((length (length folder))
449 (trailing-slash-present (and (> length 0)
450 (equal (aref folder (1- length)) ?/)))
451 (leading-slash-present (and (> length 0)
452 (equal (aref folder 0) ?/))))
453 (when (and (> length 0) (equal (aref folder 0) ?@)
454 (stringp mh-current-folder-name))
455 (setq folder (format "%s/%s/" mh-current-folder-name
456 (substring folder 1))))
457 ;; XXX: Purge empty strings from the list that split-string
458 ;; returns. In XEmacs, (split-string "+foo/" "/") returns
459 ;; ("+foo" "") while in GNU Emacs it returns ("+foo"). In the
460 ;; code it is assumed that the components list has no empty
461 ;; strings.
462 (let ((components (delete "" (split-string folder "/")))
463 (result ()))
464 ;; Remove .. and . from the pathname.
465 (dolist (component components)
466 (cond ((and (equal component "..") result)
467 (pop result))
468 ((equal component ".."))
469 ((equal component "."))
470 (t (push component result))))
471 (setq folder "")
472 (dolist (component result)
473 (setq folder (concat component "/" folder)))
474 ;; Remove trailing '/' if needed.
475 (unless (and trailing-slash-present dont-remove-trailing-slash)
476 (when (not (equal folder ""))
477 (setq folder (substring folder 0 (1- (length folder))))))
478 (when leading-slash-present
479 (setq folder (concat "/" folder)))))
480 (cond ((and empty-string-okay (equal folder "")))
481 ((equal folder "")
482 (setq folder "+"))
483 ((not (equal (aref folder 0) ?+))
484 (setq folder (concat "+" folder))))))
485 folder)
486
487 (defmacro mh-children-p (folder)
488 "Return t if FOLDER from sub-folders cache has children.
489 The car of folder is the name, and the cdr is either t or some
490 sort of count that I do not understand. It's too small to be the
491 number of messages in the sub-folders and too large to be the
492 number of sub-folders. XXX"
493 `(if (cdr ,folder)
494 t
495 nil))
496
497 ;;;###mh-autoload
498 (defun mh-folder-list (folder)
499 "Return FOLDER and its descendents.
500 FOLDER may have a + prefix. Returns a list of strings without the
501 + prefix. If FOLDER is nil, then all folders are considered. For
502 example, if your Mail directory only contains the folders +inbox,
503 +outbox, +lists, and +lists/mh-e, then
504
505 (mh-folder-list nil)
506 => (\"inbox\" \"lists\" \"lists/mh-e\" \"outbox\")
507 (mh-folder-list \"+lists\")
508 => (\"lists/mh-e\")
509
510 Respects the value of `mh-recursive-folders-flag'. If this flag
511 is nil, and the sub-folders have not been explicitly viewed, then
512 they will not be returned."
513 (let ((folder-list))
514 ;; Normalize folder. Strip leading + and trailing slash(es). If no
515 ;; folder is specified, ensure it is nil to avoid adding the
516 ;; folder to the folder-list and adding a slash to it.
517 (when folder
518 (setq folder (mh-replace-regexp-in-string "^\+" "" folder))
519 (setq folder (mh-replace-regexp-in-string "/+$" "" folder))
520 (if (equal folder "")
521 (setq folder nil)))
522 ;; Add provided folder to list, unless all folders are asked for.
523 ;; Then append slash to separate sub-folders.
524 (unless (null folder)
525 (setq folder-list (list folder))
526 (setq folder (concat folder "/")))
527 (loop for f in (mh-sub-folders folder) do
528 (setq folder-list
529 (append folder-list
530 (if (mh-children-p f)
531 (mh-folder-list (concat folder (car f)))
532 (list (concat folder (car f)))))))
533 folder-list))
534
535 ;;;###mh-autoload
536 (defun mh-sub-folders (folder &optional add-trailing-slash-flag)
537 "Find the subfolders of FOLDER.
538 The function avoids running folders unnecessarily by caching the
539 results of the actual folders call.
540
541 If optional argument ADD-TRAILING-SLASH-FLAG is non-nil then a
542 slash is added to each of the sub-folder names that may have
543 nested folders within them."
544 (let* ((folder (mh-normalize-folder-name folder nil nil t))
545 (match (gethash folder mh-sub-folders-cache 'no-result))
546 (sub-folders (cond ((eq match 'no-result)
547 (setf (gethash folder mh-sub-folders-cache)
548 (mh-sub-folders-actual folder)))
549 (t match))))
550 (if add-trailing-slash-flag
551 (mapcar #'(lambda (x)
552 (if (cdr x) (cons (concat (car x) "/") (cdr x)) x))
553 sub-folders)
554 sub-folders)))
555
556 (defun mh-sub-folders-actual (folder)
557 "Execute the command folders to return the sub-folders of FOLDER.
558 Filters out the folder names that start with \".\" so that
559 directories that aren't usually mail folders are hidden."
560 (let ((arg-list `(,(expand-file-name "folders" mh-progs)
561 nil (t nil) nil "-noheader" "-norecurse" "-nototal"
562 ,@(if (stringp folder) (list folder) ())))
563 (results ())
564 (current-folder (concat
565 (with-temp-buffer
566 (call-process (expand-file-name "folder" mh-progs)
567 nil '(t nil) nil "-fast")
568 (buffer-substring (point-min) (1- (point-max))))
569 "+")))
570 (with-temp-buffer
571 (apply #'call-process arg-list)
572 (goto-char (point-min))
573 (while (not (and (eolp) (bolp)))
574 (goto-char (mh-line-end-position))
575 (let ((start-pos (mh-line-beginning-position))
576 (has-pos (search-backward " has "
577 (mh-line-beginning-position) t)))
578 (when (integerp has-pos)
579 (while (equal (char-after has-pos) ? )
580 (decf has-pos))
581 (incf has-pos)
582 (while (equal (char-after start-pos) ? )
583 (incf start-pos))
584 (let* ((name (buffer-substring start-pos has-pos))
585 (first-char (aref name 0))
586 (last-char (aref name (1- (length name)))))
587 (unless (member first-char '(?. ?# ?,))
588 (when (and (equal last-char ?+) (equal name current-folder))
589 (setq name (substring name 0 (1- (length name)))))
590 (push
591 (cons name
592 (search-forward "(others)" (mh-line-end-position) t))
593 results))))
594 (forward-line 1))))
595 (setq results (nreverse results))
596 (when (stringp folder)
597 (setq results (cdr results))
598 (let ((folder-name-len (length (format "%s/" (substring folder 1)))))
599 (setq results (mapcar (lambda (f)
600 (cons (substring (car f) folder-name-len)
601 (cdr f)))
602 results))))
603 results))
604
605 ;;;###mh-autoload
606 (defun mh-remove-from-sub-folders-cache (folder)
607 "Remove FOLDER and its parent from `mh-sub-folders-cache'.
608 FOLDER should be unconditionally removed from the cache. Also the
609 last ancestor of FOLDER present in the cache must be removed as
610 well.
611
612 To see why this is needed assume we have a folder +foo which has
613 a single sub-folder qux. Now we create the folder +foo/bar/baz.
614 Here we will need to invalidate the cached sub-folders of +foo,
615 otherwise completion on +foo won't tell us about the option
616 +foo/bar!"
617 (remhash folder mh-sub-folders-cache)
618 (block ancestor-found
619 (let ((parent folder)
620 (one-ancestor-found nil)
621 last-slash)
622 (while (setq last-slash (mh-search-from-end ?/ parent))
623 (setq parent (substring parent 0 last-slash))
624 (unless (eq (gethash parent mh-sub-folders-cache 'none) 'none)
625 (remhash parent mh-sub-folders-cache)
626 (if one-ancestor-found
627 (return-from ancestor-found)
628 (setq one-ancestor-found t))))
629 (remhash nil mh-sub-folders-cache))))
630
631 \f
632
633 ;;; Folder Utilities
634
635 ;;;###mh-autoload
636 (defun mh-folder-name-p (name)
637 "Return non-nil if NAME is the name of a folder.
638 A name (a string or symbol) can be a folder name if it begins
639 with \"+\"."
640 (if (symbolp name)
641 (eq (aref (symbol-name name) 0) ?+)
642 (and (> (length name) 0)
643 (eq (aref name 0) ?+))))
644
645 ;;;###mh-autoload
646 (defun mh-expand-file-name (filename &optional default)
647 "Expand FILENAME like `expand-file-name', but also handle MH folder names.
648 Any filename that starts with '+' is treated as a folder name.
649 See `expand-file-name' for description of DEFAULT."
650 (if (mh-folder-name-p filename)
651 (expand-file-name (substring filename 1) mh-user-path)
652 (expand-file-name filename default)))
653
654 (defvar mh-folder-hist nil)
655
656 ;; Shush compiler.
657 (eval-when-compile (defvar mh-speed-flists-cache))
658
659 (defvar mh-allow-root-folder-flag nil
660 "Non-nil means \"+\" is an acceptable folder name.
661 This variable is used to communicate with
662 `mh-folder-completion-function'. That function can have exactly
663 three arguments so we bind this variable to t or nil.
664
665 This variable should never be set.")
666
667 (defvar mh-folder-completion-map (copy-keymap minibuffer-local-completion-map))
668 (define-key mh-folder-completion-map " " 'minibuffer-complete) ;Why???
669
670 (defvar mh-speed-flists-inhibit-flag nil)
671
672 ;;;###mh-autoload
673 (defun mh-speed-flists-active-p ()
674 "Check if speedbar is running with message counts enabled."
675 (and (featurep 'mh-speed)
676 (not mh-speed-flists-inhibit-flag)
677 (> (hash-table-count mh-speed-flists-cache) 0)))
678
679 ;;;###mh-autoload
680 (defun mh-folder-completion-function (name predicate flag)
681 "Programmable completion for folder names.
682 NAME is the partial folder name that has been input. PREDICATE if
683 non-nil is a function that is used to filter the possible choices
684 and FLAG determines whether the completion is over."
685 (let* ((orig-name name)
686 (name (mh-normalize-folder-name name nil t))
687 (last-slash (mh-search-from-end ?/ name))
688 (last-complete (if last-slash (substring name 0 last-slash) nil))
689 (remainder (cond (last-complete (substring name (1+ last-slash)))
690 ((and (> (length name) 0) (equal (aref name 0) ?+))
691 (substring name 1))
692 (t ""))))
693 (cond ((eq flag nil)
694 (let ((try-res (try-completion
695 name
696 (mapcar (lambda (x)
697 (cons (if (not last-complete)
698 (concat "+" (car x))
699 (concat last-complete "/" (car x)))
700 (cdr x)))
701 (mh-sub-folders last-complete t))
702 predicate)))
703 (cond ((eq try-res nil) nil)
704 ((and (eq try-res t) (equal name orig-name)) t)
705 ((eq try-res t) name)
706 (t try-res))))
707 ((eq flag t)
708 (all-completions
709 remainder (mh-sub-folders last-complete t) predicate))
710 ((eq flag 'lambda)
711 (let ((path (concat mh-user-path
712 (substring (mh-normalize-folder-name name) 1))))
713 (cond (mh-allow-root-folder-flag (file-exists-p path))
714 ((equal path mh-user-path) nil)
715 (t (file-exists-p path))))))))
716
717 ;; Shush compiler.
718 (eval-when-compile
719 (mh-do-in-xemacs
720 (defvar completion-root-regexp)
721 (defvar minibuffer-completing-file-name)))
722
723 (defun mh-folder-completing-read (prompt default allow-root-folder-flag)
724 "Read folder name with PROMPT and default result DEFAULT.
725 If ALLOW-ROOT-FOLDER-FLAG is non-nil then \"+\" is allowed to be
726 a folder name corresponding to `mh-user-path'."
727 (mh-normalize-folder-name
728 (let ((minibuffer-completing-file-name t)
729 (completion-root-regexp "^[+/]")
730 (minibuffer-local-completion-map mh-folder-completion-map)
731 (mh-allow-root-folder-flag allow-root-folder-flag))
732 (completing-read prompt 'mh-folder-completion-function nil nil nil
733 'mh-folder-hist default))
734 t))
735
736 ;;;###mh-autoload
737 (defun mh-prompt-for-folder (prompt default can-create
738 &optional default-string allow-root-folder-flag)
739 "Prompt for a folder name with PROMPT.
740 Returns the folder's name as a string. DEFAULT is used if the
741 folder exists and the user types return. If the CAN-CREATE flag
742 is t, then a folder is created if it doesn't already exist. If
743 optional argument DEFAULT-STRING is non-nil, use it in the prompt
744 instead of DEFAULT. If ALLOW-ROOT-FOLDER-FLAG is non-nil then the
745 function will accept the folder +, which means all folders when
746 used in searching."
747 (if (null default)
748 (setq default ""))
749 (let* ((default-string (cond (default-string (format " (default %s)" default-string))
750 ((equal "" default) "")
751 (t (format " (default %s)" default))))
752 (prompt (format "%s folder%s: " prompt default-string))
753 (mh-current-folder-name mh-current-folder)
754 read-name folder-name)
755 (while (and (setq read-name (mh-folder-completing-read
756 prompt default allow-root-folder-flag))
757 (equal read-name "")
758 (equal default "")))
759 (cond ((or (equal read-name "")
760 (and (equal read-name "+") (not allow-root-folder-flag)))
761 (setq read-name default))
762 ((not (mh-folder-name-p read-name))
763 (setq read-name (format "+%s" read-name))))
764 (if (or (not read-name) (equal "" read-name))
765 (error "No folder specified"))
766 (setq folder-name read-name)
767 (cond ((and (> (length folder-name) 0)
768 (eq (aref folder-name (1- (length folder-name))) ?/))
769 (setq folder-name (substring folder-name 0 -1))))
770 (let* ((last-slash (mh-search-from-end ?/ folder-name))
771 (parent (and last-slash (substring folder-name 0 last-slash)))
772 (child (if last-slash
773 (substring folder-name (1+ last-slash))
774 (substring folder-name 1))))
775 (unless (member child
776 (mapcar #'car (gethash parent mh-sub-folders-cache)))
777 (mh-remove-from-sub-folders-cache folder-name)))
778 (let ((new-file-flag
779 (not (file-exists-p (mh-expand-file-name folder-name)))))
780 (cond ((and new-file-flag
781 can-create
782 (y-or-n-p
783 (format "Folder %s does not exist. Create it? "
784 folder-name)))
785 (message "Creating %s" folder-name)
786 (mh-exec-cmd-error nil "folder" folder-name)
787 (mh-remove-from-sub-folders-cache folder-name)
788 (when (boundp 'mh-speed-folder-map)
789 (mh-speed-add-folder folder-name))
790 (message "Creating %s...done" folder-name))
791 (new-file-flag
792 (error "Folder %s does not exist" folder-name))
793 ((not (file-directory-p (mh-expand-file-name folder-name)))
794 (error "%s is not a directory"
795 (mh-expand-file-name folder-name)))))
796 folder-name))
797
798 \f
799
800 ;;; Message Utilities
801
802 ;; Functions that would ordinarily be in mh-letter.el that are needed
803 ;; by mh-show.el are found here in order to prevent the loading of
804 ;; mh-letter.el until a message is actually composed.
805
806 ;;;###mh-autoload
807 (defun mh-in-header-p ()
808 "Return non-nil if the point is in the header of a draft message."
809 (< (point) (mh-mail-header-end)))
810
811 ;;;###mh-autoload
812 (defun mh-extract-from-header-value ()
813 "Extract From: string from header."
814 (save-excursion
815 (if (not (mh-goto-header-field "From:"))
816 nil
817 (skip-chars-forward " \t")
818 (buffer-substring-no-properties
819 (point) (progn (mh-header-field-end)(point))))))
820
821 ;;;###mh-autoload
822 (defun mh-get-header-field (field)
823 "Find and return the body of FIELD in the mail header.
824 Returns the empty string if the field is not in the header of the
825 current buffer."
826 (if (mh-goto-header-field field)
827 (progn
828 (skip-chars-forward " \t") ;strip leading white space in body
829 (let ((start (point)))
830 (mh-header-field-end)
831 (buffer-substring-no-properties start (point))))
832 ""))
833
834 ;;;###mh-autoload
835 (defun mh-goto-header-field (field)
836 "Move to FIELD in the message header.
837 Move to the end of the FIELD name, which should end in a colon.
838 Returns t if found, nil if not."
839 (goto-char (point-min))
840 (let ((case-fold-search t)
841 (headers-end (save-excursion
842 (mh-goto-header-end 0)
843 (point))))
844 (re-search-forward (format "^%s" field) headers-end t)))
845
846 ;;;###mh-autoload
847 (defun mh-goto-header-end (arg)
848 "Move the cursor ARG lines after the header."
849 (if (re-search-forward "^-*$" nil nil)
850 (forward-line arg)))
851
852 ;;;###mh-autoload
853 (defun mh-mail-header-end ()
854 "Substitute for `mail-header-end' that doesn't widen the buffer.
855
856 In MH-E we frequently need to find the end of headers in nested
857 messages, where the buffer has been narrowed. This function works
858 in this situation."
859 (save-excursion
860 ;; XXX: The following replaces a call to rfc822-goto-eoh. Occasionally,
861 ;; mail headers that MH-E has to read contains lines of the form:
862 ;; From xxx@yyy Mon May 10 11:48:07 2004
863 ;; In this situation, rfc822-goto-eoh doesn't go to the end of the
864 ;; header. The replacement allows From_ lines in the mail header.
865 (goto-char (point-min))
866 (loop for p = (re-search-forward
867 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
868 do (cond ((null p) (return))
869 (t (goto-char (match-beginning 0))
870 (unless (looking-at "From ") (return))
871 (goto-char p))))
872 (point)))
873
874 ;;;###mh-autoload
875 (defun mh-header-field-beginning ()
876 "Move to the beginning of the current header field.
877 Handles RFC 822 continuation lines."
878 (beginning-of-line)
879 (while (looking-at "^[ \t]")
880 (forward-line -1)))
881
882 ;;;###mh-autoload
883 (defun mh-header-field-end ()
884 "Move to the end of the current header field.
885 Handles RFC 822 continuation lines."
886 (forward-line 1)
887 (while (looking-at "^[ \t]")
888 (forward-line 1))
889 (backward-char 1)) ;to end of previous line
890
891 ;;;###mh-autoload
892 (defun mh-letter-hide-all-skipped-fields ()
893 "Hide all skipped fields."
894 (save-excursion
895 (goto-char (point-min))
896 (save-restriction
897 (narrow-to-region (point) (mh-mail-header-end))
898 (while (re-search-forward mh-letter-header-field-regexp nil t)
899 (if (mh-letter-skipped-header-field-p (match-string 1))
900 (mh-letter-toggle-header-field-display -1)
901 (mh-letter-toggle-header-field-display 'long))
902 (beginning-of-line 2)))))
903
904 ;;;###mh-autoload
905 (defun mh-letter-skipped-header-field-p (field)
906 "Check if FIELD is to be skipped."
907 (let ((field (downcase field)))
908 (loop for x in mh-compose-skipped-header-fields
909 when (equal (downcase x) field) return t
910 finally return nil)))
911
912 (defvar mh-hidden-header-keymap
913 (let ((map (make-sparse-keymap)))
914 (mh-do-in-gnu-emacs
915 (define-key map [mouse-2] 'mh-letter-toggle-header-field-display-button))
916 (mh-do-in-xemacs
917 (define-key map '(button2)
918 'mh-letter-toggle-header-field-display-button))
919 map))
920
921 ;;;###mh-autoload
922 (defun mh-letter-toggle-header-field-display (arg)
923 "Toggle display of header field at point.
924
925 Use this command to display truncated header fields. This command
926 is a toggle so entering it again will hide the field. This
927 command takes a prefix argument ARG: if negative then the field
928 is hidden, if positive then the field is displayed."
929 (interactive (list nil))
930 (when (and (mh-in-header-p)
931 (progn
932 (end-of-line)
933 (re-search-backward mh-letter-header-field-regexp nil t)))
934 (let ((buffer-read-only nil)
935 (modified-flag (buffer-modified-p))
936 (begin (point))
937 end)
938 (end-of-line)
939 (setq end (1- (if (re-search-forward "^[^ \t]" nil t)
940 (match-beginning 0)
941 (point-max))))
942 (goto-char begin)
943 ;; Make it clickable...
944 (add-text-properties begin end `(keymap ,mh-hidden-header-keymap
945 mouse-face highlight))
946 (unwind-protect
947 (cond ((or (and (not arg)
948 (text-property-any begin end 'invisible 'vanish))
949 (and (numberp arg)
950 (>= arg 0))
951 (and (eq arg 'long)
952 (> (mh-line-beginning-position 5) end)))
953 (remove-text-properties begin end '(invisible nil))
954 (search-forward ":" (mh-line-end-position) t)
955 (mh-letter-skip-leading-whitespace-in-header-field))
956 ;; XXX Redesign to make usable by user. Perhaps use a positive
957 ;; numeric prefix to make that many lines visible.
958 ((eq arg 'long)
959 (end-of-line 4)
960 (mh-letter-truncate-header-field end)
961 (beginning-of-line))
962 (t (end-of-line)
963 (mh-letter-truncate-header-field end)
964 (beginning-of-line)))
965 (set-buffer-modified-p modified-flag)))))
966
967 ;;;###mh-autoload
968 (defun mh-letter-skip-leading-whitespace-in-header-field ()
969 "Skip leading whitespace in a header field.
970 If the header field doesn't have at least one space after the
971 colon then a space character is added."
972 (let ((need-space t))
973 (while (memq (char-after) '(?\t ?\ ))
974 (forward-char)
975 (setq need-space nil))
976 (when need-space (insert " "))))
977
978 (defun mh-letter-truncate-header-field (end)
979 "Replace text from current line till END with an ellipsis.
980 If the current line is too long truncate a part of it as well."
981 (let ((max-len (min (window-width) 62)))
982 (when (> (+ (current-column) 4) max-len)
983 (backward-char (- (+ (current-column) 5) max-len)))
984 (when (> end (point))
985 (add-text-properties (point) end '(invisible vanish)))))
986
987 ;;;###mh-autoload
988 (defun mh-signature-separator-p ()
989 "Return non-nil if buffer includes \"^-- $\"."
990 (save-excursion
991 (goto-char (point-min))
992 (re-search-forward mh-signature-separator-regexp nil t)))
993
994 (provide 'mh-utils)
995
996 ;; Local Variables:
997 ;; indent-tabs-mode: nil
998 ;; sentence-end-double-space: nil
999 ;; End:
1000
1001 ;; arch-tag: 1af39fdf-f66f-4b06-9b48-18a7656c8e36
1002 ;;; mh-utils.el ends here