1;;; mailalias.el --- expand and complete mailing address aliases
2
3;; Copyright (C) 1985, 1987, 1995, 1996, 1997, 2001, 2002, 2003,
4;;   2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6;; Maintainer: FSF
7;; Keywords: mail
8
9;; This file is part of GNU Emacs.
10
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 2, or (at your option)
14;; any later version.
15
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.
20
21;; You should have received a copy of the GNU General Public License
22;; along with GNU Emacs; see the file COPYING.  If not, write to the
23;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24;; Boston, MA 02110-1301, USA.
25
26;;; Commentary:
27
28;; Basic functions for defining and expanding mail aliases.
29;; These seal off the interface to the alias-definition parts of a
30;; .mailrc file formatted for BSD's Mail or USL's mailx.
31
32;;; Code:
33
34(require 'sendmail)
35
36(defgroup mailalias nil
37  "Expanding mail aliases."
38  :group 'mail)
39
40(defcustom mail-passwd-files '("/etc/passwd")
41  "*List of files from which to determine valid user names."
42  :type '(repeat string)
43  :group 'mailalias)
44
45(defcustom mail-passwd-command nil
46  "*Shell command to retrieve text to add to `/etc/passwd', or nil."
47  :type '(choice string (const nil))
48  :group 'mailalias)
49
50(defvar mail-directory-names t
51  "Alist of mail address directory entries.
52When t this still needs to be initialized.")
53
54(defvar mail-address-field-regexp
55  "^\\(Resent-\\)?\\(To\\|From\\|CC\\|BCC\\|Reply-to\\):")
56
57(defcustom mail-complete-alist
58  ;; Don't use backquote here; we don't want backquote to get loaded
59  ;; just because of loading this file.
60  ;; Don't refer to mail-address-field-regexp here;
61  ;; that confuses some things such as cus-dep.el.
62  (cons '("^\\(Resent-\\)?\\(To\\|From\\|CC\\|BCC\\|Reply-to\\):"
63	  . (mail-get-names pattern))
64	'(("Newsgroups:" . (if (boundp 'gnus-active-hashtb)
65			       gnus-active-hashtb
66			     (if (boundp news-group-article-assoc)
67				 news-group-article-assoc)))
68	  ("Followup-To:" . (mail-sentto-newsgroups))
69	  ;;("Distribution:" ???)
70	  ))
71  "*Alist of header field and expression to return alist for completion.
72The expression may reference the variable `pattern'
73which will hold the string being completed.
74If not on matching header, `mail-complete-function' gets called instead."
75  :type 'alist
76  :group 'mailalias)
77(put 'mail-complete-alist 'risky-local-variable t)
78
79;;;###autoload
80(defcustom mail-complete-style 'angles
81  "*Specifies how \\[mail-complete] formats the full name when it completes.
82If `nil', they contain just the return address like:
83	king@grassland.com
84If `parens', they look like:
85	king@grassland.com (Elvis Parsley)
86If `angles', they look like:
87	Elvis Parsley <king@grassland.com>"
88  :type '(choice (const angles) (const parens) (const nil))
89  :group 'mailalias)
90
91(defcustom mail-complete-function 'ispell-complete-word
92  "*Function to call when completing outside `mail-complete-alist'-header."
93  :type '(choice function (const nil))
94  :group 'mailalias)
95
96(defcustom mail-directory-function nil
97  "*Function to get completions from directory service or nil for none.
98See `mail-directory-requery'."
99  :type '(choice function (const nil))
100  :group 'mailalias)
101
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.
105In that case, one argument gets passed to the function, the partial string
106entered so far."
107  :type 'boolean
108  :group 'mailalias)
109
110(defcustom mail-directory-process nil
111  "*Shell command to get the list of names from a mail directory.
112This value is used when the value of `mail-directory-function'
113is `mail-directory-process'.  The value should be a list
114of the form (COMMAND ARG ...), where each of the list elements
115is evaluated.  COMMAND should evaluate to a string.  When
116`mail-directory-requery' is non-nil, during evaluation of these
117elements, the variable `pattern' contains the partial input being
118completed.  `pattern' is nil when `mail-directory-requery' is nil.
119
120The value might look like this:
121
122  '(remote-shell-program \"HOST\" \"-nl\" \"USER\" \"COMMAND\")
123
124or like this:
125
126  '(remote-shell-program \"HOST\" \"-n\" \"COMMAND '^\" pattern \"'\")"
127  :type 'sexp
128  :group 'mailalias)
129(put 'mail-directory-process 'risky-local-variable t)
130
131(defcustom mail-directory-stream nil
132  "*List of (HOST SERVICE) for stream connection to mail directory."
133  :type 'sexp
134  :group 'mailalias)
135(put 'mail-directory-stream 'risky-local-variable t)
136
137(defcustom mail-directory-parser nil
138  "*How to interpret the output of `mail-directory-function'.
139Three types of values are possible:
140
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)
145  :group 'mailalias)
146(put 'mail-directory-parser 'risky-local-variable t)
147
148;; Internal variables.
149
150(defvar mail-names t
151  "Alist of local users, aliases and directory entries as available.
152Elements have the form (MAILNAME) or (MAILNAME . FULLNAME).
153If the value means t, it means the real value should be calculated
154for the next use.  This is used in `mail-complete'.")
155
156(defvar mail-local-names t
157  "Alist of local users.
158When t this still needs to be initialized.")
159
160
161;; Called from sendmail-send-it, or similar functions,
162;; only if some mail aliases are defined.
163;;;###autoload
164(defun expand-mail-aliases (beg end &optional exclude)
165  "Expand all mail aliases in suitable header fields found between BEG and END.
166If interactive, expand in header fields.
167Suitable header fields are `To', `From', `CC' and `BCC', `Reply-to', and
168their `Resent-' variants.
169
170Optional second arg EXCLUDE may be a regular expression defining text to be
171removed from alias expansions."
172  (interactive
173   (save-excursion
174     (list (goto-char (point-min))
175	   (mail-header-end))))
176  (sendmail-sync-aliases)
177  (when (eq mail-aliases t)
178    (setq mail-aliases nil)
179    (build-mail-aliases))
180  (save-excursion
181    (goto-char beg)
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")
187	(let ((beg1 (point))
188	      end1 pos epos seplen
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)
196	  (beginning-of-line)
197	  (skip-chars-backward " \t\n")
198	  (setq end1 (point-marker))
199	  (goto-char beg1)
200	  (while (< (point) end1)
201	    (setq pos (point))
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	      (setq epos (marker-position end1) seplen 0))
213	    (let ((string (buffer-substring-no-properties pos epos))
214		  translation)
215	      (if (and (not (assoc string disabled-aliases))
216		       (setq translation (cdr (assoc string mail-aliases))))
217		  (progn
218		    ;; This name is an alias.  Disable it.
219		    (setq disabled-aliases (cons (cons string (- end1 epos))
220						 disabled-aliases))
221		    ;; Replace the alias with its expansion
222		    ;; then rescan the expansion for more aliases.
223		    (goto-char pos)
224		    (insert translation)
225		    (when exclude
226		      (let ((regexp (concat "\\b\\(" exclude "\\)\\b"))
227			    (end (point-marker)))
228			(goto-char pos)
229			(while (re-search-forward regexp end t)
230			  (replace-match ""))
231			(goto-char end)))
232		    (delete-region (point) (+ (point) (- epos pos)))
233		    (goto-char pos))
234		;; Name is not an alias.  Skip to start of next name.
235		(goto-char epos)
236		(forward-char seplen))))
237	  (set-marker end1 nil)))
238      (set-marker end nil))))
239
240;; Called by mail-setup, or similar functions, only if the file specified
241;; by mail-personal-alias-file (usually `~/.mailrc') exists.
242(defun build-mail-aliases (&optional file)
243  "Read mail aliases from personal aliases file and set `mail-aliases'.
244By default, this is the file specified by `mail-personal-alias-file'."
245  (setq file (expand-file-name (or file mail-personal-alias-file)))
246  ;; In case mail-aliases is t, make sure define-mail-alias
247  ;; does not recursively call build-mail-aliases.
248  (setq mail-aliases nil)
249  (let ((buffer nil)
250	(obuf (current-buffer)))
251    (unwind-protect
252	(progn
253	  (setq buffer (generate-new-buffer " mailrc"))
254	  (set-buffer buffer)
255	  (while file
256	    (cond ((get-file-buffer file)
257		   (insert (save-excursion
258			     (set-buffer (get-file-buffer file))
259			     (buffer-substring-no-properties
260			      (point-min) (point-max)))))
261		  ((file-exists-p file) (insert-file-contents file))
262		  ((file-exists-p (setq file (concat "~/" file)))
263		   (insert-file-contents file))
264		  (t (setq file nil)))
265	    (goto-char (point-min))
266	    ;; Delete comments from the contents.
267	    (while (search-forward "# " nil t)
268	      (let ((p (- (point) 2)))
269		(end-of-line)
270		(delete-region p (point))))
271	    ;; Don't lose if no final newline.
272	    (goto-char (point-max))
273	    (or (eq (preceding-char) ?\n) (newline))
274	    (goto-char (point-min))
275	    ;; handle "\\\n" continuation lines
276	    (while (not (eobp))
277	      (end-of-line)
278	      (if (= (preceding-char) ?\\)
279		  (progn (delete-char -1) (delete-char 1) (insert ?\ ))
280	        (forward-char 1)))
281	    (goto-char (point-min))
282	    ;; handle `source' directives -- Eddy/1994/May/25
283	    (cond ((re-search-forward "^source[ \t]+" nil t)
284		   (re-search-forward "\\S-+")
285		   (setq file (buffer-substring-no-properties
286			       (match-beginning 0) (match-end 0)))
287		   (beginning-of-line)
288		   (insert "# ") ; to ensure we don't re-process this file
289		   (beginning-of-line))
290		  (t (setq file nil))))
291	  (goto-char (point-min))
292	  (while (re-search-forward
293		  "^\\(a\\|alias\\|g\\|group\\)[ \t]+\\([^ \t\n]+\\)" nil t)
294	    (let* ((name (match-string 2))
295		   (start (progn (skip-chars-forward " \t") (point)))
296		   value)
297	      (end-of-line)
298	      (setq value (buffer-substring-no-properties start (point)))
299	      (unless (equal value "")
300		(define-mail-alias name value t))))
301	  mail-aliases)
302      (if buffer (kill-buffer buffer))
303      (set-buffer obuf))))
304
305;; Always autoloadable in case the user wants to define aliases
306;; interactively or in .emacs.
307;;;###autoload
308(defun define-mail-alias (name definition &optional from-mailrc-file)
309  "Define NAME as a mail alias that translates to DEFINITION.
310This means that sending a message to NAME will actually send to DEFINITION.
311
312Normally, the addresses in DEFINITION must be separated by commas.
313If FROM-MAILRC-FILE is non-nil, then addresses in DEFINITION
314can be separated by spaces; an address can contain spaces
315if it is quoted with double-quotes."
316
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)
323      (progn
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))))
332  (let ((result '())
333	;; If DEFINITION is null string, avoid looping even once.
334	(start (and (not (equal definition "")) 0))
335	(L (length definition))
336	convert-backslash
337	end tem)
338    (while start
339      (setq convert-backslash nil)
340      ;; If we're reading from the mailrc file, then addresses are delimited
341      ;; by spaces, and addresses with embedded spaces must be surrounded by
342      ;; double-quotes.  Otherwise, addresses are separated by commas.
343      (if from-mailrc-file
344	  (if (eq ?\" (aref definition start))
345	      ;; The following test on `found' compensates for a bug
346	      ;; in match-end, which does not return nil when match
347	      ;; failed.
348	      (let ((found (string-match "[^\\]\\(\\([\\][\\]\\)*\\)\"[ \t,]*"
349					 definition start)))
350		(setq start (1+ start)
351		      end (and found (match-end 1))
352		      convert-backslash t))
353	    (setq end (string-match "[ \t,]+" definition start)))
354	(setq end (string-match "[ \t\n,]*,[ \t\n,]*" definition start)))
355      (let ((temp (substring definition start end))
356	    (pos 0))
357	(setq start (and end
358			 (/= (match-end 0) L)
359			 (match-end 0)))
360	(if convert-backslash
361	    (while (string-match "[\\]" temp pos)
362	      (setq temp (replace-match "" t t temp))
363	      (if start
364		  (setq start (1- start)))
365	      (setq pos (match-end 0))))
366	(setq result (cons temp result))))
367    (setq definition (mapconcat (function identity)
368				(nreverse result)
369				", "))
370    (setq tem (assoc name mail-aliases))
371    (if tem
372	(rplacd tem definition)
373      (setq mail-aliases (cons (cons name definition) mail-aliases)
374	    mail-names t))))
375
376;;;###autoload
377(defun mail-complete (arg)
378  "Perform completion on header field or word preceding point.
379Completable headers are according to `mail-complete-alist'.  If none matches
380current header, calls `mail-complete-function' and passes prefix arg if any."
381  (interactive "P")
382  ;; Read the defaults first, if we have not done so.
383  (sendmail-sync-aliases)
384  (if (eq mail-aliases t)
385      (progn
386	(setq mail-aliases nil)
387	(if (file-exists-p mail-personal-alias-file)
388	    (build-mail-aliases))))
389  (let ((list mail-complete-alist))
390    (if (and (< 0 (mail-header-end))
391	     (save-excursion
392	       (if (re-search-backward "^[^\t]" nil t)
393		   (while list
394		     (if (looking-at (car (car list)))
395			 (setq arg (cdr (car list))
396			       list ())
397		       (setq list (cdr list)))))
398	       arg))
399	(let* ((end (point))
400	       (beg (save-excursion
401		      (skip-chars-backward "^ \t<,:")
402		      (point)))
403	       (pattern (buffer-substring beg end))
404	       completion)
405	  (setq list (eval arg)
406		completion (try-completion pattern list))
407	  (cond ((eq completion t))
408		((null completion)
409		 (message "Can't find completion for \"%s\"" pattern)
410		 (ding))
411		((not (string= pattern completion))
412		 (delete-region beg end)
413		 (let ((alist-elt (assoc completion mail-names)))
414		   (if (cdr alist-elt)
415		       (cond ((eq mail-complete-style 'parens)
416			      (insert completion " (" (cdr alist-elt) ")"))
417			     ((eq mail-complete-style 'angles)
418			      (insert (cdr alist-elt) " <" completion ">"))
419			     (t
420			      (insert completion)))
421		     (insert completion))))
422		(t
423		 (message "Making completion list...")
424		 (with-output-to-temp-buffer "*Completions*"
425		   (display-completion-list
426		    (all-completions pattern list)))
427		 (message "Making completion list...%s" "done"))))
428      (funcall mail-complete-function arg))))
429
430(defun mail-get-names (pattern)
431  "Fetch local users and global mail addresses for completion.
432Consults `/etc/passwd' and a directory service if one is set up via
433`mail-directory-function'.
434PATTERN is the string we want to complete."
435  (if (eq mail-local-names t)
436      (save-excursion
437	(set-buffer (generate-new-buffer " passwd"))
438	(let ((files mail-passwd-files))
439	  (while files
440	    (insert-file-contents (car files) nil nil nil t)
441	    (setq files (cdr files))))
442	(if mail-passwd-command
443	    (call-process shell-file-name nil t nil
444			  shell-command-switch mail-passwd-command))
445	(goto-char (point-min))
446	(setq mail-local-names nil)
447	(while (not (eobp))
448	  ;;Recognize lines like
449	  ;;  nobody:*:65534:65534::/:
450	  ;;  +demo::::::/bin/csh
451	  ;;  +ethanb
452	  ;;while skipping
453	  ;;  +@SOFTWARE
454	  ;; The second \(...\) matches the user id.
455	  (if (looking-at "\\+?\\([^:@\n+]+\\):[^:\n]*:\\([^\n:]*\\):")
456	      (add-to-list 'mail-local-names
457			   (cons (match-string 1)
458				 (user-full-name
459				  (string-to-number (match-string 2))))))
460	  (beginning-of-line 2))
461	(kill-buffer (current-buffer))))
462  (if (or (eq mail-names t)
463	  (eq mail-directory-names t))
464      (let (directory)
465	(and mail-directory-function
466	     (eq mail-directory-names t)
467	     (setq directory
468		   (mail-directory (if mail-directory-requery pattern))))
469	(or mail-directory-requery
470	    (setq mail-directory-names directory))
471	(if (or directory
472		(eq mail-names t))
473	    (setq mail-names
474		  (sort (append (if (consp mail-aliases)
475				    (mapcar
476				     (function (lambda (a) (list (car a))))
477				     mail-aliases))
478				(if (consp mail-local-names)
479				    mail-local-names)
480				(or directory
481				    (when (consp mail-directory-names)
482				      mail-directory-names)))
483			(lambda (a b)
484			  ;; should cache downcased strings
485			  (string< (downcase (car a))
486				   (downcase (car b)))))))))
487  mail-names)
488
489
490(defun mail-directory (pattern)
491  "Use mail-directory facility to get user names matching PATTERN.
492If PATTERN is nil, get all the defined user names.
493This function calls `mail-directory-function' to query the directory,
494then uses `mail-directory-parser' to parse the output it returns."
495  (save-excursion
496    (message "Querying directory...")
497    (set-buffer (generate-new-buffer " *mail-directory*"))
498    (funcall mail-directory-function pattern)
499    (goto-char 1)
500    (let (directory)
501      (if (stringp mail-directory-parser)
502	  (while (re-search-forward mail-directory-parser nil t)
503	    (setq directory
504		  (cons (match-string 1) directory)))
505	(if mail-directory-parser
506	    (setq directory (funcall mail-directory-parser))
507	  (while (not (eobp))
508	    (setq directory
509		  (cons (buffer-substring (point)
510					  (progn
511					    (forward-line)
512					    (if (bolp)
513						(1- (point))
514					      (point))))
515			directory)))))
516      (kill-buffer (current-buffer))
517      (message "Querying directory...done")
518      directory)))
519
520
521(defun mail-directory-process (pattern)
522  "Run a shell command to output names in directory.
523See `mail-directory-process'."
524  (when (consp mail-directory-process)
525    (apply 'call-process (eval (car mail-directory-process)) nil t nil
526	   (mapcar 'eval (cdr mail-directory-process)))))
527
528;; This should handle a dialog.  Currently expects port to spit out names.
529(defun mail-directory-stream (pattern)
530  "Open a stream to retrieve names in directory.
531See `mail-directory-stream'."
532  (let (mailalias-done)
533    (set-process-sentinel
534     (apply 'open-network-stream "mailalias" (current-buffer)
535	    mail-directory-stream)
536     (lambda (x y)
537       (setq mailalias-done t)))
538    (while (not mailalias-done)
539      (sit-for .1))))
540
541(defun mail-sentto-newsgroups ()
542  "Return all entries from Newsgroups: header as completion alist."
543  (save-excursion
544    (if (mail-position-on-field "newsgroups" t)
545	(let ((point (point))
546	      list)
547	  (while (< (skip-chars-backward "^:, \t\n") 0)
548	    (setq list `((,(buffer-substring (point) point))
549			 ,@list))
550	    (skip-chars-backward ", \t\n")
551	    (setq point (point)))
552	  list))))
553
554(provide 'mailalias)
555
556;;; arch-tag: 1d6a0f87-eb34-4d45-8816-60c1b952cf46
557;;; mailalias.el ends here
558