* lsdb.el (lsdb-print-record-function): Abolish.
[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
35 ;;; For Wanderlust, put the following lines into your ~/.wl:
36 ;;; (require 'lsdb)
37 ;;; (lsdb-wl-insinuate)
38 ;;; (add-hook 'wl-draft-mode-hook
39 ;;;           (lambda ()
40 ;;;             (define-key wl-draft-mode-map "\M-\t" 'lsdb-complete-name)))
41
42 ;;; Code:
43
44 (require 'poem)
45 (require 'mime)
46
47 ;;;_* USER CUSTOMIZATION VARIABLES:
48 (defgroup lsdb nil
49   "The Lovely Sister Database."
50   :group 'news
51   :group 'mail)
52   
53 (defcustom lsdb-file (expand-file-name "~/.lsdb")
54   "The name of the Lovely Sister Database file."
55   :group 'lsdb
56   :type 'file)
57
58 (defcustom lsdb-file-coding-system 'iso-2022-jp
59   "Coding system for `lsdb-file'."
60   :group 'lsdb
61   :type 'symbol)
62
63 (defcustom lsdb-sender-headers
64   "From\\|Resent-From"
65   "List of headers to search for senders."
66   :group 'lsdb
67   :type 'list)
68
69 (defcustom lsdb-recipients-headers
70   "Resent-To\\|Resent-Cc\\|Reply-To\\|To\\|Cc\\|Bcc"
71   "List of headers to search for recipients."
72   :group 'lsdb
73   :type 'list)
74
75 (defcustom lsdb-interesting-header-alist
76   '(("Organization" nil organization)
77     ("\\(X-\\)?User-Agent\\|X-Mailer" nil user-agent)
78     ("\\(X-\\)?ML-Name" nil mailing-list)
79     ("\\(X-URL\\|X-URI\\)" nil www)
80     ("X-Attribution\\|X-cite-me" nil attribution)
81     ("X-Face" nil x-face))
82   "Alist of headers we are interested in.
83 The format of elements of this list should be
84      (FIELD-NAME REGEXP ENTRY STRING)
85 where the last three elements are optional."
86   :group 'lsdb
87   :type 'list)
88
89 (defcustom lsdb-entry-type-alist
90   '((net 5 ?,)
91     (creation-date 2)
92     (last-modified 3)
93     (mailing-list 4 ?,)
94     (attribution 4 ?.)
95     (organization 4)
96     (www 1)
97     (score -1)
98     (x-face -1))
99   "Alist of entries to display.
100 The format of elements of this list should be
101      (ENTRY SCORE CLASS)
102 where the last element is optional."
103   :group 'lsdb
104   :type 'list)
105
106 (defcustom lsdb-decode-field-body-function #'lsdb-decode-field-body
107   "Field body decoder."
108   :group 'lsdb
109   :type 'function)
110
111 (defcustom lsdb-canonicalize-full-name-function
112   #'lsdb-canonicalize-spaces-and-dots
113   "Way to canonicalize full name."
114   :group 'lsdb
115   :type 'function)
116
117 (defcustom lsdb-window-max-height 7
118   "Maximum number of lines used to display LSDB record."
119   :group 'lsdb
120   :type 'integer)
121
122 (defcustom lsdb-insert-x-face-function
123   (if (and (>= emacs-major-version 21)
124            (locate-library "x-face-e21"))
125       #'lsdb-insert-x-face-with-x-face-e21
126     (if (and (featurep 'xemacs)
127              (memq 'xface (image-instantiator-format-list)))
128         #'lsdb-insert-x-face-with-xemacs-glyph))
129   "Function to display X-Face."
130   :group 'lsdb
131   :type 'function)
132
133 (defcustom lsdb-display-record-hook
134   (if lsdb-insert-x-face-function
135       #'lsdb-expose-x-face)
136   "A hook called after a record is displayed."
137   :group 'lsdb
138   :type 'hook)
139
140 (defgroup lsdb-edit-form nil
141   "A mode for editing forms."
142   :group 'lsdb)
143
144 (defcustom lsdb-edit-form-mode-hook nil
145   "Hook run in `lsdb-edit-form-mode' buffers."
146   :group 'lsdb-edit-form
147   :type 'hook)
148
149 ;;;_. Faces
150 (defface lsdb-header-face
151   '((t (:underline t)))
152   "Face for the file header line in `lsdb-mode'."
153   :group 'lsdb)
154 (defvar lsdb-header-face 'lsdb-header-face)
155
156 (defface lsdb-field-name-face
157   '((((class color) (background dark))
158      (:foreground "PaleTurquoise" :bold t))
159     (t (:bold t)))
160   "Face for the message header line in `lsdb-mode'."
161   :group 'lsdb)
162 (defvar lsdb-field-name-face 'lsdb-field-name-face)
163
164 (defface lsdb-field-body-face
165   '((((class color) (background dark))
166      (:foreground "turquoise" :italic t))
167     (t (:italic t)))
168   "Face for the message header line in `lsdb-mode'."
169   :group 'lsdb)
170 (defvar lsdb-field-body-face 'lsdb-field-body-face)
171
172 (defconst lsdb-font-lock-keywords
173   '(("^\\sw[^\r\n]*"
174      (0 lsdb-header-face))
175     ("^\t\t.*$"
176      (0 lsdb-field-body-face))
177     ("^\t\\([^\t:]+:\\)[ \t]*\\(.*\\)$"
178      (1 lsdb-field-name-face)
179      (2 lsdb-field-body-face))))
180
181 (put 'lsdb-mode 'font-lock-defaults '(lsdb-font-lock-keywords t))
182
183 ;;;_* CODE - no user customizations below
184 ;;;_. Internal Variables
185 (defvar lsdb-hash-table nil
186   "Internal hash table to hold LSDB records.")
187
188 (defvar lsdb-buffer-name "*LSDB*"
189   "Buffer name to display LSDB record.")
190
191 (defvar lsdb-hash-table-is-dirty nil
192   "Flag to indicate whether the hash table needs to be saved.")
193
194 (defvar lsdb-known-entry-names
195   (make-vector 29 0)
196   "An obarray used to complete an entry name.")
197
198 ;;;_. Hash Table Emulation
199 (if (fboundp 'make-hash-table)
200     (progn
201       (defalias 'lsdb-puthash 'puthash)
202       (defalias 'lsdb-gethash 'gethash)
203       (defalias 'lsdb-remhash 'remhash)
204       (defalias 'lsdb-maphash 'maphash)
205       (defalias 'lsdb-hash-table-size 'hash-table-size)
206       (defalias 'lsdb-hash-table-count 'hash-table-count)
207       (defalias 'lsdb-make-hash-table 'make-hash-table))
208   (defun lsdb-puthash (key value hash-table)
209     "Hash KEY to VALUE in HASH-TABLE."
210     ;; Obarray is regarded as an open hash table, as a matter of
211     ;; fact, rehashing doesn't make sense.
212     (let (new-obarray)
213       (when (> (car hash-table)
214                (* (length (nth 1 hash-table)) 0.7))
215         (setq new-obarray (make-vector (* (length (nth 1 hash-table)) 2) 0))
216         (mapatoms
217          (lambda (symbol)
218            (set (intern (symbol-name symbol) new-obarray)
219                 (symbol-value symbol)))
220          (nth 1 hash-table))
221         (setcdr hash-table (list new-obarray)))
222       (set (intern key (nth 1 hash-table)) value)
223       (setcar hash-table (1+ (car hash-table)))))
224   (defun lsdb-gethash (key hash-table &optional default)
225     "Find hash value for KEY in HASH-TABLE.
226 If there is no corresponding value, return DEFAULT (which defaults to nil)."
227     (let ((symbol (intern-soft key (nth 1 hash-table))))
228       (if symbol
229           (symbol-value symbol)
230         default)))
231   (defun lsdb-remhash (key hash-table)
232     "Remove the entry for KEY from HASH-TABLE.
233 Do nothing if there is no entry for KEY in HASH-TABLE."
234     (unintern key (nth 1 hash-table))
235     (setcar hash-table (1- (car hash-table))))
236   (defun lsdb-maphash (function hash-table)
237     "Map FUNCTION over entries in HASH-TABLE, calling it with two args,
238 each key and value in HASH-TABLE.
239
240 FUNCTION may not modify HASH-TABLE, with the one exception that FUNCTION
241 may remhash or puthash the entry currently being processed by FUNCTION."
242     (mapatoms
243      (lambda (symbol)
244        (funcall function (symbol-name symbol) (symbol-value symbol)))
245      hash-table))
246   (defun lsdb-hash-table-size (hash-table)
247     "Return the size of HASH-TABLE.
248 This is the current number of slots in HASH-TABLE, whether occupied or not."
249     (length (nth 1 hash-table)))
250   (defalias 'lsdb-hash-table-count 'car)
251   (defun lsdb-make-hash-table (&rest args)
252     "Return a new empty hash table object."
253     (list 0 (make-vector (or (plist-get args :size) 29) 0))))
254
255 ;;;_. Hash Table Reader/Writer
256 (eval-and-compile
257   (condition-case nil
258       (progn
259         ;; In XEmacs, hash tables can also be created by the lisp reader
260         ;; using structure syntax.
261         (read-from-string "#s(hash-table)")
262         (defun lsdb-load-file (file)
263           "Read the contents of FILE into a hash table."
264           (let ((buffer (find-file-noselect file)))
265             (unwind-protect
266                 (save-excursion
267                   (set-buffer buffer)
268                   (re-search-forward "^#s")
269                   (beginning-of-line)
270                   (read (point-min-marker)))
271               (kill-buffer buffer)))))
272     (invalid-read-syntax
273     (defun lsdb-load-file (file)
274       "Read the contents of FILE into a hash table."
275       (let* ((plist
276               (with-temp-buffer
277                 (insert-file-contents file)
278                 (save-excursion
279                   (re-search-forward "^#s")
280                   (replace-match "")
281                   (beginning-of-line)
282                   (cdr (read (point-marker))))))
283              (size (plist-get plist 'size))
284              (data (plist-get plist 'data))
285              (hash-table (lsdb-make-hash-table :size size :test 'equal)))
286         (while data
287           (lsdb-puthash (pop data) (pop data) hash-table))
288         hash-table)))))
289
290 (defun lsdb-save-file (file hash-table)
291   "Write the entries within HASH-TABLE into FILE."
292   (let ((coding-system-for-write lsdb-file-coding-system))
293     (with-temp-file file
294       (if (and (or (featurep 'mule)
295                    (featurep 'file-coding))
296                lsdb-file-coding-system)
297           (insert ";;; -*- coding: "
298                   (if (symbolp lsdb-file-coding-system)
299                       (symbol-name lsdb-file-coding-system)
300                     ;; XEmacs
301                     (coding-system-name lsdb-file-coding-system))
302                   " -*-\n"))
303       (insert "#s(hash-table size "
304               (number-to-string (lsdb-hash-table-size hash-table))
305               " test equal data (")
306       (lsdb-maphash
307        (lambda (key value)
308          (insert (prin1-to-string key) " " (prin1-to-string value) " "))
309        hash-table)
310       (insert "))"))))
311
312 ;;;_. Mail Header Extraction
313 (defun lsdb-fetch-field-bodies (regexp)
314   (save-excursion
315     (goto-char (point-min))
316     (let ((case-fold-search t)
317           field-bodies)
318       (while (re-search-forward (concat "^\\(" regexp "\\):[ \t]*")
319                                 nil t)
320         (push (funcall lsdb-decode-field-body-function
321                              (buffer-substring (point) (std11-field-end))
322                              (match-string 1))
323                     field-bodies))
324       (nreverse field-bodies))))
325
326 (defun lsdb-canonicalize-spaces-and-dots (string)
327   (while (string-match "  +\\|[\f\t\n\r\v]+\\|\\." string)
328     (setq string (replace-match " " nil t string)))
329   string)
330
331 (defun lsdb-extract-address-components (string)
332   (let ((components (std11-extract-address-components string)))
333     (if (nth 1 components)
334         (if (car components)
335             (list (nth 1 components)
336                   (funcall lsdb-canonicalize-full-name-function
337                            (car components)))
338           (list (nth 1 components) (nth 1 components))))))
339
340 ;; stolen (and renamed) from nnheader.el
341 (defun lsdb-decode-field-body (field-body field-name
342                                           &optional mode max-column)
343   (let ((multibyte enable-multibyte-characters))
344     (unwind-protect
345         (progn
346           (set-buffer-multibyte t)
347           (mime-decode-field-body field-body
348                                   (if (stringp field-name)
349                                       (intern (capitalize field-name))
350                                     field-name)
351                                   mode max-column))
352       (set-buffer-multibyte multibyte))))
353
354 ;;;_. Record Management
355 (defun lsdb-maybe-load-file ()
356   (unless lsdb-hash-table
357     (if (file-exists-p lsdb-file)
358         (setq lsdb-hash-table (lsdb-load-file lsdb-file))
359       (setq lsdb-hash-table (lsdb-make-hash-table :test 'equal)))))
360
361 (defun lsdb-update-record (sender &optional interesting)
362   (let ((old (lsdb-gethash (nth 1 sender) lsdb-hash-table))
363         (new (cons (cons 'net (list (car sender)))
364                    interesting))
365         merged
366         record)
367     (unless old
368       (setq new (cons (cons 'creation-date (format-time-string "%Y-%m-%d"))
369                       new)))
370     (setq merged (lsdb-merge-record-entries old new)
371           record (cons (nth 1 sender) merged))
372     (unless (equal merged old)
373       (let ((entry (assq 'last-modified (cdr record)))
374             (last-modified (format-time-string "%Y-%m-%d")))
375         (if entry
376             (setcdr entry last-modified)
377           (setcdr record (cons (cons 'last-modified last-modified)
378                                (cdr record)))))
379       (lsdb-puthash (car record) (cdr record)
380                     lsdb-hash-table)
381       (setq lsdb-hash-table-is-dirty t))
382     record))
383
384 (defun lsdb-update-records ()
385   (lsdb-maybe-load-file)
386   (let (senders recipients interesting alist records bodies entry)
387     (save-restriction
388       (std11-narrow-to-header)
389       (setq senders
390             (delq nil (mapcar #'lsdb-extract-address-components
391                               (lsdb-fetch-field-bodies
392                                lsdb-sender-headers)))
393             recipients
394             (delq nil (mapcar #'lsdb-extract-address-components
395                               (lsdb-fetch-field-bodies
396                                lsdb-recipients-headers))))
397       (setq alist lsdb-interesting-header-alist)
398       (while alist
399         (setq bodies
400               (mapcar
401                (lambda (field-body)
402                  (if (and (nth 1 (car alist))
403                           (string-match (nth 1 (car alist)) field-body))
404                      (replace-match (nth 3 (car alist)) nil nil field-body)
405                    field-body))
406                (lsdb-fetch-field-bodies (car (car alist)))))
407         (when bodies
408           (setq entry (or (nth 2 (car alist))
409                           'notes))
410           (push (cons entry
411                       (if (eq ?. (nth 2 (assq entry lsdb-entry-type-alist)))
412                           (car bodies)
413                         bodies))
414                 interesting))
415         (setq alist (cdr alist))))
416     (if senders
417         (setq records (list (lsdb-update-record (pop senders) interesting))))
418     (setq alist (nconc senders recipients))
419     (while alist
420       (setq records (cons (lsdb-update-record (pop alist)) records)))
421     (nreverse records)))
422
423 (defun lsdb-merge-record-entries (old new)
424   (setq old (copy-sequence old))
425   (while new
426     (let ((entry (assq (car (car new)) old))
427           list pointer)
428       (if (null entry)
429           (setq old (nconc old (list (car new))))
430         (if (listp (cdr entry))
431             (progn
432               (setq list (cdr (car new)) pointer list)
433               (while pointer
434                 (if (member (car pointer) (cdr entry))
435                     (setq list (delq (car pointer) list)))
436                 (setq pointer (cdr pointer)))
437               (setcdr entry (nconc (cdr entry) list)))
438           (setcdr entry (cdr (car new))))))
439     (setq new (cdr new)))
440   old)
441
442 ;;;_. Display Management
443 (defun lsdb-temp-buffer-show-function (buffer)
444   (save-selected-window
445     (let ((window (or (get-buffer-window lsdb-buffer-name)
446                       (progn
447                         (select-window (get-largest-window))
448                         (split-window-vertically))))
449           height)
450       (set-window-buffer window buffer)
451       (select-window window)
452       (unless (pos-visible-in-window-p (point-max))
453         (enlarge-window (- lsdb-window-max-height (window-height))))
454       (shrink-window-if-larger-than-buffer)
455       (if (> (setq height (window-height))
456              lsdb-window-max-height)
457           (shrink-window (- height lsdb-window-max-height)))
458       (set-window-start window (point-min)))))
459
460 (defun lsdb-display-record (record)
461   "Display only one RECORD, then shrink the window as possible."
462   (let ((temp-buffer-show-function
463          (function lsdb-temp-buffer-show-function)))
464     (lsdb-display-records (list record))))
465
466 (defun lsdb-display-records (records)
467   (with-output-to-temp-buffer lsdb-buffer-name
468     (set-buffer standard-output)
469     (while records
470       (save-restriction
471         (narrow-to-region (point) (point))
472         (lsdb-print-record (car records))
473         (add-text-properties (point-min) (point-max)
474                              (list 'lsdb-record (car records)))
475         (run-hooks 'lsdb-display-record-hook))
476       (goto-char (point-max))
477       (setq records (cdr records)))
478     (lsdb-mode)))
479
480 (defsubst lsdb-entry-score (entry)
481   (or (nth 1 (assq (car entry) lsdb-entry-type-alist)) 0))
482
483 (defun lsdb-insert-entry (entry)
484   (let ((entry-name (capitalize (symbol-name (car entry)))))
485     (intern entry-name lsdb-known-entry-names)
486     (insert "\t" entry-name ": "
487             (if (listp (cdr entry))
488                 (mapconcat
489                  #'identity (cdr entry)
490                  (if (eq ?, (nth 2 (assq (car entry) lsdb-entry-type-alist)))
491                      ", "
492                    "\n\t\t"))
493               (cdr entry))
494             "\n")))
495
496 (defun lsdb-print-record (record)
497   (insert (car record) "\n")
498   (let ((entries
499          (sort (copy-sequence (cdr record))
500                (lambda (entry1 entry2)
501                  (> (lsdb-entry-score entry1) (lsdb-entry-score entry2))))))
502     (while entries
503       (if (>= (lsdb-entry-score (car entries)) 0)
504           (lsdb-insert-entry (car entries)))
505       (setq entries (cdr entries)))))
506
507 ;;;_. Completion
508 (defvar lsdb-last-completion nil)
509 (defvar lsdb-last-candidates nil)
510 (defvar lsdb-last-candidates-pointer nil)
511
512 (defun lsdb-complete-name ()
513   "Complete the user full-name or net-address before point"
514   (interactive)
515   (lsdb-maybe-load-file)
516   (let* ((start
517           (save-excursion
518             (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
519             (goto-char (match-end 0))
520             (point)))
521          pattern
522          (case-fold-search t)
523          (completion-ignore-case t))
524     (unless (eq last-command this-command)
525       (setq lsdb-last-candidates nil
526             lsdb-last-candidates-pointer nil
527             lsdb-last-completion (buffer-substring start (point))
528             pattern (concat "\\<" lsdb-last-completion))
529       (lsdb-maphash
530        (lambda (key value)
531          (let ((net (cdr (assq 'net value))))
532            (if (string-match pattern key)
533                (setq lsdb-last-candidates
534                      (nconc lsdb-last-candidates
535                             (mapcar (lambda (address)
536                                       (if (equal key address)
537                                           key
538                                         (concat key " <" address ">")))
539                                     net)))
540              (while net
541                (if (string-match pattern (car net))
542                    (push (car net) lsdb-last-candidates))
543                (setq net (cdr net))))))
544        lsdb-hash-table))
545     (unless lsdb-last-candidates-pointer
546       (setq lsdb-last-candidates-pointer lsdb-last-candidates))
547     (when lsdb-last-candidates-pointer
548       (delete-region start (point))
549       (insert (pop lsdb-last-candidates-pointer)))))
550
551 ;;;_. Major Mode (`lsdb-mode') Implementation
552 (defvar lsdb-mode-map
553   (let ((keymap (make-sparse-keymap)))
554     (define-key keymap "a" 'lsdb-mode-add-entry)
555     (define-key keymap "d" 'lsdb-mode-delete-entry)
556     (define-key keymap "e" 'lsdb-mode-edit-entry)
557     (define-key keymap "s" 'lsdb-mode-save)
558     (define-key keymap "q" 'lsdb-mode-quit-window)
559     (define-key keymap "g" 'lsdb-mode-lookup)
560     (define-key keymap "p" 'lsdb-mode-previous-record)
561     (define-key keymap "n" 'lsdb-mode-next-record)
562     keymap)
563   "LSDB's keymap.")
564
565 (define-derived-mode lsdb-mode fundamental-mode "LSDB"
566   "Major mode for browsing LSDB records."
567   (setq buffer-read-only t)
568   (if (featurep 'xemacs)
569       ;; In XEmacs, setting `font-lock-defaults' only affects on
570       ;; `find-file-hooks'.
571       (font-lock-set-defaults)
572     (set (make-local-variable 'font-lock-defaults)
573          '(lsdb-font-lock-keywords t))))
574
575 (defun lsdb-narrow-to-record ()
576   (narrow-to-region
577    (previous-single-property-change (point) 'lsdb-record nil (point-min))
578    (next-single-property-change (point) 'lsdb-record nil (point-max)))
579   (goto-char (point-min)))
580
581 (defun lsdb-current-entry ()
582   (save-excursion
583     (beginning-of-line)
584     (if (looking-at "^[^\t]")
585         (let ((record (get-text-property (point) 'lsdb-record))
586               (completion-ignore-case t))
587           (completing-read
588            "Which entry to modify: "
589            (mapcar (lambda (entry)
590                      (list (capitalize (symbol-name (car entry)))))
591                    (cdr record))))
592       (end-of-line)
593       (re-search-backward "^\t\\([^\t][^:]+\\):")
594       (match-string 1))))
595
596 (defun lsdb-mode-add-entry (entry-name)
597   "Add an entry on the current line."
598   (interactive
599    (let ((completion-ignore-case t))
600      (list (completing-read "Entry name: " lsdb-known-entry-names))))
601   (beginning-of-line)
602   (unless (symbolp entry-name)
603     (setq entry-name (intern (downcase entry-name))))
604   (when (assq entry-name (cdr (get-text-property (point) 'lsdb-record)))
605     (error "The entry already exists"))
606   (let ((marker (point-marker)))
607     (lsdb-edit-form
608      nil "Editing the entry."
609      `(lambda (form)
610         (when form
611           (save-excursion
612             (set-buffer lsdb-buffer-name)
613             (goto-char ,marker)
614             (let* ((record (get-text-property (point) 'lsdb-record))
615                    (inhibit-read-only t)
616                    buffer-read-only)
617               (setcdr record (cons (cons ',entry-name form) (cdr record)))
618               (lsdb-puthash (car record) (cdr record)
619                             lsdb-hash-table)
620               (setq lsdb-hash-table-is-dirty t)
621               (beginning-of-line 2)
622               (add-text-properties
623                (point)
624                (progn
625                  (lsdb-insert-entry (cons ',entry-name form))
626                  (point))
627                (list 'lsdb-record record)))))))))
628
629 (defun lsdb-mode-delete-entry (&optional entry-name dont-update)
630   "Delete the entry on the current line."
631   (interactive)
632   (let ((record (get-text-property (point) 'lsdb-record))
633         entry)
634     (or entry-name
635         (setq entry-name (lsdb-current-entry)))
636     (setq entry (assq (intern (downcase entry-name)) (cdr record)))
637     (when (and entry
638                (not dont-update))
639       (setcdr record (delq entry (cdr record)))
640       (lsdb-puthash (car record) (cdr record)
641                     lsdb-hash-table)
642       (setq lsdb-hash-table-is-dirty t))
643     (save-restriction
644       (lsdb-narrow-to-record)
645       (let ((case-fold-search t)
646             (inhibit-read-only t)
647             buffer-read-only)
648         (goto-char (point-min))
649         (if (re-search-forward
650              (concat "^\t" (or entry-name
651                                (lsdb-current-entry))
652                      ":")
653              nil t)
654             (delete-region (match-beginning 0)
655                            (if (re-search-forward
656                                 "^\t[^\t][^:]+:" nil t)
657                                (match-beginning 0)
658                              (point-max))))))))
659
660 (defun lsdb-mode-edit-entry ()
661   "Edit the entry on the current line."
662   (interactive)
663   (let* ((record (get-text-property (point) 'lsdb-record))
664          (entry-name (intern (downcase (lsdb-current-entry))))
665          (entry (assq entry-name (cdr record)))
666          (marker (point-marker)))
667     (lsdb-edit-form
668      (cdr entry) "Editing the entry."
669      `(lambda (form)
670         (unless (equal form ',entry-name)
671           (save-excursion
672             (set-buffer lsdb-buffer-name)
673             (goto-char ,marker)
674             (let* ((record (get-text-property (point) 'lsdb-record))
675                    (entry (assq ',entry-name (cdr record)))
676                    (inhibit-read-only t)
677                    buffer-read-only)
678               (setcdr entry form)
679               (setq lsdb-hash-table-is-dirty t)
680               (lsdb-mode-delete-entry (symbol-name ',entry-name) t)
681               (beginning-of-line)
682               (add-text-properties
683                (point)
684                (progn
685                  (lsdb-insert-entry (cons ',entry-name form))
686                  (point))
687                (list 'lsdb-record record)))))))))
688
689 (defun lsdb-mode-save ()
690   "Save LSDB hash table into `lsdb-file'."
691   (interactive)
692   (if (not lsdb-hash-table-is-dirty)
693       (message "(No changes need to be saved)")
694     (when (or (interactive-p)
695               (y-or-n-p "Save the LSDB now?"))
696       (lsdb-save-file lsdb-file lsdb-hash-table)
697       (setq lsdb-hash-table-is-dirty nil)
698       (message "The LSDB was saved successfully."))))
699
700 (if (commandp 'quit-window)
701     (defalias 'lsdb-mode-quit-window 'quit-window)
702   (defun lsdb-mode-quit-window ()
703     "Quit the current buffer."
704     (interactive)
705     (if (one-window-p)
706         (bury-buffer)
707       (delete-window))))
708
709 (defvar lsdb-mode-lookup-history nil)
710
711 (defun lsdb-mode-lookup (regexp &optional entry-name)
712   "Display all entries in the LSDB matching the REGEXP."
713   (interactive
714    (let* ((completion-ignore-case t)
715           (entry-name
716            (if current-prefix-arg
717                (completing-read "Entry name: "
718                                 lsdb-known-entry-names))))
719      (list
720       (read-from-minibuffer
721        (if entry-name
722            (format "Search records `%s' regexp: " entry-name)
723          "Search records regexp: ")
724        nil nil nil 'lsdb-mode-lookup-history)
725       entry-name)))
726   (let (records)
727     (lsdb-maphash
728      (if entry-name
729          (lambda (key value)
730            (let ((entry (cdr (assq (intern (downcase entry-name))
731                                    value)))
732                  found)
733              (unless (listp entry)
734                (setq entry (list entry)))
735              (while (and (not found) entry)
736                (if (string-match regexp (pop entry))
737                    (setq found t)))
738              (if found
739                  (push (cons key value) records))))
740        (lambda (key value)
741          (if (string-match regexp key)
742              (push (cons key value) records))))
743      lsdb-hash-table)
744     (lsdb-display-records records)))
745
746 ;;;###autoload
747 (defalias 'lsdb 'lsdb-mode-lookup)
748
749 (defun lsdb-mode-next-record (&optional arg)
750   "Go to the next record."
751   (interactive "p")
752   (unless arg                           ;called noninteractively?
753     (setq arg 1))
754   (if (< arg 0)
755       (lsdb-mode-previous-record (- arg))
756     (while (> arg 0)
757       (goto-char (next-single-property-change
758                   (point) 'lsdb-record nil (point-max)))
759       (setq arg (1- arg)))))
760
761 (defun lsdb-mode-previous-record (&optional arg)
762   "Go to the previous record."
763   (interactive "p")
764   (unless arg                           ;called noninteractively?
765     (setq arg 1))
766   (if (< arg 0)
767       (lsdb-mode-next-record (- arg))
768     (while (> arg 0)
769       (goto-char (previous-single-property-change
770                   (point) 'lsdb-record nil (point-min)))
771       (setq arg (1- arg)))))
772
773 ;;;_ : Edit Forms -- stolen (and renamed) from gnus-eform.el
774 (defvar lsdb-edit-form-buffer "*LSDB edit form*")
775 (defvar lsdb-edit-form-done-function nil)
776 (defvar lsdb-previous-window-configuration nil)
777
778 (defvar lsdb-edit-form-mode-map
779   (let ((keymap (make-sparse-keymap)))
780     (set-keymap-parent keymap emacs-lisp-mode-map)
781     (define-key keymap "\C-c\C-c" 'lsdb-edit-form-done)
782     (define-key keymap "\C-c\C-k" 'lsdb-edit-form-exit)
783     keymap)
784   "Edit form's keymap.")
785
786 (defun lsdb-edit-form-mode ()
787   "Major mode for editing forms.
788 It is a slightly enhanced emacs-lisp-mode.
789
790 \\{lsdb-edit-form-mode-map}"
791   (interactive)
792   (kill-all-local-variables)
793   (setq major-mode 'lsdb-edit-form-mode
794         mode-name "LSDB Edit Form")
795   (use-local-map lsdb-edit-form-mode-map)
796   (make-local-variable 'lsdb-edit-form-done-function)
797   (make-local-variable 'lsdb-previous-window-configuration)
798   (run-hooks 'lsdb-edit-form-mode-hook))
799
800 (defun lsdb-edit-form (form documentation exit-func)
801   "Edit FORM in a new buffer.
802 Call EXIT-FUNC on exit.  Display DOCUMENTATION in the beginning
803 of the buffer."
804   (let ((window-configuration
805          (current-window-configuration)))
806     (switch-to-buffer (get-buffer-create lsdb-edit-form-buffer))
807     (lsdb-edit-form-mode)
808     (setq lsdb-previous-window-configuration window-configuration
809           lsdb-edit-form-done-function exit-func)
810     (erase-buffer)
811     (insert documentation)
812     (unless (bolp)
813       (insert "\n"))
814     (goto-char (point-min))
815     (while (not (eobp))
816       (insert ";;; ")
817       (forward-line 1))
818     (insert ";; Type `C-c C-c' after you've finished editing.\n")
819     (insert "\n")
820     (let ((p (point)))
821       (pp form (current-buffer))
822       (insert "\n")
823       (goto-char p))))
824
825 (defun lsdb-edit-form-done ()
826   "Update changes and kill the current buffer."
827   (interactive)
828   (goto-char (point-min))
829   (let ((form (condition-case nil
830                   (read (current-buffer))
831                 (end-of-file nil)))
832         (func lsdb-edit-form-done-function))
833     (lsdb-edit-form-exit)
834     (funcall func form)))
835
836 (defun lsdb-edit-form-exit ()
837   "Kill the current buffer."
838   (interactive)
839   (let ((window-configuration lsdb-previous-window-configuration))
840     (kill-buffer (current-buffer))
841     (set-window-configuration window-configuration)))
842
843 ;;;_. Interface to Semi-gnus
844 ;;;###autoload
845 (defun lsdb-gnus-insinuate ()
846   "Call this function to hook LSDB into Semi-gnus."
847   (add-hook 'gnus-article-prepare-hook 'lsdb-gnus-update-record)
848   (add-hook 'gnus-save-newsrc-hook 'lsdb-mode-save))
849
850 (defvar gnus-current-headers)
851 (defun lsdb-gnus-update-record ()
852   (let ((entity gnus-current-headers)
853         records)
854     (with-temp-buffer
855       (set-buffer-multibyte nil)
856       (buffer-disable-undo)
857       (mime-insert-entity entity)
858       (setq records (lsdb-update-records))
859       (when records
860         (lsdb-display-record (car records))))))
861
862 ;;;_. Interface to Wanderlust
863 ;;;###autoload
864 (defun lsdb-wl-insinuate ()
865   "Call this function to hook LSDB into Wanderlust."
866   (add-hook 'wl-message-redisplay-hook 'lsdb-wl-update-record)
867   (add-hook 'wl-summary-exit-hook 'lsdb-wl-hide-buffer)
868   (add-hook 'wl-exit-hook 'lsdb-mode-save))
869
870 (defun lsdb-wl-update-record ()
871   (save-excursion
872     (set-buffer (wl-message-get-original-buffer))
873     (let ((records (lsdb-update-records)))
874       (when records
875         (lsdb-display-record (car records))))))
876
877 (defun lsdb-wl-hide-buffer ()
878   (let ((window (get-buffer-window lsdb-buffer-name)))
879     (if window
880         (delete-window window))))
881
882 ;;;_. X-Face Rendering
883 (defun lsdb-expose-x-face ()
884   (let* ((record (get-text-property (point-min) 'lsdb-record))
885          (x-face (cdr (assq 'x-face (cdr record))))
886          (limit "\r"))
887     (when (and lsdb-insert-x-face-function
888                x-face)
889       (goto-char (point-min))
890       (end-of-line)
891       (if (fboundp 'propertize)
892           (insert (propertize limit 'invisible t) " ")
893         (put-text-property 0 1 'invisible t limit)
894         (insert limit " "))
895       (while x-face
896         (funcall lsdb-insert-x-face-function (pop x-face))))))
897
898 ;; stolen (and renamed) from gnus-summary-x-face.el written by Akihiro Arisawa.
899 (defvar lsdb-x-face-scale-factor 0.5
900   "A number of scale factor used to scale down X-face image.
901 See also `x-face-scale-factor'.")
902
903 (defun lsdb-insert-x-face-with-x-face-e21 (x-face)
904   (require 'x-face-e21)
905   (insert-image (x-face-create-image
906                  x-face :scale-factor lsdb-x-face-scale-factor)))
907
908 (defun lsdb-insert-x-face-with-xemacs-glyph (x-face)
909   (let ((glyph
910          (make-glyph
911           (vector 'xface :data (concat "X-Face: " x-face)))))
912     (if glyph
913         (set-extent-end-glyph
914          (make-extent (point) (point))
915          glyph))))
916
917 (require 'product)
918 (provide 'lsdb)
919
920 (product-provide 'lsdb
921   (product-define "LSDB" nil '(0 1)))
922
923 ;;;_* Local emacs vars.
924 ;;; The following `outline-layout' local variable setting:
925 ;;;  - closes all topics from the first topic to just before the third-to-last,
926 ;;;  - shows the children of the third to last (config vars)
927 ;;;  - and the second to last (code section),
928 ;;;  - and closes the last topic (this local-variables section).
929 ;;;Local variables:
930 ;;;outline-layout: (0 : -1 -1 0)
931 ;;;End:
932
933 ;;; lsdb.el ends here