* lsdb.el (lsdb-mode-save): Fix `y-or-n-p' prompt.
[elisp/lsdb.git] / lsdb.el
1 ;;; lsdb.el --- the Lovely Sister Database
2
3 ;; Copyright (C) 2002 Daiki Ueno
4
5 ;; Author: Daiki Ueno <ueno@unixuser.org>
6 ;; Keywords: adress book
7
8 ;; This file is part of the Lovely Sister Database.
9
10 ;; This program is free software; you can redistribute it and/or
11 ;; modify it under the terms of the GNU General Public License as
12 ;; published by the Free Software Foundation; either version 2, or (at
13 ;; your option) any later version.
14
15 ;; This program is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 ;; General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; For Semi-gnus:
28 ;;; (autoload 'lsdb-gnus-insinuate "lsdb")
29 ;;; (autoload 'lsdb-gnus-insinuate-message "lsdb")
30 ;;; (add-hook 'gnus-startup-hook 'lsdb-gnus-insinuate)
31 ;;; (add-hook 'message-setup-hook
32 ;;;           (lambda ()
33 ;;;             (define-key message-mode-map "\M-\t" 'lsdb-complete-name)))
34 ;;; (add-hook 'gnus-summary-mode-hook
35 ;;;           (lambda ()
36 ;;;             (define-key gnus-summary-mode-map ":" 'lsdb-toggle-buffer)))
37
38 ;;; For Wanderlust, put the following lines into your ~/.wl:
39 ;;; (require 'lsdb)
40 ;;; (lsdb-wl-insinuate)
41 ;;; (add-hook 'wl-draft-mode-hook
42 ;;;           (lambda ()
43 ;;;             (define-key wl-draft-mode-map "\M-\t" 'lsdb-complete-name)))
44 ;;; (add-hook 'wl-summary-mode-hook
45 ;;;           (lambda ()
46 ;;;             (define-key wl-summary-mode-map ":" 'lsdb-wl-toggle-buffer)))
47
48 ;;; For Mew, put the following lines into your ~/.mew:
49 ;;; (autoload 'lsdb-mew-insinuate "lsdb")
50 ;;; (add-hook 'mew-init-hook 'lsdb-mew-insinuate)
51 ;;; (add-hook 'mew-draft-mode-hook
52 ;;;           (lambda ()
53 ;;;             (define-key mew-draft-header-map "\M-I" 'lsdb-complete-name)))
54 ;;; (add-hook 'mew-summary-mode-hook
55 ;;;           (lambda ()
56 ;;;             (define-key mew-summary-mode-map "l" 'lsdb-toggle-buffer)))
57
58 ;;; Code:
59
60 (require 'poem)
61 (require 'pces)
62 (require 'mime)
63 (require 'static)
64
65 ;;;_* USER CUSTOMIZATION VARIABLES:
66 (defgroup lsdb nil
67   "The Lovely Sister Database."
68   :group 'news
69   :group 'mail)
70   
71 (defcustom lsdb-file (expand-file-name "~/.lsdb")
72   "The name of the Lovely Sister Database file."
73   :group 'lsdb
74   :type 'file)
75
76 (defcustom lsdb-file-coding-system (find-coding-system 'iso-2022-jp)
77   "Coding system for `lsdb-file'."
78   :group 'lsdb
79   :type 'symbol)
80
81 (defcustom lsdb-sender-headers
82   "From\\|Resent-From"
83   "List of headers to search for senders."
84   :group 'lsdb
85   :type 'list)
86
87 (defcustom lsdb-recipients-headers
88   "Resent-To\\|Resent-Cc\\|Reply-To\\|To\\|Cc\\|Bcc"
89   "List of headers to search for recipients."
90   :group 'lsdb
91   :type 'list)
92
93 (defcustom lsdb-interesting-header-alist
94   '(("Organization" nil organization)
95     ("\\(X-\\)?User-Agent\\|X-Mailer\\|X-Newsreader" nil user-agent)
96     ("\\(X-\\)?ML-Name" nil mailing-list)
97     ("List-Id" "\\(.*\\)[ \t]+<[^>]+>\\'" mailing-list "\\1")
98     ("X-Sequence" "\\(.*\\)[ \t]+[0-9]+\\'" mailing-list "\\1")
99     ("Delivered-To" "mailing list[ \t]+\\([^@]+\\)@.*" mailing-list "\\1")
100     ("\\(X-URL\\|X-URI\\)" nil www)
101     ("X-Attribution\\|X-cite-me" nil attribution)
102     ("X-Face" nil x-face))
103   "Alist of headers we are interested in.
104 The format of elements of this list should be
105      (FIELD-NAME REGEXP ENTRY STRING)
106 where the last three elements are optional."
107   :group 'lsdb
108   :type 'list)
109
110 (defcustom lsdb-entry-type-alist
111   '((net 5 ?,)
112     (creation-date 2 ?. t)
113     (last-modified 3 ?. t)
114     (mailing-list 4 ?,)
115     (attribution 4 ?.)
116     (organization 4)
117     (www 4)
118     (aka 4 ?,)
119     (score -1)
120     (x-face -1))
121   "Alist of entry types for presentation.
122 The format of elements of this list should be
123      (ENTRY SCORE [CLASS READ-ONLY])
124 where the last two elements are optional.
125 Possible values for CLASS are `?.' and '?,'.  If CLASS is `?.', the
126 entry takes a unique value which is overridden by newly assigned one
127 by `lsdb-mode-edit-entry' or such a command.  If CLASS is `?,', the
128 entry can have multiple values separated by commas.
129 If the fourth element READ-ONLY is non-nil, it is assumed that the
130 entry cannot be modified."
131   :group 'lsdb
132   :type 'list)
133
134 (defcustom lsdb-decode-field-body-function #'lsdb-decode-field-body
135   "Field body decoder."
136   :group 'lsdb
137   :type 'function)
138
139 (defcustom lsdb-canonicalize-full-name-function
140   #'lsdb-canonicalize-spaces-and-dots
141   "Way to canonicalize full name."
142   :group 'lsdb
143   :type 'function)
144
145 (defcustom lsdb-lookup-full-name-functions
146   '(lsdb-lookup-full-name-from-address-cache)
147   "List of functions to pick up the existing full-name of the sender.
148 The sender is passed to each function as the argument."
149   :group 'lsdb
150   :type 'hook)
151
152 (defcustom lsdb-update-record-functions
153   '(lsdb-update-address-cache)
154   "List of functions called after a record is updated.
155 The updated record is passed to each function as the argument."
156   :group 'lsdb
157   :type 'hook)
158
159 (defcustom lsdb-secondary-hash-tables
160   '(lsdb-address-cache)
161   "List of the hash tables for reverse lookup"
162   :group 'lsdb
163   :type 'list)
164
165 (defcustom lsdb-window-max-height 7
166   "Maximum number of lines used to display LSDB record."
167   :group 'lsdb
168   :type 'integer)
169
170 (defcustom lsdb-x-face-image-type nil
171   "A image type of displayed x-face.
172 If non-nil, supersedes the return value of `lsdb-x-face-available-image-type'."
173   :group 'lsdb
174   :type 'symbol)
175
176 (defcustom lsdb-x-face-command-alist
177   '((pbm "{ echo '/* Width=48, Height=48 */'; uncompface; } | icontopbm | pnmscale 0.5")
178     (xpm "{ echo '/* Width=48, Height=48 */'; uncompface; } | icontopbm | pnmscale 0.5 | ppmtoxpm"))
179   "An alist from an image type to a command to be executed to display an X-Face header.
180 The command will be executed in a sub-shell asynchronously.
181 The compressed face will be piped to this command."
182   :group 'lsdb
183   :type 'list)
184
185 (defcustom lsdb-insert-x-face-function
186   (if (static-if (featurep 'xemacs)
187           (featurep 'xpm)
188         (and (>= emacs-major-version 21)
189              (fboundp 'image-type-available-p)
190              (or (image-type-available-p 'pbm)
191                  (image-type-available-p 'xpm))))
192       #'lsdb-insert-x-face-asynchronously)
193   "Function to display X-Face."
194   :group 'lsdb
195   :type 'function)
196
197 (defcustom lsdb-print-record-hook '(lsdb-expose-x-face)
198   "A hook called after a record is displayed."
199   :group 'lsdb
200   :type 'hook)
201
202 (defcustom lsdb-display-records-sort-predicate nil
203   "A predicate to sort records."
204   :group 'lsdb
205   :type 'function)
206
207 (defcustom lsdb-pop-up-windows t
208   "Non-nil means LSDB should make new windows to display records."
209   :group 'lsdb
210   :type 'boolean)
211
212 (defgroup lsdb-edit-form nil
213   "A mode for editing forms."
214   :group 'lsdb)
215
216 (defcustom lsdb-edit-form-mode-hook nil
217   "Hook run in `lsdb-edit-form-mode' buffers."
218   :group 'lsdb-edit-form
219   :type 'hook)
220
221 (defcustom lsdb-shell-file-name "/bin/sh"
222   "File name to load inferior shells from.
223 Bourne shell or its equivalent \(not tcsh) is needed for \"2>\"."
224   :group 'lsdb
225   :type 'string)
226
227 (defcustom lsdb-shell-command-switch "-c"
228   "Switch used to have the shell execute its command line argument."
229   :group 'lsdb
230   :type 'string)
231
232 ;;;_. Faces
233 (defface lsdb-header-face
234   '((t (:underline t)))
235   "Face for the file header line in `lsdb-mode'."
236   :group 'lsdb)
237 (defvar lsdb-header-face 'lsdb-header-face)
238
239 (defface lsdb-field-name-face
240   '((((class color) (background dark))
241      (:foreground "PaleTurquoise" :bold t))
242     (t (:bold t)))
243   "Face for the message header line in `lsdb-mode'."
244   :group 'lsdb)
245 (defvar lsdb-field-name-face 'lsdb-field-name-face)
246
247 (defface lsdb-field-body-face
248   '((((class color) (background dark))
249      (:foreground "turquoise" :italic t))
250     (t (:italic t)))
251   "Face for the message header line in `lsdb-mode'."
252   :group 'lsdb)
253 (defvar lsdb-field-body-face 'lsdb-field-body-face)
254
255 (defconst lsdb-font-lock-keywords
256   '(("^\\sw[^\r\n]*"
257      (0 lsdb-header-face))
258     ("^\t\t.*$"
259      (0 lsdb-field-body-face))
260     ("^\t\\([^\t:]+:\\)[ \t]*\\(.*\\)$"
261      (1 lsdb-field-name-face)
262      (2 lsdb-field-body-face))))
263
264 (put 'lsdb-mode 'font-lock-defaults '(lsdb-font-lock-keywords t))
265
266 ;;;_* CODE - no user customizations below
267 ;;;_. Internal Variables
268 (defvar lsdb-hash-table nil
269   "Internal hash table to hold LSDB records.")
270
271 (defvar lsdb-address-cache nil
272   "The reverse lookup table for `lsdb-hash-table'.
273 It represents address to full-name mapping.")
274
275 (defvar lsdb-buffer-name "*LSDB*"
276   "Buffer name to display LSDB record.")
277
278 (defvar lsdb-hash-tables-are-dirty nil
279   "Flag to indicate whether the internal hash tables need to be saved.")
280
281 (defvar lsdb-known-entry-names
282   (make-vector 29 0)
283   "An obarray used to complete an entry name.")
284
285 (defvar lsdb-temp-buffer-show-function
286   #'lsdb-temp-buffer-show-function
287   "Non-nil means call as function to display a help buffer.
288 The function is called with one argument, the buffer to be displayed.
289 Overrides `temp-buffer-show-function'.")
290
291 ;;;_. Hash Table Emulation
292 (if (and (fboundp 'make-hash-table)
293          (subrp (symbol-function 'make-hash-table)))
294     (progn
295       (defalias 'lsdb-puthash 'puthash)
296       (defalias 'lsdb-gethash 'gethash)
297       (defalias 'lsdb-remhash 'remhash)
298       (defalias 'lsdb-maphash 'maphash)
299       (defalias 'lsdb-hash-table-size 'hash-table-size)
300       (defalias 'lsdb-hash-table-count 'hash-table-count)
301       (defalias 'lsdb-make-hash-table 'make-hash-table))
302   (defun lsdb-puthash (key value hash-table)
303     "Hash KEY to VALUE in HASH-TABLE."
304     ;; Obarray is regarded as an open hash table, as a matter of
305     ;; fact, rehashing doesn't make sense.
306     (let (new-obarray)
307       (when (> (car hash-table)
308                (* (length (nth 1 hash-table)) 0.7))
309         (setq new-obarray (make-vector (* (length (nth 1 hash-table)) 2) 0))
310         (mapatoms
311          (lambda (symbol)
312            (set (intern (symbol-name symbol) new-obarray)
313                 (symbol-value symbol)))
314          (nth 1 hash-table))
315         (setcdr hash-table (list new-obarray)))
316       (set (intern key (nth 1 hash-table)) value)
317       (setcar hash-table (1+ (car hash-table)))))
318   (defun lsdb-gethash (key hash-table &optional default)
319     "Find hash value for KEY in HASH-TABLE.
320 If there is no corresponding value, return DEFAULT (which defaults to nil)."
321     (let ((symbol (intern-soft key (nth 1 hash-table))))
322       (if symbol
323           (symbol-value symbol)
324         default)))
325   (defun lsdb-remhash (key hash-table)
326     "Remove the entry for KEY from HASH-TABLE.
327 Do nothing if there is no entry for KEY in HASH-TABLE."
328     (unintern key (nth 1 hash-table))
329     (setcar hash-table (1- (car hash-table))))
330   (defun lsdb-maphash (function hash-table)
331     "Map FUNCTION over entries in HASH-TABLE, calling it with two args,
332 each key and value in HASH-TABLE.
333
334 FUNCTION may not modify HASH-TABLE, with the one exception that FUNCTION
335 may remhash or puthash the entry currently being processed by FUNCTION."
336     (mapatoms
337      (lambda (symbol)
338        (funcall function (symbol-name symbol) (symbol-value symbol)))
339      (nth 1 hash-table)))
340   (defun lsdb-hash-table-size (hash-table)
341     "Return the size of HASH-TABLE.
342 This is the current number of slots in HASH-TABLE, whether occupied or not."
343     (length (nth 1 hash-table)))
344   (defalias 'lsdb-hash-table-count 'car)
345   (defun lsdb-make-hash-table (&rest args)
346     "Return a new empty hash table object."
347     (list 0 (make-vector (or (plist-get args :size) 29) 0))))
348
349 ;;;_. Hash Table Reader/Writer
350 (defconst lsdb-secondary-hash-table-start-format
351   ";;; %S\n")
352
353 (defsubst lsdb-secondary-hash-table-start (hash-table)
354   (format lsdb-secondary-hash-table-start-format hash-table))
355
356 (eval-and-compile
357   (condition-case nil
358       (progn
359         ;; In XEmacs, hash tables can also be created by the lisp reader
360         ;; using structure syntax.
361         (read-from-string "#s(hash-table)")
362         (defalias 'lsdb-read 'read))
363     (invalid-read-syntax
364      (defun lsdb-read (&optional marker)
365        "Read one Lisp expression as text from MARKER, return as Lisp object."
366        (save-excursion
367          (goto-char marker)
368          (if (looking-at "^#s(")
369              (with-temp-buffer
370                (buffer-disable-undo)
371                (insert-buffer-substring (marker-buffer marker) marker)
372                (goto-char (point-min))
373                (delete-char 2)
374                (let ((object (read (current-buffer)))
375                      hash-table data)
376                  (if (eq 'hash-table (car object))
377                      (progn
378                        (setq hash-table
379                              (lsdb-make-hash-table
380                               :size (plist-get (cdr object) 'size)
381                               :test 'equal)
382                              data (plist-get (cdr object) 'data))
383                        (while data
384                          (lsdb-puthash (pop data) (pop data) hash-table))
385                        hash-table)
386                    object)))))))))
387
388 (defun lsdb-load-hash-tables ()
389   "Read the contents of `lsdb-file' into the internal hash tables."
390   (let ((buffer (find-file-noselect lsdb-file))
391         tables)
392     (unwind-protect
393         (save-excursion
394           (set-buffer buffer)
395           (goto-char (point-min))
396           (re-search-forward "^#s(")
397           (goto-char (match-beginning 0))
398           (setq lsdb-hash-table (lsdb-read (point-marker)))
399           ;; Load the secondary hash tables following.
400           (setq tables lsdb-secondary-hash-tables)
401           (while tables
402             (if (re-search-forward
403                  (concat "^" (lsdb-secondary-hash-table-start
404                               (car tables)))
405                  nil t)
406                 (set (car tables) (lsdb-read (point-marker))))
407             (setq tables (cdr tables))))
408       (kill-buffer buffer))))
409
410 (defun lsdb-insert-hash-table (hash-table)
411   (insert "#s(hash-table size "
412           ;; Reduce the actual size of the close hash table, because
413           ;; XEmacs doesn't have a distinction between index-size and
414           ;; hash-table-size.
415           (number-to-string (lsdb-hash-table-count hash-table))
416           " test equal data (")
417   (lsdb-maphash
418    (lambda (key value)
419      (insert (prin1-to-string key) " " (prin1-to-string value) " "))
420    hash-table)
421   (insert "))"))
422
423 (defun lsdb-save-hash-tables ()
424   "Write the records within the internal hash tables into `lsdb-file'."
425   (let ((coding-system-for-write lsdb-file-coding-system)
426         tables)
427     (with-temp-file lsdb-file
428       (if (and (or (featurep 'mule)
429                    (featurep 'file-coding))
430                lsdb-file-coding-system)
431           (let ((coding-system-name
432                  (if (symbolp lsdb-file-coding-system)
433                      (symbol-name lsdb-file-coding-system)
434                    ;; XEmacs
435                    (static-if (featurep 'xemacs)
436                        (symbol-name (coding-system-name
437                                      lsdb-file-coding-system))))))
438             (if coding-system-name
439                 (insert ";;; -*- coding: " coding-system-name " -*-\n"))))
440       (lsdb-insert-hash-table lsdb-hash-table)
441       ;; Save the secondary hash tables following.
442       (setq tables lsdb-secondary-hash-tables)
443       (while tables
444         (insert "\n" (lsdb-secondary-hash-table-start
445                       (car tables)))
446         (lsdb-insert-hash-table (symbol-value (car tables)))
447         (setq tables (cdr tables))))))
448
449 ;;;_. Mail Header Extraction
450 (defun lsdb-fetch-field-bodies (regexp)
451   (save-excursion
452     (goto-char (point-min))
453     (let ((case-fold-search t)
454           field-bodies)
455       (while (re-search-forward (concat "^\\(" regexp "\\):[ \t]*")
456                                 nil t)
457         (push (funcall lsdb-decode-field-body-function
458                              (buffer-substring (point) (std11-field-end))
459                              (match-string 1))
460                     field-bodies))
461       (nreverse field-bodies))))
462
463 (defun lsdb-canonicalize-spaces-and-dots (string)
464   (while (string-match "  +\\|[\f\t\n\r\v]+\\|\\." string)
465     (setq string (replace-match " " nil t string)))
466   string)
467
468 (defun lsdb-extract-address-components (string)
469   (let ((components (std11-extract-address-components string)))
470     (if (and (nth 1 components)
471              ;; When parsing a group address,
472              ;; std11-extract-address-components is likely to return
473              ;; the ("GROUP" "") form.
474              (not (equal (nth 1 components) "")))
475         (if (car components)
476             (list (funcall lsdb-canonicalize-full-name-function
477                            (car components))
478                   (nth 1 components))
479           (list (nth 1 components) (nth 1 components))))))
480
481 ;; stolen (and renamed) from nnheader.el
482 (defun lsdb-decode-field-body (field-body field-name
483                                           &optional mode max-column)
484   (let ((multibyte enable-multibyte-characters))
485     (unwind-protect
486         (progn
487           (set-buffer-multibyte t)
488           (mime-decode-field-body field-body
489                                   (if (stringp field-name)
490                                       (intern (capitalize field-name))
491                                     field-name)
492                                   mode max-column))
493       (set-buffer-multibyte multibyte))))
494
495 ;;;_. Record Management
496 (defun lsdb-rebuild-secondary-hash-tables (&optional force)
497   (let ((tables lsdb-secondary-hash-tables))
498     (while tables
499       (when (or force (not (symbol-value (car tables))))
500         (set (car tables) (lsdb-make-hash-table :test 'equal))
501         (lsdb-maphash
502          (lambda (key value)
503            (run-hook-with-args
504             'lsdb-update-record-functions
505             (cons key value)))
506          lsdb-hash-table)
507         (setq lsdb-hash-tables-are-dirty t))
508       (setq tables (cdr tables)))))
509
510 (defun lsdb-maybe-load-hash-tables ()
511   (unless lsdb-hash-table
512     (if (file-exists-p lsdb-file)
513         (lsdb-load-hash-tables)
514       (setq lsdb-hash-table (lsdb-make-hash-table :test 'equal)))
515     (lsdb-rebuild-secondary-hash-tables)))
516
517 ;;;_ : Fallback Lookup Functions
518 ;;;_  , #1 Address Cache
519 (defun lsdb-lookup-full-name-from-address-cache (sender)
520   (lsdb-gethash (nth 1 sender) lsdb-address-cache))
521
522 (defun lsdb-update-address-cache (record)
523   (let ((net (cdr (assq 'net record))))
524     (while net
525       (lsdb-puthash (pop net) (car record) lsdb-address-cache))))
526
527 ;;;_  , #2 Iterate on the All Records (very slow)
528 (defun lsdb-lookup-full-name-by-fuzzy-matching (sender)
529   (let ((names
530          (if (string-match
531               "\\`\\(.+\\)[ \t]+\\(/[ \t]+\\|(\\([^)]+\\))\\)"
532               (car sender))
533              (if (match-beginning 3)
534                  (list (match-string 1 (car sender))
535                        (match-string 3 (car sender)))
536                (list (match-string 1 (car sender))
537                      (substring (car sender) (match-end 0))))
538            (list (car sender))))
539         (case-fold-search t))
540     (catch 'found
541       (lsdb-maphash
542        (lambda (key value)
543          (while names
544            (if (or (string-match
545                     (concat "\\<" (regexp-quote (car names)) "\\>")
546                     key)
547                    (string-match
548                     (concat
549                      "\\<"
550                      (regexp-quote
551                       (mapconcat #'identity
552                                  (nreverse (split-string (car names)))
553                                  " "))
554                      "\\>")
555                     key)
556                    ;; Don't assume that we are using address cache.
557                    (member (nth 1 sender) (cdr (assq 'net value))))
558                (throw 'found key))
559            (setq names (cdr names))))
560        lsdb-hash-table))))
561
562 ;;;_ : Update Records
563 (defun lsdb-update-record (sender &optional interesting)
564   (let ((old (lsdb-gethash (car sender) lsdb-hash-table))
565         (new (cons (cons 'net (list (nth 1 sender)))
566                    interesting))
567         merged
568         record
569         full-name)
570     ;; Look for the existing record from the reverse hash table.
571     ;; If it is found, regsiter the current full-name as AKA.
572     (unless old
573       (setq full-name
574             (run-hook-with-args-until-success
575              'lsdb-lookup-full-name-functions
576              sender))
577       (when full-name
578         (setq old (lsdb-gethash full-name lsdb-hash-table)
579               new (cons (list 'aka (car sender)) new))
580         (setcar sender full-name)))
581     (unless old
582       (setq new (cons (cons 'creation-date (format-time-string "%Y-%m-%d"))
583                       new)))
584     (setq merged (lsdb-merge-record-entries old new)
585           record (cons (car sender) merged))
586     (unless (equal merged old)
587       (let ((entry (assq 'last-modified (cdr record)))
588             (last-modified (format-time-string "%Y-%m-%d")))
589         (if entry
590             (setcdr entry last-modified)
591           (setcdr record (cons (cons 'last-modified last-modified)
592                                (cdr record)))))
593       (lsdb-puthash (car record) (cdr record)
594                     lsdb-hash-table)
595       (run-hook-with-args 'lsdb-update-record-functions record)
596       (setq lsdb-hash-tables-are-dirty t))
597     record))
598
599 (defun lsdb-update-records ()
600   (lsdb-maybe-load-hash-tables)
601   (let (senders recipients interesting alist records bodies entry)
602     (save-restriction
603       (std11-narrow-to-header)
604       (setq senders
605             (delq nil (mapcar #'lsdb-extract-address-components
606                               (lsdb-fetch-field-bodies
607                                lsdb-sender-headers)))
608             recipients
609             (delq nil (mapcar #'lsdb-extract-address-components
610                               (lsdb-fetch-field-bodies
611                                lsdb-recipients-headers))))
612       (setq alist lsdb-interesting-header-alist)
613       (while alist
614         (setq bodies
615               (delq nil (mapcar
616                          (lambda (field-body)
617                            (if (nth 1 (car alist))
618                                (and (string-match (nth 1 (car alist))
619                                                   field-body)
620                                     (replace-match (nth 3 (car alist))
621                                                    nil nil field-body))
622                              field-body))
623                          (lsdb-fetch-field-bodies (car (car alist))))))
624         (when bodies
625           (setq entry (or (nth 2 (car alist))
626                           'notes))
627           (push (cons entry
628                       (if (eq ?. (nth 2 (assq entry lsdb-entry-type-alist)))
629                           (car bodies)
630                         bodies))
631                 interesting))
632         (setq alist (cdr alist))))
633     (if senders
634         (setq records (list (lsdb-update-record (pop senders) interesting))))
635     (setq alist (nconc senders recipients))
636     (while alist
637       (setq records (cons (lsdb-update-record (pop alist)) records)))
638     (nreverse records)))
639
640 (defun lsdb-merge-record-entries (old new)
641   (setq old (copy-sequence old))
642   (while new
643     (let ((entry (assq (car (car new)) old))
644           list pointer)
645       (if (null entry)
646           (setq old (nconc old (list (car new))))
647         (if (listp (cdr entry))
648             (progn
649               (setq list (cdr (car new)) pointer list)
650               (while pointer
651                 (if (member (car pointer) (cdr entry))
652                     (setq list (delq (car pointer) list)))
653                 (setq pointer (cdr pointer)))
654               (setcdr entry (nconc (cdr entry) list)))
655           (setcdr entry (cdr (car new))))))
656     (setq new (cdr new)))
657   old)
658
659 ;;;_. Display Management
660 (defun lsdb-fit-window-to-buffer (&optional window)
661   (save-selected-window
662     (if window
663         (select-window window))
664     (unless (pos-visible-in-window-p (point-max))
665       (enlarge-window (- lsdb-window-max-height (window-height))))
666     (shrink-window-if-larger-than-buffer)
667     (let ((height (window-height)))
668       (if (> height lsdb-window-max-height)
669           (shrink-window (- height lsdb-window-max-height)))
670       (set-window-start window (point-min)))))
671
672 (defun lsdb-temp-buffer-show-function (buffer)
673   (when lsdb-pop-up-windows
674     (save-selected-window
675       (let ((window (or (get-buffer-window lsdb-buffer-name)
676                         (progn
677                           (select-window (get-largest-window))
678                           (split-window-vertically)))))
679         (set-window-buffer window buffer)
680         (lsdb-fit-window-to-buffer window)))))
681
682 (defun lsdb-display-record (record)
683   "Display only one RECORD, then shrink the window as possible."
684   (let ((temp-buffer-show-function lsdb-temp-buffer-show-function))
685     (lsdb-display-records (list record))))
686
687 (defun lsdb-display-records (records)
688   (with-output-to-temp-buffer lsdb-buffer-name
689     (set-buffer standard-output)
690     (setq records
691           (sort (copy-sequence records)
692                 (or lsdb-display-records-sort-predicate
693                     (lambda (record1 record2)
694                       (string-lessp (car record1) (car record2))))))
695     (while records
696       (save-restriction
697         (narrow-to-region (point) (point))
698         (lsdb-print-record (car records)))
699       (goto-char (point-max))
700       (setq records (cdr records)))
701     (lsdb-mode)))
702
703 (defsubst lsdb-entry-score (entry)
704   (or (nth 1 (assq (car entry) lsdb-entry-type-alist)) 0))
705
706 (defun lsdb-insert-entry (entry)
707   (let ((entry-name (capitalize (symbol-name (car entry)))))
708     (intern entry-name lsdb-known-entry-names)
709     (if (>= (lsdb-entry-score entry) 0)
710         (insert "\t" entry-name ": "
711                 (if (listp (cdr entry))
712                     (mapconcat
713                      #'identity (cdr entry)
714                      (if (eq ?, (nth 2 (assq (car entry)
715                                              lsdb-entry-type-alist)))
716                          ", "
717                        "\n\t\t"))
718                   (cdr entry))
719                 "\n"))))
720
721 (defun lsdb-print-record (record)
722   (insert (car record) "\n")
723   (let ((entries
724          (sort (copy-sequence (cdr record))
725                (lambda (entry1 entry2)
726                  (> (lsdb-entry-score entry1) (lsdb-entry-score entry2))))))
727     (while entries
728       (lsdb-insert-entry (car entries))
729       (setq entries (cdr entries))))
730   (add-text-properties (point-min) (point-max)
731                        (list 'lsdb-record record))
732   (run-hooks 'lsdb-print-record-hook))
733
734 ;;;_. Completion
735 (defvar lsdb-last-completion nil)
736 (defvar lsdb-last-candidates nil)
737 (defvar lsdb-last-candidates-pointer nil)
738 (defvar lsdb-complete-marker nil)
739
740 ;;;_ : Matching Highlight
741 (defvar lsdb-last-highlight-overlay nil)
742
743 (defun lsdb-complete-name-highlight (start end)
744   (make-local-hook 'pre-command-hook)
745   (add-hook 'pre-command-hook 'lsdb-complete-name-highlight-update nil t)
746   (save-excursion
747     (goto-char start)
748     (search-forward lsdb-last-completion end)
749     (setq lsdb-last-highlight-overlay
750           (make-overlay (match-beginning 0) (match-end 0)))
751     (overlay-put lsdb-last-highlight-overlay 'face
752                  (or (find-face 'isearch-secondary)
753                      (find-face 'isearch-lazy-highlight-face)
754                      'underline))))
755
756 (defun lsdb-complete-name-highlight-update ()
757   (unless (eq this-command 'lsdb-complete-name)
758     (if lsdb-last-highlight-overlay
759         (delete-overlay lsdb-last-highlight-overlay))
760     (set-marker lsdb-complete-marker nil)
761     (remove-hook 'pre-command-hook
762                  'lsdb-complete-name-highlight-update t)))
763
764 ;;;_ : Name Completion
765 (defun lsdb-complete-name ()
766   "Complete the user full-name or net-address before point"
767   (interactive)
768   (lsdb-maybe-load-hash-tables)
769   (unless (markerp lsdb-complete-marker)
770     (setq lsdb-complete-marker (make-marker)))
771   (let* ((start
772           (or (and (eq (marker-buffer lsdb-complete-marker) (current-buffer))
773                    (marker-position lsdb-complete-marker))
774               (save-excursion
775                 (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
776                 (set-marker lsdb-complete-marker (match-end 0)))))
777          pattern
778          (case-fold-search t)
779          (completion-ignore-case t))
780     (unless (eq last-command this-command)
781       (setq lsdb-last-candidates nil
782             lsdb-last-candidates-pointer nil
783             lsdb-last-completion (buffer-substring start (point))
784             pattern (concat "\\<" (regexp-quote lsdb-last-completion)))
785       (lsdb-maphash
786        (lambda (key value)
787          (let ((net (cdr (assq 'net value))))
788            (if (string-match pattern key)
789                (setq lsdb-last-candidates
790                      (nconc lsdb-last-candidates
791                             (mapcar (lambda (address)
792                                       (if (equal key address)
793                                           key
794                                         (concat key " <" address ">")))
795                                     net)))
796              (while net
797                (if (string-match pattern (car net))
798                    (push (car net) lsdb-last-candidates))
799                (setq net (cdr net))))))
800        lsdb-hash-table)
801       ;; Sort candidates by the position where the pattern occurred.
802       (setq lsdb-last-candidates
803             (sort lsdb-last-candidates
804                   (lambda (cand1 cand2)
805                     (< (if (string-match pattern cand1)
806                            (match-beginning 0))
807                        (if (string-match pattern cand2)
808                            (match-beginning 0)))))))
809     (unless lsdb-last-candidates-pointer
810       (setq lsdb-last-candidates-pointer lsdb-last-candidates))
811     (when lsdb-last-candidates-pointer
812       (delete-region start (point))
813       (insert (pop lsdb-last-candidates-pointer))
814       (lsdb-complete-name-highlight start (point)))))
815
816 ;;;_. Major Mode (`lsdb-mode') Implementation
817 ;;;_ : Modeline Buffer Identification
818 (defconst lsdb-pointer-xpm
819   "/* XPM */
820 static char * lsdb_pointer_xpm[] = {
821 \"14 14 5 1\",
822 \"      c None\",
823 \"+     c #FF9696\",
824 \"@     c #FF0000\",
825 \"#     c #FF7575\",
826 \"$     c #FF5959\",
827 \"              \",
828 \"  +++   @@@   \",
829 \" +++## @@@@@  \",
830 \" ++### @@@@@  \",
831 \" +#####@@@@@  \",
832 \" +###$$@@@@@  \",
833 \" +###$$@@@@@  \",
834 \"  ##$$$@@@@   \",
835 \"   #$$$@@@    \",
836 \"    $$@@@     \",
837 \"     $@@      \",
838 \"      @       \",
839 \"              \",
840 \"              \"};")
841
842 (static-if (featurep 'xemacs)
843     (progn
844       (defvar lsdb-xemacs-modeline-left-extent
845         (copy-extent modeline-buffer-id-left-extent))
846
847       (defvar lsdb-xemacs-modeline-right-extent
848         (copy-extent modeline-buffer-id-right-extent))
849
850       (defun lsdb-modeline-buffer-identification (line)
851         "Decorate 1st element of `mode-line-buffer-identification' LINE.
852 Modify whole identification by side effect."
853         (let ((id (car line)) chopped)
854           (if (and (stringp id) (string-match "^LSDB:" id))
855               (progn
856                 (setq chopped (substring id 0 (match-end 0))
857                       id (substring id (match-end 0)))
858                 (nconc
859                  (list
860                   (let ((glyph
861                          (make-glyph
862                           (nconc
863                            (if (featurep 'xpm)
864                                (list (vector 'xpm :data lsdb-pointer-xpm)))
865                            (list (vector 'string :data chopped))))))
866                     (set-glyph-face glyph 'modeline-buffer-id)
867                     (cons lsdb-xemacs-modeline-left-extent glyph))
868                   (cons lsdb-xemacs-modeline-right-extent id))
869                  (cdr line)))
870             line))))
871   (condition-case nil
872       (progn
873         (require 'image)
874         (defun lsdb-modeline-buffer-identification (line)
875           "Decorate 1st element of `mode-line-buffer-identification' LINE.
876 Modify whole identification by side effect."
877           (let ((id (copy-sequence (car line)))
878                 (image
879                  (if (image-type-available-p 'xpm)
880                      (create-image lsdb-pointer-xpm 'xpm t :ascent 'center))))
881             (when (and image
882                        (stringp id) (string-match "^LSDB:" id))
883               (add-text-properties 0 (length id)
884                                    (list 'display image
885                                          'rear-nonsticky (list 'display))
886                                    id)
887               (setcar line id))
888             line)))
889     (error
890      (defalias 'lsdb-modeline-buffer-identification 'identity))))
891
892 (defvar lsdb-mode-map
893   (let ((keymap (make-sparse-keymap)))
894     (define-key keymap "a" 'lsdb-mode-add-entry)
895     (define-key keymap "d" 'lsdb-mode-delete-entry)
896     (define-key keymap "e" 'lsdb-mode-edit-entry)
897     (define-key keymap "l" 'lsdb-mode-load)
898     (define-key keymap "s" 'lsdb-mode-save)
899     (define-key keymap "q" 'lsdb-mode-quit-window)
900     (define-key keymap "g" 'lsdb-mode-lookup)
901     (define-key keymap "p" 'lsdb-mode-previous-record)
902     (define-key keymap "n" 'lsdb-mode-next-record)
903     (define-key keymap " " 'scroll-up)
904     (define-key keymap [delete] 'scroll-down)
905     (define-key keymap "\177" 'scroll-down)
906     (define-key keymap [backspace] 'scroll-down)
907     keymap)
908   "LSDB's keymap.")
909
910 (defvar lsdb-modeline-string "")
911
912 (define-derived-mode lsdb-mode fundamental-mode "LSDB"
913   "Major mode for browsing LSDB records."
914   (setq buffer-read-only t)
915   (static-if (featurep 'xemacs)
916       ;; In XEmacs, setting `font-lock-defaults' only affects on
917       ;; `find-file-hooks'.
918       (font-lock-set-defaults)
919     (set (make-local-variable 'font-lock-defaults)
920          '(lsdb-font-lock-keywords t)))
921   (make-local-hook 'post-command-hook)
922   (add-hook 'post-command-hook 'lsdb-modeline-update nil t)
923   (make-local-variable 'lsdb-modeline-string)
924   (setq mode-line-buffer-identification
925         (lsdb-modeline-buffer-identification
926          '("LSDB: " lsdb-modeline-string)))
927   (lsdb-modeline-update)
928   (force-mode-line-update))
929
930 (defun lsdb-modeline-update ()
931   (let ((record
932          (get-text-property (if (eobp) (point-min) (point)) 'lsdb-record))
933         net)
934     (if record
935         (progn
936           (setq net (car (cdr (assq 'net (cdr record)))))
937           (if (equal net (car record))
938               (setq lsdb-modeline-string net)
939             (setq lsdb-modeline-string (concat (car record) " <" net ">"))))
940       (setq lsdb-modeline-string ""))))
941
942 (defun lsdb-narrow-to-record ()
943   "Narrow to the current record."
944   (let ((end (next-single-property-change (point) 'lsdb-record nil
945                                           (point-max))))
946     (narrow-to-region
947      (previous-single-property-change end 'lsdb-record nil (point-min))
948      end)
949     (goto-char (point-min))))
950
951 (defun lsdb-current-record ()
952   "Return the current record name."
953   (let ((record (get-text-property (point) 'lsdb-record)))
954     (unless record
955       (error "There is nothing to follow here"))
956     record))
957
958 (defun lsdb-current-entry ()
959   "Return the current entry name.
960 If the point is not on a entry line, it prompts to select a entry in
961 the current record."
962   (save-excursion
963     (beginning-of-line)
964     (if (looking-at "^[^\t]")
965         (let ((record (lsdb-current-record))
966               (completion-ignore-case t))
967           (completing-read
968            "Which entry to modify: "
969            (mapcar (lambda (entry)
970                      (list (capitalize (symbol-name (car entry)))))
971                    (cdr record))))
972       (end-of-line)
973       (re-search-backward "^\t\\([^\t][^:]+\\):")
974       (match-string 1))))
975
976 (defun lsdb-mode-add-entry (entry-name)
977   "Add an entry on the current line."
978   (interactive
979    (let ((completion-ignore-case t))
980      (list (completing-read "Entry name: " lsdb-known-entry-names))))
981   (beginning-of-line)
982   (unless (symbolp entry-name)
983     (setq entry-name (intern (downcase entry-name))))
984   (when (assq entry-name (cdr (lsdb-current-record)))
985     (error "The entry already exists"))
986   (let ((marker (point-marker)))
987     (lsdb-edit-form
988      nil "Editing the entry."
989      `(lambda (form)
990         (when form
991           (save-excursion
992             (set-buffer lsdb-buffer-name)
993             (goto-char ,marker)
994             (let ((record (lsdb-current-record))
995                   (inhibit-read-only t)
996                   buffer-read-only)
997               (setcdr record (cons (cons ',entry-name form) (cdr record)))
998               (lsdb-puthash (car record) (cdr record)
999                             lsdb-hash-table)
1000               (run-hook-with-args 'lsdb-update-record-functions record)
1001               (setq lsdb-hash-tables-are-dirty t)
1002               (beginning-of-line 2)
1003               (add-text-properties
1004                (point)
1005                (progn
1006                  (lsdb-insert-entry (cons ',entry-name form))
1007                  (point))
1008                (list 'lsdb-record record)))))))))
1009
1010 (defun lsdb-mode-delete-entry (&optional entry-name dont-update)
1011   "Delete the entry on the current line."
1012   (interactive)
1013   (let ((record (lsdb-current-record))
1014         entry)
1015     (or entry-name
1016         (setq entry-name (lsdb-current-entry)))
1017     (setq entry (assq (intern (downcase entry-name)) (cdr record)))
1018     (when (and entry
1019                (not dont-update))
1020       (setcdr record (delq entry (cdr record)))
1021       (lsdb-puthash (car record) (cdr record)
1022                     lsdb-hash-table)
1023       (run-hook-with-args 'lsdb-update-record-functions record)
1024       (setq lsdb-hash-tables-are-dirty t))
1025     (save-restriction
1026       (lsdb-narrow-to-record)
1027       (let ((case-fold-search t)
1028             (inhibit-read-only t)
1029             buffer-read-only)
1030         (goto-char (point-min))
1031         (if (re-search-forward
1032              (concat "^\t" (or entry-name
1033                                (lsdb-current-entry))
1034                      ":")
1035              nil t)
1036             (delete-region (match-beginning 0)
1037                            (if (re-search-forward
1038                                 "^\t[^\t][^:]+:" nil t)
1039                                (match-beginning 0)
1040                              (point-max))))))))
1041
1042 (defun lsdb-mode-edit-entry ()
1043   "Edit the entry on the current line."
1044   (interactive)
1045   (let* ((record (lsdb-current-record))
1046          (entry-name (intern (downcase (lsdb-current-entry))))
1047          (entry (assq entry-name (cdr record)))
1048          (marker (point-marker)))
1049     (lsdb-edit-form
1050      (cdr entry) "Editing the entry."
1051      `(lambda (form)
1052         (unless (equal form ',(cdr entry))
1053           (save-excursion
1054             (set-buffer lsdb-buffer-name)
1055             (goto-char ,marker)
1056             (let* ((record (lsdb-current-record))
1057                    (entry (assq ',entry-name (cdr record)))
1058                    (inhibit-read-only t)
1059                    buffer-read-only)
1060               (setcdr entry form)
1061               (run-hook-with-args 'lsdb-update-record-functions record)
1062               (setq lsdb-hash-tables-are-dirty t)
1063               (lsdb-mode-delete-entry (symbol-name ',entry-name) t)
1064               (beginning-of-line)
1065               (add-text-properties
1066                (point)
1067                (progn
1068                  (lsdb-insert-entry (cons ',entry-name form))
1069                  (point))
1070                (list 'lsdb-record record)))))))))
1071
1072 (defun lsdb-mode-save (&optional dont-ask)
1073   "Save LSDB hash table into `lsdb-file'."
1074   (interactive)
1075   (if (not lsdb-hash-tables-are-dirty)
1076       (message "(No changes need to be saved)")
1077     (when (or (interactive-p)
1078               dont-ask
1079               (y-or-n-p "Save the LSDB now? "))
1080       (lsdb-save-hash-tables)
1081       (setq lsdb-hash-tables-are-dirty nil)
1082       (message "The LSDB was saved successfully."))))
1083
1084 (defun lsdb-mode-load ()
1085   "Load LSDB hash table from `lsdb-file'."
1086   (interactive)
1087   (let (lsdb-secondary-hash-tables)
1088     (lsdb-load-hash-tables))
1089   (message "Rebuilding secondary hash tables...")
1090   (lsdb-rebuild-secondary-hash-tables t)
1091   (message "Rebuilding secondary hash tables...done"))
1092
1093 (defun lsdb-mode-quit-window (&optional kill window)
1094   "Quit the current buffer.
1095 It partially emulates the GNU Emacs' of `quit-window'."
1096   (interactive "P")
1097   (unless window
1098     (setq window (selected-window)))
1099   (let ((buffer (window-buffer window)))
1100     (unless (save-selected-window
1101               (select-window window)
1102               (one-window-p))
1103       (delete-window window))
1104     (if kill
1105         (kill-buffer buffer)
1106       (bury-buffer (unless (eq buffer (current-buffer)) buffer)))))
1107
1108 (defun lsdb-hide-buffer ()
1109   "Hide the LSDB window."
1110   (let ((window (get-buffer-window lsdb-buffer-name)))
1111     (if window
1112         (lsdb-mode-quit-window nil window))))
1113
1114 (defun lsdb-show-buffer ()
1115   "Show the LSDB window."
1116   (if (get-buffer lsdb-buffer-name)
1117       (if lsdb-temp-buffer-show-function
1118           (let ((lsdb-pop-up-windows t))
1119             (funcall lsdb-temp-buffer-show-function lsdb-buffer-name))
1120         (pop-to-buffer lsdb-buffer-name))))
1121
1122 (defun lsdb-toggle-buffer (&optional arg)
1123   "Toggle hiding of the LSDB window.
1124 If given a negative prefix, always show; if given a positive prefix,
1125 always hide."
1126   (interactive
1127    (list (if current-prefix-arg
1128              (prefix-numeric-value current-prefix-arg)
1129            0)))
1130   (unless arg                           ;called noninteractively?
1131     (setq arg 0))
1132   (cond
1133    ((or (< arg 0)
1134         (and (zerop arg)
1135              (not (get-buffer-window lsdb-buffer-name))))
1136     (lsdb-show-buffer))
1137    ((or (> arg 0)
1138         (and (zerop arg)
1139              (get-buffer-window lsdb-buffer-name)))
1140     (lsdb-hide-buffer))))
1141
1142 (defun lsdb-lookup-records (regexp &optional entry-name)
1143   "Return the all records in the LSDB matching the REGEXP.
1144 If the optional 2nd argument ENTRY-NAME is given, matching only
1145 performed against the entry field."
1146   (let (records)
1147     (lsdb-maphash
1148      (if entry-name
1149          (progn
1150            (unless (symbolp entry-name)
1151              (setq entry-name (intern (downcase entry-name))))
1152            (lambda (key value)
1153              (let ((entry (cdr (assq entry-name value)))
1154                    found)
1155                (unless (listp entry)
1156                  (setq entry (list entry)))
1157                (while (and (not found) entry)
1158                  (if (string-match regexp (pop entry))
1159                      (setq found t)))
1160                (if found
1161                    (push (cons key value) records)))))
1162        (lambda (key value)
1163          (if (string-match regexp key)
1164              (push (cons key value) records))))
1165      lsdb-hash-table)
1166     records))
1167
1168 (defvar lsdb-mode-lookup-history nil)
1169
1170 (defun lsdb-mode-lookup (regexp &optional entry-name)
1171   "Display the all records in the LSDB matching the REGEXP.
1172 If the optional 2nd argument ENTRY-NAME is given, matching only
1173 performed against the entry field."
1174   (interactive
1175    (let* ((completion-ignore-case t)
1176           (entry-name
1177            (if current-prefix-arg
1178                (completing-read "Entry name: "
1179                                 lsdb-known-entry-names))))
1180      (list
1181       (read-from-minibuffer
1182        (if entry-name
1183            (format "Search records `%s' regexp: " entry-name)
1184          "Search records regexp: ")
1185        nil nil nil 'lsdb-mode-lookup-history)
1186       entry-name)))
1187   (lsdb-maybe-load-hash-tables)
1188   (let ((records (lsdb-lookup-records regexp entry-name)))
1189     (if records
1190         (lsdb-display-records records))))
1191
1192 ;;;###autoload
1193 (defalias 'lsdb 'lsdb-mode-lookup)
1194
1195 (defun lsdb-mode-next-record (&optional arg)
1196   "Go to the next record."
1197   (interactive "p")
1198   (unless arg                           ;called noninteractively?
1199     (setq arg 1))
1200   (if (< arg 0)
1201       (lsdb-mode-previous-record (- arg))
1202     (while (> arg 0)
1203       (goto-char (next-single-property-change
1204                   (point) 'lsdb-record nil (point-max)))
1205       (setq arg (1- arg)))))
1206
1207 (defun lsdb-mode-previous-record (&optional arg)
1208   "Go to the previous record."
1209   (interactive "p")
1210   (unless arg                           ;called noninteractively?
1211     (setq arg 1))
1212   (if (< arg 0)
1213       (lsdb-mode-next-record (- arg))
1214     (while (> arg 0)
1215       (goto-char (previous-single-property-change
1216                   (point) 'lsdb-record nil (point-min)))
1217       (setq arg (1- arg)))))
1218
1219 ;;;_ : Edit Forms -- stolen (and renamed) from gnus-eform.el
1220 (defvar lsdb-edit-form-buffer "*LSDB edit form*")
1221 (defvar lsdb-edit-form-done-function nil)
1222 (defvar lsdb-previous-window-configuration nil)
1223
1224 (defvar lsdb-edit-form-mode-map
1225   (let ((keymap (make-sparse-keymap)))
1226     (set-keymap-parent keymap emacs-lisp-mode-map)
1227     (define-key keymap "\C-c\C-c" 'lsdb-edit-form-done)
1228     (define-key keymap "\C-c\C-k" 'lsdb-edit-form-exit)
1229     keymap)
1230   "Edit form's keymap.")
1231
1232 (defun lsdb-edit-form-mode ()
1233   "Major mode for editing forms.
1234 It is a slightly enhanced emacs-lisp-mode.
1235
1236 \\{lsdb-edit-form-mode-map}"
1237   (interactive)
1238   (kill-all-local-variables)
1239   (setq major-mode 'lsdb-edit-form-mode
1240         mode-name "LSDB Edit Form")
1241   (use-local-map lsdb-edit-form-mode-map)
1242   (make-local-variable 'lsdb-edit-form-done-function)
1243   (make-local-variable 'lsdb-previous-window-configuration)
1244   (run-hooks 'lsdb-edit-form-mode-hook))
1245
1246 (defun lsdb-edit-form (form documentation exit-func)
1247   "Edit FORM in a new buffer.
1248 Call EXIT-FUNC on exit.  Display DOCUMENTATION in the beginning
1249 of the buffer."
1250   (let ((window-configuration
1251          (current-window-configuration)))
1252     (switch-to-buffer (get-buffer-create lsdb-edit-form-buffer))
1253     (lsdb-edit-form-mode)
1254     (setq lsdb-previous-window-configuration window-configuration
1255           lsdb-edit-form-done-function exit-func)
1256     (erase-buffer)
1257     (insert documentation)
1258     (unless (bolp)
1259       (insert "\n"))
1260     (goto-char (point-min))
1261     (while (not (eobp))
1262       (insert ";;; ")
1263       (forward-line 1))
1264     (insert ";; Type `C-c C-c' after you've finished editing.\n")
1265     (insert "\n")
1266     (let ((p (point)))
1267       (pp form (current-buffer))
1268       (insert "\n")
1269       (goto-char p))))
1270
1271 (defun lsdb-edit-form-done ()
1272   "Update changes and kill the current buffer."
1273   (interactive)
1274   (goto-char (point-min))
1275   (let ((form (condition-case nil
1276                   (read (current-buffer))
1277                 (end-of-file nil)))
1278         (func lsdb-edit-form-done-function))
1279     (lsdb-edit-form-exit)
1280     (funcall func form)))
1281
1282 (defun lsdb-edit-form-exit ()
1283   "Kill the current buffer."
1284   (interactive)
1285   (let ((window-configuration lsdb-previous-window-configuration))
1286     (kill-buffer (current-buffer))
1287     (set-window-configuration window-configuration)))
1288
1289 ;;;_. Interface to Semi-gnus
1290 ;;;###autoload
1291 (defun lsdb-gnus-insinuate ()
1292   "Call this function to hook LSDB into Semi-gnus."
1293   (add-hook 'gnus-article-prepare-hook 'lsdb-gnus-update-record)
1294   (add-hook 'gnus-save-newsrc-hook 'lsdb-mode-save))
1295
1296 (defvar gnus-current-headers)
1297 (defun lsdb-gnus-update-record ()
1298   (let ((entity gnus-current-headers)
1299         records)
1300     (with-temp-buffer
1301       (set-buffer-multibyte nil)
1302       (buffer-disable-undo)
1303       (mime-insert-entity entity)
1304       (setq records (lsdb-update-records))
1305       (when records
1306         (lsdb-display-record (car records))))))
1307
1308 ;;;_. Interface to Wanderlust
1309 ;;;###autoload
1310 (defun lsdb-wl-insinuate ()
1311   "Call this function to hook LSDB into Wanderlust."
1312   (add-hook 'wl-message-redisplay-hook 'lsdb-wl-update-record)
1313   (add-hook 'wl-summary-exit-hook 'lsdb-hide-buffer)
1314   (add-hook 'wl-summary-toggle-disp-off-hook 'lsdb-hide-buffer)
1315   (add-hook 'wl-summary-toggle-disp-folder-on-hook 'lsdb-hide-buffer)
1316   (add-hook 'wl-summary-toggle-disp-folder-off-hook 'lsdb-hide-buffer)
1317   (add-hook 'wl-summary-toggle-disp-folder-message-resumed-hook
1318             'lsdb-wl-show-buffer)
1319   (add-hook 'wl-exit-hook 'lsdb-mode-save)
1320   (add-hook 'wl-save-hook 'lsdb-mode-save))
1321
1322 (eval-when-compile
1323   (autoload 'wl-message-get-original-buffer "wl-message"))
1324 (defun lsdb-wl-update-record ()
1325   (save-excursion
1326     (set-buffer (wl-message-get-original-buffer))
1327     (let ((records (lsdb-update-records)))
1328       (when records
1329         (let ((lsdb-temp-buffer-show-function
1330                #'lsdb-wl-temp-buffer-show-function))
1331           (lsdb-display-record (car records)))))))
1332
1333 (defun lsdb-wl-toggle-buffer (&optional arg)
1334   "Toggle hiding of the LSDB window for Wanderlust.
1335 If given a negative prefix, always show; if given a positive prefix,
1336 always hide."
1337   (interactive
1338    (list (if current-prefix-arg
1339              (prefix-numeric-value current-prefix-arg)
1340            0)))
1341   (let ((lsdb-temp-buffer-show-function
1342          #'lsdb-wl-temp-buffer-show-function))
1343     (lsdb-toggle-buffer arg)))
1344
1345 (defun lsdb-wl-show-buffer ()
1346   (when lsdb-pop-up-windows
1347     (let ((lsdb-temp-buffer-show-function
1348            #'lsdb-wl-temp-buffer-show-function))
1349       (lsdb-show-buffer))))
1350
1351 (defvar wl-current-summary-buffer)
1352 (defvar wl-message-buffer)
1353 (defun lsdb-wl-temp-buffer-show-function (buffer)
1354   (when lsdb-pop-up-windows
1355     (save-selected-window
1356       (let ((window (or (get-buffer-window lsdb-buffer-name)
1357                         (progn
1358                           (select-window 
1359                            (or (save-excursion
1360                                  (if (buffer-live-p wl-current-summary-buffer)
1361                                      (set-buffer wl-current-summary-buffer))
1362                                  (get-buffer-window wl-message-buffer))
1363                                (get-largest-window)))
1364                           (split-window-vertically)))))
1365         (set-window-buffer window buffer)
1366         (lsdb-fit-window-to-buffer window)))))
1367
1368 ;;;_. Interface to Mew written by Hideyuki SHIRAI <shirai@meadowy.org>
1369 (eval-when-compile
1370   (autoload 'mew-sinfo-get-disp-msg "mew")
1371   (autoload 'mew-current-get-fld "mew")
1372   (autoload 'mew-current-get-msg "mew")
1373   (autoload 'mew-frame-id "mew")
1374   (autoload 'mew-cache-hit "mew")
1375   (autoload 'mew-xinfo-get-decode-err "mew")
1376   (autoload 'mew-xinfo-get-action "mew"))
1377
1378 ;;;###autoload
1379 (defun lsdb-mew-insinuate ()
1380   "Call this function to hook LSDB into Mew."
1381   (add-hook 'mew-message-hook 'lsdb-mew-update-record)
1382   (add-hook 'mew-summary-toggle-disp-msg-hook
1383             (lambda ()
1384               (unless (mew-sinfo-get-disp-msg)
1385                 (lsdb-hide-buffer))))
1386   (add-hook 'mew-suspend-hook 'lsdb-hide-buffer)
1387   (add-hook 'mew-quit-hook 'lsdb-mode-save)
1388   (add-hook 'kill-emacs-hook 'lsdb-mode-save)
1389   (cond
1390    ;; Mew 3
1391    ((fboundp 'mew-summary-visit-folder)
1392     (defadvice mew-summary-visit-folder (before lsdb-hide-buffer activate)
1393       (lsdb-hide-buffer)))
1394    ;; Mew 2
1395    ((fboundp 'mew-summary-switch-to-folder)
1396     (defadvice mew-summary-switch-to-folder (before lsdb-hide-buffer activate)
1397       (lsdb-hide-buffer)))))
1398
1399 (defun lsdb-mew-update-record ()
1400   (let* ((fld (mew-current-get-fld (mew-frame-id)))
1401          (msg (mew-current-get-msg (mew-frame-id)))
1402          (cache (mew-cache-hit fld msg))
1403          records)
1404     (when cache
1405       (save-excursion
1406         (set-buffer cache)
1407         (unless (or (mew-xinfo-get-decode-err) (mew-xinfo-get-action))
1408           (make-local-variable 'lsdb-decode-field-body-function)
1409           (setq lsdb-decode-field-body-function
1410                 (lambda (body name)
1411                   (set-text-properties 0 (length body) nil body)
1412                   body))
1413           (when (setq records (lsdb-update-records))
1414             (lsdb-display-record (car records))))))))
1415
1416 ;;;_. Interface to MU-CITE
1417 (eval-when-compile
1418   (autoload 'mu-cite-get-value "mu-cite"))
1419
1420 (defun lsdb-mu-attribution (address)
1421   "Extract attribute information from LSDB."
1422   (let ((records
1423          (lsdb-lookup-records (concat "\\<" address "\\>") 'net)))
1424     (if records
1425         (cdr (assq 'attribution (cdr (car records)))))))
1426
1427 (defun lsdb-mu-set-attribution (attribution address)
1428   "Add attribute information to LSDB."
1429   (let ((records
1430          (lsdb-lookup-records (concat "\\<" address "\\>") 'net))
1431         entry)
1432     (when records
1433       (setq entry (assq 'attribution (cdr (car records))))
1434       (if entry
1435           (setcdr entry attribution)
1436         (setcdr (car records) (cons (cons 'attribution attribution)
1437                                     (cdr (car records))))
1438         (lsdb-puthash (car (car records)) (cdr (car records))
1439                       lsdb-hash-table)
1440         (run-hook-with-args 'lsdb-update-record-functions (car records))
1441         (setq lsdb-hash-tables-are-dirty t)))))
1442
1443 (defun lsdb-mu-get-prefix-method ()
1444   "A mu-cite method to return a prefix from LSDB or \">\".
1445 If an `attribution' value is found in LSDB, the value is returned.
1446 Otherwise \">\" is returned."
1447   (or (lsdb-mu-attribution (mu-cite-get-value 'address))
1448       ">"))
1449
1450 (defvar minibuffer-allow-text-properties)
1451
1452 (defvar lsdb-mu-history nil)
1453
1454 (defun lsdb-mu-get-prefix-register-method ()
1455   "A mu-cite method to return a prefix from LSDB or register it.
1456 If an `attribution' value is found in LSDB, the value is returned.
1457 Otherwise the function requests a prefix from a user.  The prefix will
1458 be registered to LSDB if the user wants it."
1459   (let ((address (mu-cite-get-value 'address)))
1460     (or (lsdb-mu-attribution address)
1461         (let* (minibuffer-allow-text-properties
1462                (result (read-string "Citation name? "
1463                                     (or (mu-cite-get-value 'x-attribution)
1464                                         (mu-cite-get-value 'full-name))
1465                                     'lsdb-mu-history)))
1466           (if (and (not (string-equal result ""))
1467                    (y-or-n-p (format "Register \"%s\"? " result)))
1468               (lsdb-mu-set-attribution result address))
1469           result))))
1470
1471 (defun lsdb-mu-get-prefix-register-verbose-method ()
1472   "A mu-cite method to return a prefix using LSDB.
1473
1474 In this method, a user must specify a prefix unconditionally.  If an
1475 `attribution' value is found in LSDB, the value is used as a initial
1476 value to input the prefix.  The prefix will be registered to LSDB if
1477 the user wants it."
1478   (let* ((address (mu-cite-get-value 'address))
1479          (attribution (lsdb-mu-attribution address))
1480          minibuffer-allow-text-properties
1481          (result (read-string "Citation name? "
1482                               (or attribution
1483                                   (mu-cite-get-value 'x-attribution)
1484                                   (mu-cite-get-value 'full-name))
1485                               'lsdb-mu-history)))
1486     (if (and (not (string-equal result ""))
1487              (not (string-equal result attribution))
1488              (y-or-n-p (format "Register \"%s\"? " result)))
1489         (lsdb-mu-set-attribution result address))
1490     result))
1491
1492 (defvar mu-cite-methods-alist)
1493 ;;;###autoload
1494 (defun lsdb-mu-insinuate ()
1495   (add-hook 'mu-cite-instantiation-hook
1496             (lambda ()
1497               (setq mu-cite-methods-alist
1498                     (nconc
1499                      mu-cite-methods-alist
1500                      (list
1501                       (cons 'lsdb-prefix
1502                             #'lsdb-mu-get-prefix-method)
1503                       (cons 'lsdb-prefix-register
1504                             #'lsdb-mu-get-prefix-register-method)
1505                       (cons 'lsdb-prefix-register-verbose
1506                             #'lsdb-mu-get-prefix-register-verbose-method)))))))
1507
1508 ;;;_. X-Face Rendering
1509 (defvar lsdb-x-face-cache
1510   (lsdb-make-hash-table :test 'equal))
1511
1512 (defun lsdb-x-face-available-image-type ()
1513   (static-if (featurep 'xemacs)
1514       (if (featurep 'xpm)
1515           'xpm)
1516     (and (>= emacs-major-version 21)
1517          (fboundp 'image-type-available-p)
1518          (if (image-type-available-p 'pbm)
1519              'pbm
1520            (if (image-type-available-p 'xpm)
1521                'xpm)))))
1522
1523 (defun lsdb-expose-x-face ()
1524   (let* ((record (get-text-property (point-min) 'lsdb-record))
1525          (x-face (cdr (assq 'x-face (cdr record))))
1526          (delimiter "\r "))
1527     (when (and lsdb-insert-x-face-function
1528                x-face)
1529       (goto-char (point-min))
1530       (end-of-line)
1531       (put-text-property 0 1 'invisible t delimiter) ;hide "\r"
1532       (put-text-property
1533        (point)
1534        (progn
1535          (insert delimiter)
1536          (while x-face
1537            (funcall lsdb-insert-x-face-function (pop x-face)))
1538          (point))
1539        'lsdb-record record))))
1540
1541 (defun lsdb-insert-x-face-image (data type marker)
1542   (static-if (featurep 'xemacs)
1543       (save-excursion
1544         (set-buffer (marker-buffer marker))
1545         (goto-char marker)
1546         (let* ((inhibit-read-only t)
1547                buffer-read-only
1548                (glyph (make-glyph (vector type :data data))))
1549           (set-extent-begin-glyph
1550            (make-extent (point) (point))
1551            glyph)))
1552     (save-excursion
1553       (set-buffer (marker-buffer marker))
1554       (goto-char marker)
1555       (let* ((inhibit-read-only t)
1556              buffer-read-only
1557              (image (create-image data type t :ascent 'center))
1558              (record (get-text-property (point) 'lsdb-record)))
1559         (put-text-property (point) (progn
1560                                      (insert-image image)
1561                                      (point))
1562                            'lsdb-record record)))))
1563
1564 (defun lsdb-insert-x-face-asynchronously (x-face)
1565   (let* ((type (or lsdb-x-face-image-type
1566                    (lsdb-x-face-available-image-type)))
1567          (shell-file-name lsdb-shell-file-name)
1568          (shell-command-switch lsdb-shell-command-switch)
1569          (process-connection-type nil)
1570          (cached (cdr (assq type (lsdb-gethash x-face lsdb-x-face-cache))))
1571          (marker (point-marker))
1572          process)
1573     (if cached
1574         (lsdb-insert-x-face-image cached type marker)
1575       (setq process
1576             (start-process-shell-command
1577              "lsdb-x-face-command" (generate-new-buffer " *lsdb work*")
1578              (concat "{ "
1579                      (nth 1 (assq type lsdb-x-face-command-alist))
1580                      "; } 2> /dev/null")))
1581       (process-send-string process (concat x-face "\n"))
1582       (process-send-eof process)
1583       (set-process-sentinel
1584        process
1585        `(lambda (process string)
1586           (unwind-protect
1587               (when (and (buffer-live-p (marker-buffer ,marker))
1588                          (equal string "finished\n"))
1589                 (let ((data
1590                        (with-current-buffer (process-buffer process)
1591                          (set-buffer-multibyte nil)
1592                          (buffer-string))))
1593                   (lsdb-insert-x-face-image data ',type ,marker)
1594                   (lsdb-puthash ,x-face (list (cons ',type data))
1595                                 lsdb-x-face-cache)))
1596             (kill-buffer (process-buffer process))))))))
1597
1598 (require 'product)
1599 (provide 'lsdb)
1600
1601 (product-provide 'lsdb
1602   (product-define "LSDB" nil '(0 7)))
1603
1604 ;;;_* Local emacs vars.
1605 ;;; The following `outline-layout' local variable setting:
1606 ;;;  - closes all topics from the first topic to just before the third-to-last,
1607 ;;;  - shows the children of the third to last (config vars)
1608 ;;;  - and the second to last (code section),
1609 ;;;  - and closes the last topic (this local-variables section).
1610 ;;;Local variables:
1611 ;;;outline-layout: (0 : -1 -1 0)
1612 ;;;End:
1613
1614 ;;; lsdb.el ends here