* lsdb.el (lsdb-mode-map): Bind [backspace]
[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     (define-key keymap " " 'scroll-up)
564     (define-key keymap [delete] 'scroll-down)
565     (define-key keymap "\177" 'scroll-down)
566     (define-key keymap [backspace] 'scroll-down)
567     keymap)
568   "LSDB's keymap.")
569
570 (define-derived-mode lsdb-mode fundamental-mode "LSDB"
571   "Major mode for browsing LSDB records."
572   (setq buffer-read-only t)
573   (if (featurep 'xemacs)
574       ;; In XEmacs, setting `font-lock-defaults' only affects on
575       ;; `find-file-hooks'.
576       (font-lock-set-defaults)
577     (set (make-local-variable 'font-lock-defaults)
578          '(lsdb-font-lock-keywords t))))
579
580 (defun lsdb-narrow-to-record ()
581   (narrow-to-region
582    (previous-single-property-change (point) 'lsdb-record nil (point-min))
583    (next-single-property-change (point) 'lsdb-record nil (point-max)))
584   (goto-char (point-min)))
585
586 (defun lsdb-current-record ()
587   (let ((record (get-text-property (point) 'lsdb-record)))
588     (unless record
589       (error "There is nothing to follow here"))
590     record))
591
592 (defun lsdb-current-entry ()
593   (save-excursion
594     (beginning-of-line)
595     (if (looking-at "^[^\t]")
596         (let ((record (lsdb-current-record))
597               (completion-ignore-case t))
598           (completing-read
599            "Which entry to modify: "
600            (mapcar (lambda (entry)
601                      (list (capitalize (symbol-name (car entry)))))
602                    (cdr record))))
603       (end-of-line)
604       (re-search-backward "^\t\\([^\t][^:]+\\):")
605       (match-string 1))))
606
607 (defun lsdb-mode-add-entry (entry-name)
608   "Add an entry on the current line."
609   (interactive
610    (let ((completion-ignore-case t))
611      (list (completing-read "Entry name: " lsdb-known-entry-names))))
612   (beginning-of-line)
613   (unless (symbolp entry-name)
614     (setq entry-name (intern (downcase entry-name))))
615   (when (assq entry-name (cdr (lsdb-current-record)))
616     (error "The entry already exists"))
617   (let ((marker (point-marker)))
618     (lsdb-edit-form
619      nil "Editing the entry."
620      `(lambda (form)
621         (when form
622           (save-excursion
623             (set-buffer lsdb-buffer-name)
624             (goto-char ,marker)
625             (let ((record (lsdb-current-record))
626                   (inhibit-read-only t)
627                   buffer-read-only)
628               (setcdr record (cons (cons ',entry-name form) (cdr record)))
629               (lsdb-puthash (car record) (cdr record)
630                             lsdb-hash-table)
631               (setq lsdb-hash-table-is-dirty t)
632               (beginning-of-line 2)
633               (add-text-properties
634                (point)
635                (progn
636                  (lsdb-insert-entry (cons ',entry-name form))
637                  (point))
638                (list 'lsdb-record record)))))))))
639
640 (defun lsdb-mode-delete-entry (&optional entry-name dont-update)
641   "Delete the entry on the current line."
642   (interactive)
643   (let ((record (lsdb-current-record))
644         entry)
645     (or entry-name
646         (setq entry-name (lsdb-current-entry)))
647     (setq entry (assq (intern (downcase entry-name)) (cdr record)))
648     (when (and entry
649                (not dont-update))
650       (setcdr record (delq entry (cdr record)))
651       (lsdb-puthash (car record) (cdr record)
652                     lsdb-hash-table)
653       (setq lsdb-hash-table-is-dirty t))
654     (save-restriction
655       (lsdb-narrow-to-record)
656       (let ((case-fold-search t)
657             (inhibit-read-only t)
658             buffer-read-only)
659         (goto-char (point-min))
660         (if (re-search-forward
661              (concat "^\t" (or entry-name
662                                (lsdb-current-entry))
663                      ":")
664              nil t)
665             (delete-region (match-beginning 0)
666                            (if (re-search-forward
667                                 "^\t[^\t][^:]+:" nil t)
668                                (match-beginning 0)
669                              (point-max))))))))
670
671 (defun lsdb-mode-edit-entry ()
672   "Edit the entry on the current line."
673   (interactive)
674   (let* ((record (lsdb-current-record))
675          (entry-name (intern (downcase (lsdb-current-entry))))
676          (entry (assq entry-name (cdr record)))
677          (marker (point-marker)))
678     (lsdb-edit-form
679      (cdr entry) "Editing the entry."
680      `(lambda (form)
681         (unless (equal form ',entry-name)
682           (save-excursion
683             (set-buffer lsdb-buffer-name)
684             (goto-char ,marker)
685             (let* ((record (lsdb-current-record))
686                    (entry (assq ',entry-name (cdr record)))
687                    (inhibit-read-only t)
688                    buffer-read-only)
689               (setcdr entry form)
690               (setq lsdb-hash-table-is-dirty t)
691               (lsdb-mode-delete-entry (symbol-name ',entry-name) t)
692               (beginning-of-line)
693               (add-text-properties
694                (point)
695                (progn
696                  (lsdb-insert-entry (cons ',entry-name form))
697                  (point))
698                (list 'lsdb-record record)))))))))
699
700 (defun lsdb-mode-save ()
701   "Save LSDB hash table into `lsdb-file'."
702   (interactive)
703   (if (not lsdb-hash-table-is-dirty)
704       (message "(No changes need to be saved)")
705     (when (or (interactive-p)
706               (y-or-n-p "Save the LSDB now?"))
707       (lsdb-save-file lsdb-file lsdb-hash-table)
708       (setq lsdb-hash-table-is-dirty nil)
709       (message "The LSDB was saved successfully."))))
710
711 (if (commandp 'quit-window)
712     (defalias 'lsdb-mode-quit-window 'quit-window)
713   (defun lsdb-mode-quit-window ()
714     "Quit the current buffer."
715     (interactive)
716     (if (one-window-p)
717         (bury-buffer)
718       (delete-window))))
719
720 (defvar lsdb-mode-lookup-history nil)
721
722 (defun lsdb-mode-lookup (regexp &optional entry-name)
723   "Display all entries in the LSDB matching the REGEXP."
724   (interactive
725    (let* ((completion-ignore-case t)
726           (entry-name
727            (if current-prefix-arg
728                (completing-read "Entry name: "
729                                 lsdb-known-entry-names))))
730      (list
731       (read-from-minibuffer
732        (if entry-name
733            (format "Search records `%s' regexp: " entry-name)
734          "Search records regexp: ")
735        nil nil nil 'lsdb-mode-lookup-history)
736       entry-name)))
737   (let (records)
738     (lsdb-maybe-load-file)
739     (lsdb-maphash
740      (if entry-name
741          (lambda (key value)
742            (let ((entry (cdr (assq (intern (downcase entry-name))
743                                    value)))
744                  found)
745              (unless (listp entry)
746                (setq entry (list entry)))
747              (while (and (not found) entry)
748                (if (string-match regexp (pop entry))
749                    (setq found t)))
750              (if found
751                  (push (cons key value) records))))
752        (lambda (key value)
753          (if (string-match regexp key)
754              (push (cons key value) records))))
755      lsdb-hash-table)
756     (lsdb-display-records records)))
757
758 ;;;###autoload
759 (defalias 'lsdb 'lsdb-mode-lookup)
760
761 (defun lsdb-mode-next-record (&optional arg)
762   "Go to the next record."
763   (interactive "p")
764   (unless arg                           ;called noninteractively?
765     (setq arg 1))
766   (if (< arg 0)
767       (lsdb-mode-previous-record (- arg))
768     (while (> arg 0)
769       (goto-char (next-single-property-change
770                   (point) 'lsdb-record nil (point-max)))
771       (setq arg (1- arg)))))
772
773 (defun lsdb-mode-previous-record (&optional arg)
774   "Go to the previous record."
775   (interactive "p")
776   (unless arg                           ;called noninteractively?
777     (setq arg 1))
778   (if (< arg 0)
779       (lsdb-mode-next-record (- arg))
780     (while (> arg 0)
781       (goto-char (previous-single-property-change
782                   (point) 'lsdb-record nil (point-min)))
783       (setq arg (1- arg)))))
784
785 ;;;_ : Edit Forms -- stolen (and renamed) from gnus-eform.el
786 (defvar lsdb-edit-form-buffer "*LSDB edit form*")
787 (defvar lsdb-edit-form-done-function nil)
788 (defvar lsdb-previous-window-configuration nil)
789
790 (defvar lsdb-edit-form-mode-map
791   (let ((keymap (make-sparse-keymap)))
792     (set-keymap-parent keymap emacs-lisp-mode-map)
793     (define-key keymap "\C-c\C-c" 'lsdb-edit-form-done)
794     (define-key keymap "\C-c\C-k" 'lsdb-edit-form-exit)
795     keymap)
796   "Edit form's keymap.")
797
798 (defun lsdb-edit-form-mode ()
799   "Major mode for editing forms.
800 It is a slightly enhanced emacs-lisp-mode.
801
802 \\{lsdb-edit-form-mode-map}"
803   (interactive)
804   (kill-all-local-variables)
805   (setq major-mode 'lsdb-edit-form-mode
806         mode-name "LSDB Edit Form")
807   (use-local-map lsdb-edit-form-mode-map)
808   (make-local-variable 'lsdb-edit-form-done-function)
809   (make-local-variable 'lsdb-previous-window-configuration)
810   (run-hooks 'lsdb-edit-form-mode-hook))
811
812 (defun lsdb-edit-form (form documentation exit-func)
813   "Edit FORM in a new buffer.
814 Call EXIT-FUNC on exit.  Display DOCUMENTATION in the beginning
815 of the buffer."
816   (let ((window-configuration
817          (current-window-configuration)))
818     (switch-to-buffer (get-buffer-create lsdb-edit-form-buffer))
819     (lsdb-edit-form-mode)
820     (setq lsdb-previous-window-configuration window-configuration
821           lsdb-edit-form-done-function exit-func)
822     (erase-buffer)
823     (insert documentation)
824     (unless (bolp)
825       (insert "\n"))
826     (goto-char (point-min))
827     (while (not (eobp))
828       (insert ";;; ")
829       (forward-line 1))
830     (insert ";; Type `C-c C-c' after you've finished editing.\n")
831     (insert "\n")
832     (let ((p (point)))
833       (pp form (current-buffer))
834       (insert "\n")
835       (goto-char p))))
836
837 (defun lsdb-edit-form-done ()
838   "Update changes and kill the current buffer."
839   (interactive)
840   (goto-char (point-min))
841   (let ((form (condition-case nil
842                   (read (current-buffer))
843                 (end-of-file nil)))
844         (func lsdb-edit-form-done-function))
845     (lsdb-edit-form-exit)
846     (funcall func form)))
847
848 (defun lsdb-edit-form-exit ()
849   "Kill the current buffer."
850   (interactive)
851   (let ((window-configuration lsdb-previous-window-configuration))
852     (kill-buffer (current-buffer))
853     (set-window-configuration window-configuration)))
854
855 ;;;_. Interface to Semi-gnus
856 ;;;###autoload
857 (defun lsdb-gnus-insinuate ()
858   "Call this function to hook LSDB into Semi-gnus."
859   (add-hook 'gnus-article-prepare-hook 'lsdb-gnus-update-record)
860   (add-hook 'gnus-save-newsrc-hook 'lsdb-mode-save))
861
862 (defvar gnus-current-headers)
863 (defun lsdb-gnus-update-record ()
864   (let ((entity gnus-current-headers)
865         records)
866     (with-temp-buffer
867       (set-buffer-multibyte nil)
868       (buffer-disable-undo)
869       (mime-insert-entity entity)
870       (setq records (lsdb-update-records))
871       (when records
872         (lsdb-display-record (car records))))))
873
874 ;;;_. Interface to Wanderlust
875 ;;;###autoload
876 (defun lsdb-wl-insinuate ()
877   "Call this function to hook LSDB into Wanderlust."
878   (add-hook 'wl-message-redisplay-hook 'lsdb-wl-update-record)
879   (add-hook 'wl-summary-exit-hook 'lsdb-wl-hide-buffer)
880   (add-hook 'wl-exit-hook 'lsdb-mode-save))
881
882 (defun lsdb-wl-update-record ()
883   (save-excursion
884     (set-buffer (wl-message-get-original-buffer))
885     (let ((records (lsdb-update-records)))
886       (when records
887         (lsdb-display-record (car records))))))
888
889 (defun lsdb-wl-hide-buffer ()
890   (let ((window (get-buffer-window lsdb-buffer-name)))
891     (if window
892         (delete-window window))))
893
894 ;;;_. X-Face Rendering
895 (defun lsdb-expose-x-face ()
896   (let* ((record (get-text-property (point-min) 'lsdb-record))
897          (x-face (cdr (assq 'x-face (cdr record))))
898          (limit "\r"))
899     (when (and lsdb-insert-x-face-function
900                x-face)
901       (goto-char (point-min))
902       (end-of-line)
903       (if (fboundp 'propertize)
904           (insert (propertize limit 'invisible t) " ")
905         (put-text-property 0 1 'invisible t limit)
906         (insert limit " "))
907       (while x-face
908         (funcall lsdb-insert-x-face-function (pop x-face))))))
909
910 ;; stolen (and renamed) from gnus-summary-x-face.el written by Akihiro Arisawa.
911 (defvar lsdb-x-face-scale-factor 0.5
912   "A number of scale factor used to scale down X-face image.
913 See also `x-face-scale-factor'.")
914
915 (defun lsdb-insert-x-face-with-x-face-e21 (x-face)
916   (require 'x-face-e21)
917   (insert-image (x-face-create-image
918                  x-face :scale-factor lsdb-x-face-scale-factor)))
919
920 (defun lsdb-insert-x-face-with-xemacs-glyph (x-face)
921   (let ((glyph
922          (make-glyph
923           (vector 'xface :data (concat "X-Face: " x-face)))))
924     (if glyph
925         (set-extent-end-glyph
926          (make-extent (point) (point))
927          glyph))))
928
929 (require 'product)
930 (provide 'lsdb)
931
932 (product-provide 'lsdb
933   (product-define "LSDB" nil '(0 1)))
934
935 ;;;_* Local emacs vars.
936 ;;; The following `outline-layout' local variable setting:
937 ;;;  - closes all topics from the first topic to just before the third-to-last,
938 ;;;  - shows the children of the third to last (config vars)
939 ;;;  - and the second to last (code section),
940 ;;;  - and closes the last topic (this local-variables section).
941 ;;;Local variables:
942 ;;;outline-layout: (0 : -1 -1 0)
943 ;;;End:
944
945 ;;; lsdb.el ends here