Initial Commit
[packages] / xemacs-packages / mail-lib / mail-extr.el
1 ;;; mail-extr.el --- extract full name and address from RFC 822 mail header
2
3 ;; Copyright (C) 1991, 1992, 1993, 1994, 1997, 2001
4 ;;   Free Software Foundation, Inc.
5
6 ;; Author: Joe Wells <jbw@cs.bu.edu>
7 ;; Maintainer: FSF
8 ;; Keywords: mail
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Synched up with: Emacs 21.3 CVS as of 2004-06-10.
28
29 ;;; Commentary:
30
31 ;; The entry point of this code is
32 ;;
33 ;;    mail-extract-address-components: (address &optional all)
34 ;;
35 ;;    Given an RFC-822 ADDRESS, extract full name and canonical address.
36 ;;    Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).
37 ;;    If no name can be extracted, FULL-NAME will be nil.
38 ;;    ADDRESS may be a string or a buffer.  If it is a buffer, the visible
39 ;;     (narrowed) portion of the buffer will be interpreted as the address.
40 ;;     (This feature exists so that the clever caller might be able to avoid
41 ;;     consing a string.)
42 ;;    If ADDRESS contains more than one RFC-822 address, only the first is
43 ;;     returned.
44 ;;
45 ;;    If ALL is non-nil, that means return info about all the addresses
46 ;;     that are found in ADDRESS.  The value is a list of elements of
47 ;;     the form (FULL-NAME CANONICAL-ADDRESS), one per address.
48 ;;
49 ;; This code is more correct (and more heuristic) parser than the code in
50 ;; rfc822.el.  And despite its size, it's fairly fast.
51 ;;
52 ;; There are two main benefits:
53 ;;
54 ;; 1. Higher probability of getting the correct full name for a human than
55 ;;    any other package we know of.  (On the other hand, it will cheerfully
56 ;;    mangle non-human names/comments.)
57 ;; 2. Address part is put in a canonical form.
58 ;;
59 ;; The interface is not yet carved in stone; please give us suggestions.
60 ;;
61 ;; We have an extensive test-case collection of funny addresses if you want to
62 ;; work with the code.  Developing this code requires frequent testing to
63 ;; make sure you're not breaking functionality.  The test cases aren't included
64 ;; because they are over 100K.
65 ;;
66 ;; If you find an address that mail-extr fails on, please send it to the
67 ;; maintainer along with what you think the correct results should be.  We do
68 ;; not consider it a bug if mail-extr mangles a comment that does not
69 ;; correspond to a real human full name, although we would prefer that
70 ;; mail-extr would return the comment as-is.
71 ;;
72 ;; Features:
73 ;;
74 ;; * Full name handling:
75 ;;
76 ;;   * knows where full names can be found in an address.
77 ;;   * avoids using empty comments and quoted text.
78 ;;   * extracts full names from mailbox names.
79 ;;   * recognizes common formats for comments after a full name.
80 ;;   * puts a period and a space after each initial.
81 ;;   * understands & referring to the mailbox name, capitalized.
82 ;;   * strips name prefixes like "Prof.", etc.
83 ;;   * understands what characters can occur in names (not just letters).
84 ;;   * figures out middle initial from mailbox name.
85 ;;   * removes funny nicknames.
86 ;;   * keeps suffixes such as Jr., Sr., III, etc.
87 ;;   * reorders "Last, First" type names.
88 ;;
89 ;; * Address handling:
90 ;;
91 ;;   * parses rfc822 quoted text, comments, and domain literals.
92 ;;   * parses rfc822 multi-line headers.
93 ;;   * does something reasonable with rfc822 GROUP addresses.
94 ;;   * handles many rfc822 noncompliant and garbage addresses.
95 ;;   * canonicalizes addresses (after stripping comments/phrases outside <>).
96 ;;     * converts ! addresses into .UUCP and %-style addresses.
97 ;;     * converts rfc822 ROUTE addresses to %-style addresses.
98 ;;     * truncates %-style addresses at leftmost fully qualified domain name.
99 ;;     * handles local relative precedence of ! vs. % and @ (untested).
100 ;;
101 ;; It does almost no string creation.  It primarily uses the built-in
102 ;; parsing routines with the appropriate syntax tables.  This should
103 ;; result in greater speed.
104 ;;
105 ;; TODO:
106 ;;
107 ;; * handle all test cases.  (This will take forever.)
108 ;; * software to pick the correct header to use (eg., "Senders-Name:").
109 ;; * multiple addresses in the "From:" header (almost all of the necessary
110 ;;   code is there).
111 ;; * flag to not treat `,' as an address separator.  (This is useful when
112 ;;   there is a "From:" header but no "Sender:" header, because then there
113 ;;   is only allowed to be one address.)
114 ;; * mailbox name does not necessarily contain full name.
115 ;; * fixing capitalization when it's all upper or lowercase.  (Hard!)
116 ;; * some of the domain literal handling is missing.  (But I've never even
117 ;;   seen one of these in a mail address, so maybe no big deal.)
118 ;; * arrange to have syntax tables byte-compiled.
119 ;; * speed hacks.
120 ;; * delete unused variables.
121 ;; * arrange for testing with different relative precedences of ! vs. @
122 ;;   and %.
123 ;; * insert documentation strings!
124 ;; * handle X.400-gatewayed addresses according to RFC 1148.
125
126 ;;; Change Log:
127 ;;
128 ;; Thu Feb 17 17:57:33 1994  Jamie Zawinski (jwz@lucid.com)
129 ;;
130 ;;      * merged with jbw's latest version
131 ;;
132 ;; Wed Feb  9 21:56:27 1994  Jamie Zawinski (jwz@lucid.com)
133 ;;
134 ;;      * high-bit chars in comments weren't treated as word syntax
135 ;;
136 ;; Sat Feb  5 03:13:40 1994  Jamie Zawinski (jwz@lucid.com)
137 ;;
138 ;;      * call replace-match with fixed-case arg
139 ;;
140 ;; Thu Dec 16 21:56:45 1993  Jamie Zawinski (jwz@lucid.com)
141 ;;
142 ;;      * some more cleanup, doc, added provide
143 ;;
144 ;; Tue Mar 23 21:23:18 1993  Joe Wells  (jbw at csd.bu.edu)
145 ;;
146 ;;      * Made mail-full-name-prefixes a user-customizable variable.
147 ;;        Allow passing the address as a buffer as well as a string.
148 ;;        Allow [ and ] as name characters (Finnish character set).
149 ;;
150 ;; Mon Mar 22 21:20:56 1993  Joe Wells  (jbw at bigbird.bu.edu)
151 ;;
152 ;;      * Handle "null" addresses.  Handle = used for spacing in mailbox
153 ;;        name.  Fix bug in handling of ROUTE-ADDR-type addresses that are
154 ;;        missing their brackets.  Handle uppercase "JR".  Extract full
155 ;;        names from X.400 addresses encoded in RFC-822.  Fix bug in
156 ;;        handling of multiple addresses where first has trailing comment.
157 ;;        Handle more kinds of telephone extension lead-ins.
158 ;;
159 ;; Mon Mar 22 20:16:57 1993  Joe Wells  (jbw at bigbird.bu.edu)
160 ;;
161 ;;      * Handle HZ encoding for embedding GB encoded chinese characters.
162 ;;
163 ;; Mon Mar 22 00:46:12 1993  Joe Wells  (jbw at bigbird.bu.edu)
164 ;;
165 ;;      * Fixed too broad matching of ham radio call signs.  Fixed bug in
166 ;;        handling an unmatched ' in a name string.  Enhanced recognition
167 ;;        of when . in the mailbox name terminates the name portion.
168 ;;        Narrowed conversion of . to space to only the necessary
169 ;;        situation.  Deal with VMS's stupid date stamps.  Handle a unique
170 ;;        way of introducing an alternate address.  Fixed spacing bug I
171 ;;        introduced in switching last name order.  Fixed bug in handling
172 ;;        address with ! and % but no @.  Narrowed the cases in which
173 ;;        certain trailing words are discarded.
174 ;;
175 ;; Sun Mar 21 21:41:06 1993  Joe Wells  (jbw at bigbird.bu.edu)
176 ;;
177 ;;      * Fixed bugs in handling GROUP addresses.  Certain words in the
178 ;;        middle of a name no longer terminate it.  Handle LISTSERV list
179 ;;        names.  Ignore comment field containing mailbox name.
180 ;;
181 ;; Sun Mar 21 14:39:38 1993  Joe Wells  (jbw at bigbird.bu.edu)
182 ;;
183 ;;      * Moved variant-method code back into main function.  Handle
184 ;;      underscores as spaces in comments.  Handle leading nickname.  Add
185 ;;      flag to ignore single-word names.  Other changes.
186 ;;
187 ;; Mon Feb  1 22:23:31 1993  Joe Wells  (jbw at bigbird.bu.edu)
188 ;;
189 ;;      * Added in changes by Rod Whitby and Jamie Zawinski.  This
190 ;;        includes the flag mail-extr-guess-middle-initial and the fix for
191 ;;        handling multiple addresses correctly.  (Whitby just changed
192 ;;        a > to a <.)
193 ;;
194 ;; Mon Apr  6 23:59:09 1992  Joe Wells  (jbw at bigbird.bu.edu)
195 ;;
196 ;;      * Cleaned up some more.  Release version 1.0 to world.
197 ;;
198 ;; Sun Apr  5 19:39:08 1992  Joe Wells  (jbw at bigbird.bu.edu)
199 ;;
200 ;;      * Cleaned up full name extraction extensively.
201 ;;
202 ;; Sun Feb  2 14:45:24 1992  Joe Wells  (jbw at bigbird.bu.edu)
203 ;;
204 ;;      * Total rewrite.  Integrated mail-canonicalize-address into
205 ;;      mail-extract-address-components.  Now handles GROUP addresses more
206 ;;      or less correctly.  Better handling of lots of different cases.
207 ;;
208 ;; Fri Jun 14 19:39:50 1991
209 ;;      * Created.
210
211 ;;; Code:
212 \f
213
214 (defgroup mail-extr nil
215   "Extract full name and address from RFC 822 mail header."
216   :prefix "mail-extr-"
217   :group 'mail)
218
219 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
220 ;;
221 ;; User configuration variable definitions.
222 ;;
223
224 (defcustom mail-extr-guess-middle-initial nil
225   "*Whether to try to guess middle initial from mail address.
226 If true, then when we see an address like \"John Smith <jqs@host.com>\"
227 we will assume that \"John Q. Smith\" is the fellow's name."
228   :type 'boolean
229   :group 'mail-extr)
230
231 (defcustom mail-extr-ignore-single-names nil
232   "*Whether to ignore a name that is just a single word.
233 If true, then when we see an address like \"Idiot <dumb@stupid.com>\"
234 we will act as though we couldn't find a full name in the address."
235   :type 'boolean
236   :group 'mail-extr)
237
238 ;; Matches a leading title that is not part of the name (does not
239 ;; contribute to uniquely identifying the person).
240 (defcustom mail-extr-full-name-prefixes
241   (purecopy
242    "\\(Prof\\|D[Rr]\\|Mrs?\\|Rev\\|Rabbi\\|SysOp\\|LCDR\\)\\.?[ \t\n]")
243   "*Matches prefixes to the full name that identify a person's position.
244 These are stripped from the full name because they do not contribute to
245 uniquely identifying the person."
246   :type 'regexp
247   :group 'mail-extr)
248
249 (defcustom mail-extr-@-binds-tighter-than-! nil
250   "*Whether the local mail transport agent looks at ! before @."
251   :type 'boolean
252   :group 'mail-extr)
253
254 (defcustom mail-extr-mangle-uucp nil
255   "*Whether to throw away information in UUCP addresses
256 by translating things like \"foo!bar!baz@host\" into \"baz@bar.UUCP\"."
257   :type 'boolean
258   :group 'mail-extr)
259
260 ;;----------------------------------------------------------------------
261 ;; what orderings are meaningful?????
262 ;;(defvar mail-operator-precedence-list '(?! ?% ?@))
263 ;; Right operand of a % or a @ must be a domain name, period.  No other
264 ;; operators allowed.  Left operand of a @ is an address relative to that
265 ;; site.
266
267 ;; Left operand of a ! must be a domain name.  Right operand is an
268 ;; arbitrary address.
269 ;;----------------------------------------------------------------------
270
271 \f
272
273 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
274 ;;
275 ;; Constant definitions.
276 ;;
277
278 ;; Any character that can occur in a name, not counting characters that
279 ;; separate parts of a multipart name (hyphen and period).
280 ;; Yes, there are weird people with digits in their names.
281 ;; You will also notice the consideration for the
282 ;; Swedish/Finnish/Norwegian character set.
283 ;; XEmacs: Add \200-\376 range (not \377 due to bug (?) in search.c...).
284 (defconst mail-extr-all-letters-but-separators
285   (purecopy "][A-Za-z{|}'~0-9`\200-\376")) ;; XEmacs
286
287 ;; Any character that can occur in a name in an RFC822 address including
288 ;; the separator (hyphen and possibly period) for multipart names.
289 ;; #### should . be in here?
290 (defconst mail-extr-all-letters
291   (purecopy (concat mail-extr-all-letters-but-separators "---")))
292
293 ;; Any character that can start a name.
294 ;; Keep this set as minimal as possible.
295 (defconst mail-extr-first-letters (purecopy "A-Za-z")) ;; XEmacs
296
297 ;; Any character that can end a name.
298 ;; Keep this set as minimal as possible.
299 (defconst mail-extr-last-letters (purecopy "[A-Za-z`'.")) ;; XEmacs
300
301 (defconst mail-extr-leading-garbage "\\W+")
302
303 ;; (defconst mail-extr-non-name-chars
304 ;;   (purecopy (concat "^" mail-extr-all-letters ".")))
305 ;; (defconst mail-extr-non-begin-name-chars
306 ;;   (purecopy (concat "^" mail-extr-first-letters)))
307 ;; (defconst mail-extr-non-end-name-chars
308 ;;   (purecopy (concat "^" mail-extr-last-letters)))
309
310 ;; Matches an initial not followed by both a period and a space.
311 ;; (defconst mail-extr-bad-initials-pattern
312 ;;   (purecopy
313 ;;    (format "\\(\\([^%s]\\|\\`\\)[%s]\\)\\(\\.\\([^ ]\\)\\| \\|\\([^%s .]\\)\\|\\'\\)"
314 ;;            mail-extr-all-letters mail-extr-first-letters mail-extr-all-letters)))
315
316 ;; Matches periods used instead of spaces.  Must not match the period
317 ;; following an initial.
318 (defconst mail-extr-bad-dot-pattern
319   (purecopy
320    (format "\\([%s][%s]\\)\\.+\\([%s]\\)"
321            mail-extr-all-letters
322            mail-extr-last-letters
323            mail-extr-first-letters)))
324
325 ;; Matches an embedded or leading nickname that should be removed.
326 ;; (defconst mail-extr-nickname-pattern
327 ;;   (purecopy
328 ;;    (format "\\([ .]\\|\\`\\)[\"'`\[\(]\\([ .%s]+\\)[\]\"'\)] "
329 ;;            mail-extr-all-letters)))
330
331 ;; Matches the occurrence of a generational name suffix, and the last
332 ;; character of the preceding name.  This is important because we want to
333 ;; keep such suffixes: they help to uniquely identify the person.
334 ;; *** Perhaps this should be a user-customizable variable.  However, the
335 ;; *** regular expression is fairly tricky to alter, so maybe not.
336 (defconst mail-extr-full-name-suffix-pattern
337   (purecopy
338    (format
339     "\\(,? ?\\([JjSs][Rr]\\.?\\|V?I+V?\\)\\)\\([^%s]\\([^%s]\\|\\'\\)\\|\\'\\)"
340     mail-extr-all-letters mail-extr-all-letters)))
341
342 (defconst mail-extr-roman-numeral-pattern (purecopy "V?I+V?\\b"))
343
344 ;; Matches a trailing uppercase (with other characters possible) acronym.
345 ;; Must not match a trailing uppercase last name or trailing initial
346 (defconst mail-extr-weird-acronym-pattern
347   (purecopy "\\([A-Z]+[-_/]\\|[A-Z][A-Z][A-Z]?\\b\\)"))
348
349 ;; Matches a mixed-case or lowercase name (not an initial).
350 ;; #### Match Latin1 lower case letters here too?
351 ;; (defconst mail-extr-mixed-case-name-pattern
352 ;;   (purecopy
353 ;;    (format
354 ;;     "\\b\\([a-z][%s]*[%s]\\|[%s][%s]*[a-z][%s]*[%s]\\|[%s][%s]*[a-z]\\)"
355 ;;     mail-extr-all-letters mail-extr-last-letters
356 ;;     mail-extr-first-letters mail-extr-all-letters mail-extr-all-letters
357 ;;     mail-extr-last-letters mail-extr-first-letters mail-extr-all-letters)))
358
359 ;; Matches a trailing alternative address.
360 ;; #### Match Latin1 letters here too?
361 ;; #### Match _ before @ here too?
362 (defconst mail-extr-alternative-address-pattern
363   (purecopy "\\(aka *\\)?[a-zA-Z.]+[!@][a-zA-Z.]"))
364
365 ;; Matches a variety of trailing comments not including comma-delimited
366 ;; comments.
367 (defconst mail-extr-trailing-comment-start-pattern
368   (purecopy " [-{]\\|--\\|[+@#></\;]"))
369
370 ;; Matches a name (not an initial).
371 ;; This doesn't force a word boundary at the end because sometimes a
372 ;; comment is separated by a `-' with no preceding space.
373 (defconst mail-extr-name-pattern
374   (purecopy (format "\\b[%s][%s]*[%s]"
375                     mail-extr-first-letters
376                     mail-extr-all-letters
377                     mail-extr-last-letters)))
378
379 (defconst mail-extr-initial-pattern
380   (purecopy (format "\\b[%s]\\([. ]\\|\\b\\)" mail-extr-first-letters)))
381
382 ;; Matches a single name before a comma.
383 ;; (defconst mail-extr-last-name-first-pattern
384 ;;   (purecopy (concat "\\`" mail-extr-name-pattern ",")))
385
386 ;; Matches telephone extensions.
387 (defconst mail-extr-telephone-extension-pattern
388   (purecopy
389    "\\(\\([Ee]xt\\|\\|[Tt]ph\\|[Tt]el\\|[Xx]\\).?\\)? *\\+?[0-9][- 0-9]+"))
390
391 ;; Matches ham radio call signs.
392 ;; Help from: Mat Maessen N2NJZ <maessm@rpi.edu>, Mark Feit
393 ;; <mark@era.com>, Michael Covington <mcovingt@ai.uga.edu>.
394 ;; Examples: DX504 DX515 K5MRU K8DHK KA9WGN KA9WGN KD3FU KD6EUI KD6HBW
395 ;; KE9TV KF0NV N1API N3FU N3GZE N3IGS N4KCC N7IKQ N9HHU W4YHF W6ANK WA2SUH
396 ;; WB7VZI N2NJZ NR3G KJ4KK AB4UM AL7NI KH6OH WN3KBT N4TMI W1A N0NZO
397 (defconst mail-extr-ham-call-sign-pattern
398   (purecopy "\\b\\(DX[0-9]+\\|[AKNW][A-Z]?[0-9][A-Z][A-Z]?[A-Z]?\\)"))
399
400 ;; Possible trailing suffixes: "\\(/\\(KT\\|A[AEG]\\|[R0-9]\\)\\)?"
401 ;; /KT == Temporary Technician (has CSC but not "real" license)
402 ;; /AA == Temporary Advanced
403 ;; /AE == Temporary Extra
404 ;; /AG == Temporary General
405 ;; /R  == repeater
406 ;; /#  == stations operating out of home district
407 ;; I don't include these in the regexp above because I can't imagine
408 ;; anyone putting them with their name in an e-mail address.
409
410 ;; Matches normal single-part name
411 (defconst mail-extr-normal-name-pattern
412   (purecopy (format "\\b[%s][%s]+[%s]"
413                     mail-extr-first-letters
414                     mail-extr-all-letters-but-separators
415                     mail-extr-last-letters)))
416
417 ;; Matches a single word name.
418 ;; (defconst mail-extr-one-name-pattern
419 ;;   (purecopy (concat "\\`" mail-extr-normal-name-pattern "\\'")))
420
421 ;; Matches normal two names with missing middle initial
422 ;; The first name is not allowed to have a hyphen because this can cause
423 ;; false matches where the "middle initial" is actually the first letter
424 ;; of the second part of the first name.
425 (defconst mail-extr-two-name-pattern
426   (purecopy
427    (concat "\\`\\(" mail-extr-normal-name-pattern
428            "\\|" mail-extr-initial-pattern
429            "\\) +\\(" mail-extr-name-pattern "\\)\\(,\\|\\'\\)")))
430
431 (defconst mail-extr-listserv-list-name-pattern
432   (purecopy "Multiple recipients of list \\([-A-Z]+\\)"))
433
434 (defconst mail-extr-stupid-vms-date-stamp-pattern
435   (purecopy
436    "[0-9][0-9]-[JFMASOND][aepuco][nbrylgptvc]-[0-9][0-9][0-9][0-9] [0-9]+ *"))
437
438 ;;; HZ -- GB (PRC Chinese character encoding) in ASCII embedding protocol
439 ;;
440 ;; In ASCII mode, a byte is interpreted as an ASCII character, unless a '~' is
441 ;; encountered. The character '~' is an escape character. By convention, it
442 ;; must be immediately followed ONLY by '~', '{' or '\n' (<LF>), with the
443 ;; following special meaning.
444 ;;
445 ;; o The escape sequence '~~' is interpreted as a '~'.
446 ;; o The escape-to-GB sequence '~{' switches the mode from ASCII to GB.
447 ;; o The escape sequence '~\n' is a line-continuation marker to be consumed
448 ;;   with no output produced.
449 ;;
450 ;; In GB mode, characters are interpreted two bytes at a time as (pure) GB
451 ;; codes until the escape-from-GB code '~}' is read. This code switches the
452 ;; mode from GB back to ASCII.  (Note that the escape-from-GB code '~}'
453 ;; ($7E7D) is outside the defined GB range.)
454 (defconst mail-extr-hz-embedded-gb-encoded-chinese-pattern
455   (purecopy "~{\\([^~].\\|~[^\}]\\)+~}"))
456
457 ;; The leading optional lowercase letters are for a bastardized version of
458 ;; the encoding, as is the optional nature of the final slash.
459 (defconst mail-extr-x400-encoded-address-pattern
460   (purecopy "[a-z]?[a-z]?\\(/[A-Za-z]+\\(\\.[A-Za-z]+\\)?=[^/]+\\)+/?\\'"))
461
462 (defconst mail-extr-x400-encoded-address-field-pattern-format
463   (purecopy "/%s=\\([^/]+\\)\\(/\\|\\'\\)"))
464
465 (defconst mail-extr-x400-encoded-address-surname-pattern
466   ;; S stands for Surname (family name).
467   (purecopy
468    (format mail-extr-x400-encoded-address-field-pattern-format "[Ss]")))
469
470 (defconst mail-extr-x400-encoded-address-given-name-pattern
471   ;; G stands for Given name.
472   (purecopy
473    (format mail-extr-x400-encoded-address-field-pattern-format "[Gg]")))
474
475 (defconst mail-extr-x400-encoded-address-full-name-pattern
476   ;; PN stands for Personal Name.  When used it represents the combination
477   ;; of the G and S fields.
478   ;; "The one system I used having this field asked it with the prompt
479   ;; `Personal Name'.  But they mapped it into G and S on outgoing real
480   ;; X.400 addresses.  As they mapped G and S into PN on incoming..."
481   (purecopy
482    (format mail-extr-x400-encoded-address-field-pattern-format "[Pp][Nn]")))
483
484 \f
485
486 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
487 ;;
488 ;; Syntax tables used for quick parsing.
489 ;;
490
491 (defconst mail-extr-address-syntax-table (make-syntax-table))
492 (defconst mail-extr-address-comment-syntax-table (make-syntax-table))
493 (defconst mail-extr-address-domain-literal-syntax-table (make-syntax-table))
494 (defconst mail-extr-address-text-comment-syntax-table (make-syntax-table))
495 (defconst mail-extr-address-text-syntax-table (make-syntax-table))
496 (mapc
497  (lambda (pair)
498    (let ((syntax-table (symbol-value (car pair))))
499      (dolist (item (cdr pair))
500        (if (eq 2 (length item))
501            ;; modifying syntax of a single character
502            (modify-syntax-entry (car item) (car (cdr item)) syntax-table)
503          ;; modifying syntax of a range of characters
504          (let ((char (nth 0 item))
505                (bound (nth 1 item))
506                (syntax (nth 2 item)))
507            (while (<= char bound)
508              (modify-syntax-entry char syntax syntax-table)
509              (setq char (1+ char))))))))
510  '((mail-extr-address-syntax-table
511     (?\000 ?\037 "w")                   ;control characters
512     (?\040       " ")                   ;SPC
513     (?! ?~       "w")                   ;printable characters
514     (?\177       "w")                   ;DEL
515     (?\t " ")
516     (?\r " ")
517     (?\n " ")
518     (?\( ".")
519     (?\) ".")
520     (?<  ".")
521     (?>  ".")
522     (?@  ".")
523     (?,  ".")
524     (?\; ".")
525     (?:  ".")
526     (?\\ "\\")
527     (?\" "\"")
528     (?.  ".")
529     (?\[ ".")
530     (?\] ".")
531     ;; % and ! aren't RFC822 characters, but it is convenient to pretend
532     (?%  ".")
533     (?!  ".") ;; this needs to be word-constituent when not in .UUCP mode
534     )
535    (mail-extr-address-comment-syntax-table
536     (?\000 ?\377 "w")
537     (?\040 " ")
538     (?\240 " ")
539     (?\t " ")
540     (?\r " ")
541     (?\n " ")
542     (?\( "\(\)")
543     (?\) "\)\(")
544     (?\\ "\\"))
545    (mail-extr-address-domain-literal-syntax-table
546     (?\000 ?\377 "w")
547     (?\040 " ")
548     (?\240 " ")
549     (?\t " ")
550     (?\r " ")
551     (?\n " ")
552     (?\[ "\(\]")                        ;??????
553     (?\] "\)\[")                        ;??????
554     (?\\ "\\"))
555    (mail-extr-address-text-comment-syntax-table
556     (?\000 ?\377 "w")
557     (?\040 " ")
558     (?\240 " ")
559     (?\t " ")
560     (?\r " ")
561     (?\n " ")
562     (?\( "\(\)")
563     (?\) "\)\(")
564     (?\[ "\(\]")
565     (?\] "\)\[")
566     (?\{ "\(\}")
567     (?\} "\)\{")
568     (?\\ "\\")
569     (?\" "\"")
570     ;; (?\' "\)\`")
571     ;; (?\` "\(\'")
572     )
573    (mail-extr-address-text-syntax-table
574     (?\000 ?\177 ".")
575     (?\200 ?\377 "w")
576     (?\040 " ")
577     (?\t " ")
578     (?\r " ")
579     (?\n " ")
580     (?A ?Z "w")
581     (?a ?z "w")
582     (?-    "w")
583     (?\}   "w")
584     (?\{   "w")
585     (?|    "w")
586     (?\'   "w")
587     (?~    "w")
588     (?0 ?9 "w"))
589    ))
590
591 \f
592 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
593 ;;
594 ;; Utility functions and macros.
595 ;;
596
597 ;; Fixme: There are Latin-1 nbsp below.  If such characters should be
598 ;; included, this is the wrong thing to do -- it should use syntax (or
599 ;; regexp char classes).
600
601 (defsubst mail-extr-skip-whitespace-forward ()
602   ;; v19 fn skip-syntax-forward is more tasteful, but not byte-coded.
603   (skip-chars-forward " \t\n\r\240"))
604
605 (defsubst mail-extr-skip-whitespace-backward ()
606   ;; v19 fn skip-syntax-backward is more tasteful, but not byte-coded.
607   (skip-chars-backward " \t\n\r\240"))
608
609
610 (defsubst mail-extr-undo-backslash-quoting (beg end)
611   (save-excursion
612     (save-restriction
613       (narrow-to-region beg end)
614       (goto-char (point-min))
615       ;; undo \ quoting
616       (while (search-forward "\\" nil t)
617         (delete-char -1)
618         (or (eobp)
619             (forward-char 1))))))
620
621 (defsubst mail-extr-nuke-char-at (pos)
622   (save-excursion
623     (goto-char pos)
624     (delete-char 1)
625     (insert ?\ )))
626
627 (put 'mail-extr-nuke-outside-range
628      'edebug-form-spec '(symbolp &optional form form atom))
629
630 (defmacro mail-extr-nuke-outside-range (list-symbol
631                                         beg-symbol end-symbol
632                                         &optional no-replace)
633   "Delete all elements outside BEG..END in LIST.
634 LIST-SYMBOL names a variable holding a list of buffer positions
635 BEG-SYMBOL and END-SYMBOL name variables delimiting a range
636 Each element of LIST-SYMBOL which lies outside of the range is
637  deleted from the list.
638 Unless NO-REPLACE is true, at each of the positions in LIST-SYMBOL
639  which lie outside of the range, one character at that position is
640  replaced with a SPC."
641   (or (memq no-replace '(t nil))
642       (error "no-replace must be t or nil, evaluable at macroexpand-time"))
643   `(let ((temp ,list-symbol)
644            ch)
645        (while temp
646          (setq ch (car temp))
647          (when (or (> ch ,end-symbol)
648                    (< ch ,beg-symbol))
649            ,@(if no-replace
650                    nil
651                  `((mail-extr-nuke-char-at ch)))
652            (setcar temp nil))
653          (setq temp (cdr temp)))
654        (setq ,list-symbol (delq nil ,list-symbol))))
655
656 (defun mail-extr-demarkerize (marker)
657   ;; if arg is a marker, destroys the marker, then returns the old value.
658   ;; otherwise returns the arg.
659   (if (markerp marker)
660       (let ((temp (marker-position marker)))
661         (set-marker marker nil)
662         temp)
663     marker))
664
665 (defun mail-extr-markerize (pos)
666   ;; coerces pos to a marker if non-nil.
667   (if (or (markerp pos) (null pos))
668       pos
669     (copy-marker pos)))
670
671 (defsubst mail-extr-safe-move-sexp (arg)
672   ;; Safely skip over one balanced sexp, if there is one.  Return t if success.
673   (condition-case error
674       (progn
675         (goto-char (or (scan-sexps (point) arg) (point)))
676         t)
677     (error
678      ;; #### kludge kludge kludge kludge kludge kludge kludge !!!
679      (if (string-equal (nth 1 error) "Unbalanced parentheses")
680          nil
681        (while t
682          (signal (car error) (cdr error)))))))
683 \f
684 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
685 ;;
686 ;; The main function to grind addresses
687 ;;
688
689 (defvar disable-initial-guessing-flag)  ; dynamic assignment
690 (defvar cbeg)                           ; dynamic assignment
691 (defvar cend)                           ; dynamic assignment
692
693 ;;;###autoload
694 (defun mail-extract-address-components (address &optional all)
695   "Given an RFC-822 address ADDRESS, extract full name and canonical address.
696 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).
697 If no name can be extracted, FULL-NAME will be nil.  Also see
698 `mail-extr-ignore-single-names'.
699
700 If the optional argument ALL is non-nil, then ADDRESS can contain zero
701 or more recipients, separated by commas, and we return a list of
702 the form ((FULL-NAME CANONICAL-ADDRESS) ...) with one element for
703 each recipient.  If ALL is nil, then if ADDRESS contains more than
704 one recipients, all but the first is ignored.
705
706 ADDRESS may be a string or a buffer.  If it is a buffer, the visible
707 \(narrowed) portion of the buffer will be interpreted as the address.
708 \(This feature exists so that the clever caller might be able to avoid
709 consing a string.)"
710   (let ((canonicalization-buffer (get-buffer-create " *canonical address*"))
711         (extraction-buffer (get-buffer-create " *extract address components*"))
712         value-list)
713
714     (with-current-buffer (get-buffer-create extraction-buffer)
715       (fundamental-mode)
716       (buffer-disable-undo extraction-buffer)
717       (set-syntax-table mail-extr-address-syntax-table)
718       (widen)
719       (erase-buffer)
720       (setq case-fold-search nil)
721
722       ;; Insert extra space at beginning to allow later replacement with <
723       ;; without having to move markers.
724       (insert ?\ )
725
726       ;; Insert the address itself.
727       (cond ((stringp address)
728              (insert address))
729             ((bufferp address)
730              (insert-buffer-substring address))
731             (t
732              (error "Invalid address: %s" address)))
733
734       (set-text-properties (point-min) (point-max) nil)
735
736       (with-current-buffer (get-buffer-create canonicalization-buffer)
737         (fundamental-mode)
738         (buffer-disable-undo canonicalization-buffer)
739         (setq case-fold-search nil))
740
741
742       ;; Unfold multiple lines.
743       (goto-char (point-min))
744       (while (re-search-forward "\\([^\\]\\(\\\\\\\\\\)*\\)\n[ \t]" nil t)
745         (replace-match "\\1 " t))
746
747       ;; Loop over addresses until we have as many as we want.
748       (while (and (or all (null value-list))
749                   (progn (goto-char (point-min))
750                          (skip-chars-forward " \t")
751                          (not (eobp))))
752         (let (char
753               end-of-address
754               <-pos >-pos @-pos colon-pos comma-pos !-pos %-pos \;-pos
755               group-:-pos group-\;-pos route-addr-:-pos
756               record-pos-symbol
757               first-real-pos last-real-pos
758               phrase-beg phrase-end
759               cbeg cend                 ; dynamically set from -voodoo
760               quote-beg quote-end
761               atom-beg atom-end
762               mbox-beg mbox-end
763               \.-ends-name
764               temp
765               ;;        name-suffix
766               fi mi li                  ; first, middle, last initial
767               saved-%-pos saved-!-pos saved-@-pos
768               domain-pos \.-pos insert-point
769               ;;        mailbox-name-processed-flag
770               disable-initial-guessing-flag) ; dynamically set from -voodoo
771
772           (set-syntax-table mail-extr-address-syntax-table)
773           (goto-char (point-min))
774
775           ;; Insert extra space at beginning to allow later replacement with <
776           ;; without having to move markers.
777           (or (eq (following-char) ?\ )
778               (insert ?\ ))
779
780           ;; First pass grabs useful information about address.
781           (while (progn
782                    (mail-extr-skip-whitespace-forward)
783                    (not (eobp)))
784             (setq char (char-after (point)))
785             (or first-real-pos
786                 (if (not (eq char ?\())
787                     (setq first-real-pos (point))))
788             (cond
789              ;; comment
790              ((eq char ?\()
791               (set-syntax-table mail-extr-address-comment-syntax-table)
792               ;; only record the first non-empty comment's position
793               (if (and (not cbeg)
794                        (save-excursion
795                          (forward-char 1)
796                          (mail-extr-skip-whitespace-forward)
797                          (not (eq ?\) (char-after (point))))))
798                   (setq cbeg (point)))
799               ;; TODO: don't record if unbalanced
800               (or (mail-extr-safe-move-sexp 1)
801                   (forward-char 1))
802               (set-syntax-table mail-extr-address-syntax-table)
803               (if (and cbeg
804                        (not cend))
805                   (setq cend (point))))
806              ;; quoted text
807              ((eq char ?\")
808               ;; only record the first non-empty quote's position
809               (if (and (not quote-beg)
810                        (save-excursion
811                          (forward-char 1)
812                          (mail-extr-skip-whitespace-forward)
813                          (not (eq ?\" (char-after (point))))))
814                   (setq quote-beg (point)))
815               ;; TODO: don't record if unbalanced
816               (or (mail-extr-safe-move-sexp 1)
817                   (forward-char 1))
818               (if (and quote-beg
819                        (not quote-end))
820                   (setq quote-end (point))))
821              ;; domain literals
822              ((eq char ?\[)
823               (set-syntax-table mail-extr-address-domain-literal-syntax-table)
824               (or (mail-extr-safe-move-sexp 1)
825                   (forward-char 1))
826               (set-syntax-table mail-extr-address-syntax-table))
827              ;; commas delimit addresses when outside < > pairs.
828              ((and (eq char ?,)
829                    (or (and (null <-pos)
830                             ;; Handle ROUTE-ADDR address that is missing its <.
831                             (not (eq ?@ (char-after (1+ (point))))))
832                        (and >-pos
833                             ;; handle weird munged addresses
834                             ;; BUG FIX: This test was reversed.  Thanks to the
835                             ;; brilliant Rod Whitby <rwhitby@research.canon.oz.au>
836                             ;; for discovering this!
837                             (< (car (last <-pos)) (car >-pos)))))
838               ;; The argument contains more than one address.
839               ;; Temporarily hide everything after this one.
840               (setq end-of-address (copy-marker (1+ (point)) t))
841               (narrow-to-region (point-min) (1+ (point)))
842               (delete-char 1)
843               (setq char ?\() ; HAVE I NO SHAME??
844               )
845              ;; record the position of various interesting chars, determine
846              ;; legality later.
847              ((setq record-pos-symbol
848                     (cdr (assq char
849                                '((?< . <-pos) (?> . >-pos) (?@ . @-pos)
850                                  (?: . colon-pos) (?, . comma-pos) (?! . !-pos)
851                                  (?% . %-pos) (?\; . \;-pos)))))
852               (set record-pos-symbol
853                    (cons (point) (symbol-value record-pos-symbol)))
854               (forward-char 1))
855              ((eq char ?.)
856               (forward-char 1))
857              ((memq char '(
858                            ;; comment terminator illegal
859                            ?\)
860                            ;; domain literal terminator illegal
861                            ?\]
862                            ;; \ allowed only within quoted strings,
863                            ;; domain literals, and comments
864                            ?\\
865                            ))
866               (mail-extr-nuke-char-at (point))
867               (forward-char 1))
868              (t
869               (forward-word 1)))
870             (or (eq char ?\()
871                 ;; At the end of first address of a multiple address header.
872                 (and (eq char ?,)
873                      (eobp))
874                 (setq last-real-pos (point))))
875
876           ;; Use only the leftmost <, if any.  Replace all others with spaces.
877           (while (cdr <-pos)
878             (mail-extr-nuke-char-at (car <-pos))
879             (setq <-pos (cdr <-pos)))
880
881           ;; Use only the rightmost >, if any.  Replace all others with spaces.
882           (while (cdr >-pos)
883             (mail-extr-nuke-char-at (nth 1 >-pos))
884             (setcdr >-pos (nthcdr 2 >-pos)))
885
886           ;; If multiple @s and a :, but no < and >, insert around buffer.
887           ;; Example: @foo.bar.dom,@xxx.yyy.zzz:mailbox@aaa.bbb.ccc
888           ;; This commonly happens on the UUCP "From " line.  Ugh.
889           (when (and (> (length @-pos) 1)
890                       (eq 1 (length colon-pos)) ;TODO: check if between last two @s
891                       (not \;-pos)
892                       (not <-pos))
893             (goto-char (point-min))
894             (delete-char 1)
895             (setq <-pos (list (point)))
896             (insert ?<))
897
898           ;; If < but no >, insert > in rightmost possible position
899           (when (and <-pos (null >-pos))
900             (goto-char (point-max))
901             (setq >-pos (list (point)))
902             (insert ?>))
903
904           ;; If > but no <, replace > with space.
905           (when (and >-pos (null <-pos))
906             (mail-extr-nuke-char-at (car >-pos))
907             (setq >-pos nil))
908
909           ;; Turn >-pos and <-pos into non-lists
910           (setq >-pos (car >-pos)
911                 <-pos (car <-pos))
912
913           ;; Trim other punctuation lists of items outside < > pair to handle
914           ;; stupid MTAs.
915           (when <-pos                   ; don't need to check >-pos also
916             ;; handle bozo software that violates RFC 822 by sticking
917             ;; punctuation marks outside of a < > pair
918             (mail-extr-nuke-outside-range @-pos <-pos >-pos t)
919             ;; RFC 822 says nothing about these two outside < >, but
920             ;; remove those positions from the lists to make things
921             ;; easier.
922             (mail-extr-nuke-outside-range !-pos <-pos >-pos t)
923             (mail-extr-nuke-outside-range %-pos <-pos >-pos t))
924
925           ;; Check for : that indicates GROUP list and for : part of
926           ;; ROUTE-ADDR spec.
927           ;; Can't possibly be more than two :.  Nuke any extra.
928           (while colon-pos
929             (setq temp (car colon-pos)
930                   colon-pos (cdr colon-pos))
931             (cond ((and <-pos >-pos
932                         (> temp <-pos)
933                         (< temp >-pos))
934                    (if (or route-addr-:-pos
935                            (< (length @-pos) 2)
936                            (> temp (car @-pos))
937                            (< temp (nth 1 @-pos)))
938                        (mail-extr-nuke-char-at temp)
939                      (setq route-addr-:-pos temp)))
940                   ((or (not <-pos)
941                        (and <-pos
942                             (< temp <-pos)))
943                    (setq group-:-pos temp))))
944
945           ;; Nuke any ; that is in or to the left of a < > pair or to the left
946           ;; of a GROUP starting :.  Also, there may only be one ;.
947           (while \;-pos
948             (setq temp (car \;-pos)
949                   \;-pos (cdr \;-pos))
950             (cond ((and <-pos >-pos
951                         (> temp <-pos)
952                         (< temp >-pos))
953                    (mail-extr-nuke-char-at temp))
954                   ((and (or (not group-:-pos)
955                             (> temp group-:-pos))
956                         (not group-\;-pos))
957                    (setq group-\;-pos temp))))
958
959           ;; Nuke unmatched GROUP syntax characters.
960           (when (and group-:-pos (not group-\;-pos))
961             ;; *** Do I really need to erase it?
962             (mail-extr-nuke-char-at group-:-pos)
963             (setq group-:-pos nil))
964           (when (and group-\;-pos (not group-:-pos))
965             ;; *** Do I really need to erase it?
966             (mail-extr-nuke-char-at group-\;-pos)
967             (setq group-\;-pos nil))
968
969           ;; Handle junk like ";@host.company.dom" that sendmail adds.
970           ;; **** should I remember comment positions?
971           (when group-\;-pos
972             ;; this is fine for now
973             (mail-extr-nuke-outside-range !-pos group-:-pos group-\;-pos t)
974             (mail-extr-nuke-outside-range @-pos group-:-pos group-\;-pos t)
975             (mail-extr-nuke-outside-range %-pos group-:-pos group-\;-pos t)
976             (mail-extr-nuke-outside-range comma-pos group-:-pos group-\;-pos t)
977             (and last-real-pos
978                  (> last-real-pos (1+ group-\;-pos))
979                  (setq last-real-pos (1+ group-\;-pos)))
980             ;; *** This may be wrong:
981             (and cend
982                  (> cend group-\;-pos)
983                  (setq cend nil
984                        cbeg nil))
985             (and quote-end
986                  (> quote-end group-\;-pos)
987                  (setq quote-end nil
988                        quote-beg nil))
989             ;; This was both wrong and unnecessary:
990             ;;(narrow-to-region (point-min) group-\;-pos)
991
992             ;; *** The entire handling of GROUP addresses seems rather lame.
993             ;; *** It deserves a complete rethink, except that these addresses
994             ;; *** are hardly ever seen.
995             )
996
997           ;; Any commas must be between < and : of ROUTE-ADDR.  Nuke any
998           ;; others.
999           ;; Hell, go ahead and nuke all of the commas.
1000           ;; **** This will cause problems when we start handling commas in
1001           ;; the PHRASE part .... no it won't ... yes it will ... ?????
1002           (mail-extr-nuke-outside-range comma-pos 1 1)
1003
1004           ;; can only have multiple @s inside < >.  The fact that some MTAs
1005           ;; put de-bracketed ROUTE-ADDRs in the UUCP-style "From " line is
1006           ;; handled above.
1007
1008           ;; Locate PHRASE part of ROUTE-ADDR.
1009           (when <-pos
1010             (goto-char <-pos)
1011             (mail-extr-skip-whitespace-backward)
1012             (setq phrase-end (point))
1013             (goto-char (or ;;group-:-pos
1014                         (point-min)))
1015             (mail-extr-skip-whitespace-forward)
1016             (if (< (point) phrase-end)
1017                 (setq phrase-beg (point))
1018               (setq phrase-end nil)))
1019
1020           ;; handle ROUTE-ADDRS with real ROUTEs.
1021           ;; If there are multiple @s, then we assume ROUTE-ADDR syntax, and
1022           ;; any % or ! must be semantically meaningless.
1023           ;; TODO: do this processing into canonicalization buffer
1024           (when route-addr-:-pos
1025             (setq !-pos nil
1026                   %-pos nil
1027                   >-pos (copy-marker >-pos)
1028                   route-addr-:-pos (copy-marker route-addr-:-pos))
1029             (goto-char >-pos)
1030             (insert-before-markers ?X)
1031             (goto-char (car @-pos))
1032             (while (setq @-pos (cdr @-pos))
1033               (delete-char 1)
1034               (setq %-pos (cons (point-marker) %-pos))
1035               (insert "%")
1036               (goto-char (1- >-pos))
1037               (save-excursion
1038                 (insert-buffer-substring extraction-buffer
1039                                          (car @-pos) route-addr-:-pos)
1040                 (delete-region (car @-pos) route-addr-:-pos))
1041               (or (cdr @-pos)
1042                   (setq saved-@-pos (list (point)))))
1043             (setq @-pos saved-@-pos)
1044             (goto-char >-pos)
1045             (delete-char -1)
1046             (mail-extr-nuke-char-at route-addr-:-pos)
1047             (mail-extr-demarkerize route-addr-:-pos)
1048             (setq route-addr-:-pos nil
1049                   >-pos (mail-extr-demarkerize >-pos)
1050                   %-pos (mapcar 'mail-extr-demarkerize %-pos)))
1051
1052           ;; de-listify @-pos
1053           (setq @-pos (car @-pos))
1054
1055           ;; TODO: remove comments in the middle of an address
1056
1057           (with-current-buffer canonicalization-buffer
1058             (widen)
1059             (erase-buffer)
1060             (insert-buffer-substring extraction-buffer)
1061
1062             (if <-pos
1063                 (narrow-to-region (progn
1064                                     (goto-char (1+ <-pos))
1065                                     (mail-extr-skip-whitespace-forward)
1066                                     (point))
1067                                   >-pos)
1068               (if (and first-real-pos last-real-pos)
1069                   (narrow-to-region first-real-pos last-real-pos)
1070                 ;; ****** Oh no!  What if the address is completely empty!
1071                 ;; *** Is this correct?
1072                 (narrow-to-region (point-max) (point-max))))
1073
1074             (and @-pos %-pos
1075                  (mail-extr-nuke-outside-range %-pos (point-min) @-pos))
1076             (and %-pos !-pos
1077                  (mail-extr-nuke-outside-range !-pos (point-min) (car %-pos)))
1078             (and @-pos !-pos (not %-pos)
1079                  (mail-extr-nuke-outside-range !-pos (point-min) @-pos))
1080
1081             ;; Error condition:?? (and %-pos (not @-pos))
1082
1083             ;; WARNING: THIS CODE IS DUPLICATED BELOW.
1084             (when (and %-pos (not @-pos))
1085               (goto-char (car %-pos))
1086               (delete-char 1)
1087               (setq @-pos (point))
1088               (insert "@")
1089               (setq %-pos (cdr %-pos)))
1090
1091             (when (and mail-extr-mangle-uucp !-pos)
1092               ;; **** I don't understand this save-restriction and the
1093               ;; narrow-to-region inside it.  Why did I do that?
1094               (save-restriction
1095                 (cond ((and @-pos
1096                             mail-extr-@-binds-tighter-than-!)
1097                        (goto-char @-pos)
1098                        (setq %-pos (cons (point) %-pos)
1099                              @-pos nil)
1100                        (delete-char 1)
1101                        (insert "%")
1102                        (setq insert-point (point-max)))
1103                       (mail-extr-@-binds-tighter-than-!
1104                        (setq insert-point (point-max)))
1105                       (%-pos
1106                        (setq insert-point (car (last %-pos))
1107                              saved-%-pos (mapcar 'mail-extr-markerize %-pos)
1108                              %-pos nil
1109                              @-pos (mail-extr-markerize @-pos)))
1110                       (@-pos
1111                        (setq insert-point @-pos)
1112                        (setq @-pos (mail-extr-markerize @-pos)))
1113                       (t
1114                        (setq insert-point (point-max))))
1115                 (narrow-to-region (point-min) insert-point)
1116                 (setq saved-!-pos (car !-pos))
1117                 (while !-pos
1118                   (goto-char (point-max))
1119                   (cond ((and (not @-pos)
1120                               (not (cdr !-pos)))
1121                          (setq @-pos (point))
1122                          (insert-before-markers "@ "))
1123                         (t
1124                          (setq %-pos (cons (point) %-pos))
1125                          (insert-before-markers "% ")))
1126                   (backward-char 1)
1127                   (insert-buffer-substring
1128                    (current-buffer)
1129                    (if (nth 1 !-pos)
1130                        (1+ (nth 1 !-pos))
1131                      (point-min))
1132                    (car !-pos))
1133                   (delete-char 1)
1134                   (or (save-excursion
1135                         (mail-extr-safe-move-sexp -1)
1136                         (mail-extr-skip-whitespace-backward)
1137                         (eq ?. (preceding-char)))
1138                       (insert-before-markers
1139                        (if (save-excursion
1140                              (mail-extr-skip-whitespace-backward)
1141                              (eq ?. (preceding-char)))
1142                            ""
1143                          ".")
1144                        "uucp"))
1145                   (setq !-pos (cdr !-pos))))
1146               (and saved-%-pos
1147                    (setq %-pos (append (mapcar 'mail-extr-demarkerize
1148                                                saved-%-pos)
1149                                        %-pos)))
1150               (setq @-pos (mail-extr-demarkerize @-pos))
1151               (narrow-to-region (1+ saved-!-pos) (point-max)))
1152
1153             ;; WARNING: THIS CODE IS DUPLICATED ABOVE.
1154             (when (and %-pos (not @-pos))
1155               (goto-char (car %-pos))
1156               (delete-char 1)
1157               (setq @-pos (point))
1158               (insert "@")
1159               (setq %-pos (cdr %-pos)))
1160
1161             (when (setq %-pos (nreverse %-pos)) ; implies @-pos valid
1162               (setq temp %-pos)
1163               (catch 'truncated
1164                 (while temp
1165                   (goto-char (or (nth 1 temp)
1166                                  @-pos))
1167                   (mail-extr-skip-whitespace-backward)
1168                   (save-excursion
1169                     (mail-extr-safe-move-sexp -1)
1170                     (setq domain-pos (point))
1171                     (mail-extr-skip-whitespace-backward)
1172                     (setq \.-pos (eq ?. (preceding-char))))
1173                   (when (and \.-pos
1174                              ;; #### string consing
1175                              (let ((s (intern-soft
1176                                        (buffer-substring domain-pos (point))
1177                                        mail-extr-all-top-level-domains)))
1178                                (and s (get s 'domain-name))))
1179                     (narrow-to-region (point-min) (point))
1180                     (goto-char (car temp))
1181                     (delete-char 1)
1182                     (setq @-pos (point))
1183                     (setcdr temp nil)
1184                     (setq %-pos (delq @-pos %-pos))
1185                     (insert "@")
1186                     (throw 'truncated t))
1187                   (setq temp (cdr temp)))))
1188             (setq mbox-beg (point-min)
1189                   mbox-end (if %-pos (car %-pos)
1190                              (or @-pos
1191                                  (point-max))))
1192
1193             (when @-pos
1194               ;; Make the domain-name part lowercase since it's case
1195               ;; insensitive anyway.
1196               (downcase-region (1+ @-pos) (point-max))))
1197
1198           ;; Done canonicalizing address.
1199           ;; We are now back in extraction-buffer.
1200
1201           ;; Decide what part of the address to search to find the full name.
1202           (cond (
1203                  ;; Example: "First M. Last" <fml@foo.bar.dom>
1204                  (and phrase-beg
1205                       (eq quote-beg phrase-beg)
1206                       (<= quote-end phrase-end))
1207                  (narrow-to-region (1+ quote-beg) (1- quote-end))
1208                  (mail-extr-undo-backslash-quoting (point-min) (point-max)))
1209
1210                 ;; Example: First Last <fml@foo.bar.dom>
1211                 (phrase-beg
1212                  (narrow-to-region phrase-beg phrase-end))
1213
1214                 ;; Example: fml@foo.bar.dom (First M. Last)
1215                 (cbeg
1216                  (narrow-to-region (1+ cbeg) (1- cend))
1217                  (mail-extr-undo-backslash-quoting (point-min) (point-max))
1218
1219                  ;; Deal with spacing problems
1220                  (goto-char (point-min))
1221 ;;;          (cond ((not (search-forward " " nil t))
1222 ;;;                 (goto-char (point-min))
1223 ;;;                 (cond ((search-forward "_" nil t)
1224 ;;;                        ;; Handle the *idiotic* use of underlines as spaces.
1225 ;;;                        ;; Example: fml@foo.bar.dom (First_M._Last)
1226 ;;;                        (goto-char (point-min))
1227 ;;;                        (while (search-forward "_" nil t)
1228 ;;;                          (replace-match " " t)))
1229 ;;;                       ((search-forward "." nil t)
1230 ;;;                        ;; Fix . used as space
1231 ;;;                        ;; Example: danj1@cb.att.com (daniel.jacobson)
1232 ;;;                        (goto-char (point-min))
1233 ;;;                        (while (re-search-forward mail-extr-bad-dot-pattern nil t)
1234 ;;;                          (replace-match "\\1 \\2" t))))))
1235                  )
1236
1237                 ;; Otherwise we try to get the name from the mailbox portion
1238                 ;; of the address.
1239                 ;; Example: First_M_Last@foo.bar.dom
1240                 (t
1241                  ;; *** Work in canon buffer instead?  No, can't.  Hmm.
1242                  (goto-char (point-max))
1243                  (narrow-to-region (point) (point))
1244                  (insert-buffer-substring canonicalization-buffer
1245                                           mbox-beg mbox-end)
1246                  (goto-char (point-min))
1247
1248                  ;; Example: First_Last.XXX@foo.bar.dom
1249                  (setq \.-ends-name (re-search-forward "[_0-9]" nil t))
1250
1251                  (goto-char (point-min))
1252
1253                  (if (not mail-extr-mangle-uucp)
1254                      (modify-syntax-entry ?! "w" (syntax-table)))
1255
1256                  (while (progn
1257                           (mail-extr-skip-whitespace-forward)
1258                           (not (eobp)))
1259                    (setq char (char-after (point)))
1260                    (cond
1261                     ((eq char ?\")
1262                      (setq quote-beg (point))
1263                      (or (mail-extr-safe-move-sexp 1)
1264                          ;; TODO: handle this error condition!!!!!
1265                          (forward-char 1))
1266                      ;; take into account deletions
1267                      (setq quote-end (- (point) 2))
1268                      (save-excursion
1269                        (backward-char 1)
1270                        (delete-char 1)
1271                        (goto-char quote-beg)
1272                        (or (eobp)
1273                            (delete-char 1)))
1274                      (mail-extr-undo-backslash-quoting quote-beg quote-end)
1275                      (or (eq ?\  (char-after (point)))
1276                          (insert " "))
1277                      ;;          (setq mailbox-name-processed-flag t)
1278                      (setq \.-ends-name t))
1279                     ((eq char ?.)
1280                      (if (memq (char-after (1+ (point))) '(?_ ?=))
1281                          (progn
1282                            (forward-char 1)
1283                            (delete-char 1)
1284                            (insert ?\ ))
1285                        (if \.-ends-name
1286                            (narrow-to-region (point-min) (point))
1287                          (delete-char 1)
1288                          (insert " ")))
1289                      ;;          (setq mailbox-name-processed-flag t)
1290                      )
1291                     ((memq (char-syntax char) '(?. ?\\))
1292                      (delete-char 1)
1293                      (insert " ")
1294                      ;;          (setq mailbox-name-processed-flag t)
1295                      )
1296                     (t
1297                      (setq atom-beg (point))
1298                      (forward-word 1)
1299                      (setq atom-end (point))
1300                      (goto-char atom-beg)
1301                      (save-restriction
1302                        (narrow-to-region atom-beg atom-end)
1303                        (cond
1304
1305                         ;; Handle X.400 addresses encoded in RFC-822.
1306                         ;; *** Shit!  This has to handle the case where it is
1307                         ;; *** embedded in a quote too!
1308                         ;; *** Shit!  The input is being broken up into atoms
1309                         ;; *** by periods!
1310                         ((looking-at mail-extr-x400-encoded-address-pattern)
1311
1312                          ;; Copy the contents of the individual fields that
1313                          ;; might hold name data to the beginning.
1314                          (mapc
1315                           (lambda (field-pattern)
1316                             (when
1317                                 (save-excursion
1318                                   (re-search-forward field-pattern nil t))
1319                               (insert-buffer-substring (current-buffer)
1320                                                        (match-beginning 1)
1321                                                        (match-end 1))
1322                               (insert " ")))
1323                           (list mail-extr-x400-encoded-address-given-name-pattern
1324                                 mail-extr-x400-encoded-address-surname-pattern
1325                                 mail-extr-x400-encoded-address-full-name-pattern))
1326
1327                          ;; Discard the rest, since it contains stuff like
1328                          ;; routing information, not part of a name.
1329                          (mail-extr-skip-whitespace-backward)
1330                          (delete-region (point) (point-max))
1331
1332                          ;; Handle periods used for spacing.
1333                          (while (re-search-forward mail-extr-bad-dot-pattern nil t)
1334                            (replace-match "\\1 \\2" t))
1335
1336                          ;;                  (setq mailbox-name-processed-flag t)
1337                          )
1338
1339                         ;; Handle normal addresses.
1340                         (t
1341                          (goto-char (point-min))
1342                          ;; Handle _ and = used for spacing.
1343                          (while (re-search-forward "\\([^_=]+\\)[_=]" nil t)
1344                            (replace-match "\\1 " t)
1345                            ;;                  (setq mailbox-name-processed-flag t)
1346                            )
1347                          (goto-char (point-max))))))))
1348
1349                  ;; undo the dirty deed
1350                  (if (not mail-extr-mangle-uucp)
1351                      (modify-syntax-entry ?! "." (syntax-table)))
1352                  ;;
1353                  ;; If we derived the name from the mailbox part of the address,
1354                  ;; and we only got one word out of it, don't treat that as a
1355                  ;; name.  "foo@bar" --> (nil "foo@bar"), not ("foo" "foo@bar")
1356                  ;; (if (not mailbox-name-processed-flag)
1357                  ;;     (delete-region (point-min) (point-max)))
1358                  ))
1359
1360           (set-syntax-table mail-extr-address-text-syntax-table)
1361
1362           (mail-extr-voodoo mbox-beg mbox-end canonicalization-buffer)
1363           (goto-char (point-min))
1364
1365           ;; If name is "First Last" and userid is "F?L", then assume
1366           ;; the middle initial is the second letter in the userid.
1367           ;; Initial code by Jamie Zawinski <jwz@lucid.com>
1368           ;; *** Make it work when there's a suffix as well.
1369           (goto-char (point-min))
1370           (when (and mail-extr-guess-middle-initial
1371                      (not disable-initial-guessing-flag)
1372                      (eq 3 (- mbox-end mbox-beg))
1373                      (progn
1374                        (goto-char (point-min))
1375                        (looking-at mail-extr-two-name-pattern)))
1376             (setq fi (char-after (match-beginning 0))
1377                   li (char-after (match-beginning 3)))
1378             (with-current-buffer canonicalization-buffer
1379               ;; char-equal is ignoring case here, so no need to upcase
1380               ;; or downcase.
1381               (let ((case-fold-search t))
1382                 (and (char-equal fi (char-after mbox-beg))
1383                      (char-equal li (char-after (1- mbox-end)))
1384                      (setq mi (char-after (1+ mbox-beg))))))
1385             (when (and mi
1386                        ;; TODO: use better table than syntax table
1387                        (eq ?w (char-syntax mi)))
1388               (goto-char (match-beginning 3))
1389               (insert (upcase mi) ". ")))
1390
1391           ;; Nuke name if it is the same as mailbox name.
1392           (let ((buffer-length (- (point-max) (point-min)))
1393                 (i 0)
1394                 (names-match-flag t))
1395             (when (and (> buffer-length 0)
1396                        (eq buffer-length (- mbox-end mbox-beg)))
1397               (goto-char (point-max))
1398               (insert-buffer-substring canonicalization-buffer
1399                                        mbox-beg mbox-end)
1400               (while (and names-match-flag
1401                           (< i buffer-length))
1402                 (or (eq (downcase (char-after (+ i (point-min))))
1403                         (downcase
1404                          (char-after (+ i buffer-length (point-min)))))
1405                     (setq names-match-flag nil))
1406                 (setq i (1+ i)))
1407               (delete-region (+ (point-min) buffer-length) (point-max))
1408               (if names-match-flag
1409                   (narrow-to-region (point) (point)))))
1410
1411           ;; Nuke name if it's just one word.
1412           (goto-char (point-min))
1413           (and mail-extr-ignore-single-names
1414                (not (re-search-forward "[- ]" nil t))
1415                (narrow-to-region (point) (point)))
1416
1417           ;; Record the result
1418           (setq value-list
1419                 (cons (list (if (not (= (point-min) (point-max)))
1420                                 (buffer-string))
1421                             (with-current-buffer canonicalization-buffer
1422                               (if (not (= (point-min) (point-max)))
1423                                   (buffer-string))))
1424                       value-list))
1425
1426           ;; Unless one address is all we wanted,
1427           ;; delete this one from extraction-buffer
1428           ;; and get ready to extract the next address.
1429           (when all
1430             (if end-of-address
1431                 (narrow-to-region 1 end-of-address)
1432               (widen))
1433             (delete-region (point-min) (point-max))
1434             (widen))
1435           )))
1436     (if all (nreverse value-list) (car value-list))
1437     ))
1438
1439 (defun mail-extr-voodoo (mbox-beg mbox-end canonicalization-buffer)
1440   (let ((word-count 0)
1441         (case-fold-search nil)
1442         mixed-case-flag lower-case-flag ;;upper-case-flag
1443         suffix-flag last-name-comma-flag
1444         ;;cbeg cend
1445         initial
1446         begin-again-flag
1447         drop-this-word-if-trailing-flag
1448         drop-last-word-if-trailing-flag
1449         word-found-flag
1450         this-word-beg last-word-beg
1451         name-beg name-end
1452         name-done-flag
1453         )
1454     (save-excursion
1455       (set-syntax-table mail-extr-address-text-syntax-table)
1456
1457       ;; Get rid of comments.
1458       (goto-char (point-min))
1459       (while (not (eobp))
1460         ;; Initialize for this iteration of the loop.
1461         (skip-chars-forward "^({[\"'`")
1462         (let ((cbeg (point)))
1463           (set-syntax-table mail-extr-address-text-comment-syntax-table)
1464           (if (memq (following-char) '(?\' ?\`))
1465               (search-forward "'" nil 'move
1466                               (if (eq ?\' (following-char)) 2 1))
1467             (or (mail-extr-safe-move-sexp 1)
1468                 (goto-char (point-max))))
1469           (set-syntax-table mail-extr-address-text-syntax-table)
1470           (when (eq (char-after cbeg) ?\()
1471             ;; Delete the comment itself.
1472             (delete-region cbeg (point))
1473             ;; Canonicalize whitespace where the comment was.
1474             (skip-chars-backward " \t")
1475             (if (looking-at "\\([ \t]+$\\|[ \t]+,\\)")
1476                 (replace-match "")
1477               (setq cbeg (point))
1478               (skip-chars-forward " \t")
1479               (if (bobp)
1480                   (delete-region (point) cbeg)
1481                 (just-one-space))))))
1482
1483       ;; This was moved above.
1484       ;; Fix . used as space
1485       ;; But it belongs here because it occurs not only as
1486       ;;   rypens@reks.uia.ac.be (Piet.Rypens)
1487       ;; but also as
1488       ;;   "Piet.Rypens" <rypens@reks.uia.ac.be>
1489       ;;(goto-char (point-min))
1490       ;;(while (re-search-forward mail-extr-bad-dot-pattern nil t)
1491       ;;  (replace-match "\\1 \\2" t))
1492
1493       (unless (search-forward " " nil t)
1494         (goto-char (point-min))
1495         (cond ((search-forward "_" nil t)
1496                ;; Handle the *idiotic* use of underlines as spaces.
1497                ;; Example: fml@foo.bar.dom (First_M._Last)
1498                (goto-char (point-min))
1499                (while (search-forward "_" nil t)
1500                  (replace-match " " t)))
1501               ((search-forward "." nil t)
1502                ;; Fix . used as space
1503                ;; Example: danj1@cb.att.com (daniel.jacobson)
1504                (goto-char (point-min))
1505                (while (re-search-forward mail-extr-bad-dot-pattern nil t)
1506                  (replace-match "\\1 \\2" t)))))
1507
1508       ;; Loop over the words (and other junk) in the name.
1509       (goto-char (point-min))
1510       (while (not name-done-flag)
1511
1512         (when word-found-flag
1513           ;; Last time through this loop we skipped over a word.
1514           (setq last-word-beg this-word-beg)
1515           (setq drop-last-word-if-trailing-flag
1516                 drop-this-word-if-trailing-flag)
1517           (setq word-found-flag nil))
1518
1519         (when begin-again-flag
1520           ;; Last time through the loop we found something that
1521           ;; indicates we should pretend we are beginning again from
1522           ;; the start.
1523           (setq word-count 0)
1524           (setq last-word-beg nil)
1525           (setq drop-last-word-if-trailing-flag nil)
1526           (setq mixed-case-flag nil)
1527           (setq lower-case-flag nil)
1528           ;;           (setq upper-case-flag nil)
1529           (setq begin-again-flag nil))
1530
1531         ;; Initialize for this iteration of the loop.
1532         (mail-extr-skip-whitespace-forward)
1533         (if (eq word-count 0) (narrow-to-region (point) (point-max)))
1534         (setq this-word-beg (point))
1535         (setq drop-this-word-if-trailing-flag nil)
1536
1537         ;; Decide what to do based on what we are looking at.
1538         (cond
1539
1540          ;; Delete title
1541          ((and (eq word-count 0)
1542                (looking-at mail-extr-full-name-prefixes))
1543           (goto-char (match-end 0))
1544           (narrow-to-region (point) (point-max)))
1545
1546          ;; Stop after name suffix
1547          ((and (>= word-count 2)
1548                (looking-at mail-extr-full-name-suffix-pattern))
1549           (mail-extr-skip-whitespace-backward)
1550           (setq suffix-flag (point))
1551           (if (eq ?, (following-char))
1552               (forward-char 1)
1553             (insert ?,))
1554           ;; Enforce at least one space after comma
1555           (or (eq ?\  (following-char))
1556               (insert ?\ ))
1557           (mail-extr-skip-whitespace-forward)
1558           (cond ((memq (following-char) '(?j ?J ?s ?S))
1559                  (capitalize-word 1)
1560                  (if (eq (following-char) ?.)
1561                      (forward-char 1)
1562                    (insert ?.)))
1563                 (t
1564                  (upcase-word 1)))
1565           (setq word-found-flag t)
1566           (setq name-done-flag t))
1567
1568          ;; Handle SCA names
1569          ((looking-at "MKA \\(.+\\)")   ; "Mundanely Known As"
1570           (goto-char (match-beginning 1))
1571           (narrow-to-region (point) (point-max))
1572           (setq begin-again-flag t))
1573
1574          ;; Check for initial last name followed by comma
1575          ((and (eq ?, (following-char))
1576                (eq word-count 1))
1577           (forward-char 1)
1578           (setq last-name-comma-flag t)
1579           (or (eq ?\  (following-char))
1580               (insert ?\ )))
1581
1582          ;; Stop before trailing comma-separated comment
1583          ;; THIS CASE MUST BE AFTER THE PRECEDING CASES.
1584          ;; *** This case is redundant???
1585          ;;((eq ?, (following-char))
1586          ;; (setq name-done-flag t))
1587
1588          ;; Delete parenthesized/quoted comment/nickname
1589          ((memq (following-char) '(?\( ?\{ ?\[ ?\" ?\' ?\`))
1590           (setq cbeg (point))
1591           (set-syntax-table mail-extr-address-text-comment-syntax-table)
1592           (cond ((memq (following-char) '(?\' ?\`))
1593                  (or (search-forward "'" nil t
1594                                      (if (eq ?\' (following-char)) 2 1))
1595                      (delete-char 1)))
1596                 (t
1597                  (or (mail-extr-safe-move-sexp 1)
1598                      (goto-char (point-max)))))
1599           (set-syntax-table mail-extr-address-text-syntax-table)
1600           (setq cend (point))
1601           (cond
1602            ;; Handle case of entire name being quoted
1603            ((and (eq word-count 0)
1604                  (looking-at " *\\'")
1605                  (>= (- cend cbeg) 2))
1606             (narrow-to-region (1+ cbeg) (1- cend))
1607             (goto-char (point-min)))
1608            (t
1609             ;; Handle case of quoted initial
1610             (if (and (or (= 3 (- cend cbeg))
1611                          (and (= 4 (- cend cbeg))
1612                               (eq ?. (char-after (+ 2 cbeg)))))
1613                      (not (looking-at " *\\'")))
1614                 (setq initial (char-after (1+ cbeg)))
1615               (setq initial nil))
1616             (delete-region cbeg cend)
1617             (if initial
1618                 (insert initial ". ")))))
1619
1620          ;; Handle *Stupid* VMS date stamps
1621          ((looking-at mail-extr-stupid-vms-date-stamp-pattern)
1622           (replace-match "" t))
1623
1624          ;; Handle Chinese characters.
1625          ((looking-at mail-extr-hz-embedded-gb-encoded-chinese-pattern)
1626           (goto-char (match-end 0))
1627           (setq word-found-flag t))
1628
1629          ;; Skip initial garbage characters.
1630          ;; THIS CASE MUST BE AFTER THE PRECEDING CASES.
1631          ((and (eq word-count 0)
1632                (looking-at mail-extr-leading-garbage))
1633           (goto-char (match-end 0))
1634           ;; *** Skip backward over these???
1635           ;; (skip-chars-backward "& \"")
1636           (narrow-to-region (point) (point-max)))
1637
1638          ;; Various stopping points
1639          ((or
1640
1641            ;; Stop before ALL CAPS acronyms, if preceded by mixed-case
1642            ;; words.  Example: XT-DEM.
1643            (and (>= word-count 2)
1644                 mixed-case-flag
1645                 (looking-at mail-extr-weird-acronym-pattern)
1646                 (not (looking-at mail-extr-roman-numeral-pattern)))
1647
1648            ;; Stop before trailing alternative address
1649            (looking-at mail-extr-alternative-address-pattern)
1650
1651            ;; Stop before trailing comment not introduced by comma
1652            ;; THIS CASE MUST BE AFTER AN EARLIER CASE.
1653            (looking-at mail-extr-trailing-comment-start-pattern)
1654
1655            ;; Stop before telephone numbers
1656            (and (>= word-count 1)
1657                 (looking-at mail-extr-telephone-extension-pattern)))
1658           (setq name-done-flag t))
1659
1660          ;; Delete ham radio call signs
1661          ((looking-at mail-extr-ham-call-sign-pattern)
1662           (delete-region (match-beginning 0) (match-end 0)))
1663
1664          ;; Fixup initials
1665          ((looking-at mail-extr-initial-pattern)
1666           (or (eq (following-char) (upcase (following-char)))
1667               (setq lower-case-flag t))
1668           (forward-char 1)
1669           (if (eq ?. (following-char))
1670               (forward-char 1)
1671             (insert ?.))
1672           (or (eq ?\  (following-char))
1673               (insert ?\ ))
1674           (setq word-found-flag t))
1675
1676          ;; Handle BITNET LISTSERV list names.
1677          ((and (eq word-count 0)
1678                (looking-at mail-extr-listserv-list-name-pattern))
1679           (narrow-to-region (match-beginning 1) (match-end 1))
1680           (setq word-found-flag t)
1681           (setq name-done-flag t))
1682
1683          ;; Handle & substitution, when & is last and is not first.
1684          ((and (> word-count 0)
1685                (eq ?\  (preceding-char))
1686                (eq (following-char) ?&)
1687                (eq (1+ (point)) (point-max)))
1688           (delete-char 1)
1689           (capitalize-region
1690            (point)
1691            (progn
1692              (insert-buffer-substring canonicalization-buffer
1693                                       mbox-beg mbox-end)
1694              (point)))
1695           (setq disable-initial-guessing-flag t)
1696           (setq word-found-flag t))
1697
1698          ;; Handle & between names, as in "Bob & Susie".
1699          ((and (> word-count 0) (eq (following-char) ?\&))
1700           (setq name-beg (point))
1701           (setq name-end (1+ name-beg))
1702           (setq word-found-flag t)
1703           (goto-char name-end))
1704
1705          ;; Regular name words
1706          ((looking-at mail-extr-name-pattern)
1707           (setq name-beg (point))
1708           (setq name-end (match-end 0))
1709
1710           ;; Certain words will be dropped if they are at the end.
1711           (and (>= word-count 2)
1712                (not lower-case-flag)
1713                (or
1714                 ;; Trailing 4-or-more letter lowercase words preceded by
1715                 ;; mixed case or uppercase words will be dropped.
1716                 (looking-at "[a-z][a-z][a-z][a-z]+[ \t]*\\'") ;; XEmacs
1717                 ;; Drop a trailing word which is terminated with a period.
1718                 (eq ?. (char-after (1- name-end))))
1719                (setq drop-this-word-if-trailing-flag t))
1720
1721           ;; Set the flags that indicate whether we have seen a lowercase
1722           ;; word, a mixed case word, and an uppercase word.
1723           (if (re-search-forward "[a-z]" name-end t)
1724               (if (progn
1725                     (goto-char name-beg)
1726                     (re-search-forward "[A-Z]" name-end t))
1727                   (setq mixed-case-flag t)
1728                 (setq lower-case-flag t))
1729 ;;          (setq upper-case-flag t)
1730             )
1731
1732           (goto-char name-end)
1733           (setq word-found-flag t))
1734
1735          ;; Allow a number as a word, if it doesn't mean anything else.
1736          ((looking-at "[0-9]+\\>")
1737           (setq name-beg (point))
1738           (setq name-end (match-end 0))
1739           (goto-char name-end)
1740           (setq word-found-flag t))
1741
1742          (t
1743           (setq name-done-flag t)
1744           ))
1745
1746         ;; Count any word that we skipped over.
1747         (if word-found-flag
1748             (setq word-count (1+ word-count))))
1749
1750       ;; If the last thing in the name is 2 or more periods, or one or more
1751       ;; other sentence terminators (but not a single period) then keep them
1752       ;; and the preceding word.  This is for the benefit of whole sentences
1753       ;; in the name field: it's better behavior than dropping the last word
1754       ;; of the sentence...
1755       (if (and (not suffix-flag)
1756                (looking-at "\\(\\.+\\|[?!;:.][?!;:.]+\\|[?!;:][?!;:.]*\\)\\'"))
1757           (goto-char (setq suffix-flag (point-max))))
1758
1759       ;; Drop everything after point and certain trailing words.
1760       (narrow-to-region (point-min)
1761                         (or (and drop-last-word-if-trailing-flag
1762                                  last-word-beg)
1763                             (point)))
1764
1765       ;; Xerox's mailers SUCK!!!!!!
1766       ;; We simply refuse to believe that any last name is PARC or ADOC.
1767       ;; If it looks like that is the last name, that there is no meaningful
1768       ;; here at all.  Actually I guess it would be best to map patterns
1769       ;; like foo.hoser@xerox.com into foo@hoser.xerox.com, but I don't
1770       ;; actually know that that is what's going on.
1771       (unless suffix-flag
1772         (goto-char (point-min))
1773         (let ((case-fold-search t))
1774           (if (looking-at "[-A-Za-z_]+[. ]\\(PARC\\|ADOC\\)\\'")
1775               (erase-buffer))))
1776
1777       ;; If last name first put it at end (but before suffix)
1778       (when last-name-comma-flag
1779         (goto-char (point-min))
1780         (search-forward ",")
1781         (setq name-end (1- (point)))
1782         (goto-char (or suffix-flag (point-max)))
1783         (or (eq ?\  (preceding-char))
1784             (insert ?\ ))
1785         (insert-buffer-substring (current-buffer) (point-min) name-end)
1786         (goto-char name-end)
1787         (skip-chars-forward "\t ,")
1788         (narrow-to-region (point) (point-max)))
1789
1790       ;; Delete leading and trailing junk characters.
1791       ;; *** This is probably completely unneeded now.
1792       ;;(goto-char (point-max))
1793       ;;(skip-chars-backward mail-extr-non-end-name-chars)
1794       ;;(if (eq ?. (following-char))
1795       ;;    (forward-char 1))
1796       ;;(narrow-to-region (point)
1797       ;;                  (progn
1798       ;;                    (goto-char (point-min))
1799       ;;                    (skip-chars-forward mail-extr-non-begin-name-chars)
1800       ;;                    (point)))
1801
1802       ;; Compress whitespace
1803       (goto-char (point-min))
1804       (while (re-search-forward "[ \t\n]+" nil t)
1805         (replace-match (if (eobp) "" " ") t))
1806       )))
1807
1808 \f
1809
1810 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1811 ;;
1812 ;; Table of top-level domain names.
1813 ;;
1814 ;; This is used during address canonicalization; be careful of format changes.
1815 ;; Keep in mind that the country abbreviations follow ISO-3166.  There is
1816 ;; a U.S. FIPS that specifies a different set of two-letter country
1817 ;; abbreviations.
1818 ;;
1819 ;; Updated by the RIPE Network Coordination Centre.
1820 ;;
1821 ;; Source: ISO 3166 Maintenance Agency
1822 ;; http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1-semic.txt
1823 ;; http://www.iana.org/domain-names.htm
1824 ;; http://www.iana.org/cctld/cctld-whois.htm
1825 ;; Latest change: Mon Jul  8 14:21:59 CEST 2002
1826
1827 (defconst mail-extr-all-top-level-domains
1828   (let ((ob (make-vector 739 0)))
1829     (mapc
1830      (lambda (x)
1831        (put (intern (downcase (car x)) ob)
1832             'domain-name
1833             (if (nth 2 x)
1834                 (format (nth 2 x) (nth 1 x))
1835               (nth 1 x))))
1836      '(
1837        ;; ISO 3166 codes:
1838        ("ad" "Andorra")
1839        ("ae" "United Arab Emirates")
1840        ("af" "Afghanistan")
1841        ("ag" "Antigua and Barbuda")
1842        ("ai" "Anguilla")
1843        ("al" "Albania")
1844        ("am" "Armenia")
1845        ("an" "Netherlands Antilles")
1846        ("ao" "Angola")
1847        ("aq" "Antarctica")              ; continent
1848        ("ar" "Argentina"        "Argentine Republic")
1849        ("as" "American Samoa")
1850        ("at" "Austria"          "The Republic of %s")
1851        ("au" "Australia")
1852        ("aw" "Aruba")
1853        ("az" "Azerbaijan")
1854        ("ba" "Bosnia-Herzegovina")
1855        ("bb" "Barbados")
1856        ("bd" "Bangladesh")
1857        ("be" "Belgium"          "The Kingdom of %s")
1858        ("bf" "Burkina Faso")
1859        ("bg" "Bulgaria")
1860        ("bh" "Bahrain")
1861        ("bi" "Burundi")
1862        ("bj" "Benin")
1863        ("bm" "Bermuda")
1864        ("bn" "Brunei Darussalam")
1865        ("bo" "Bolivia"          "Republic of %s")
1866        ("br" "Brazil"           "The Federative Republic of %s")
1867        ("bs" "Bahamas")
1868        ("bt" "Bhutan")
1869        ("bv" "Bouvet Island")
1870        ("bw" "Botswana")
1871        ("by" "Belarus")
1872        ("bz" "Belize")
1873        ("ca" "Canada")
1874        ("cc" "Cocos (Keeling) Islands")
1875        ("cd" "Congo"            "The Democratic Republic of the %s")
1876        ("cf" "Central African Republic")
1877        ("cg" "Congo")
1878        ("ch" "Switzerland"      "The Swiss Confederation")
1879        ("ci" "Ivory Coast")             ; Cote D'ivoire
1880        ("ck" "Cook Islands")
1881        ("cl" "Chile"            "The Republic of %s")
1882        ("cm" "Cameroon")                ; In .fr domain
1883        ("cn" "China"            "The People's Republic of %s")
1884        ("co" "Colombia")
1885        ("cr" "Costa Rica"       "The Republic of %s")
1886        ("cu" "Cuba")
1887        ("cv" "Cape Verde")
1888        ("cx" "Christmas Island")
1889        ("cy" "Cyprus")
1890        ("cz" "Czech Republic")
1891        ("de" "Germany")
1892        ("dj" "Djibouti")
1893        ("dk" "Denmark")
1894        ("dm" "Dominica")
1895        ("do" "Dominican Republic"       "The %s")
1896        ("dz" "Algeria")
1897        ("ec" "Ecuador"          "The Republic of %s")
1898        ("ee" "Estonia")
1899        ("eg" "Egypt"            "The Arab Republic of %s")
1900        ("eh" "Western Sahara")
1901        ("er" "Eritrea")
1902        ("es" "Spain"            "The Kingdom of %s")
1903        ("et" "Ethiopia")
1904        ("fi" "Finland"          "The Republic of %s")
1905        ("fj" "Fiji")
1906        ("fk" "Falkland Islands (Malvinas)")
1907        ("fm" "Micronesia"       "Federated States of %s")
1908        ("fo" "Faroe Islands")
1909        ("fr" "France")
1910        ("ga" "Gabon")
1911        ("gb" "United Kingdom")
1912        ("gd" "Grenada")
1913        ("ge" "Georgia")
1914        ("gf" "French Guiana")
1915        ("gh" "Ghana")
1916        ("gi" "Gibraltar")
1917        ("gl" "Greenland")
1918        ("gm" "Gambia")
1919        ("gn" "Guinea")
1920        ("gp" "Guadeloupe (Fr.)")
1921        ("gq" "Equatorial Guinea")
1922        ("gr" "Greece"           "The Hellenic Republic (%s)")
1923        ("gs" "South Georgia and The South Sandwich Islands")
1924        ("gt" "Guatemala")
1925        ("gu" "Guam (U.S.)")
1926        ("gw" "Guinea-Bissau")
1927        ("gy" "Guyana")
1928        ("hk" "Hong Kong")
1929        ("hm" "Heard Island and Mcdonald Islands")
1930        ("hn" "Honduras")
1931        ("hr" "Croatia"          "Croatia (Hrvatska)")
1932        ("ht" "Haiti")
1933        ("hu" "Hungary"          "The Hungarian Republic")
1934        ("id" "Indonesia")
1935        ("ie" "Ireland")
1936        ("il" "Israel"           "The State of %s")
1937        ("im" "Isle of Man"      "The %s") ; NOT in ISO 3166-1 of 2001-02-26
1938        ("in" "India"            "The Republic of %s")
1939        ("io" "British Indian Ocean Territory")
1940        ("iq" "Iraq")
1941        ("ir" "Iran"             "Islamic Republic of %s")
1942        ("is" "Iceland"          "The Republic of %s")
1943        ("it" "Italy"            "The Italian Republic")
1944        ("jm" "Jamaica")
1945        ("jo" "Jordan")
1946        ("jp" "Japan")
1947        ("ke" "Kenya")
1948        ("kg" "Kyrgyzstan")
1949        ("kh" "Cambodia")
1950        ("ki" "Kiribati")
1951        ("km" "Comoros")
1952        ("kn" "Saint Kitts and Nevis")
1953        ("kp" "Korea (North)"    "Democratic People's Republic of Korea")
1954        ("kr" "Korea (South)"    "Republic of Korea")
1955        ("kw" "Kuwait")
1956        ("ky" "Cayman Islands")
1957        ("kz" "Kazakhstan")
1958        ("la" "Lao People's Democratic Republic")
1959        ("lb" "Lebanon")
1960        ("lc" "Saint Lucia")
1961        ("li" "Liechtenstein")
1962        ("lk" "Sri Lanka"        "The Democratic Socialist Republic of %s")
1963        ("lr" "Liberia")
1964        ("ls" "Lesotho")
1965        ("lt" "Lithuania")
1966        ("lu" "Luxembourg")
1967        ("lv" "Latvia")
1968        ("ly" "Libyan Arab Jamahiriya")
1969        ("ma" "Morocco")
1970        ("mc" "Monaco")
1971        ("md" "Moldova"          "The Republic of %s")
1972        ("mg" "Madagascar")
1973        ("mh" "Marshall Islands")
1974        ("mk" "Macedonia"        "The Former Yugoslav Republic of %s")
1975        ("ml" "Mali")
1976        ("mm" "Myanmar")
1977        ("mn" "Mongolia")
1978        ("mo" "Macao")
1979        ("mp" "Northern Mariana Islands")
1980        ("mq" "Martinique")
1981        ("mr" "Mauritania")
1982        ("ms" "Montserrat")
1983        ("mt" "Malta")
1984        ("mu" "Mauritius")
1985        ("mv" "Maldives")
1986        ("mw" "Malawi")
1987        ("mx" "Mexico"           "The United Mexican States")
1988        ("my" "Malaysia")
1989        ("mz" "Mozambique")
1990        ("na" "Namibia")
1991        ("nc" "New Caledonia (Fr.)")
1992        ("ne" "Niger")                   ; In .fr domain
1993        ("nf" "Norfolk Island")
1994        ("ng" "Nigeria")
1995        ("ni" "Nicaragua"        "The Republic of %s")
1996        ("nl" "Netherlands"      "The Kingdom of the %s")
1997        ("no" "Norway"           "The Kingdom of %s")
1998        ("np" "Nepal")                   ; Via .in domain
1999        ("nr" "Nauru")
2000        ("nu" "Niue")
2001        ("nz" "New Zealand")
2002        ("om" "Oman")
2003        ("pa" "Panama")
2004        ("pe" "Peru")
2005        ("pf" "French Polynesia")
2006        ("pg" "Papua New Guinea")
2007        ("ph" "Philippines"      "The Republic of the %s")
2008        ("pk" "Pakistan")
2009        ("pl" "Poland")
2010        ("pm" "Saint Pierre and Miquelon")
2011        ("pn" "Pitcairn")
2012        ("pr" "Puerto Rico (U.S.)")
2013        ("ps" "Palestinian Territory, Occupied")
2014        ("pt" "Portugal"         "The Portuguese Republic")
2015        ("pw" "Palau")
2016        ("py" "Paraguay")
2017        ("qa" "Qatar")
2018        ("re" "Reunion (Fr.)")           ; In .fr domain
2019        ("ro" "Romania")
2020        ("ru" "Russia"           "Russian Federation")
2021        ("rw" "Rwanda")
2022        ("sa" "Saudi Arabia")
2023        ("sb" "Solomon Islands")
2024        ("sc" "Seychelles")
2025        ("sd" "Sudan")
2026        ("se" "Sweden"           "The Kingdom of %s")
2027        ("sg" "Singapore"        "The Republic of %s")
2028        ("sh" "Saint Helena")
2029        ("si" "Slovenia")
2030        ("sj" "Svalbard and Jan Mayen") ; In .no domain
2031        ("sk" "Slovakia"         "The Slovak Republic")
2032        ("sl" "Sierra Leone")
2033        ("sm" "San Marino")
2034        ("sn" "Senegal")
2035        ("so" "Somalia")
2036        ("sr" "Suriname")
2037        ("st" "Sao Tome and Principe")
2038        ("su" "U.S.S.R." "The Union of Soviet Socialist Republics")
2039        ("sv" "El Salvador")
2040        ("sy" "Syrian Arab Republic")
2041        ("sz" "Swaziland")
2042        ("tc" "Turks and Caicos Islands")
2043        ("td" "Chad")
2044        ("tf" "French Southern Territories")
2045        ("tg" "Togo")
2046        ("th" "Thailand"         "The Kingdom of %s")
2047        ("tj" "Tajikistan")
2048        ("tk" "Tokelau")
2049        ("tl" "East Timor")
2050        ("tm" "Turkmenistan")
2051        ("tn" "Tunisia")
2052        ("to" "Tonga")
2053        ("tp" "East Timor")
2054        ("tr" "Turkey"           "The Republic of %s")
2055        ("tt" "Trinidad and Tobago")
2056        ("tv" "Tuvalu")
2057        ("tw" "Taiwan"           "%s, Province of China")
2058        ("tz" "Tanzania"         "United Republic of %s")
2059        ("ua" "Ukraine")
2060        ("ug" "Uganda")
2061        ("uk" "United Kingdom"   "The %s of Great Britain and Northern Ireland")
2062        ("um" "United States Minor Outlying Islands")
2063        ("us" "United States"    "The %s of America")
2064        ("uy" "Uruguay"          "The Eastern Republic of %s")
2065        ("uz" "Uzbekistan")
2066        ("va" "Holy See (Vatican City State)")
2067        ("vc" "Saint Vincent and the Grenadines")
2068        ("ve" "Venezuela"        "The Republic of %s")
2069        ("vg" "Virgin Islands, British")
2070        ("vi" "Virgin Islands, U.S.")
2071        ("vn" "Vietnam")
2072        ("vu" "Vanuatu")
2073        ("wf" "Wallis and Futuna")
2074        ("ws" "Samoa")
2075        ("ye" "Yemen")
2076        ("yt" "Mayotte")
2077        ("yu" "Yugoslavia"       "Yugoslavia, AKA Serbia-Montenegro")
2078        ("za" "South Africa"     "The Republic of %s")
2079        ("zm" "Zambia")
2080        ("zw" "Zimbabwe"         "Republic of %s")
2081        ;; Generic Domains:
2082        ("aero" t                "Air Transport Industry")
2083        ("biz" t                 "Businesses")
2084        ("com" t                 "Commercial")
2085        ("coop" t                "Cooperative Associations")
2086        ("info" t                "Info")
2087        ("museum" t              "Museums")
2088        ("name" t                "Individuals")
2089        ("net" t                 "Network")
2090        ("org" t                 "Non-profit Organization")
2091        ;;("pro" t                 "Credentialed professionals")
2092        ;;("bitnet" t            "Because It's Time NET")
2093        ("gov" t                 "United States Government")
2094        ("edu" t                 "Educational")
2095        ("mil" t                 "United States Military")
2096        ("int" t                 "International Treaties")
2097        ;;("nato" t              "North Atlantic Treaty Organization")
2098        ("uucp" t                "Unix to Unix CoPy")
2099        ;; Infrastructure Domains:
2100        ("arpa" t                "Advanced Research Projects Agency (U.S. DoD)")
2101        ))
2102     ob))
2103
2104 ;;;###autoload
2105 (defun what-domain (domain)
2106   "Convert mail domain DOMAIN to the country it corresponds to."
2107   (interactive
2108    (let ((completion-ignore-case t))
2109      (list (completing-read "Domain: "
2110                             mail-extr-all-top-level-domains nil t))))
2111   (or (setq domain (intern-soft (downcase domain)
2112                                 mail-extr-all-top-level-domains))
2113       (error "No such domain"))
2114   (message "%s: %s" (upcase (symbol-name domain)) (get domain 'domain-name)))
2115
2116 \f
2117 ;(let ((all nil))
2118 ;  (mapatoms #'(lambda (x)
2119 ;               (if (and (boundp x)
2120 ;                        (string-match "^mail-extr-" (symbol-name x)))
2121 ;                   (setq all (cons x all)))))
2122 ;  (setq all (sort all #'string-lessp))
2123 ;  (cons 'setq
2124 ;       (apply 'nconc (mapcar #'(lambda (x)
2125 ;                                 (list x (symbol-value x)))
2126 ;                             all))))
2127
2128 \f
2129 (provide 'mail-extr)
2130
2131 ;;; arch-tag: 7785fade-1073-4ed6-b4f6-28db34a7982d
2132 ;;; mail-extr.el ends here