(Out of Rmail): Mention b2m.pl.
[bpt/emacs.git] / lisp / mail / mailalias.el
1 ;;; mailalias.el --- expand and complete mailing address aliases
2
3 ;; Copyright (C) 1985, 1987, 1995, 1996, 1997, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7 ;; Keywords: mail
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Basic functions for defining and expanding mail aliases.
27 ;; These seal off the interface to the alias-definition parts of a
28 ;; .mailrc file formatted for BSD's Mail or USL's mailx.
29
30 ;;; Code:
31
32 (require 'sendmail)
33
34 (defgroup mailalias nil
35 "Expanding mail aliases."
36 :group 'mail)
37
38 (defcustom mail-passwd-files '("/etc/passwd")
39 "*List of files from which to determine valid user names."
40 :type '(repeat string)
41 :group 'mailalias)
42
43 (defcustom mail-passwd-command nil
44 "*Shell command to retrieve text to add to `/etc/passwd', or nil."
45 :type '(choice string (const nil))
46 :group 'mailalias)
47
48 (defvar mail-directory-names t
49 "Alist of mail address directory entries.
50 When t this still needs to be initialized.")
51
52 (defvar mail-address-field-regexp
53 "^\\(Resent-\\)?\\(To\\|From\\|CC\\|BCC\\|Reply-to\\):")
54
55 (defcustom mail-complete-alist
56 ;; Don't use backquote here; we don't want backquote to get loaded
57 ;; just because of loading this file.
58 ;; Don't refer to mail-address-field-regexp here;
59 ;; that confuses some things such as cus-dep.el.
60 (cons '("^\\(Resent-\\)?\\(To\\|From\\|CC\\|BCC\\|Reply-to\\):"
61 . (mail-get-names pattern))
62 '(("Newsgroups:" . (if (boundp 'gnus-active-hashtb)
63 gnus-active-hashtb
64 (if (boundp news-group-article-assoc)
65 news-group-article-assoc)))
66 ("Followup-To:" . (mail-sentto-newsgroups))
67 ;;("Distribution:" ???)
68 ))
69 "*Alist of header field and expression to return alist for completion.
70 The expression may reference the variable `pattern'
71 which will hold the string being completed.
72 If not on matching header, `mail-complete-function' gets called instead."
73 :type 'alist
74 :group 'mailalias)
75 (put 'mail-complete-alist 'risky-local-variable t)
76
77 ;;;###autoload
78 (defcustom mail-complete-style 'angles
79 "*Specifies how \\[mail-complete] formats the full name when it completes.
80 If `nil', they contain just the return address like:
81 king@grassland.com
82 If `parens', they look like:
83 king@grassland.com (Elvis Parsley)
84 If `angles', they look like:
85 Elvis Parsley <king@grassland.com>"
86 :type '(choice (const angles) (const parens) (const nil))
87 :group 'mailalias)
88
89 (defcustom mail-complete-function 'ispell-complete-word
90 "*Function to call when completing outside `mail-complete-alist'-header."
91 :type '(choice function (const nil))
92 :group 'mailalias)
93
94 (defcustom mail-directory-function nil
95 "*Function to get completions from directory service or nil for none.
96 See `mail-directory-requery'."
97 :type '(choice function (const nil))
98 :group 'mailalias)
99
100 ;; This is for when the directory is huge, or changes frequently.
101 (defcustom mail-directory-requery nil
102 "*When non-nil call `mail-directory-function' for each completion.
103 In that case, one argument gets passed to the function, the partial string
104 entered so far."
105 :type 'boolean
106 :group 'mailalias)
107
108 (defcustom mail-directory-process nil
109 "*Shell command to get the list of names from a mail directory.
110 This value is used when the value of `mail-directory-function'
111 is `mail-directory-process'. The value should be a list
112 of the form (COMMAND ARG ...), where each of the list elements
113 is evaluated. COMMAND should evaluate to a string. When
114 `mail-directory-requery' is non-nil, during evaluation of these
115 elements, the variable `pattern' contains the partial input being
116 completed. `pattern' is nil when `mail-directory-requery' is nil.
117
118 The value might look like this:
119
120 '(remote-shell-program \"HOST\" \"-nl\" \"USER\" \"COMMAND\")
121
122 or like this:
123
124 '(remote-shell-program \"HOST\" \"-n\" \"COMMAND '^\" pattern \"'\")"
125 :type 'sexp
126 :group 'mailalias)
127 (put 'mail-directory-process 'risky-local-variable t)
128
129 (defcustom mail-directory-stream nil
130 "*List of (HOST SERVICE) for stream connection to mail directory."
131 :type 'sexp
132 :group 'mailalias)
133 (put 'mail-directory-stream 'risky-local-variable t)
134
135 (defcustom mail-directory-parser nil
136 "*How to interpret the output of `mail-directory-function'.
137 Three types of values are possible:
138
139 - nil means to gather each line as one name
140 - regexp means first \\(grouping\\) in successive matches is name
141 - function called at beginning of buffer that returns an alist of names"
142 :type '(choice (const nil) regexp function)
143 :group 'mailalias)
144 (put 'mail-directory-parser 'risky-local-variable t)
145
146 ;; Internal variables.
147
148 (defvar mail-names t
149 "Alist of local users, aliases and directory entries as available.
150 Elements have the form (MAILNAME) or (MAILNAME . FULLNAME).
151 If the value means t, it means the real value should be calculated
152 for the next use. This is used in `mail-complete'.")
153
154 (defvar mail-local-names t
155 "Alist of local users.
156 When t this still needs to be initialized.")
157 \f
158
159 ;; Called from sendmail-send-it, or similar functions,
160 ;; only if some mail aliases are defined.
161 ;;;###autoload
162 (defun expand-mail-aliases (beg end &optional exclude)
163 "Expand all mail aliases in suitable header fields found between BEG and END.
164 If interactive, expand in header fields.
165 Suitable header fields are `To', `From', `CC' and `BCC', `Reply-to', and
166 their `Resent-' variants.
167
168 Optional second arg EXCLUDE may be a regular expression defining text to be
169 removed from alias expansions."
170 (interactive
171 (save-excursion
172 (list (goto-char (point-min))
173 (mail-header-end))))
174 (sendmail-sync-aliases)
175 (when (eq mail-aliases t)
176 (setq mail-aliases nil)
177 (build-mail-aliases))
178 (save-excursion
179 (goto-char beg)
180 (setq end (set-marker (make-marker) end))
181 (let ((case-fold-search nil))
182 (while (let ((case-fold-search t))
183 (re-search-forward mail-address-field-regexp end t))
184 (skip-chars-forward " \t")
185 (let ((beg1 (point))
186 end1 pos epos seplen
187 ;; DISABLED-ALIASES records aliases temporarily disabled
188 ;; while we scan text that resulted from expanding those aliases.
189 ;; Each element is (ALIAS . TILL-WHEN), where TILL-WHEN
190 ;; is where to reenable the alias (expressed as number of chars
191 ;; counting from END1).
192 (disabled-aliases nil))
193 (re-search-forward "^[^ \t]" end 'move)
194 (beginning-of-line)
195 (skip-chars-backward " \t\n")
196 (setq end1 (point-marker))
197 (goto-char beg1)
198 (while (< (point) end1)
199 (setq pos (point))
200 ;; Reenable any aliases which were disabled for ranges
201 ;; that we have passed out of.
202 (while (and disabled-aliases
203 (> pos (- end1 (cdr (car disabled-aliases)))))
204 (setq disabled-aliases (cdr disabled-aliases)))
205 ;; EPOS gets position of end of next name;
206 ;; SEPLEN gets length of whitespace&separator that follows it.
207 (if (re-search-forward "[ \t]*[\n,][ \t]*" end1 t)
208 (setq epos (match-beginning 0)
209 seplen (- (point) epos))
210 (setq epos (marker-position end1) seplen 0))
211 (let ((string (buffer-substring-no-properties pos epos))
212 translation)
213 (if (and (not (assoc string disabled-aliases))
214 (setq translation (cdr (assoc string mail-aliases))))
215 (progn
216 ;; This name is an alias. Disable it.
217 (setq disabled-aliases (cons (cons string (- end1 epos))
218 disabled-aliases))
219 ;; Replace the alias with its expansion
220 ;; then rescan the expansion for more aliases.
221 (goto-char pos)
222 (insert translation)
223 (when exclude
224 (let ((regexp (concat "\\b\\(" exclude "\\)\\b"))
225 (end (point-marker)))
226 (goto-char pos)
227 (while (re-search-forward regexp end t)
228 (replace-match ""))
229 (goto-char end)))
230 (delete-region (point) (+ (point) (- epos pos)))
231 (goto-char pos))
232 ;; Name is not an alias. Skip to start of next name.
233 (goto-char epos)
234 (forward-char seplen))))
235 (set-marker end1 nil)))
236 (set-marker end nil))))
237
238 ;; Called by mail-setup, or similar functions, only if the file specified
239 ;; by mail-personal-alias-file (usually `~/.mailrc') exists.
240 (defun build-mail-aliases (&optional file)
241 "Read mail aliases from personal aliases file and set `mail-aliases'.
242 By default, this is the file specified by `mail-personal-alias-file'."
243 (setq file (expand-file-name (or file mail-personal-alias-file)))
244 ;; In case mail-aliases is t, make sure define-mail-alias
245 ;; does not recursively call build-mail-aliases.
246 (setq mail-aliases nil)
247 (let ((buffer nil)
248 (obuf (current-buffer)))
249 (unwind-protect
250 (progn
251 (setq buffer (generate-new-buffer " mailrc"))
252 (set-buffer buffer)
253 (while file
254 (cond ((get-file-buffer file)
255 (insert (save-excursion
256 (set-buffer (get-file-buffer file))
257 (buffer-substring-no-properties
258 (point-min) (point-max)))))
259 ((file-exists-p file) (insert-file-contents file))
260 ((file-exists-p (setq file (concat "~/" file)))
261 (insert-file-contents file))
262 (t (setq file nil)))
263 (goto-char (point-min))
264 ;; Delete comments from the contents.
265 (while (search-forward "# " nil t)
266 (let ((p (- (point) 2)))
267 (end-of-line)
268 (delete-region p (point))))
269 ;; Don't lose if no final newline.
270 (goto-char (point-max))
271 (or (eq (preceding-char) ?\n) (newline))
272 (goto-char (point-min))
273 ;; handle "\\\n" continuation lines
274 (while (not (eobp))
275 (end-of-line)
276 (if (= (preceding-char) ?\\)
277 (progn (delete-char -1) (delete-char 1) (insert ?\ ))
278 (forward-char 1)))
279 (goto-char (point-min))
280 ;; handle `source' directives -- Eddy/1994/May/25
281 (cond ((re-search-forward "^source[ \t]+" nil t)
282 (re-search-forward "\\S-+")
283 (setq file (buffer-substring-no-properties
284 (match-beginning 0) (match-end 0)))
285 (beginning-of-line)
286 (insert "# ") ; to ensure we don't re-process this file
287 (beginning-of-line))
288 (t (setq file nil))))
289 (goto-char (point-min))
290 (while (re-search-forward
291 "^\\(a\\|alias\\|g\\|group\\)[ \t]+\\([^ \t\n]+\\)" nil t)
292 (let* ((name (match-string 2))
293 (start (progn (skip-chars-forward " \t") (point)))
294 value)
295 (end-of-line)
296 (setq value (buffer-substring-no-properties start (point)))
297 (unless (equal value "")
298 (define-mail-alias name value t))))
299 mail-aliases)
300 (if buffer (kill-buffer buffer))
301 (set-buffer obuf))))
302
303 ;; Always autoloadable in case the user wants to define aliases
304 ;; interactively or in .emacs.
305 ;; define-mail-abbrev in mailabbrev.el duplicates much of this code.
306 ;;;###autoload
307 (defun define-mail-alias (name definition &optional from-mailrc-file)
308 "Define NAME as a mail alias that translates to DEFINITION.
309 This means that sending a message to NAME will actually send to DEFINITION.
310
311 Normally, the addresses in DEFINITION must be separated by commas.
312 If FROM-MAILRC-FILE is non-nil, then addresses in DEFINITION
313 can be separated by spaces; an address can contain spaces
314 if it is quoted with double-quotes."
315
316 (interactive "sDefine mail alias: \nsDefine %s as mail alias for: ")
317 ;; Read the defaults first, if we have not done so.
318 ;; But not if we are doing that already right now.
319 (unless from-mailrc-file
320 (sendmail-sync-aliases))
321 (if (eq mail-aliases t)
322 (progn
323 (setq mail-aliases nil)
324 (if (file-exists-p mail-personal-alias-file)
325 (build-mail-aliases))))
326 ;; strip garbage from front and end
327 (if (string-match "\\`[ \t\n,]+" definition)
328 (setq definition (substring definition (match-end 0))))
329 (if (string-match "[ \t\n,]+\\'" definition)
330 (setq definition (substring definition 0 (match-beginning 0))))
331
332 (let* ((L (length definition))
333 (start (if (> L 0) 0))
334 end this-entry result tem)
335 (while start
336 (cond
337 (from-mailrc-file
338 ;; If we're reading from the mailrc file, addresses are
339 ;; delimited by spaces, and addresses with embedded spaces are
340 ;; surrounded by non-escaped double-quotes.
341 (if (eq ?\" (aref definition start))
342 (setq start (1+ start)
343 end (and (string-match
344 "[^\\]\\(\\([\\][\\]\\)*\\)\"[ \t,]*"
345 definition start)
346 (match-end 1)))
347 (setq end (string-match "[ \t,]+" definition start)))
348 ;; Extract the address and advance the loop past it.
349 (setq this-entry (substring definition start end)
350 start (and end (/= (match-end 0) L) (match-end 0)))
351 ;; If the full name contains a problem character, quote it.
352 (and (string-match "\\(.+?\\)[ \t]*\\(<.*>\\)" this-entry)
353 (string-match "[^- !#$%&'*+/0-9=?A-Za-z^_`{|}~]"
354 (match-string 1 this-entry))
355 (setq this-entry (replace-regexp-in-string
356 "\\(.+?\\)[ \t]*\\(<.*>\\)"
357 "\"\\1\" \\2"
358 this-entry))))
359 ;; When we are not reading from .mailrc, addresses are
360 ;; separated by commas. Try to accept a rfc822-like syntax.
361 ;; (Todo: extend rfc822.el to do the work for us.)
362 ((equal (string-match
363 "[ \t,]*\\(\"\\(?:[^\"]\\|[^\\]\\(?:[\\][\\]\\)*\"\\)*\"[ \t]*\
364 <[-.!#$%&'*+/0-9=?A-Za-z^_`{|}~@]+>\\)[ \t,]*"
365 definition start)
366 start)
367 ;; If an entry has a valid [ "foo bar" <foo@example.com> ]
368 ;; form, use it literally . This also allows commas in the
369 ;; quoted string, e.g. [ "foo bar, jr" <foo@example.com> ]
370 (setq this-entry (match-string 1 definition)
371 start (and (/= (match-end 0) L) (match-end 0))))
372 (t
373 ;; Otherwise, read the next address by looking for a comma.
374 (setq end (string-match "[ \t\n,]*,[ \t\n]*" definition start))
375 (setq this-entry (substring definition start end))
376 ;; Advance the loop past this address.
377 (setq start (and end (/= (match-end 0) L) (match-end 0)))
378 ;; If the full name contains a problem character, quote it.
379 (and (string-match "\\(.+?\\)[ \t]*\\(<.*>\\)" this-entry)
380 (string-match "[^- !#$%&'*+/0-9=?A-Za-z^_`{|}~]"
381 (match-string 1 this-entry))
382 (setq this-entry (replace-regexp-in-string
383 "\\(.+?\\)[ \t]*\\(<.*>\\)" "\"\\1\" \\2"
384 this-entry)))))
385 (push this-entry result))
386
387 (setq definition (mapconcat (function identity)
388 (nreverse result) ", "))
389 (setq tem (assoc name mail-aliases))
390 (if tem
391 (rplacd tem definition)
392 (setq mail-aliases (cons (cons name definition) mail-aliases)
393 mail-names t))))
394
395 ;;;###autoload
396 (defun mail-complete (arg)
397 "Perform completion on header field or word preceding point.
398 Completable headers are according to `mail-complete-alist'. If none matches
399 current header, calls `mail-complete-function' and passes prefix arg if any."
400 (interactive "P")
401 ;; Read the defaults first, if we have not done so.
402 (sendmail-sync-aliases)
403 (if (eq mail-aliases t)
404 (progn
405 (setq mail-aliases nil)
406 (if (file-exists-p mail-personal-alias-file)
407 (build-mail-aliases))))
408 (let ((list mail-complete-alist))
409 (if (and (< 0 (mail-header-end))
410 (save-excursion
411 (if (re-search-backward "^[^\t]" nil t)
412 (while list
413 (if (looking-at (car (car list)))
414 (setq arg (cdr (car list))
415 list ())
416 (setq list (cdr list)))))
417 arg))
418 (let* ((end (point))
419 (beg (save-excursion
420 (skip-chars-backward "^ \t<,:")
421 (point)))
422 (pattern (buffer-substring beg end))
423 completion)
424 (setq list (eval arg)
425 completion (try-completion pattern list))
426 (cond ((eq completion t))
427 ((null completion)
428 (message "Can't find completion for \"%s\"" pattern)
429 (ding))
430 ((not (string= pattern completion))
431 (delete-region beg end)
432 (let ((alist-elt (assoc completion mail-names)))
433 (if (cdr alist-elt)
434 (cond ((eq mail-complete-style 'parens)
435 (insert completion " (" (cdr alist-elt) ")"))
436 ((eq mail-complete-style 'angles)
437 (insert (cdr alist-elt) " <" completion ">"))
438 (t
439 (insert completion)))
440 (insert completion))))
441 (t
442 (message "Making completion list...")
443 (with-output-to-temp-buffer "*Completions*"
444 (display-completion-list
445 (all-completions pattern list)))
446 (message "Making completion list...%s" "done"))))
447 (funcall mail-complete-function arg))))
448
449 (defun mail-get-names (pattern)
450 "Fetch local users and global mail addresses for completion.
451 Consults `/etc/passwd' and a directory service if one is set up via
452 `mail-directory-function'.
453 PATTERN is the string we want to complete."
454 (if (eq mail-local-names t)
455 (save-excursion
456 (set-buffer (generate-new-buffer " passwd"))
457 (let ((files mail-passwd-files))
458 (while files
459 (insert-file-contents (car files) nil nil nil t)
460 (setq files (cdr files))))
461 (if mail-passwd-command
462 (call-process shell-file-name nil t nil
463 shell-command-switch mail-passwd-command))
464 (goto-char (point-min))
465 (setq mail-local-names nil)
466 (while (not (eobp))
467 ;;Recognize lines like
468 ;; nobody:*:65534:65534::/:
469 ;; +demo::::::/bin/csh
470 ;; +ethanb
471 ;;while skipping
472 ;; +@SOFTWARE
473 ;; The second \(...\) matches the user id.
474 (if (looking-at "\\+?\\([^:@\n+]+\\):[^:\n]*:\\([^\n:]*\\):")
475 (add-to-list 'mail-local-names
476 (cons (match-string 1)
477 (user-full-name
478 (string-to-number (match-string 2))))))
479 (beginning-of-line 2))
480 (kill-buffer (current-buffer))))
481 (if (or (eq mail-names t)
482 (eq mail-directory-names t))
483 (let (directory)
484 (and mail-directory-function
485 (eq mail-directory-names t)
486 (setq directory
487 (mail-directory (if mail-directory-requery pattern))))
488 (or mail-directory-requery
489 (setq mail-directory-names directory))
490 (if (or directory
491 (eq mail-names t))
492 (setq mail-names
493 (sort (append (if (consp mail-aliases)
494 (mapcar
495 (function (lambda (a) (list (car a))))
496 mail-aliases))
497 (if (consp mail-local-names)
498 mail-local-names)
499 (or directory
500 (when (consp mail-directory-names)
501 mail-directory-names)))
502 (lambda (a b)
503 ;; should cache downcased strings
504 (string< (downcase (car a))
505 (downcase (car b)))))))))
506 mail-names)
507
508
509 (defun mail-directory (pattern)
510 "Use mail-directory facility to get user names matching PATTERN.
511 If PATTERN is nil, get all the defined user names.
512 This function calls `mail-directory-function' to query the directory,
513 then uses `mail-directory-parser' to parse the output it returns."
514 (save-excursion
515 (message "Querying directory...")
516 (set-buffer (generate-new-buffer " *mail-directory*"))
517 (funcall mail-directory-function pattern)
518 (goto-char 1)
519 (let (directory)
520 (if (stringp mail-directory-parser)
521 (while (re-search-forward mail-directory-parser nil t)
522 (setq directory
523 (cons (match-string 1) directory)))
524 (if mail-directory-parser
525 (setq directory (funcall mail-directory-parser))
526 (while (not (eobp))
527 (setq directory
528 (cons (buffer-substring (point)
529 (progn
530 (forward-line)
531 (if (bolp)
532 (1- (point))
533 (point))))
534 directory)))))
535 (kill-buffer (current-buffer))
536 (message "Querying directory...done")
537 directory)))
538
539
540 (defun mail-directory-process (pattern)
541 "Run a shell command to output names in directory.
542 See `mail-directory-process'."
543 (when (consp mail-directory-process)
544 (apply 'call-process (eval (car mail-directory-process)) nil t nil
545 (mapcar 'eval (cdr mail-directory-process)))))
546
547 ;; This should handle a dialog. Currently expects port to spit out names.
548 (defun mail-directory-stream (pattern)
549 "Open a stream to retrieve names in directory.
550 See `mail-directory-stream'."
551 (let (mailalias-done)
552 (set-process-sentinel
553 (apply 'open-network-stream "mailalias" (current-buffer)
554 mail-directory-stream)
555 (lambda (x y)
556 (setq mailalias-done t)))
557 (while (not mailalias-done)
558 (sit-for .1))))
559
560 (defun mail-sentto-newsgroups ()
561 "Return all entries from Newsgroups: header as completion alist."
562 (save-excursion
563 (if (mail-position-on-field "newsgroups" t)
564 (let ((point (point))
565 list)
566 (while (< (skip-chars-backward "^:, \t\n") 0)
567 (setq list `((,(buffer-substring (point) point))
568 ,@list))
569 (skip-chars-backward ", \t\n")
570 (setq point (point)))
571 list))))
572
573 (provide 'mailalias)
574
575 ;; arch-tag: 1d6a0f87-eb34-4d45-8816-60c1b952cf46
576 ;;; mailalias.el ends here