1 ;;; mailalias.el --- expand and complete mailing address aliases
3 ;; Copyright (C) 1985, 1987, 1995, 1996, 1997 Free Software Foundation, Inc.
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)
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.
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.
35 (defgroup mailalias nil
36 "Expanding mail aliases"
39 (defcustom mail-passwd-files '("/etc/passwd")
40 "*List of files from which to determine valid user names."
41 :type '(repeat string)
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))
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 ;; 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)
65 (if (boundp news-group-article-assoc)
66 news-group-article-assoc)))
67 ("Followup-To:" . (mail-sentto-newsgroups))
68 ;;("Distribution:" ???)
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."
76 (put 'mail-complete-alist 'risky-local-variable t)
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:
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))
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))
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))
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
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. When `mail-directory-requery' is non-nil, during
115 evaluation of these elements, the variable `pattern' contains
116 the partial input being completed.
118 The value might look like this:
120 '(remote-shell-program \"HOST\" \"-nl\" \"USER\" \"COMMAND\")
124 '(remote-shell-program \"HOST\" \"-n\" \"COMMAND '^\" pattern \"'\")"
127 (put 'mail-directory-process 'risky-local-variable t)
129 (defcustom mail-directory-stream nil
130 "*List of (HOST SERVICE) for stream connection to mail directory."
133 (put 'mail-directory-stream 'risky-local-variable t)
135 (defcustom mail-directory-parser nil
136 "*How to interpret the output of `mail-directory-function'.
137 Three types of values are possible:
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)
144 (put 'mail-directory-parser 'risky-local-variable t)
146 ;; Internal variables.
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'.")
154 (defvar mail-local-names t
155 "Alist of local users.
156 When t this still needs to be initialized.")
159 ;; Called from sendmail-send-it, or similar functions,
160 ;; only if some mail aliases are defined.
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 before `mail-header-separator'.
165 Suitable header fields are `To', `From', `CC' and `BCC', `Reply-to', and
166 their `Resent-' variants.
168 Optional second arg EXCLUDE may be a regular expression defining text to be
169 removed from alias expansions."
172 (list (goto-char (point-min))
173 (search-forward (concat "\n" mail-header-separator "\n")))))
174 (sendmail-sync-aliases)
175 (when (eq mail-aliases t)
176 (setq mail-aliases nil)
177 (build-mail-aliases))
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")
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)
195 (skip-chars-backward " \t\n")
196 (setq end1 (point-marker))
198 (while (< (point) end1)
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))
213 (if (and (not (assoc string disabled-aliases))
214 (setq translation (cdr (assoc string mail-aliases))))
216 ;; This name is an alias. Disable it.
217 (setq disabled-aliases (cons (cons string (- end1 epos))
219 ;; Replace the alias with its expansion
220 ;; then rescan the expansion for more aliases.
224 (let ((regexp (concat "\\b\\(" exclude "\\)\\b"))
225 (end (point-marker)))
227 (while (re-search-forward regexp end t)
230 (delete-region (point) (+ (point) (- epos pos)))
232 ;; Name is not an alias. Skip to start of next name.
234 (forward-char seplen))))
235 (set-marker end1 nil)))
236 (set-marker end nil))))
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)
248 (obuf (current-buffer)))
251 (setq buffer (generate-new-buffer " mailrc"))
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))
263 ;; Don't lose if no final newline.
264 (goto-char (point-max))
265 (or (eq (preceding-char) ?\n) (newline))
266 (goto-char (point-min))
267 ;; handle "\\\n" continuation lines
270 (if (= (preceding-char) ?\\)
271 (progn (delete-char -1) (delete-char 1) (insert ?\ ))
273 (goto-char (point-min))
274 ;; handle `source' directives -- Eddy/1994/May/25
275 (cond ((re-search-forward "^source[ \t]+" nil t)
276 (re-search-forward "\\S-+")
277 (setq file (buffer-substring-no-properties
278 (match-beginning 0) (match-end 0)))
280 (insert "# ") ; to ensure we don't re-process this file
282 (t (setq file nil))))
283 (goto-char (point-min))
284 (while (re-search-forward
285 "^\\(a\\|alias\\|g\\|group\\)[ \t]+\\([^ \t]+\\)" nil t)
286 (let* ((name (match-string 2))
287 (start (progn (skip-chars-forward " \t") (point))))
291 (buffer-substring-no-properties start (point))
294 (if buffer (kill-buffer buffer))
297 ;; Always autoloadable in case the user wants to define aliases
298 ;; interactively or in .emacs.
300 (defun define-mail-alias (name definition &optional from-mailrc-file)
301 "Define NAME as a mail alias that translates to DEFINITION.
302 This means that sending a message to NAME will actually send to DEFINITION.
304 Normally, the addresses in DEFINITION must be separated by commas.
305 If FROM-MAILRC-FILE is non-nil, then addresses in DEFINITION
306 can be separated by spaces; an address can contain spaces
307 if it is quoted with double-quotes."
309 (interactive "sDefine mail alias: \nsDefine %s as mail alias for: ")
310 ;; Read the defaults first, if we have not done so.
311 ;; But not if we are doing that already right now.
312 (unless from-mailrc-file
313 (sendmail-sync-aliases))
314 (if (eq mail-aliases t)
316 (setq mail-aliases nil)
317 (if (file-exists-p mail-personal-alias-file)
318 (build-mail-aliases))))
319 ;; strip garbage from front and end
320 (if (string-match "\\`[ \t\n,]+" definition)
321 (setq definition (substring definition (match-end 0))))
322 (if (string-match "[ \t\n,]+\\'" definition)
323 (setq definition (substring definition 0 (match-beginning 0))))
325 ;; If DEFINITION is null string, avoid looping even once.
326 (start (and (not (equal definition "")) 0))
327 (L (length definition))
331 (setq convert-backslash nil)
332 ;; If we're reading from the mailrc file, then addresses are delimited
333 ;; by spaces, and addresses with embedded spaces must be surrounded by
334 ;; double-quotes. Otherwise, addresses are separated by commas.
336 (if (eq ?\" (aref definition start))
337 (progn (string-match "[^\\]\\(\\([\\][\\]\\)*\\)\"[ \t,]*" definition start)
338 (setq start (1+ start)
340 convert-backslash t))
341 (setq end (string-match "[ \t,]+" definition start)))
342 (setq end (string-match "[ \t\n,]*,[ \t\n,]*" definition start)))
343 (let ((temp (substring definition start end))
348 (if convert-backslash
349 (while (string-match "[\\]" temp pos)
350 (setq temp (replace-match "" t t temp))
352 (setq start (1- start)))
353 (setq pos (match-end 0))))
354 (setq result (cons temp result))))
355 (setq definition (mapconcat (function identity)
358 (setq tem (assoc name mail-aliases))
360 (rplacd tem definition)
361 (setq mail-aliases (cons (cons name definition) mail-aliases)
365 (defun mail-complete (arg)
366 "Perform completion on header field or word preceding point.
367 Completable headers are according to `mail-complete-alist'. If none matches
368 current header, calls `mail-complete-function' and passes prefix arg if any."
370 ;; Read the defaults first, if we have not done so.
371 (sendmail-sync-aliases)
372 (if (eq mail-aliases t)
374 (setq mail-aliases nil)
375 (if (file-exists-p mail-personal-alias-file)
376 (build-mail-aliases))))
377 (let ((list mail-complete-alist))
378 (if (and (save-excursion (search-forward
379 (concat "\n" mail-header-separator "\n")
382 (if (re-search-backward "^[^\t]" nil t)
384 (if (looking-at (car (car list)))
385 (setq arg (cdr (car list))
387 (setq list (cdr list)))))
391 (skip-chars-backward "^ \t<,:")
393 (pattern (buffer-substring beg end))
395 (setq list (eval arg)
396 completion (try-completion pattern list))
397 (cond ((eq completion t))
399 (message "Can't find completion for \"%s\"" pattern)
401 ((not (string= pattern completion))
402 (delete-region beg end)
403 (let ((alist-elt (assoc completion mail-names)))
405 (cond ((eq mail-complete-style 'parens)
406 (insert completion " (" (cdr alist-elt) ")"))
407 ((eq mail-complete-style 'angles)
408 (insert (cdr alist-elt) " <" completion ">"))
410 (insert completion)))
411 (insert completion))))
413 (message "Making completion list...")
414 (with-output-to-temp-buffer "*Completions*"
415 (display-completion-list
416 (all-completions pattern list)))
417 (message "Making completion list...%s" "done"))))
418 (funcall mail-complete-function arg))))
420 (defun mail-get-names (pattern)
421 "Fetch local users and global mail addresses for completion.
422 Consults `/etc/passwd' and a directory service if one is set up via
423 `mail-directory-function'.
424 PATTERN is the string we want to complete."
425 (if (eq mail-local-names t)
427 (set-buffer (generate-new-buffer " passwd"))
428 (let ((files mail-passwd-files))
430 (insert-file-contents (car files) nil nil nil t)
431 (setq files (cdr files))))
432 (if mail-passwd-command
433 (call-process shell-file-name nil t nil
434 shell-command-switch mail-passwd-command))
435 (beginning-of-buffer)
436 (setq mail-local-names nil)
438 ;;Recognize lines like
439 ;; nobody:*:65534:65534::/:
440 ;; +demo::::::/bin/csh
444 ;; The second \(...\) matches the user id.
445 (if (looking-at "\\+?\\([^:@\n+]+\\):[^:\n]*:\\([^\n:]*\\):")
446 (add-to-list 'mail-local-names
447 (cons (match-string 1)
449 (string-to-int (match-string 2))))))
450 (beginning-of-line 2))
451 (kill-buffer (current-buffer))))
452 (if (or (eq mail-names t)
453 (eq mail-directory-names t))
455 (and mail-directory-function
456 (eq mail-directory-names t)
458 (mail-directory (if mail-directory-requery pattern))))
459 (or mail-directory-requery
460 (setq mail-directory-names directory))
464 (sort (append (if (consp mail-aliases)
466 (function (lambda (a) (list (car a))))
468 (if (consp mail-local-names)
470 (or directory mail-directory-names))
472 ;; should cache downcased strings
473 (string< (downcase (car a))
474 (downcase (car b)))))))))
478 (defun mail-directory (pattern)
479 "Call directory to get names matching PATTERN or all if `nil'.
480 Calls `mail-directory-function' and applies `mail-directory-parser' to output."
482 (message "Querying directory...")
483 (set-buffer (generate-new-buffer " *mail-directory*"))
484 (funcall mail-directory-function pattern)
487 (if (stringp mail-directory-parser)
488 (while (re-search-forward mail-directory-parser nil t)
490 (cons (match-string 1) directory)))
491 (if mail-directory-parser
492 (setq directory (funcall mail-directory-parser))
495 (cons (buffer-substring (point)
502 (kill-buffer (current-buffer))
503 (message "Querying directory...done")
507 (defun mail-directory-process (pattern)
508 "Run a shell command to output names in directory.
509 See `mail-directory-process'."
510 (apply 'call-process (eval (car mail-directory-process)) nil t nil
511 (mapcar 'eval (cdr mail-directory-process))))
513 ;; This should handle a dialog. Currently expects port to spit out names.
514 (defun mail-directory-stream (pattern)
515 "Open a stream to retrieve names in directory.
516 See `mail-directory-stream'."
517 (let (mailalias-done)
518 (set-process-sentinel
519 (apply 'open-network-stream "mailalias" (current-buffer)
520 mail-directory-stream)
522 (setq mailalias-done t)))
523 (while (not mailalias-done)
526 (defun mail-sentto-newsgroups ()
527 "Return all entries from Newsgroups: header as completion alist."
529 (if (mail-position-on-field "newsgroups" t)
530 (let ((point (point))
532 (while (< (skip-chars-backward "^:, \t\n") 0)
533 (setq list `((,(buffer-substring (point) point))
535 (skip-chars-backward ", \t\n")
536 (setq point (point)))
541 ;;; mailalias.el ends here