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