1 ;;; mh-search --- MH-E search
3 ;; Copyright (C) 1993, 1995,
4 ;; 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
6 ;; Author: Indexed search by Satyaki Das <satyaki@theforce.stanford.edu>
7 ;; Maintainer: Bill Wohler <wohler@newt.com>
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
30 ;; (1) The following search engines are supported:
38 ;; (2) To use this package, you first have to build an index. Please
39 ;; read the documentation for `mh-search' to get started. That
40 ;; documentation will direct you to the specific instructions for
41 ;; your particular searcher.
47 (eval-when-compile (require 'mh-acros))
54 (defvar mh-searcher nil
55 "Cached value of chosen search program.")
57 (defvar mh-search-function nil
58 "Function which executes the search program.")
60 (defvar mh-search-next-result-function nil
61 "Function to parse the next line of output.
62 Expected to return a list of three strings: name of the folder,
63 message number, and optionally the match.")
65 (defvar mh-search-regexp-builder nil
66 "Function used to construct search regexp.")
68 (defvar mh-index-folder "+mhe-index"
69 "Folder that contains the folders resulting from the index searches.")
71 (defvar mh-flists-results-folder "sequence"
72 "Subfolder for `mh-index-folder' where flists output is placed.")
74 (defvar mh-flists-sequence)
76 (defvar mh-flists-called-flag nil)
83 (defun* mh-search (folder search-regexp
84 &optional redo-search-flag window-config)
87 This command helps you find messages in your entire corpus of
88 mail. You can search for messages to or from a particular person
89 or about a particular subject. In fact, you can also search for
90 messages containing selected strings in any arbitrary header
91 field or any string found within the messages.
93 Out of the box, MH-E uses \"pick\" to find messages. With a
94 little extra effort, you can set an indexing program which
95 rewards you with extremely quick results. The drawback is that
96 sometimes the index does not contain the words you're looking
97 for. You can still use \"pick\" in these situations.
99 You are prompted for the FOLDER to search. This can be \"all\" to
100 search all folders. Note that the search works recursively on the
103 Next, an MH-Search buffer appears where you can enter search
104 criteria SEARCH-REGEXP.
113 Edit this template by entering your search criteria in an
114 appropriate header field that is already there, or create a new
115 field yourself. If the string you're looking for could be
116 anywhere in a message, then place the string underneath the row
119 As an example, let's say that we want to find messages from
120 Ginnean about horseback riding in the Kosciusko National
121 Park (Australia) during January, 1994. Normally we would start
122 with a broad search and narrow it down if necessary to produce a
123 manageable amount of data, but we'll cut to the chase and create
124 a fairly restrictive set of criteria as follows:\\<mh-search-mode-map>
135 As with MH-Letter mode, MH-Search provides commands like
136 \\[mh-to-field] to help you fill in the blanks.\\<mh-folder-mode-map>
138 If you find that you do the same thing over and over when editing
139 the search template, you may wish to bind some shortcuts to keys.
140 This can be done with the variable `mh-search-mode-hook', which is
141 called when \\[mh-search] is run on a new pattern.\\<mh-search-mode-map>
143 To perform the search, type \\[mh-index-do-search].
145 Sometimes you're searching for text that is either not indexed,
146 or hasn't been indexed yet. In this case you can override the
147 default method with the pick method by running the command
148 \\[mh-pick-do-search].
150 The messages that are found are put in a temporary sub-folder of
151 \"+mhe-index\" and are displayed in an MH-Folder buffer. This
152 buffer is special because it displays messages from multiple
153 folders; each set of messages from a given folder has a heading
154 with the folder name.\\<mh-folder-mode-map>
156 The appearance of the heading can be modified by customizing the
157 face `mh-search-folder'. You can jump back and forth between the
158 headings using the commands \\[mh-index-next-folder] and
159 \\[mh-index-previous-folder].
161 In addition, the command \\[mh-index-visit-folder] can be used to
162 visit the folder of the message at point. Initially, only the
163 messages that matched the search criteria are displayed in the
164 folder. While the temporary buffer has its own set of message
165 numbers, the actual messages numbers are shown in the visited
166 folder. Thus, the command \\[mh-index-visit-folder] is useful to
167 find the actual message number of an interesting message, or to
168 view surrounding messages with the command \\[mh-rescan-folder].
170 Because this folder is temporary, you'll probably get in the
171 habit of killing it when you're done with \\[mh-kill-folder].
173 You can regenerate the results by running this command with a
174 prefix argument REDO-SEARCH-FLAG.
176 Note: This command uses an \"X-MHE-Checksum:\" header field to
177 cache the MD5 checksum of a message. This means that if an
178 incoming message already contains an \"X-MHE-Checksum:\" field,
179 that message might not be found by this command. The following
180 \"procmail\" recipe avoids this problem by renaming the existing
184 | formail -R \"X-MHE-Checksum\" \"X-Old-MHE-Checksum\"
186 Configuring Indexed Searches
188 The command \\[mh-search] runs the command defined by the option
189 `mh-search-program'. The default value is \"Auto-detect\" which
190 means that MH-E will automatically choose one of \"swish++\",
191 \"swish-e\", \"mairix\", \"namazu\", \"pick\" and \"grep\" in
192 that order. If, for example, you have both \"swish++\" and
193 \"mairix\" installed and you want to use \"mairix\", then you can
194 set this option to \"mairix\".
196 The documentation for the following commands describe how to set
197 up the various indexing programs to use with MH-E.
199 - `mh-swish++-execute-search'
200 - `mh-swish-execute-search'
201 - `mh-mairix-execute-search'
202 - `mh-namazu-execute-search'
203 - `mh-pick-execute-search'
204 - `mh-grep-execute-search'
206 In a program, if FOLDER is \"+\" or nil, then mail in all folders
207 are searched. Optional argument WINDOW-CONFIG stores the window
208 configuration that will be restored after the user quits the
209 folder containing the index search results."
213 ;; Yes, we do want to call mh-search-choose every time in case the
214 ;; user has switched the searcher manually.
215 (unless (mh-search-choose (and current-prefix-arg
216 mh-index-previous-search
217 (cadr mh-index-previous-search)))
218 (error "No search program found"))
219 (or (and current-prefix-arg mh-index-sequence-search-flag)
220 (and current-prefix-arg (car mh-index-previous-search))
221 (mh-prompt-for-folder "Search" "+" nil "all" t)))
222 (or (and current-prefix-arg (caddr mh-index-previous-search))
223 mh-search-regexp-builder
224 (read-string (format "%s regexp: "
225 (upcase-initials (symbol-name mh-searcher)))))
227 (if (and (not (and current-prefix-arg
228 (caddr mh-index-previous-search)))
229 mh-search-regexp-builder)
230 (current-window-configuration)
232 ;; Redoing a sequence search?
233 (when (and redo-search-flag mh-index-data mh-index-sequence-search-flag
234 (not mh-flists-called-flag))
235 (let ((mh-flists-called-flag t))
236 (apply #'mh-index-sequenced-messages mh-index-previous-search))
237 (return-from mh-search))
238 ;; We have fancy query parsing.
239 (when (symbolp search-regexp)
240 (mh-search-folder folder window-config)
241 (return-from mh-search))
242 ;; Begin search proper.
244 (let ((result-count 0)
245 (old-window-config (or window-config mh-previous-window-config))
246 (previous-search mh-index-previous-search)
247 (index-folder (format "%s/%s" mh-index-folder
248 (mh-index-generate-pretty-name search-regexp))))
249 ;; Create a new folder for the search results or recreate the old one...
250 (if (and redo-search-flag mh-index-previous-search)
251 (let ((buffer-name (buffer-name (current-buffer))))
252 (mh-process-or-undo-commands buffer-name)
253 (save-excursion (mh-exec-cmd-quiet nil "rmf" buffer-name))
254 (mh-exec-cmd-quiet nil "folder" "-create" "-fast" buffer-name)
255 (setq index-folder buffer-name))
256 (setq index-folder (mh-index-new-folder index-folder search-regexp)))
258 (let ((folder-path (format "%s%s" mh-user-path (substring folder 1)))
259 (folder-results-map (make-hash-table :test #'equal))
260 (origin-map (make-hash-table :test #'equal)))
261 ;; Run search program...
262 (message "Executing %s... " mh-searcher)
263 (funcall mh-search-function folder-path search-regexp)
265 ;; Parse searcher output.
266 (message "Processing %s output... " mh-searcher)
267 (goto-char (point-min))
268 (loop for next-result = (funcall mh-search-next-result-function)
270 do (unless (eq next-result 'error)
271 (unless (gethash (car next-result) folder-results-map)
272 (setf (gethash (car next-result) folder-results-map)
273 (make-hash-table :test #'equal)))
274 (setf (gethash (cadr next-result)
275 (gethash (car next-result) folder-results-map))
278 ;; Copy the search results over.
279 (maphash #'(lambda (folder msgs)
280 (let ((cur (car (mh-translate-range folder "cur")))
281 (msgs (sort (loop for msg being the hash-keys of msgs
284 (mh-exec-cmd "refile" msgs "-src" folder
285 "-link" index-folder)
286 ;; Restore cur to old value, that refile changed
288 (mh-exec-cmd-quiet nil "mark" folder "-add" "-zero"
289 "-sequence" "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)))))
296 ;; Vist the results folder.
297 (mh-visit-folder index-folder () (list folder-results-map origin-map))
299 (goto-char (point-min))
301 (mh-update-sequences)
304 ;; Update the speedbar, if needed.
305 (when (mh-speed-flists-active-p)
306 (mh-speed-flists t mh-current-folder))
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))
313 ;; Write out data to disk.
314 (unless mh-flists-called-flag (mh-index-write-data))
316 (message "%s found %s matches in %s folders"
317 (upcase-initials (symbol-name mh-searcher))
318 (loop for msg-hash being hash-values of mh-index-data
319 sum (hash-table-count msg-hash))
320 (loop for msg-hash being hash-values of mh-index-data
321 count (> (hash-table-count msg-hash) 0))))))
323 (defun mh-search-folder (folder window-config)
324 "Search FOLDER for messages matching a pattern.
326 In a program, argument WINDOW-CONFIG is the current window
327 configuration and is used when the search folder is dismissed."
328 (interactive (list (mh-prompt-for-folder "Search" mh-current-folder nil nil t)
329 (current-window-configuration)))
330 (let ((pick-folder (if (equal folder "+") mh-current-folder folder)))
331 (switch-to-buffer-other-window "search-pattern")
332 (if (or (zerop (buffer-size))
333 (not (y-or-n-p "Reuse pattern? ")))
334 (mh-make-pick-template)
336 (mh-make-local-vars 'mh-current-folder folder
337 'mh-previous-window-config window-config)
338 (message "%s" (substitute-command-keys
339 (concat "Type \\[mh-index-do-search] to search messages, "
340 "\\[mh-pick-do-search] to use pick, "
341 "\\[mh-help] for help")))))
343 (defun mh-make-pick-template ()
344 "Initialize the current buffer with a template for a pick pattern."
345 (let ((inhibit-read-only t)) (erase-buffer))
353 (goto-char (point-min))
355 (add-text-properties (point) (1+ (point)) '(front-sticky t))
356 (add-text-properties (- (line-end-position) 2) (1- (line-end-position))
358 (add-text-properties (point) (1- (line-end-position)) '(read-only t))
360 (add-text-properties (point) (1+ (point)) '(front-sticky t))
361 (add-text-properties (point) (1- (line-end-position)) '(read-only t))
362 (goto-char (point-max)))
365 (defvar mh-search-mode-map (make-sparse-keymap)
366 "Keymap for searching folder.")
369 ;; If this changes, modify mh-search-mode-help-messages accordingly, below.
370 (gnus-define-keys mh-search-mode-map
372 "\C-c\C-c" mh-index-do-search
373 "\C-c\C-p" mh-pick-do-search
374 "\C-c\C-f\C-b" mh-to-field
375 "\C-c\C-f\C-c" mh-to-field
376 "\C-c\C-f\C-d" mh-to-field
377 "\C-c\C-f\C-f" mh-to-field
378 "\C-c\C-f\C-r" mh-to-field
379 "\C-c\C-f\C-s" mh-to-field
380 "\C-c\C-f\C-t" mh-to-field
381 "\C-c\C-fb" mh-to-field
382 "\C-c\C-fc" mh-to-field
383 "\C-c\C-fd" mh-to-field
384 "\C-c\C-ff" mh-to-field
385 "\C-c\C-fr" mh-to-field
386 "\C-c\C-fs" mh-to-field
387 "\C-c\C-ft" mh-to-field)
390 mh-pick-menu mh-search-mode-map "Menu for MH-E Search"
392 ["Perform Search" mh-index-do-search t]
393 ["Search with pick" mh-pick-do-search t]))
395 ;; Group messages logically, more or less.
396 (defvar mh-search-mode-help-messages
398 "Perform search: \\[mh-index-do-search]\n"
399 "Search with pick: \\[mh-pick-do-search]\n"
400 "Move to a field by typing C-c C-f C-<field>\n"
401 "where <field> is the first letter of the desired field\n"
402 "(except for From: which uses \"m\")."))
403 "Key binding cheat sheet.
405 This is an associative array which is used to show the most common
406 commands. The key is a prefix char. The value is one or more strings
407 which are concatenated together and displayed in the minibuffer if ?
408 is pressed after the prefix character. The special key nil is used to
409 display the non-prefixed commands.
411 The substitutions described in `substitute-command-keys' are performed
414 (put 'mh-search-mode 'mode-class 'special)
416 (define-derived-mode mh-search-mode fundamental-mode "MH-Search"
417 "Mode for creating search templates in MH-E.\\<mh-search-mode-map>
419 Edit this template by entering your search criteria in an
420 appropriate header field that is already there, or create a new
421 field yourself. If the string you're looking for could be
422 anywhere in a message, then place the string underneath the row
425 To perform the search, type \\[mh-index-do-search].
427 Sometimes you're searching for text that is either not indexed,
428 or hasn't been indexed yet. In this case you can override the
429 default method with the pick method by running the command
430 \\[mh-pick-do-search].
432 The hook `mh-search-mode-hook' is called upon entry to this mode.
434 \\{mh-search-mode-map}"
436 (make-local-variable 'mh-help-messages)
437 (easy-menu-add mh-pick-menu)
438 (setq mh-help-messages mh-search-mode-help-messages))
441 (defun mh-index-do-search (&optional searcher)
442 "Find messages using `mh-search-program'.
443 If optional argument SEARCHER is present, use it instead of
444 `mh-search-program'."
446 (unless (mh-search-choose searcher) (error "No search program found"))
447 (let* ((regexp-list (mh-pick-parse-search-buffer))
448 (pattern (funcall mh-search-regexp-builder regexp-list)))
450 (mh-search mh-current-folder pattern nil mh-previous-window-config)
451 (error "No search terms"))))
454 (defun mh-pick-do-search ()
455 "Find messages using \"pick\".
457 Uses the pick method described in `mh-pick-execute-search'."
459 (mh-index-do-search 'pick))
461 (defun mh-pick-parse-search-buffer ()
462 "Parse the search buffer contents.
463 The function returns a alist. The car of each element is either
464 the header name to search in or nil to search the whole message.
465 The cdr of the element is the pattern to search."
467 (let ((pattern-list ())
470 (goto-char (point-min))
472 (if (search-forward "--------" (line-end-position) t)
473 (setq in-body-flag t)
476 (setq start (if in-body-flag
478 (search-forward ":" (line-end-position) t)
480 (push (cons (and (not in-body-flag)
482 (buffer-substring-no-properties
484 (mh-index-parse-search-regexp
485 (buffer-substring-no-properties
486 start (line-end-position))))
492 (defun mh-index-parse-search-regexp (input-string)
493 "Construct parse tree for INPUT-STRING.
494 All occurrences of &, |, ! and ~ in INPUT-STRING are replaced by
495 AND, OR and NOT as appropriate. Then the resulting string is
499 (insert input-string)
501 (mh-replace-string "\t" " ")
503 (mh-replace-string " AND " " and ")
504 (mh-replace-string "&" " and ")
505 (mh-replace-string " -and " " and ")
507 (mh-replace-string " OR " " or ")
508 (mh-replace-string "|" " or ")
509 (mh-replace-string " -or " " or ")
511 (mh-replace-string " NOT " " not ")
512 (mh-replace-string "!" " not ")
513 (mh-replace-string "~" " not ")
514 (mh-replace-string " -not " " not ")
515 ;; synonyms of left brace
516 (mh-replace-string "(" " ( ")
517 (mh-replace-string " -lbrace " " ( ")
518 ;; synonyms of right brace
519 (mh-replace-string ")" " ) ")
520 (mh-replace-string " -rbrace " " ) ")
521 ;; get the normalized input
522 (setq input (format "( %s )" (buffer-substring (point-min) (point-max)))))
524 (let ((tokens (mh-index-add-implicit-ops (split-string input)))
528 (dolist (token tokens)
529 (cond ((equal token "(") (push 'paren op-stack))
530 ((equal token "not") (push 'not op-stack))
531 ((equal token "or") (push 'or op-stack))
532 ((equal token "and") (push 'and op-stack))
534 (multiple-value-setq (op-stack operand-stack)
535 (mh-index-evaluate op-stack operand-stack))
536 (when (eq (car op-stack) 'not)
537 (setq op-stack (cdr op-stack))
538 (push `(not ,(pop operand-stack)) operand-stack))
539 (when (eq (car op-stack) 'and)
540 (setq op-stack (cdr op-stack))
541 (setq oper1 (pop operand-stack))
542 (push `(and ,(pop operand-stack) ,oper1) operand-stack)))
543 ((eq (car op-stack) 'not)
544 (setq op-stack (cdr op-stack))
545 (push `(not ,token) operand-stack)
546 (when (eq (car op-stack) 'and)
547 (setq op-stack (cdr op-stack))
548 (setq oper1 (pop operand-stack))
549 (push `(and ,(pop operand-stack) ,oper1) operand-stack)))
550 ((eq (car op-stack) 'and)
551 (setq op-stack (cdr op-stack))
552 (push `(and ,(pop operand-stack) ,token) operand-stack))
553 (t (push token operand-stack))))
554 (prog1 (pop operand-stack)
555 (when (or op-stack operand-stack)
556 (error "Invalid regexp: %s" input))))))
558 (defun mh-index-add-implicit-ops (tokens)
559 "Add implicit operators in the list TOKENS."
564 (setq current (pop tokens))
565 (cond ((or (equal current ")") (equal current "and") (equal current "or"))
566 (setq literal-seen nil)
567 (push current result))
570 (setq literal-seen nil)
573 (push current result)
574 (unless (or (equal current "(") (equal current "not"))
575 (setq literal-seen t)))))
578 (defun mh-index-evaluate (op-stack operand-stack)
579 "Read expression till starting paren based on OP-STACK and OPERAND-STACK."
580 (block mh-index-evaluate
583 (setq op (pop op-stack))
584 (cond ((eq op 'paren)
585 (return-from mh-index-evaluate (values op-stack operand-stack)))
587 (push `(not ,(pop operand-stack)) operand-stack))
588 ((or (eq op 'and) (eq op 'or))
589 (setq oper1 (pop operand-stack))
590 (push `(,op ,(pop operand-stack) ,oper1) operand-stack))))
591 (error "Ran out of tokens"))))
595 ;;; Sequence browsing
598 (defun mh-index-new-messages (folders)
599 "Display unseen messages.
601 If you use a program such as \"procmail\" to use \"rcvstore\" to file
602 your incoming mail automatically, you can display new, unseen,
603 messages using this command. All messages in the \"unseen\"
604 sequence from the folders in `mh-new-messages-folders' are
607 With a prefix argument, enter a space-separated list of FOLDERS,
608 or nothing to search all folders."
610 (list (if current-prefix-arg
611 (split-string (read-string "Search folder(s) (default all): "))
612 mh-new-messages-folders)))
613 (mh-index-sequenced-messages folders mh-unseen-seq))
616 (defun mh-index-ticked-messages (folders)
617 "Display ticked messages.
619 All messages in `mh-tick-seq' from the folders in
620 `mh-ticked-messages-folders' are listed.
622 With a prefix argument, enter a space-separated list of FOLDERS,
623 or nothing to search all folders."
625 (list (if current-prefix-arg
626 (split-string (read-string "Search folder(s) (default all): "))
627 mh-ticked-messages-folders)))
628 (mh-index-sequenced-messages folders mh-tick-seq))
631 (defun mh-index-sequenced-messages (folders sequence)
632 "Display messages in any sequence.
634 All messages from the FOLDERS in `mh-new-messages-folders' in the
635 SEQUENCE you provide are listed. With a prefix argument, enter a
636 space-separated list of folders at the prompt, or nothing to
639 (list (if current-prefix-arg
640 (split-string (read-string "Search folder(s) (default all): "))
641 mh-new-messages-folders)
642 (mh-read-seq-default "Search" nil)))
643 (unless sequence (setq sequence mh-unseen-seq))
644 (let* ((mh-flists-search-folders folders)
645 (mh-flists-sequence sequence)
646 (mh-flists-called-flag t)
647 (mh-searcher 'flists)
648 (mh-search-function 'mh-flists-execute)
649 (mh-search-next-result-function 'mh-mairix-next-result)
650 (mh-mairix-folder mh-user-path)
651 (mh-search-regexp-builder nil)
652 (new-folder (format "%s/%s/%s" mh-index-folder
653 mh-flists-results-folder sequence))
654 (window-config (if (equal new-folder mh-current-folder)
655 mh-previous-window-config
656 (current-window-configuration)))
659 (cond ((buffer-live-p (get-buffer new-folder))
660 ;; The destination folder is being visited. Trick `mh-search'
661 ;; into thinking that the folder resulted from a previous search.
662 (set-buffer new-folder)
663 (setq mh-index-previous-search (list folders mh-searcher sequence))
665 ((mh-folder-exists-p new-folder)
666 ;; Folder exists but we don't have it open. That means they are
667 ;; stale results from a old flists search. Clear it out.
668 (mh-exec-cmd-quiet nil "rmf" new-folder)))
669 (setq message (mh-search "+" mh-flists-results-folder
670 redo-flag window-config)
671 mh-index-sequence-search-flag t
672 mh-index-previous-search (list folders mh-searcher sequence))
673 (mh-index-write-data)
674 (when (stringp message) (message "%s" message))))
676 (defvar mh-flists-search-folders)
678 (defun mh-flists-execute (&rest args)
680 Search for messages belonging to `mh-flists-sequence' in the
681 folders specified by `mh-flists-search-folders'. If
682 `mh-recursive-folders-flag' is t, then the folders are searched
683 recursively. All parameters ARGS are ignored."
684 (set-buffer (get-buffer-create mh-temp-index-buffer))
686 (unless (executable-find "sh")
687 (error "Didn't find sh"))
689 (let ((seq (symbol-name mh-flists-sequence)))
690 (insert "for folder in `" (expand-file-name "flists" mh-progs) " "
691 (cond ((eq mh-flists-search-folders t)
692 (mh-quote-for-shell mh-inbox))
693 ((eq mh-flists-search-folders nil) "")
694 ((listp mh-flists-search-folders)
695 (loop for folder in mh-flists-search-folders
697 (concat " " (mh-quote-for-shell folder)))))
698 (if mh-recursive-folders-flag " -recurse" "")
699 " -sequence " seq " -noshowzero -fast` ; do\n"
700 (expand-file-name "mhpath" mh-progs) " \"+$folder\" " seq "\n"
703 (point-min) (point-max) "sh" nil (get-buffer mh-temp-index-buffer))))
707 ;;; Folder navigation and utilities
710 (defun mh-index-group-by-folder ()
711 "Partition the messages based on source folder.
712 Returns an alist with the the folder names in the car and the cdr
713 being the list of messages originally from that folder."
715 (goto-char (point-min))
716 (let ((result-table (make-hash-table :test #'equal)))
717 (loop for msg being hash-keys of mh-index-msg-checksum-map
718 do (push msg (gethash (car (gethash
719 (gethash msg mh-index-msg-checksum-map)
720 mh-index-checksum-origin-map))
722 (loop for x being the hash-keys of result-table
723 collect (cons x (nreverse (gethash x result-table)))))))
726 (defun mh-index-insert-folder-headers ()
727 "Annotate the search results with original folder names."
728 (let ((cur-msg (mh-get-msg-num nil))
729 (old-buffer-modified-flag (buffer-modified-p))
730 (buffer-read-only nil)
731 current-folder last-folder)
732 (goto-char (point-min))
734 (setq current-folder (car (gethash (gethash (mh-get-msg-num nil)
735 mh-index-msg-checksum-map)
736 mh-index-checksum-origin-map)))
737 (when (and current-folder (not (equal current-folder last-folder)))
738 (insert (if last-folder "\n" "") current-folder "\n")
739 (setq last-folder current-folder))
743 (mh-goto-msg cur-msg t))
744 (set-buffer-modified-p old-buffer-modified-flag))
745 (mh-index-create-imenu-index))
748 (defun mh-index-delete-folder-headers ()
749 "Delete the folder headers."
750 (let ((cur-msg (mh-get-msg-num nil))
751 (old-buffer-modified-flag (buffer-modified-p))
752 (buffer-read-only nil))
753 (while (and (not cur-msg) (not (eobp)))
755 (setq cur-msg (mh-get-msg-num nil)))
756 (goto-char (point-min))
758 (if (or (char-equal (char-after) ?+) (char-equal (char-after) 10))
759 (delete-region (point) (progn (forward-line) (point)))
761 (when cur-msg (mh-goto-msg cur-msg t t))
762 (set-buffer-modified-p old-buffer-modified-flag)))
765 (defun mh-index-create-imenu-index ()
766 "Create alist of folder names and positions in index folder buffers."
768 (setq which-func-mode t)
770 (goto-char (point-min))
771 (while (re-search-forward "^+" nil t)
774 (push (cons (buffer-substring-no-properties
775 (point) (line-end-position))
776 (set-marker (make-marker) (point)))
778 (setq imenu--index-alist (nreverse alist)))))
781 (defun mh-index-next-folder (&optional backward-flag)
782 "Jump to the next folder marker.
784 With non-nil optional argument BACKWARD-FLAG, jump to the previous
787 (if (null mh-index-data)
788 (message "Only applicable in an MH-E index search buffer")
789 (let ((point (point)))
790 (forward-line (if backward-flag 0 1))
791 (cond ((if backward-flag
792 (re-search-backward "^+" (point-min) t)
793 (re-search-forward "^+" (point-max) t))
795 ((and (if backward-flag
796 (goto-char (point-max))
797 (goto-char (point-min)))
800 (re-search-backward "^+" (point-min) t)
801 (re-search-forward "^+" (point-max) t))
803 (t (goto-char point))))))
806 (defun mh-index-previous-folder ()
807 "Jump to the previous folder marker."
809 (mh-index-next-folder t))
812 (defun mh-index-visit-folder ()
813 "Visit original folder from where the message at point was found."
815 (unless mh-index-data
816 (error "Not in an index folder"))
819 (cond ((and (bolp) (eolp))
820 (ignore-errors (forward-line -1))
821 (setq msg (mh-get-msg-num t)))
822 ((equal (char-after (line-beginning-position)) ?+)
823 (setq folder (buffer-substring-no-properties
824 (line-beginning-position) (line-end-position))))
825 (t (setq msg (mh-get-msg-num t)))))
827 (setq folder (car (gethash (gethash msg mh-index-msg-checksum-map)
828 mh-index-checksum-origin-map))))
829 (when (or (not (get-buffer folder))
830 (y-or-n-p (format "Reuse buffer displaying %s? " folder)))
832 folder (loop for x being the hash-keys of (gethash folder mh-index-data)
833 when (mh-msg-exists-p x folder) collect x)))))
836 (defun mh-search-p ()
837 "Non-nil means that this folder was generated by searching."
841 (defun mh-index-execute-commands ()
842 "Delete/refile the actual messages.
843 The copies in the searched folder are then deleted/refiled to get
844 the desired result. Before deleting the messages we make sure
845 that the message being deleted is identical to the one that the
846 user has marked in the index buffer."
849 (mh-speed-flists-inhibit-flag t))
851 (lambda (folder msgs)
852 (push folder folders)
853 (if (not (get-buffer folder))
854 ;; If source folder not open, just delete the messages...
855 (apply #'mh-exec-cmd "rmm" folder (mh-coalesce-msg-list msgs))
856 ;; Otherwise delete the messages in the source buffer...
859 (let ((old-refile-list mh-refile-list)
860 (old-delete-list mh-delete-list))
861 (setq mh-refile-list nil
863 (unwind-protect (mh-execute-commands)
867 (loop for y in (cdr x)
868 unless (memq y msgs) collect y)))
871 (loop for x in old-delete-list
872 unless (memq x msgs) collect x))
873 (mh-set-folder-modified-p (mh-outstanding-commands-p))
874 (when (mh-outstanding-commands-p)
875 (mh-notate-deleted-and-refiled)))))))
876 (mh-index-matching-source-msgs (append (loop for x in mh-refile-list
884 ;;; Indexing functions
886 ;; Support different search programs
887 (defvar mh-search-choices
889 mh-swish++-binary mh-swish++-execute-search mh-swish++-next-result
890 mh-swish++-regexp-builder)
892 mh-swish-binary mh-swish-execute-search mh-swish-next-result nil)
894 mh-mairix-binary mh-mairix-execute-search mh-mairix-next-result
895 mh-mairix-regexp-builder)
897 mh-namazu-binary mh-namazu-execute-search mh-namazu-next-result nil)
899 mh-pick-binary mh-pick-execute-search mh-pick-next-result
900 mh-pick-regexp-builder)
902 mh-grep-binary mh-grep-execute-search mh-grep-next-result nil))
903 "List of possible searcher choices.")
905 (defun mh-search-choose (&optional searcher)
906 "Choose a searching function.
907 The side-effects of this function are that the variables
908 `mh-searcher', `mh-search-function', and
909 `mh-search-next-result-function' are set according to the first
910 searcher in `mh-search-choices' present on the system. If
911 optional argument SEARCHER is present, use it instead of
912 `mh-search-program'."
914 (let ((program-alist (cond (searcher
915 (list (assoc searcher mh-search-choices)))
918 (assoc mh-search-program mh-search-choices)))
919 (t mh-search-choices))))
921 (let* ((current (pop program-alist))
922 (executable (symbol-value (cadr current))))
924 (setq mh-searcher (car current))
925 (setq mh-search-function (nth 2 current))
926 (setq mh-search-next-result-function (nth 3 current))
927 (setq mh-search-regexp-builder (nth 4 current))
928 (return mh-searcher))))
931 ;;; Swish++ interface
933 (defvar mh-swish++-binary (or (executable-find "search++")
934 (executable-find "search")))
935 (defvar mh-swish++-directory ".swish++")
936 (defvar mh-swish-folder nil)
939 (defun mh-swish++-execute-search (folder-path search-regexp)
942 In the examples below, replace \"/home/user/Mail\" with the path to
945 First create the directory \"/home/user/Mail/.swish++\". Then create
946 the file \"/home/user/Mail/.swish++/swish++.conf\" with the following
949 IncludeMeta Bcc Cc Comments Content-Description From Keywords
950 IncludeMeta Newsgroups Resent-To Subject To
951 IncludeMeta Message-Id References In-Reply-To
953 IndexFile /home/user/Mail/.swish++/swish++.index
955 Use the following command line to generate the swish index. Run
956 this daily from cron:
958 find /home/user/Mail -path /home/user/Mail/mhe-index -prune \\
959 -o -path /home/user/Mail/.swish++ -prune \\
960 -o -name \"[0-9]*\" -print \\
961 | index -c /home/user/Mail/.swish++/swish++.conf -
963 This command does not index the folders that hold the results of your
964 searches in \"+mhe-index\" since they tend to be ephemeral and the
965 original messages are indexed anyway.
967 On some systems (Debian GNU/Linux, for example), use \"index++\"
968 instead of \"index\".
970 In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP is
972 (set-buffer (get-buffer-create mh-temp-index-buffer))
974 (unless mh-swish++-binary
975 (error "Set `mh-swish++-binary' appropriately"))
976 (call-process mh-swish++-binary nil '(t nil) nil
978 (format "-i%s%s/swish++.index"
979 mh-user-path mh-swish++-directory)
981 (goto-char (point-min))
982 (setq mh-swish-folder
983 (let ((last-char (substring folder-path (1- (length folder-path)))))
984 (if (equal last-char "/")
986 (format "%s/" folder-path)))))
988 (defalias 'mh-swish++-next-result 'mh-swish-next-result)
990 (defun mh-swish++-regexp-builder (regexp-list)
991 "Generate query for swish++.
992 REGEXP-LIST is an alist of fields and values."
994 (dolist (elem regexp-list)
996 (setq regexp (concat regexp " and "
997 (if (car elem) "(" "")
998 (if (car elem) (symbol-name (car elem)) "")
999 (if (car elem) " = " "")
1000 (mh-swish++-print-regexp (cdr elem))
1001 (if (car elem) ")" "")))))
1002 (substring regexp 4)))
1004 (defun mh-swish++-print-regexp (expr)
1005 "Return infix expression corresponding to EXPR."
1006 (cond ((atom expr) (format "%s" expr))
1007 ((eq (car expr) 'not)
1008 (format "(not %s)" (mh-swish++-print-regexp (cadr expr))))
1009 (t (format "(%s %s %s)" (mh-swish++-print-regexp (cadr expr))
1010 (symbol-name (car expr))
1011 (mh-swish++-print-regexp (caddr expr))))))
1015 (defvar mh-swish-binary (executable-find "swish-e"))
1016 (defvar mh-swish-directory ".swish")
1019 (defun mh-swish-execute-search (folder-path search-regexp)
1022 In the examples below, replace \"/home/user/Mail\" with the path
1023 to your MH directory.
1025 First create the directory \"/home/user/Mail/.swish\". Then
1026 create the file \"/home/user/Mail/.swish/config\" with the
1029 DefaultContents TXT*
1030 IndexDir /home/user/Mail
1031 IndexFile /home/user/Mail/.swish/index
1032 IndexName \"Mail Index\"
1033 IndexDescription \"Mail Index\"
1034 IndexPointer \"http://nowhere\"
1035 IndexAdmin \"nobody\"
1036 #MetaNames automatic
1040 IgnoreTotalWordCountWhenRanking yes
1041 WordCharacters abcdefghijklmnopqrstuvwxyz0123456789-
1042 BeginCharacters abcdefghijklmnopqrstuvwxyz
1043 EndCharacters abcdefghijklmnopqrstuvwxyz0123456789
1046 FileRules filename contains \\D
1047 FileRules pathname contains /home/user/Mail/.swish
1048 FileRules pathname contains /home/user/Mail/mhe-index
1050 This configuration does not index the folders that hold the
1051 results of your searches in \"+mhe-index\" since they tend to be
1052 ephemeral and the original messages are indexed anyway.
1054 If there are any directories you would like to ignore, append
1055 lines like the following to \"config\":
1057 FileRules pathname contains /home/user/Mail/scripts
1059 Use the following command line to generate the swish index. Run
1060 this daily from cron:
1062 swish-e -c /home/user/Mail/.swish/config
1064 In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP
1066 (set-buffer (get-buffer-create mh-temp-index-buffer))
1068 (unless mh-swish-binary
1069 (error "Set `mh-swish-binary' appropriately"))
1070 (call-process mh-swish-binary nil '(t nil) nil
1072 "-f" (format "%s%s/index" mh-user-path mh-swish-directory))
1073 (goto-char (point-min))
1074 (setq mh-swish-folder
1075 (let ((last-char (substring folder-path (1- (length folder-path)))))
1076 (if (equal last-char "/")
1078 (format "%s/" folder-path)))))
1080 (defun mh-swish-next-result ()
1081 "Get the next result from swish output."
1084 (when (or (eobp) (equal (char-after (point)) ?.))
1086 (when (equal (char-after (point)) ?#)
1088 (let* ((start (search-forward " " (line-end-position) t))
1089 (end (search-forward " " (line-end-position) t)))
1090 (unless (and start end)
1093 (unless (file-exists-p (buffer-substring-no-properties start end))
1095 (unless (search-backward "/" start t)
1097 (list (let* ((s (buffer-substring-no-properties start (1+ (point)))))
1098 (unless (string-match mh-swish-folder s)
1100 (if (and (string-match mh-user-path s)
1101 (< (match-end 0) (1- (length s))))
1103 (substring s (match-end 0) (1- (length s))))
1105 (let* ((s (buffer-substring-no-properties (1+ (point)) end))
1106 (val (ignore-errors (read-from-string s))))
1107 (if (and (consp val) (numberp (car val)))
1113 ;;; Mairix interface
1115 (defvar mh-mairix-binary (executable-find "mairix"))
1116 (defvar mh-mairix-directory ".mairix")
1117 (defvar mh-mairix-folder nil)
1120 (defun mh-mairix-execute-search (folder-path search-regexp-list)
1123 In the examples below, replace \"/home/user/Mail\" with the path
1124 to your MH directory.
1126 First create the directory \"/home/user/Mail/.mairix\". Then
1127 create the file \"/home/user/Mail/.mairix/config\" with the
1130 base=/home/user/Mail
1132 # List of folders that should be indexed. 3 dots at the end means there
1133 # are subfolders within the folder
1134 mh=archive...:inbox:drafts:news:sent:trash
1137 database=/home/user/Mail/mairix/database
1139 Use the following command line to generate the mairix index. Run
1140 this daily from cron:
1142 mairix -f /home/user/Mail/.mairix/config
1144 In a program, FOLDER-PATH is the directory in which
1145 SEARCH-REGEXP-LIST is used to search."
1146 (set-buffer (get-buffer-create mh-temp-index-buffer))
1148 (unless mh-mairix-binary
1149 (error "Set `mh-mairix-binary' appropriately"))
1150 (apply #'call-process mh-mairix-binary nil '(t nil) nil
1151 "-r" "-f" (format "%s%s/config" mh-user-path mh-mairix-directory)
1153 (goto-char (point-min))
1154 (setq mh-mairix-folder
1155 (let ((last-char (substring folder-path (1- (length folder-path)))))
1156 (if (equal last-char "/")
1158 (format "%s/" folder-path)))))
1160 (defun mh-mairix-next-result ()
1161 "Return next result from mairix output."
1164 (when (or (eobp) (and (bolp) (eolp)))
1166 (unless (eq (char-after) ?/)
1168 (let ((start (point))
1170 (setq end (line-end-position))
1171 (unless (search-forward mh-mairix-folder end t)
1173 (goto-char (match-beginning 0))
1174 (unless (equal (point) start)
1177 (unless (search-backward "/" start t)
1179 (setq msg-start (1+ (point)))
1181 (unless (search-forward mh-user-path end t)
1183 (list (format "+%s" (buffer-substring-no-properties
1184 (point) (1- msg-start)))
1185 (car (read-from-string
1186 (buffer-substring-no-properties msg-start end)))
1190 (defun mh-mairix-regexp-builder (regexp-list)
1191 "Generate query for mairix.
1192 REGEXP-LIST is an alist of fields and values."
1194 (dolist (pair regexp-list)
1198 (cond ((eq (car pair) 'to) "t:")
1199 ((eq (car pair) 'from) "f:")
1200 ((eq (car pair) 'cc) "c:")
1201 ((eq (car pair) 'subject) "s:")
1202 ((eq (car pair) 'date) "d:")
1204 (let ((sop (cdr (mh-mairix-convert-to-sop* (cdr pair))))
1206 (dolist (conjunct sop)
1207 (let ((expr-list (cdr conjunct))
1209 (dolist (e expr-list)
1210 (setq expr-string (concat expr-string ","
1211 (if (atom e) "" "~")
1212 (if (atom e) e (cadr e)))))
1213 (setq final (concat final "/" (substring expr-string 1)))))
1214 (substring final 1)))
1218 (defun mh-mairix-convert-to-sop* (expr)
1219 "Convert EXPR to sum of product form."
1220 (cond ((atom expr) `(or (and ,expr)))
1221 ((eq (car expr) 'or)
1223 (loop for e in (mapcar #'mh-mairix-convert-to-sop* (cdr expr))
1225 ((eq (car expr) 'and)
1226 (let ((conjuncts (mapcar #'mh-mairix-convert-to-sop* (cdr expr)))
1228 (setq result (pop conjuncts))
1230 (setq next-factor (pop conjuncts))
1231 (setq result (let ((res ()))
1232 (dolist (t1 (cdr result))
1233 (dolist (t2 (cdr next-factor))
1234 (push `(and ,@(cdr t1) ,@(cdr t2)) res)))
1237 ((atom (cadr expr)) `(or (and ,expr)))
1238 ((eq (caadr expr) 'not) (mh-mairix-convert-to-sop* (cadadr expr)))
1239 ((eq (caadr expr) 'and) (mh-mairix-convert-to-sop*
1240 `(or ,@(mapcar #'(lambda (x) `(not ,x))
1242 ((eq (caadr expr) 'or) (mh-mairix-convert-to-sop*
1243 `(and ,@(mapcar #'(lambda (x) `(not ,x))
1245 (t (error "Unreachable: %s" expr))))
1247 ;;; Namazu interface
1249 (defvar mh-namazu-binary (executable-find "namazu"))
1250 (defvar mh-namazu-directory ".namazu")
1251 (defvar mh-namazu-folder nil)
1254 (defun mh-namazu-execute-search (folder-path search-regexp)
1257 In the examples below, replace \"/home/user/Mail\" with the path to
1260 First create the directory \"/home/user/Mail/.namazu\". Then create
1261 the file \"/home/user/Mail/.namazu/mknmzrc\" with the following
1264 package conf; # Don't remove this line!
1265 $ADDRESS = 'user@localhost';
1266 $ALLOW_FILE = \"[0-9]*\";
1267 $EXCLUDE_PATH = \"^/home/user/Mail/(mhe-index|spam)\";
1269 This configuration does not index the folders that hold the results of
1270 your searches in \"+mhe-index\" since they tend to be ephemeral and
1271 the original messages are indexed anyway.
1273 Use the following command line to generate the namazu index. Run this
1276 mknmz -f /home/user/Mail/.namazu/mknmzrc -O /home/user/Mail/.namazu \\
1279 In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP
1281 (let ((namazu-index-directory
1282 (format "%s%s" mh-user-path mh-namazu-directory)))
1283 (unless (file-exists-p namazu-index-directory)
1284 (error "Namazu directory %s not present" namazu-index-directory))
1285 (unless (executable-find mh-namazu-binary)
1286 (error "Set `mh-namazu-binary' appropriately"))
1287 (set-buffer (get-buffer-create mh-temp-index-buffer))
1289 (call-process mh-namazu-binary nil '(t nil) nil
1290 "-alR" search-regexp namazu-index-directory)
1291 (goto-char (point-min))
1292 (setq mh-namazu-folder
1293 (let ((last (substring folder-path (1- (length folder-path)))))
1294 (if (equal last "/")
1296 (format "%s/" folder-path))))))
1298 (defun mh-namazu-next-result ()
1299 "Get the next result from namazu output."
1302 (when (eobp) (return nil))
1303 (let ((file-name (buffer-substring-no-properties
1304 (point) (line-end-position))))
1305 (unless (equal (string-match mh-namazu-folder file-name) 0)
1307 (unless (file-exists-p file-name)
1309 (string-match mh-user-path file-name)
1310 (let* ((folder/msg (substring file-name (match-end 0)))
1311 (mark (mh-search-from-end ?/ folder/msg)))
1312 (unless mark (return 'error))
1313 (list (format "+%s" (substring folder/msg 0 mark))
1314 (let ((n (ignore-errors (read-from-string
1315 (substring folder/msg (1+ mark))))))
1316 (if (and (consp n) (numberp (car n)))
1324 (defvar mh-index-pick-folder)
1325 (defvar mh-pick-binary "pick")
1326 (defconst mh-pick-single-dash '(cc date from subject to)
1327 "Search components that are supported by single-dash option in pick.")
1330 (defun mh-pick-execute-search (folder-path search-regexp)
1333 Read \"pick(1)\" or the section Finding Messages with pick in the
1334 MH book to find out more about how to enter the criteria (see URL
1335 `http://www.ics.uci.edu/~mh/book/mh/finpic.htm').
1337 In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP
1339 (set-buffer (get-buffer-create mh-temp-index-buffer))
1342 (mh-folder-list (substring folder-path (length mh-user-path)))))
1343 (loop for folder in folders do
1344 (setq folder (concat "+" folder))
1345 (insert folder "\n")
1346 (apply #'call-process (expand-file-name "pick" mh-progs)
1347 nil '(t nil) nil folder "-list" search-regexp)))
1348 (goto-char (point-min)))
1350 (defun mh-pick-next-result ()
1351 "Return the next pick search result."
1354 (when (eobp) (return nil))
1355 (when (search-forward-regexp "^\+" (line-end-position) t)
1356 (setq mh-index-pick-folder
1357 (buffer-substring-no-properties (line-beginning-position)
1358 (line-end-position)))
1360 (unless (search-forward-regexp "^[1-9][0-9]*$" (line-end-position) t)
1362 (list mh-index-pick-folder
1364 (buffer-substring-no-properties (line-beginning-position)
1365 (line-end-position)))
1369 ;; All implementations of pick have special options -cc, -date, -from and
1370 ;; -subject that allow to search for corresponding components. Any other
1371 ;; component is searched using option --COMPNAME, for example: `pick
1372 ;; --x-mailer mh-e'. Mailutils "pick" supports this option using a certain
1373 ;; kludge, but it prefers the following syntax for this purpose:
1374 ;; "--component=COMPNAME --pattern=PATTERN".
1375 ;; -- Sergey Poznyakoff, Aug 2003
1376 (defun mh-pick-regexp-builder (pattern-list)
1377 "Generate pick search expression from PATTERN-LIST."
1379 (dolist (pattern pattern-list)
1381 (setq result `(,@result "-and" "-lbrace"
1382 ,@(mh-pick-construct-regexp
1383 (if (and (mh-variant-p 'mu-mh) (car pattern))
1384 (format "--pattern=%s" (cdr pattern))
1388 ((mh-variant-p 'mu-mh)
1389 (format "--component=%s" (car pattern)))
1390 ((member (car pattern) mh-pick-single-dash)
1391 (format "-%s" (car pattern)))
1393 (format "--%s" (car pattern))))
1398 (defun mh-pick-construct-regexp (expr component)
1399 "Construct pick compatible expression corresponding to EXPR.
1400 COMPONENT is the component to search."
1401 (cond ((atom expr) (list component expr))
1402 ((eq (car expr) 'and)
1403 `("-lbrace" ,@(mh-pick-construct-regexp (cadr expr) component) "-and"
1404 ,@(mh-pick-construct-regexp (caddr expr) component) "-rbrace"))
1405 ((eq (car expr) 'or)
1406 `("-lbrace" ,@(mh-pick-construct-regexp (cadr expr) component) "-or"
1407 ,@(mh-pick-construct-regexp (caddr expr) component) "-rbrace"))
1408 ((eq (car expr) 'not)
1409 `("-lbrace" "-not" ,@(mh-pick-construct-regexp (cadr expr) component)
1411 (t (error "Unknown operator %s seen" (car expr)))))
1415 (defvar mh-grep-binary (executable-find "grep"))
1418 (defun mh-grep-execute-search (folder-path search-regexp)
1421 Unlike the other search methods, this method does not use the
1422 MH-Search buffer. Instead, you simply enter a regular expression
1423 in the minibuffer. For help in constructing regular expressions,
1424 see your man page for \"grep\".
1426 In a program, FOLDER-PATH is the directory in which SEARCH-REGEXP
1428 (set-buffer (get-buffer-create mh-temp-index-buffer))
1430 (call-process mh-grep-binary nil '(t nil) nil
1431 "-i" "-r" search-regexp folder-path)
1432 (goto-char (point-min)))
1434 (defun mh-grep-next-result ()
1435 "Read the next result.
1436 Parse it and return the message folder, message index and the
1437 match. If no other matches left then return nil. If the current
1438 record is invalid return 'error."
1443 (let ((eol-pos (line-end-position))
1444 (bol-pos (line-beginning-position))
1445 folder-start msg-end)
1447 (unless (search-forward mh-user-path eol-pos t)
1449 (setq folder-start (point))
1450 (unless (search-forward ":" eol-pos t)
1452 (let ((match (buffer-substring-no-properties (point) eol-pos)))
1454 (setq msg-end (point))
1455 (unless (search-backward "/" folder-start t)
1457 (list (format "+%s" (buffer-substring-no-properties
1458 folder-start (point)))
1459 (let ((val (ignore-errors (read-from-string
1460 (buffer-substring-no-properties
1461 (1+ (point)) msg-end)))))
1462 (if (and (consp val) (integerp (car val)))
1472 (defun mh-index-generate-pretty-name (string)
1473 "Given STRING generate a name which is suitable for use as a folder name.
1474 White space from the beginning and end are removed. All spaces in
1475 the name are replaced with underscores and all / are replaced
1476 with $. If STRING is longer than 20 it is truncated too. STRING
1477 could be a list of strings in which case they are concatenated to
1478 construct the base name."
1480 (if (stringp string)
1482 (when (car string) (insert (car string)))
1483 (dolist (s (cdr string))
1485 (setq string (mh-replace-string "-lbrace" " "))
1486 (setq string (mh-replace-string "-rbrace" " "))
1487 (setq string (mh-replace-string "-search" " "))
1488 (subst-char-in-region (point-min) (point-max) ?( ? t)
1489 (subst-char-in-region (point-min) (point-max) ?) ? t)
1490 (subst-char-in-region (point-min) (point-max) ?- ? t)
1491 (goto-char (point-min))
1492 (while (and (not (eobp)) (memq (char-after) '(? ?\t ?\n ?\r ?_)))
1494 (goto-char (point-max))
1495 (while (and (not (bobp)) (memq (char-before) '(? ?\t ?\n ?\r ?_)))
1496 (delete-backward-char 1))
1497 (subst-char-in-region (point-min) (point-max) ? ?_ t)
1498 (subst-char-in-region (point-min) (point-max) ?\t ?_ t)
1499 (subst-char-in-region (point-min) (point-max) ?\n ?_ t)
1500 (subst-char-in-region (point-min) (point-max) ?\r ?_ t)
1501 (subst-char-in-region (point-min) (point-max) ?/ ?$ t)
1502 (let ((out (truncate-string-to-width (buffer-string) 20)))
1503 (cond ((eq mh-searcher 'flists)
1504 (format "%s/%s" mh-flists-results-folder mh-flists-sequence))
1505 ((equal out mh-flists-results-folder) (concat out "1"))
1508 (defun mh-folder-exists-p (folder)
1509 "Check if FOLDER exists."
1510 (and (mh-folder-name-p folder)
1513 (mh-exec-cmd-output "folder" nil "-fast" "-nocreate" folder)
1514 (goto-char (point-min))
1517 (defun mh-msg-exists-p (msg folder)
1518 "Check if MSG exists in FOLDER."
1519 (file-exists-p (format "%s%s/%s" mh-user-path (substring folder 1) msg)))
1521 (defun mh-index-new-folder (name search-regexp)
1522 "Return a folder name based on NAME for search results of SEARCH-REGEXP.
1524 If folder NAME already exists and was generated for the same
1525 SEARCH-REGEXP then it is reused.
1527 Otherwise if the folder NAME was generated from a different
1528 search then check if NAME<2> can be used. Otherwise try NAME<3>.
1529 This is repeated till we find a new folder name.
1531 If the folder returned doesn't exist then it is created."
1532 (unless (mh-folder-name-p name)
1533 (error "The argument should be a valid MH folder name"))
1536 for candidate = (if (equal i 1) name (format "%s<%s>" name i))
1537 when (or (not (mh-folder-exists-p candidate))
1538 (equal (mh-index-folder-search-regexp candidate)
1541 ;; Do pending refiles/deletes...
1542 (when (get-buffer chosen-name)
1543 (mh-process-or-undo-commands chosen-name))
1544 ;; Recreate folder...
1545 (save-excursion (mh-exec-cmd-quiet nil "rmf" chosen-name))
1546 (mh-exec-cmd-quiet nil "folder" "-create" "-fast" chosen-name)
1547 (mh-remove-from-sub-folders-cache chosen-name)
1548 (when (boundp 'mh-speed-folder-map)
1549 (mh-speed-add-folder chosen-name))
1552 (defun mh-index-folder-search-regexp (folder)
1553 "If FOLDER was created by a index search, return the search regexp.
1554 Return nil if FOLDER doesn't exist or the .mhe_index file is
1558 (insert-file-contents
1559 (format "%s%s/%s" mh-user-path (substring folder 1) mh-index-data-file))
1560 (goto-char (point-min))
1562 (cadr (read (current-buffer))))))
1566 ;;; Sequence support
1569 (defun mh-index-create-sequences ()
1570 "Mirror sequences present in source folders in index folder."
1571 (let ((seq-hash (make-hash-table :test #'equal))
1573 (loop for folder being the hash-keys of mh-index-data
1574 do (setf (gethash folder seq-hash)
1575 (mh-create-sequence-map
1576 (mh-read-folder-sequences folder nil))))
1577 (dolist (msg (mh-translate-range mh-current-folder "all"))
1578 (let* ((checksum (gethash msg mh-index-msg-checksum-map))
1579 (pair (gethash checksum mh-index-checksum-origin-map))
1580 (ofolder (car pair))
1582 (loop for seq in (ignore-errors
1583 (gethash omsg (gethash ofolder seq-hash)))
1584 do (if (assoc seq seq-list)
1585 (push msg (cdr (assoc seq seq-list)))
1586 (push (list seq msg) seq-list)))))
1587 (loop for seq in seq-list
1588 do (apply #'mh-exec-cmd "mark" mh-current-folder
1589 "-sequence" (symbol-name (car seq)) "-add"
1590 (mapcar #'(lambda (x) (format "%s" x)) (cdr seq))))))
1593 (defun mh-create-sequence-map (seq-list)
1594 "Return a map from msg number to list of sequences in which it is present.
1595 SEQ-LIST is an assoc list whose keys are sequence names and whose
1596 cdr is the list of messages in that sequence."
1597 (loop with map = (make-hash-table)
1599 when (and (not (memq (car seq) (mh-unpropagated-sequences)))
1600 (mh-valid-seq-p (car seq)))
1601 do (loop for msg in (cdr seq)
1602 do (push (car seq) (gethash msg map)))
1603 finally return map))
1606 (defun mh-index-add-to-sequence (seq msgs)
1607 "Add to SEQ the messages in the list MSGS.
1608 This function updates the source folder sequences. Also makes an
1609 attempt to update the source folder buffer if we have it open."
1610 ;; Don't need to do anything for cur
1612 (when (and (not (memq seq (mh-unpropagated-sequences)))
1613 (mh-valid-seq-p seq))
1615 (mh-speed-flists-inhibit-flag t))
1616 (maphash (lambda (folder msgs)
1617 (push folder folders)
1618 ;; Add messages to sequence in source folder...
1619 (apply #'mh-exec-cmd-quiet nil "mark" folder
1620 "-add" "-nozero" "-sequence" (symbol-name seq)
1621 (mapcar (lambda (x) (format "%s" x))
1622 (mh-coalesce-msg-list msgs)))
1623 ;; Update source folder buffer if we have it open...
1624 (when (get-buffer folder)
1627 (mh-put-msg-in-seq msgs seq))))
1628 (mh-index-matching-source-msgs msgs))
1632 (defun mh-index-delete-from-sequence (seq msgs)
1633 "Delete from SEQ the messages in MSGS.
1634 This function updates the source folder sequences. Also makes an
1635 attempt to update the source folder buffer if present."
1637 (when (and (not (memq seq (mh-unpropagated-sequences)))
1638 (mh-valid-seq-p seq))
1640 (mh-speed-flists-inhibit-flag t))
1641 (maphash (lambda (folder msgs)
1642 (push folder folders)
1643 ;; Remove messages from sequence in source folder...
1644 (apply #'mh-exec-cmd-quiet nil "mark" folder
1645 "-del" "-nozero" "-sequence" (symbol-name seq)
1646 (mapcar (lambda (x) (format "%s" x))
1647 (mh-coalesce-msg-list msgs)))
1648 ;; Update source folder buffer if we have it open...
1649 (when (get-buffer folder)
1652 (mh-delete-msg-from-seq msgs seq t))))
1653 (mh-index-matching-source-msgs msgs))
1656 (defvar mh-unpropagated-sequences '(cur range subject search)
1657 "List of sequences that aren't preserved.")
1659 (defun mh-unpropagated-sequences ()
1660 "Return a list of sequences that aren't propagated to the source folders.
1661 It is just the sequences in the variable
1662 `mh-unpropagated-sequences' in addition to the
1663 Previous-Sequence (see mh-profile 5)."
1665 (cons mh-previous-seq mh-unpropagated-sequences)
1666 mh-unpropagated-sequences))
1668 (defun mh-index-matching-source-msgs (msgs &optional delete-from-index-data)
1669 "Return a table of original messages and folders for messages in MSGS.
1670 If optional argument DELETE-FROM-INDEX-DATA is non-nil, then each
1671 of the messages, whose counter-part is found in some source
1672 folder, is removed from `mh-index-data'."
1673 (let ((table (make-hash-table :test #'equal)))
1675 (let* ((checksum (gethash msg mh-index-msg-checksum-map))
1676 (pair (gethash checksum mh-index-checksum-origin-map)))
1677 (when (and checksum (car pair) (cdr pair)
1678 (mh-index-match-checksum (cdr pair) (car pair) checksum))
1679 (push (cdr pair) (gethash (car pair) table))
1680 (when delete-from-index-data
1681 (remhash (cdr pair) (gethash (car pair) mh-index-data))))))
1684 (defun mh-index-match-checksum (msg folder checksum)
1685 "Check if MSG in FOLDER has X-MHE-Checksum header value of CHECKSUM."
1687 (mh-exec-cmd-output mh-scan-prog nil "-width" "80"
1688 "-format" "%{x-mhe-checksum}\n" folder msg)
1689 (goto-char (point-min))
1690 (string-equal (buffer-substring-no-properties (point) (line-end-position))
1695 ;;; Serialization of index data
1697 (defun mh-index-write-data ()
1698 "Write index data to file."
1700 (unless (eq major-mode 'mh-folder-mode)
1701 (error "Can't be called from folder in \"%s\"" major-mode))
1702 (let ((data mh-index-data)
1703 (msg-checksum-map mh-index-msg-checksum-map)
1704 (checksum-origin-map mh-index-checksum-origin-map)
1705 (previous-search mh-index-previous-search)
1706 (sequence-search-flag mh-index-sequence-search-flag)
1707 (outfile (concat buffer-file-name mh-index-data-file))
1710 (with-temp-file outfile
1711 (mh-index-write-hashtable
1712 data (lambda (x) (loop for y being the hash-keys of x collect y)))
1713 (mh-index-write-hashtable msg-checksum-map #'identity)
1714 (mh-index-write-hashtable checksum-origin-map #'identity)
1715 (pp previous-search (current-buffer)) (insert "\n")
1716 (pp sequence-search-flag (current-buffer)) (insert "\n")))))
1718 (defun mh-index-write-hashtable (table proc)
1719 "Write TABLE to `current-buffer'.
1720 PROC is used to serialize the values corresponding to the hash
1722 (pp (loop for x being the hash-keys of table
1723 collect (cons x (funcall proc (gethash x table))))
1728 (defun mh-index-read-data ()
1729 "Read index data from file."
1731 (unless (eq major-mode 'mh-folder-mode)
1732 (error "Can't be called from folder in \"%s\"" major-mode))
1733 (let ((infile (concat buffer-file-name mh-index-data-file))
1736 (insert-file-contents-literally infile)
1737 (goto-char (point-min))
1738 (setq t1 (mh-index-read-hashtable
1740 (loop with table = (make-hash-table :test #'equal)
1741 for x in data do (setf (gethash x table) t)
1742 finally return table)))
1743 t2 (mh-index-read-hashtable #'identity)
1744 t3 (mh-index-read-hashtable #'identity)
1745 t4 (read (current-buffer))
1746 t5 (read (current-buffer))))
1747 (setq mh-index-data t1
1748 mh-index-msg-checksum-map t2
1749 mh-index-checksum-origin-map t3
1750 mh-index-previous-search t4
1751 mh-index-sequence-search-flag t5))))
1753 (defun mh-index-read-hashtable (proc)
1754 "From BUFFER read a hash table serialized as a list.
1755 PROC is used to convert the value to actual data."
1756 (loop with table = (make-hash-table :test #'equal)
1757 for pair in (read (current-buffer))
1758 do (setf (gethash (car pair) table) (funcall proc (cdr pair)))
1759 finally return table))
1763 ;;; Checksum routines
1765 ;; A few different checksum programs are supported. The supported programs
1772 ;; To add support for your favorite checksum program add a clause to the cond
1773 ;; statement in mh-checksum-choose. This should set the variable
1774 ;; mh-checksum-cmd to the command line needed to run the checsum program and
1775 ;; should set mh-checksum-parser to a function which returns a cons cell
1776 ;; containing the message number and checksum string.
1778 (defvar mh-checksum-cmd)
1779 (defvar mh-checksum-parser)
1781 (defun mh-checksum-choose ()
1782 "Check if a program to create a checksum is present."
1783 (unless (boundp 'mh-checksum-cmd)
1784 (let ((exec-path (append '("/sbin" "/usr/sbin") exec-path)))
1785 (cond ((executable-find "md5sum")
1786 (setq mh-checksum-cmd (list (executable-find "md5sum")))
1787 (setq mh-checksum-parser #'mh-md5sum-parser))
1788 ((executable-find "openssl")
1789 (setq mh-checksum-cmd (list (executable-find "openssl") "md5"))
1790 (setq mh-checksum-parser #'mh-openssl-parser))
1791 ((executable-find "md5")
1792 (setq mh-checksum-cmd (list (executable-find "md5")))
1793 (setq mh-checksum-parser #'mh-md5-parser))
1794 (t (error "No suitable checksum program"))))))
1796 (defun mh-md5sum-parser ()
1797 "Parse md5sum output."
1798 (let ((begin (line-beginning-position))
1799 (end (line-end-position))
1800 first-space last-slash)
1801 (setq first-space (search-forward " " end t))
1803 (setq last-slash (search-backward "/" begin t))
1804 (cond ((and first-space last-slash)
1805 (cons (car (read-from-string (buffer-substring-no-properties
1806 (1+ last-slash) end)))
1807 (buffer-substring-no-properties begin (1- first-space))))
1808 (t (cons nil nil)))))
1810 (defun mh-openssl-parser ()
1811 "Parse openssl output."
1812 (let ((begin (line-beginning-position))
1813 (end (line-end-position))
1814 last-space last-slash)
1816 (setq last-space (search-backward " " begin t))
1817 (setq last-slash (search-backward "/" begin t))
1818 (cond ((and last-slash last-space)
1819 (cons (car (read-from-string (buffer-substring-no-properties
1820 (1+ last-slash) (1- last-space))))
1821 (buffer-substring-no-properties (1+ last-space) end))))))
1823 (defalias 'mh-md5-parser 'mh-openssl-parser)
1826 (defun mh-index-update-maps (folder &optional origin-map)
1827 "Annotate all as yet unannotated messages in FOLDER with their MD5 hash.
1828 As a side effect msg -> checksum map is updated. Optional
1829 argument ORIGIN-MAP is a hashtable which maps each message in the
1830 index folder to the original folder and message from whence it
1831 was copied. If present the checksum -> (origin-folder,
1832 origin-index) map is updated too."
1833 (clrhash mh-index-msg-checksum-map)
1835 ;; Clear temp buffer
1836 (set-buffer (get-buffer-create mh-temp-checksum-buffer))
1838 ;; Run scan to check if any messages needs MD5 annotations at all
1840 (mh-exec-cmd-output mh-scan-prog nil "-width" "80"
1841 "-format" "%(msg)\n%{x-mhe-checksum}\n"
1843 (goto-char (point-min))
1846 (setq msg (buffer-substring-no-properties
1847 (point) (line-end-position)))
1850 (cond ((not (string-match "^[0-9]*$" msg)))
1852 ;; need to compute checksum
1853 (set-buffer mh-temp-checksum-buffer)
1854 (insert mh-user-path (substring folder 1) "/" msg "\n"))
1857 (setq checksum (buffer-substring-no-properties
1858 (point) (line-end-position)))
1859 (let ((msg (car (read-from-string msg))))
1861 (mh-index-update-single-msg msg checksum origin-map)))))
1863 ;; Run checksum program if needed
1864 (unless (and (eobp) (bobp))
1865 (apply #'mh-xargs mh-checksum-cmd)
1866 (goto-char (point-min))
1868 (let* ((intermediate (funcall mh-checksum-parser))
1869 (msg (car intermediate))
1870 (checksum (cdr intermediate)))
1873 (mh-exec-cmd "anno" folder msg "-component" "X-MHE-Checksum"
1874 "-nodate" "-text" checksum "-inplace")
1878 (mh-index-update-single-msg msg checksum origin-map)))
1880 (mh-index-write-data))
1882 (defun mh-index-update-single-msg (msg checksum origin-map)
1883 "Update various maps for one message.
1884 MSG is a index folder message, CHECKSUM its MD5 hash and
1885 ORIGIN-MAP, if non-nil, a hashtable containing which maps each
1886 message in the index folder to the folder and message that it was
1887 copied from. The function updates the hash tables
1888 `mh-index-msg-checksum-map' and `mh-index-checksum-origin-map'.
1890 This function should only be called in the appropriate index
1892 (cond ((and origin-map (gethash checksum mh-index-checksum-origin-map))
1893 (let* ((intermediate (gethash msg origin-map))
1894 (ofolder (car intermediate))
1895 (omsg (cdr intermediate)))
1896 ;; This is most probably a duplicate. So eliminate it.
1897 (call-process "rm" nil nil nil
1898 (format "%s%s/%s" mh-user-path
1899 (substring mh-current-folder 1) msg))
1900 (when (gethash ofolder mh-index-data)
1901 (remhash omsg (gethash ofolder mh-index-data)))))
1903 (setf (gethash msg mh-index-msg-checksum-map) checksum)
1905 (setf (gethash checksum mh-index-checksum-origin-map)
1906 (gethash msg origin-map))))))
1908 (provide 'mh-search)
1911 ;; indent-tabs-mode: nil
1912 ;; sentence-end-double-space: nil
1915 ;; arch-tag: 607762ad-0dff-4fe1-a27e-6c0dde0dcc47
1916 ;;; mh-search ends here