1 ;;; mailalias.el --- expand and complete mailing address aliases -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985, 1987, 1995-1997, 2001-2014 Free Software
6 ;; Maintainer: emacs-devel@gnu.org
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
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.
34 (defgroup mailalias nil
35 "Expanding mail aliases."
38 (defcustom mail-passwd-files
'("/etc/passwd")
39 "List of files from which to determine valid user names."
40 :type
'(repeat string
)
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
))
48 (defvar mail-directory-names t
49 "Alist of mail address directory entries.
50 When t this still needs to be initialized.")
52 (defvar mail-address-field-regexp
53 "^\\(Resent-\\)?\\(To\\|From\\|CC\\|BCC\\|Reply-to\\):")
57 (defcustom mail-complete-alist
58 ;; Don't refer to mail-address-field-regexp here;
59 ;; that confuses some things such as cus-dep.el.
60 '(("^\\(Resent-\\)?\\(To\\|From\\|CC\\|BCC\\|Reply-to\\):"
61 .
(mail-get-names pattern
))
62 ("Newsgroups:" .
(if (boundp 'gnus-active-hashtb
)
64 (if (boundp news-group-article-assoc
)
65 news-group-article-assoc
)))
66 ("Followup-To:" .
(mail-sentto-newsgroups))
67 ;;("Distribution:" ???)
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."
75 (put 'mail-complete-alist
'risky-local-variable t
)
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:
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
))
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
))
93 (make-obsolete-variable 'mail-complete-function
94 'completion-at-point-functions
"24.1")
96 (defcustom mail-directory-function nil
97 "Function to get completions from directory service or nil for none.
98 See `mail-directory-requery'."
99 :type
'(choice function
(const nil
))
102 ;; This is for when the directory is huge, or changes frequently.
103 (defcustom mail-directory-requery nil
104 "When non-nil call `mail-directory-function' for each completion.
105 In that case, one argument gets passed to the function, the partial string
110 (defcustom mail-directory-process nil
111 "Shell command to get the list of names from a mail directory.
112 This value is used when the value of `mail-directory-function'
113 is `mail-directory-process'. The value should be a list
114 of the form (COMMAND ARG ...), where each of the list elements
115 is evaluated. COMMAND should evaluate to a string. When
116 `mail-directory-requery' is non-nil, during evaluation of these
117 elements, the variable `pattern' contains the partial input being
118 completed. `pattern' is nil when `mail-directory-requery' is nil.
120 The value might look like this:
122 '(remote-shell-program \"HOST\" \"-nl\" \"USER\" \"COMMAND\")
126 '(remote-shell-program \"HOST\" \"-n\" \"COMMAND '^\" pattern \"'\")"
129 (put 'mail-directory-process
'risky-local-variable t
)
131 (defcustom mail-directory-stream nil
132 "List of (HOST SERVICE) for stream connection to mail directory."
135 (put 'mail-directory-stream
'risky-local-variable t
)
137 (defcustom mail-directory-parser nil
138 "How to interpret the output of `mail-directory-function'.
139 Three types of values are possible:
141 - nil means to gather each line as one name
142 - regexp means first \\(grouping\\) in successive matches is name
143 - function called at beginning of buffer that returns an alist of names"
144 :type
'(choice (const nil
) regexp function
)
146 (put 'mail-directory-parser
'risky-local-variable t
)
148 ;; Internal variables.
151 "Alist of local users, aliases and directory entries as available.
152 Elements have the form (MAILNAME) or (MAILNAME . FULLNAME).
153 If the value means t, it means the real value should be calculated
154 for the next use. This is used in `mail-complete'.")
156 (defvar mail-local-names t
157 "Alist of local users.
158 When t this still needs to be initialized.")
161 ;; Called from sendmail-send-it, or similar functions,
162 ;; only if some mail aliases are defined.
164 (defun expand-mail-aliases (beg end
&optional exclude
)
165 "Expand all mail aliases in suitable header fields found between BEG and END.
166 If interactive, expand in header fields.
167 Suitable header fields are `To', `From', `CC' and `BCC', `Reply-to', and
168 their `Resent-' variants.
170 Optional second arg EXCLUDE may be a regular expression defining text to be
171 removed from alias expansions."
174 (list (goto-char (point-min))
176 (sendmail-sync-aliases)
177 (when (eq mail-aliases t
)
178 (setq mail-aliases nil
)
179 (build-mail-aliases))
182 (setq end
(set-marker (make-marker) end
))
183 (let ((case-fold-search nil
))
184 (while (let ((case-fold-search t
))
185 (re-search-forward mail-address-field-regexp end t
))
186 (skip-chars-forward " \t")
189 ;; DISABLED-ALIASES records aliases temporarily disabled
190 ;; while we scan text that resulted from expanding those aliases.
191 ;; Each element is (ALIAS . TILL-WHEN), where TILL-WHEN
192 ;; is where to reenable the alias (expressed as number of chars
193 ;; counting from END1).
194 (disabled-aliases nil
))
195 (re-search-forward "^[^ \t]" end
'move
)
197 (skip-chars-backward " \t\n")
198 (setq end1
(point-marker))
200 (while (< (point) end1
)
202 ;; Reenable any aliases which were disabled for ranges
203 ;; that we have passed out of.
204 (while (and disabled-aliases
205 (> pos
(- end1
(cdr (car disabled-aliases
)))))
206 (setq disabled-aliases
(cdr disabled-aliases
)))
207 ;; EPOS gets position of end of next name;
208 ;; SEPLEN gets length of whitespace&separator that follows it.
209 (if (re-search-forward "[ \t]*[\n,][ \t]*" end1 t
)
210 (setq epos
(match-beginning 0)
211 seplen
(- (point) epos
))
212 ;; Handle the last name in this header field.
213 ;; We already moved END1 back across whitespace after it.
214 (setq epos
(marker-position end1
) seplen
0))
215 (let ((string (buffer-substring-no-properties pos epos
))
217 (if (and (not (assoc string disabled-aliases
))
218 (setq translation
(cdr (assoc string mail-aliases
))))
220 ;; This name is an alias. Disable it.
221 (setq disabled-aliases
(cons (cons string
(- end1 epos
))
223 ;; Replace the alias with its expansion
224 ;; then rescan the expansion for more aliases.
228 (let ((regexp (concat "\\b\\(" exclude
"\\)\\b"))
229 (end (point-marker)))
231 (while (re-search-forward regexp end t
)
234 (delete-region (point) (+ (point) (- epos pos
)))
236 ;; Name is not an alias. Skip to start of next name.
238 (forward-char seplen
))))
239 (set-marker end1 nil
)))
240 (set-marker end nil
))))
242 ;; Called by mail-setup, or similar functions, only if the file specified
243 ;; by mail-personal-alias-file (usually `~/.mailrc') exists.
244 (defun build-mail-aliases (&optional file
)
245 "Read mail aliases from personal aliases file and set `mail-aliases'.
246 By default, this is the file specified by `mail-personal-alias-file'."
249 (read-file-name (format "Read mail alias file (default %s): "
250 mail-personal-alias-file
)
251 nil mail-personal-alias-file t
)))
252 (setq file
(expand-file-name (or file mail-personal-alias-file
)))
253 ;; In case mail-aliases is t, make sure define-mail-alias
254 ;; does not recursively call build-mail-aliases.
255 (setq mail-aliases nil
)
258 (cond ((get-file-buffer file
)
259 (insert (with-current-buffer (get-file-buffer file
)
260 (buffer-substring-no-properties
261 (point-min) (point-max)))))
262 ((file-exists-p file
) (insert-file-contents file
))
263 ((file-exists-p (setq file
(expand-file-name file
"~/")))
264 (insert-file-contents file
))
266 (goto-char (point-min))
267 ;; Delete comments from the contents.
268 (while (search-forward "# " nil t
)
269 (let ((p (- (point) 2)))
271 (delete-region p
(point))))
272 ;; Don't lose if no final newline.
273 (goto-char (point-max))
274 (or (eq (preceding-char) ?
\n) (newline))
275 (goto-char (point-min))
276 ;; handle "\\\n" continuation lines
279 (if (= (preceding-char) ?
\\)
280 (progn (delete-char -
1) (delete-char 1) (insert ?\
))
282 (goto-char (point-min))
283 ;; handle `source' directives -- Eddy/1994/May/25
284 (cond ((re-search-forward "^source[ \t]+" nil t
)
285 (re-search-forward "\\S-+")
286 (setq file
(buffer-substring-no-properties
287 (match-beginning 0) (match-end 0)))
289 (insert "# ") ; to ensure we don't re-process this file
291 (t (setq file nil
))))
292 (goto-char (point-min))
293 (while (re-search-forward
294 "^\\(a\\|alias\\|g\\|group\\)[ \t]+\\([^ \t\n]+\\)" nil t
)
295 (let* ((name (match-string 2))
296 (start (progn (skip-chars-forward " \t") (point)))
299 (setq value
(buffer-substring-no-properties start
(point)))
300 (unless (equal value
"")
301 (define-mail-alias name value t
))))
304 ;; Always autoloadable in case the user wants to define aliases
305 ;; interactively or in .emacs.
306 ;; define-mail-abbrev in mailabbrev.el duplicates much of this code.
308 (defun define-mail-alias (name definition
&optional from-mailrc-file
)
309 "Define NAME as a mail alias that translates to DEFINITION.
310 This means that sending a message to NAME will actually send to DEFINITION.
312 Normally, the addresses in DEFINITION must be separated by commas.
313 If FROM-MAILRC-FILE is non-nil, then addresses in DEFINITION
314 can be separated by spaces; an address can contain spaces
315 if it is quoted with double-quotes."
317 (interactive "sDefine mail alias: \nsDefine %s as mail alias for: ")
318 ;; Read the defaults first, if we have not done so.
319 ;; But not if we are doing that already right now.
320 (unless from-mailrc-file
321 (sendmail-sync-aliases))
322 (if (eq mail-aliases t
)
324 (setq mail-aliases nil
)
325 (if (file-exists-p mail-personal-alias-file
)
326 (build-mail-aliases))))
327 ;; strip garbage from front and end
328 (if (string-match "\\`[ \t\n,]+" definition
)
329 (setq definition
(substring definition
(match-end 0))))
330 (if (string-match "[ \t\n,]+\\'" definition
)
331 (setq definition
(substring definition
0 (match-beginning 0))))
333 (let* ((L (length definition
))
334 (start (if (> L
0) 0))
335 end this-entry result tem
)
339 ;; If we're reading from the mailrc file, addresses are
340 ;; delimited by spaces, and addresses with embedded spaces are
341 ;; surrounded by non-escaped double-quotes.
342 (if (eq ?
\" (aref definition start
))
343 (setq start
(1+ start
)
344 end
(and (string-match
345 "[^\\]\\(\\([\\][\\]\\)*\\)\"[ \t,]*"
348 (setq end
(string-match "[ \t,]+" definition start
)))
349 ;; Extract the address and advance the loop past it.
350 (setq this-entry
(substring definition start end
)
351 start
(and end
(/= (match-end 0) L
) (match-end 0)))
352 ;; If the full name contains a problem character, quote it.
353 (and (string-match "\\(.+?\\)[ \t]*\\(<.*>\\)" this-entry
)
354 (string-match "[^- !#$%&'*+/0-9=?A-Za-z^_`{|}~]"
355 (match-string 1 this-entry
))
356 (setq this-entry
(replace-regexp-in-string
357 "\\(.+?\\)[ \t]*\\(<.*>\\)"
360 ;; When we are not reading from .mailrc, addresses are
361 ;; separated by commas. Try to accept a rfc822-like syntax.
362 ;; (Todo: extend rfc822.el to do the work for us.)
363 ((equal (string-match
364 "[ \t,]*\\(\"\\(?:[^\"]\\|[^\\]\\(?:[\\][\\]\\)*\"\\)*\"[ \t]*\
365 <[-.!#$%&'*+/0-9=?A-Za-z^_`{|}~@]+>\\)[ \t,]*"
368 ;; If an entry has a valid [ "foo bar" <foo@example.com> ]
369 ;; form, use it literally . This also allows commas in the
370 ;; quoted string, e.g. [ "foo bar, jr" <foo@example.com> ]
371 (setq this-entry
(match-string 1 definition
)
372 start
(and (/= (match-end 0) L
) (match-end 0))))
374 ;; Otherwise, read the next address by looking for a comma.
375 (setq end
(string-match "[ \t\n,]*,[ \t\n]*" definition start
))
376 (setq this-entry
(substring definition start end
))
377 ;; Advance the loop past this address.
378 (setq start
(and end
(/= (match-end 0) L
) (match-end 0)))
379 ;; If the full name contains a problem character, quote it.
380 (and (string-match "\\(.+?\\)[ \t]*\\(<.*>\\)" this-entry
)
381 (string-match "[^- !#$%&'*+/0-9=?A-Za-z^_`{|}~]"
382 (match-string 1 this-entry
))
383 (setq this-entry
(replace-regexp-in-string
384 "\\(.+?\\)[ \t]*\\(<.*>\\)" "\"\\1\" \\2"
386 (push this-entry result
))
388 (setq definition
(mapconcat (function identity
)
389 (nreverse result
) ", "))
390 (setq tem
(assoc name mail-aliases
))
392 (rplacd tem definition
)
393 (setq mail-aliases
(cons (cons name definition
) mail-aliases
)
397 (defun mail-completion-at-point-function ()
398 "Compute completion data for mail aliases.
399 For use on `completion-at-point-functions'."
400 ;; Read the defaults first, if we have not done so.
401 (sendmail-sync-aliases)
402 (if (eq mail-aliases t
)
404 (setq mail-aliases nil
)
405 (if (file-exists-p mail-personal-alias-file
)
406 (build-mail-aliases))))
407 (let ((list mail-complete-alist
)
409 (if (and (< 0 (mail-header-end))
411 (if (re-search-backward "^[^\t ]" nil t
)
413 (if (looking-at (car (car list
)))
414 (setq list-exp
(cdr (car list
))
416 (setq list
(cdr list
)))))
420 (skip-chars-backward "^ \t<,:")
422 (table (completion-table-dynamic
424 (let ((pattern prefix
)) (eval list-exp
))))))
425 (list beg end table
)))))
428 (defun mail-complete (arg)
429 "Perform completion on header field or word preceding point.
430 Completable headers are according to `mail-complete-alist'. If none matches
431 current header, calls `mail-complete-function' and passes prefix ARG if any."
432 (declare (obsolete mail-completion-at-point-function
"24.1"))
434 ;; Read the defaults first, if we have not done so.
435 (sendmail-sync-aliases)
436 (if (eq mail-aliases t
)
438 (setq mail-aliases nil
)
439 (if (file-exists-p mail-personal-alias-file
)
440 (build-mail-aliases))))
441 (let ((data (mail-completion-at-point-function)))
443 (apply #'completion-in-region data
)
444 (funcall mail-complete-function arg
))))
446 (defun mail-completion-expand (table)
447 "Build new completion table that expands aliases.
448 Completes like TABLE except that if the completion is a valid alias,
449 it expands it to its full `mail-complete-style' form."
450 (lambda (string pred action
)
453 (let* ((comp (try-completion string table pred
))
454 (name (and (listp table
) comp
455 (assoc (if (stringp comp
) comp string
) table
))))
458 ((eq mail-complete-style
'parens
)
459 (concat (car name
) " (" (cdr name
) ")"))
460 ((eq mail-complete-style
'angles
)
461 (concat (cdr name
) " <" (car name
) ">"))
464 (complete-with-action action table string pred
)))))
466 (defun mail-get-names (prefix)
467 "Fetch local users and global mail addresses for completion.
468 Consults `/etc/passwd' and a directory service if one is set up via
469 `mail-directory-function'.
470 PREFIX is the string we want to complete."
471 (if (eq mail-local-names t
)
472 (with-current-buffer (generate-new-buffer " passwd")
473 (let ((files mail-passwd-files
))
475 (insert-file-contents (car files
) nil nil nil t
)
476 (setq files
(cdr files
))))
477 (if mail-passwd-command
478 (call-process shell-file-name nil t nil
479 shell-command-switch mail-passwd-command
))
480 (goto-char (point-min))
481 (setq mail-local-names nil
)
483 ;;Recognize lines like
484 ;; nobody:*:65534:65534::/:
485 ;; +demo::::::/bin/csh
489 ;; The second \(...\) matches the user id.
490 (if (looking-at "\\+?\\([^:@\n+]+\\):[^:\n]*:\\([^\n:]*\\):")
491 (add-to-list 'mail-local-names
492 (cons (match-string 1)
494 (string-to-number (match-string 2))))))
495 (beginning-of-line 2))
496 (kill-buffer (current-buffer))))
497 (if (or (eq mail-names t
)
498 (eq mail-directory-names t
))
500 (and mail-directory-function
501 (eq mail-directory-names t
)
503 (mail-directory (if mail-directory-requery prefix
))))
504 (or mail-directory-requery
505 (setq mail-directory-names directory
))
509 (sort (append (if (consp mail-aliases
)
511 (function (lambda (a) (list (car a
))))
513 (if (consp mail-local-names
)
516 (when (consp mail-directory-names
)
517 mail-directory-names
)))
519 ;; Should cache downcased strings.
520 (string< (downcase (car a
))
521 (downcase (car b
)))))))))
522 (mail-completion-expand mail-names
))
525 (defun mail-directory (prefix)
526 "Use mail-directory facility to get user names matching PREFIX.
527 If PREFIX is nil, get all the defined user names.
528 This function calls `mail-directory-function' to query the directory,
529 then uses `mail-directory-parser' to parse the output it returns."
530 (message "Querying directory...")
531 (with-current-buffer (generate-new-buffer " *mail-directory*")
532 (funcall mail-directory-function prefix
)
533 (goto-char (point-min))
535 (if (stringp mail-directory-parser
)
536 (while (re-search-forward mail-directory-parser nil t
)
537 (push (match-string 1) directory
))
538 (if mail-directory-parser
539 (setq directory
(funcall mail-directory-parser
))
541 (push (buffer-substring (point)
548 (kill-buffer (current-buffer))
549 (message "Querying directory...done")
552 (defvar mailalias-done
)
554 (defun mail-directory-process (prefix)
555 "Run a shell command to output names in directory.
556 See `mail-directory-process'."
557 (when (consp mail-directory-process
)
558 (let ((pattern prefix
)) ;Dynbind!
559 (apply 'call-process
(eval (car mail-directory-process
)) nil t nil
560 (mapcar 'eval
(cdr mail-directory-process
))))))
562 ;; This should handle a dialog. Currently expects port to spit out names.
563 (defun mail-directory-stream (prefix)
564 "Open a stream to retrieve names in directory.
565 See `mail-directory-stream'."
566 (let ((mailalias-done nil
)
567 (pattern prefix
)) ;Dynbind!
568 (set-process-sentinel
569 (apply 'open-network-stream
"mailalias" (current-buffer)
570 mail-directory-stream
)
572 (setq mailalias-done t
)))
573 (while (not mailalias-done
)
576 (defun mail-sentto-newsgroups ()
577 "Return all entries from Newsgroups: header as completion alist."
579 (if (mail-position-on-field "newsgroups" t
)
580 (let ((point (point))
582 (while (< (skip-chars-backward "^:, \t\n") 0)
583 (setq list
`((,(buffer-substring (point) point
))
585 (skip-chars-backward ", \t\n")
586 (setq point
(point)))
591 ;;; mailalias.el ends here