mh-utils.el 39 KB

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