1 ;;; ph.el --- Client for the CCSO directory system (aka PH/QI)
3 ;; Copyright (C) 1997 Free Software Foundation, Inc.
5 ;; Author: Oscar Figueiredo <Oscar.Figueiredo@di.epfl.ch>
6 ;; Maintainer: Oscar Figueiredo <Oscar.Figueiredo@di.epfl.ch>
11 ;; This file is part of GNU Emacs
13 ;; GNU Emacs is free software; you can redistribute it and/or modify it
14 ;; under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 ;; General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to
25 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
29 ;; This package provides functions to query CCSO PH/QI nameservers
30 ;; through an interactive form or replace inline query strings in
31 ;; buffers with appropriately formatted query results (especially
32 ;; used to expand email addresses in message buffers). It also
33 ;; interfaces with the BBDB package to let you register entries of
34 ;; the CCSO PH/QI directory into your own database. The CCSO PH/QI
35 ;; white pages system was developped at UIUC and is in use in more
36 ;; than 300 sites in the world. The distribution can be found at
37 ;; ftp://uiarchive.cso.uiuc.edu/pub/packages/ph Traditionally the
38 ;; server is called QI while the client is called PH.
41 ;; This package uses the custom and widget libraries. If they are not already
42 ;; installed on your system get them from http://www.dina.kvl.dk/~abraham/custom/
43 ;; Then uncomment and add the following to your .emacs file:
45 ;; (eval-after-load "message"
46 ;; '(define-key message-mode-map [(control ?c) (tab)] 'ph-expand-inline))
47 ;; (eval-after-load "mail"
48 ;; '(define-key mail-mode-map [(control ?c) (tab)] 'ph-expand-inline))
49 ;; See the info file for details
51 ;; This package runs under XEmacs 19.15 or 20 and under Emacs 19.34 and above
54 ;; - Provided you did the installation as proposed in the above section,
55 ;; inline expansion will be available when you compose an email
56 ;; message. Type the name of somebody recorded in your PH/QI server and hit
57 ;; C-c TAB, this will overwrite the name with the corresponding email
59 ;; - M-x ph-customize to customize inline expansion and other features to
61 ;; - Look for the Ph submenu in the Tools menu for more.
62 ;; See the info file for details.
68 (if (not (fboundp 'make-overlay))
71 (autoload 'custom-menu-create "cus-edit")
73 ;;{{{ Package customization variables
76 "CCSO (PH/QI) directory system client"
80 (defcustom ph-server nil
81 "*The name or IP address of the CCSO (PH/QI) server.
82 A port number may be specified by appending a colon and a
83 number to the name of the server."
84 :type '(string :tag "Server")
87 (defcustom ph-strict-return-matches t
88 "*If non-nil, entries that do not contain all the requested return fields are ignored."
92 (defcustom ph-default-return-fields nil
93 "*A list of the default fields to extract from CCSO entries.
94 If it contains `all' then all available fields are returned.
95 nil means return the default fields as configured in the server."
96 :type '(repeat (symbol :tag "Field name"))
99 (defcustom ph-multiple-match-handling-method 'select
100 "*What to do when multiple entries match a query for an inline expansion.
102 `first' (equivalent to nil) which means consider the first match.
103 `select' pop-up a selection buffer
104 `all' use all matches
105 `abort' the operation is aborted, an error is signaled"
106 :type '(choice :menu-tag "Method"
107 (const :menu-tag "First" first)
108 (const :menu-tag "Select" select)
109 (const :menu-tag "All" all)
110 (const :menu-tag "Abort" abort)
111 (const :menu-tag "None" nil))
114 (defcustom ph-duplicate-fields-handling-method '((email . duplicate))
115 "*A method to handle entries containing duplicate fields.
116 This is either an alist (FIELD . METHOD) or a symbol METHOD.
117 The alist form of the variable associates a method to an individual field,
118 the second form specifies a method applicable to all fields.
119 Available methods are:
120 `list' or nil lets the value of the field be a list of values
121 `first' keeps the first value and discards the others,
122 `concat' concatenates the values into a single multiline string,
123 `duplicate' duplicates the entire entry into as many instances as
125 :type '(choice (const :menu-tag "List" list)
126 (const :menu-tag "First" first)
127 (const :menu-tag "Concat" concat)
128 (const :menu-tag "Duplicate" duplicate)
129 (repeat :menu-tag "Per Field Specification"
130 :tag "Per Field Specification"
131 (cons :tag "Field/Method"
133 (symbol :tag "Field name")
134 (choice :tag "Method"
136 (const :menu-tag "List" list)
137 (const :menu-tag "First" first)
138 (const :menu-tag "Concat" concat)
139 (const :menu-tag "Duplicate" duplicate)))))
143 (defcustom ph-inline-query-format-list nil
144 "*Format of an inline expansion query.
145 If the inline query string consists of several words, this list specifies
146 how these individual words are associated to CCSO database field names.
147 If nil all the words will be mapped onto the default CCSO database key."
148 :type '(repeat (symbol :tag "Field name"))
151 (defcustom ph-expanding-overwrites-query t
152 "*If non nil, expanding a query overwrites the query string"
156 (defcustom ph-inline-expansion-format '("%s" email)
157 "*A list specifying the format of the expansion of inline queries.
158 This variable controls what ph-expand-inline actually inserts in the buffer.
159 First element is a string passed to format. Remaining elements are symbols
160 indicating CCSO database field names, corresponding field values are passed
161 as additional arguments to format."
162 :type '(list (string :tag "Format String")
168 (defcustom ph-form-fields '(name email phone)
169 "*A list of fields presented in the query form."
170 :tag "Default Fields in Query Forms"
171 :type '(repeat (symbol :tag "Field name"))
174 (defcustom ph-fieldname-formstring-alist '((url . "URL")
175 (callsign . "HAM Call Sign")
178 (firstname . "First Name"))
179 "*A mapping of CCSO database field names onto prompt strings used in query/response forms.
180 Prompt strings for fields that are not in this are derived by splitting the field name
181 at `_' signs and capitalizing the individual words."
182 :tag "Mapping of Field Names onto Prompt Strings"
183 :type '(repeat (cons :tag "Field"
185 (string :tag "Prompt string")))
188 (defcustom ph-bbdb-conversion-alist
191 (address . (ph-bbdbify-address address "Address"))
192 (phone . ((ph-bbdbify-phone phone "Phone")
193 (ph-bbdbify-phone office_phone "Office Phone"))))
194 "*A mapping from BBDB to PH/QI fields.
195 This is a list of cons cells (BBDB-FIELD . SPEC-OR-LIST) where
196 BBDB-FIELD is the name of a field that must be defined in your BBDB
197 environment (standard field names are `name', `company', `net', `phone',
198 `address' and `notes'). SPEC-OR-LIST is either a single SPEC or a list
199 of SPECs. Lists of specs are valid only for the `phone' and `address'
200 BBDB fields. SPECs are sexps which are evaluated:
201 a string evaluates to itself
202 a symbol evaluates to the symbol value. Symbols naming PH/QI fields
203 present in the record evaluate to the value of the field in the record
204 a form is evaluated as a function. The argument list may contain PH/QI
205 field names which eval to the corresponding values in the
206 record. The form evaluation should return something appropriate for
207 the particular BBDB-FIELD (see bbdb-create-internal).
208 ph-bbdbify-phone and ph-bbdbify-address are provided as convenience
209 functions to parse phones and addresses."
210 :tag "BBDB to CCSO Field Name Mapping"
211 :type '(repeat (cons :tag "Field Name"
212 (symbol :tag "BBDB Field")
213 (sexp :tag "Conversion Spec")))
216 (defcustom ph-options-file "~/.ph-options"
217 "*A file where the `servers' hotlist is stored."
218 :type '(file :Tag "File Name:"))
220 (defcustom ph-mode-hook nil
221 "*Normal hook run on entry to ph-mode."
222 :type '(repeat (sexp :tag "Hook")))
227 ;;{{{ Internal cooking
230 (defconst ph-xemacs-p (string-match "XEmacs" emacs-version))
231 (defconst ph-emacs-p (not ph-xemacs-p))
232 (defconst ph-xemacs-mule-p (and ph-xemacs-p
234 (defconst ph-emacs-mule-p (and ph-emacs-p
237 (defvar ph-server-hotlist nil)
239 (defconst ph-default-server-port 105
240 "Default TCP port for CCSO directory services")
242 (defvar ph-form-widget-list nil)
243 (defvar ph-process-buffer nil)
244 (defvar ph-read-point)
246 ;;; Load the options file
247 (if (and (and (locate-library ph-options-file)
248 (message "")) ; Remove modeline message
249 (not (featurep 'ph-options-file)))
250 (load ph-options-file))
259 "Major mode used in buffers displaying the results of PH queries.
260 There is no sense in calling this command from a buffer other than
261 one containing the results of a PH query.
266 (kill-all-local-variables)
267 (setq major-mode 'ph-mode)
268 (setq mode-name "PH")
269 (use-local-map ph-mode-map)
270 (setq mode-popup-menu (ph-menu))
271 (run-hooks 'ph-mode-hook)
274 (defun ph-display-records (records &optional raw-field-names)
275 "Display the record list RECORDS in a formatted buffer.
276 If RAW-FIELD-NAMES is non-nil, field names will be formatted to look
277 more attractive byi capitalizing and forming strings."
278 (let ((buffer (get-buffer-create "*PH Query Results*"))
284 (switch-to-buffer buffer)
285 (setq buffer-read-only t)
286 (setq inhibit-read-only t)
288 (insert "PH Query Result\n")
289 (insert "===============\n\n\n")
291 (insert "No match found.\n"
292 (if ph-strict-return-matches
293 "Try setting ph-strict-return-matches to nil or change ph-default-return-fields."
295 ;; Replace field names with prompt strings, compute prompt max width
303 (setq field-name (if raw-field-names
304 (symbol-name (car field))
305 (or (and (assq (car field) ph-fieldname-formstring-alist)
306 (cdr (assq (car field) ph-fieldname-formstring-alist)))
307 (capitalize (mapconcat '(lambda (char)
310 (char-to-string char)))
311 (symbol-name (car field))
313 (if (> (length field-name) width)
314 (setq width (length field-name)))
315 (cons field-name (cdr field))))
321 ;; Actually insert the field/value pairs
324 (setq field-beg (point))
325 (insert (format (concat "%" width "s: ") (car field)))
326 (put-text-property field-beg (point) 'face 'bold)
329 (indent-to (+ 2 width))
331 (if (stringp (cdr field))
332 (split-string (cdr field) "\n")
335 ;; Store the record internal format in some convenient place
336 (overlay-put (make-overlay beg (point))
339 (setq records (cdr records))
343 (widget-create 'push-button
344 :notify (lambda (&rest ignore)
348 (widget-create 'push-button
349 :notify (lambda (&rest ignore)
357 (defun ph-process-form ()
358 "Process the form in current buffer and display the results"
361 (if (not (and (boundp 'ph-form-widget-list)
362 ph-form-widget-list))
363 (error "Not in a PH query form buffer")
366 (setq value (widget-value (cdr wid-field)))
367 (if (not (string= value ""))
368 (setq query-alist (cons (cons (car wid-field) value)
371 (kill-buffer (current-buffer))
372 (ph-display-records (ph-query-internal query-alist))
376 (defun ph-query-internal (query &optional return-fields)
377 "Query the PH/QI server with QUERY.
378 QUERY can be a string NAME or a list made of strings NAME
379 and/or cons cells (KEY . VALUE) where KEYs should be valid
380 CCSO database keys. NAME is equivalent to (DEFAULT . NAME) where
381 DEFAULT is the default key of the database)
382 RETURN-FIELDS is a list of database fields to return defaulting to
383 ph-default-return-fields."
385 (if (null return-fields)
386 (setq return-fields ph-default-return-fields))
391 (mapconcat (function (lambda (elt)
392 (if (stringp elt) elt)
393 (format "%s=%s" (car elt) (cdr elt))))
397 (concat " return " (mapconcat 'symbol-name return-fields " ")))))
398 (and (> (length request) 6)
399 (ph-do-request request)
400 (ph-parse-query-result return-fields))))
402 (defun ph-parse-query-result (&optional fields)
403 "Return a list of alists of key/values from the record in ph-process-buffer.
404 Fields not in FIELDS are discarded."
407 current-key key value
410 (message "Parsing results...")
411 (set-buffer ph-process-buffer)
412 (goto-char (point-min))
413 (while (re-search-forward "^\\(-[0-9]+\\):\\([0-9]+\\):" nil t)
415 (setq line-regexp (concat "^\\(-[0-9]+\\):" (match-string 2) ":[ \t]*\\([-a-zA-Z_]*\\)?:[ \t]*\\(.*\\)$"))
420 (while (re-search-forward line-regexp nil t)
422 (if (string= "-508" (match-string 1))
423 ;; A field is missing in this entry. Skip it or skip the
424 ;; whole record (see ph-strict-return-matches)
425 (if (not ph-strict-return-matches)
427 (while (re-search-forward line-regexp nil t))
430 (setq key (and (not (string= (match-string 2) ""))
431 (intern (match-string 2)))
432 value (match-string 3))
434 (eq key current-key))
436 (setq current-key key))
437 (if (or (null fields)
439 (memq current-key fields))
441 (setq record (cons (cons key value) record)) ; New key
442 (setcdr (car record) (if (listp (ph-cdar record))
443 (append (ph-cdar record) (list value))
444 (list (ph-cdar record) value))))))))
448 (setq record (nreverse record)))
449 (setq record (if (not (eq 'list ph-duplicate-fields-handling-method))
450 (ph-filter-duplicate-fields record)
452 (setq records (append record records))))
458 (defun ph-filter-duplicate-fields (record)
459 "Filter RECORD according to ph-duplicate-fields-handling-method."
465 ;; Search for multiple records
467 (not (listp (ph-cdar rec))))
468 (setq rec (cdr rec)))
470 (if (null (ph-cdar rec))
471 (list record) ; No duplicate fields in this record
474 (if (listp (cdr field))
475 (setq duplicates (cons field duplicates))
476 (setq unique (cons field unique)))))
478 (setq result (list unique))
481 (let ((method (if (consp ph-duplicate-fields-handling-method)
482 (cdr (assq (car field) ph-duplicate-fields-handling-method))
483 ph-duplicate-fields-handling-method)))
485 ((or (null method) (eq 'list method))
487 (ph-add-field-to-records field result)))
490 (ph-add-field-to-records (cons (car field) (ph-cadr field)) result)))
493 (ph-add-field-to-records (cons (car field)
498 ((eq 'duplicate method)
500 (ph-distribute-field-on-records field result)))))))
504 (defun ph-add-field-to-records (field records)
505 "Add FIELD to each individual record in RECORDS and return the resulting list."
511 (defun ph-distribute-field-on-records (field records)
512 "Duplicate each individual record in RECORDS according to value of FIELD.
513 Each copy is added a new field containing one of the values of FIELD."
515 (values (cdr field)))
516 ;; Uniquify values first
518 (setcdr values (delete (car values) (cdr values)))
519 (setq values (cdr values)))
522 (let ((result-list (copy-sequence records)))
523 (setq result-list (ph-add-field-to-records (cons (car field) value)
525 (setq result (append result-list result))
531 (defun ph-do-request (request)
532 "Send REQUEST to the server.
533 Wait for response and return the buffer containing it."
538 (message "Contacting server...")
539 (setq process (ph-open-session))
542 (set-buffer (setq buffer (process-buffer process)))
543 (ph-send-command process request)
544 (message "Request sent, waiting for reply...")
545 (ph-read-response process))))
547 (ph-close-session process)))
550 (defun ph-open-session (&optional server)
551 "Open a connection to the given CCSO SERVER.
552 SERVER is either a string naming the server or a list (NAME PORT)."
558 (setq server (or ph-server
559 (call-interactively 'ph-set-server))))
560 (string-match "\\(.*\\)\\(:\\(.*\\)\\)?" server)
561 (setq host (match-string 1 server))
562 (setq port (or (match-string 3 server)
563 ph-default-server-port))
564 (setq ph-process-buffer (get-buffer-create (format " *PH-%s*" host)))
566 (set-buffer ph-process-buffer)
568 (setq ph-read-point (point))
569 (and ph-xemacs-mule-p
570 (set-buffer-file-coding-system 'binary t)))
571 (setq process (open-network-stream "ph" ph-process-buffer host port))
574 (process-kill-without-query process)
578 (defun ph-close-session (process)
580 (set-buffer (process-buffer process))
581 (ph-send-command process "quit")
582 (ph-read-response process)
583 (if (fboundp 'add-async-timeout)
584 (add-async-timeout 10 'delete-process process)
585 (run-at-time 2 nil 'delete-process process))))
587 (defun ph-send-command (process command)
588 (goto-char (point-max))
589 (process-send-string process command)
590 (process-send-string process "\r\n")
593 (defun ph-read-response (process &optional return-response)
594 "Read a response from the PH/QI query process PROCESS.
595 Returns nil if response starts with an error code. If the
596 response is successful the return code or the reponse itself is returned
597 depending on RETURN-RESPONSE"
598 (let ((case-fold-search nil)
601 (goto-char ph-read-point)
602 ;; CCSO protocol : response complete if status >= 200
603 (while (not (re-search-forward "^\\(^[2-5].*\\):.*\n" nil t))
604 (accept-process-output process)
605 (goto-char ph-read-point))
606 (setq match-end (point))
607 (goto-char ph-read-point)
608 (if (and (setq return-code (match-string 1))
609 (setq return-code (string-to-number return-code))
610 (>= (abs return-code) 300))
611 (progn (setq ph-read-point match-end) nil)
612 (setq ph-read-point match-end)
614 (buffer-substring (point) match-end)
617 (defun ph-create-bbdb-record (record)
618 "Create a BBDB record using the RECORD alist.
619 RECORD is an alist of (KEY . VALUE) where KEY is a symbol naming a field
620 of the PH/QI database and VALUE is the corresponding value for the record"
621 ;; This function runs in a special context where lisp symbols corresponding
622 ;; to field names in record are bound to the corresponding values
624 `(let* (,@(mapcar '(lambda (c)
625 (list (car c) (if (listp (cdr c))
626 (list 'quote (cdr c))
639 ;; BBDB standard fields
640 (setq bbdb-name (ph-parse-spec (cdr (assq 'name ph-bbdb-conversion-alist)) record nil)
641 bbdb-company (ph-parse-spec (cdr (assq 'company ph-bbdb-conversion-alist)) record nil)
642 bbdb-net (ph-parse-spec (cdr (assq 'net ph-bbdb-conversion-alist)) record nil)
643 bbdb-notes (ph-parse-spec (cdr (assq 'notes ph-bbdb-conversion-alist)) record nil))
644 (setq spec (cdr (assq 'address ph-bbdb-conversion-alist)))
645 (setq bbdb-address (delq nil (ph-parse-spec (if (listp (car spec))
649 (setq spec (cdr (assq 'phone ph-bbdb-conversion-alist)))
650 (setq bbdb-phones (delq nil (ph-parse-spec (if (listp (car spec))
654 ;; BBDB custom fields
655 (setq bbdb-notes (append (list (and bbdb-notes (cons 'notes bbdb-notes)))
658 (if (and (not (memq (car mapping)
659 '(name company net address phone notes)))
660 (setq value (ph-parse-spec (cdr mapping) record nil)))
661 (cons (car mapping) value))))
662 ph-bbdb-conversion-alist)))
663 (setq bbdb-notes (delq nil bbdb-notes))
664 (setq bbdb-record (bbdb-create-internal bbdb-name
671 (bbdb-display-records (list bbdb-record))
674 (defun ph-parse-spec (spec record recurse)
675 "Parse the conversion SPEC using RECORD.
676 If RECURSE is non-nil then SPEC may be a list of atomic specs"
682 (fboundp (car spec))))
685 (void-variable nil)))
688 (mapcar '(lambda (spec-elem)
689 (ph-parse-spec spec-elem record nil))
692 (error "Invalid mapping specification for `%s'. Fix ph-bbdb-conversion-alist" spec))))
694 (defun ph-bbdbify-address (addr location)
695 "Parse ADDR into a vector compatible with bbdb-create-internal.
696 ADDR should be an address string of no more than four lines or a
698 The last line is searched for the zip code, city and state name.
699 LOCATION is used as the address location for bbdb."
700 (let* ((addr-components (if (listp addr)
702 (reverse (split-string addr "\n"))))
703 (lastl (pop addr-components))
705 (setq addr-components (nreverse addr-components))
708 ((string-match "\\(\\w+\\)\\W*\\([A-Z][A-Z]\\)\\W*\\([0-9]+\\)" lastl)
709 (setq city (match-string 1 lastl)
710 state (match-string 2 lastl)
711 zip (string-to-number (match-string 3 lastl))))
713 ((string-match "\\([0-9]+\\)[ \t]+\\(.*\\)" lastl)
714 (setq city (match-string 2 lastl)
715 zip (string-to-number (match-string 1 lastl))))
717 (error "ph-bbdbify-address was unable to parse the address. Customize ph-bbdb-conversion-alist")))
719 (or (nth 0 addr-components) "")
720 (or (nth 1 addr-components) "")
721 (or (nth 2 addr-components) "")
726 (defun ph-bbdbify-phone (phone location)
727 "Parse PHONE into a vector compatible with bbdb-create-internal.
728 PHONE is either a string supposedly containing a phone number or
729 a list of such strings which are concatenated.
730 LOCATION is used as the phone location for bbdb"
735 (setq phone-list (bbdb-parse-phone-number phone))
737 (if (string= "phone number unparsable." (ph-cadr err))
738 (if (not (y-or-n-p (format "BBDB claims %S to be unparsable. Insert it unparsed ? " phone)))
739 (error "phone number unparsable")
740 (setq phone-list (list (bbdb-string-trim phone))))
741 (signal (car err) (cdr err)))))
742 (if (= 3 (length phone-list))
743 (setq phone-list (append phone-list '(nil))))
744 (apply 'vector location phone-list)))
746 (vector location (mapconcat 'identity phone ", ")))
748 (error "Invalid phone specification. Cannot create bbdb record"))))
752 ;;{{{ High-level interfaces (interactive functions)
754 (defun ph-customize ()
755 "Customize the PH package."
757 (customize-group 'ph))
759 (defun ph-set-server (server)
760 "Set the server to SERVER."
761 (interactive "sNew PH/QI Server: ")
762 (message "Selected PH/QI server is now %s" server)
763 (setq ph-server server))
766 (defun ph-get-email (name)
767 "Get the email field of NAME from the PH/QI directory server."
768 (interactive "sName: ")
769 (let ((email (cdaar (ph-query-internal name '(email)))))
773 (message "No record matching %s" name)))
777 (defun ph-get-phone (name)
778 "Get the phone field of NAME from the PH/QI directory server."
779 (interactive "sName: ")
780 (let ((phone (cdaar (ph-query-internal name '(phone)))))
784 (message "No record matching %s" name)))
787 (defun ph-get-field-list ()
788 "Return a list of valid field names for current server.
789 When called interactively the list is formatted in a dedicated buffer
790 otherwise a list of symbols is returned."
792 (ph-do-request "fields")
794 (let ((ph-duplicate-fields-handling-method 'list))
795 (ph-display-records (ph-parse-query-result) t))
797 (ph-parse-query-result)))
801 (defun ph-expand-inline (&optional replace)
802 "Query the server and expand the query string before point.
803 The query string consists of the buffer substring from the point back to
804 the preceding comma, colon or beginning of line. If it consists of more than
805 one word the variable ph-inline-query-format-list controls how these are mapped
806 onto CCSO database field names.
807 After querying the server for the given string, the expansion specified by
808 ph-inline-expansion-format is inserted in the buffer at point. If REPLACE is t
809 then this expansion replaces the name in the buffer.
810 If ph-expanding-overwrites-query is t then the meaning of REPLACE is inverted."
814 (if (re-search-backward "[:,][ \t]*"
819 (goto-char (match-end 0)))
821 (words (buffer-substring beg end))
824 (query-format ph-inline-query-format-list)
830 (if (or (not query-format)
831 (not (string-match "[ \t]+" words)))
833 (setq words (split-string words "[ \t]+"))
834 (while (and words query-format)
835 (setq query-alist (cons (cons (car query-format) (car words)) query-alist))
836 (setq words (cdr words)
837 query-format (cdr query-format)))
839 (setcdr (car query-alist)
840 (concat (ph-cdar query-alist) " "
841 (mapconcat 'identity words " "))))
842 ;; Uniquify query-alist
843 (setq query-alist (nreverse query-alist))
845 (setq key (caar query-alist)
846 val (ph-cdar query-alist)
847 cell (assq key query))
849 (setcdr cell (concat val " " (cdr cell)))
850 (setq query (cons (car query-alist) query))))
851 (setq query-alist (cdr query-alist)))
853 (setq response (ph-query-internal query (cdr ph-inline-expansion-format)))
856 (error "No match found")
858 ;; Process response through ph-inline-expansion-format
860 (setq response-strings
862 (car ph-inline-expansion-format)
865 (or (cdr (assq field (car response)))
867 (cdr ph-inline-expansion-format)))
869 (setq response (cdr response)))
872 (and replace (not ph-expanding-overwrites-query))
873 (and (not replace) ph-expanding-overwrites-query))
874 (delete-region beg end))
876 ((or (= (length response-strings) 1)
877 (null ph-multiple-match-handling-method)
878 (eq ph-multiple-match-handling-method 'first))
879 (insert (car response-strings)))
880 ((eq ph-multiple-match-handling-method 'select)
881 (with-output-to-temp-buffer "*Completions*"
882 (display-completion-list response-strings)))
883 ((eq ph-multiple-match-handling-method 'all)
884 (insert (mapconcat 'identity response-strings ", ")))
885 ((eq ph-multiple-match-handling-method 'abort)
886 (error "There is more than one match for the query"))
892 (defun ph-query-form (&optional get-fields-from-server)
893 "*Display a form to query the CCSO PH/QI nameserver.
894 If given a non-nil argument the function first queries the server
895 for the existing fields and displays a corresponding form."
897 (let ((fields (or (and get-fields-from-server
900 (buffer (get-buffer-create "*PH/QI Query Form*"))
906 (switch-to-buffer buffer)
907 (setq inhibit-read-only t)
909 (kill-all-local-variables)
910 (make-local-variable 'ph-form-widget-list)
911 (widget-insert "PH/QI Query Form\n")
912 (widget-insert "================\n\n")
913 (widget-insert "Current server is: " (or ph-server
914 (call-interactively 'ph-set-server)) "\n")
915 ;; Loop over prompt strings to find the biggest one
919 (setq field-name (or (and (assq field ph-fieldname-formstring-alist)
920 (cdr (assq field ph-fieldname-formstring-alist)))
921 (capitalize (symbol-name field))))
922 (if (> (length field-name) width)
923 (setq width (length field-name)))
924 (cons field field-name)))
926 ;; Insert the first widget out of the mapcar to leave the cursor
927 ;; in the first field
928 (widget-insert "\n\n" (format (concat "%" width "s: ") (cdr (car fields))))
930 (setq widget (widget-create 'editable-field :size 15))
931 (setq ph-form-widget-list (cons (cons (car (car fields)) widget)
932 ph-form-widget-list))
933 (setq fields (cdr fields))
936 (widget-insert "\n\n" (format (concat "%" width "s: ") (cdr field)))
937 (setq widget (widget-create 'editable-field
939 (setq ph-form-widget-list (cons (cons (car field) widget)
940 ph-form-widget-list))))
942 (widget-insert "\n\n")
943 (widget-create 'push-button
944 :notify (lambda (&rest ignore)
948 (widget-create 'push-button
949 :notify (lambda (&rest ignore)
953 (widget-create 'push-button
954 :notify (lambda (&rest ignore)
957 (goto-char (1+ pt)) ; 1+ for some extent boundary reason
958 (use-local-map widget-keymap)
962 (defun ph-bookmark-server (server)
963 "Add SERVER to the `servers' hotlist."
964 (interactive "sServer: ")
965 (if (member server ph-server-hotlist)
966 (error "%s is already in the hotlist" server)
967 (setq ph-server-hotlist (cons server ph-server-hotlist))
971 (defun ph-bookmark-current-server ()
972 "Add current server to the `servers' hotlist."
974 (ph-bookmark-server ph-server))
976 (defun ph-save-options ()
977 "Save options (essentially the hotlist) to ph-options-file"
980 (set-buffer (find-file-noselect ph-options-file t))
981 ;; delete the previous setq
982 (let ((standard-output (current-buffer))
987 (let ((sexp (condition-case nil
988 (read (current-buffer))
989 (end-of-file (throw 'found nil)))))
992 (if (and (eq (car sexp) 'setq)
993 (eq (ph-cadr sexp) 'ph-server-hotlist))
995 (delete-region (save-excursion
1000 (if (and (eq (car sexp) 'provide)
1001 (equal (ph-cadr sexp) '(quote ph-options-file)))
1005 (throw 'found t)))))))
1006 (if (eq (point-min) (point-max))
1007 (princ ";; This file was automatically generated by ph.el\n\n"))
1010 (princ "(setq ph-server-hotlist '")
1011 (prin1 ph-server-hotlist)
1014 (princ "(provide 'ph-options-file)\n"))
1018 (defun ph-insert-record-at-point-into-bbdb ()
1019 "Insert record at point into the BBDB database.
1020 This function can only be called from a PH/QI query result buffer."
1022 (let ((record (and (overlays-at (point))
1023 (overlay-get (car (overlays-at (point))) 'ph-record))))
1025 (error "Point is not over a record")
1026 (ph-create-bbdb-record record))))
1028 (defun ph-try-bbdb-insert ()
1029 "Call ph-insert-record-at-point-into-bbdb if on a record"
1031 (and (or (featurep 'bbdb)
1032 (prog1 (locate-library "bbdb") (message "")))
1033 (overlays-at (point))
1034 (overlay-get (car (overlays-at (point))) 'ph-record)
1035 (ph-insert-record-at-point-into-bbdb)))
1037 (defun ph-move-to-next-record ()
1038 "Move to next record in a buffer displaying ph query results"
1040 (if (not (eq major-mode 'ph-mode))
1041 (error "Not in a PH buffer")
1042 (let ((pt (next-overlay-change (point))))
1043 (if (< pt (point-max))
1045 (error "No more records after point")))))
1047 (defun ph-move-to-previous-record ()
1048 "Move to next record in a buffer displaying ph query results"
1050 (if (not (eq major-mode 'ph-mode))
1051 (error "Not in a PH buffer")
1052 (let ((pt (previous-overlay-change (point))))
1053 (if (> pt (point-min))
1055 (error "No more records before point")))))
1061 ;;{{{ Menus an keymaps
1065 (defvar ph-mode-map (let ((map (make-sparse-keymap)))
1066 (define-key map "q" 'kill-this-buffer)
1067 (define-key map "x" 'kill-this-buffer)
1068 (define-key map "f" 'ph-query-form)
1069 (define-key map "b" 'ph-try-bbdb-insert)
1070 (define-key map "n" 'ph-move-to-next-record)
1071 (define-key map "p" 'ph-move-to-previous-record)
1073 (set-keymap-parent ph-mode-map widget-keymap)
1075 (defconst ph-tail-menu
1077 ["Query Form" ph-query-form t]
1078 ["Expand Inline" ph-expand-inline t]
1079 ["Insert Record into BBDB" ph-insert-record-at-point-into-bbdb
1080 (and (or (featurep 'bbdb)
1081 (prog1 (locate-library "bbdb") (message "")))
1082 (overlays-at (point))
1083 (overlay-get (car (overlays-at (point))) 'ph-record))]
1085 ["Get Email" ph-get-email t]
1086 ["Get Phone" ph-get-phone t]
1087 ["List Valid Field Names" ph-get-field-list t]
1089 ,(cons "Customize" (cdr (custom-menu-create 'ph)))))
1091 (defconst ph-server-menu
1092 '(["---" ph-bookmark-server t]
1093 ["Bookmark Current Server" ph-bookmark-current-server t]
1094 ["New Server" ph-set-server t]))
1104 (setq command (intern (concat "ph-set-server-" server)))
1105 (if (not (fboundp command))
1106 (fset command `(lambda ()
1108 (setq ph-server ,server)
1109 (message "Selected PH/QI server is now %s" ,server))))
1110 (vector server command t)))
1115 (defun ph-install-menu ()
1118 (add-submenu '("Tools") (ph-menu)))
1120 (easy-menu-define ph-menu-map ph-mode-map "PH Menu" (ph-menu))
1125 (easy-menu-create-keymaps "Ph" (cdr (ph-menu))))))