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.
36 "Alist of local users, aliases and directory entries as available.
37 Elements have the form (MAILNAME) or (MAILNAME . FULLNAME).
38 If the value means t, it means the real value should be calculated
39 for the next use. this is used in `mail-complete'.")
41 (defvar mail-local-names t
42 "Alist of local users.
43 When t this still needs to be initialized.")
45 (defvar mail-passwd-files '("/etc/passwd")
46 "List of files from which to determine valid user names.")
48 (defvar mail-passwd-command nil
49 "Shell command to retrieve text to add to `/etc/passwd', or nil.")
51 (defvar mail-directory-names t
52 "Alist of mail address directory entries.
53 When t this still needs to be initialized.")
55 (defvar mail-address-field-regexp
56 "^\\(Resent-\\)?\\(To\\|From\\|CC\\|BCC\\|Reply-to\\):")
58 (defvar mail-complete-alist
59 `((,mail-address-field-regexp mail-get-names pattern)
60 ("Newsgroups:" . (if (boundp '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 Expression may reference variable `pattern' which is the string being completed.
69 If not on matching header, `mail-complete-function' gets called instead.")
72 (defvar mail-complete-style 'angles
73 "*Specifies how \\[mail-complete] formats the full name when it completes.
74 If `nil', they contain just the return address like:
76 If `parens', they look like:
77 king@grassland.com (Elvis Parsley)
78 If `angles', they look like:
79 Elvis Parsley <king@grassland.com>")
81 (defvar mail-complete-function 'ispell-complete-word
82 "Function to call when completing outside `mail-complete-alist'-header.")
85 (defvar mail-directory-function nil
86 "Function to get completions from directory service or `nil' for none.
87 See `mail-directory-requery'.")
90 ;; This is for when the directory is huge, or changes frequently.
91 (defvar mail-directory-requery nil
92 "When non-`nil' call `mail-directory-function' for each completion.
93 In that case, one argument gets passed to the function, the partial string
97 (defvar mail-directory-process nil
98 "Unix command when `mail-directory-function' is `mail-directory-process'.
99 This is a list of the form (COMMAND ARG ...), where each of the list elements
100 is evaluated. When `mail-directory-requery' is non-`nil', during
101 evaluation the variable `pattern' contains the partial input being completed.
104 '(remote-shell-program \"HOST\" \"-nl\" \"USER\" \"COMMAND\")
108 '(remote-shell-program \"HOST\" \"-n\" \"COMMAND '^\" pattern \"'\")")
110 (defvar mail-directory-stream ()
111 "List of (HOST SERVICE) for stream connection to mail directory.")
113 (defvar mail-directory-parser nil
114 "How to interpret the output of `mail-directory-function'.
115 Three types of values are possible:
117 - nil means to gather each line as one name
118 - regexp means first \\(grouping\\) in successive matches is name
119 - function called at beginning of buffer that returns an alist of names")
122 ;; Called from sendmail-send-it, or similar functions,
123 ;; only if some mail aliases are defined.
124 (defun expand-mail-aliases (beg end &optional exclude)
125 "Expand all mail aliases in suitable header fields found between BEG and END.
126 Suitable header fields are `To', `From', `CC' and `BCC', `Reply-to', and
127 their `Resent-' variants.
129 Optional second arg EXCLUDE may be a regular expression defining text to be
130 removed from alias expansions."
131 (sendmail-sync-aliases)
132 (if (eq mail-aliases t)
133 (progn (setq mail-aliases nil) (build-mail-aliases)))
135 (setq end (set-marker (make-marker) end))
136 (let ((case-fold-search nil))
137 (while (let ((case-fold-search t))
138 (re-search-forward mail-address-field-regexp end t))
139 (skip-chars-forward " \t")
142 ;; DISABLED-ALIASES records aliases temporarily disabled
143 ;; while we scan text that resulted from expanding those aliases.
144 ;; Each element is (ALIAS . TILL-WHEN), where TILL-WHEN
145 ;; is where to reenable the alias (expressed as number of chars
146 ;; counting from END1).
147 (disabled-aliases nil))
148 (re-search-forward "^[^ \t]" end 'move)
150 (skip-chars-backward " \t\n")
151 (setq end1 (point-marker))
153 (while (< (point) end1)
155 ;; Reenable any aliases which were disabled for ranges
156 ;; that we have passed out of.
157 (while (and disabled-aliases (> pos (- end1 (cdr (car disabled-aliases)))))
158 (setq disabled-aliases (cdr disabled-aliases)))
159 ;; EPOS gets position of end of next name;
160 ;; SEPLEN gets length of whitespace&separator that follows it.
161 (if (re-search-forward "[ \t]*[\n,][ \t]*" end1 t)
162 (setq epos (match-beginning 0)
163 seplen (- (point) epos))
164 (setq epos (marker-position end1) seplen 0))
166 (string (buffer-substring-no-properties pos epos)))
167 (if (and (not (assoc string disabled-aliases))
169 (cdr (assoc string mail-aliases))))
171 ;; This name is an alias. Disable it.
172 (setq disabled-aliases (cons (cons string (- end1 epos))
174 ;; Replace the alias with its expansion
175 ;; then rescan the expansion for more aliases.
180 (concat "\\b\\(" exclude "\\)\\b"))
181 (end (point-marker)))
183 (while (re-search-forward regexp end t)
186 (delete-region (point) (+ (point) (- epos pos)))
188 ;; Name is not an alias. Skip to start of next name.
190 (forward-char seplen))))
191 (set-marker end1 nil)))
192 (set-marker end nil)))
194 ;; Called by mail-setup, or similar functions, only if the file specified
195 ;; by mail-personal-alias-file (usually `~/.mailrc') exists.
196 (defun build-mail-aliases (&optional file)
197 "Read mail aliases from personal aliases file and set `mail-aliases'.
198 By default, this is the file specified by `mail-personal-alias-file'."
199 (setq file (expand-file-name (or file mail-personal-alias-file)))
201 (obuf (current-buffer)))
204 (setq buffer (generate-new-buffer " mailrc"))
207 (cond ((get-file-buffer file)
208 (insert (save-excursion
209 (set-buffer (get-file-buffer file))
210 (buffer-substring-no-properties
211 (point-min) (point-max)))))
212 ((file-exists-p file) (insert-file-contents file))
213 ((file-exists-p (setq file (concat "~/" file)))
214 (insert-file-contents file))
216 ;; Don't lose if no final newline.
217 (goto-char (point-max))
218 (or (eq (preceding-char) ?\n) (newline))
219 (goto-char (point-min))
220 ;; handle "\\\n" continuation lines
223 (if (= (preceding-char) ?\\)
224 (progn (delete-char -1) (delete-char 1) (insert ?\ ))
226 (goto-char (point-min))
227 ;; handle `source' directives -- Eddy/1994/May/25
228 (cond ((re-search-forward "^source[ \t]+" nil t)
229 (re-search-forward "\\S-+")
230 (setq file (buffer-substring-no-properties
231 (match-beginning 0) (match-end 0)))
233 (insert "# ") ; to ensure we don't re-process this file
235 (t (setq file nil))))
236 (goto-char (point-min))
237 (while (re-search-forward
238 "^\\(a\\|alias\\|g\\|group\\)[ \t]+\\([^ \t]+\\)" nil t)
239 (let* ((name (match-string 2))
240 (start (progn (skip-chars-forward " \t") (point))))
244 (buffer-substring-no-properties start (point))
247 (if buffer (kill-buffer buffer))
250 ;; Always autoloadable in case the user wants to define aliases
251 ;; interactively or in .emacs.
253 (defun define-mail-alias (name definition &optional from-mailrc-file)
254 "Define NAME as a mail alias that translates to DEFINITION.
255 This means that sending a message to NAME will actually send to DEFINITION.
257 Normally, the addresses in DEFINITION must be separated by commas.
258 If FROM-MAILRC-FILE is non-nil, then addresses in DEFINITION
259 can be separated by spaces; an address can contain spaces
260 if it is quoted with double-quotes."
262 (interactive "sDefine mail alias: \nsDefine %s as mail alias for: ")
263 ;; Read the defaults first, if we have not done so.
264 (sendmail-sync-aliases)
265 (if (eq mail-aliases t)
267 (setq mail-aliases nil)
268 (if (file-exists-p mail-personal-alias-file)
269 (build-mail-aliases))))
270 ;; strip garbage from front and end
271 (if (string-match "\\`[ \t\n,]+" definition)
272 (setq definition (substring definition (match-end 0))))
273 (if (string-match "[ \t\n,]+\\'" definition)
274 (setq definition (substring definition 0 (match-beginning 0))))
276 ;; If DEFINITION is null string, avoid looping even once.
277 (start (and (not (equal definition "")) 0))
278 (L (length definition))
281 ;; If we're reading from the mailrc file, then addresses are delimited
282 ;; by spaces, and addresses with embedded spaces must be surrounded by
283 ;; double-quotes. Otherwise, addresses are separated by commas.
285 (if (eq ?\" (aref definition start))
286 (setq start (1+ start)
287 end (string-match "\"[ \t,]*" definition start))
288 (setq end (string-match "[ \t,]+" definition start)))
289 (setq end (string-match "[ \t\n,]*,[ \t\n,]*" definition start)))
290 (setq result (cons (substring definition start end) result))
294 (setq definition (mapconcat (function identity)
297 (setq tem (assoc name mail-aliases))
299 (rplacd tem definition)
300 (setq mail-aliases (cons (cons name definition) mail-aliases)
304 (defun mail-complete (arg)
305 "Perform completion on header field or word preceding point.
306 Completable headers are according to `mail-complete-alist'. If none matches
307 current header, calls `mail-complete-function' and passes prefix arg if any."
309 ;; Read the defaults first, if we have not done so.
310 (sendmail-sync-aliases)
311 (if (eq mail-aliases t)
313 (setq mail-aliases nil)
314 (if (file-exists-p mail-personal-alias-file)
315 (build-mail-aliases))))
316 (let ((list mail-complete-alist))
317 (if (and (save-excursion (search-forward
318 (concat "\n" mail-header-separator "\n")
321 (if (re-search-backward "^[^\t]" nil t)
323 (if (looking-at (car (car list)))
324 (setq arg (cdr (car list))
326 (setq list (cdr list)))))
330 (skip-chars-backward "^ \t<,:")
332 (pattern (buffer-substring beg end))
334 (setq list (eval arg)
335 completion (try-completion pattern list))
336 (cond ((eq completion t))
338 (message "Can't find completion for \"%s\"" pattern)
340 ((not (string= pattern completion))
341 (delete-region beg end)
342 (let ((alist-elt (assoc completion mail-names)))
344 (cond ((eq mail-complete-style 'parens)
345 (insert completion " (" (cdr alist-elt) ")"))
346 ((eq mail-complete-style 'angles)
347 (insert (cdr alist-elt) " <" completion ">"))
349 (insert completion)))
350 (insert completion))))
352 (message "Making completion list...")
353 (with-output-to-temp-buffer "*Completions*"
354 (display-completion-list
355 (all-completions pattern list)))
356 (message "Making completion list...%s" "done"))))
357 (funcall mail-complete-function arg))))
359 (defun mail-get-names (pattern)
360 "Fetch local users and global mail addresses for completion.
361 Consults `/etc/passwd' and a directory service if one is set up via
362 `mail-directory-function'.
363 PATTERN is the string we want to complete."
364 (if (eq mail-local-names t)
366 (set-buffer (generate-new-buffer " passwd"))
367 (let ((files mail-passwd-files))
369 (insert-file-contents (car files) nil nil nil t)
370 (setq files (cdr files))))
371 (if mail-passwd-command
372 (call-process shell-file-name nil t nil
373 shell-command-switch mail-passwd-command))
374 (beginning-of-buffer)
375 (setq mail-local-names nil)
377 ;;Recognize lines like
378 ;; nobody:*:65534:65534::/:
379 ;; +demo::::::/bin/csh
383 ;; The second \(...\) matches the user id.
384 (if (looking-at "\\+?\\([^:@\n+]+\\):[^:\n]*:\\([^\n:]*\\):")
385 (add-to-list 'mail-local-names
386 (cons (match-string 1)
388 (string-to-int (match-string 2))))))
389 (beginning-of-line 2))
390 (kill-buffer (current-buffer))))
391 (if (or (eq mail-names t)
392 (eq mail-directory-names t))
394 (and mail-directory-function
395 (eq mail-directory-names t)
397 (mail-directory (if mail-directory-requery pattern))))
398 (or mail-directory-requery
399 (setq mail-directory-names directory))
403 (sort (append (if (consp mail-aliases)
405 (function (lambda (a) (list (car a))))
407 (if (consp mail-local-names)
409 (or directory mail-directory-names))
411 ;; should cache downcased strings
412 (string< (downcase (car a))
413 (downcase (car b)))))))))
417 (defun mail-directory (pattern)
418 "Call directory to get names matching PATTERN or all if `nil'.
419 Calls `mail-directory-function' and applies `mail-directory-parser' to output."
421 (message "Querying directory...")
422 (set-buffer (generate-new-buffer " *mail-directory*"))
423 (funcall mail-directory-function pattern)
426 (if (stringp mail-directory-parser)
427 (while (re-search-forward mail-directory-parser nil t)
429 (cons (match-string 1) directory)))
430 (if mail-directory-parser
431 (setq directory (funcall mail-directory-parser))
434 (cons (buffer-substring (point)
441 (kill-buffer (current-buffer))
442 (message "Querying directory...done")
446 (defun mail-directory-process (pattern)
447 "Call a Unix process to output names in directory.
448 See `mail-directory-process'."
449 (apply 'call-process (eval (car mail-directory-process)) nil t nil
450 (mapcar 'eval (cdr mail-directory-process))))
452 ;; This should handle a dialog. Currently expects port to spit out names.
453 (defun mail-directory-stream (pattern)
454 "Open a stream to retrieve names in directory.
455 See `mail-directory-stream'."
456 (let (mailalias-done)
457 (set-process-sentinel
458 (apply 'open-network-stream "mailalias" (current-buffer)
459 mail-directory-stream)
461 (setq mailalias-done t)))
462 (while (not mailalias-done)
465 (defun mail-sentto-newsgroups ()
466 "Return all entries from Newsgroups: header as completion alist."
468 (if (mail-position-on-field "newsgroups" t)
469 (let ((point (point))
471 (while (< (skip-chars-backward "^:, \t\n") 0)
472 (setq list `((,(buffer-substring (point) point))
474 (skip-chars-backward ", \t\n")
475 (setq point (point)))
480 ;;; mailalias.el ends here