(Auhthors): Change my email address.
[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                 (goto-char (match-end 0))
777                 (point))))
778          pattern
779          (case-fold-search t)
780          (completion-ignore-case t))
781     (unless (eq last-command this-command)
782       (setq lsdb-last-candidates nil
783             lsdb-last-candidates-pointer nil
784             lsdb-last-completion (buffer-substring start (point))
785             pattern (concat "\\<" (regexp-quote lsdb-last-completion)))
786       (lsdb-maphash
787        (lambda (key value)
788          (let ((net (cdr (assq 'net value))))
789            (if (string-match pattern key)
790                (setq lsdb-last-candidates
791                      (nconc lsdb-last-candidates
792                             (mapcar (lambda (address)
793                                       (if (equal key address)
794                                           key
795                                         (concat key " <" address ">")))
796                                     net)))
797              (while net
798                (if (string-match pattern (car net))
799                    (push (car net) lsdb-last-candidates))
800                (setq net (cdr net))))))
801        lsdb-hash-table)
802       ;; Sort candidates by the position where the pattern occurred.
803       (setq lsdb-last-candidates
804             (sort lsdb-last-candidates
805                   (lambda (cand1 cand2)
806                     (< (if (string-match pattern cand1)
807                            (match-beginning 0))
808                        (if (string-match pattern cand2)
809                            (match-beginning 0)))))))
810     (unless lsdb-last-candidates-pointer
811       (setq lsdb-last-candidates-pointer lsdb-last-candidates))
812     (when lsdb-last-candidates-pointer
813       (delete-region start (point))
814       (insert (pop lsdb-last-candidates-pointer))
815       (lsdb-complete-name-highlight start (point)))))
816
817 ;;;_. Major Mode (`lsdb-mode') Implementation
818 ;;;_ : Modeline Buffer Identification
819 (defconst lsdb-pointer-xpm
820   "/* XPM */
821 static char * lsdb_pointer_xpm[] = {
822 \"14 14 5 1\",
823 \"      c None\",
824 \"+     c #FF9696\",
825 \"@     c #FF0000\",
826 \"#     c #FF7575\",
827 \"$     c #FF5959\",
828 \"              \",
829 \"  +++   @@@   \",
830 \" +++## @@@@@  \",
831 \" ++### @@@@@  \",
832 \" +#####@@@@@  \",
833 \" +###$$@@@@@  \",
834 \" +###$$@@@@@  \",
835 \"  ##$$$@@@@   \",
836 \"   #$$$@@@    \",
837 \"    $$@@@     \",
838 \"     $@@      \",
839 \"      @       \",
840 \"              \",
841 \"              \"};")
842
843 (static-if (featurep 'xemacs)
844     (progn
845       (defvar lsdb-xemacs-modeline-left-extent
846         (copy-extent modeline-buffer-id-left-extent))
847
848       (defvar lsdb-xemacs-modeline-right-extent
849         (copy-extent modeline-buffer-id-right-extent))
850
851       (defun lsdb-modeline-buffer-identification (line)
852         "Decorate 1st element of `mode-line-buffer-identification' LINE.
853 Modify whole identification by side effect."
854         (let ((id (car line)) chopped)
855           (if (and (stringp id) (string-match "^LSDB:" id))
856               (progn
857                 (setq chopped (substring id 0 (match-end 0))
858                       id (substring id (match-end 0)))
859                 (nconc
860                  (list
861                   (let ((glyph
862                          (make-glyph
863                           (nconc
864                            (if (featurep 'xpm)
865                                (list (vector 'xpm :data lsdb-pointer-xpm)))
866                            (list (vector 'string :data chopped))))))
867                     (set-glyph-face glyph 'modeline-buffer-id)
868                     (cons lsdb-xemacs-modeline-left-extent glyph))
869                   (cons lsdb-xemacs-modeline-right-extent id))
870                  (cdr line)))
871             line))))
872   (condition-case nil
873       (progn
874         (require 'image)
875         (defun lsdb-modeline-buffer-identification (line)
876           "Decorate 1st element of `mode-line-buffer-identification' LINE.
877 Modify whole identification by side effect."
878           (let ((id (copy-sequence (car line)))
879                 (image
880                  (if (image-type-available-p 'xpm)
881                      (create-image lsdb-pointer-xpm 'xpm t :ascent 'center))))
882             (when (and image
883                        (stringp id) (string-match "^LSDB:" id))
884               (add-text-properties 0 (length id)
885                                    (list 'display image
886                                          'rear-nonsticky (list 'display))
887                                    id)
888               (setcar line id))
889             line)))
890     (error
891      (defalias 'lsdb-modeline-buffer-identification 'identity))))
892
893 (defvar lsdb-mode-map
894   (let ((keymap (make-sparse-keymap)))
895     (define-key keymap "a" 'lsdb-mode-add-entry)
896     (define-key keymap "d" 'lsdb-mode-delete-entry)
897     (define-key keymap "e" 'lsdb-mode-edit-entry)
898     (define-key keymap "l" 'lsdb-mode-load)
899     (define-key keymap "s" 'lsdb-mode-save)
900     (define-key keymap "q" 'lsdb-mode-quit-window)
901     (define-key keymap "g" 'lsdb-mode-lookup)
902     (define-key keymap "p" 'lsdb-mode-previous-record)
903     (define-key keymap "n" 'lsdb-mode-next-record)
904     (define-key keymap " " 'scroll-up)
905     (define-key keymap [delete] 'scroll-down)
906     (define-key keymap "\177" 'scroll-down)
907     (define-key keymap [backspace] 'scroll-down)
908     keymap)
909   "LSDB's keymap.")
910
911 (defvar lsdb-modeline-string "")
912
913 (define-derived-mode lsdb-mode fundamental-mode "LSDB"
914   "Major mode for browsing LSDB records."
915   (setq buffer-read-only t)
916   (static-if (featurep 'xemacs)
917       ;; In XEmacs, setting `font-lock-defaults' only affects on
918       ;; `find-file-hooks'.
919       (font-lock-set-defaults)
920     (set (make-local-variable 'font-lock-defaults)
921          '(lsdb-font-lock-keywords t)))
922   (make-local-hook 'post-command-hook)
923   (add-hook 'post-command-hook 'lsdb-modeline-update nil t)
924   (make-local-variable 'lsdb-modeline-string)
925   (setq mode-line-buffer-identification
926         (lsdb-modeline-buffer-identification
927          '("LSDB: " lsdb-modeline-string)))
928   (lsdb-modeline-update)
929   (force-mode-line-update))
930
931 (defun lsdb-modeline-update ()
932   (let ((record
933          (get-text-property (if (eobp) (point-min) (point)) 'lsdb-record))
934         net)
935     (if record
936         (progn
937           (setq net (car (cdr (assq 'net (cdr record)))))
938           (if (equal net (car record))
939               (setq lsdb-modeline-string net)
940             (setq lsdb-modeline-string (concat (car record) " <" net ">"))))
941       (setq lsdb-modeline-string ""))))
942
943 (defun lsdb-narrow-to-record ()
944   "Narrow to the current record."
945   (let ((end (next-single-property-change (point) 'lsdb-record nil
946                                           (point-max))))
947     (narrow-to-region
948      (previous-single-property-change end 'lsdb-record nil (point-min))
949      end)
950     (goto-char (point-min))))
951
952 (defun lsdb-current-record ()
953   "Return the current record name."
954   (let ((record (get-text-property (point) 'lsdb-record)))
955     (unless record
956       (error "There is nothing to follow here"))
957     record))
958
959 (defun lsdb-current-entry ()
960   "Return the current entry name.
961 If the point is not on a entry line, it prompts to select a entry in
962 the current record."
963   (save-excursion
964     (beginning-of-line)
965     (if (looking-at "^[^\t]")
966         (let ((record (lsdb-current-record))
967               (completion-ignore-case t))
968           (completing-read
969            "Which entry to modify: "
970            (mapcar (lambda (entry)
971                      (list (capitalize (symbol-name (car entry)))))
972                    (cdr record))))
973       (end-of-line)
974       (re-search-backward "^\t\\([^\t][^:]+\\):")
975       (match-string 1))))
976
977 (defun lsdb-mode-add-entry (entry-name)
978   "Add an entry on the current line."
979   (interactive
980    (let ((completion-ignore-case t))
981      (list (completing-read "Entry name: " lsdb-known-entry-names))))
982   (beginning-of-line)
983   (unless (symbolp entry-name)
984     (setq entry-name (intern (downcase entry-name))))
985   (when (assq entry-name (cdr (lsdb-current-record)))
986     (error "The entry already exists"))
987   (let ((marker (point-marker)))
988     (lsdb-edit-form
989      nil "Editing the entry."
990      `(lambda (form)
991         (when form
992           (save-excursion
993             (set-buffer lsdb-buffer-name)
994             (goto-char ,marker)
995             (let ((record (lsdb-current-record))
996                   (inhibit-read-only t)
997                   buffer-read-only)
998               (setcdr record (cons (cons ',entry-name form) (cdr record)))
999               (lsdb-puthash (car record) (cdr record)
1000                             lsdb-hash-table)
1001               (run-hook-with-args 'lsdb-update-record-functions record)
1002               (setq lsdb-hash-tables-are-dirty t)
1003               (beginning-of-line 2)
1004               (add-text-properties
1005                (point)
1006                (progn
1007                  (lsdb-insert-entry (cons ',entry-name form))
1008                  (point))
1009                (list 'lsdb-record record)))))))))
1010
1011 (defun lsdb-mode-delete-entry (&optional entry-name dont-update)
1012   "Delete the entry on the current line."
1013   (interactive)
1014   (let ((record (lsdb-current-record))
1015         entry)
1016     (or entry-name
1017         (setq entry-name (lsdb-current-entry)))
1018     (setq entry (assq (intern (downcase entry-name)) (cdr record)))
1019     (when (and entry
1020                (not dont-update))
1021       (setcdr record (delq entry (cdr record)))
1022       (lsdb-puthash (car record) (cdr record)
1023                     lsdb-hash-table)
1024       (run-hook-with-args 'lsdb-update-record-functions record)
1025       (setq lsdb-hash-tables-are-dirty t))
1026     (save-restriction
1027       (lsdb-narrow-to-record)
1028       (let ((case-fold-search t)
1029             (inhibit-read-only t)
1030             buffer-read-only)
1031         (goto-char (point-min))
1032         (if (re-search-forward
1033              (concat "^\t" (or entry-name
1034                                (lsdb-current-entry))
1035                      ":")
1036              nil t)
1037             (delete-region (match-beginning 0)
1038                            (if (re-search-forward
1039                                 "^\t[^\t][^:]+:" nil t)
1040                                (match-beginning 0)
1041                              (point-max))))))))
1042
1043 (defun lsdb-mode-edit-entry ()
1044   "Edit the entry on the current line."
1045   (interactive)
1046   (let* ((record (lsdb-current-record))
1047          (entry-name (intern (downcase (lsdb-current-entry))))
1048          (entry (assq entry-name (cdr record)))
1049          (marker (point-marker)))
1050     (lsdb-edit-form
1051      (cdr entry) "Editing the entry."
1052      `(lambda (form)
1053         (unless (equal form ',(cdr entry))
1054           (save-excursion
1055             (set-buffer lsdb-buffer-name)
1056             (goto-char ,marker)
1057             (let* ((record (lsdb-current-record))
1058                    (entry (assq ',entry-name (cdr record)))
1059                    (inhibit-read-only t)
1060                    buffer-read-only)
1061               (setcdr entry form)
1062               (run-hook-with-args 'lsdb-update-record-functions record)
1063               (setq lsdb-hash-tables-are-dirty t)
1064               (lsdb-mode-delete-entry (symbol-name ',entry-name) t)
1065               (beginning-of-line)
1066               (add-text-properties
1067                (point)
1068                (progn
1069                  (lsdb-insert-entry (cons ',entry-name form))
1070                  (point))
1071                (list 'lsdb-record record)))))))))
1072
1073 (defun lsdb-mode-save (&optional dont-ask)
1074   "Save LSDB hash table into `lsdb-file'."
1075   (interactive)
1076   (if (not lsdb-hash-tables-are-dirty)
1077       (message "(No changes need to be saved)")
1078     (when (or (interactive-p)
1079               dont-ask
1080               (y-or-n-p "Save the LSDB now?"))
1081       (lsdb-save-hash-tables)
1082       (setq lsdb-hash-tables-are-dirty nil)
1083       (message "The LSDB was saved successfully."))))
1084
1085 (defun lsdb-mode-load ()
1086   "Load LSDB hash table from `lsdb-file'."
1087   (interactive)
1088   (let (lsdb-secondary-hash-tables)
1089     (lsdb-load-hash-tables))
1090   (message "Rebuilding secondary hash tables...")
1091   (lsdb-rebuild-secondary-hash-tables t)
1092   (message "Rebuilding secondary hash tables...done"))
1093
1094 (defun lsdb-mode-quit-window (&optional kill window)
1095   "Quit the current buffer.
1096 It partially emulates the GNU Emacs' of `quit-window'."
1097   (interactive "P")
1098   (unless window
1099     (setq window (selected-window)))
1100   (let ((buffer (window-buffer window)))
1101     (unless (save-selected-window
1102               (select-window window)
1103               (one-window-p))
1104       (delete-window window))
1105     (if kill
1106         (kill-buffer buffer)
1107       (bury-buffer (unless (eq buffer (current-buffer)) buffer)))))
1108
1109 (defun lsdb-hide-buffer ()
1110   "Hide the LSDB window."
1111   (let ((window (get-buffer-window lsdb-buffer-name)))
1112     (if window
1113         (lsdb-mode-quit-window nil window))))
1114
1115 (defun lsdb-show-buffer ()
1116   "Show the LSDB window."
1117   (if (get-buffer lsdb-buffer-name)
1118       (if lsdb-temp-buffer-show-function
1119           (let ((lsdb-pop-up-windows t))
1120             (funcall lsdb-temp-buffer-show-function lsdb-buffer-name))
1121         (pop-to-buffer lsdb-buffer-name))))
1122
1123 (defun lsdb-toggle-buffer (&optional arg)
1124   "Toggle hiding of the LSDB window.
1125 If given a negative prefix, always show; if given a positive prefix,
1126 always hide."
1127   (interactive
1128    (list (if current-prefix-arg
1129              (prefix-numeric-value current-prefix-arg)
1130            0)))
1131   (unless arg                           ;called noninteractively?
1132     (setq arg 0))
1133   (cond
1134    ((or (< arg 0)
1135         (and (zerop arg)
1136              (not (get-buffer-window lsdb-buffer-name))))
1137     (lsdb-show-buffer))
1138    ((or (> arg 0)
1139         (and (zerop arg)
1140              (get-buffer-window lsdb-buffer-name)))
1141     (lsdb-hide-buffer))))
1142
1143 (defun lsdb-lookup-records (regexp &optional entry-name)
1144   "Return the all records in the LSDB matching the REGEXP.
1145 If the optional 2nd argument ENTRY-NAME is given, matching only
1146 performed against the entry field."
1147   (let (records)
1148     (lsdb-maphash
1149      (if entry-name
1150          (progn
1151            (unless (symbolp entry-name)
1152              (setq entry-name (intern (downcase entry-name))))
1153            (lambda (key value)
1154              (let ((entry (cdr (assq entry-name value)))
1155                    found)
1156                (unless (listp entry)
1157                  (setq entry (list entry)))
1158                (while (and (not found) entry)
1159                  (if (string-match regexp (pop entry))
1160                      (setq found t)))
1161                (if found
1162                    (push (cons key value) records)))))
1163        (lambda (key value)
1164          (if (string-match regexp key)
1165              (push (cons key value) records))))
1166      lsdb-hash-table)
1167     records))
1168
1169 (defvar lsdb-mode-lookup-history nil)
1170
1171 (defun lsdb-mode-lookup (regexp &optional entry-name)
1172   "Display the all records in the LSDB matching the REGEXP.
1173 If the optional 2nd argument ENTRY-NAME is given, matching only
1174 performed against the entry field."
1175   (interactive
1176    (let* ((completion-ignore-case t)
1177           (entry-name
1178            (if current-prefix-arg
1179                (completing-read "Entry name: "
1180                                 lsdb-known-entry-names))))
1181      (list
1182       (read-from-minibuffer
1183        (if entry-name
1184            (format "Search records `%s' regexp: " entry-name)
1185          "Search records regexp: ")
1186        nil nil nil 'lsdb-mode-lookup-history)
1187       entry-name)))
1188   (lsdb-maybe-load-hash-tables)
1189   (let ((records (lsdb-lookup-records regexp entry-name)))
1190     (if records
1191         (lsdb-display-records records))))
1192
1193 ;;;###autoload
1194 (defalias 'lsdb 'lsdb-mode-lookup)
1195
1196 (defun lsdb-mode-next-record (&optional arg)
1197   "Go to the next record."
1198   (interactive "p")
1199   (unless arg                           ;called noninteractively?
1200     (setq arg 1))
1201   (if (< arg 0)
1202       (lsdb-mode-previous-record (- arg))
1203     (while (> arg 0)
1204       (goto-char (next-single-property-change
1205                   (point) 'lsdb-record nil (point-max)))
1206       (setq arg (1- arg)))))
1207
1208 (defun lsdb-mode-previous-record (&optional arg)
1209   "Go to the previous record."
1210   (interactive "p")
1211   (unless arg                           ;called noninteractively?
1212     (setq arg 1))
1213   (if (< arg 0)
1214       (lsdb-mode-next-record (- arg))
1215     (while (> arg 0)
1216       (goto-char (previous-single-property-change
1217                   (point) 'lsdb-record nil (point-min)))
1218       (setq arg (1- arg)))))
1219
1220 ;;;_ : Edit Forms -- stolen (and renamed) from gnus-eform.el
1221 (defvar lsdb-edit-form-buffer "*LSDB edit form*")
1222 (defvar lsdb-edit-form-done-function nil)
1223 (defvar lsdb-previous-window-configuration nil)
1224
1225 (defvar lsdb-edit-form-mode-map
1226   (let ((keymap (make-sparse-keymap)))
1227     (set-keymap-parent keymap emacs-lisp-mode-map)
1228     (define-key keymap "\C-c\C-c" 'lsdb-edit-form-done)
1229     (define-key keymap "\C-c\C-k" 'lsdb-edit-form-exit)
1230     keymap)
1231   "Edit form's keymap.")
1232
1233 (defun lsdb-edit-form-mode ()
1234   "Major mode for editing forms.
1235 It is a slightly enhanced emacs-lisp-mode.
1236
1237 \\{lsdb-edit-form-mode-map}"
1238   (interactive)
1239   (kill-all-local-variables)
1240   (setq major-mode 'lsdb-edit-form-mode
1241         mode-name "LSDB Edit Form")
1242   (use-local-map lsdb-edit-form-mode-map)
1243   (make-local-variable 'lsdb-edit-form-done-function)
1244   (make-local-variable 'lsdb-previous-window-configuration)
1245   (run-hooks 'lsdb-edit-form-mode-hook))
1246
1247 (defun lsdb-edit-form (form documentation exit-func)
1248   "Edit FORM in a new buffer.
1249 Call EXIT-FUNC on exit.  Display DOCUMENTATION in the beginning
1250 of the buffer."
1251   (let ((window-configuration
1252          (current-window-configuration)))
1253     (switch-to-buffer (get-buffer-create lsdb-edit-form-buffer))
1254     (lsdb-edit-form-mode)
1255     (setq lsdb-previous-window-configuration window-configuration
1256           lsdb-edit-form-done-function exit-func)
1257     (erase-buffer)
1258     (insert documentation)
1259     (unless (bolp)
1260       (insert "\n"))
1261     (goto-char (point-min))
1262     (while (not (eobp))
1263       (insert ";;; ")
1264       (forward-line 1))
1265     (insert ";; Type `C-c C-c' after you've finished editing.\n")
1266     (insert "\n")
1267     (let ((p (point)))
1268       (pp form (current-buffer))
1269       (insert "\n")
1270       (goto-char p))))
1271
1272 (defun lsdb-edit-form-done ()
1273   "Update changes and kill the current buffer."
1274   (interactive)
1275   (goto-char (point-min))
1276   (let ((form (condition-case nil
1277                   (read (current-buffer))
1278                 (end-of-file nil)))
1279         (func lsdb-edit-form-done-function))
1280     (lsdb-edit-form-exit)
1281     (funcall func form)))
1282
1283 (defun lsdb-edit-form-exit ()
1284   "Kill the current buffer."
1285   (interactive)
1286   (let ((window-configuration lsdb-previous-window-configuration))
1287     (kill-buffer (current-buffer))
1288     (set-window-configuration window-configuration)))
1289
1290 ;;;_. Interface to Semi-gnus
1291 ;;;###autoload
1292 (defun lsdb-gnus-insinuate ()
1293   "Call this function to hook LSDB into Semi-gnus."
1294   (add-hook 'gnus-article-prepare-hook 'lsdb-gnus-update-record)
1295   (add-hook 'gnus-save-newsrc-hook 'lsdb-mode-save))
1296
1297 (defvar gnus-current-headers)
1298 (defun lsdb-gnus-update-record ()
1299   (let ((entity gnus-current-headers)
1300         records)
1301     (with-temp-buffer
1302       (set-buffer-multibyte nil)
1303       (buffer-disable-undo)
1304       (mime-insert-entity entity)
1305       (setq records (lsdb-update-records))
1306       (when records
1307         (lsdb-display-record (car records))))))
1308
1309 ;;;_. Interface to Wanderlust
1310 ;;;###autoload
1311 (defun lsdb-wl-insinuate ()
1312   "Call this function to hook LSDB into Wanderlust."
1313   (add-hook 'wl-message-redisplay-hook 'lsdb-wl-update-record)
1314   (add-hook 'wl-summary-exit-hook 'lsdb-hide-buffer)
1315   (add-hook 'wl-summary-toggle-disp-off-hook 'lsdb-hide-buffer)
1316   (add-hook 'wl-summary-toggle-disp-folder-on-hook 'lsdb-hide-buffer)
1317   (add-hook 'wl-summary-toggle-disp-folder-off-hook 'lsdb-hide-buffer)
1318   (add-hook 'wl-summary-toggle-disp-folder-message-resumed-hook
1319             'lsdb-wl-show-buffer)
1320   (add-hook 'wl-exit-hook 'lsdb-mode-save)
1321   (add-hook 'wl-save-hook 'lsdb-mode-save))
1322
1323 (eval-when-compile
1324   (autoload 'wl-message-get-original-buffer "wl-message"))
1325 (defun lsdb-wl-update-record ()
1326   (save-excursion
1327     (set-buffer (wl-message-get-original-buffer))
1328     (let ((records (lsdb-update-records)))
1329       (when records
1330         (let ((lsdb-temp-buffer-show-function
1331                #'lsdb-wl-temp-buffer-show-function))
1332           (lsdb-display-record (car records)))))))
1333
1334 (defun lsdb-wl-toggle-buffer (&optional arg)
1335   "Toggle hiding of the LSDB window for Wanderlust.
1336 If given a negative prefix, always show; if given a positive prefix,
1337 always hide."
1338   (interactive
1339    (list (if current-prefix-arg
1340              (prefix-numeric-value current-prefix-arg)
1341            0)))
1342   (let ((lsdb-temp-buffer-show-function
1343          #'lsdb-wl-temp-buffer-show-function))
1344     (lsdb-toggle-buffer arg)))
1345
1346 (defun lsdb-wl-show-buffer ()
1347   (when lsdb-pop-up-windows
1348     (let ((lsdb-temp-buffer-show-function
1349            #'lsdb-wl-temp-buffer-show-function))
1350       (lsdb-show-buffer))))
1351
1352 (defvar wl-current-summary-buffer)
1353 (defvar wl-message-buffer)
1354 (defun lsdb-wl-temp-buffer-show-function (buffer)
1355   (when lsdb-pop-up-windows
1356     (save-selected-window
1357       (let ((window (or (get-buffer-window lsdb-buffer-name)
1358                         (progn
1359                           (select-window 
1360                            (or (save-excursion
1361                                  (if (buffer-live-p wl-current-summary-buffer)
1362                                      (set-buffer wl-current-summary-buffer))
1363                                  (get-buffer-window wl-message-buffer))
1364                                (get-largest-window)))
1365                           (split-window-vertically)))))
1366         (set-window-buffer window buffer)
1367         (lsdb-fit-window-to-buffer window)))))
1368
1369 ;;;_. Interface to Mew written by Hideyuki SHIRAI <shirai@rdmg.mgcs.mei.co.jp>
1370 (eval-when-compile
1371   (autoload 'mew-sinfo-get-disp-msg "mew")
1372   (autoload 'mew-current-get-fld "mew")
1373   (autoload 'mew-current-get-msg "mew")
1374   (autoload 'mew-frame-id "mew")
1375   (autoload 'mew-cache-hit "mew")
1376   (autoload 'mew-xinfo-get-decode-err "mew")
1377   (autoload 'mew-xinfo-get-action "mew"))
1378
1379 ;;;###autoload
1380 (defun lsdb-mew-insinuate ()
1381   "Call this function to hook LSDB into Mew."
1382   (add-hook 'mew-message-hook 'lsdb-mew-update-record)
1383   (add-hook 'mew-summary-toggle-disp-msg-hook
1384             (lambda ()
1385               (unless (mew-sinfo-get-disp-msg)
1386                 (lsdb-hide-buffer))))
1387   (add-hook 'mew-suspend-hook 'lsdb-hide-buffer)
1388   (add-hook 'mew-quit-hook 'lsdb-mode-save)
1389   (add-hook 'kill-emacs-hook 'lsdb-mode-save)
1390   (cond
1391    ;; Mew 3
1392    ((fboundp 'mew-summary-visit-folder)
1393     (defadvice mew-summary-visit-folder (before lsdb-hide-buffer activate)
1394       (lsdb-hide-buffer)))
1395    ;; Mew 2
1396    ((fboundp 'mew-summary-switch-to-folder)
1397     (defadvice mew-summary-switch-to-folder (before lsdb-hide-buffer activate)
1398       (lsdb-hide-buffer)))))
1399
1400 (defun lsdb-mew-update-record ()
1401   (let* ((fld (mew-current-get-fld (mew-frame-id)))
1402          (msg (mew-current-get-msg (mew-frame-id)))
1403          (cache (mew-cache-hit fld msg))
1404          records)
1405     (when cache
1406       (save-excursion
1407         (set-buffer cache)
1408         (unless (or (mew-xinfo-get-decode-err) (mew-xinfo-get-action))
1409           (make-local-variable 'lsdb-decode-field-body-function)
1410           (setq lsdb-decode-field-body-function
1411                 (lambda (body name)
1412                   (set-text-properties 0 (length body) nil body)
1413                   body))
1414           (when (setq records (lsdb-update-records))
1415             (lsdb-display-record (car records))))))))
1416
1417 ;;;_. Interface to MU-CITE
1418 (eval-when-compile
1419   (autoload 'mu-cite-get-value "mu-cite"))
1420
1421 (defun lsdb-mu-attribution (address)
1422   "Extract attribute information from LSDB."
1423   (let ((records
1424          (lsdb-lookup-records (concat "\\<" address "\\>") 'net)))
1425     (if records
1426         (cdr (assq 'attribution (cdr (car records)))))))
1427
1428 (defun lsdb-mu-set-attribution (attribution address)
1429   "Add attribute information to LSDB."
1430   (let ((records
1431          (lsdb-lookup-records (concat "\\<" address "\\>") 'net))
1432         entry)
1433     (when records
1434       (setq entry (assq 'attribution (cdr (car records))))
1435       (if entry
1436           (setcdr entry attribution)
1437         (setcdr (car records) (cons (cons 'attribution attribution)
1438                                     (cdr (car records))))
1439         (lsdb-puthash (car (car records)) (cdr (car records))
1440                       lsdb-hash-table)
1441         (run-hook-with-args 'lsdb-update-record-functions (car records))
1442         (setq lsdb-hash-tables-are-dirty t)))))
1443
1444 (defun lsdb-mu-get-prefix-method ()
1445   "A mu-cite method to return a prefix from LSDB or \">\".
1446 If an `attribution' value is found in LSDB, the value is returned.
1447 Otherwise \">\" is returned."
1448   (or (lsdb-mu-attribution (mu-cite-get-value 'address))
1449       ">"))
1450
1451 (defvar minibuffer-allow-text-properties)
1452
1453 (defvar lsdb-mu-history nil)
1454
1455 (defun lsdb-mu-get-prefix-register-method ()
1456   "A mu-cite method to return a prefix from LSDB or register it.
1457 If an `attribution' value is found in LSDB, the value is returned.
1458 Otherwise the function requests a prefix from a user.  The prefix will
1459 be registered to LSDB if the user wants it."
1460   (let ((address (mu-cite-get-value 'address)))
1461     (or (lsdb-mu-attribution address)
1462         (let* (minibuffer-allow-text-properties
1463                (result (read-string "Citation name? "
1464                                     (or (mu-cite-get-value 'x-attribution)
1465                                         (mu-cite-get-value 'full-name))
1466                                     'lsdb-mu-history)))
1467           (if (and (not (string-equal result ""))
1468                    (y-or-n-p (format "Register \"%s\"? " result)))
1469               (lsdb-mu-set-attribution result address))
1470           result))))
1471
1472 (defun lsdb-mu-get-prefix-register-verbose-method ()
1473   "A mu-cite method to return a prefix using LSDB.
1474
1475 In this method, a user must specify a prefix unconditionally.  If an
1476 `attribution' value is found in LSDB, the value is used as a initial
1477 value to input the prefix.  The prefix will be registered to LSDB if
1478 the user wants it."
1479   (let* ((address (mu-cite-get-value 'address))
1480          (attribution (lsdb-mu-attribution address))
1481          minibuffer-allow-text-properties
1482          (result (read-string "Citation name? "
1483                               (or attribution
1484                                   (mu-cite-get-value 'x-attribution)
1485                                   (mu-cite-get-value 'full-name))
1486                               'lsdb-mu-history)))
1487     (if (and (not (string-equal result ""))
1488              (not (string-equal result attribution))
1489              (y-or-n-p (format "Register \"%s\"? " result)))
1490         (lsdb-mu-set-attribution result address))
1491     result))
1492
1493 (defvar mu-cite-methods-alist)
1494 ;;;###autoload
1495 (defun lsdb-mu-insinuate ()
1496   (add-hook 'mu-cite-instantiation-hook
1497             (lambda ()
1498               (setq mu-cite-methods-alist
1499                     (nconc
1500                      mu-cite-methods-alist
1501                      (list
1502                       (cons 'lsdb-prefix
1503                             #'lsdb-mu-get-prefix-method)
1504                       (cons 'lsdb-prefix-register
1505                             #'lsdb-mu-get-prefix-register-method)
1506                       (cons 'lsdb-prefix-register-verbose
1507                             #'lsdb-mu-get-prefix-register-verbose-method)))))))
1508
1509 ;;;_. X-Face Rendering
1510 (defvar lsdb-x-face-cache
1511   (lsdb-make-hash-table :test 'equal))
1512
1513 (defun lsdb-x-face-available-image-type ()
1514   (static-if (featurep 'xemacs)
1515       (if (featurep 'xpm)
1516           'xpm)
1517     (and (>= emacs-major-version 21)
1518          (fboundp 'image-type-available-p)
1519          (if (image-type-available-p 'pbm)
1520              'pbm
1521            (if (image-type-available-p 'xpm)
1522                'xpm)))))
1523
1524 (defun lsdb-expose-x-face ()
1525   (let* ((record (get-text-property (point-min) 'lsdb-record))
1526          (x-face (cdr (assq 'x-face (cdr record))))
1527          (delimiter "\r "))
1528     (when (and lsdb-insert-x-face-function
1529                x-face)
1530       (goto-char (point-min))
1531       (end-of-line)
1532       (put-text-property 0 1 'invisible t delimiter) ;hide "\r"
1533       (put-text-property
1534        (point)
1535        (progn
1536          (insert delimiter)
1537          (while x-face
1538            (funcall lsdb-insert-x-face-function (pop x-face)))
1539          (point))
1540        'lsdb-record record))))
1541
1542 (defun lsdb-insert-x-face-image (data type marker)
1543   (static-if (featurep 'xemacs)
1544       (save-excursion
1545         (set-buffer (marker-buffer marker))
1546         (goto-char marker)
1547         (let* ((inhibit-read-only t)
1548                buffer-read-only
1549                (glyph (make-glyph (vector type :data data))))
1550           (set-extent-begin-glyph
1551            (make-extent (point) (point))
1552            glyph)))
1553     (save-excursion
1554       (set-buffer (marker-buffer marker))
1555       (goto-char marker)
1556       (let* ((inhibit-read-only t)
1557              buffer-read-only
1558              (image (create-image data type t :ascent 'center))
1559              (record (get-text-property (point) 'lsdb-record)))
1560         (put-text-property (point) (progn
1561                                      (insert-image image)
1562                                      (point))
1563                            'lsdb-record record)))))
1564
1565 (defun lsdb-insert-x-face-asynchronously (x-face)
1566   (let* ((type (or lsdb-x-face-image-type
1567                    (lsdb-x-face-available-image-type)))
1568          (shell-file-name lsdb-shell-file-name)
1569          (shell-command-switch lsdb-shell-command-switch)
1570          (process-connection-type nil)
1571          (cached (cdr (assq type (lsdb-gethash x-face lsdb-x-face-cache))))
1572          (marker (point-marker))
1573          process)
1574     (if cached
1575         (lsdb-insert-x-face-image cached type marker)
1576       (setq process
1577             (start-process-shell-command
1578              "lsdb-x-face-command" (generate-new-buffer " *lsdb work*")
1579              (concat "{ "
1580                      (nth 1 (assq type lsdb-x-face-command-alist))
1581                      "; } 2> /dev/null")))
1582       (process-send-string process (concat x-face "\n"))
1583       (process-send-eof process)
1584       (set-process-sentinel
1585        process
1586        `(lambda (process string)
1587           (unwind-protect
1588               (when (and (buffer-live-p (marker-buffer ,marker))
1589                          (equal string "finished\n"))
1590                 (let ((data
1591                        (with-current-buffer (process-buffer process)
1592                          (set-buffer-multibyte nil)
1593                          (buffer-string))))
1594                   (lsdb-insert-x-face-image data ',type ,marker)
1595                   (lsdb-puthash ,x-face (list (cons ',type data))
1596                                 lsdb-x-face-cache)))
1597             (kill-buffer (process-buffer process))))))))
1598
1599 (require 'product)
1600 (provide 'lsdb)
1601
1602 (product-provide 'lsdb
1603   (product-define "LSDB" nil '(0 7)))
1604
1605 ;;;_* Local emacs vars.
1606 ;;; The following `outline-layout' local variable setting:
1607 ;;;  - closes all topics from the first topic to just before the third-to-last,
1608 ;;;  - shows the children of the third to last (config vars)
1609 ;;;  - and the second to last (code section),
1610 ;;;  - and closes the last topic (this local-variables section).
1611 ;;;Local variables:
1612 ;;;outline-layout: (0 : -1 -1 0)
1613 ;;;End:
1614
1615 ;;; lsdb.el ends here