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