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