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