Refill some long/short copyright headers.
[bpt/emacs.git] / lisp / mh-e / mh-search.el
CommitLineData
dda00b2c 1;;; mh-search --- MH-Search mode
bdcfe844 2
95df8112 3;; Copyright (C) 1993, 1995, 2001-2011 Free Software Foundation, Inc.
bdcfe844 4
44140699 5;; Author: Indexed search by Satyaki Das <satyaki@theforce.stanford.edu>
bdcfe844
BW
6;; Maintainer: Bill Wohler <wohler@newt.com>
7;; Keywords: mail
8;; See: mh-e.el
9
10;; This file is part of GNU Emacs.
11
5e809f55 12;; GNU Emacs is free software: you can redistribute it and/or modify
bdcfe844 13;; it under the terms of the GNU General Public License as published by
5e809f55
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
bdcfe844
BW
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
5e809f55 19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
bdcfe844
BW
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
5e809f55 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
bdcfe844
BW
24
25;;; Commentary:
26
dda00b2c
BW
27;; Mode used to compose search criteria.
28
cee9f5c6
BW
29;; (1) The following search engines are supported:
30;; swish++
31;; swish-e
32;; mairix
33;; namazu
34;; pick
35;; grep
dda00b2c 36
44140699
BW
37;; (2) To use this package, you first have to build an index. Please
38;; read the documentation for `mh-search' to get started. That
39;; documentation will direct you to the specific instructions for
a4d7cec3 40;; your particular searcher.
bdcfe844
BW
41
42;;; Change Log:
43
bdcfe844
BW
44;;; Code:
45
dda00b2c 46(require 'mh-e)
a66894d8 47(mh-require-cl)
7094eefe 48
44140699 49(require 'gnus-util)
dda00b2c 50(require 'imenu)
bdcfe844 51
a4d7cec3
BW
52(defvar mh-searcher nil
53 "Cached value of chosen search program.")
44140699 54
a4d7cec3 55(defvar mh-search-function nil
bdcfe844 56 "Function which executes the search program.")
44140699 57
a4d7cec3 58(defvar mh-search-next-result-function nil
11db987f
BW
59 "Function to parse the next line of output.
60Expected to return a list of three strings: name of the folder,
61message number, and optionally the match.")
44140699 62
a4d7cec3 63(defvar mh-search-regexp-builder nil
3d7ca223 64 "Function used to construct search regexp.")
bdcfe844 65
c3d9274a
BW
66(defvar mh-index-folder "+mhe-index"
67 "Folder that contains the folders resulting from the index searches.")
68
44140699
BW
69(defvar mh-flists-results-folder "sequence"
70 "Subfolder for `mh-index-folder' where flists output is placed.")
c3d9274a 71
44140699 72(defvar mh-flists-sequence)
c3d9274a 73
44140699 74(defvar mh-flists-called-flag nil)
c3d9274a 75
44140699 76\f
c3d9274a 77
dda00b2c 78;;; MH-Folder Commands
bdcfe844 79
44140699 80;;;###mh-autoload
be397698
BW
81(defun mh-search (folder search-regexp
82 &optional redo-search-flag window-config)
44140699
BW
83 "Search your MH mail.
84
a4d7cec3
BW
85This command helps you find messages in your entire corpus of
86mail. You can search for messages to or from a particular person
87or about a particular subject. In fact, you can also search for
88messages containing selected strings in any arbitrary header
89field or any string found within the messages.
44140699 90
a4d7cec3
BW
91Out of the box, MH-E uses \"pick\" to find messages. With a
92little extra effort, you can set an indexing program which
93rewards you with extremely quick results. The drawback is that
94sometimes the index does not contain the words you're looking
95for. You can still use \"pick\" in these situations.
44140699
BW
96
97You are prompted for the FOLDER to search. This can be \"all\" to
a4d7cec3
BW
98search all folders. Note that the search works recursively on the
99listed folder.
44140699
BW
100
101Next, an MH-Search buffer appears where you can enter search
a4d7cec3 102criteria SEARCH-REGEXP.
44140699
BW
103
104 From:
105 To:
106 Cc:
107 Date:
108 Subject:
109 --------
110
111Edit this template by entering your search criteria in an
112appropriate header field that is already there, or create a new
113field yourself. If the string you're looking for could be
114anywhere in a message, then place the string underneath the row
115of dashes.
116
44140699
BW
117As an example, let's say that we want to find messages from
118Ginnean about horseback riding in the Kosciusko National
119Park (Australia) during January, 1994. Normally we would start
120with a broad search and narrow it down if necessary to produce a
121manageable amount of data, but we'll cut to the chase and create
a4d7cec3 122a fairly restrictive set of criteria as follows:\\<mh-search-mode-map>
44140699
BW
123
124 From: ginnean
125 To:
126 Cc:
127 Date: Jan 1994
128 Subject:
129 --------
130 horse
131 kosciusko
132
133As with MH-Letter mode, MH-Search provides commands like
a4d7cec3 134\\[mh-to-field] to help you fill in the blanks.\\<mh-folder-mode-map>
44140699
BW
135
136If you find that you do the same thing over and over when editing
137the search template, you may wish to bind some shortcuts to keys.
138This can be done with the variable `mh-search-mode-hook', which is
a4d7cec3 139called when \\[mh-search] is run on a new pattern.\\<mh-search-mode-map>
44140699
BW
140
141To perform the search, type \\[mh-index-do-search].
142
143Sometimes you're searching for text that is either not indexed,
144or hasn't been indexed yet. In this case you can override the
145default method with the pick method by running the command
146\\[mh-pick-do-search].
147
148The messages that are found are put in a temporary sub-folder of
149\"+mhe-index\" and are displayed in an MH-Folder buffer. This
150buffer is special because it displays messages from multiple
151folders; each set of messages from a given folder has a heading
152with the folder name.\\<mh-folder-mode-map>
bdcfe844 153
44140699 154The appearance of the heading can be modified by customizing the
a4d7cec3 155face `mh-search-folder'. You can jump back and forth between the
44140699
BW
156headings using the commands \\[mh-index-next-folder] and
157\\[mh-index-previous-folder].
c3d9274a 158
44140699
BW
159In addition, the command \\[mh-index-visit-folder] can be used to
160visit the folder of the message at point. Initially, only the
161messages that matched the search criteria are displayed in the
162folder. While the temporary buffer has its own set of message
163numbers, the actual messages numbers are shown in the visited
164folder. Thus, the command \\[mh-index-visit-folder] is useful to
165find the actual message number of an interesting message, or to
166view surrounding messages with the command \\[mh-rescan-folder].
bdcfe844 167
44140699 168Because this folder is temporary, you'll probably get in the
a4d7cec3
BW
169habit of killing it when you're done with \\[mh-kill-folder].
170
171You can regenerate the results by running this command with a
172prefix argument REDO-SEARCH-FLAG.
173
174Note: This command uses an \"X-MHE-Checksum:\" header field to
175cache the MD5 checksum of a message. This means that if an
176incoming message already contains an \"X-MHE-Checksum:\" field,
177that message might not be found by this command. The following
178\"procmail\" recipe avoids this problem by renaming the existing
179header field:
180
181 :0 wf
182 | formail -R \"X-MHE-Checksum\" \"X-Old-MHE-Checksum\"
bdcfe844 183
a4d7cec3 184Configuring Indexed Searches
2dcf34f9 185
44140699 186The command \\[mh-search] runs the command defined by the option
a4d7cec3 187`mh-search-program'. The default value is \"Auto-detect\" which
44140699
BW
188means that MH-E will automatically choose one of \"swish++\",
189\"swish-e\", \"mairix\", \"namazu\", \"pick\" and \"grep\" in
190that order. If, for example, you have both \"swish++\" and
191\"mairix\" installed and you want to use \"mairix\", then you can
192set this option to \"mairix\".
c3d9274a 193
44140699 194The documentation for the following commands describe how to set
a4d7cec3 195up the various indexing programs to use with MH-E.
a66894d8 196
44140699
BW
197 - `mh-swish++-execute-search'
198 - `mh-swish-execute-search'
199 - `mh-mairix-execute-search'
200 - `mh-namazu-execute-search'
201 - `mh-pick-execute-search'
202 - `mh-grep-execute-search'
924df208 203
a4d7cec3
BW
204In a program, if FOLDER is \"+\" or nil, then mail in all folders
205are searched. Optional argument WINDOW-CONFIG stores the window
206configuration that will be restored after the user quits the
207folder containing the index search results."
bdcfe844 208 (interactive
a4d7cec3 209 (list (progn
191c8741 210 (mh-find-path)
a4d7cec3
BW
211 ;; Yes, we do want to call mh-search-choose every time in case the
212 ;; user has switched the searcher manually.
213 (unless (mh-search-choose (and current-prefix-arg
214 mh-index-previous-search
215 (cadr mh-index-previous-search)))
216 (error "No search program found"))
a66894d8
BW
217 (or (and current-prefix-arg mh-index-sequence-search-flag)
218 (and current-prefix-arg (car mh-index-previous-search))
3d7ca223 219 (mh-prompt-for-folder "Search" "+" nil "all" t)))
44140699 220 (or (and current-prefix-arg (caddr mh-index-previous-search))
a4d7cec3 221 mh-search-regexp-builder
44140699 222 (read-string (format "%s regexp: "
a4d7cec3
BW
223 (upcase-initials (symbol-name mh-searcher)))))
224 current-prefix-arg
44140699
BW
225 (if (and (not (and current-prefix-arg
226 (caddr mh-index-previous-search)))
a4d7cec3 227 mh-search-regexp-builder)
3d7ca223
BW
228 (current-window-configuration)
229 nil)))
be397698
BW
230 (block mh-search
231 ;; Redoing a sequence search?
232 (when (and redo-search-flag mh-index-data mh-index-sequence-search-flag
233 (not mh-flists-called-flag))
234 (let ((mh-flists-called-flag t))
235 (apply #'mh-index-sequenced-messages mh-index-previous-search))
236 (return-from mh-search))
237 ;; We have fancy query parsing.
238 (when (symbolp search-regexp)
239 (mh-search-folder folder window-config)
240 (return-from mh-search))
241 ;; Begin search proper.
242 (mh-checksum-choose)
243 (let ((result-count 0)
244 (old-window-config (or window-config mh-previous-window-config))
245 (previous-search mh-index-previous-search)
246 (index-folder (format "%s/%s" mh-index-folder
247 (mh-index-generate-pretty-name search-regexp))))
248 ;; Create a new folder for the search results or recreate the old one...
249 (if (and redo-search-flag mh-index-previous-search)
250 (let ((buffer-name (buffer-name (current-buffer))))
251 (mh-process-or-undo-commands buffer-name)
252 (save-excursion (mh-exec-cmd-quiet nil "rmf" buffer-name))
253 (mh-exec-cmd-quiet nil "folder" "-create" "-fast" buffer-name)
254 (setq index-folder buffer-name))
255 (setq index-folder (mh-index-new-folder index-folder search-regexp)))
256
257 (let ((folder-path (format "%s%s" mh-user-path (substring folder 1)))
258 (folder-results-map (make-hash-table :test #'equal))
259 (origin-map (make-hash-table :test #'equal)))
260 ;; Run search program...
261 (message "Executing %s... " mh-searcher)
262 (funcall mh-search-function folder-path search-regexp)
263
264 ;; Parse searcher output.
265 (message "Processing %s output... " mh-searcher)
266 (goto-char (point-min))
267 (loop for next-result = (funcall mh-search-next-result-function)
268 while next-result
269 do (unless (eq next-result 'error)
270 (unless (gethash (car next-result) folder-results-map)
271 (setf (gethash (car next-result) folder-results-map)
272 (make-hash-table :test #'equal)))
273 (setf (gethash (cadr next-result)
274 (gethash (car next-result) folder-results-map))
275 t)))
276
277 ;; Copy the search results over.
278 (maphash #'(lambda (folder msgs)
279 (let ((cur (car (mh-translate-range folder "cur")))
280 (msgs (sort (loop for msg being the hash-keys of msgs
281 collect msg)
282 #'<)))
283 (mh-exec-cmd "refile" msgs "-src" folder
284 "-link" index-folder)
285 ;; Restore cur to old value, that refile changed
286 (when cur
287 (mh-exec-cmd-quiet nil "mark" folder "-add" "-zero"
288 "-sequence"
289 "cur" (format "%s" cur)))
290 (loop for msg in msgs
291 do (incf result-count)
292 (setf (gethash result-count origin-map)
293 (cons folder msg)))))
294 folder-results-map)
295
296 ;; Vist the results folder.
297 (mh-visit-folder index-folder () (list folder-results-map origin-map))
298
299 (goto-char (point-min))
300 (forward-line)
301 (mh-update-sequences)
302 (mh-recenter nil)
303
304 ;; Update the speedbar, if needed.
305 (when (mh-speed-flists-active-p)
306 (mh-speed-flists t mh-current-folder))
307
308 ;; Maintain history.
309 (when (or (and redo-search-flag previous-search) window-config)
310 (setq mh-previous-window-config old-window-config))
311 (setq mh-index-previous-search (list folder mh-searcher search-regexp))
312
313 ;; Write out data to disk.
314 (unless mh-flists-called-flag (mh-index-write-data))
315
316 (message "%s found %s matches in %s folders"
317 (upcase-initials (symbol-name mh-searcher))
1937adc2 318 (loop for msg-hash being the hash-values of mh-index-data
be397698 319 sum (hash-table-count msg-hash))
1937adc2 320 (loop for msg-hash being the hash-values of mh-index-data
be397698 321 count (> (hash-table-count msg-hash) 0)))))))
c3d9274a 322
dda00b2c 323;; Shush compiler.
42f8c37f 324(defvar pick-folder) ; XEmacs
dda00b2c 325
44140699
BW
326(defun mh-search-folder (folder window-config)
327 "Search FOLDER for messages matching a pattern.
328
329In a program, argument WINDOW-CONFIG is the current window
330configuration and is used when the search folder is dismissed."
331 (interactive (list (mh-prompt-for-folder "Search" mh-current-folder nil nil t)
332 (current-window-configuration)))
333 (let ((pick-folder (if (equal folder "+") mh-current-folder folder)))
334 (switch-to-buffer-other-window "search-pattern")
335 (if (or (zerop (buffer-size))
336 (not (y-or-n-p "Reuse pattern? ")))
337 (mh-make-pick-template)
338 (message ""))
339 (mh-make-local-vars 'mh-current-folder folder
340 'mh-previous-window-config window-config)
341 (message "%s" (substitute-command-keys
342 (concat "Type \\[mh-index-do-search] to search messages, "
343 "\\[mh-pick-do-search] to use pick, "
344 "\\[mh-help] for help")))))
345
346(defun mh-make-pick-template ()
347 "Initialize the current buffer with a template for a pick pattern."
348 (let ((inhibit-read-only t)) (erase-buffer))
349 (insert "From: \n"
350 "To: \n"
351 "Cc: \n"
352 "Date: \n"
353 "Subject: \n"
354 "---------\n")
355 (mh-search-mode)
356 (goto-char (point-min))
357 (dotimes (i 5)
358 (add-text-properties (point) (1+ (point)) '(front-sticky t))
d5dc8c56
BW
359 (add-text-properties (- (mh-line-end-position) 2)
360 (1- (mh-line-end-position))
44140699 361 '(rear-nonsticky t))
d5dc8c56 362 (add-text-properties (point) (1- (mh-line-end-position)) '(read-only t))
44140699
BW
363 (forward-line))
364 (add-text-properties (point) (1+ (point)) '(front-sticky t))
d5dc8c56 365 (add-text-properties (point) (1- (mh-line-end-position)) '(read-only t))
44140699
BW
366 (goto-char (point-max)))
367
dda00b2c
BW
368;; Sequence Searches
369
a4d7cec3 370;;;###mh-autoload
dda00b2c
BW
371(defun mh-index-new-messages (folders)
372 "Display unseen messages.
373
374If you use a program such as \"procmail\" to use \"rcvstore\" to file
375your incoming mail automatically, you can display new, unseen,
376messages using this command. All messages in the \"unseen\"
377sequence from the folders in `mh-new-messages-folders' are
378listed.
379
380With a prefix argument, enter a space-separated list of FOLDERS,
381or nothing to search all folders."
382 (interactive
383 (list (if current-prefix-arg
384 (split-string (read-string "Search folder(s) (default all): "))
385 mh-new-messages-folders)))
386 (mh-index-sequenced-messages folders mh-unseen-seq))
44140699 387
a4d7cec3 388;;;###mh-autoload
dda00b2c
BW
389(defun mh-index-ticked-messages (folders)
390 "Display ticked messages.
391
392All messages in `mh-tick-seq' from the folders in
393`mh-ticked-messages-folders' are listed.
394
395With a prefix argument, enter a space-separated list of FOLDERS,
396or nothing to search all folders."
397 (interactive
398 (list (if current-prefix-arg
399 (split-string (read-string "Search folder(s) (default all): "))
400 mh-ticked-messages-folders)))
401 (mh-index-sequenced-messages folders mh-tick-seq))
402
403;; Shush compiler.
42f8c37f
BW
404(defvar mh-mairix-folder) ; XEmacs
405(defvar mh-flists-search-folders) ; XEmacs
dda00b2c
BW
406
407;;;###mh-autoload
408(defun mh-index-sequenced-messages (folders sequence)
409 "Display messages in any sequence.
410
411All messages from the FOLDERS in `mh-new-messages-folders' in the
412SEQUENCE you provide are listed. With a prefix argument, enter a
413space-separated list of folders at the prompt, or nothing to
414search all folders."
415 (interactive
416 (list (if current-prefix-arg
417 (split-string (read-string "Search folder(s) (default all): "))
418 mh-new-messages-folders)
419 (mh-read-seq-default "Search" nil)))
420 (unless sequence (setq sequence mh-unseen-seq))
421 (let* ((mh-flists-search-folders folders)
422 (mh-flists-sequence sequence)
423 (mh-flists-called-flag t)
424 (mh-searcher 'flists)
425 (mh-search-function 'mh-flists-execute)
426 (mh-search-next-result-function 'mh-mairix-next-result)
427 (mh-mairix-folder mh-user-path)
428 (mh-search-regexp-builder nil)
429 (new-folder (format "%s/%s/%s" mh-index-folder
430 mh-flists-results-folder sequence))
431 (window-config (if (equal new-folder mh-current-folder)
432 mh-previous-window-config
433 (current-window-configuration)))
434 (redo-flag nil)
435 message)
436 (cond ((buffer-live-p (get-buffer new-folder))
437 ;; The destination folder is being visited. Trick `mh-search'
438 ;; into thinking that the folder resulted from a previous search.
439 (set-buffer new-folder)
440 (setq mh-index-previous-search (list folders mh-searcher sequence))
441 (setq redo-flag t))
442 ((mh-folder-exists-p new-folder)
443 ;; Folder exists but we don't have it open. That means they are
444 ;; stale results from a old flists search. Clear it out.
445 (mh-exec-cmd-quiet nil "rmf" new-folder)))
446 (setq message (mh-search "+" mh-flists-results-folder
447 redo-flag window-config)
448 mh-index-sequence-search-flag t
449 mh-index-previous-search (list folders mh-searcher sequence))
450 (mh-index-write-data)
451 (when (stringp message) (message "%s" message))))
452
453(defvar mh-flists-search-folders)
454
455(defun mh-flists-execute (&rest args)
456 "Execute flists.
457Search for messages belonging to `mh-flists-sequence' in the
458folders specified by `mh-flists-search-folders'. If
459`mh-recursive-folders-flag' is t, then the folders are searched
460recursively. All parameters ARGS are ignored."
461 (set-buffer (get-buffer-create mh-temp-index-buffer))
462 (erase-buffer)
463 (unless (executable-find "sh")
464 (error "Didn't find sh"))
465 (with-temp-buffer
466 (let ((seq (symbol-name mh-flists-sequence)))
467 (insert "for folder in `" (expand-file-name "flists" mh-progs) " "
468 (cond ((eq mh-flists-search-folders t)
469 (mh-quote-for-shell mh-inbox))
470 ((eq mh-flists-search-folders nil) "")
471 ((listp mh-flists-search-folders)
472 (loop for folder in mh-flists-search-folders
473 concat
474 (concat " " (mh-quote-for-shell folder)))))
475 (if mh-recursive-folders-flag " -recurse" "")
476 " -sequence " seq " -noshowzero -fast` ; do\n"
477 (expand-file-name "mhpath" mh-progs) " \"+$folder\" " seq "\n"
478 "done\n"))
479 (call-process-region
480 (point-min) (point-max) "sh" nil (get-buffer mh-temp-index-buffer))))
481
482;; Navigation
483
484;;;###mh-autoload
485(defun mh-index-next-folder (&optional backward-flag)
486 "Jump to the next folder marker.
487
488With non-nil optional argument BACKWARD-FLAG, jump to the previous
489group of results."
490 (interactive "P")
491 (if (null mh-index-data)
492 (message "Only applicable in an MH-E index search buffer")
493 (let ((point (point)))
494 (forward-line (if backward-flag 0 1))
495 (cond ((if backward-flag
496 (re-search-backward "^+" (point-min) t)
497 (re-search-forward "^+" (point-max) t))
498 (beginning-of-line))
499 ((and (if backward-flag
500 (goto-char (point-max))
501 (goto-char (point-min)))
502 nil))
503 ((if backward-flag
504 (re-search-backward "^+" (point-min) t)
505 (re-search-forward "^+" (point-max) t))
506 (beginning-of-line))
507 (t (goto-char point))))))
508
509;;;###mh-autoload
510(defun mh-index-previous-folder ()
511 "Jump to the previous folder marker."
512 (interactive)
513 (mh-index-next-folder t))
514
515;;;###mh-autoload
516(defun mh-index-visit-folder ()
517 "Visit original folder from where the message at point was found."
518 (interactive)
519 (unless mh-index-data
520 (error "Not in an index folder"))
521 (let (folder msg)
522 (save-excursion
523 (cond ((and (bolp) (eolp))
524 (ignore-errors (forward-line -1))
525 (setq msg (mh-get-msg-num t)))
d5dc8c56 526 ((equal (char-after (mh-line-beginning-position)) ?+)
dda00b2c 527 (setq folder (buffer-substring-no-properties
d5dc8c56
BW
528 (mh-line-beginning-position)
529 (mh-line-end-position))))
dda00b2c
BW
530 (t (setq msg (mh-get-msg-num t)))))
531 (when (not folder)
532 (setq folder (car (gethash (gethash msg mh-index-msg-checksum-map)
533 mh-index-checksum-origin-map))))
534 (when (or (not (get-buffer folder))
535 (y-or-n-p (format "Reuse buffer displaying %s? " folder)))
536 (mh-visit-folder
537 folder (loop for x being the hash-keys of (gethash folder mh-index-data)
538 when (mh-msg-exists-p x folder) collect x)))))
539
540\f
541
542;;; Search Menu
543
544(easy-menu-define
545 mh-pick-menu mh-search-mode-map "Menu for MH-E Search"
546 '("Search"
547 ["Perform Search" mh-index-do-search t]
548 ["Search with pick" mh-pick-do-search t]))
549
550\f
551
552;;; MH-Search Keys
553
44140699
BW
554;; If this changes, modify mh-search-mode-help-messages accordingly, below.
555(gnus-define-keys mh-search-mode-map
556 "\C-c?" mh-help
557 "\C-c\C-c" mh-index-do-search
558 "\C-c\C-p" mh-pick-do-search
559 "\C-c\C-f\C-b" mh-to-field
560 "\C-c\C-f\C-c" mh-to-field
dda00b2c 561 "\C-c\C-f\C-m" mh-to-field
44140699
BW
562 "\C-c\C-f\C-s" mh-to-field
563 "\C-c\C-f\C-t" mh-to-field
564 "\C-c\C-fb" mh-to-field
565 "\C-c\C-fc" mh-to-field
dda00b2c 566 "\C-c\C-fm" mh-to-field
44140699
BW
567 "\C-c\C-fs" mh-to-field
568 "\C-c\C-ft" mh-to-field)
569
dda00b2c
BW
570\f
571
572;;; MH-Search Help Messages
44140699
BW
573
574;; Group messages logically, more or less.
575(defvar mh-search-mode-help-messages
576 '((nil
dda00b2c
BW
577 "Perform search: \\[mh-index-do-search]\n"
578 "Search with pick: \\[mh-pick-do-search]\n\n"
44140699
BW
579 "Move to a field by typing C-c C-f C-<field>\n"
580 "where <field> is the first letter of the desired field\n"
581 "(except for From: which uses \"m\")."))
582 "Key binding cheat sheet.
583
584This is an associative array which is used to show the most common
585commands. The key is a prefix char. The value is one or more strings
586which are concatenated together and displayed in the minibuffer if ?
587is pressed after the prefix character. The special key nil is used to
588display the non-prefixed commands.
589
590The substitutions described in `substitute-command-keys' are performed
591as well.")
592
dda00b2c
BW
593\f
594
595;;; MH-Search Mode
596
44140699
BW
597(put 'mh-search-mode 'mode-class 'special)
598
599(define-derived-mode mh-search-mode fundamental-mode "MH-Search"
600 "Mode for creating search templates in MH-E.\\<mh-search-mode-map>
601
a4d7cec3
BW
602Edit this template by entering your search criteria in an
603appropriate header field that is already there, or create a new
604field yourself. If the string you're looking for could be
605anywhere in a message, then place the string underneath the row
606of dashes.
607
608To perform the search, type \\[mh-index-do-search].
609
610Sometimes you're searching for text that is either not indexed,
611or hasn't been indexed yet. In this case you can override the
612default method with the pick method by running the command
613\\[mh-pick-do-search].
44140699
BW
614
615The hook `mh-search-mode-hook' is called upon entry to this mode.
616
617\\{mh-search-mode-map}"
618
44140699 619 (easy-menu-add mh-pick-menu)
dda00b2c
BW
620 (mh-set-help mh-search-mode-help-messages))
621
622\f
623
624;;; MH-Search Commands
a66894d8 625
a4d7cec3
BW
626(defun mh-index-do-search (&optional searcher)
627 "Find messages using `mh-search-program'.
628If optional argument SEARCHER is present, use it instead of
629`mh-search-program'."
3d7ca223 630 (interactive)
a4d7cec3 631 (unless (mh-search-choose searcher) (error "No search program found"))
3d7ca223 632 (let* ((regexp-list (mh-pick-parse-search-buffer))
a4d7cec3 633 (pattern (funcall mh-search-regexp-builder regexp-list)))
3d7ca223 634 (if pattern
a4d7cec3 635 (mh-search mh-current-folder pattern nil mh-previous-window-config)
3d7ca223
BW
636 (error "No search terms"))))
637
44140699 638(defun mh-pick-do-search ()
a4d7cec3 639 "Find messages using \"pick\".
44140699
BW
640
641Uses the pick method described in `mh-pick-execute-search'."
642 (interactive)
643 (mh-index-do-search 'pick))
644
645(defun mh-pick-parse-search-buffer ()
646 "Parse the search buffer contents.
647The function returns a alist. The car of each element is either
648the header name to search in or nil to search the whole message.
649The cdr of the element is the pattern to search."
650 (save-excursion
651 (let ((pattern-list ())
652 (in-body-flag nil)
653 start begin)
654 (goto-char (point-min))
655 (while (not (eobp))
d5dc8c56 656 (if (search-forward "--------" (mh-line-end-position) t)
44140699
BW
657 (setq in-body-flag t)
658 (beginning-of-line)
659 (setq begin (point))
660 (setq start (if in-body-flag
661 (point)
d5dc8c56 662 (search-forward ":" (mh-line-end-position) t)
44140699
BW
663 (point)))
664 (push (cons (and (not in-body-flag)
665 (intern (downcase
666 (buffer-substring-no-properties
667 begin (1- start)))))
668 (mh-index-parse-search-regexp
669 (buffer-substring-no-properties
d5dc8c56 670 start (mh-line-end-position))))
44140699
BW
671 pattern-list))
672 (forward-line))
673 pattern-list)))
674
3d7ca223
BW
675(defun mh-index-parse-search-regexp (input-string)
676 "Construct parse tree for INPUT-STRING.
2dcf34f9
BW
677All occurrences of &, |, ! and ~ in INPUT-STRING are replaced by
678AND, OR and NOT as appropriate. Then the resulting string is
679parsed."
3d7ca223
BW
680 (let (input)
681 (with-temp-buffer
682 (insert input-string)
3d7ca223
BW
683 ;; replace tabs
684 (mh-replace-string "\t" " ")
685 ;; synonyms of AND
a66894d8 686 (mh-replace-string " AND " " and ")
3d7ca223
BW
687 (mh-replace-string "&" " and ")
688 (mh-replace-string " -and " " and ")
689 ;; synonyms of OR
a66894d8 690 (mh-replace-string " OR " " or ")
3d7ca223
BW
691 (mh-replace-string "|" " or ")
692 (mh-replace-string " -or " " or ")
693 ;; synonyms of NOT
a66894d8 694 (mh-replace-string " NOT " " not ")
3d7ca223
BW
695 (mh-replace-string "!" " not ")
696 (mh-replace-string "~" " not ")
697 (mh-replace-string " -not " " not ")
698 ;; synonyms of left brace
699 (mh-replace-string "(" " ( ")
700 (mh-replace-string " -lbrace " " ( ")
701 ;; synonyms of right brace
702 (mh-replace-string ")" " ) ")
703 (mh-replace-string " -rbrace " " ) ")
704 ;; get the normalized input
705 (setq input (format "( %s )" (buffer-substring (point-min) (point-max)))))
706
707 (let ((tokens (mh-index-add-implicit-ops (split-string input)))
708 (op-stack ())
709 (operand-stack ())
710 oper1)
711 (dolist (token tokens)
712 (cond ((equal token "(") (push 'paren op-stack))
713 ((equal token "not") (push 'not op-stack))
714 ((equal token "or") (push 'or op-stack))
715 ((equal token "and") (push 'and op-stack))
716 ((equal token ")")
717 (multiple-value-setq (op-stack operand-stack)
7c730dd6 718 (values-list (mh-index-evaluate op-stack operand-stack)))
3d7ca223 719 (when (eq (car op-stack) 'not)
a66894d8 720 (setq op-stack (cdr op-stack))
3d7ca223
BW
721 (push `(not ,(pop operand-stack)) operand-stack))
722 (when (eq (car op-stack) 'and)
a66894d8 723 (setq op-stack (cdr op-stack))
3d7ca223
BW
724 (setq oper1 (pop operand-stack))
725 (push `(and ,(pop operand-stack) ,oper1) operand-stack)))
726 ((eq (car op-stack) 'not)
a66894d8 727 (setq op-stack (cdr op-stack))
3d7ca223
BW
728 (push `(not ,token) operand-stack)
729 (when (eq (car op-stack) 'and)
a66894d8 730 (setq op-stack (cdr op-stack))
3d7ca223
BW
731 (setq oper1 (pop operand-stack))
732 (push `(and ,(pop operand-stack) ,oper1) operand-stack)))
733 ((eq (car op-stack) 'and)
a66894d8 734 (setq op-stack (cdr op-stack))
3d7ca223
BW
735 (push `(and ,(pop operand-stack) ,token) operand-stack))
736 (t (push token operand-stack))))
737 (prog1 (pop operand-stack)
dda00b2c
BW
738 (when (or op-stack operand-stack)
739 (error "Invalid regexp: %s" input))))))
44140699 740
dda00b2c
BW
741(defun mh-index-add-implicit-ops (tokens)
742 "Add implicit operators in the list TOKENS."
743 (let ((result ())
744 (literal-seen nil)
745 current)
746 (while tokens
747 (setq current (pop tokens))
748 (cond ((or (equal current ")") (equal current "and") (equal current "or"))
749 (setq literal-seen nil)
750 (push current result))
751 ((and literal-seen
752 (push "and" result)
753 (setq literal-seen nil)
44140699 754 nil))
dda00b2c
BW
755 (t
756 (push current result)
757 (unless (or (equal current "(") (equal current "not"))
758 (setq literal-seen t)))))
759 (nreverse result)))
a66894d8 760
dda00b2c
BW
761(defun mh-index-evaluate (op-stack operand-stack)
762 "Read expression till starting paren based on OP-STACK and OPERAND-STACK."
763 (block mh-index-evaluate
764 (let (op oper1)
765 (while op-stack
766 (setq op (pop op-stack))
767 (cond ((eq op 'paren)
7c730dd6 768 (return-from mh-index-evaluate (list op-stack operand-stack)))
dda00b2c
BW
769 ((eq op 'not)
770 (push `(not ,(pop operand-stack)) operand-stack))
771 ((or (eq op 'and) (eq op 'or))
772 (setq oper1 (pop operand-stack))
773 (push `(,op ,(pop operand-stack) ,oper1) operand-stack))))
774 (error "Ran out of tokens"))))
a66894d8 775
bdcfe844
BW
776\f
777
dda00b2c 778;;; Indexing Functions
3d7ca223 779
a4d7cec3
BW
780;; Support different search programs
781(defvar mh-search-choices
44140699
BW
782 '((swish++
783 mh-swish++-binary mh-swish++-execute-search mh-swish++-next-result
784 mh-swish++-regexp-builder)
785 (swish
786 mh-swish-binary mh-swish-execute-search mh-swish-next-result nil)
787 (mairix
788 mh-mairix-binary mh-mairix-execute-search mh-mairix-next-result
789 mh-mairix-regexp-builder)
790 (namazu
791 mh-namazu-binary mh-namazu-execute-search mh-namazu-next-result nil)
792 (pick
793 mh-pick-binary mh-pick-execute-search mh-pick-next-result
794 mh-pick-regexp-builder)
795 (grep
796 mh-grep-binary mh-grep-execute-search mh-grep-next-result nil))
a4d7cec3 797 "List of possible searcher choices.")
44140699 798
a4d7cec3
BW
799(defun mh-search-choose (&optional searcher)
800 "Choose a searching function.
44140699 801The side-effects of this function are that the variables
a4d7cec3
BW
802`mh-searcher', `mh-search-function', and
803`mh-search-next-result-function' are set according to the first
804searcher in `mh-search-choices' present on the system. If
805optional argument SEARCHER is present, use it instead of
806`mh-search-program'."
44140699 807 (block nil
a4d7cec3
BW
808 (let ((program-alist (cond (searcher
809 (list (assoc searcher mh-search-choices)))
810 (mh-search-program
44140699 811 (list
a4d7cec3
BW
812 (assoc mh-search-program mh-search-choices)))
813 (t mh-search-choices))))
44140699
BW
814 (while program-alist
815 (let* ((current (pop program-alist))
816 (executable (symbol-value (cadr current))))
817 (when executable
a4d7cec3
BW
818 (setq mh-searcher (car current))
819 (setq mh-search-function (nth 2 current))
820 (setq mh-search-next-result-function (nth 3 current))
821 (setq mh-search-regexp-builder (nth 4 current))
822 (return mh-searcher))))
44140699 823 nil)))
3d7ca223 824
dda00b2c 825;;; Swish++
3d7ca223 826
44140699
BW
827(defvar mh-swish++-binary (or (executable-find "search++")
828 (executable-find "search")))
829(defvar mh-swish++-directory ".swish++")
830(defvar mh-swish-folder nil)
831
44140699 832(defun mh-swish++-execute-search (folder-path search-regexp)
a4d7cec3 833 "Execute swish++.
44140699
BW
834
835In the examples below, replace \"/home/user/Mail\" with the path to
836your MH directory.
837
838First create the directory \"/home/user/Mail/.swish++\". Then create
839the file \"/home/user/Mail/.swish++/swish++.conf\" with the following
840contents:
841
842 IncludeMeta Bcc Cc Comments Content-Description From Keywords
843 IncludeMeta Newsgroups Resent-To Subject To
844 IncludeMeta Message-Id References In-Reply-To
845 IncludeFile Mail *
846 IndexFile /home/user/Mail/.swish++/swish++.index
847
848Use the following command line to generate the swish index. Run
849this daily from cron:
850
851 find /home/user/Mail -path /home/user/Mail/mhe-index -prune \\
852 -o -path /home/user/Mail/.swish++ -prune \\
853 -o -name \"[0-9]*\" -print \\
854 | index -c /home/user/Mail/.swish++/swish++.conf -
855
856This command does not index the folders that hold the results of your
857searches in \"+mhe-index\" since they tend to be ephemeral and the
858original messages are indexed anyway.
859
860On some systems (Debian GNU/Linux, for example), use \"index++\"
861instead of \"index\".
862
863In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP is
864used to search."
9c2cf222 865 (set-buffer (get-buffer-create mh-temp-index-buffer))
3d7ca223 866 (erase-buffer)
44140699
BW
867 (unless mh-swish++-binary
868 (error "Set `mh-swish++-binary' appropriately"))
869 (call-process mh-swish++-binary nil '(t nil) nil
870 "-m" "10000"
871 (format "-i%s%s/swish++.index"
872 mh-user-path mh-swish++-directory)
873 search-regexp)
874 (goto-char (point-min))
875 (setq mh-swish-folder
876 (let ((last-char (substring folder-path (1- (length folder-path)))))
877 (if (equal last-char "/")
878 folder-path
879 (format "%s/" folder-path)))))
3d7ca223 880
44140699 881(defalias 'mh-swish++-next-result 'mh-swish-next-result)
3d7ca223 882
44140699
BW
883(defun mh-swish++-regexp-builder (regexp-list)
884 "Generate query for swish++.
885REGEXP-LIST is an alist of fields and values."
886 (let ((regexp ""))
887 (dolist (elem regexp-list)
888 (when (cdr elem)
889 (setq regexp (concat regexp " and "
890 (if (car elem) "(" "")
891 (if (car elem) (symbol-name (car elem)) "")
892 (if (car elem) " = " "")
893 (mh-swish++-print-regexp (cdr elem))
894 (if (car elem) ")" "")))))
895 (substring regexp 4)))
896
897(defun mh-swish++-print-regexp (expr)
898 "Return infix expression corresponding to EXPR."
899 (cond ((atom expr) (format "%s" expr))
900 ((eq (car expr) 'not)
901 (format "(not %s)" (mh-swish++-print-regexp (cadr expr))))
902 (t (format "(%s %s %s)" (mh-swish++-print-regexp (cadr expr))
903 (symbol-name (car expr))
904 (mh-swish++-print-regexp (caddr expr))))))
3d7ca223 905
dda00b2c 906;;; Swish
bdcfe844 907
44140699
BW
908(defvar mh-swish-binary (executable-find "swish-e"))
909(defvar mh-swish-directory ".swish")
bdcfe844 910
44140699 911(defun mh-swish-execute-search (folder-path search-regexp)
a4d7cec3 912 "Execute swish-e.
44140699
BW
913
914In the examples below, replace \"/home/user/Mail\" with the path
915to your MH directory.
916
917First create the directory \"/home/user/Mail/.swish\". Then
918create the file \"/home/user/Mail/.swish/config\" with the
919following contents:
920
921 DefaultContents TXT*
922 IndexDir /home/user/Mail
923 IndexFile /home/user/Mail/.swish/index
924 IndexName \"Mail Index\"
925 IndexDescription \"Mail Index\"
926 IndexPointer \"http://nowhere\"
927 IndexAdmin \"nobody\"
928 #MetaNames automatic
929 IndexReport 3
930 FollowSymLinks no
931 UseStemming no
932 IgnoreTotalWordCountWhenRanking yes
933 WordCharacters abcdefghijklmnopqrstuvwxyz0123456789-
934 BeginCharacters abcdefghijklmnopqrstuvwxyz
935 EndCharacters abcdefghijklmnopqrstuvwxyz0123456789
936 IgnoreLimit 50 1000
937 IndexComments 0
938 FileRules filename contains \\D
939 FileRules pathname contains /home/user/Mail/.swish
940 FileRules pathname contains /home/user/Mail/mhe-index
941
942This configuration does not index the folders that hold the
943results of your searches in \"+mhe-index\" since they tend to be
944ephemeral and the original messages are indexed anyway.
945
946If there are any directories you would like to ignore, append
947lines like the following to \"config\":
e495eaec 948
44140699
BW
949 FileRules pathname contains /home/user/Mail/scripts
950
951Use the following command line to generate the swish index. Run
952this daily from cron:
953
954 swish-e -c /home/user/Mail/.swish/config
e495eaec 955
2dcf34f9
BW
956In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP
957is used to search."
9c2cf222 958 (set-buffer (get-buffer-create mh-temp-index-buffer))
bdcfe844 959 (erase-buffer)
44140699
BW
960 (unless mh-swish-binary
961 (error "Set `mh-swish-binary' appropriately"))
962 (call-process mh-swish-binary nil '(t nil) nil
963 "-w" search-regexp
964 "-f" (format "%s%s/index" mh-user-path mh-swish-directory))
965 (goto-char (point-min))
966 (setq mh-swish-folder
967 (let ((last-char (substring folder-path (1- (length folder-path)))))
968 (if (equal last-char "/")
969 folder-path
970 (format "%s/" folder-path)))))
bdcfe844 971
44140699
BW
972(defun mh-swish-next-result ()
973 "Get the next result from swish output."
bdcfe844 974 (prog1
c3d9274a 975 (block nil
44140699 976 (when (or (eobp) (equal (char-after (point)) ?.))
c3d9274a 977 (return nil))
44140699
BW
978 (when (equal (char-after (point)) ?#)
979 (return 'error))
d5dc8c56
BW
980 (let* ((start (search-forward " " (mh-line-end-position) t))
981 (end (search-forward " " (mh-line-end-position) t)))
44140699 982 (unless (and start end)
bdcfe844 983 (return 'error))
44140699
BW
984 (setq end (1- end))
985 (unless (file-exists-p (buffer-substring-no-properties start end))
c3d9274a 986 (return 'error))
44140699
BW
987 (unless (search-backward "/" start t)
988 (return 'error))
989 (list (let* ((s (buffer-substring-no-properties start (1+ (point)))))
990 (unless (string-match mh-swish-folder s)
991 (return 'error))
992 (if (and (string-match mh-user-path s)
993 (< (match-end 0) (1- (length s))))
994 (format "+%s"
995 (substring s (match-end 0) (1- (length s))))
996 (return 'error)))
997 (let* ((s (buffer-substring-no-properties (1+ (point)) end))
8d2aa237
BW
998 (n (ignore-errors (string-to-number s))))
999 (if n n (return 'error)))
44140699 1000 nil)))
bdcfe844
BW
1001 (forward-line)))
1002
dda00b2c 1003;;; Mairix
3d7ca223
BW
1004
1005(defvar mh-mairix-binary (executable-find "mairix"))
1006(defvar mh-mairix-directory ".mairix")
1007(defvar mh-mairix-folder nil)
1008
1009(defun mh-mairix-execute-search (folder-path search-regexp-list)
a4d7cec3 1010 "Execute mairix.
3d7ca223 1011
2dcf34f9
BW
1012In the examples below, replace \"/home/user/Mail\" with the path
1013to your MH directory.
3d7ca223 1014
2dcf34f9
BW
1015First create the directory \"/home/user/Mail/.mairix\". Then
1016create the file \"/home/user/Mail/.mairix/config\" with the
1017following contents:
3d7ca223 1018
e495eaec 1019 base=/home/user/Mail
a1506d29 1020
e495eaec
BW
1021 # List of folders that should be indexed. 3 dots at the end means there
1022 # are subfolders within the folder
1023 mh=archive...:inbox:drafts:news:sent:trash
a1506d29 1024
002d2524
BW
1025 vfolder_format=mh
1026 database=/home/user/Mail/.mairix/database
3d7ca223 1027
2dcf34f9
BW
1028Use the following command line to generate the mairix index. Run
1029this daily from cron:
3d7ca223 1030
e495eaec 1031 mairix -f /home/user/Mail/.mairix/config
3d7ca223 1032
2dcf34f9
BW
1033In a program, FOLDER-PATH is the directory in which
1034SEARCH-REGEXP-LIST is used to search."
9c2cf222 1035 (set-buffer (get-buffer-create mh-temp-index-buffer))
3d7ca223
BW
1036 (erase-buffer)
1037 (unless mh-mairix-binary
836f2863 1038 (error "Set `mh-mairix-binary' appropriately"))
3d7ca223 1039 (apply #'call-process mh-mairix-binary nil '(t nil) nil
e495eaec 1040 "-r" "-f" (format "%s%s/config" mh-user-path mh-mairix-directory)
3d7ca223
BW
1041 search-regexp-list)
1042 (goto-char (point-min))
1043 (setq mh-mairix-folder
1044 (let ((last-char (substring folder-path (1- (length folder-path)))))
1045 (if (equal last-char "/")
1046 folder-path
1047 (format "%s/" folder-path)))))
1048
1049(defun mh-mairix-next-result ()
1050 "Return next result from mairix output."
1051 (prog1
1052 (block nil
1053 (when (or (eobp) (and (bolp) (eolp)))
1054 (return nil))
1055 (unless (eq (char-after) ?/)
924df208 1056 (return 'error))
3d7ca223
BW
1057 (let ((start (point))
1058 end msg-start)
d5dc8c56 1059 (setq end (mh-line-end-position))
3d7ca223
BW
1060 (unless (search-forward mh-mairix-folder end t)
1061 (return 'error))
1062 (goto-char (match-beginning 0))
1063 (unless (equal (point) start)
1064 (return 'error))
1065 (goto-char end)
1066 (unless (search-backward "/" start t)
1067 (return 'error))
1068 (setq msg-start (1+ (point)))
1069 (goto-char start)
1070 (unless (search-forward mh-user-path end t)
1071 (return 'error))
1072 (list (format "+%s" (buffer-substring-no-properties
1073 (point) (1- msg-start)))
8d2aa237
BW
1074 (string-to-number
1075 (buffer-substring-no-properties msg-start end))
11db987f 1076 nil)))
3d7ca223
BW
1077 (forward-line)))
1078
1079(defun mh-mairix-regexp-builder (regexp-list)
1080 "Generate query for mairix.
1081REGEXP-LIST is an alist of fields and values."
1082 (let ((result ()))
1083 (dolist (pair regexp-list)
1084 (when (cdr pair)
1085 (push
1086 (concat
1087 (cond ((eq (car pair) 'to) "t:")
1088 ((eq (car pair) 'from) "f:")
1089 ((eq (car pair) 'cc) "c:")
770ea979
BW
1090 ((eq (car pair) 'to-or-cc) "tc:")
1091 ((eq (car pair) 'address) "a:")
3d7ca223 1092 ((eq (car pair) 'subject) "s:")
770ea979 1093 ((eq (car pair) 'subject-or-body) "bs:")
3d7ca223 1094 ((eq (car pair) 'date) "d:")
770ea979
BW
1095 ((eq (car pair) 'message-id) "m:")
1096 ((eq (car pair) 'message-body) "b:")
1097 ((eq (car pair) 'message-size) "z:")
1098 ((eq (car pair) 'message-attachment-name) "n:")
1099 ((eq (car pair) 'message-flags) "F:")
3d7ca223
BW
1100 (t ""))
1101 (let ((sop (cdr (mh-mairix-convert-to-sop* (cdr pair))))
1102 (final ""))
1103 (dolist (conjunct sop)
1104 (let ((expr-list (cdr conjunct))
1105 (expr-string ""))
1106 (dolist (e expr-list)
e495eaec 1107 (setq expr-string (concat expr-string ","
3d7ca223
BW
1108 (if (atom e) "" "~")
1109 (if (atom e) e (cadr e)))))
e495eaec 1110 (setq final (concat final "/" (substring expr-string 1)))))
3d7ca223
BW
1111 (substring final 1)))
1112 result)))
1113 result))
1114
1115(defun mh-mairix-convert-to-sop* (expr)
1116 "Convert EXPR to sum of product form."
1117 (cond ((atom expr) `(or (and ,expr)))
1118 ((eq (car expr) 'or)
1119 (cons 'or
1120 (loop for e in (mapcar #'mh-mairix-convert-to-sop* (cdr expr))
1121 append (cdr e))))
1122 ((eq (car expr) 'and)
1123 (let ((conjuncts (mapcar #'mh-mairix-convert-to-sop* (cdr expr)))
1124 result next-factor)
1125 (setq result (pop conjuncts))
1126 (while conjuncts
1127 (setq next-factor (pop conjuncts))
1128 (setq result (let ((res ()))
1129 (dolist (t1 (cdr result))
1130 (dolist (t2 (cdr next-factor))
1131 (push `(and ,@(cdr t1) ,@(cdr t2)) res)))
1132 (cons 'or res))))
1133 result))
1134 ((atom (cadr expr)) `(or (and ,expr)))
1135 ((eq (caadr expr) 'not) (mh-mairix-convert-to-sop* (cadadr expr)))
1136 ((eq (caadr expr) 'and) (mh-mairix-convert-to-sop*
1137 `(or ,@(mapcar #'(lambda (x) `(not ,x))
1138 (cdadr expr)))))
1139 ((eq (caadr expr) 'or) (mh-mairix-convert-to-sop*
1140 `(and ,@(mapcar #'(lambda (x) `(not ,x))
1141 (cdadr expr)))))
1142 (t (error "Unreachable: %s" expr))))
1143
dda00b2c 1144;;; Namazu
3d7ca223 1145
44140699
BW
1146(defvar mh-namazu-binary (executable-find "namazu"))
1147(defvar mh-namazu-directory ".namazu")
1148(defvar mh-namazu-folder nil)
924df208 1149
44140699 1150(defun mh-namazu-execute-search (folder-path search-regexp)
a4d7cec3 1151 "Execute namazu.
af435184 1152
44140699
BW
1153In the examples below, replace \"/home/user/Mail\" with the path to
1154your MH directory.
a66894d8 1155
44140699
BW
1156First create the directory \"/home/user/Mail/.namazu\". Then create
1157the file \"/home/user/Mail/.namazu/mknmzrc\" with the following
1158contents:
a8a47814 1159
44140699
BW
1160 package conf; # Don't remove this line!
1161 $ADDRESS = 'user@localhost';
1162 $ALLOW_FILE = \"[0-9]*\";
1163 $EXCLUDE_PATH = \"^/home/user/Mail/(mhe-index|spam)\";
a8a47814 1164
44140699
BW
1165This configuration does not index the folders that hold the results of
1166your searches in \"+mhe-index\" since they tend to be ephemeral and
1167the original messages are indexed anyway.
a66894d8 1168
44140699
BW
1169Use the following command line to generate the namazu index. Run this
1170daily from cron:
a8a47814 1171
44140699 1172 mknmz -f /home/user/Mail/.namazu/mknmzrc -O /home/user/Mail/.namazu \\
002d2524 1173 -q /home/user/Mail
a8a47814 1174
44140699
BW
1175In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP
1176is used to search."
1177 (let ((namazu-index-directory
1178 (format "%s%s" mh-user-path mh-namazu-directory)))
1179 (unless (file-exists-p namazu-index-directory)
1180 (error "Namazu directory %s not present" namazu-index-directory))
1181 (unless (executable-find mh-namazu-binary)
1182 (error "Set `mh-namazu-binary' appropriately"))
1183 (set-buffer (get-buffer-create mh-temp-index-buffer))
1184 (erase-buffer)
1185 (call-process mh-namazu-binary nil '(t nil) nil
1186 "-alR" search-regexp namazu-index-directory)
1187 (goto-char (point-min))
1188 (setq mh-namazu-folder
1189 (let ((last (substring folder-path (1- (length folder-path)))))
1190 (if (equal last "/")
1191 folder-path
1192 (format "%s/" folder-path))))))
924df208 1193
44140699
BW
1194(defun mh-namazu-next-result ()
1195 "Get the next result from namazu output."
1196 (prog1
1197 (block nil
1198 (when (eobp) (return nil))
1199 (let ((file-name (buffer-substring-no-properties
d5dc8c56 1200 (point) (mh-line-end-position))))
44140699
BW
1201 (unless (equal (string-match mh-namazu-folder file-name) 0)
1202 (return 'error))
1203 (unless (file-exists-p file-name)
1204 (return 'error))
1205 (string-match mh-user-path file-name)
1206 (let* ((folder/msg (substring file-name (match-end 0)))
1207 (mark (mh-search-from-end ?/ folder/msg)))
1208 (unless mark (return 'error))
1209 (list (format "+%s" (substring folder/msg 0 mark))
8d2aa237 1210 (let ((n (ignore-errors (string-to-number
44140699 1211 (substring folder/msg (1+ mark))))))
8d2aa237 1212 (if n n (return 'error)))
44140699
BW
1213 nil))))
1214 (forward-line)))
924df208 1215
dda00b2c 1216;;; Pick
bdcfe844 1217
44140699
BW
1218(defvar mh-index-pick-folder)
1219(defvar mh-pick-binary "pick")
1220(defconst mh-pick-single-dash '(cc date from subject to)
1221 "Search components that are supported by single-dash option in pick.")
bdcfe844 1222
44140699
BW
1223(defun mh-pick-execute-search (folder-path search-regexp)
1224 "Execute pick.
bdcfe844 1225
a4d7cec3
BW
1226Read \"pick(1)\" or the section Finding Messages with pick in the
1227MH book to find out more about how to enter the criteria (see URL
1228`http://www.ics.uci.edu/~mh/book/mh/finpic.htm').
e495eaec 1229
44140699
BW
1230In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP
1231is used to search."
1232 (set-buffer (get-buffer-create mh-temp-index-buffer))
1233 (erase-buffer)
11db987f
BW
1234 (let ((folders
1235 (mh-folder-list (substring folder-path (length mh-user-path)))))
1236 (loop for folder in folders do
1237 (setq folder (concat "+" folder))
1238 (insert folder "\n")
1239 (apply #'call-process (expand-file-name "pick" mh-progs)
1240 nil '(t nil) nil folder "-list" search-regexp)))
44140699 1241 (goto-char (point-min)))
e495eaec 1242
44140699
BW
1243(defun mh-pick-next-result ()
1244 "Return the next pick search result."
11db987f
BW
1245 (prog1
1246 (block nil
1247 (when (eobp) (return nil))
d5dc8c56 1248 (when (search-forward-regexp "^\+" (mh-line-end-position) t)
11db987f 1249 (setq mh-index-pick-folder
d5dc8c56
BW
1250 (buffer-substring-no-properties (mh-line-beginning-position)
1251 (mh-line-end-position)))
11db987f 1252 (return 'error))
d5dc8c56 1253 (unless (search-forward-regexp "^[1-9][0-9]*$" (mh-line-end-position) t)
11db987f
BW
1254 (return 'error))
1255 (list mh-index-pick-folder
1256 (string-to-number
d5dc8c56
BW
1257 (buffer-substring-no-properties (mh-line-beginning-position)
1258 (mh-line-end-position)))
11db987f 1259 nil))
44140699 1260 (forward-line)))
bdcfe844 1261
44140699
BW
1262;; All implementations of pick have special options -cc, -date, -from and
1263;; -subject that allow to search for corresponding components. Any other
1264;; component is searched using option --COMPNAME, for example: `pick
1265;; --x-mailer mh-e'. Mailutils "pick" supports this option using a certain
1266;; kludge, but it prefers the following syntax for this purpose:
1267;; "--component=COMPNAME --pattern=PATTERN".
1268;; -- Sergey Poznyakoff, Aug 2003
1269(defun mh-pick-regexp-builder (pattern-list)
1270 "Generate pick search expression from PATTERN-LIST."
1271 (let ((result ()))
1272 (dolist (pattern pattern-list)
1273 (when (cdr pattern)
1274 (setq result `(,@result "-and" "-lbrace"
1275 ,@(mh-pick-construct-regexp
1624e7c9 1276 (if (and (mh-variant-p 'gnu-mh) (car pattern))
44140699
BW
1277 (format "--pattern=%s" (cdr pattern))
1278 (cdr pattern))
1279 (if (car pattern)
1280 (cond
1624e7c9 1281 ((mh-variant-p 'gnu-mh)
44140699
BW
1282 (format "--component=%s" (car pattern)))
1283 ((member (car pattern) mh-pick-single-dash)
1284 (format "-%s" (car pattern)))
1285 (t
1286 (format "--%s" (car pattern))))
1287 "-search"))
1288 "-rbrace"))))
1289 (cdr result)))
1290
1291(defun mh-pick-construct-regexp (expr component)
1292 "Construct pick compatible expression corresponding to EXPR.
1293COMPONENT is the component to search."
1294 (cond ((atom expr) (list component expr))
1295 ((eq (car expr) 'and)
1296 `("-lbrace" ,@(mh-pick-construct-regexp (cadr expr) component) "-and"
1297 ,@(mh-pick-construct-regexp (caddr expr) component) "-rbrace"))
1298 ((eq (car expr) 'or)
1299 `("-lbrace" ,@(mh-pick-construct-regexp (cadr expr) component) "-or"
1300 ,@(mh-pick-construct-regexp (caddr expr) component) "-rbrace"))
1301 ((eq (car expr) 'not)
1302 `("-lbrace" "-not" ,@(mh-pick-construct-regexp (cadr expr) component)
1303 "-rbrace"))
1304 (t (error "Unknown operator %s seen" (car expr)))))
bdcfe844 1305
dda00b2c 1306;;; Grep
c3d9274a 1307
44140699 1308(defvar mh-grep-binary (executable-find "grep"))
bdcfe844 1309
44140699 1310(defun mh-grep-execute-search (folder-path search-regexp)
a4d7cec3
BW
1311 "Execute grep.
1312
1313Unlike the other search methods, this method does not use the
1314MH-Search buffer. Instead, you simply enter a regular expression
1315in the minibuffer. For help in constructing regular expressions,
1316see your man page for \"grep\".
bdcfe844 1317
2dcf34f9
BW
1318In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP
1319is used to search."
9c2cf222 1320 (set-buffer (get-buffer-create mh-temp-index-buffer))
bdcfe844 1321 (erase-buffer)
44140699
BW
1322 (call-process mh-grep-binary nil '(t nil) nil
1323 "-i" "-r" search-regexp folder-path)
1324 (goto-char (point-min)))
bdcfe844 1325
44140699
BW
1326(defun mh-grep-next-result ()
1327 "Read the next result.
1328Parse it and return the message folder, message index and the
1329match. If no other matches left then return nil. If the current
1330record is invalid return 'error."
bdcfe844
BW
1331 (prog1
1332 (block nil
44140699 1333 (when (eobp)
bdcfe844 1334 (return nil))
d5dc8c56
BW
1335 (let ((eol-pos (mh-line-end-position))
1336 (bol-pos (mh-line-beginning-position))
44140699
BW
1337 folder-start msg-end)
1338 (goto-char bol-pos)
1339 (unless (search-forward mh-user-path eol-pos t)
bdcfe844 1340 (return 'error))
44140699
BW
1341 (setq folder-start (point))
1342 (unless (search-forward ":" eol-pos t)
bdcfe844 1343 (return 'error))
44140699
BW
1344 (let ((match (buffer-substring-no-properties (point) eol-pos)))
1345 (forward-char -1)
1346 (setq msg-end (point))
1347 (unless (search-backward "/" folder-start t)
1348 (return 'error))
1349 (list (format "+%s" (buffer-substring-no-properties
1350 folder-start (point)))
8d2aa237
BW
1351 (let ((n (ignore-errors (string-to-number
1352 (buffer-substring-no-properties
1353 (1+ (point)) msg-end)))))
1354 (if n n (return 'error)))
44140699 1355 match))))
bdcfe844
BW
1356 (forward-line)))
1357
1358\f
1359
dda00b2c
BW
1360;;; Folder Utilities
1361
1362;;;###mh-autoload
1363(defun mh-index-group-by-folder ()
1364 "Partition the messages based on source folder.
88675922 1365Returns an alist with the folder names in the car and the cdr
dda00b2c
BW
1366being the list of messages originally from that folder."
1367 (save-excursion
1368 (goto-char (point-min))
1369 (let ((result-table (make-hash-table :test #'equal)))
1937adc2 1370 (loop for msg being the hash-keys of mh-index-msg-checksum-map
dda00b2c
BW
1371 do (push msg (gethash (car (gethash
1372 (gethash msg mh-index-msg-checksum-map)
1373 mh-index-checksum-origin-map))
1374 result-table)))
1375 (loop for x being the hash-keys of result-table
1376 collect (cons x (nreverse (gethash x result-table)))))))
1377
1378;;;###mh-autoload
1379(defun mh-index-insert-folder-headers ()
1380 "Annotate the search results with original folder names."
1381 (let ((cur-msg (mh-get-msg-num nil))
1382 (old-buffer-modified-flag (buffer-modified-p))
1383 (buffer-read-only nil)
1384 current-folder last-folder)
1385 (goto-char (point-min))
1386 (while (not (eobp))
1387 (setq current-folder (car (gethash (gethash (mh-get-msg-num nil)
1388 mh-index-msg-checksum-map)
1389 mh-index-checksum-origin-map)))
1390 (when (and current-folder (not (equal current-folder last-folder)))
1391 (insert (if last-folder "\n" "") current-folder "\n")
1392 (setq last-folder current-folder))
1393 (forward-line))
1394 (when cur-msg
1395 (mh-notate-cur)
1396 (mh-goto-msg cur-msg t))
1397 (set-buffer-modified-p old-buffer-modified-flag))
1398 (mh-index-create-imenu-index))
1399
1400;;;###mh-autoload
1401(defun mh-index-delete-folder-headers ()
1402 "Delete the folder headers."
1403 (let ((cur-msg (mh-get-msg-num nil))
1404 (old-buffer-modified-flag (buffer-modified-p))
1405 (buffer-read-only nil))
1406 (while (and (not cur-msg) (not (eobp)))
1407 (forward-line)
1408 (setq cur-msg (mh-get-msg-num nil)))
1409 (goto-char (point-min))
1410 (while (not (eobp))
1411 (if (or (char-equal (char-after) ?+) (char-equal (char-after) 10))
1412 (delete-region (point) (progn (forward-line) (point)))
1413 (forward-line)))
1414 (when cur-msg (mh-goto-msg cur-msg t t))
1415 (set-buffer-modified-p old-buffer-modified-flag)))
1416
92486f28
BW
1417(mh-require 'which-func nil t)
1418
dda00b2c 1419;; Shush compiler.
42f8c37f 1420(defvar which-func-mode) ; < Emacs 22, XEmacs
dda00b2c
BW
1421
1422;;;###mh-autoload
1423(defun mh-index-create-imenu-index ()
1424 "Create alist of folder names and positions in index folder buffers."
1425 (save-excursion
1426 (if (boundp 'which-func-mode)
1427 (setq which-func-mode t))
1428 (let ((alist ()))
1429 (goto-char (point-min))
1430 (while (re-search-forward "^+" nil t)
1431 (save-excursion
1432 (beginning-of-line)
1433 (push (cons (buffer-substring-no-properties
d5dc8c56 1434 (point) (mh-line-end-position))
dda00b2c
BW
1435 (set-marker (make-marker) (point)))
1436 alist)))
1437 (setq imenu--index-alist (nreverse alist)))))
1438
1439;;;###mh-autoload
1440(defun mh-search-p ()
1441 "Non-nil means that this folder was generated by searching."
1442 mh-index-data)
1443
1444;; Shush compiler
42f8c37f 1445(defvar mh-speed-flists-inhibit-flag) ; XEmacs
dda00b2c
BW
1446
1447;;;###mh-autoload
1448(defun mh-index-execute-commands ()
1449 "Delete/refile the actual messages.
1450The copies in the searched folder are then deleted/refiled to get
1451the desired result. Before deleting the messages we make sure
1452that the message being deleted is identical to the one that the
1453user has marked in the index buffer."
1454 (save-excursion
1455 (let ((folders ())
1456 (mh-speed-flists-inhibit-flag t))
1457 (maphash
1458 (lambda (folder msgs)
1459 (push folder folders)
1460 (if (not (get-buffer folder))
1461 ;; If source folder not open, just delete the messages...
1462 (apply #'mh-exec-cmd "rmm" folder (mh-coalesce-msg-list msgs))
1463 ;; Otherwise delete the messages in the source buffer...
b5553d47 1464 (with-current-buffer folder
dda00b2c
BW
1465 (let ((old-refile-list mh-refile-list)
1466 (old-delete-list mh-delete-list))
1467 (setq mh-refile-list nil
1468 mh-delete-list msgs)
1469 (unwind-protect (mh-execute-commands)
1470 (setq mh-refile-list
1471 (mapcar (lambda (x)
1472 (cons (car x)
1473 (loop for y in (cdr x)
1474 unless (memq y msgs) collect y)))
1475 old-refile-list)
1476 mh-delete-list
1477 (loop for x in old-delete-list
1478 unless (memq x msgs) collect x))
1479 (mh-set-folder-modified-p (mh-outstanding-commands-p))
1480 (when (mh-outstanding-commands-p)
1481 (mh-notate-deleted-and-refiled)))))))
1482 (mh-index-matching-source-msgs (append (loop for x in mh-refile-list
1483 append (cdr x))
1484 mh-delete-list)
1485 t))
1486 folders)))
bdcfe844 1487
44140699
BW
1488(defun mh-index-generate-pretty-name (string)
1489 "Given STRING generate a name which is suitable for use as a folder name.
1490White space from the beginning and end are removed. All spaces in
1491the name are replaced with underscores and all / are replaced
1492with $. If STRING is longer than 20 it is truncated too. STRING
1493could be a list of strings in which case they are concatenated to
1494construct the base name."
1495 (with-temp-buffer
1496 (if (stringp string)
1497 (insert string)
1498 (when (car string) (insert (car string)))
1499 (dolist (s (cdr string))
1500 (insert "_" s)))
1501 (setq string (mh-replace-string "-lbrace" " "))
1502 (setq string (mh-replace-string "-rbrace" " "))
a4d7cec3 1503 (setq string (mh-replace-string "-search" " "))
44140699
BW
1504 (subst-char-in-region (point-min) (point-max) ?( ? t)
1505 (subst-char-in-region (point-min) (point-max) ?) ? t)
1506 (subst-char-in-region (point-min) (point-max) ?- ? t)
1507 (goto-char (point-min))
1508 (while (and (not (eobp)) (memq (char-after) '(? ?\t ?\n ?\r ?_)))
1509 (delete-char 1))
1510 (goto-char (point-max))
1511 (while (and (not (bobp)) (memq (char-before) '(? ?\t ?\n ?\r ?_)))
d355a0b7 1512 (delete-char -1))
44140699
BW
1513 (subst-char-in-region (point-min) (point-max) ? ?_ t)
1514 (subst-char-in-region (point-min) (point-max) ?\t ?_ t)
1515 (subst-char-in-region (point-min) (point-max) ?\n ?_ t)
1516 (subst-char-in-region (point-min) (point-max) ?\r ?_ t)
1517 (subst-char-in-region (point-min) (point-max) ?/ ?$ t)
1518 (let ((out (truncate-string-to-width (buffer-string) 20)))
a4d7cec3 1519 (cond ((eq mh-searcher 'flists)
44140699
BW
1520 (format "%s/%s" mh-flists-results-folder mh-flists-sequence))
1521 ((equal out mh-flists-results-folder) (concat out "1"))
1522 (t out)))))
bdcfe844 1523
44140699
BW
1524(defun mh-folder-exists-p (folder)
1525 "Check if FOLDER exists."
1526 (and (mh-folder-name-p folder)
1527 (save-excursion
1528 (with-temp-buffer
1529 (mh-exec-cmd-output "folder" nil "-fast" "-nocreate" folder)
1530 (goto-char (point-min))
1937adc2
BW
1531 ;; Strip + from folder; use optional + in regexp.
1532 (looking-at (format "+?%s" (substring folder 1)))))))
c3d9274a 1533
44140699
BW
1534(defun mh-msg-exists-p (msg folder)
1535 "Check if MSG exists in FOLDER."
1536 (file-exists-p (format "%s%s/%s" mh-user-path (substring folder 1) msg)))
bdcfe844 1537
44140699
BW
1538(defun mh-index-new-folder (name search-regexp)
1539 "Return a folder name based on NAME for search results of SEARCH-REGEXP.
bdcfe844 1540
44140699
BW
1541If folder NAME already exists and was generated for the same
1542SEARCH-REGEXP then it is reused.
bdcfe844 1543
44140699 1544Otherwise if the folder NAME was generated from a different
d9044cd6 1545search then check if NAME-2 can be used. Otherwise try NAME-3.
44140699 1546This is repeated till we find a new folder name.
bdcfe844 1547
44140699
BW
1548If the folder returned doesn't exist then it is created."
1549 (unless (mh-folder-name-p name)
1550 (error "The argument should be a valid MH folder name"))
1551 (let ((chosen-name
1552 (loop for i from 1
d9044cd6 1553 for candidate = (if (equal i 1) name (format "%s-%s" name i))
44140699
BW
1554 when (or (not (mh-folder-exists-p candidate))
1555 (equal (mh-index-folder-search-regexp candidate)
1556 search-regexp))
1557 return candidate)))
1558 ;; Do pending refiles/deletes...
1559 (when (get-buffer chosen-name)
1560 (mh-process-or-undo-commands chosen-name))
1561 ;; Recreate folder...
1562 (save-excursion (mh-exec-cmd-quiet nil "rmf" chosen-name))
1563 (mh-exec-cmd-quiet nil "folder" "-create" "-fast" chosen-name)
1564 (mh-remove-from-sub-folders-cache chosen-name)
1565 (when (boundp 'mh-speed-folder-map)
1566 (mh-speed-add-folder chosen-name))
1567 chosen-name))
3d7ca223 1568
44140699
BW
1569(defun mh-index-folder-search-regexp (folder)
1570 "If FOLDER was created by a index search, return the search regexp.
1571Return nil if FOLDER doesn't exist or the .mhe_index file is
1572garbled."
1573 (ignore-errors
1574 (with-temp-buffer
1575 (insert-file-contents
1576 (format "%s%s/%s" mh-user-path (substring folder 1) mh-index-data-file))
1577 (goto-char (point-min))
1578 (forward-list 3)
1579 (cadr (read (current-buffer))))))
3d7ca223 1580
bdcfe844
BW
1581\f
1582
dda00b2c 1583;;; Sequence Support
bdcfe844 1584
44140699
BW
1585;;;###mh-autoload
1586(defun mh-index-create-sequences ()
1587 "Mirror sequences present in source folders in index folder."
1588 (let ((seq-hash (make-hash-table :test #'equal))
1589 (seq-list ()))
1590 (loop for folder being the hash-keys of mh-index-data
1591 do (setf (gethash folder seq-hash)
1592 (mh-create-sequence-map
1593 (mh-read-folder-sequences folder nil))))
1594 (dolist (msg (mh-translate-range mh-current-folder "all"))
1595 (let* ((checksum (gethash msg mh-index-msg-checksum-map))
1596 (pair (gethash checksum mh-index-checksum-origin-map))
1597 (ofolder (car pair))
1598 (omsg (cdr pair)))
1599 (loop for seq in (ignore-errors
1600 (gethash omsg (gethash ofolder seq-hash)))
1601 do (if (assoc seq seq-list)
1602 (push msg (cdr (assoc seq seq-list)))
1603 (push (list seq msg) seq-list)))))
1604 (loop for seq in seq-list
1605 do (apply #'mh-exec-cmd "mark" mh-current-folder
1606 "-sequence" (symbol-name (car seq)) "-add"
1607 (mapcar #'(lambda (x) (format "%s" x)) (cdr seq))))))
bdcfe844 1608
c3d9274a 1609;;;###mh-autoload
44140699
BW
1610(defun mh-create-sequence-map (seq-list)
1611 "Return a map from msg number to list of sequences in which it is present.
1612SEQ-LIST is an assoc list whose keys are sequence names and whose
1613cdr is the list of messages in that sequence."
1614 (loop with map = (make-hash-table)
1615 for seq in seq-list
1616 when (and (not (memq (car seq) (mh-unpropagated-sequences)))
1617 (mh-valid-seq-p (car seq)))
1618 do (loop for msg in (cdr seq)
1619 do (push (car seq) (gethash msg map)))
1620 finally return map))
bdcfe844 1621
44140699
BW
1622;;;###mh-autoload
1623(defun mh-index-add-to-sequence (seq msgs)
1624 "Add to SEQ the messages in the list MSGS.
1625This function updates the source folder sequences. Also makes an
1626attempt to update the source folder buffer if we have it open."
1627 ;; Don't need to do anything for cur
1628 (save-excursion
1629 (when (and (not (memq seq (mh-unpropagated-sequences)))
1630 (mh-valid-seq-p seq))
1631 (let ((folders ())
1632 (mh-speed-flists-inhibit-flag t))
1633 (maphash (lambda (folder msgs)
1634 (push folder folders)
1635 ;; Add messages to sequence in source folder...
1636 (apply #'mh-exec-cmd-quiet nil "mark" folder
1637 "-add" "-nozero" "-sequence" (symbol-name seq)
1638 (mapcar (lambda (x) (format "%s" x))
1639 (mh-coalesce-msg-list msgs)))
1640 ;; Update source folder buffer if we have it open...
1641 (when (get-buffer folder)
b5553d47 1642 (with-current-buffer folder
44140699
BW
1643 (mh-put-msg-in-seq msgs seq))))
1644 (mh-index-matching-source-msgs msgs))
1645 folders))))
bdcfe844 1646
44140699
BW
1647;;;###mh-autoload
1648(defun mh-index-delete-from-sequence (seq msgs)
1649 "Delete from SEQ the messages in MSGS.
1650This function updates the source folder sequences. Also makes an
1651attempt to update the source folder buffer if present."
1652 (save-excursion
1653 (when (and (not (memq seq (mh-unpropagated-sequences)))
1654 (mh-valid-seq-p seq))
1655 (let ((folders ())
1656 (mh-speed-flists-inhibit-flag t))
1657 (maphash (lambda (folder msgs)
1658 (push folder folders)
1659 ;; Remove messages from sequence in source folder...
1660 (apply #'mh-exec-cmd-quiet nil "mark" folder
1661 "-del" "-nozero" "-sequence" (symbol-name seq)
1662 (mapcar (lambda (x) (format "%s" x))
1663 (mh-coalesce-msg-list msgs)))
1664 ;; Update source folder buffer if we have it open...
1665 (when (get-buffer folder)
b5553d47 1666 (with-current-buffer folder
44140699
BW
1667 (mh-delete-msg-from-seq msgs seq t))))
1668 (mh-index-matching-source-msgs msgs))
1669 folders))))
c3d9274a 1670
44140699
BW
1671(defvar mh-unpropagated-sequences '(cur range subject search)
1672 "List of sequences that aren't preserved.")
c3d9274a 1673
44140699
BW
1674(defun mh-unpropagated-sequences ()
1675 "Return a list of sequences that aren't propagated to the source folders.
1676It is just the sequences in the variable
1677`mh-unpropagated-sequences' in addition to the
1678Previous-Sequence (see mh-profile 5)."
1679 (if mh-previous-seq
1680 (cons mh-previous-seq mh-unpropagated-sequences)
1681 mh-unpropagated-sequences))
bdcfe844 1682
44140699
BW
1683(defun mh-index-matching-source-msgs (msgs &optional delete-from-index-data)
1684 "Return a table of original messages and folders for messages in MSGS.
1685If optional argument DELETE-FROM-INDEX-DATA is non-nil, then each
1686of the messages, whose counter-part is found in some source
1687folder, is removed from `mh-index-data'."
1688 (let ((table (make-hash-table :test #'equal)))
1689 (dolist (msg msgs)
1690 (let* ((checksum (gethash msg mh-index-msg-checksum-map))
1691 (pair (gethash checksum mh-index-checksum-origin-map)))
1692 (when (and checksum (car pair) (cdr pair)
1693 (mh-index-match-checksum (cdr pair) (car pair) checksum))
1694 (push (cdr pair) (gethash (car pair) table))
1695 (when delete-from-index-data
1696 (remhash (cdr pair) (gethash (car pair) mh-index-data))))))
1697 table))
bdcfe844 1698
44140699
BW
1699(defun mh-index-match-checksum (msg folder checksum)
1700 "Check if MSG in FOLDER has X-MHE-Checksum header value of CHECKSUM."
1701 (with-temp-buffer
1702 (mh-exec-cmd-output mh-scan-prog nil "-width" "80"
1703 "-format" "%{x-mhe-checksum}\n" folder msg)
bdcfe844 1704 (goto-char (point-min))
d5dc8c56
BW
1705 (string-equal (buffer-substring-no-properties
1706 (point) (mh-line-end-position))
44140699 1707 checksum)))
bdcfe844
BW
1708
1709\f
1710
dda00b2c 1711;;; Serialization of Index Data
44140699
BW
1712
1713(defun mh-index-write-data ()
1714 "Write index data to file."
1715 (ignore-errors
1716 (unless (eq major-mode 'mh-folder-mode)
1717 (error "Can't be called from folder in \"%s\"" major-mode))
1718 (let ((data mh-index-data)
1719 (msg-checksum-map mh-index-msg-checksum-map)
1720 (checksum-origin-map mh-index-checksum-origin-map)
1721 (previous-search mh-index-previous-search)
1722 (sequence-search-flag mh-index-sequence-search-flag)
1723 (outfile (concat buffer-file-name mh-index-data-file))
1724 (print-length nil)
1725 (print-level nil))
1726 (with-temp-file outfile
1727 (mh-index-write-hashtable
1728 data (lambda (x) (loop for y being the hash-keys of x collect y)))
1729 (mh-index-write-hashtable msg-checksum-map #'identity)
1730 (mh-index-write-hashtable checksum-origin-map #'identity)
1731 (pp previous-search (current-buffer)) (insert "\n")
1732 (pp sequence-search-flag (current-buffer)) (insert "\n")))))
1733
1734(defun mh-index-write-hashtable (table proc)
1735 "Write TABLE to `current-buffer'.
1736PROC is used to serialize the values corresponding to the hash
1737table keys."
1738 (pp (loop for x being the hash-keys of table
1739 collect (cons x (funcall proc (gethash x table))))
1740 (current-buffer))
1741 (insert "\n"))
1742
924df208 1743;;;###mh-autoload
44140699
BW
1744(defun mh-index-read-data ()
1745 "Read index data from file."
1746 (ignore-errors
1747 (unless (eq major-mode 'mh-folder-mode)
1748 (error "Can't be called from folder in \"%s\"" major-mode))
1749 (let ((infile (concat buffer-file-name mh-index-data-file))
1750 t1 t2 t3 t4 t5)
1751 (with-temp-buffer
1752 (insert-file-contents-literally infile)
1753 (goto-char (point-min))
1754 (setq t1 (mh-index-read-hashtable
1755 (lambda (data)
1756 (loop with table = (make-hash-table :test #'equal)
1757 for x in data do (setf (gethash x table) t)
1758 finally return table)))
1759 t2 (mh-index-read-hashtable #'identity)
1760 t3 (mh-index-read-hashtable #'identity)
1761 t4 (read (current-buffer))
1762 t5 (read (current-buffer))))
1763 (setq mh-index-data t1
1764 mh-index-msg-checksum-map t2
1765 mh-index-checksum-origin-map t3
1766 mh-index-previous-search t4
1767 mh-index-sequence-search-flag t5))))
1768
1769(defun mh-index-read-hashtable (proc)
1770 "From BUFFER read a hash table serialized as a list.
1771PROC is used to convert the value to actual data."
1772 (loop with table = (make-hash-table :test #'equal)
1773 for pair in (read (current-buffer))
1774 do (setf (gethash (car pair) table) (funcall proc (cdr pair)))
1775 finally return table))
bdcfe844
BW
1776
1777\f
1778
dda00b2c
BW
1779;;; Checksum Routines
1780
1781;; A few different checksum programs are supported. The supported
1782;; programs are:
44140699 1783
44140699
BW
1784;; 1. md5sum
1785;; 2. md5
1786;; 3. openssl
dda00b2c
BW
1787
1788;; To add support for your favorite checksum program add a clause to
1789;; the cond statement in mh-checksum-choose. This should set the
1790;; variable mh-checksum-cmd to the command line needed to run the
1791;; checsum program and should set mh-checksum-parser to a function
1792;; which returns a cons cell containing the message number and
1793;; checksum string.
44140699
BW
1794
1795(defvar mh-checksum-cmd)
1796(defvar mh-checksum-parser)
1797
1798(defun mh-checksum-choose ()
1799 "Check if a program to create a checksum is present."
1800 (unless (boundp 'mh-checksum-cmd)
1801 (let ((exec-path (append '("/sbin" "/usr/sbin") exec-path)))
1802 (cond ((executable-find "md5sum")
1803 (setq mh-checksum-cmd (list (executable-find "md5sum")))
1804 (setq mh-checksum-parser #'mh-md5sum-parser))
1805 ((executable-find "openssl")
1806 (setq mh-checksum-cmd (list (executable-find "openssl") "md5"))
1807 (setq mh-checksum-parser #'mh-openssl-parser))
1808 ((executable-find "md5")
1809 (setq mh-checksum-cmd (list (executable-find "md5")))
1810 (setq mh-checksum-parser #'mh-md5-parser))
1811 (t (error "No suitable checksum program"))))))
1812
1813(defun mh-md5sum-parser ()
1814 "Parse md5sum output."
d5dc8c56
BW
1815 (let ((begin (mh-line-beginning-position))
1816 (end (mh-line-end-position))
44140699
BW
1817 first-space last-slash)
1818 (setq first-space (search-forward " " end t))
1819 (goto-char end)
1820 (setq last-slash (search-backward "/" begin t))
1821 (cond ((and first-space last-slash)
8d2aa237
BW
1822 (cons (string-to-number (buffer-substring-no-properties
1823 (1+ last-slash) end))
44140699
BW
1824 (buffer-substring-no-properties begin (1- first-space))))
1825 (t (cons nil nil)))))
1826
1827(defun mh-openssl-parser ()
1828 "Parse openssl output."
d5dc8c56
BW
1829 (let ((begin (mh-line-beginning-position))
1830 (end (mh-line-end-position))
44140699
BW
1831 last-space last-slash)
1832 (goto-char end)
1833 (setq last-space (search-backward " " begin t))
1834 (setq last-slash (search-backward "/" begin t))
1835 (cond ((and last-slash last-space)
8d2aa237
BW
1836 (cons (string-to-number (buffer-substring-no-properties
1837 (1+ last-slash) (1- last-space)))
44140699
BW
1838 (buffer-substring-no-properties (1+ last-space) end))))))
1839
1840(defalias 'mh-md5-parser 'mh-openssl-parser)
1841
1842;;;###mh-autoload
1843(defun mh-index-update-maps (folder &optional origin-map)
1844 "Annotate all as yet unannotated messages in FOLDER with their MD5 hash.
1845As a side effect msg -> checksum map is updated. Optional
1846argument ORIGIN-MAP is a hashtable which maps each message in the
1847index folder to the original folder and message from whence it
1848was copied. If present the checksum -> (origin-folder,
1849origin-index) map is updated too."
1850 (clrhash mh-index-msg-checksum-map)
b5553d47
SM
1851 ;; Clear temp buffer
1852 (with-current-buffer (get-buffer-create mh-temp-checksum-buffer)
44140699
BW
1853 (erase-buffer)
1854 ;; Run scan to check if any messages needs MD5 annotations at all
1855 (with-temp-buffer
1856 (mh-exec-cmd-output mh-scan-prog nil "-width" "80"
1857 "-format" "%(msg)\n%{x-mhe-checksum}\n"
1858 folder "all")
1859 (goto-char (point-min))
1860 (let (msg checksum)
1861 (while (not (eobp))
1862 (setq msg (buffer-substring-no-properties
d5dc8c56 1863 (point) (mh-line-end-position)))
44140699
BW
1864 (forward-line)
1865 (save-excursion
1866 (cond ((not (string-match "^[0-9]*$" msg)))
1867 ((eolp)
1868 ;; need to compute checksum
1869 (set-buffer mh-temp-checksum-buffer)
1870 (insert mh-user-path (substring folder 1) "/" msg "\n"))
1871 (t
1872 ;; update maps
1873 (setq checksum (buffer-substring-no-properties
d5dc8c56 1874 (point) (mh-line-end-position)))
8d2aa237 1875 (let ((msg (string-to-number msg)))
44140699
BW
1876 (set-buffer folder)
1877 (mh-index-update-single-msg msg checksum origin-map)))))
1878 (forward-line))))
1879 ;; Run checksum program if needed
1880 (unless (and (eobp) (bobp))
1881 (apply #'mh-xargs mh-checksum-cmd)
1882 (goto-char (point-min))
1883 (while (not (eobp))
1884 (let* ((intermediate (funcall mh-checksum-parser))
1885 (msg (car intermediate))
1886 (checksum (cdr intermediate)))
1887 (when msg
1888 ;; annotate
1889 (mh-exec-cmd "anno" folder msg "-component" "X-MHE-Checksum"
1890 "-nodate" "-text" checksum "-inplace")
1891 ;; update maps
b5553d47 1892 (with-current-buffer folder
44140699
BW
1893 (mh-index-update-single-msg msg checksum origin-map)))
1894 (forward-line)))))
1895 (mh-index-write-data))
1896
1897(defun mh-index-update-single-msg (msg checksum origin-map)
1898 "Update various maps for one message.
1899MSG is a index folder message, CHECKSUM its MD5 hash and
1900ORIGIN-MAP, if non-nil, a hashtable containing which maps each
1901message in the index folder to the folder and message that it was
1902copied from. The function updates the hash tables
1903`mh-index-msg-checksum-map' and `mh-index-checksum-origin-map'.
1904
1905This function should only be called in the appropriate index
1906folder buffer."
1af028e6
SD
1907 (cond ((gethash checksum mh-index-checksum-origin-map)
1908 (when origin-map
1909 (let* ((intermediate (gethash msg origin-map))
1910 (ofolder (car intermediate))
1911 (omsg (cdr intermediate)))
1912 ;; This is most probably a duplicate. So eliminate it.
1913 (call-process "rm" nil nil nil
1914 (format "%s%s/%s" mh-user-path
1915 (substring mh-current-folder 1) msg))
1916 (when (gethash ofolder mh-index-data)
1917 (remhash omsg (gethash ofolder mh-index-data))))))
44140699
BW
1918 (t
1919 (setf (gethash msg mh-index-msg-checksum-map) checksum)
1af028e6 1920 (when (and origin-map (gethash msg origin-map))
44140699
BW
1921 (setf (gethash checksum mh-index-checksum-origin-map)
1922 (gethash msg origin-map))))))
1923
1af028e6 1924
44140699 1925(provide 'mh-search)
bdcfe844 1926
cee9f5c6
BW
1927;; Local Variables:
1928;; indent-tabs-mode: nil
1929;; sentence-end-double-space: nil
1930;; End:
bdcfe844 1931
44140699 1932;;; mh-search ends here