1;;; mailalias.el --- expand and complete mailing address aliases -*- lexical-binding: t -*-
2
3;; Copyright (C) 1985, 1987, 1995-1997, 2001-2021 Free Software
4;; Foundation, Inc.
5
6;; Maintainer: emacs-devel@gnu.org
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 3 of the License, or
14;; (at your option) 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.  If not, see <https://www.gnu.org/licenses/>.
23
24;;; Commentary:
25
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.
29
30;;; Code:
31
32(require 'sendmail)
33
34(defgroup mailalias nil
35  "Expanding mail aliases."
36  :group 'mail)
37
38(defcustom mail-passwd-files '("/etc/passwd")
39  "List of files from which to determine valid user names."
40  :type '(repeat string)
41  :group 'mailalias)
42
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))
46  :group 'mailalias)
47
48(defvar mail-directory-names t
49  "Alist of mail address directory entries.
50When t this still needs to be initialized.")
51
52(defvar mail-address-field-regexp
53  "^\\(Resent-\\)?\\(To\\|From\\|Cc\\|Bcc\\|Reply-To\\):")
54
55;; `pattern' is bound dynamically before evaluating the forms in
56;; `mail-complete-alist' and may be part of user customizations of
57;; that variable.
58(with-suppressed-warnings ((lexical pattern))
59  (defvar pattern))
60
61(defcustom mail-complete-alist
62  ;; Don't refer to mail-address-field-regexp here;
63  ;; that confuses some things such as cus-dep.el.
64  '(("^\\(Resent-\\)?\\(To\\|From\\|Cc\\|Bcc\\|Reply-To\\):"
65     . (mail-get-names pattern))
66    ("Newsgroups:" . (if (boundp 'gnus-active-hashtb)
67                         gnus-active-hashtb
68                       (if (boundp news-group-article-assoc)
69                           news-group-article-assoc)))
70    ("Followup-To:" . (mail-sentto-newsgroups))
71    ;;("Distribution:" ???)
72    )
73  "Alist of header field and expression to return alist for completion.
74The expression may reference the variable `pattern'
75which will hold the string being completed.
76If not on matching header, `mail-complete-function' gets called instead."
77  :type 'alist
78  :group 'mailalias)
79(put 'mail-complete-alist 'risky-local-variable t)
80
81;;;###autoload
82(defcustom mail-complete-style 'angles
83  "Specifies how \\[mail-complete] formats the full name when it completes.
84If nil, they contain just the return address like:
85	king@grassland.com
86If `parens', they look like:
87	king@grassland.com (Elvis Parsley)
88If `angles', they look like:
89	Elvis Parsley <king@grassland.com>"
90  :type '(choice (const angles) (const parens) (const nil))
91  :group 'mailalias)
92
93(defcustom mail-complete-function 'ispell-complete-word
94  "Function to call when completing outside `mail-complete-alist'-header."
95  :type '(choice function (const nil))
96  :group 'mailalias)
97(make-obsolete-variable 'mail-complete-function
98                        'completion-at-point-functions "24.1")
99
100(defcustom mail-directory-function nil
101  "Function to get completions from directory service or nil for none.
102See `mail-directory-requery'."
103  :type '(choice function (const nil))
104  :group 'mailalias)
105
106;; This is for when the directory is huge, or changes frequently.
107(defcustom mail-directory-requery nil
108  "When non-nil call `mail-directory-function' for each completion.
109In that case, one argument gets passed to the function, the partial string
110entered so far."
111  :type 'boolean
112  :group 'mailalias)
113
114(defcustom mail-directory-process nil
115  "Shell command to get the list of names from a mail directory.
116This value is used when the value of `mail-directory-function'
117is `mail-directory-process'.  The value should be a list
118of the form (COMMAND ARG ...), where each of the list elements
119is evaluated.  COMMAND should evaluate to a string.  When
120`mail-directory-requery' is non-nil, during evaluation of these
121elements, the variable `pattern' contains the partial input being
122completed.  `pattern' is nil when `mail-directory-requery' is nil.
123
124The value might look like this:
125
126  (remote-shell-program \"HOST\" \"-nl\" \"USER\" \"COMMAND\")
127
128or like this:
129
130  (remote-shell-program \"HOST\" \"-n\" \"COMMAND \\='^\" pattern \"\\='\")"
131  :type 'sexp
132  :group 'mailalias)
133(put 'mail-directory-process 'risky-local-variable t)
134
135(defcustom mail-directory-stream nil
136  "List of (HOST SERVICE) for stream connection to mail directory."
137  :type '(choice (const nil)
138                 (list (string :tag "Host name or ip address")
139                       (choice (integer :tag "Service port number")
140                               (string :tag "Service name"))
141                       (plist :inline t
142                              :tag "Additional open-network-stream parameters")))
143  :group 'mailalias)
144(put 'mail-directory-stream 'risky-local-variable t)
145
146(defcustom mail-directory-parser nil
147  "How to interpret the output of `mail-directory-function'.
148Three types of values are possible:
149
150  - nil means to gather each line as one name
151  - regexp means first \\(grouping\\) in successive matches is name
152  - function called at beginning of buffer that returns an alist of names"
153  :type '(choice (const nil) regexp function)
154  :group 'mailalias)
155(put 'mail-directory-parser 'risky-local-variable t)
156
157;; Internal variables.
158
159(defvar mail-names t
160  "Alist of local users, aliases and directory entries as available.
161Elements have the form (MAILNAME) or (MAILNAME . FULLNAME).
162If the value means t, it means the real value should be calculated
163for the next use.  This is used in `mail-complete'.")
164
165(defvar mail-local-names t
166  "Alist of local users.
167When t this still needs to be initialized.")
168
169
170;; Called from sendmail-send-it, or similar functions,
171;; only if some mail aliases are defined.
172;;;###autoload
173(defun expand-mail-aliases (beg end &optional exclude)
174  "Expand all mail aliases in suitable header fields found between BEG and END.
175If interactive, expand in header fields.
176Suitable header fields are `To', `From', `Cc' and `Bcc', `Reply-To', and
177their `Resent-' variants.
178
179Optional second arg EXCLUDE may be a regular expression defining text to be
180removed from alias expansions."
181  (interactive
182   (save-excursion
183     (list (goto-char (point-min))
184	   (mail-header-end))))
185  (sendmail-sync-aliases)
186  (when (eq mail-aliases t)
187    (setq mail-aliases nil)
188    (build-mail-aliases))
189  (save-excursion
190    (goto-char beg)
191    (setq end (set-marker (make-marker) end))
192    (let ((case-fold-search nil))
193      (while (let ((case-fold-search t))
194	       (re-search-forward mail-address-field-regexp end t))
195	(skip-chars-forward " \t")
196	(let ((beg1 (point))
197	      end1 pos epos seplen
198	      ;; DISABLED-ALIASES records aliases temporarily disabled
199	      ;; while we scan text that resulted from expanding those aliases.
200	      ;; Each element is (ALIAS . TILL-WHEN), where TILL-WHEN
201	      ;; is where to reenable the alias (expressed as number of chars
202	      ;; counting from END1).
203	      (disabled-aliases nil))
204	  (re-search-forward "^[^ \t]" end 'move)
205	  (beginning-of-line)
206	  (skip-chars-backward " \t\n")
207	  (setq end1 (point-marker))
208	  (goto-char beg1)
209	  (while (< (point) end1)
210	    (setq pos (point))
211	    ;; Reenable any aliases which were disabled for ranges
212	    ;; that we have passed out of.
213	    (while (and disabled-aliases
214			(> pos (- end1 (cdr (car disabled-aliases)))))
215	      (setq disabled-aliases (cdr disabled-aliases)))
216	    ;; EPOS gets position of end of next name;
217	    ;; SEPLEN gets length of whitespace&separator that follows it.
218	    (if (re-search-forward "[ \t]*[\n,][ \t]*" end1 t)
219		(setq epos (match-beginning 0)
220		      seplen (- (point) epos))
221	      ;; Handle the last name in this header field.
222	      ;; We already moved END1 back across whitespace after it.
223 	      (setq epos (marker-position end1) seplen 0))
224	    (let ((string (buffer-substring-no-properties pos epos))
225		  translation)
226	      (if (and (not (assoc string disabled-aliases))
227		       (setq translation (cdr (assoc string mail-aliases))))
228		  (progn
229		    ;; This name is an alias.  Disable it.
230		    (setq disabled-aliases (cons (cons string (- end1 epos))
231						 disabled-aliases))
232		    ;; Replace the alias with its expansion
233		    ;; then rescan the expansion for more aliases.
234		    (goto-char pos)
235		    (insert translation)
236		    (when exclude
237		      (let ((regexp (concat "\\b\\(" exclude "\\)\\b"))
238			    (end (point-marker)))
239			(goto-char pos)
240			(while (re-search-forward regexp end t)
241			  (replace-match ""))
242			(goto-char end)))
243		    (delete-region (point) (+ (point) (- epos pos)))
244		    (goto-char pos))
245		;; Name is not an alias.  Skip to start of next name.
246		(goto-char epos)
247		(forward-char seplen))))
248	  (set-marker end1 nil)))
249      (set-marker end nil))))
250
251;; Called by mail-setup, or similar functions, only if the file specified
252;; by mail-personal-alias-file (usually `~/.mailrc') exists.
253(defun build-mail-aliases (&optional file)
254  "Read mail aliases from personal aliases file and set `mail-aliases'.
255By default, this is the file specified by `mail-personal-alias-file'."
256  (interactive
257   (list
258    (read-file-name
259     (format-prompt "Read mail alias file" mail-personal-alias-file)
260     nil mail-personal-alias-file t)))
261  (setq file (expand-file-name (or file mail-personal-alias-file)))
262  ;; In case mail-aliases is t, make sure define-mail-alias
263  ;; does not recursively call build-mail-aliases.
264  (setq mail-aliases nil)
265  (with-temp-buffer
266    (while file
267      (cond ((get-file-buffer file)
268             (insert (with-current-buffer (get-file-buffer file)
269                       (buffer-substring-no-properties
270                        (point-min) (point-max)))))
271            ((file-exists-p file) (insert-file-contents file))
272            ((file-exists-p (setq file (expand-file-name file "~/")))
273             (insert-file-contents file))
274            (t (setq file nil)))
275      (goto-char (point-min))
276      ;; Delete comments from the contents.
277      (while (search-forward "# " nil t)
278        (let ((p (- (point) 2)))
279          (end-of-line)
280          (delete-region p (point))))
281      ;; Don't lose if no final newline.
282      (goto-char (point-max))
283      (or (eq (preceding-char) ?\n) (newline))
284      (goto-char (point-min))
285      ;; handle "\\\n" continuation lines
286      (while (not (eobp))
287        (end-of-line)
288        (if (= (preceding-char) ?\\)
289            (progn (delete-char -1) (delete-char 1) (insert ?\ ))
290          (forward-char 1)))
291      (goto-char (point-min))
292      ;; handle `source' directives -- Eddy/1994/May/25
293      (cond ((re-search-forward "^source[ \t]+" nil t)
294             (re-search-forward "\\S-+")
295             (setq file (buffer-substring-no-properties
296                         (match-beginning 0) (match-end 0)))
297             (beginning-of-line)
298             (insert "# ")   ; to ensure we don't re-process this file
299             (beginning-of-line))
300            (t (setq file nil))))
301    (goto-char (point-min))
302    (while (re-search-forward
303            "^\\(a\\|alias\\|g\\|group\\)[ \t]+\\([^ \t\n]+\\)" nil t)
304      (let* ((name (match-string 2))
305             (start (progn (skip-chars-forward " \t") (point)))
306             value)
307        (end-of-line)
308        (setq value (buffer-substring-no-properties start (point)))
309        (unless (equal value "")
310          (define-mail-alias name value t))))
311    mail-aliases))
312
313;; Always autoloadable in case the user wants to define aliases
314;; interactively or in .emacs.
315;; define-mail-abbrev in mailabbrev.el duplicates much of this code.
316;;;###autoload
317(defun define-mail-alias (name definition &optional from-mailrc-file)
318  "Define NAME as a mail alias that translates to DEFINITION.
319This means that sending a message to NAME will actually send to DEFINITION.
320
321Normally, the addresses in DEFINITION must be separated by commas.
322If FROM-MAILRC-FILE is non-nil, then addresses in DEFINITION
323can be separated by spaces; an address can contain spaces
324if it is quoted with double-quotes."
325
326  (interactive "sDefine mail alias: \nsDefine %s as mail alias for: ")
327  ;; Read the defaults first, if we have not done so.
328  ;; But not if we are doing that already right now.
329  (unless from-mailrc-file
330    (sendmail-sync-aliases))
331  (if (eq mail-aliases t)
332      (progn
333	(setq mail-aliases nil)
334	(if (file-exists-p mail-personal-alias-file)
335	    (build-mail-aliases))))
336  ;; strip garbage from front and end
337  (if (string-match "\\`[ \t\n,]+" definition)
338      (setq definition (substring definition (match-end 0))))
339  (if (string-match "[ \t\n,]+\\'" definition)
340      (setq definition (substring definition 0 (match-beginning 0))))
341
342  (let* ((L (length definition))
343	 (start (if (> L 0) 0))
344	 end this-entry result tem)
345    (while start
346      (cond
347       (from-mailrc-file
348	;; If we're reading from the mailrc file, addresses are
349	;; delimited by spaces, and addresses with embedded spaces are
350	;; surrounded by non-escaped double-quotes.
351	(if (eq ?\" (aref definition start))
352	    (setq start (1+ start)
353		  end (and (string-match
354			    "[^\\]\\(\\([\\][\\]\\)*\\)\"[ \t,]*"
355			    definition start)
356			   (match-end 1)))
357	  (setq end (string-match "[ \t,]+" definition start)))
358	;; Extract the address and advance the loop past it.
359	(setq this-entry (substring definition start end)
360	      start (and end (/= (match-end 0) L) (match-end 0)))
361	;; If the full name contains a problem character, quote it.
362	(and (string-match "\\(.+?\\)[ \t]*\\(<.*>\\)" this-entry)
363	     (string-match "[^- !#$%&'*+/0-9=?A-Za-z^_`{|}~]"
364			   (match-string 1 this-entry))
365	     (setq this-entry (replace-regexp-in-string
366			       "\\(.+?\\)[ \t]*\\(<.*>\\)"
367			       "\"\\1\" \\2"
368			       this-entry))))
369       ;; When we are not reading from .mailrc, addresses are
370       ;; separated by commas.  Try to accept a rfc822-like syntax.
371       ;; (Todo: extend rfc822.el to do the work for us.)
372       ((equal (string-match
373		"[ \t,]*\\(\"\\(?:[^\"]\\|[^\\]\\(?:[\\][\\]\\)*\"\\)*\"[ \t]*\
374<[-.!#$%&'*+/0-9=?A-Za-z^_`{|}~@]+>\\)[ \t,]*"
375		definition start)
376	       start)
377	;; If an entry has a valid [ "foo bar" <foo@example.com> ]
378	;; form, use it literally .  This also allows commas in the
379	;; quoted string, e.g.  [ "foo bar, jr" <foo@example.com> ]
380	(setq this-entry (match-string 1 definition)
381	      start (and (/= (match-end 0) L) (match-end 0))))
382       (t
383	;; Otherwise, read the next address by looking for a comma.
384	(setq end (string-match "[ \t\n,]*,[ \t\n]*" definition start))
385	(setq this-entry (substring definition start end))
386	;; Advance the loop past this address.
387	(setq start (and end (/= (match-end 0) L) (match-end 0)))
388	;; If the full name contains a problem character, quote it.
389	(and (string-match "\\(.+?\\)[ \t]*\\(<.*>\\)" this-entry)
390	     (string-match "[^- !#$%&'*+/0-9=?A-Za-z^_`{|}~]"
391			   (match-string 1 this-entry))
392	     (setq this-entry (replace-regexp-in-string
393			       "\\(.+?\\)[ \t]*\\(<.*>\\)" "\"\\1\" \\2"
394			       this-entry)))))
395      (push this-entry result))
396
397    (setq definition (mapconcat (function identity)
398				(nreverse result) ", "))
399    (setq tem (assoc name mail-aliases))
400    (if tem
401	(rplacd tem definition)
402      (setq mail-aliases (cons (cons name definition) mail-aliases)
403	    mail-names t))))
404
405;;;###autoload
406(defun mail-completion-at-point-function ()
407  "Compute completion data for mail aliases.
408For use on `completion-at-point-functions'."
409  ;; Read the defaults first, if we have not done so.
410  (sendmail-sync-aliases)
411  (if (eq mail-aliases t)
412      (progn
413	(setq mail-aliases nil)
414	(if (file-exists-p mail-personal-alias-file)
415	    (build-mail-aliases))))
416  (let ((list mail-complete-alist)
417        (list-exp nil))
418    (if (and (< 0 (mail-header-end))
419	     (save-excursion
420	       (if (re-search-backward "^[^\t ]" nil t)
421		   (while list
422		     (if (looking-at (car (car list)))
423			 (setq list-exp (cdr (car list))
424			       list ())
425		       (setq list (cdr list)))))
426	       list-exp))
427	(let* ((end (point))
428	       (beg (save-excursion
429		      (skip-chars-backward "^ \t<,:")
430		      (point)))
431               (table (completion-table-dynamic
432                       (lambda (prefix)
433                         (let ((pattern prefix)) (eval list-exp))))))
434          (list beg end table)))))
435
436;;;###autoload
437(defun mail-complete (arg)
438  "Perform completion on header field or word preceding point.
439Completable headers are according to `mail-complete-alist'.  If none matches
440current header, calls `mail-complete-function' and passes prefix ARG if any."
441  (declare (obsolete mail-completion-at-point-function "24.1"))
442  (interactive "P")
443  ;; Read the defaults first, if we have not done so.
444  (sendmail-sync-aliases)
445  (if (eq mail-aliases t)
446      (progn
447	(setq mail-aliases nil)
448	(if (file-exists-p mail-personal-alias-file)
449	    (build-mail-aliases))))
450  (let ((data (mail-completion-at-point-function)))
451    (if data
452        (apply #'completion-in-region data)
453      (funcall mail-complete-function arg))))
454
455(defun mail-completion-expand (table)
456  "Build new completion table that expands aliases.
457Completes like TABLE except that if the completion is a valid alias,
458it expands it to its full `mail-complete-style' form."
459  (lambda (string pred action)
460    (cond
461     ((eq action nil)
462      (let* ((comp (try-completion string table pred))
463             (name (and (listp table) comp
464                        (assoc (if (stringp comp) comp string) table))))
465        (cond
466         ((null name) comp)
467         ((eq mail-complete-style 'parens)
468          (concat (car name) " (" (cdr name) ")"))
469         ((eq mail-complete-style 'angles)
470          (concat (cdr name) " <" (car name) ">"))
471         (t comp))))
472     (t
473      (complete-with-action action table string pred)))))
474
475(defun mail-get-names (prefix)
476  "Fetch local users and global mail addresses for completion.
477Consults `/etc/passwd' and a directory service if one is set up via
478`mail-directory-function'.
479PREFIX is the string we want to complete."
480  (if (eq mail-local-names t)
481      (with-current-buffer (generate-new-buffer " passwd")
482	(let ((files mail-passwd-files))
483	  (while files
484	    (insert-file-contents (car files) nil nil nil t)
485	    (setq files (cdr files))))
486	(if mail-passwd-command
487	    (call-process shell-file-name nil t nil
488			  shell-command-switch mail-passwd-command))
489	(goto-char (point-min))
490	(setq mail-local-names nil)
491	(while (not (eobp))
492	  ;;Recognize lines like
493	  ;;  nobody:*:65534:65534::/:
494	  ;;  +demo::::::/bin/csh
495	  ;;  +ethanb
496	  ;;while skipping
497	  ;;  +@SOFTWARE
498	  ;; The second \(...\) matches the user id.
499	  (if (looking-at "\\+?\\([^:@\n+]+\\):[^:\n]*:\\([^\n:]*\\):")
500	      (add-to-list 'mail-local-names
501			   (cons (match-string 1)
502				 (user-full-name
503				  (string-to-number (match-string 2))))))
504	  (beginning-of-line 2))
505	(kill-buffer (current-buffer))))
506  (if (or (eq mail-names t)
507	  (eq mail-directory-names t))
508      (let (directory)
509	(and mail-directory-function
510	     (eq mail-directory-names t)
511	     (setq directory
512		   (mail-directory (if mail-directory-requery prefix))))
513	(or mail-directory-requery
514	    (setq mail-directory-names directory))
515	(if (or directory
516		(eq mail-names t))
517	    (setq mail-names
518		  (sort (append (if (consp mail-aliases)
519				    (mapcar
520                                     (lambda (a) (list (car a)))
521				     mail-aliases))
522				(if (consp mail-local-names)
523				    mail-local-names)
524				(or directory
525				    (when (consp mail-directory-names)
526				      mail-directory-names)))
527			(lambda (a b)
528			  ;; Should cache downcased strings.
529			  (string< (downcase (car a))
530				   (downcase (car b)))))))))
531  (mail-completion-expand mail-names))
532
533
534(defun mail-directory (prefix)
535  "Use mail-directory facility to get user names matching PREFIX.
536If PREFIX is nil, get all the defined user names.
537This function calls `mail-directory-function' to query the directory,
538then uses `mail-directory-parser' to parse the output it returns."
539  (message "Querying directory...")
540  (with-current-buffer (generate-new-buffer " *mail-directory*")
541    (funcall mail-directory-function prefix)
542    (goto-char (point-min))
543    (let (directory)
544      (if (stringp mail-directory-parser)
545	  (while (re-search-forward mail-directory-parser nil t)
546	    (push (match-string 1) directory))
547	(if mail-directory-parser
548	    (setq directory (funcall mail-directory-parser))
549	  (while (not (eobp))
550	    (push (buffer-substring (point)
551                                    (progn
552                                      (forward-line)
553                                      (if (bolp)
554                                          (1- (point))
555                                        (point))))
556                  directory))))
557      (kill-buffer (current-buffer))
558      (message "Querying directory...done")
559      directory)))
560
561(defvar mailalias-done)
562
563(defun mail-directory-process (prefix)
564  "Run a shell command to output names in directory.
565See `mail-directory-process'."
566  (when (consp mail-directory-process)
567    (let ((pattern prefix))             ;Dynbind!
568      (apply 'call-process (eval (car mail-directory-process)) nil t nil
569             (mapcar 'eval (cdr mail-directory-process))))))
570
571;; This should handle a dialog.  Currently expects port to spit out names.
572(defun mail-directory-stream (prefix)
573  "Open a stream to retrieve names in directory.
574See `mail-directory-stream'."
575  (let ((mailalias-done nil)
576        (pattern prefix))               ;Dynbind!
577    (set-process-sentinel
578     (apply 'open-network-stream "mailalias" (current-buffer)
579	    mail-directory-stream)
580     (lambda (_x _y)
581       (setq mailalias-done t)))
582    (while (not mailalias-done)
583      (sit-for .1))))
584
585(defun mail-sentto-newsgroups ()
586  "Return all entries from Newsgroups: header as completion alist."
587  (save-excursion
588    (if (mail-position-on-field "newsgroups" t)
589	(let ((point (point))
590	      list)
591	  (while (< (skip-chars-backward "^:, \t\n") 0)
592	    (setq list `((,(buffer-substring (point) point))
593			 ,@list))
594	    (skip-chars-backward ", \t\n")
595	    (setq point (point)))
596	  list))))
597
598(provide 'mailalias)
599
600;;; mailalias.el ends here
601