Source

eudc / eudc.el

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
;;; eudc.el --- Emacs Unified Directory Client

;; Copyright (C) 1998 Free Software Foundation, Inc.

;; Author: Oscar Figueiredo <oscar@xemacs.org>
;; Maintainer: Oscar Figueiredo <oscar@xemacs.org>
;; Created: Feb 1998
;; Version: $Revision$
;; Keywords: help

;; This file is part of XEmacs

;; XEmacs is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; XEmacs is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with XEmacs; see the file COPYING.  If not, write to 
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:
;;    This package provides a common interface to query directory servers using
;;    different protocols such as LDAP, CCSO PH/QI or BBDB.  Queries can be
;;    made through an interactive form or inline. Inline query strings in
;;    buffers are expanded with appropriately formatted query results
;;    (especially used to expand email addresses in message buffers).  EUDC
;;    also interfaces with the BBDB package to let you register query results
;;    into your own BBDB database.

;;; Usage:
;;    EUDC comes with an extensive documentation, please refer to it.
;;
;;    The main entry points of EUDC are:
;;      `eudc-query-form': Query a directory server from a query form
;;      `eudc-expand-inline': Query a directory server for the e-mail address
;;                            of the name before cursor and insert it in the 
;;                            buffer
;;      `eudc-get-phone': Get a phone number from a directory server
;;      `eudc-get-email': Get an e-mail address from a directory server
;;      `eudc-customize': Customize various aspects of EUDC

;;; Code:

(require 'wid-edit)

(eval-and-compile
  (if (not (fboundp 'make-overlay))
      (require 'overlay))
  (if (not (fboundp 'unless))
      (require 'cl)))

(unless (fboundp 'custom-menu-create)
  (autoload 'custom-menu-create "cus-edit"))

(require 'eudc-vars)



;;{{{      Internal cooking

;;{{{      Internal variables and compatibility tricks

(defconst eudc-xemacs-p (string-match "XEmacs" emacs-version))
(defconst eudc-emacs-p (not eudc-xemacs-p))
(defconst eudc-xemacs-mule-p (and eudc-xemacs-p
				  (featurep 'mule)))
(defconst eudc-emacs-mule-p (and eudc-emacs-p
				 (featurep 'mule)))

(defvar eudc-form-widget-list nil)
(defvar eudc-mode-map nil)
;; Used by the selection insertion mechanism
(defvar eudc-pre-select-window-configuration nil)
(defvar eudc-insertion-marker nil)

;; List of known servers
;; Alist of (SERVER . PROTOCOL)
(defvar eudc-server-hotlist nil)

;; List of variables that have server- or protocol-local bindings
(defvar eudc-local-vars nil)

;; Protocol local. Query function 
(defvar eudc-query-function nil)

;; Protocol local.  A function that retrieves a list of valid attribute names
(defvar eudc-list-attributes-function nil)

;; Protocol local. A mapping between EUDC attribute names and corresponding
;; protocol specific names.  The following names are defined by EUDC and may be
;; included in that list: `name' , `firstname', `email', `phone'
(defvar eudc-protocol-attributes-translation-alist nil)

;; Protocol local. Mapping between protocol attribute names and BBDB field
;; names
(defvar eudc-bbdb-conversion-alist nil)

;; Protocol/Server local. Hook called upon switching to that server
(defvar eudc-switch-to-server-hook nil)

;; Protocol/Server local. Hook called upon switching from that server
(defvar eudc-switch-from-server-hook nil)

;; Protocol local. Whether the protocol supports queries with no specified
;; attribute name
(defvar eudc-protocol-has-default-query-attributes nil)

(defun eudc-cadr (obj)
  (car (cdr obj)))

(defun eudc-cdar (obj)
  (cdr (car obj)))

(defun eudc-caar (obj)
  (car (car obj)))

(defun eudc-cdaar (obj)
  (cdr (car (car obj))))

(defun eudc-plist-member (plist prop)
  "Return t if PROP has a value specified in PLIST."
  (if (not (= 0 (% (length plist) 2)))
      (error "Malformed plist"))
  (catch 'found
    (while plist
      (if (eq prop (car plist))
	  (throw 'found t))
      (setq plist (cdr (cdr plist))))
    nil))

;; Emacs' plist-get lacks third parameter
(defun eudc-plist-get (plist prop &optional default)
  "Extract a value from a property list.
PLIST is a property list, which is a list of the form
(PROP1 VALUE1 PROP2 VALUE2...).  This function returns the value
corresponding to the given PROP, or DEFAULT if PROP is not
one of the properties on the list."
  (if (eudc-plist-member plist prop)
      (plist-get plist prop)
    default))

(defun eudc-lax-plist-get (plist prop &optional default)
  "Extract a value from a lax property list.
PLIST is a lax property list, which is a list of the form (PROP1
VALUE1 PROP2 VALUE2...), where comparisons between properties are done
using `equal' instead of `eq'.  This function returns the value
corresponding to PROP, or DEFAULT if PROP is not one of the
properties on the list."
  (if (not (= 0 (% (length plist) 2)))
      (error "Malformed plist"))
  (catch 'found
    (while plist
      (if (equal prop (car plist))
	  (throw 'found (car (cdr plist))))
      (setq plist (cdr (cdr plist))))
    default))

(if (not (fboundp 'split-string))
    (defun split-string (string &optional pattern)
      "Return a list of substrings of STRING which are separated by PATTERN.
If PATTERN is omitted, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
  (or pattern
      (setq pattern "[ \f\t\n\r\v]+"))
  (let (parts (start 0))
    (when (string-match pattern string 0)
      (if (> (match-beginning 0) 0)
	  (setq parts (cons (substring string 0 (match-beginning 0)) nil)))
      (setq start (match-end 0))
      (while (and (string-match pattern string start)
		  (> (match-end 0) start))
	(setq parts (cons (substring string start (match-beginning 0)) parts)
	      start (match-end 0))))
    (nreverse (if (< start (length string))
		  (cons (substring string start) parts)
		parts)))))

(defun eudc-replace-in-string (str regexp newtext)
  "Replace all matches in STR for REGEXP with NEWTEXT.
Value is the new string."
  (let ((rtn-str "")
	(start 0)
	match prev-start)
    (while (setq match (string-match regexp str start))
      (setq prev-start start
	    start (match-end 0)
	    rtn-str
	    (concat rtn-str
		    (substring str prev-start match)
		    newtext)))
    (concat rtn-str (substring str start))))

;;}}} 

;;{{{ Server and Protocol Variable Routines

(defun eudc-server-local-variable-p (var)
  "Return non-nil if VAR has server-local bindings."
  (eudc-plist-member (get var 'eudc-locals) 'server))

(defun eudc-protocol-local-variable-p (var)
  "Return non-nil if VAR has protocol-local bindings."
  (eudc-plist-member (get var 'eudc-locals) 'protocol))

(defun eudc-default-set (var val)
  "Set the EUDC default value of VAR to VAL.
The current binding of VAR is not changed."
  (put var 'eudc-locals 
       (plist-put (get var 'eudc-locals) 'default val))
  (add-to-list 'eudc-local-vars var))

(defun eudc-protocol-set (var val &optional protocol)
  "Set the PROTOCOL-local binding of VAR to VAL.
If omitted PROTOCOL defaults to the current value of `eudc-protocol'.
The current binding of VAR is changed only if PROTOCOL is omitted."
  (if (eq 'unbound (eudc-variable-default-value var))
      (eudc-default-set var (symbol-value var)))
  (let* ((eudc-locals (get var 'eudc-locals))
	 (protocol-locals (eudc-plist-get eudc-locals 'protocol)))
    (setq protocol-locals (plist-put protocol-locals (or protocol
							 eudc-protocol) val))
    (setq eudc-locals 
	  (plist-put eudc-locals 'protocol protocol-locals))
    (put var 'eudc-locals eudc-locals)
    (add-to-list 'eudc-local-vars var)
    (unless protocol
      (eudc-update-variable var))))
       
(defun eudc-server-set (var val &optional server)
  "Set the SERVER-local binding of VAR to VAL.
If omitted SERVER defaults to the current value of `eudc-server'.
The current binding of VAR is changed only if SERVER is omitted."
  (if (eq 'unbound (eudc-variable-default-value var))
      (eudc-default-set var (symbol-value var)))
  (let* ((eudc-locals (get var 'eudc-locals))
	 (server-locals (eudc-plist-get eudc-locals 'server)))
    (setq server-locals (plist-put server-locals (or server
						     eudc-server) val))
    (setq eudc-locals 
	  (plist-put eudc-locals 'server server-locals))
    (put var 'eudc-locals eudc-locals)
    (add-to-list 'eudc-local-vars var)
    (unless server
      (eudc-update-variable var))))


(defun eudc-set (var val)
  "Set the most local (server, protocol or default) binding of VAR to VAL.
The current binding of VAR is also set to VAL"
  (cond 
   ((not (eq 'unbound (eudc-variable-server-value var)))
    (eudc-server-set var val))
   ((not (eq 'unbound (eudc-variable-protocol-value var)))
    (eudc-protocol-set var val))
   (t
    (eudc-default-set var val)))
  (set var val))

(defun eudc-variable-default-value (var)
  "Return the default binding of VAR.
Return `unbound' if VAR has no EUDC default value."
  (let ((eudc-locals (get var 'eudc-locals)))
    (if (and (boundp var)
	     eudc-locals)
	(eudc-plist-get eudc-locals 'default 'unbound)
      'unbound)))

(defun eudc-variable-protocol-value (var &optional protocol)
  "Return the value of VAR local to PROTOCOL.
Return `unbound' if VAR has no value local to PROTOCOL.
PROTOCOL defaults to `eudc-protocol'"
  (let* ((eudc-locals (get var 'eudc-locals))
	 protocol-locals)
    (if (not (and  (boundp var)
		   eudc-locals
		   (eudc-plist-member eudc-locals 'protocol)))
	'unbound
      (setq protocol-locals (eudc-plist-get eudc-locals 'protocol))
      (eudc-lax-plist-get protocol-locals 
			  (or protocol
			      eudc-protocol) 'unbound))))

(defun eudc-variable-server-value (var &optional server)
  "Return the value of VAR local to SERVER.
Return `unbound' if VAR has no value local to SERVER.
SERVER defaults to `eudc-server'"
  (let* ((eudc-locals (get var 'eudc-locals))
	 server-locals)
    (if (not (and (boundp var)
		  eudc-locals
		  (eudc-plist-member eudc-locals 'server)))
	'unbound
      (setq server-locals (eudc-plist-get eudc-locals 'server))
      (eudc-lax-plist-get server-locals 
			  (or server
			      eudc-server) 'unbound))))

(defun eudc-update-variable (var)
  "Set the value of VAR according to its locals.
If the VAR has a server- or protocol-local value corresponding
to the current `eudc-server' and `eudc-protocol' then it is set
accordingly. Otherwise it is set to its EUDC default binding"
  (let (val)
    (cond 
     ((not (eq 'unbound (setq val (eudc-variable-server-value var))))
      (set var val))
     ((not (eq 'unbound (setq val (eudc-variable-protocol-value var))))
      (set var val))
     ((not (eq 'unbound (setq val (eudc-variable-default-value var))))
      (set var val)))))

(defun eudc-update-local-variables ()
  "Update all EUDC variables according to their local settings."
  (interactive)
  (mapcar 'eudc-update-variable eudc-local-vars))

(eudc-default-set 'eudc-query-function nil)
(eudc-default-set 'eudc-list-attributes-function nil)
(eudc-default-set 'eudc-protocol-attributes-translation-alist nil)
(eudc-default-set 'eudc-bbdb-conversion-alist nil)
(eudc-default-set 'eudc-switch-to-server-hook nil)
(eudc-default-set 'eudc-switch-from-server-hook nil)
(eudc-default-set 'eudc-protocol-has-default-query-attributes nil)
(eudc-default-set 'eudc-attribute-display-method-alist nil)

;;}}}


;; Add PROTOCOL to the list of supported protocols
(defun eudc-register-protocol (protocol)
  (unless (memq protocol eudc-supported-protocols)
    (setq eudc-supported-protocols 
	  (cons protocol eudc-supported-protocols))
    (put 'eudc-protocol 'custom-type 
	 `(choice :menu-tag "Protocol"
		  ,@(mapcar (lambda (s) 
			      (list 'string ':tag (symbol-name s)))
			    eudc-supported-protocols))))
  (or (memq protocol eudc-known-protocols)
      (setq eudc-known-protocols
	    (cons protocol eudc-known-protocols))))

;; Execute BODY restoring the server and protocol if anything goes wrong
(defmacro eudc-server-protect (&rest body)
  `(let ((eudc-former-server eudc-server)
	 (eudc-former-protocol eudc-protocol))
     (condition-case signal
	(progn
	  ,@body
	  (or (and (equal eudc-server eudc-former-server)
		   (equal eudc-protocol eudc-former-protocol))
	      (eudc-set-server eudc-former-server eudc-former-protocol t)))
       (t (or (and (equal eudc-server eudc-former-server)
		   (equal eudc-protocol eudc-former-protocol))
	      (eudc-set-server eudc-former-server eudc-former-protocol t))
	  (signal (car signal) (cdr signal))))))

(defun eudc-echo-progress (server protocol)
  (message "Querying %s with protocol %s..." server protocol))

(defun eudc-translate-query (query)
  "Translate attribute names of QUERY.
The translation is done according to 
`eudc-protocol-attributes-translation-alist'."
  (if eudc-protocol-attributes-translation-alist
      (mapcar '(lambda (attribute)
		 (let ((trans (assq (car attribute) 
				    (symbol-value eudc-protocol-attributes-translation-alist))))
		   (if trans
		       (cons (cdr trans) (cdr attribute))
		     attribute)))
	      query)
    query)) 

(defun eudc-translate-attribute-list (list)
  "Translate a list of attribute names LIST.
The translation is done according to
`eudc-protocol-attributes-translation-alist'."
  (if eudc-protocol-attributes-translation-alist
      (let (trans)
	(mapcar '(lambda (attribute)
		   (setq trans (assq attribute
				     (symbol-value eudc-protocol-attributes-translation-alist)))
		   (if trans
		       (cdr trans)
		     attribute))
		list))
    list))

(defun eudc-select (choices)
  "Choose one from CHOICES using a completion buffer."
  (setq eudc-pre-select-window-configuration (current-window-configuration))
  (setq eudc-insertion-marker (point-marker))
  (with-output-to-temp-buffer "*EUDC Completions*"
    (apply 'display-completion-list 
	   choices 
	   (if eudc-xemacs-p
	       '(:activate-callback eudc-insert-selected)))))

(defun eudc-insert-selected (event extent user)
  "Insert a completion at the appropriate point."
  (when eudc-insertion-marker
    (set-buffer (marker-buffer eudc-insertion-marker))
    (goto-char eudc-insertion-marker)
    (insert (extent-string extent)))
  (if eudc-pre-select-window-configuration
      (set-window-configuration eudc-pre-select-window-configuration))
  (setq eudc-pre-select-window-configuration nil
	eudc-insertion-marker nil))

(defun eudc-query (query &optional return-attributes)
   "Query the current directory server with QUERY.
QUERY is a list of cons cells (ATTR . VALUE) where ATTR is an attribute
name and VALUE the corresponding value.
RETURN-ATTRIBUTES is a list of attributes to return defaulting to 
`eudc-default-return-attributes'."
   (unless eudc-query-function
     (error "Don't know how to perform the query"))
   (funcall eudc-query-function 
	    (eudc-translate-query query)
	    (cond 
	     (return-attributes
	      (eudc-translate-attribute-list return-attributes))
	     ((listp eudc-default-return-attributes)
	      (eudc-translate-attribute-list eudc-default-return-attributes))
	     (t
	      eudc-default-return-attributes))))

(defun eudc-multi-query (queries-or-words sentinel for-inline-expansion try-all)
  "Query one or several directory servers.
The servers that are queried are determined by `eudc-multi-query-policy' 
and `eudc-max-servers-to-query'.
If FOR-INLINE-EXPANSION is non-nil, the function is called for inline
expansion and QUERIES-OR-WORDS is expected to be a list of individual
words which are mapped onto `eudc-inline-query-format' to build the
directory queries. If FOR-INLINE-EXPANSION is nil, QUERIES-OR-WORDS is
expected to be a list of individual queries. An individual query is a
list of cons cells (ATTR . VALUE) where ATTR is an attribute name and
VALUE is the corresponding value.
SENTINEL is a symbol naming a sentinel function which is called
for each new server tried.
If TRY-ALL is non-nil then all servers are tried in order, otherwise
search stops when at leasta match is found on a server.
The returned value is a list of server matches. Each server match is
itself a list of the form ((SERVER .PROTO) MATCH1 MATCH2 ...) where
MATCHn is a matching record found on this server.  A matching record is
a list of cons cells (ATTR . VALUE) where ATTR is an attribute name and
VALUE is the corresponding value"
  (if (memq eudc-multi-query-policy 
	    '(current-server server-then-hotlist))
      (or eudc-server
	  (call-interactively 'eudc-set-server))
    (or eudc-server-hotlist
	(error "No server in the hotlist")))
  (let (servers response found query-formats queries return-attributes)
    ;; Prepare the list of servers to query
    (setq servers
	  (cond 
	   ((eq eudc-multi-query-policy 'hotlist)
	    eudc-server-hotlist)
	   ((eq eudc-multi-query-policy 'server-then-hotlist)
	    (cons (cons eudc-server eudc-protocol)
		  (delete (cons eudc-server eudc-protocol)
			  (copy-sequence eudc-server-hotlist))))
	   ((eq eudc-multi-query-policy 'current-server)
	    (list (cons eudc-server eudc-protocol)))
	   (t
	    (error "Wrong value for `eudc-multi-query-policy': %S"
		   eudc-multi-query-policy))))
    (if (and eudc-max-servers-to-query
	     (> (length servers) eudc-max-servers-to-query))
	(setcdr (nthcdr (1- eudc-max-servers-to-query) servers) nil))
    
    (eudc-server-protect
     (catch 'found
       ;; Loop on the servers
       (while servers
	 (eudc-set-server (eudc-caar servers) (eudc-cdar servers) t)
	 (if sentinel
	     (funcall sentinel 
		      (eudc-caar servers) 
		      (eudc-cdar servers)))
	 
	 (if (null for-inline-expansion)
	     (setq queries queries-or-words
		   return-attributes nil)
	   ;; Determine which formats apply in the query-format list
	   (setq query-formats
		 (eudc-extract-n-word-formats eudc-inline-query-format
					      (length queries-or-words)))
	   ;; Build the queries
	   (setq queries 
		 (if query-formats
		     (mapcar '(lambda (format)
				(eudc-build-query-with-words-on-format
				 queries-or-words 
				 format))
			     query-formats)
		   queries-or-words))
	   ;; Get the return attributes from the inline expansion format
	   (setq return-attributes (cdr eudc-inline-expansion-format)))

	 ;; Loop on queries
	 (mapcar 
	  (function 
	   (lambda (query)
	     ;; If the query is a simple list of strings, 
	     ;; try to build a valid query
	     (or (consp (car query))
		 (setq query (eudc-build-query-with-words-on-format query)))
	     (setq response (cons (cons (cons eudc-server eudc-protocol)
					(eudc-query query return-attributes))
				  response))
	     (setq found (or found (cadr (car response))))
	     (if (and found (null try-all))
		 (throw 'found response))))
	  queries)
	 (setq servers (cdr servers)))))
     
     (if (null found)
	 (error "No match")
       response)))

(defun eudc-format-attribute-name-for-display (attribute)
  "Format a directory attribute name for display.
ATTRIBUTE is looked up in `eudc-user-attribute-names-alist' and replaced 
by the corresponding user name if any.  Otherwise it is capitalized and
underscore characters are replaced by spaces."
  (let ((match (assq attribute eudc-user-attribute-names-alist)))
    (if match
	(cdr match)
      (capitalize 
       (mapconcat 'identity 
		  (split-string (symbol-name attribute) "_")
		  " ")))))

(defun eudc-print-attribute-value (field)
  "Insert the value of the directory FIELD at point.
The directory attribute name in car of FIELD is looked up in 
`eudc-attribute-display-method-alist' and the corresponding method, 
if any, is called to print the value in cdr of FIELD."
  (let ((match (assoc (downcase (car field))
		      eudc-attribute-display-method-alist))
	(col (current-column))
	(val (cdr field)))
    (if match
	(progn
	  (eval (list (cdr match) val))
	  (insert "\n"))
      (mapcar
       (function
	(lambda (val-elem)
	  (indent-to col)
	  (insert val-elem "\n")))
       (cond
	((listp val) val)
	((stringp val) (split-string val "\n"))
	((null val) '(""))
	(t (list val)))))))

(defun eudc-print-record-field (field column-width)
  "Print the record field FIELD.
FIELD is a list (ATTR VALUE1 VALUE2 ...) or cons-cell (ATTR . VAL)
COLUMN-WIDTH is the width of the first display column containing the 
attribute name ATTR."
  (let ((field-beg (point)))
;; The record field that is passed to this function has already been processed
;; by `eudc-format-attribute-name-for-display' so we don't need to call it
;; again to display the attribute name
    (insert (format (concat "%" (int-to-string column-width) "s: ") 
		    (car field)))
    (put-text-property field-beg (point) 'face 'bold)
    (indent-to (+ 2 column-width))
    (eudc-print-attribute-value field)))

(defun eudc-setup-record-display-buffer ()
  "Setup a buffer to display records."
  (let ((buffer (get-buffer-create "*Directory Query Results*"))
	inhibit-read-only)
    (switch-to-buffer buffer)    
    (setq buffer-read-only t
	  inhibit-read-only t)
    (erase-buffer)
    (insert "Directory Query Result\n")
    (insert "======================\n\n\n")))

(defun eudc-close-record-display-buffer ()
  "Insert the closing of a record display buffer."
  (let ((inhibit-read-only t))
    (insert "\n")
    (widget-create 'push-button
		   :notify (lambda (&rest ignore)
			     (eudc-query-form))
		   "New query")
    (widget-insert " ")
    (widget-create 'push-button
		   :notify (lambda (&rest ignore)
			     (kill-this-buffer))
		   "Quit")
    (eudc-mode)
    (widget-setup)))
 
(defun eudc-display-records (records &optional raw-attr-names)
  "Display RECORDS in a formatted buffer.
RECORDS is a server-prefixed record list as returned by `eudc-multi-query'.
If RAW-ATTR-NAMES is non-nil, the raw attribute names are displayed
otherwise they are formatted according to `eudc-user-attribute-names-alist'."
  (let ((inhibit-read-only t)
	precords
	(width 0)
	beg
	attribute-name
	num-matches
	server)

    ;; Print the number of records in the list
    (setq num-matches (if (cdr records)
			  (length (cdr records))
			0))
    (widget-insert (format "%d match%s found on %s (%s)\n\n"
			   num-matches
			   (if (> num-matches 1) "es" "")
			   (caar records)
			   (cdar records)))
    
    (eudc-server-protect
     (setq server (car records))
     ;; We need to switch servers because value display methods depend on the server
     (eudc-set-server (car server) (cdr server) t)
     ;; Drop server header from the record list
     (setq records (cdr records))
     ;; Replace field names with user names and compute max width
     (setq precords
	   (mapcar 
	    (function
	     (lambda (record)
	       (mapcar 
		(function
		 (lambda (field)
		   (setq attribute-name 
			 (if raw-attr-names
			     (symbol-name (car field))
			   (eudc-format-attribute-name-for-display (car field))))
		   (if (> (length attribute-name) width)
		       (setq width (length attribute-name)))
		   (cons attribute-name (cdr field))))
		record)))
	    records))
     ;; Display the records
     (mapcar 
      (function
       (lambda (record)
	 (setq beg (point))
	 ;; Map over the record fields to print the attribute/value pairs
	 (mapcar (function 
		  (lambda (field)
		    (eudc-print-record-field field width))) 
		 record)
	 ;; Store the record internal format in some convenient place
	 (overlay-put (make-overlay beg (point))
		      'eudc-record
		      (cons server (car records)))
	 (setq records (cdr records))
	 (insert "\n")))
      precords))))
  
(defun eudc-send-mail ()
  "Send email to the address in the current record."
  (interactive)
  (unless (eq major-mode 'eudc-mode)
    (error "This command should be called in EUDC buffers"))
  (let ((record
         (overlay-get (car (overlays-at (point))) 'eudc-record))
        (mail nil))
    (unless record (error "Not on a record"))
    ;; Since eudc-protocol-attributes-translation-alist is server-dependent we
    ;; need to switch servers temporarily
    (eudc-server-protect
     (eudc-set-server (caar record) (cdar record) t)
     (setq mail (cdr (assq 
		      (or 
		       (cdr (assq 'email 
				 (symbol-value eudc-protocol-attributes-translation-alist)))
			 'email) 
		     (cdr record)))))
    (if mail
	(funcall (get mail-user-agent 'composefunc) mail)
      (error "Cannot determine email address"))))

(defun eudc-process-form ()
  "Process the query form in current buffer and display the results."
  (let (query value result inhibit-read-only)
    (if (not (and (boundp 'eudc-form-widget-list)
		  eudc-form-widget-list))
	(error "Not in a directory query form buffer")
      (mapcar (function 
	       (lambda (wid-field)
		 (setq value (widget-value (cdr wid-field)))
		 (if (not (string= value ""))
		     (setq query (cons (cons (car wid-field) value)
				       query)))))
	      eudc-form-widget-list)
      (kill-buffer (current-buffer))
      (setq result (eudc-multi-query (list query) 'eudc-echo-progress nil t))
      ;; Display the query results
      (eudc-setup-record-display-buffer)
      (mapcar (function 
	       (lambda (server-matches)
		 (eudc-display-records server-matches
				       eudc-use-raw-directory-names)))
	      result)
      (eudc-close-record-display-buffer))))

(defun eudc-filter-duplicate-attributes (record)
  "Filter RECORD according to `eudc-duplicate-attribute-handling-method'."
  (let ((rec record)
	unique
	duplicates
	result)

    ;; Search for multiple records
    (while (and rec
		(not (listp (eudc-cdar rec))))
      (setq rec (cdr rec)))

    (if (null (eudc-cdar rec))
	(list record)			; No duplicate attrs in this record
      (mapcar (function 
	       (lambda (field)
		 (if (listp (cdr field))
		     (setq duplicates (cons field duplicates))
		   (setq unique (cons field unique)))))
	      record)
      (setq result (list unique))
      ;; Map over the record fields that have multiple values
      (mapcar 
       (function
	(lambda (field)
	  (let ((method (if (consp eudc-duplicate-attribute-handling-method)
			    (cdr 
			     (assq 
			      (or 
			       (car 
				(rassq 
				 (car field)
				 (symbol-value 
				  eudc-protocol-attributes-translation-alist)))
			       (car field))
			      eudc-duplicate-attribute-handling-method))
			  eudc-duplicate-attribute-handling-method)))
	    (cond
	     ((or (null method) (eq 'list method))
	      (setq result 
		    (eudc-add-field-to-records field result)))
	     ((eq 'first method)
	      (setq result 
		    (eudc-add-field-to-records (cons (car field) 
						     (eudc-cadr field)) 
					       result)))
	     ((eq 'concat method)
	      (setq result 
		    (eudc-add-field-to-records (cons (car field)
						     (mapconcat 
						      'identity
						      (cdr field)
						      "\n")) result)))
	     ((eq 'duplicate method)
	      (setq result
		    (eudc-distribute-field-on-records field result)))))))
       duplicates)
      result)))

(defun eudc-filter-partial-records (records attrs)
  "Eliminate records that do not contain all ATTRS from RECORDS."
  (delq nil 
	(mapcar 
	 (function 
	  (lambda (rec)
	    (if (eval (cons 'and 
		       (mapcar 
			(function 
			 (lambda (attr)
			   (consp (assq attr rec))))
			attrs)))
		rec)))
	 records)))
	   
(defun eudc-add-field-to-records (field records)
  "Add FIELD to each individual record in RECORDS and return the resulting list."
  (mapcar (function
	   (lambda (r)
	     (cons field r)))
	  records))

(defun eudc-distribute-field-on-records (field records)
  "Duplicate each individual record in RECORDS according to value of FIELD.
Each copy is added a new field containing one of the values of FIELD."
  (let (result
	(values (cdr field)))
    ;; Uniquify values first
    (while values
      (setcdr values (delete (car values) (cdr values)))
      (setq values (cdr values)))
    (mapcar 
     (function
      (lambda (value)
	(let ((result-list (copy-sequence records)))
	  (setq result-list (eudc-add-field-to-records 
			     (cons (car field) value)
			     result-list))
	  (setq result (append result-list result))
		 )))
	    (cdr field))
    result))


(defun eudc-mode ()
  "Major mode used in buffers displaying the results of directory queries.
There is no sense in calling this command from a buffer other than
one containing the results of a directory query.

These are the special commands of EUDC mode:
    q -- Kill this buffer.
    f -- Display a form to query the current directory server.
    n -- Move to next record.
    p -- Move to previous record.
    b -- Insert record at point into the BBDB database."
  (interactive)
  (kill-all-local-variables)
  (setq major-mode 'eudc-mode)
  (setq mode-name "EUDC")
  (use-local-map eudc-mode-map)
  (if eudc-emacs-p
      (easy-menu-define eudc-emacs-menu eudc-mode-map "" (eudc-menu))
    (setq mode-popup-menu (eudc-menu)))
  (run-hooks 'eudc-mode-hook)
  )

;;}}}        

;;{{{      High-level interfaces (interactive functions)

(defun eudc-customize ()
  "Customize the EUDC package."
  (interactive)
  (customize-group 'eudc))

;;;###autoload
(defun eudc-set-server (server protocol &optional no-save)
  "Set the directory server to SERVER using PROTOCOL.
Unless NO-SAVE is non-nil, the server is saved as the default 
server for future sessions."
  (interactive (list
		(read-from-minibuffer "Directory Server: ")
		(intern (completing-read "Protocol: " 
					 (mapcar '(lambda (elt)
						    (cons (symbol-name elt)
							  elt))
						 eudc-known-protocols)))))
  (unless (or (member protocol
		      eudc-supported-protocols)
	      (load (concat "eudcb-" (symbol-name protocol)) t))
    (error "Unsupported protocol: %s" protocol))
  (run-hooks 'eudc-switch-from-server-hook)
  (setq eudc-protocol protocol)
  (setq eudc-server server)
  (eudc-update-local-variables)
  (run-hooks 'eudc-switch-to-server-hook)
  (if (interactive-p)
      (message "Current directory server is now %s (%s)" eudc-server eudc-protocol))
  (if (null no-save)
      (eudc-save-options)))

;;;###autoload
(defun eudc-get-email (name)
  "Get the email field of NAME from the directory server."
  (interactive "sName: ")
  (or eudc-server
      (call-interactively 'eudc-set-server))
  (let ((result (eudc-query (list (cons 'name name)) '(email)))
	email)
    (if (null (cdr result)) 
	(setq email (eudc-cdaar result))
      (error "Multiple match. Use the query form"))
    (if (interactive-p)
	(if email
	    (message "%s" email)
	  (error "No record matching %s" name)))
    email))

;;;###autoload
(defun eudc-get-phone (name)
  "Get the phone field of NAME from the directory server."
  (interactive "sName: ")
  (or eudc-server
      (call-interactively 'eudc-set-server))
  (let ((result (eudc-query (list (cons 'name name)) '(phone)))
	phone)
    (if (null (cdr result)) 
	(setq phone (eudc-cdaar result))
      (error "Multiple match. Use the query form"))
    (if (interactive-p)
	(if phone
	    (message "%s" phone)
	  (error "No record matching %s" name)))
    phone))

(defun eudc-get-attribute-list ()
  "Return a list of valid attributes for the current server.
When called interactively the list is formatted in a dedicated buffer
otherwise a list of symbols is returned."
  (interactive)
  (if eudc-list-attributes-function
      (let ((entries (funcall eudc-list-attributes-function (interactive-p))))
	(if entries 
	    (if (interactive-p)
		(eudc-display-records entries t)
	      entries)))
    (error "The %s protocol has no support for listing attributes" eudc-protocol)))

(defun eudc-build-query-with-words-on-format (words &optional format)
  "Use FORMAT to build a EUDC query from WORDS.
If FORMAT id nil, use the protocol default attribute name, if any."
  (let (query
	query-alist
	key val cell)
    (if format
	(progn
	  (while (and words format)
	    (setq query-alist (cons (cons (car format) (car words)) 
				    query-alist))
	    (setq words (cdr words)
		  format (cdr format)))
	  ;; If the same attribute appears more than once, merge
	  ;; the corresponding values
	  (setq query-alist (nreverse query-alist))
	  (while query-alist
	    (setq key (eudc-caar query-alist)
		  val (eudc-cdar query-alist)
		  cell (assq key query))
	    (if cell
		(setcdr cell (concat (cdr cell) " " val))
	      (setq query (cons (car query-alist) query)))
	    (setq query-alist (cdr query-alist)))
	  query)
      (if eudc-protocol-has-default-query-attributes
	  (mapconcat 'identity words " ")
	(list (cons 'name (mapconcat 'identity words " ")))))))

(defun eudc-extract-n-word-formats (format-list n)
  "Extract a list of N-long formats from FORMAT-LIST.
If none try N - 1 and so forth."
  (let (formats)
    (while (and (null formats)
		(> n 0))
      (setq formats 
	    (delq nil
		  (mapcar '(lambda (format)
			     (if (= n
				    (length format))
				 format
			       nil))
			  format-list)))
      (setq n (1- n)))
    formats))
				    


;;;###autoload
(defun eudc-expand-inline (&optional replace)
  "Query the directory server, and expand the query string before point.
The query string consists of the buffer substring from the point back to
the preceding comma, colon or beginning of line.  
The variable `eudc-inline-query-format' controls how to associate the 
individual inline query words with directory attribute names.
After querying the server for the given string, the expansion specified by 
`eudc-inline-expansion-format' is inserted in the buffer at point.
If REPLACE is non nil, then this expansion replaces the name in the buffer.
`eudc-expansion-overwrites-query' being non nil inverts the meaning of REPLACE.
Multiple servers can be tried with the same query until a match is found, 
see `eudc-multi-query-policy'"
  (interactive)
  (let* ((end (point))
	 (beg (save-excursion
		(if (re-search-backward "\\([:,]\\|^\\)[ \t]*" 
					(save-excursion
					  (beginning-of-line)
					  (point))
					'move)
		    (goto-char (match-end 0)))
		(point)))
	 (query-words (split-string (buffer-substring beg end) "[ \t]+"))
	 response
	 response-string
	 response-strings)
				
    (setq response
	  (car (eudc-multi-query query-words nil t nil)))
	    
    ;; Process response through eudc-inline-expansion-format. We need
    ;; to switch to the context of the server where a match was found
    (if response
	(eudc-server-protect
	  ;; Switch to the context of the server where a match was found
	 (eudc-set-server (caar response) (cdar response) t)
	 (setq response (cdr response))	; Drop the server/protocol part

	 ;; Loop over the matches found on the server
	 (while response
	   (setq response-string (apply 'format 
					(car eudc-inline-expansion-format)
					(mapcar (function 
						 (lambda (field)
						   (or (cdr (assq field (car response))) 
						       "")))
						(eudc-translate-attribute-list
						 (cdr eudc-inline-expansion-format)))))
	   (if (> (length response-string) 0)
	       (setq response-strings
		     (cons response-string response-strings)))
	   (setq response (cdr response)))
    
	 (if (or
	      (and replace (not eudc-expansion-overwrites-query))
	      (and (not replace) eudc-expansion-overwrites-query))
	     (delete-region beg end))
	 (cond 
	  ((or (= (length response-strings) 1)
	       (null eudc-multiple-match-handling-method)
	       (eq eudc-multiple-match-handling-method 'first))
	   (insert (car response-strings)))
	  ((eq eudc-multiple-match-handling-method 'select)
	   (eudc-select response-strings))
	  ((eq eudc-multiple-match-handling-method 'all)
	   (insert (mapconcat 'identity response-strings ", ")))
	  ((eq eudc-multiple-match-handling-method 'abort)
	   (error "There is more than one match for the query")))))))

;;;###autoload
(defun eudc-query-form (&optional get-fields-from-server)
  "Display a form to query directory servers.
If given a non-nil argument GET-FIELDS-FROM-SERVER, the function first
queries the server for the existing fields and displays a corresponding form."
  (interactive "P")
  (let ((fields (or (and get-fields-from-server
			 (eudc-get-attribute-list))
		    eudc-query-form-attributes))
	(buffer (get-buffer-create "*Directory Query Form*"))
	prompts
	widget
	(width 0)
	inhibit-read-only
	pt)
    (switch-to-buffer buffer)
    (setq inhibit-read-only t)
    (erase-buffer)
    (kill-all-local-variables)
    (make-local-variable 'eudc-form-widget-list)
    (widget-insert "Directory Query Form\n")
    (widget-insert "====================\n\n")
    (widget-insert "Multi-query policy: "
		   (cond
		    ((eq eudc-multi-query-policy 'current-server)
		     "current server only\n")
		    ((eq eudc-multi-query-policy 'hotlist)
		     (if (or (null eudc-max-servers-to-query)
			     (>= eudc-max-servers-to-query
				 (length eudc-server-hotlist)))
			 "hotlist servers\n"
		       (concat "First " 
			       eudc-max-servers-to-query
			       " servers of the hotlist\n")))
		    ((eq eudc-multi-query-policy 'server-then-hotlist)
		     (if (or (null eudc-max-servers-to-query)
			     (> eudc-max-servers-to-query
				(length eudc-server-hotlist)))
			 "current server then hotlist\n"
		       (format "current server then first %d servers of the hotlist\n"
			       (1- eudc-max-servers-to-query))))))
    (widget-insert "Current server is : " (or eudc-server
					     (progn 
					       (call-interactively 'eudc-set-server)
					       eudc-server))
					     "\n")
    (widget-insert "Protocol          : " (symbol-name eudc-protocol) "\n")
    ;; Build the list of prompts
    (setq prompts (if eudc-use-raw-directory-names
		      (mapcar 'symbol-name (eudc-translate-attribute-list fields))
		    (mapcar (function
			     (lambda (field)
			       (or (and (assq field eudc-user-attribute-names-alist)
					(cdr (assq field eudc-user-attribute-names-alist)))
				   (capitalize (symbol-name field)))))
			    fields)))
    ;; Loop over prompt strings to find the longest one
    (mapcar (function
	     (lambda (prompt)
		     (if (> (length prompt) width)
			 (setq width (length prompt)))))
	    prompts)
    ;; Insert the first widget out of the mapcar to leave the cursor 
    ;; in the first field 
    (widget-insert "\n\n" (format (concat "%" (int-to-string width) "s: ") (car prompts)))
    (setq pt (point))
    (setq widget (widget-create 'editable-field :size 15))
    (setq eudc-form-widget-list (cons (cons (car fields) widget)
				      eudc-form-widget-list))
    (setq fields (cdr fields))
    (setq prompts (cdr prompts))
    (mapcar (function
	     (lambda (field)
	       (widget-insert "\n\n" (format (concat "%" (int-to-string width) "s: ") (car prompts)))
	       (setq widget (widget-create 'editable-field
					   :size 15))
	       (setq eudc-form-widget-list (cons (cons field widget)
						 eudc-form-widget-list))
	       (setq prompts (cdr prompts))))
	    fields)
    (widget-insert "\n\n")
    (widget-create 'push-button
		   :notify (lambda (&rest ignore)
			     (eudc-process-form))
		   "Query Server")
    (widget-insert " ")
    (widget-create 'push-button
		   :notify (lambda (&rest ignore)
			     (eudc-query-form))
		   "Reset Form")
    (widget-insert " ")
    (widget-create 'push-button
		   :notify (lambda (&rest ignore)
			     (kill-this-buffer))
		   "Quit")
    (goto-char pt)
    (use-local-map widget-keymap)
    (widget-setup))
  )

(defun eudc-bookmark-server (server protocol)
  "Add SERVER using PROTOCOL to the EUDC `servers' hotlist."
  (interactive "sDirectory server: \nsProtocol: ")
  (if (member (cons server protocol) eudc-server-hotlist)
      (error "%s:%s is already in the hotlist" protocol server)
    (setq eudc-server-hotlist (cons (cons server protocol) eudc-server-hotlist))
    (eudc-install-menu)
    (eudc-save-options)))

(defun eudc-bookmark-current-server ()
  "Add current server to the EUDC `servers' hotlist."
  (interactive)
  (eudc-bookmark-server eudc-server eudc-protocol))

(defun eudc-save-options ()
  "Save options to `eudc-options-file'."
  (interactive)
  (save-excursion
    (set-buffer (find-file-noselect eudc-options-file t))
    (goto-char (point-min))
    ;; delete the previous setq
    (let ((standard-output (current-buffer))
	  provide-p
	  set-hotlist-p
	  set-server-p)
      (catch 'found
	(while t
	  (let ((sexp (condition-case nil
			  (read (current-buffer))
			(end-of-file (throw 'found nil)))))
	    (if (listp sexp)
		(cond
		 ((eq (car sexp)  'eudc-set-server)
		  (delete-region (save-excursion
				   (backward-sexp)
				   (point))
				 (point))
		  (setq set-server-p t))
		 ((and (eq (car sexp)  'setq)
		       (eq (eudc-cadr sexp) 'eudc-server-hotlist))
		  (delete-region (save-excursion
				   (backward-sexp)
				   (point))
				 (point))
		  (setq set-hotlist-p t))
		 ((and (eq (car sexp)  'provide)
		       (equal (eudc-cadr sexp) '(quote eudc-options-file)))
		  (setq provide-p t)))
	      (if (and provide-p
		       set-hotlist-p
		       set-server-p)
		  (throw 'found t))))))
      (if (eq (point-min) (point-max))
	  (princ ";; This file was automatically generated by eudc.el.\n\n"))
      (or provide-p
	  (princ "(provide 'eudc-options-file)\n"))
      (or (bolp)
	  (princ "\n"))
      (delete-blank-lines)
      (princ "(eudc-set-server ")
      (prin1 eudc-server)
      (princ " '")
      (prin1 eudc-protocol)
      (princ " t)\n")
      (princ "(setq eudc-server-hotlist '")
      (prin1 eudc-server-hotlist)
      (princ ")\n")
      (save-buffer))))

(defun eudc-move-to-next-record ()
  "Move to next record, in a buffer displaying directory query results."
  (interactive)
  (if (not (eq major-mode 'eudc-mode))
      (error "Not in a EUDC buffer")
    (let ((pt (next-overlay-change (point))))
      (if (< pt (point-max))
	  (goto-char (1+ pt))
	(error "No more records after point")))))

(defun eudc-move-to-previous-record ()
  "Move to previous record, in a buffer displaying directory query results."
  (interactive)
  (if (not (eq major-mode 'eudc-mode))
      (error "Not in a EUDC buffer")
    (let ((pt (previous-overlay-change (point))))
      (if (> pt (point-min))
	  (goto-char pt)
	(error "No more records before point")))))


      
;;}}}

;;{{{      Menus an keymaps

(require 'easymenu)

(setq eudc-mode-map 
      (let ((map (make-sparse-keymap)))
	(define-key map "q" 'kill-this-buffer)
	(define-key map "x" 'kill-this-buffer)
	(define-key map "f" 'eudc-query-form)
	(define-key map "b" 'eudc-try-bbdb-insert)
	(define-key map "n" 'eudc-move-to-next-record)
	(define-key map "p" 'eudc-move-to-previous-record)
	map))
(set-keymap-parent eudc-mode-map widget-keymap)

(defconst eudc-custom-generated-menu (cdr (custom-menu-create 'eudc)))

(defconst eudc-tail-menu 
  `("---"
    ["Query with Form" eudc-query-form t]
    ["Expand Inline Query" eudc-expand-inline t]
    ["Send mail to this address" eudc-send-mail
     (and (overlays-at (point))
	  (overlay-get (car (overlays-at (point))) 'eudc-record))]
    ["Insert Record into BBDB" eudc-insert-record-at-point-into-bbdb 
     (and (or (featurep 'bbdb)
	      (prog1 (locate-library "bbdb") (message "")))
	  (overlays-at (point))
	  (overlay-get (car (overlays-at (point))) 'eudc-record))]
    ["Insert All Records into BBDB" eudc-batch-export-records-to-bbdb 
     (and (eq major-mode 'eudc-mode)
	  (or (featurep 'bbdb)
	      (prog1 (locate-library "bbdb") (message ""))))]
    "---"
    ["Get Email" eudc-get-email t]
    ["Get Phone" eudc-get-phone t]
    ["List Valid Attribute Names" eudc-get-attribute-list t]
    "---"
    ,(cons "Customize" eudc-custom-generated-menu)))
    

(defconst eudc-server-menu 
  '("---"
    ["Bookmark Current Server" eudc-bookmark-current-server t]
    ["Edit Server List" eudc-edit-hotlist t]
    ["New Server" eudc-set-server t]))

(defun eudc-menu ()
  (let (command)
    (append '("Directory Search")
	    (list
	     (append 
	      '("Server")
	      (mapcar 
	       (function 
		(lambda (servspec)
		  (let* ((server (car servspec))
			 (protocol (cdr servspec))
			 (proto-name (symbol-name protocol)))
		    (setq command (intern (concat "eudc-set-server-" 
						  server 
						  "-" 
						  proto-name)))
		    (if (not (fboundp command))
			(fset command 
			      `(lambda ()
				 (interactive)
				 (eudc-set-server ,server (quote ,protocol))
				 (message "Selected directory server is now %s (%s)" 
					  ,server 
					  ,proto-name))))
		    (vector (format "%s (%s)" server proto-name)
			    command
			    :style 'radio
			    :selected `(equal eudc-server ,server)))))
	       eudc-server-hotlist)
	      eudc-server-menu))
	    eudc-tail-menu)))

(defun eudc-install-menu ()
  (cond 
   ((and eudc-xemacs-p (featurep 'menubar))
    (add-submenu '("Tools") (eudc-menu)))
   (eudc-emacs-p
    (cond 
     ((fboundp 'easy-menu-add-item)
      (let ((menu (eudc-menu)))
	(easy-menu-add-item nil '("tools") (easy-menu-create-menu (car menu)
								  (cdr menu)))))
     ((fboundp 'easy-menu-create-keymaps)
      (easy-menu-define eudc-menu-map eudc-mode-map "Directory Client Menu" (eudc-menu))
      (define-key 
	global-map
	[menu-bar tools eudc] 
	(cons "Directory Search"
	      (easy-menu-create-keymaps "Directory Search" (cdr (eudc-menu))))))
     (t
      (error "Unknown version of easymenu"))))
   ))


;;; Load time initializations :

;;; Load the options file
(if (and (not noninteractive)
	 (and (locate-library eudc-options-file)
	      (message ""))		; Remove modeline message
	 (not (featurep 'eudc-options-file)))
    (load eudc-options-file))
  
	 
;;; Install the full menu
(unless (featurep 'infodock)
  (eudc-install-menu))


;;; The following installs a short menu for EUDC at XEmacs startup.

;;;###autoload
(defun eudc-load-eudc ()
  "Load the Emacs Unified Directory Client.
This does nothing except loading eudc by autoload side-effect."
  (interactive)
  nil)

;;}}}

;;;###autoload
(cond ((not (string-match "XEmacs" emacs-version))
       (defvar eudc-tools-menu (make-sparse-keymap "Directory Search"))
       (fset 'eudc-tools-menu (symbol-value 'eudc-tools-menu))
       
       (define-key eudc-tools-menu [phone]
	 '("Get Phone" . eudc-get-phone))
       (define-key eudc-tools-menu [email]
	 '("Get Email" . eudc-get-email))
       (define-key eudc-tools-menu [separator-eudc-email]
	 '("---"))
       (define-key eudc-tools-menu [expand-inline]
	 '("Expand Inline Query" . eudc-expand-inline))
       (define-key eudc-tools-menu [query]
	 '("Query with Form" . eudc-query-form))
       (define-key eudc-tools-menu [separator-eudc-query]
	 '("---"))
       (define-key eudc-tools-menu [new]
	 '("New Server" . eudc-set-server))
       (define-key eudc-tools-menu [load]
	 '("Load Hotlist of Servers" . eudc-load-eudc)))
      
      (t
       (let ((menu  '("Directory Search"
		      ["Load Hotlist of Servers" eudc-load-eudc t]
		      ["New Server" eudc-set-server t]
		      "---"
		      ["Query with Form" eudc-query-form t]
		      ["Expand Inline Query" eudc-expand-inline t]
		      "---"
		      ["Get Email" eudc-get-email t]
		      ["Get Phone" eudc-get-phone t])))
	 (if (not (featurep 'eudc-autoloads))
	     (if (string-match "XEmacs" emacs-version)
		 (if (and (featurep 'menubar)
			  (not (featurep 'infodock)))
		     (add-submenu '("Tools") menu))
	       (require 'easymenu)
	       (cond 
		((fboundp 'easy-menu-add-item)
		 (easy-menu-add-item nil '("tools")
				     (easy-menu-create-menu (car menu)
							    (cdr menu))))
		((fboundp 'easy-menu-create-keymaps)
		 (define-key 
		   global-map
		   [menu-bar tools eudc] 
		   (cons "Directory Search"
			 (easy-menu-create-keymaps "Directory Search"
						   (cdr menu)))))))))))
        
;;}}}

(provide 'eudc)

;;; eudc.el ends here
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.