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