*** empty log message ***
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: mail, news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33
34 (require 'mailheader)
35 (require 'rmail)
36 (require 'nnheader)
37 (require 'timezone)
38 (require 'easymenu)
39 (require 'custom)
40 (if (string-match "XEmacs\\|Lucid" emacs-version)
41     (require 'mail-abbrevs)
42   (require 'mailabbrev))
43
44 (defgroup message '((user-mail-address custom-variable)
45                     (user-full-name custom-variable))
46   "Mail and news message composing."
47   :link '(custom-manual "(message)Top")
48   :group 'mail
49   :group 'news)
50
51 (put 'user-mail-address 'custom-type 'string)
52 (put 'user-full-name 'custom-type 'string)
53
54 (defgroup message-various nil
55   "Various Message Variables"
56   :link '(custom-manual "(message)Various Message Variables")
57   :group 'message)
58
59 (defgroup message-buffers nil
60   "Message Buffers"
61   :link '(custom-manual "(message)Message Buffers")
62   :group 'message)
63
64 (defgroup message-sending nil
65   "Message Sending"
66   :link '(custom-manual "(message)Sending Variables")
67   :group 'message)
68
69 (defgroup message-interface nil
70   "Message Interface"
71   :link '(custom-manual "(message)Interface")
72   :group 'message)
73
74 (defgroup message-forwarding nil
75   "Message Forwarding"
76   :link '(custom-manual "(message)Forwarding")
77   :group 'message-interface)
78
79 (defgroup message-insertion nil
80   "Message Insertion"
81   :link '(custom-manual "(message)Insertion")
82   :group 'message)
83
84 (defgroup message-headers nil
85   "Message Headers"
86   :link '(custom-manual "(message)Message Headers")
87   :group 'message)
88
89 (defgroup message-news nil
90   "Composing News Messages"
91   :group 'message)
92
93 (defgroup message-mail nil
94   "Composing Mail Messages"
95   :group 'message)
96
97 (defgroup message-faces nil
98   "Faces used for message composing."
99   :group 'message
100   :group 'faces)
101
102 (defcustom message-directory "~/Mail/"
103   "*Directory from which all other mail file variables are derived."
104   :group 'message-various
105   :type 'directory)
106
107 (defcustom message-max-buffers 10
108   "*How many buffers to keep before starting to kill them off."
109   :group 'message-buffers
110   :type 'integer)
111
112 (defcustom message-send-rename-function nil
113   "Function called to rename the buffer after sending it."
114   :group 'message-buffers
115   :type 'function)
116
117 (defcustom message-fcc-handler-function 'message-output
118   "*A function called to save outgoing articles.
119 This function will be called with the name of the file to store the
120 article in.  The default function is `message-output' which saves in Unix
121 mailbox format."
122   :type '(radio (function-item message-output)
123                 (function :tag "Other"))
124   :group 'message-sending)
125
126 (defcustom message-courtesy-message
127   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
128   "*This is inserted at the start of a mailed copy of a posted message.
129 If the string contains the format spec \"%s\", the Newsgroups
130 the article has been posted to will be inserted there.
131 If this variable is nil, no such courtesy message will be added."
132   :group 'message-sending
133   :type 'string)
134
135 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
136   "*Regexp that matches headers to be removed in resent bounced mail."
137   :group 'message-interface
138   :type 'regexp)
139
140 ;;;###autoload
141 (defcustom message-from-style 'default
142   "*Specifies how \"From\" headers look.
143
144 If `nil', they contain just the return address like:
145         king@grassland.com
146 If `parens', they look like:
147         king@grassland.com (Elvis Parsley)
148 If `angles', they look like:
149         Elvis Parsley <king@grassland.com>
150
151 Otherwise, most addresses look like `angles', but they look like
152 `parens' if `angles' would need quoting and `parens' would not."
153   :type '(choice (const :tag "simple" nil)
154                  (const parens)
155                  (const angles)
156                  (const default))
157   :group 'message-headers)
158
159 (defcustom message-syntax-checks nil
160   ;; Guess this one shouldn't be easy to customize...
161   "Controls what syntax checks should not be performed on outgoing posts.
162 To disable checking of long signatures, for instance, add
163  `(signature . disabled)' to this list.
164
165 Don't touch this variable unless you really know what you're doing.
166
167 Checks include subject-cmsg multiple-headers sendsys message-id from
168 long-lines control-chars size new-text redirected-followup signature
169 approved sender empty empty-headers message-id from subject
170 shorten-followup-to existing-newsgroups."
171   :group 'message-news)
172
173 (defcustom message-required-news-headers
174   '(From Newsgroups Subject Date Message-ID
175          (optional . Organization) Lines
176          (optional . X-Newsreader))
177   "Headers to be generated or prompted for when posting an article.
178 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
179 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
180 X-Newsreader are optional.  If don't you want message to insert some
181 header, remove it from this list."
182   :group 'message-news
183   :group 'message-headers
184   :type '(repeat sexp))
185
186 (defcustom message-required-mail-headers
187   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
188          (optional . X-Mailer))
189   "Headers to be generated or prompted for when mailing a message.
190 RFC822 required that From, Date, To, Subject and Message-ID be
191 included.  Organization, Lines and X-Mailer are optional."
192   :group 'message-mail
193   :group 'message-headers
194   :type '(repeat sexp))
195
196 (defcustom message-deletable-headers '(Message-ID Date Lines)
197   "Headers to be deleted if they already exist and were generated by message previously."
198   :group 'message-headers
199   :type 'sexp)
200
201 (defcustom message-ignored-news-headers
202   "^NNTP-Posting-Host:\\|^Xref:\\|^Bcc:\\|^Gcc:\\|^Fcc:\\|^Resent-Fcc:"
203   "*Regexp of headers to be removed unconditionally before posting."
204   :group 'message-news
205   :group 'message-headers
206   :type 'regexp)
207
208 (defcustom message-ignored-mail-headers "^Gcc:\\|^Fcc:\\|^Resent-Fcc:"
209   "*Regexp of headers to be removed unconditionally before mailing."
210   :group 'message-mail
211   :group 'message-headers
212   :type 'regexp)
213
214 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|Return-Path:\\|^Supersedes:"
215   "*Header lines matching this regexp will be deleted before posting.
216 It's best to delete old Path and Date headers before posting to avoid
217 any confusion."
218   :group 'message-interface
219   :type 'regexp)
220
221 ;;;###autoload
222 (defcustom message-signature-separator "^-- *$"
223   "Regexp matching the signature separator."
224   :type 'regexp
225   :group 'message-various)
226
227 (defcustom message-elide-elipsis "\n[...]\n\n"
228   "*The string which is inserted for elided text.")
229
230 (defcustom message-interactive nil
231   "Non-nil means when sending a message wait for and display errors.
232 nil means let mailer mail back a message to report errors."
233   :group 'message-sending
234   :group 'message-mail
235   :type 'boolean)
236
237 (defcustom message-generate-new-buffers t
238   "*Non-nil means that a new message buffer will be created whenever `mail-setup' is called.
239 If this is a function, call that function with three parameters:  The type,
240 the to address and the group name.  (Any of these may be nil.)  The function
241 should return the new buffer name."
242   :group 'message-buffers
243   :type '(choice (const :tag "off" nil)
244                  (const :tag "on" t)
245                  (function fun)))
246
247 (defcustom message-kill-buffer-on-exit nil
248   "*Non-nil means that the message buffer will be killed after sending a message."
249   :group 'message-buffers
250   :type 'boolean)
251
252 (defvar gnus-local-organization)
253 (defcustom message-user-organization
254   (or (and (boundp 'gnus-local-organization)
255            (stringp gnus-local-organization)
256            gnus-local-organization)
257       (getenv "ORGANIZATION")
258       t)
259   "*String to be used as an Organization header.
260 If t, use `message-user-organization-file'."
261   :group 'message-headers
262   :type '(choice string
263                  (const :tag "consult file" t)))
264
265 ;;;###autoload
266 (defcustom message-user-organization-file "/usr/lib/news/organization"
267   "*Local news organization file."
268   :type 'file
269   :group 'message-headers)
270
271 (defcustom message-autosave-directory "~/"
272   ; (concat (file-name-as-directory message-directory) "drafts/")
273   "*Directory where message autosaves buffers.
274 If nil, message won't autosave."
275   :group 'message-buffers
276   :type 'directory)
277
278 (defcustom message-forward-start-separator
279   "------- Start of forwarded message -------\n"
280   "*Delimiter inserted before forwarded messages."
281   :group 'message-forwarding
282   :type 'string)
283
284 (defcustom message-forward-end-separator
285   "------- End of forwarded message -------\n"
286   "*Delimiter inserted after forwarded messages."
287   :group 'message-forwarding
288   :type 'string)
289
290 (defcustom message-signature-before-forwarded-message t
291   "*If non-nil, put the signature before any included forwarded message."
292   :group 'message-forwarding
293   :type 'boolean)
294
295 (defcustom message-included-forward-headers
296   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^Followup-To:\\|^Reply-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Mail-Copies-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:"
297   "*Regexp matching headers to be included in forwarded messages."
298   :group 'message-forwarding
299   :type 'regexp)
300
301 (defcustom message-ignored-resent-headers "^Return-receipt"
302   "*All headers that match this regexp will be deleted when resending a message."
303   :group 'message-interface
304   :type 'regexp)
305
306 (defcustom message-ignored-cited-headers "."
307   "*Delete these headers from the messages you yank."
308   :group 'message-insertion
309   :type 'regexp)
310
311 (defcustom message-cancel-message "I am canceling my own article."
312   "Message to be inserted in the cancel message."
313   :group 'message-interface
314   :type 'string)
315
316 ;; Useful to set in site-init.el
317 ;;;###autoload
318 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
319   "Function to call to send the current buffer as mail.
320 The headers should be delimited by a line whose contents match the
321 variable `mail-header-separator'.
322
323 Legal values include `message-send-mail-with-sendmail' (the default),
324 `message-send-mail-with-mh' and `message-send-mail-with-qmail'."
325   :type '(radio (function-item message-send-mail-with-sendmail)
326                 (function-item message-send-mail-with-mh)
327                 (function-item message-send-mail-with-qmail)
328                 (function :tag "Other"))
329   :group 'message-sending
330   :group 'message-mail)
331
332 (defcustom message-send-news-function 'message-send-news
333   "Function to call to send the current buffer as news.
334 The headers should be delimited by a line whose contents match the
335 variable `mail-header-separator'."
336   :group 'message-sending
337   :group 'message-news
338   :type 'function)
339
340 (defcustom message-reply-to-function nil
341   "Function that should return a list of headers.
342 This function should pick out addresses from the To, Cc, and From headers
343 and respond with new To and Cc headers."
344   :group 'message-interface
345   :type 'function)
346
347 (defcustom message-wide-reply-to-function nil
348   "Function that should return a list of headers.
349 This function should pick out addresses from the To, Cc, and From headers
350 and respond with new To and Cc headers."
351   :group 'message-interface
352   :type 'function)
353
354 (defcustom message-followup-to-function nil
355   "Function that should return a list of headers.
356 This function should pick out addresses from the To, Cc, and From headers
357 and respond with new To and Cc headers."
358   :group 'message-interface
359   :type 'function)
360
361 (defcustom message-use-followup-to 'ask
362   "*Specifies what to do with Followup-To header.
363 If nil, always ignore the header.  If it is t, use its value, but
364 query before using the \"poster\" value.  If it is the symbol `ask',
365 always query the user whether to use the value.  If it is the symbol
366 `use', always use the value."
367   :group 'message-interface
368   :type '(choice (const :tag "ignore" nil)
369                  (const use)
370                  (const ask)))
371
372 ;; stuff relating to broken sendmail in MMDF
373 (defcustom message-sendmail-f-is-evil nil
374   "*Non-nil means that \"-f username\" should not be added to the sendmail
375 command line, because it is even more evil than leaving it out."
376   :group 'message-sending
377   :type 'boolean)
378
379 ;; qmail-related stuff
380 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
381   "Location of the qmail-inject program."
382   :group 'message-sending
383   :type 'file)
384
385 (defcustom message-qmail-inject-args nil
386   "Arguments passed to qmail-inject programs.
387 This should be a list of strings, one string for each argument.
388
389 For e.g., if you wish to set the envelope sender address so that bounces
390 go to the right place or to deal with listserv's usage of that address, you
391 might set this variable to '(\"-f\" \"you@some.where\")."
392   :group 'message-sending
393   :type '(repeat string))
394
395 (defvar gnus-post-method)
396 (defvar gnus-select-method)
397 (defcustom message-post-method
398   (cond ((and (boundp 'gnus-post-method)
399               gnus-post-method)
400          gnus-post-method)
401         ((boundp 'gnus-select-method)
402          gnus-select-method)
403         (t '(nnspool "")))
404   "Method used to post news."
405   :group 'message-news
406   :group 'message-sending
407   ;; This should be the `gnus-select-method' widget, but that might
408   ;; create a dependence to `gnus.el'.
409   :type 'sexp)
410
411 (defcustom message-generate-headers-first nil
412   "*If non-nil, generate all possible headers before composing."
413   :group 'message-headers
414   :type 'boolean)
415
416 (defcustom message-setup-hook nil
417   "Normal hook, run each time a new outgoing message is initialized.
418 The function `message-setup' runs this hook."
419   :group 'message-various
420   :type 'hook)
421
422 (defcustom message-signature-setup-hook nil
423   "Normal hook, run each time a new outgoing message is initialized.
424 It is run after the headers have been inserted and before
425 the signature is inserted."
426   :group 'message-various
427   :type 'hook)
428
429 (defcustom message-mode-hook nil
430   "Hook run in message mode buffers."
431   :group 'message-various
432   :type 'hook)
433
434 (defcustom message-header-hook nil
435   "Hook run in a message mode buffer narrowed to the headers."
436   :group 'message-various
437   :type 'hook)
438
439 (defcustom message-header-setup-hook nil
440   "Hook called narrowed to the headers when setting up a message
441 buffer."
442   :group 'message-various
443   :type 'hook)
444
445 ;;;###autoload
446 (defcustom message-citation-line-function 'message-insert-citation-line
447   "*Function called to insert the \"Whomever writes:\" line."
448   :type 'function
449   :group 'message-insertion)
450
451 ;;;###autoload
452 (defcustom message-yank-prefix "> "
453   "*Prefix inserted on the lines of yanked messages.
454 nil means use indentation."
455   :type 'string
456   :group 'message-insertion)
457
458 (defcustom message-indentation-spaces 3
459   "*Number of spaces to insert at the beginning of each cited line.
460 Used by `message-yank-original' via `message-yank-cite'."
461   :group 'message-insertion
462   :type 'integer)
463
464 ;;;###autoload
465 (defcustom message-cite-function
466   (if (and (boundp 'mail-citation-hook)
467            mail-citation-hook)
468       mail-citation-hook
469     'message-cite-original)
470   "*Function for citing an original message."
471   :type '(radio (function-item message-cite-original)
472                 (function-item sc-cite-original)
473                 (function :tag "Other"))
474   :group 'message-insertion)
475
476 ;;;###autoload
477 (defcustom message-indent-citation-function 'message-indent-citation
478   "*Function for modifying a citation just inserted in the mail buffer.
479 This can also be a list of functions.  Each function can find the
480 citation between (point) and (mark t).  And each function should leave
481 point and mark around the citation text as modified."
482   :type 'function
483   :group 'message-insertion)
484
485 (defvar message-abbrevs-loaded nil)
486
487 ;;;###autoload
488 (defcustom message-signature t
489   "*String to be inserted at the end of the message buffer.
490 If t, the `message-signature-file' file will be inserted instead.
491 If a function, the result from the function will be used instead.
492 If a form, the result from the form will be used instead."
493   :type 'sexp
494   :group 'message-insertion)
495
496 ;;;###autoload
497 (defcustom message-signature-file "~/.signature"
498   "*File containing the text inserted at end of message buffer."
499   :type 'file
500   :group 'message-insertion)
501
502 (defcustom message-distribution-function nil
503   "*Function called to return a Distribution header."
504   :group 'message-news
505   :group 'message-headers
506   :type 'function)
507
508 (defcustom message-expires 14
509   "Number of days before your article expires."
510   :group 'message-news
511   :group 'message-headers
512   :link '(custom-manual "(message)News Headers")
513   :type 'integer)
514
515 (defcustom message-user-path nil
516   "If nil, use the NNTP server name in the Path header.
517 If stringp, use this; if non-nil, use no host name (user name only)."
518   :group 'message-news
519   :group 'message-headers
520   :link '(custom-manual "(message)News Headers")
521   :type '(choice (const :tag "nntp" nil)
522                  (string :tag "name")
523                  (sexp :tag "none" :format "%t" t)))
524
525 (defvar message-reply-buffer nil)
526 (defvar message-reply-headers nil)
527 (defvar message-newsreader nil)
528 (defvar message-mailer nil)
529 (defvar message-sent-message-via nil)
530 (defvar message-checksum nil)
531 (defvar message-send-actions nil
532   "A list of actions to be performed upon successful sending of a message.")
533 (defvar message-exit-actions nil
534   "A list of actions to be performed upon exiting after sending a message.")
535 (defvar message-kill-actions nil
536   "A list of actions to be performed before killing a message buffer.")
537 (defvar message-postpone-actions nil
538   "A list of actions to be performed after postponing a message.")
539
540 (defcustom message-default-headers ""
541   "*A string containing header lines to be inserted in outgoing messages.
542 It is inserted before you edit the message, so you can edit or delete
543 these lines."
544   :group 'message-headers
545   :type 'string)
546
547 (defcustom message-default-mail-headers ""
548   "*A string of header lines to be inserted in outgoing mails."
549   :group 'message-headers
550   :group 'message-mail
551   :type 'string)
552
553 (defcustom message-default-news-headers ""
554   "*A string of header lines to be inserted in outgoing news
555 articles."
556   :group 'message-headers
557   :group 'message-news
558   :type 'string)
559
560 ;; Note: could use /usr/ucb/mail instead of sendmail;
561 ;; options -t, and -v if not interactive.
562 (defcustom message-mailer-swallows-blank-line
563   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
564                          system-configuration)
565            (file-readable-p "/etc/sendmail.cf")
566            (let ((buffer (get-buffer-create " *temp*")))
567              (unwind-protect
568                  (save-excursion
569                    (set-buffer buffer)
570                    (insert-file-contents "/etc/sendmail.cf")
571                    (goto-char (point-min))
572                    (let ((case-fold-search nil))
573                      (re-search-forward "^OR\\>" nil t)))
574                (kill-buffer buffer))))
575       ;; According to RFC822, "The field-name must be composed of printable
576       ;; ASCII characters (i. e., characters that have decimal values between
577       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
578       ;; space, or colon.
579       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
580   "Set this non-nil if the system's mailer runs the header and body together.
581 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
582 The value should be an expression to test whether the problem will
583 actually occur."
584   :group 'message-sending
585   :type 'sexp)
586
587 ;; Ignore errors in case this is used in Emacs 19.
588 ;; Don't use ignore-errors because this is copied into loaddefs.el.
589 ;;;###autoload
590 (condition-case nil
591     (define-mail-user-agent 'message-user-agent
592       'message-mail 'message-send-and-exit
593       'message-kill-buffer 'message-send-hook)
594   (error nil))
595
596 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
597   "If non-nil, delete the deletable headers before feeding to mh.")
598
599 (defvar message-send-method-alist
600   '((news message-news-p message-send-via-news)
601     (mail message-mail-p message-send-via-mail))
602   "Alist of ways to send outgoing messages.
603 Each element has the form
604
605   \(TYPE PREDICATE FUNCTION)
606
607 where TYPE is a symbol that names the method; PREDICATE is a function
608 called without any parameters to determine whether the message is
609 a message of type TYPE; and FUNCTION is a function to be called if
610 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
611 the prefix.")
612
613 (defvar message-mail-alias-type 'abbrev
614   "*What alias expansion type to use in Message buffers.
615 The default is `abbrev', which uses mailabbrev.  nil switches
616 mail aliases off.")
617
618 ;;; Internal variables.
619 ;;; Well, not really internal.
620
621 (defvar message-mode-syntax-table
622   (let ((table (copy-syntax-table text-mode-syntax-table)))
623     (modify-syntax-entry ?% ". " table)
624     table)
625   "Syntax table used while in Message mode.")
626
627 (defvar message-mode-abbrev-table text-mode-abbrev-table
628   "Abbrev table used in Message mode buffers.
629 Defaults to `text-mode-abbrev-table'.")
630 (defgroup message-headers nil
631   "Message headers."
632   :link '(custom-manual "(message)Variables")
633   :group 'message)
634
635 (defface message-header-to-face
636   '((((class color)
637       (background dark))
638      (:foreground "green2" :bold t))
639     (((class color)
640       (background light))
641      (:foreground "MidnightBlue" :bold t))
642     (t
643      (:bold t :italic t)))
644   "Face used for displaying From headers."
645   :group 'message-faces)
646
647 (defface message-header-cc-face
648   '((((class color)
649       (background dark))
650      (:foreground "green4" :bold t))
651     (((class color)
652       (background light))
653      (:foreground "MidnightBlue"))
654     (t
655      (:bold t)))
656   "Face used for displaying Cc headers."
657   :group 'message-faces)
658
659 (defface message-header-subject-face
660   '((((class color)
661       (background dark))
662      (:foreground "green3"))
663     (((class color)
664       (background light))
665      (:foreground "navy blue" :bold t))
666     (t
667      (:bold t)))
668   "Face used for displaying subject headers."
669   :group 'message-faces)
670
671 (defface message-header-newsgroups-face
672   '((((class color)
673       (background dark))
674      (:foreground "yellow" :bold t :italic t))
675     (((class color)
676       (background light))
677      (:foreground "blue4" :bold t :italic t))
678     (t
679      (:bold t :italic t)))
680   "Face used for displaying newsgroups headers."
681   :group 'message-faces)
682
683 (defface message-header-other-face
684   '((((class color)
685       (background dark))
686      (:foreground "red4"))
687     (((class color)
688       (background light))
689      (:foreground "steel blue"))
690     (t
691      (:bold t :italic t)))
692   "Face used for displaying newsgroups headers."
693   :group 'message-faces)
694
695 (defface message-header-name-face
696   '((((class color)
697       (background dark))
698      (:foreground "DarkGreen"))
699     (((class color)
700       (background light))
701      (:foreground "cornflower blue"))
702     (t
703      (:bold t)))
704   "Face used for displaying header names."
705   :group 'message-faces)
706
707 (defface message-header-xheader-face
708   '((((class color)
709       (background dark))
710      (:foreground "blue"))
711     (((class color)
712       (background light))
713      (:foreground "blue"))
714     (t
715      (:bold t)))
716   "Face used for displaying X-Header headers."
717   :group 'message-faces)
718
719 (defface message-separator-face
720   '((((class color)
721       (background dark))
722      (:foreground "blue4"))
723     (((class color)
724       (background light))
725      (:foreground "brown"))
726     (t
727      (:bold t)))
728   "Face used for displaying the separator."
729   :group 'message-faces)
730
731 (defface message-cited-text-face
732   '((((class color)
733       (background dark))
734      (:foreground "red"))
735     (((class color)
736       (background light))
737      (:foreground "red"))
738     (t
739      (:bold t)))
740   "Face used for displaying cited text names."
741   :group 'message-faces)
742
743 (defvar message-font-lock-keywords
744   (let* ((cite-prefix "A-Za-z")
745          (cite-suffix (concat cite-prefix "0-9_.@-"))
746          (content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)"))
747     `((,(concat "^\\([Tt]o:\\)" content)
748        (1 'message-header-name-face)
749        (2 'message-header-to-face nil t))
750       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
751        (1 'message-header-name-face)
752        (2 'message-header-cc-face nil t))
753       (,(concat "^\\([Ss]ubject:\\)" content)
754        (1 'message-header-name-face)
755        (2 'message-header-subject-face nil t))
756       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
757        (1 'message-header-name-face)
758        (2 'message-header-newsgroups-face nil t))
759       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
760        (1 'message-header-name-face)
761        (2 'message-header-other-face nil t))
762       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
763        (1 'message-header-name-face)
764        (2 'message-header-name-face))
765       (,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
766        1 'message-separator-face)
767       (,(concat "^[ \t]*"
768                 "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
769                 "[>|}].*")
770        (0 'message-cited-text-face))))
771   "Additional expressions to highlight in Message mode.")
772
773 (defvar message-face-alist
774   '((bold . bold-region)
775     (underline . underline-region)
776     (default . (lambda (b e)
777                  (unbold-region b e)
778                  (ununderline-region b e))))
779   "Alist of mail and news faces for facemenu.
780 The cdr of ech entry is a function for applying the face to a region.")
781
782 (defcustom message-send-hook nil
783   "Hook run before sending messages."
784   :group 'message-various
785   :options '(ispell-message)
786   :type 'hook)
787
788 (defcustom message-send-mail-hook nil
789   "Hook run before sending mail messages."
790   :group 'message-various
791   :type 'hook)
792
793 (defcustom message-send-news-hook nil
794   "Hook run before sending news messages."
795   :group 'message-various
796   :type 'hook)
797
798 (defcustom message-sent-hook nil
799   "Hook run after sending messages."
800   :group 'message-various
801   :type 'hook)
802
803 ;;; Internal variables.
804
805 (defvar message-buffer-list nil)
806 (defvar message-this-is-news nil)
807 (defvar message-this-is-mail nil)
808
809 ;; Byte-compiler warning
810 (defvar gnus-active-hashtb)
811 (defvar gnus-read-active-file)
812
813 ;;; Regexp matching the delimiter of messages in UNIX mail format
814 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
815 ;;; of rmail.el's rmail-unix-mail-delimiter.
816 (defvar message-unix-mail-delimiter
817   (let ((time-zone-regexp
818          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
819                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
820                  "\\|"
821                  "\\) *")))
822     (concat
823      "From "
824
825      ;; Many things can happen to an RFC 822 mailbox before it is put into
826      ;; a `From' line.  The leading phrase can be stripped, e.g.
827      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
828      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
829      ;; can be removed, e.g.
830      ;;         From: joe@y.z (Joe      K
831      ;;                 User)
832      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
833      ;;         From: Joe User
834      ;;                 <joe@y.z>
835      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
836      ;; The mailbox can be removed or be replaced by white space, e.g.
837      ;;         From: "Joe User"{space}{tab}
838      ;;                 <joe@y.z>
839      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
840      ;; where {space} and {tab} represent the Ascii space and tab characters.
841      ;; We want to match the results of any of these manglings.
842      ;; The following regexp rejects names whose first characters are
843      ;; obviously bogus, but after that anything goes.
844      "\\([^\0-\b\n-\r\^?].*\\)? "
845
846      ;; The time the message was sent.
847      "\\([^\0-\r \^?]+\\) +"                            ; day of the week
848      "\\([^\0-\r \^?]+\\) +"                            ; month
849      "\\([0-3]?[0-9]\\) +"                              ; day of month
850      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"  ; time of day
851
852      ;; Perhaps a time zone, specified by an abbreviation, or by a
853      ;; numeric offset.
854      time-zone-regexp
855
856      ;; The year.
857      " \\([0-9][0-9]+\\) *"
858
859      ;; On some systems the time zone can appear after the year, too.
860      time-zone-regexp
861
862      ;; Old uucp cruft.
863      "\\(remote from .*\\)?"
864
865      "\n"))
866   "Regexp matching the delimiter of messages in UNIX mail format.")
867
868 (defvar message-unsent-separator
869   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
870           "^ *---+ +Returned message +---+ *$\\|"
871           "^Start of returned message$\\|"
872           "^ *---+ +Original message +---+ *$\\|"
873           "^ *--+ +begin message +--+ *$\\|"
874           "^ *---+ +Original message follows +---+ *$\\|"
875           "^|? *---+ +Message text follows: +---+ *|?$")
876   "A regexp that matches the separator before the text of a failed message.")
877
878 (defvar message-header-format-alist
879   `((Newsgroups)
880     (To . message-fill-address)
881     (Cc . message-fill-address)
882     (Subject)
883     (In-Reply-To)
884     (Fcc)
885     (Bcc)
886     (Date)
887     (Organization)
888     (Distribution)
889     (Lines)
890     (Expires)
891     (Message-ID)
892     (References)
893     (X-Mailer)
894     (X-Newsreader))
895   "Alist used for formatting headers.")
896
897 (eval-and-compile
898   (autoload 'message-setup-toolbar "messagexmas")
899   (autoload 'mh-send-letter "mh-comp")
900   (autoload 'gnus-point-at-eol "gnus-util")
901   (autoload 'gnus-point-at-bol "gnus-util")
902   (autoload 'gnus-output-to-mail "gnus-util")
903   (autoload 'gnus-output-to-rmail "gnus-util")
904   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev"))
905
906 \f
907
908 ;;;
909 ;;; Utility functions.
910 ;;;
911
912 (defmacro message-y-or-n-p (question show &rest text)
913   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
914   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
915
916 ;; Delete the current line (and the next N lines.);
917 (defmacro message-delete-line (&optional n)
918   `(delete-region (progn (beginning-of-line) (point))
919                   (progn (forward-line ,(or n 1)) (point))))
920
921 (defun message-tokenize-header (header &optional separator)
922   "Split HEADER into a list of header elements.
923 \",\" is used as the separator."
924   (if (not header)
925       nil
926     (let ((regexp (format "[%s]+" (or separator ",")))
927           (beg 1)
928           (first t)
929           quoted elems paren)
930       (save-excursion
931         (message-set-work-buffer)
932         (insert header)
933         (goto-char (point-min))
934         (while (not (eobp))
935           (if first
936               (setq first nil)
937             (forward-char 1))
938           (cond ((and (> (point) beg)
939                       (or (eobp)
940                           (and (looking-at regexp)
941                                (not quoted)
942                                (not paren))))
943                  (push (buffer-substring beg (point)) elems)
944                  (setq beg (match-end 0)))
945                 ((= (following-char) ?\")
946                  (setq quoted (not quoted)))
947                 ((and (= (following-char) ?\()
948                       (not quoted))
949                  (setq paren t))
950                 ((and (= (following-char) ?\))
951                       (not quoted))
952                  (setq paren nil))))
953         (nreverse elems)))))
954
955 (defun message-mail-file-mbox-p (file)
956   "Say whether FILE looks like a Unix mbox file."
957   (when (and (file-exists-p file)
958              (file-readable-p file)
959              (file-regular-p file))
960     (nnheader-temp-write nil
961       (nnheader-insert-file-contents file)
962       (goto-char (point-min))
963       (looking-at message-unix-mail-delimiter))))
964
965 (defun message-fetch-field (header &optional not-all)
966   "The same as `mail-fetch-field', only remove all newlines."
967   (let ((value (mail-fetch-field header nil (not not-all))))
968     (when value
969       (nnheader-replace-chars-in-string value ?\n ? ))))
970
971 (defun message-add-header (&rest headers)
972   "Add the HEADERS to the message header, skipping those already present."
973   (while headers
974     (let (hclean)
975       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
976         (error "Invalid header `%s'" (car headers)))
977       (setq hclean (match-string 1 (car headers)))
978     (save-restriction
979       (message-narrow-to-headers)
980       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
981         (insert (car headers) ?\n))))
982     (setq headers (cdr headers))))
983
984 (defun message-fetch-reply-field (header)
985   "Fetch FIELD from the message we're replying to."
986   (when (and message-reply-buffer
987              (buffer-name message-reply-buffer))
988     (save-excursion
989       (set-buffer message-reply-buffer)
990       (message-fetch-field header))))
991
992 (defun message-set-work-buffer ()
993   (if (get-buffer " *message work*")
994       (progn
995         (set-buffer " *message work*")
996         (erase-buffer))
997     (set-buffer (get-buffer-create " *message work*"))
998     (kill-all-local-variables)
999     (buffer-disable-undo (current-buffer))))
1000
1001 (defun message-functionp (form)
1002   "Return non-nil if FORM is funcallable."
1003   (or (and (symbolp form) (fboundp form))
1004       (and (listp form) (eq (car form) 'lambda))
1005       (compiled-function-p form)))
1006
1007 (defun message-strip-subject-re (subject)
1008   "Remove \"Re:\" from subject lines."
1009   (if (string-match "^[Rr][Ee]: *" subject)
1010       (substring subject (match-end 0))
1011     subject))
1012
1013 (defun message-remove-header (header &optional is-regexp first reverse)
1014   "Remove HEADER in the narrowed buffer.
1015 If REGEXP, HEADER is a regular expression.
1016 If FIRST, only remove the first instance of the header.
1017 Return the number of headers removed."
1018   (goto-char (point-min))
1019   (let ((regexp (if is-regexp header (concat "^" header ":")))
1020         (number 0)
1021         (case-fold-search t)
1022         last)
1023     (while (and (not (eobp))
1024                 (not last))
1025       (if (if reverse
1026               (not (looking-at regexp))
1027             (looking-at regexp))
1028           (progn
1029             (incf number)
1030             (when first
1031               (setq last t))
1032             (delete-region
1033              (point)
1034              ;; There might be a continuation header, so we have to search
1035              ;; until we find a new non-continuation line.
1036              (progn
1037                (forward-line 1)
1038                (if (re-search-forward "^[^ \t]" nil t)
1039                    (goto-char (match-beginning 0))
1040                  (point-max)))))
1041         (forward-line 1)
1042         (if (re-search-forward "^[^ \t]" nil t)
1043             (goto-char (match-beginning 0))
1044           (point-max))))
1045     number))
1046
1047 (defun message-narrow-to-headers ()
1048   "Narrow the buffer to the head of the message."
1049   (widen)
1050   (narrow-to-region
1051    (goto-char (point-min))
1052    (if (re-search-forward
1053         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1054        (match-beginning 0)
1055      (point-max)))
1056   (goto-char (point-min)))
1057
1058 (defun message-narrow-to-head ()
1059   "Narrow the buffer to the head of the message."
1060   (widen)
1061   (narrow-to-region
1062    (goto-char (point-min))
1063    (if (search-forward "\n\n" nil 1)
1064        (1- (point))
1065      (point-max)))
1066   (goto-char (point-min)))
1067
1068 (defun message-news-p ()
1069   "Say whether the current buffer contains a news message."
1070   (or message-this-is-news
1071       (save-excursion
1072         (save-restriction
1073           (message-narrow-to-headers)
1074           (message-fetch-field "newsgroups")))))
1075
1076 (defun message-mail-p ()
1077   "Say whether the current buffer contains a mail message."
1078   (or message-this-is-mail
1079       (save-excursion
1080         (save-restriction
1081           (message-narrow-to-headers)
1082           (or (message-fetch-field "to")
1083               (message-fetch-field "cc")
1084               (message-fetch-field "bcc"))))))
1085
1086 (defun message-next-header ()
1087   "Go to the beginning of the next header."
1088   (beginning-of-line)
1089   (or (eobp) (forward-char 1))
1090   (not (if (re-search-forward "^[^ \t]" nil t)
1091            (beginning-of-line)
1092          (goto-char (point-max)))))
1093
1094 (defun message-sort-headers-1 ()
1095   "Sort the buffer as headers using `message-rank' text props."
1096   (goto-char (point-min))
1097   (sort-subr
1098    nil 'message-next-header
1099    (lambda ()
1100      (message-next-header)
1101      (unless (bobp)
1102        (forward-char -1)))
1103    (lambda ()
1104      (or (get-text-property (point) 'message-rank)
1105          10000))))
1106
1107 (defun message-sort-headers ()
1108   "Sort the headers of the current message according to `message-header-format-alist'."
1109   (interactive)
1110   (save-excursion
1111     (save-restriction
1112       (let ((max (1+ (length message-header-format-alist)))
1113             rank)
1114         (message-narrow-to-headers)
1115         (while (re-search-forward "^[^ \n]+:" nil t)
1116           (put-text-property
1117            (match-beginning 0) (1+ (match-beginning 0))
1118            'message-rank
1119            (if (setq rank (length (memq (assq (intern (buffer-substring
1120                                                        (match-beginning 0)
1121                                                        (1- (match-end 0))))
1122                                               message-header-format-alist)
1123                                         message-header-format-alist)))
1124                (- max rank)
1125              (1+ max)))))
1126       (message-sort-headers-1))))
1127
1128 \f
1129
1130 ;;;
1131 ;;; Message mode
1132 ;;;
1133
1134 ;;; Set up keymap.
1135
1136 (defvar message-mode-map nil)
1137
1138 (unless message-mode-map
1139   (setq message-mode-map (copy-keymap text-mode-map))
1140   (define-key message-mode-map "\C-c?" 'describe-mode)
1141
1142   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1143   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1144   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1145   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1146   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1147   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1148   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1149   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1150   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1151   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1152   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1153   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1154   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1155
1156   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1157   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1158
1159   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1160   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1161   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1162   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1163   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1164   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1165
1166   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1167   (define-key message-mode-map "\C-c\C-s" 'message-send)
1168   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1169   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1170
1171   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1172
1173   (define-key message-mode-map "\t" 'message-tab))
1174
1175 (easy-menu-define
1176  message-mode-menu message-mode-map "Message Menu."
1177  '("Message"
1178    ["Sort Headers" message-sort-headers t]
1179    ["Yank Original" message-yank-original t]
1180    ["Fill Yanked Message" message-fill-yanked-message t]
1181    ["Insert Signature" message-insert-signature t]
1182    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1183    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1184    ["Elide Region" message-elide-region (mark t)]
1185    ["Rename buffer" message-rename-buffer t]
1186    ["Spellcheck" ispell-message t]
1187    "----"
1188    ["Send Message" message-send-and-exit t]
1189    ["Abort Message" message-dont-send t]))
1190
1191 (easy-menu-define
1192  message-mode-field-menu message-mode-map ""
1193  '("Field"
1194    ["Fetch To" message-insert-to t]
1195    ["Fetch Newsgroups" message-insert-newsgroups t]
1196    "----"
1197    ["To" message-goto-to t]
1198    ["Subject" message-goto-subject t]
1199    ["Cc" message-goto-cc t]
1200    ["Reply-To" message-goto-reply-to t]
1201    ["Summary" message-goto-summary t]
1202    ["Keywords" message-goto-keywords t]
1203    ["Newsgroups" message-goto-newsgroups t]
1204    ["Followup-To" message-goto-followup-to t]
1205    ["Distribution" message-goto-distribution t]
1206    ["Body" message-goto-body t]
1207    ["Signature" message-goto-signature t]))
1208
1209 (defvar facemenu-add-face-function)
1210 (defvar facemenu-remove-face-function)
1211
1212 ;;;###autoload
1213 (defun message-mode ()
1214   "Major mode for editing mail and news to be sent.
1215 Like Text Mode but with these additional commands:
1216 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1217 C-c C-f  move to a header field (and create it if there isn't):
1218          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1219          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1220          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1221          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1222          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1223          C-c C-f C-f  move to Followup-To
1224 C-c C-t  message-insert-to (add a To header to a news followup)
1225 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1226 C-c C-b  message-goto-body (move to beginning of message text).
1227 C-c C-i  message-goto-signature (move to the beginning of the signature).
1228 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1229 C-c C-y  message-yank-original (insert current message, if any).
1230 C-c C-q  message-fill-yanked-message (fill what was yanked).
1231 C-c C-e  message-elide-region (elide the text between point and mark).
1232 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1233   (interactive)
1234   (kill-all-local-variables)
1235   (make-local-variable 'message-reply-buffer)
1236   (setq message-reply-buffer nil)
1237   (make-local-variable 'message-send-actions) 
1238   (make-local-variable 'message-exit-actions) 
1239   (make-local-variable 'message-kill-actions)
1240   (make-local-variable 'message-postpone-actions)
1241   (set-syntax-table message-mode-syntax-table)
1242   (use-local-map message-mode-map)
1243   (setq local-abbrev-table message-mode-abbrev-table)
1244   (setq major-mode 'message-mode)
1245   (setq mode-name "Message")
1246   (setq buffer-offer-save t)
1247   (make-local-variable 'font-lock-defaults)
1248   (setq font-lock-defaults '(message-font-lock-keywords t))
1249   (make-local-variable 'facemenu-add-face-function)
1250   (make-local-variable 'facemenu-remove-face-function)
1251   (setq facemenu-add-face-function
1252         (lambda (face end)
1253           (let ((face-fun (cdr (assq face message-face-alist))))
1254             (if face-fun
1255                 (funcall face-fun (point) end)
1256               (error "Face %s not configured for %s mode" face mode-name)))
1257           "")
1258         facemenu-remove-face-function t)
1259   (make-local-variable 'paragraph-separate)
1260   (make-local-variable 'paragraph-start)
1261   (setq paragraph-start (concat (regexp-quote mail-header-separator)
1262                                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
1263                                 "-- $\\|"
1264                                 paragraph-start))
1265   (setq paragraph-separate (concat (regexp-quote mail-header-separator)
1266                                    "$\\|[ \t]*[-_][-_][-_]+$\\|"
1267                                    "-- $\\|"
1268                                    paragraph-separate))
1269   (make-local-variable 'message-reply-headers)
1270   (setq message-reply-headers nil)
1271   (make-local-variable 'message-newsreader)
1272   (make-local-variable 'message-mailer)
1273   (make-local-variable 'message-post-method)
1274   (make-local-variable 'message-sent-message-via)
1275   (setq message-sent-message-via nil)
1276   (make-local-variable 'message-checksum)
1277   (setq message-checksum nil)
1278   ;;(when (fboundp 'mail-hist-define-keys)
1279   ;;  (mail-hist-define-keys))
1280   (when (string-match "XEmacs\\|Lucid" emacs-version)
1281     (message-setup-toolbar))
1282   (easy-menu-add message-mode-menu message-mode-map)
1283   (easy-menu-add message-mode-field-menu message-mode-map)
1284   ;; Allow mail alias things.
1285   (when (eq message-mail-alias-type 'abbrev)
1286     (if (fboundp 'mail-abbrevs-setup)
1287         (mail-abbrevs-setup)
1288       (funcall (intern "mail-aliases-setup"))))
1289   (run-hooks 'text-mode-hook 'message-mode-hook))
1290
1291 \f
1292
1293 ;;;
1294 ;;; Message mode commands
1295 ;;;
1296
1297 ;;; Movement commands
1298
1299 (defun message-goto-to ()
1300   "Move point to the To header."
1301   (interactive)
1302   (message-position-on-field "To"))
1303
1304 (defun message-goto-subject ()
1305   "Move point to the Subject header."
1306   (interactive)
1307   (message-position-on-field "Subject"))
1308
1309 (defun message-goto-cc ()
1310   "Move point to the Cc header."
1311   (interactive)
1312   (message-position-on-field "Cc" "To"))
1313
1314 (defun message-goto-bcc ()
1315   "Move point to the Bcc  header."
1316   (interactive)
1317   (message-position-on-field "Bcc" "Cc" "To"))
1318
1319 (defun message-goto-fcc ()
1320   "Move point to the Fcc header."
1321   (interactive)
1322   (message-position-on-field "Fcc" "To" "Newsgroups"))
1323
1324 (defun message-goto-reply-to ()
1325   "Move point to the Reply-To header."
1326   (interactive)
1327   (message-position-on-field "Reply-To" "Subject"))
1328
1329 (defun message-goto-newsgroups ()
1330   "Move point to the Newsgroups header."
1331   (interactive)
1332   (message-position-on-field "Newsgroups"))
1333
1334 (defun message-goto-distribution ()
1335   "Move point to the Distribution header."
1336   (interactive)
1337   (message-position-on-field "Distribution"))
1338
1339 (defun message-goto-followup-to ()
1340   "Move point to the Followup-To header."
1341   (interactive)
1342   (message-position-on-field "Followup-To" "Newsgroups"))
1343
1344 (defun message-goto-keywords ()
1345   "Move point to the Keywords header."
1346   (interactive)
1347   (message-position-on-field "Keywords" "Subject"))
1348
1349 (defun message-goto-summary ()
1350   "Move point to the Summary header."
1351   (interactive)
1352   (message-position-on-field "Summary" "Subject"))
1353
1354 (defun message-goto-body ()
1355   "Move point to the beginning of the message body."
1356   (interactive)
1357   (if (looking-at "[ \t]*\n") (expand-abbrev))
1358   (goto-char (point-min))
1359   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1360
1361 (defun message-goto-signature ()
1362   "Move point to the beginning of the message signature."
1363   (interactive)
1364   (goto-char (point-min))
1365   (if (re-search-forward message-signature-separator nil t)
1366       (forward-line 1)
1367     (goto-char (point-max))))
1368
1369 \f
1370
1371 (defun message-insert-to (&optional force)
1372   "Insert a To header that points to the author of the article being replied to.
1373 If the original author requested not to be sent mail, the function signals
1374 an error.
1375 With the prefix argument FORCE, insert the header anyway."
1376   (interactive "P")
1377   (let ((co (message-fetch-reply-field "mail-copies-to")))
1378     (when (and (null force)
1379                co
1380                (equal (downcase co) "never"))
1381       (error "The user has requested not to have copies sent via mail")))
1382   (when (and (message-position-on-field "To")
1383              (mail-fetch-field "to")
1384              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1385     (insert ", "))
1386   (insert (or (message-fetch-reply-field "reply-to")
1387               (message-fetch-reply-field "from") "")))
1388
1389 (defun message-insert-newsgroups ()
1390   "Insert the Newsgroups header from the article being replied to."
1391   (interactive)
1392   (when (and (message-position-on-field "Newsgroups")
1393              (mail-fetch-field "newsgroups")
1394              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1395     (insert ","))
1396   (insert (or (message-fetch-reply-field "newsgroups") "")))
1397
1398 \f
1399
1400 ;;; Various commands
1401
1402 (defun message-insert-signature (&optional force)
1403   "Insert a signature.  See documentation for the `message-signature' variable."
1404   (interactive (list 0))
1405   (let* ((signature
1406           (cond
1407            ((and (null message-signature)
1408                  (eq force 0))
1409             (save-excursion
1410               (goto-char (point-max))
1411               (not (re-search-backward
1412                     message-signature-separator nil t))))
1413            ((and (null message-signature)
1414                  force)
1415             t)
1416            ((message-functionp message-signature)
1417             (funcall message-signature))
1418            ((listp message-signature)
1419             (eval message-signature))
1420            (t message-signature)))
1421          (signature
1422           (cond ((stringp signature)
1423                  signature)
1424                 ((and (eq t signature)
1425                       message-signature-file
1426                       (file-exists-p message-signature-file))
1427                  signature))))
1428     (when signature
1429       (goto-char (point-max))
1430       ;; Insert the signature.
1431       (unless (bolp)
1432         (insert "\n"))
1433       (insert "\n-- \n")
1434       (if (eq signature t)
1435           (insert-file-contents message-signature-file)
1436         (insert signature))
1437       (goto-char (point-max))
1438       (or (bolp) (insert "\n")))))
1439
1440 (defun message-elide-region (b e)
1441   "Elide the text between point and mark.  An ellipsis (from
1442 message-elide-elipsis) will be inserted where the text was killed."
1443   (interactive "r")
1444   (kill-region b e)
1445   (unless (bolp)
1446     (insert "\n"))
1447   (insert message-elide-elipsis))
1448
1449 (defvar message-caesar-translation-table nil)
1450
1451 (defun message-caesar-region (b e &optional n)
1452   "Caesar rotation of region by N, default 13, for decrypting netnews."
1453   (interactive
1454    (list
1455     (min (point) (or (mark t) (point)))
1456     (max (point) (or (mark t) (point)))
1457     (when current-prefix-arg
1458       (prefix-numeric-value current-prefix-arg))))
1459
1460   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1461   (unless (or (zerop n)                 ; no action needed for a rot of 0
1462               (= b e))                  ; no region to rotate
1463     ;; We build the table, if necessary.
1464     (when (or (not message-caesar-translation-table)
1465               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1466         (setq message-caesar-translation-table
1467               (message-make-caesar-translation-table n)))
1468     ;; Then we translate the region.  Do it this way to retain
1469     ;; text properties.
1470     (while (< b e)
1471       (subst-char-in-region
1472        b (1+ b) (char-after b)
1473        (aref message-caesar-translation-table (char-after b)))
1474       (incf b))))
1475
1476 (defun message-make-caesar-translation-table (n)
1477   "Create a rot table with offset N."
1478   (let ((i -1)
1479         (table (make-string 256 0)))
1480     (while (< (incf i) 256)
1481       (aset table i i))
1482     (concat
1483      (substring table 0 ?A)
1484      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1485      (substring table ?A (+ ?A n))
1486      (substring table (+ ?A 26) ?a)
1487      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1488      (substring table ?a (+ ?a n))
1489      (substring table (+ ?a 26) 255))))
1490
1491 (defun message-caesar-buffer-body (&optional rotnum)
1492   "Caesar rotates all letters in the current buffer by 13 places.
1493 Used to encode/decode possibly offensive messages (commonly in net.jokes).
1494 With prefix arg, specifies the number of places to rotate each letter forward.
1495 Mail and USENET news headers are not rotated."
1496   (interactive (if current-prefix-arg
1497                    (list (prefix-numeric-value current-prefix-arg))
1498                  (list nil)))
1499   (save-excursion
1500     (save-restriction
1501       (when (message-goto-body)
1502         (narrow-to-region (point) (point-max)))
1503       (message-caesar-region (point-min) (point-max) rotnum))))
1504
1505 (defun message-pipe-buffer-body (program)
1506   "Pipe the message body in the current buffer through PROGRAM."
1507   (save-excursion
1508     (save-restriction
1509       (when (message-goto-body)
1510         (narrow-to-region (point) (point-max)))
1511       (let ((body (buffer-substring (point-min) (point-max))))
1512         (unless (equal 0 (call-process-region
1513                            (point-min) (point-max) program t t))
1514             (insert body)
1515             (message "%s failed." program))))))
1516
1517 (defun message-rename-buffer (&optional enter-string)
1518   "Rename the *message* buffer to \"*message* RECIPIENT\".
1519 If the function is run with a prefix, it will ask for a new buffer
1520 name, rather than giving an automatic name."
1521   (interactive "Pbuffer name: ")
1522   (save-excursion
1523     (save-restriction
1524       (goto-char (point-min))
1525       (narrow-to-region (point)
1526                         (search-forward mail-header-separator nil 'end))
1527       (let* ((mail-to (or
1528                        (if (message-news-p) (message-fetch-field "Newsgroups")
1529                          (message-fetch-field "To"))
1530                        ""))
1531              (mail-trimmed-to
1532               (if (string-match "," mail-to)
1533                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1534                 mail-to))
1535              (name-default (concat "*message* " mail-trimmed-to))
1536              (name (if enter-string
1537                        (read-string "New buffer name: " name-default)
1538                      name-default))
1539              (default-directory
1540                (file-name-as-directory message-autosave-directory)))
1541         (rename-buffer name t)))))
1542
1543 (defun message-fill-yanked-message (&optional justifyp)
1544   "Fill the paragraphs of a message yanked into this one.
1545 Numeric argument means justify as well."
1546   (interactive "P")
1547   (save-excursion
1548     (goto-char (point-min))
1549     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1550     (let ((fill-prefix message-yank-prefix))
1551       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1552
1553 (defun message-indent-citation ()
1554   "Modify text just inserted from a message to be cited.
1555 The inserted text should be the region.
1556 When this function returns, the region is again around the modified text.
1557
1558 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1559 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1560   (let ((start (point)))
1561     ;; Remove unwanted headers.
1562     (when message-ignored-cited-headers
1563       (let (all-removed)
1564         (save-restriction
1565           (narrow-to-region
1566            (goto-char start)
1567            (if (search-forward "\n\n" nil t)
1568                (1- (point))
1569              (point)))
1570           (message-remove-header message-ignored-cited-headers t)
1571           (when (= (point-min) (point-max))
1572             (setq all-removed t))
1573           (goto-char (point-max)))
1574         (if all-removed
1575             (goto-char start)
1576           (forward-line 1))))
1577     ;; Delete blank lines at the start of the buffer.
1578     (while (and (point-min)
1579                 (eolp)
1580                 (not (eobp)))
1581       (message-delete-line))
1582     ;; Delete blank lines at the end of the buffer.
1583     (goto-char (point-max))
1584     (unless (eolp)
1585       (insert "\n"))
1586     (while (and (zerop (forward-line -1))
1587                 (looking-at "$"))
1588       (message-delete-line))
1589     ;; Do the indentation.
1590     (if (null message-yank-prefix)
1591         (indent-rigidly start (mark t) message-indentation-spaces)
1592       (save-excursion
1593         (goto-char start)
1594         (while (< (point) (mark t))
1595           (insert message-yank-prefix)
1596           (forward-line 1))))
1597     (goto-char start)))
1598
1599 (defun message-yank-original (&optional arg)
1600   "Insert the message being replied to, if any.
1601 Puts point before the text and mark after.
1602 Normally indents each nonblank line ARG spaces (default 3).  However,
1603 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1604
1605 This function uses `message-cite-function' to do the actual citing.
1606
1607 Just \\[universal-argument] as argument means don't indent, insert no
1608 prefix, and don't delete any headers."
1609   (interactive "P")
1610   (let ((modified (buffer-modified-p)))
1611     (when (and message-reply-buffer
1612                message-cite-function)
1613       (delete-windows-on message-reply-buffer t)
1614       (insert-buffer message-reply-buffer)
1615       (funcall message-cite-function)
1616       (message-exchange-point-and-mark)
1617       (unless (bolp)
1618         (insert ?\n))
1619       (unless modified
1620         (setq message-checksum (cons (message-checksum) (buffer-size)))))))
1621
1622 (defun message-cite-original ()
1623   "Cite function in the standard Message manner."
1624   (let ((start (point))
1625         (functions
1626          (when message-indent-citation-function
1627            (if (listp message-indent-citation-function)
1628                message-indent-citation-function
1629              (list message-indent-citation-function)))))
1630     (goto-char start)
1631     (while functions
1632       (funcall (pop functions)))
1633     (when message-citation-line-function
1634       (unless (bolp)
1635         (insert "\n"))
1636       (funcall message-citation-line-function))))
1637
1638 (defun message-insert-citation-line ()
1639   "Function that inserts a simple citation line."
1640   (when message-reply-headers
1641     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1642
1643 (defun message-position-on-field (header &rest afters)
1644   (let ((case-fold-search t))
1645     (save-restriction
1646       (narrow-to-region
1647        (goto-char (point-min))
1648        (progn
1649          (re-search-forward
1650           (concat "^" (regexp-quote mail-header-separator) "$"))
1651          (match-beginning 0)))
1652       (goto-char (point-min))
1653       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1654           (progn
1655             (re-search-forward "^[^ \t]" nil 'move)
1656             (beginning-of-line)
1657             (skip-chars-backward "\n")
1658             t)
1659         (while (and afters
1660                     (not (re-search-forward
1661                           (concat "^" (regexp-quote (car afters)) ":")
1662                           nil t)))
1663           (pop afters))
1664         (when afters
1665           (re-search-forward "^[^ \t]" nil 'move)
1666           (beginning-of-line))
1667         (insert header ": \n")
1668         (forward-char -1)
1669         nil))))
1670
1671 (defun message-remove-signature ()
1672   "Remove the signature from the text between point and mark.
1673 The text will also be indented the normal way."
1674   (save-excursion
1675     (let ((start (point))
1676           mark)
1677       (if (not (re-search-forward message-signature-separator (mark t) t))
1678           ;; No signature here, so we just indent the cited text.
1679           (message-indent-citation)
1680         ;; Find the last non-empty line.
1681         (forward-line -1)
1682         (while (looking-at "[ \t]*$")
1683           (forward-line -1))
1684         (forward-line 1)
1685         (setq mark (set-marker (make-marker) (point)))
1686         (goto-char start)
1687         (message-indent-citation)
1688         ;; Enable undoing the deletion.
1689         (undo-boundary)
1690         (delete-region mark (mark t))
1691         (set-marker mark nil)))))
1692
1693 \f
1694
1695 ;;;
1696 ;;; Sending messages
1697 ;;;
1698
1699 (defun message-send-and-exit (&optional arg)
1700   "Send message like `message-send', then, if no errors, exit from mail buffer."
1701   (interactive "P")
1702   (let ((buf (current-buffer))
1703         (actions message-exit-actions))
1704     (when (and (message-send arg)
1705                (buffer-name buf))
1706       (if message-kill-buffer-on-exit
1707           (kill-buffer buf)
1708         (bury-buffer buf)
1709         (when (eq buf (current-buffer))
1710           (message-bury buf)))
1711       (message-do-actions actions))))
1712
1713 (defun message-dont-send ()
1714   "Don't send the message you have been editing."
1715   (interactive)
1716   (let ((actions message-postpone-actions))
1717     (message-bury (current-buffer))
1718     (message-do-actions actions)))
1719
1720 (defun message-kill-buffer ()
1721   "Kill the current buffer."
1722   (interactive)
1723   (when (or (not (buffer-modified-p))
1724             (yes-or-no-p "Message modified; kill anyway? "))
1725     (let ((actions message-kill-actions))
1726       (kill-buffer (current-buffer))
1727       (message-do-actions actions))))
1728
1729 (defun message-bury (buffer)
1730   "Bury this mail buffer."
1731   (let ((newbuf (other-buffer buffer)))
1732     (bury-buffer buffer)
1733     (if (and (fboundp 'frame-parameters)
1734              (cdr (assq 'dedicated (frame-parameters)))
1735              (not (null (delq (selected-frame) (visible-frame-list)))))
1736         (delete-frame (selected-frame))
1737       (switch-to-buffer newbuf))))
1738
1739 (defun message-send (&optional arg)
1740   "Send the message in the current buffer.
1741 If `message-interactive' is non-nil, wait for success indication
1742 or error messages, and inform user.
1743 Otherwise any failure is reported in a message back to
1744 the user from the mailer."
1745   (interactive "P")
1746   (when (if buffer-file-name
1747             (y-or-n-p (format "Send buffer contents as %s message? "
1748                               (if (message-mail-p)
1749                                   (if (message-news-p) "mail and news" "mail")
1750                                 "news")))
1751           (or (buffer-modified-p)
1752               (y-or-n-p "No changes in the buffer; really send? ")))
1753     ;; Make it possible to undo the coming changes.
1754     (undo-boundary)
1755     (let ((inhibit-read-only t))
1756       (put-text-property (point-min) (point-max) 'read-only nil))
1757     (message-fix-before-sending)
1758     (run-hooks 'message-send-hook)
1759     (message "Sending...")
1760     (let ((alist message-send-method-alist)
1761           (success t)
1762           elem sent)
1763       (while (and success
1764                   (setq elem (pop alist)))
1765         (when (and (or (not (funcall (cadr elem)))
1766                        (and (or (not (memq (car elem)
1767                                            message-sent-message-via))
1768                                 (y-or-n-p
1769                                  (format
1770                                   "Already sent message via %s; resend? "
1771                                   (car elem))))
1772                             (setq success (funcall (caddr elem) arg)))))
1773           (setq sent t)))
1774       (when (and success sent)
1775         (message-do-fcc)
1776         ;;(when (fboundp 'mail-hist-put-headers-into-history)
1777         ;; (mail-hist-put-headers-into-history))
1778         (run-hooks 'message-sent-hook)
1779         (message "Sending...done")
1780         ;; If buffer has no file, mark it as unmodified and delete autosave.
1781         (unless buffer-file-name
1782           (set-buffer-modified-p nil)
1783           (delete-auto-save-file-if-necessary t))
1784         ;; Delete other mail buffers and stuff.
1785         (message-do-send-housekeeping)
1786         (message-do-actions message-send-actions)
1787         ;; Return success.
1788         t))))
1789
1790 (defun message-send-via-mail (arg)
1791   "Send the current message via mail."  
1792   (message-send-mail arg))
1793
1794 (defun message-send-via-news (arg)
1795   "Send the current message via news."
1796   (funcall message-send-news-function arg))
1797
1798 (defun message-fix-before-sending ()
1799   "Do various things to make the message nice before sending it."
1800   ;; Make sure there's a newline at the end of the message.
1801   (goto-char (point-max))
1802   (unless (bolp)
1803     (insert "\n")))
1804
1805 (defun message-add-action (action &rest types)
1806   "Add ACTION to be performed when doing an exit of type TYPES."
1807   (let (var)
1808     (while types
1809       (set (setq var (intern (format "message-%s-actions" (pop types))))
1810            (nconc (symbol-value var) (list action))))))
1811
1812 (defun message-do-actions (actions)
1813   "Perform all actions in ACTIONS."
1814   ;; Now perform actions on successful sending.
1815   (while actions
1816     (ignore-errors
1817       (cond
1818        ;; A simple function.
1819        ((message-functionp (car actions))
1820         (funcall (car actions)))
1821        ;; Something to be evaled.
1822        (t
1823         (eval (car actions)))))
1824     (pop actions)))
1825
1826 (defun message-send-mail (&optional arg)
1827   (require 'mail-utils)
1828   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
1829         (case-fold-search nil)
1830         (news (message-news-p))
1831         (mailbuf (current-buffer)))
1832     (save-restriction
1833       (message-narrow-to-headers)
1834       ;; Insert some headers.
1835       (let ((message-deletable-headers
1836              (if news nil message-deletable-headers)))
1837         (message-generate-headers message-required-mail-headers))
1838       ;; Let the user do all of the above.
1839       (run-hooks 'message-header-hook))
1840     (unwind-protect
1841         (save-excursion
1842           (set-buffer tembuf)
1843           (erase-buffer)
1844           ;; Avoid copying text props.
1845           (insert (format
1846                    "%s" (save-excursion
1847                           (set-buffer mailbuf)
1848                           (buffer-string))))
1849           ;; Remove some headers.
1850           (save-restriction
1851             (message-narrow-to-headers)
1852             ;; Remove some headers.
1853             (message-remove-header message-ignored-mail-headers t))
1854           (goto-char (point-max))
1855           ;; require one newline at the end.
1856           (or (= (preceding-char) ?\n)
1857               (insert ?\n))
1858           (when (and news
1859                      (or (message-fetch-field "cc")
1860                          (message-fetch-field "to")))
1861             (message-insert-courtesy-copy))
1862           (funcall message-send-mail-function))
1863       (kill-buffer tembuf))
1864     (set-buffer mailbuf)
1865     (push 'mail message-sent-message-via)))
1866
1867 (defun message-send-mail-with-sendmail ()
1868   "Send off the prepared buffer with sendmail."
1869   (let ((errbuf (if message-interactive
1870                     (generate-new-buffer " sendmail errors")
1871                   0))
1872         resend-to-addresses delimline)
1873     (let ((case-fold-search t))
1874       (save-restriction
1875         (message-narrow-to-headers)
1876         (setq resend-to-addresses (message-fetch-field "resent-to")))
1877       ;; Change header-delimiter to be what sendmail expects.
1878       (goto-char (point-min))
1879       (re-search-forward
1880        (concat "^" (regexp-quote mail-header-separator) "\n"))
1881       (replace-match "\n")
1882       (backward-char 1)
1883       (setq delimline (point-marker))
1884       (run-hooks 'message-send-mail-hook)
1885       ;; Insert an extra newline if we need it to work around
1886       ;; Sun's bug that swallows newlines.
1887       (goto-char (1+ delimline))
1888       (when (eval message-mailer-swallows-blank-line)
1889         (newline))
1890       (when message-interactive
1891         (save-excursion
1892           (set-buffer errbuf)
1893           (erase-buffer))))
1894     (let ((default-directory "/"))
1895       (apply 'call-process-region
1896              (append (list (point-min) (point-max)
1897                            (if (boundp 'sendmail-program)
1898                                sendmail-program
1899                              "/usr/lib/sendmail")
1900                            nil errbuf nil "-oi")
1901                      ;; Always specify who from,
1902                      ;; since some systems have broken sendmails.
1903                      ;; But some systems are more broken with -f, so
1904                      ;; we'll let users override this.
1905                      (if (null message-sendmail-f-is-evil)
1906                          (list "-f" (user-login-name)))
1907                      ;; These mean "report errors by mail"
1908                      ;; and "deliver in background".
1909                      (if (null message-interactive) '("-oem" "-odb"))
1910                      ;; Get the addresses from the message
1911                      ;; unless this is a resend.
1912                      ;; We must not do that for a resend
1913                      ;; because we would find the original addresses.
1914                      ;; For a resend, include the specific addresses.
1915                      (if resend-to-addresses
1916                          (list resend-to-addresses)
1917                        '("-t")))))
1918     (when message-interactive
1919       (save-excursion
1920         (set-buffer errbuf)
1921         (goto-char (point-min))
1922         (while (re-search-forward "\n\n* *" nil t)
1923           (replace-match "; "))
1924         (if (not (zerop (buffer-size)))
1925             (error "Sending...failed to %s"
1926                    (buffer-substring (point-min) (point-max)))))
1927       (when (bufferp errbuf)
1928         (kill-buffer errbuf)))))
1929
1930 (defun message-send-mail-with-qmail ()
1931   "Pass the prepared message buffer to qmail-inject.
1932 Refer to the documentation for the variable `message-send-mail-function'
1933 to find out how to use this."
1934   ;; replace the header delimiter with a blank line
1935   (goto-char (point-min))
1936   (re-search-forward
1937    (concat "^" (regexp-quote mail-header-separator) "\n"))
1938   (replace-match "\n")
1939   (run-hooks 'message-send-mail-hook)
1940   ;; send the message
1941   (case
1942       (apply
1943        'call-process-region 1 (point-max) message-qmail-inject-program
1944        nil nil nil
1945        ;; qmail-inject's default behaviour is to look for addresses on the
1946        ;; command line; if there're none, it scans the headers.
1947        ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
1948        ;;
1949        ;; in general, ALL of qmail-inject's defaults are perfect for simply
1950        ;; reading a formatted (i. e., at least a To: or Resent-To header)
1951        ;; message from stdin.
1952        ;;
1953        ;; qmail also has the advantage of not having been raped by
1954        ;; various vendors, so we don't have to allow for that, either --
1955        ;; compare this with message-send-mail-with-sendmail and weep
1956        ;; for sendmail's lost innocence.
1957        ;;
1958        ;; all this is way cool coz it lets us keep the arguments entirely
1959        ;; free for -inject-arguments -- a big win for the user and for us
1960        ;; since we don't have to play that double-guessing game and the user
1961        ;; gets full control (no gestapo'ish -f's, for instance).  --sj
1962        message-qmail-inject-args)
1963     ;; qmail-inject doesn't say anything on it's stdout/stderr,
1964     ;; we have to look at the retval instead
1965     (0 nil)
1966     (1   (error "qmail-inject reported permanent failure"))
1967     (111 (error "qmail-inject reported transient failure"))
1968     ;; should never happen
1969     (t   (error "qmail-inject reported unknown failure"))))
1970
1971 (defun message-send-mail-with-mh ()
1972   "Send the prepared message buffer with mh."
1973   (let ((mh-previous-window-config nil)
1974         (name (make-temp-name
1975                (concat (file-name-as-directory
1976                         (expand-file-name message-autosave-directory))
1977                        "msg."))))
1978     (setq buffer-file-name name)
1979     ;; MH wants to generate these headers itself.
1980     (when message-mh-deletable-headers
1981       (let ((headers message-mh-deletable-headers))
1982         (while headers
1983           (goto-char (point-min))
1984           (and (re-search-forward
1985                 (concat "^" (symbol-name (car headers)) ": *") nil t)
1986                (message-delete-line))
1987           (pop headers))))
1988     (run-hooks 'message-send-mail-hook)
1989     ;; Pass it on to mh.
1990     (mh-send-letter)))
1991
1992 (defun message-send-news (&optional arg)
1993   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
1994         (case-fold-search nil)
1995         (method (if (message-functionp message-post-method)
1996                     (funcall message-post-method arg)
1997                   message-post-method))
1998         (messbuf (current-buffer))
1999         (message-syntax-checks
2000          (if arg
2001              (cons '(existing-newsgroups . disabled)
2002                    message-syntax-checks)
2003            message-syntax-checks))
2004         result)
2005     (save-restriction
2006       (message-narrow-to-headers)
2007       ;; Insert some headers.
2008       (message-generate-headers message-required-news-headers)
2009       ;; Let the user do all of the above.
2010       (run-hooks 'message-header-hook))
2011     (message-cleanup-headers)
2012     (if (not (message-check-news-syntax))
2013         (progn
2014           ;;(message "Posting not performed")
2015           nil)
2016       (unwind-protect
2017           (save-excursion
2018             (set-buffer tembuf)
2019             (buffer-disable-undo (current-buffer))
2020             (erase-buffer)
2021             ;; Avoid copying text props.
2022             (insert (format
2023                      "%s" (save-excursion
2024                             (set-buffer messbuf)
2025                             (buffer-string))))
2026             ;; Remove some headers.
2027             (save-restriction
2028               (message-narrow-to-headers)
2029               ;; Remove some headers.
2030               (message-remove-header message-ignored-news-headers t))
2031             (goto-char (point-max))
2032             ;; require one newline at the end.
2033             (or (= (preceding-char) ?\n)
2034                 (insert ?\n))
2035             (let ((case-fold-search t))
2036               ;; Remove the delimiter.
2037               (goto-char (point-min))
2038               (re-search-forward
2039                (concat "^" (regexp-quote mail-header-separator) "\n"))
2040               (replace-match "\n")
2041               (backward-char 1))
2042             (run-hooks 'message-send-news-hook)
2043             (require (car method))
2044             (funcall (intern (format "%s-open-server" (car method)))
2045                      (cadr method) (cddr method))
2046             (setq result
2047                   (funcall (intern (format "%s-request-post" (car method)))
2048                            (cadr method))))
2049         (kill-buffer tembuf))
2050       (set-buffer messbuf)
2051       (if result
2052           (push 'news message-sent-message-via)
2053         (message "Couldn't send message via news: %s"
2054                  (nnheader-get-report (car method)))
2055         nil))))
2056
2057 ;;;
2058 ;;; Header generation & syntax checking.
2059 ;;;
2060
2061 (defmacro message-check (type &rest forms)
2062   "Eval FORMS if TYPE is to be checked."
2063   `(or (message-check-element ,type)
2064        (save-excursion
2065          ,@forms)))
2066
2067 (put 'message-check 'lisp-indent-function 1)
2068 (put 'message-check 'edebug-form-spec '(form body))
2069
2070 (defun message-check-element (type)
2071   "Returns non-nil if this type is not to be checked."
2072   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2073       t
2074     (let ((able (assq type message-syntax-checks)))
2075       (and (consp able)
2076            (eq (cdr able) 'disabled)))))
2077
2078 (defun message-check-news-syntax ()
2079   "Check the syntax of the message."
2080   (save-excursion
2081     (save-restriction
2082       (widen)
2083       (and
2084        ;; We narrow to the headers and check them first.
2085        (save-excursion
2086          (save-restriction
2087            (message-narrow-to-headers)
2088            (message-check-news-header-syntax)))
2089        ;; Check the body.
2090        (message-check-news-body-syntax)))))
2091
2092 (defun message-check-news-header-syntax ()
2093   (and
2094    ;; Check the Subject header.
2095    (message-check 'subject
2096      (let* ((case-fold-search t)
2097             (subject (message-fetch-field "subject")))
2098        (or
2099         (and subject
2100              (not (string-match "\\`[ \t]*\\'" subject)))
2101         (ignore
2102          (message
2103           "The subject field is empty or missing.  Posting is denied.")))))
2104    ;; Check for commands in Subject.
2105    (message-check 'subject-cmsg
2106      (if (string-match "^cmsg " (message-fetch-field "subject"))
2107          (y-or-n-p
2108           "The control code \"cmsg\" is in the subject.  Really post? ")
2109        t))
2110    ;; Check for multiple identical headers.
2111    (message-check 'multiple-headers
2112      (let (found)
2113        (while (and (not found)
2114                    (re-search-forward "^[^ \t:]+: " nil t))
2115          (save-excursion
2116            (or (re-search-forward
2117                 (concat "^"
2118                         (regexp-quote
2119                          (setq found
2120                                (buffer-substring
2121                                 (match-beginning 0) (- (match-end 0) 2))))
2122                         ":")
2123                 nil t)
2124                (setq found nil))))
2125        (if found
2126            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2127          t)))
2128    ;; Check for Version and Sendsys.
2129    (message-check 'sendsys
2130      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2131          (y-or-n-p
2132           (format "The article contains a %s command.  Really post? "
2133                   (buffer-substring (match-beginning 0)
2134                                     (1- (match-end 0)))))
2135        t))
2136    ;; See whether we can shorten Followup-To.
2137    (message-check 'shorten-followup-to
2138      (let ((newsgroups (message-fetch-field "newsgroups"))
2139            (followup-to (message-fetch-field "followup-to"))
2140            to)
2141        (when (and newsgroups
2142                   (string-match "," newsgroups)
2143                   (not followup-to)
2144                   (not
2145                    (zerop
2146                     (length
2147                      (setq to (completing-read
2148                                "Followups to: (default all groups) "
2149                                (mapcar (lambda (g) (list g))
2150                                        (cons "poster"
2151                                              (message-tokenize-header
2152                                               newsgroups)))))))))
2153          (goto-char (point-min))
2154          (insert "Followup-To: " to "\n"))
2155        t))
2156    ;; Check "Shoot me".
2157    (message-check 'shoot
2158      (if (re-search-forward
2159           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2160          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2161        t))
2162    ;; Check for Approved.
2163    (message-check 'approved
2164      (if (re-search-forward "^Approved:" nil t)
2165          (y-or-n-p "The article contains an Approved header.  Really post? ")
2166        t))
2167    ;; Check the Message-ID header.
2168    (message-check 'message-id
2169      (let* ((case-fold-search t)
2170             (message-id (message-fetch-field "message-id" t)))
2171        (or (not message-id)
2172            (and (string-match "@" message-id)
2173                 (string-match "@[^\\.]*\\." message-id))
2174            (y-or-n-p
2175             (format "The Message-ID looks strange: \"%s\".  Really post? "
2176                     message-id)))))
2177    ;; Check the Newsgroups & Followup-To headers.
2178    (message-check 'existing-newsgroups
2179      (let* ((case-fold-search t)
2180             (newsgroups (message-fetch-field "newsgroups"))
2181             (followup-to (message-fetch-field "followup-to"))
2182             (groups (message-tokenize-header
2183                      (if followup-to
2184                          (concat newsgroups "," followup-to)
2185                        newsgroups)))
2186             (hashtb (and (boundp 'gnus-active-hashtb)
2187                          gnus-active-hashtb))
2188             errors)
2189        (if (or (not hashtb)
2190                (not (boundp 'gnus-read-active-file))
2191                (not gnus-read-active-file)
2192                (eq gnus-read-active-file 'some))
2193            t
2194          (while groups
2195            (when (and (not (boundp (intern (car groups) hashtb)))
2196                       (not (equal (car groups) "poster")))
2197              (push (car groups) errors))
2198            (pop groups))
2199          (if (not errors)
2200              t
2201            (y-or-n-p
2202             (format
2203              "Really post to %s unknown group%s: %s "
2204              (if (= (length errors) 1) "this" "these")
2205              (if (= (length errors) 1) "" "s")
2206              (mapconcat 'identity errors ", ")))))))
2207    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2208    (message-check 'valid-newsgroups
2209      (let ((case-fold-search t)
2210            (headers '("Newsgroups" "Followup-To"))
2211            header error)
2212        (while (and headers (not error))
2213          (when (setq header (mail-fetch-field (car headers)))
2214            (if (or
2215                 (not
2216                  (string-match
2217                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2218                   header))
2219                 (memq
2220                  nil (mapcar
2221                       (lambda (g)
2222                         (not (string-match "\\.\\'\\|\\.\\." g)))
2223                       (message-tokenize-header header ","))))
2224                (setq error t)))
2225          (unless error
2226            (pop headers)))
2227        (if (not error)
2228            t
2229          (y-or-n-p
2230           (format "The %s header looks odd: \"%s\".  Really post? "
2231                   (car headers) header)))))
2232    (message-check 'repeated-newsgroups
2233      (let ((case-fold-search t)
2234            (headers '("Newsgroups" "Followup-To"))
2235            header error groups group)
2236        (while (and headers
2237                    (not error))
2238          (when (setq header (mail-fetch-field (pop headers)))
2239            (setq groups (message-tokenize-header header ","))
2240            (while (setq group (pop groups))
2241              (when (member group groups)
2242                (setq error group
2243                      groups nil)))))
2244        (if (not error)
2245            t
2246          (y-or-n-p
2247           (format "Group %s is repeated in headers.  Really post? " error)))))
2248    ;; Check the From header.
2249    (message-check 'from
2250      (let* ((case-fold-search t)
2251             (from (message-fetch-field "from"))
2252             (ad (nth 1 (mail-extract-address-components from))))
2253        (cond
2254         ((not from)
2255          (message "There is no From line.  Posting is denied.")
2256          nil)
2257         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2258              (string-match "\\.\\." ad) ;larsi@ifi..uio
2259              (string-match "@\\." ad)   ;larsi@.ifi.uio
2260              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2261              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2262              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2263          (message
2264           "Denied posting -- the From looks strange: \"%s\"." from)
2265          nil)
2266         (t t))))))
2267
2268 (defun message-check-news-body-syntax ()
2269   (and
2270    ;; Check for long lines.
2271    (message-check 'long-lines
2272      (goto-char (point-min))
2273      (re-search-forward
2274       (concat "^" (regexp-quote mail-header-separator) "$"))
2275      (while (and
2276              (progn
2277                (end-of-line)
2278                (< (current-column) 80))
2279              (zerop (forward-line 1))))
2280      (or (bolp)
2281          (eobp)
2282          (y-or-n-p
2283           "You have lines longer than 79 characters.  Really post? ")))
2284    ;; Check whether the article is empty.
2285    (message-check 'empty
2286      (goto-char (point-min))
2287      (re-search-forward
2288       (concat "^" (regexp-quote mail-header-separator) "$"))
2289      (forward-line 1)
2290      (let ((b (point)))
2291        (goto-char (point-max))
2292        (re-search-backward message-signature-separator nil t)
2293        (beginning-of-line)
2294        (or (re-search-backward "[^ \n\t]" b t)
2295            (y-or-n-p "Empty article.  Really post? "))))
2296    ;; Check for control characters.
2297    (message-check 'control-chars
2298      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2299          (y-or-n-p
2300           "The article contains control characters.  Really post? ")
2301        t))
2302    ;; Check excessive size.
2303    (message-check 'size
2304      (if (> (buffer-size) 60000)
2305          (y-or-n-p
2306           (format "The article is %d octets long.  Really post? "
2307                   (buffer-size)))
2308        t))
2309    ;; Check whether any new text has been added.
2310    (message-check 'new-text
2311      (or
2312       (not message-checksum)
2313       (not (and (eq (message-checksum) (car message-checksum))
2314                 (eq (buffer-size) (cdr message-checksum))))
2315       (y-or-n-p
2316        "It looks like no new text has been added.  Really post? ")))
2317    ;; Check the length of the signature.
2318    (message-check 'signature
2319      (goto-char (point-max))
2320      (if (or (not (re-search-backward message-signature-separator nil t))
2321              (search-forward message-forward-end-separator nil t))
2322          t
2323        (if (> (count-lines (point) (point-max)) 5)
2324            (y-or-n-p
2325             (format
2326              "Your .sig is %d lines; it should be max 4.  Really post? "
2327              (1- (count-lines (point) (point-max)))))
2328          t)))))
2329
2330 (defun message-checksum ()
2331   "Return a \"checksum\" for the current buffer."
2332   (let ((sum 0))
2333     (save-excursion
2334       (goto-char (point-min))
2335       (re-search-forward
2336        (concat "^" (regexp-quote mail-header-separator) "$"))
2337       (while (not (eobp))
2338         (when (not (looking-at "[ \t\n]"))
2339           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2340                             (following-char))))
2341         (forward-char 1)))
2342     sum))
2343
2344 (defun message-do-fcc ()
2345   "Process Fcc headers in the current buffer."
2346   (let ((case-fold-search t)
2347         (buf (current-buffer))
2348         list file)
2349     (save-excursion
2350       (set-buffer (get-buffer-create " *message temp*"))
2351       (buffer-disable-undo (current-buffer))
2352       (erase-buffer)
2353       (insert-buffer-substring buf)
2354       (save-restriction
2355         (message-narrow-to-headers)
2356         (while (setq file (message-fetch-field "fcc"))
2357           (push file list)
2358           (message-remove-header "fcc" nil t)))
2359       (goto-char (point-min))
2360       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2361       (replace-match "" t t)
2362       ;; Process FCC operations.
2363       (while list
2364         (setq file (pop list))
2365         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2366             ;; Pipe the article to the program in question.
2367             (call-process-region (point-min) (point-max) shell-file-name
2368                                  nil nil nil shell-command-switch
2369                                  (match-string 1 file))
2370           ;; Save the article.
2371           (setq file (expand-file-name file))
2372           (unless (file-exists-p (file-name-directory file))
2373             (make-directory (file-name-directory file) t))
2374           (if (and message-fcc-handler-function
2375                    (not (eq message-fcc-handler-function 'rmail-output)))
2376               (funcall message-fcc-handler-function file)
2377             (if (and (file-readable-p file) (mail-file-babyl-p file))
2378                 (rmail-output file 1 nil t)
2379               (let ((mail-use-rfc822 t))
2380                 (rmail-output file 1 t t))))))
2381
2382       (kill-buffer (current-buffer)))))
2383
2384 (defun message-output (filename)
2385   "Append this article to Unix/babyl mail file.."
2386   (if (and (file-readable-p filename)
2387            (mail-file-babyl-p filename))
2388       (gnus-output-to-rmail filename t)
2389     (gnus-output-to-mail filename t)))
2390
2391 (defun message-cleanup-headers ()
2392   "Do various automatic cleanups of the headers."
2393   ;; Remove empty lines in the header.
2394   (save-restriction
2395     (message-narrow-to-headers)
2396     ;; Remove blank lines.
2397     (while (re-search-forward "^[ \t]*\n" nil t)
2398       (replace-match "" t t))
2399
2400     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2401     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2402     ;; embedded line breaks.
2403     (goto-char (point-min))
2404     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2405       (save-restriction
2406         (narrow-to-region
2407          (point)
2408          (if (re-search-forward "^[^ \t]" nil t)
2409              (match-beginning 0)
2410            (forward-line 1)
2411            (point)))
2412         (goto-char (point-min))
2413         (while (re-search-forward "\n[ \t]+" nil t)
2414           (replace-match " " t t))      ;No line breaks (too confusing)
2415         (goto-char (point-min))
2416         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2417           (replace-match "," t t))
2418         (goto-char (point-min))
2419         ;; Remove trailing commas.
2420         (when (re-search-forward ",+$" nil t)
2421           (replace-match "" t t))))))
2422
2423 (defun message-make-date ()
2424   "Make a valid data header."
2425   (let ((now (current-time)))
2426     (timezone-make-date-arpa-standard
2427      (current-time-string now) (current-time-zone now))))
2428
2429 (defun message-make-message-id ()
2430   "Make a unique Message-ID."
2431   (concat "<" (message-unique-id)
2432           (let ((psubject (save-excursion (message-fetch-field "subject")))
2433                 (psupersedes
2434                  (save-excursion (message-fetch-field "supersedes"))))
2435             (if (or
2436                  (and message-reply-headers
2437                       (mail-header-references message-reply-headers)
2438                       (mail-header-subject message-reply-headers)
2439                       psubject
2440                       (mail-header-subject message-reply-headers)
2441                       (not (string=
2442                             (message-strip-subject-re
2443                              (mail-header-subject message-reply-headers))
2444                             (message-strip-subject-re psubject))))
2445                  (and psupersedes
2446                       (string-match "_-_@" psupersedes)))
2447                 "_-_" ""))
2448           "@" (message-make-fqdn) ">"))
2449
2450 (defvar message-unique-id-char nil)
2451
2452 ;; If you ever change this function, make sure the new version
2453 ;; cannot generate IDs that the old version could.
2454 ;; You might for example insert a "." somewhere (not next to another dot
2455 ;; or string boundary), or modify the "fsf" string.
2456 (defun message-unique-id ()
2457   ;; Don't use microseconds from (current-time), they may be unsupported.
2458   ;; Instead we use this randomly inited counter.
2459   (setq message-unique-id-char
2460         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2461            ;; (current-time) returns 16-bit ints,
2462            ;; and 2^16*25 just fits into 4 digits i base 36.
2463            (* 25 25)))
2464   (let ((tm (current-time)))
2465     (concat
2466      (if (memq system-type '(ms-dos emx vax-vms))
2467          (let ((user (downcase (user-login-name))))
2468            (while (string-match "[^a-z0-9_]" user)
2469              (aset user (match-beginning 0) ?_))
2470            user)
2471        (message-number-base36 (user-uid) -1))
2472      (message-number-base36 (+ (car   tm)
2473                                (lsh (% message-unique-id-char 25) 16)) 4)
2474      (message-number-base36 (+ (nth 1 tm)
2475                                (lsh (/ message-unique-id-char 25) 16)) 4)
2476      ;; Append the newsreader name, because while the generated
2477      ;; ID is unique to this newsreader, other newsreaders might
2478      ;; otherwise generate the same ID via another algorithm.
2479      ".fsf")))
2480
2481 (defun message-number-base36 (num len)
2482   (if (if (< len 0)
2483           (<= num 0)
2484         (= len 0))
2485       ""
2486     (concat (message-number-base36 (/ num 36) (1- len))
2487             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2488                                   (% num 36))))))
2489
2490 (defun message-make-organization ()
2491   "Make an Organization header."
2492   (let* ((organization
2493           (or (getenv "ORGANIZATION")
2494               (when message-user-organization
2495                 (if (message-functionp message-user-organization)
2496                     (funcall message-user-organization)
2497                   message-user-organization)))))
2498     (save-excursion
2499       (message-set-work-buffer)
2500       (cond ((stringp organization)
2501              (insert organization))
2502             ((and (eq t organization)
2503                   message-user-organization-file
2504                   (file-exists-p message-user-organization-file))
2505              (insert-file-contents message-user-organization-file)))
2506       (goto-char (point-min))
2507       (while (re-search-forward "[\t\n]+" nil t)
2508         (replace-match "" t t))
2509       (unless (zerop (buffer-size))
2510         (buffer-string)))))
2511
2512 (defun message-make-lines ()
2513   "Count the number of lines and return numeric string."
2514   (save-excursion
2515     (save-restriction
2516       (widen)
2517       (goto-char (point-min))
2518       (re-search-forward
2519        (concat "^" (regexp-quote mail-header-separator) "$"))
2520       (forward-line 1)
2521       (int-to-string (count-lines (point) (point-max))))))
2522
2523 (defun message-make-in-reply-to ()
2524   "Return the In-Reply-To header for this message."
2525   (when message-reply-headers
2526     (let ((from (mail-header-from message-reply-headers))
2527           (date (mail-header-date message-reply-headers)))
2528       (when from
2529         (let ((stop-pos
2530                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2531           (concat (if stop-pos (substring from 0 stop-pos) from)
2532                   "'s message of \""
2533                   (if (or (not date) (string= date ""))
2534                       "(unknown date)" date)
2535                   "\""))))))
2536
2537 (defun message-make-distribution ()
2538   "Make a Distribution header."
2539   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2540     (cond ((message-functionp message-distribution-function)
2541            (funcall message-distribution-function))
2542           (t orig-distribution))))
2543
2544 (defun message-make-expires ()
2545   "Return an Expires header based on `message-expires'."
2546   (let ((current (current-time))
2547         (future (* 1.0 message-expires 60 60 24)))
2548     ;; Add the future to current.
2549     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2550     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2551     ;; Return the date in the future in UT.
2552     (timezone-make-date-arpa-standard
2553      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2554
2555 (defun message-make-path ()
2556   "Return uucp path."
2557   (let ((login-name (user-login-name)))
2558     (cond ((null message-user-path)
2559            (concat (system-name) "!" login-name))
2560           ((stringp message-user-path)
2561            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2562            (concat message-user-path "!" login-name))
2563           (t login-name))))
2564
2565 (defun message-make-from ()
2566   "Make a From header."
2567   (let* ((style message-from-style)
2568          (login (message-make-address))
2569          (fullname
2570           (or (and (boundp 'user-full-name)
2571                    user-full-name)
2572               (user-full-name))))
2573     (when (string= fullname "&")
2574       (setq fullname (user-login-name)))
2575     (save-excursion
2576       (message-set-work-buffer)
2577       (cond
2578        ((or (null style)
2579             (equal fullname ""))
2580         (insert login))
2581        ((or (eq style 'angles)
2582             (and (not (eq style 'parens))
2583                  ;; Use angles if no quoting is needed, or if parens would
2584                  ;; need quoting too.
2585                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2586                      (let ((tmp (concat fullname nil)))
2587                        (while (string-match "([^()]*)" tmp)
2588                          (aset tmp (match-beginning 0) ?-)
2589                          (aset tmp (1- (match-end 0)) ?-))
2590                        (string-match "[\\()]" tmp)))))
2591         (insert fullname)
2592         (goto-char (point-min))
2593         ;; Look for a character that cannot appear unquoted
2594         ;; according to RFC 822.
2595         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2596           ;; Quote fullname, escaping specials.
2597           (goto-char (point-min))
2598           (insert "\"")
2599           (while (re-search-forward "[\"\\]" nil 1)
2600             (replace-match "\\\\\\&" t))
2601           (insert "\""))
2602         (insert " <" login ">"))
2603        (t                               ; 'parens or default
2604         (insert login " (")
2605         (let ((fullname-start (point)))
2606           (insert fullname)
2607           (goto-char fullname-start)
2608           ;; RFC 822 says \ and nonmatching parentheses
2609           ;; must be escaped in comments.
2610           ;; Escape every instance of ()\ ...
2611           (while (re-search-forward "[()\\]" nil 1)
2612             (replace-match "\\\\\\&" t))
2613           ;; ... then undo escaping of matching parentheses,
2614           ;; including matching nested parentheses.
2615           (goto-char fullname-start)
2616           (while (re-search-forward
2617                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2618                   nil 1)
2619             (replace-match "\\1(\\3)" t)
2620             (goto-char fullname-start)))
2621         (insert ")")))
2622       (buffer-string))))
2623
2624 (defun message-make-sender ()
2625   "Return the \"real\" user address.
2626 This function tries to ignore all user modifications, and
2627 give as trustworthy answer as possible."
2628   (concat (user-login-name) "@" (system-name)))
2629
2630 (defun message-make-address ()
2631   "Make the address of the user."
2632   (or (message-user-mail-address)
2633       (concat (user-login-name) "@" (message-make-domain))))
2634
2635 (defun message-user-mail-address ()
2636   "Return the pertinent part of `user-mail-address'."
2637   (when user-mail-address
2638     (if (string-match " " user-mail-address)
2639         (nth 1 (mail-extract-address-components user-mail-address))
2640       user-mail-address)))
2641
2642 (defun message-make-fqdn ()
2643   "Return user's fully qualified domain name."
2644   (let ((system-name (system-name))
2645         (user-mail (message-user-mail-address)))
2646     (cond
2647      ((string-match "[^.]\\.[^.]" system-name)
2648       ;; `system-name' returned the right result.
2649       system-name)
2650      ;; Try `mail-host-address'.
2651      ((and (boundp 'mail-host-address)
2652            (stringp mail-host-address)
2653            (string-match "\\." mail-host-address))
2654       mail-host-address)
2655      ;; We try `user-mail-address' as a backup.
2656      ((and (string-match "\\." user-mail)
2657            (string-match "@\\(.*\\)\\'" user-mail))
2658       (match-string 1 user-mail))
2659      ;; Default to this bogus thing.
2660      (t
2661       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2662
2663 (defun message-make-host-name ()
2664   "Return the name of the host."
2665   (let ((fqdn (message-make-fqdn)))
2666     (string-match "^[^.]+\\." fqdn)
2667     (substring fqdn 0 (1- (match-end 0)))))
2668
2669 (defun message-make-domain ()
2670   "Return the domain name."
2671   (or mail-host-address
2672       (message-make-fqdn)))
2673
2674 (defun message-generate-headers (headers)
2675   "Prepare article HEADERS.
2676 Headers already prepared in the buffer are not modified."
2677   (save-restriction
2678     (message-narrow-to-headers)
2679     (let* ((Date (message-make-date))
2680            (Message-ID (message-make-message-id))
2681            (Organization (message-make-organization))
2682            (From (message-make-from))
2683            (Path (message-make-path))
2684            (Subject nil)
2685            (Newsgroups nil)
2686            (In-Reply-To (message-make-in-reply-to))
2687            (To nil)
2688            (Distribution (message-make-distribution))
2689            (Lines (message-make-lines))
2690            (X-Newsreader message-newsreader)
2691            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2692                           message-mailer))
2693            (Expires (message-make-expires))
2694            (case-fold-search t)
2695            header value elem)
2696       ;; First we remove any old generated headers.
2697       (let ((headers message-deletable-headers))
2698         (unless (buffer-modified-p)
2699           (setq headers (delq 'Message-ID (copy-sequence headers))))
2700         (while headers
2701           (goto-char (point-min))
2702           (and (re-search-forward
2703                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2704                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2705                (message-delete-line))
2706           (pop headers)))
2707       ;; Go through all the required headers and see if they are in the
2708       ;; articles already.  If they are not, or are empty, they are
2709       ;; inserted automatically - except for Subject, Newsgroups and
2710       ;; Distribution.
2711       (while headers
2712         (goto-char (point-min))
2713         (setq elem (pop headers))
2714         (if (consp elem)
2715             (if (eq (car elem) 'optional)
2716                 (setq header (cdr elem))
2717               (setq header (car elem)))
2718           (setq header elem))
2719         (when (or (not (re-search-forward
2720                         (concat "^" (downcase (symbol-name header)) ":")
2721                         nil t))
2722                   (progn
2723                     ;; The header was found.  We insert a space after the
2724                     ;; colon, if there is none.
2725                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2726                     ;; Find out whether the header is empty...
2727                     (looking-at "[ \t]*$")))
2728           ;; So we find out what value we should insert.
2729           (setq value
2730                 (cond
2731                  ((and (consp elem) (eq (car elem) 'optional))
2732                   ;; This is an optional header.  If the cdr of this
2733                   ;; is something that is nil, then we do not insert
2734                   ;; this header.
2735                   (setq header (cdr elem))
2736                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2737                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2738                  ((consp elem)
2739                   ;; The element is a cons.  Either the cdr is a
2740                   ;; string to be inserted verbatim, or it is a
2741                   ;; function, and we insert the value returned from
2742                   ;; this function.
2743                   (or (and (stringp (cdr elem)) (cdr elem))
2744                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2745                  ((and (boundp header) (symbol-value header))
2746                   ;; The element is a symbol.  We insert the value
2747                   ;; of this symbol, if any.
2748                   (symbol-value header))
2749                  (t
2750                   ;; We couldn't generate a value for this header,
2751                   ;; so we just ask the user.
2752                   (read-from-minibuffer
2753                    (format "Empty header for %s; enter value: " header)))))
2754           ;; Finally insert the header.
2755           (when (and value
2756                      (not (equal value "")))
2757             (save-excursion
2758               (if (bolp)
2759                   (progn
2760                     ;; This header didn't exist, so we insert it.
2761                     (goto-char (point-max))
2762                     (insert (symbol-name header) ": " value "\n")
2763                     (forward-line -1))
2764                 ;; The value of this header was empty, so we clear
2765                 ;; totally and insert the new value.
2766                 (delete-region (point) (gnus-point-at-eol))
2767                 (insert value))
2768               ;; Add the deletable property to the headers that require it.
2769               (and (memq header message-deletable-headers)
2770                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2771                    (add-text-properties
2772                     (point) (match-end 0)
2773                     '(message-deletable t face italic) (current-buffer)))))))
2774       ;; Insert new Sender if the From is strange.
2775       (let ((from (message-fetch-field "from"))
2776             (sender (message-fetch-field "sender"))
2777             (secure-sender (message-make-sender)))
2778         (when (and from
2779                    (not (message-check-element 'sender))
2780                    (not (string=
2781                          (downcase
2782                           (cadr (mail-extract-address-components from)))
2783                          (downcase secure-sender)))
2784                    (or (null sender)
2785                        (not
2786                         (string=
2787                          (downcase
2788                           (cadr (mail-extract-address-components sender)))
2789                          (downcase secure-sender)))))
2790           (goto-char (point-min))
2791           ;; Rename any old Sender headers to Original-Sender.
2792           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2793             (beginning-of-line)
2794             (insert "Original-")
2795             (beginning-of-line))
2796           (when (or (message-news-p)
2797                     (string-match "^[^@]@.+\\..+" secure-sender))
2798             (insert "Sender: " secure-sender "\n")))))))
2799
2800 (defun message-insert-courtesy-copy ()
2801   "Insert a courtesy message in mail copies of combined messages."
2802   (let (newsgroups)
2803     (save-excursion
2804       (save-restriction
2805         (message-narrow-to-headers)
2806         (when (setq newsgroups (message-fetch-field "newsgroups"))
2807           (goto-char (point-max))
2808           (insert "Posted-To: " newsgroups "\n")))
2809       (forward-line 1)
2810       (when message-courtesy-message
2811         (cond
2812          ((string-match "%s" message-courtesy-message)
2813           (insert (format message-courtesy-message newsgroups)))
2814          (t
2815           (insert message-courtesy-message)))))))
2816
2817 ;;;
2818 ;;; Setting up a message buffer
2819 ;;;
2820
2821 (defun message-fill-address (header value)
2822   (save-restriction
2823     (narrow-to-region (point) (point))
2824     (insert (capitalize (symbol-name header))
2825             ": "
2826             (if (consp value) (car value) value)
2827             "\n")
2828     (narrow-to-region (point-min) (1- (point-max)))
2829     (let (quoted last)
2830       (goto-char (point-min))
2831       (while (not (eobp))
2832         (skip-chars-forward "^,\"" (point-max))
2833         (if (or (= (following-char) ?,)
2834                 (eobp))
2835             (when (not quoted)
2836               (if (and (> (current-column) 78)
2837                        last)
2838                   (progn
2839                     (save-excursion
2840                       (goto-char last)
2841                       (insert "\n\t"))
2842                     (setq last (1+ (point))))
2843                 (setq last (1+ (point)))))
2844           (setq quoted (not quoted)))
2845         (unless (eobp)
2846           (forward-char 1))))
2847     (goto-char (point-max))
2848     (widen)
2849     (forward-line 1)))
2850
2851 (defun message-fill-header (header value)
2852   (let ((begin (point))
2853         (fill-column 78)
2854         (fill-prefix "\t"))
2855     (insert (capitalize (symbol-name header))
2856             ": "
2857             (if (consp value) (car value) value)
2858             "\n")
2859     (save-restriction
2860       (narrow-to-region begin (point))
2861       (fill-region-as-paragraph begin (point))
2862       ;; Tapdance around looong Message-IDs.
2863       (forward-line -1)
2864       (when (looking-at "[ \t]*$")
2865         (message-delete-line))
2866       (goto-char begin)
2867       (re-search-forward ":" nil t)
2868       (when (looking-at "\n[ \t]+")
2869         (replace-match " " t t))
2870       (goto-char (point-max)))))
2871
2872 (defun message-position-point ()
2873   "Move point to where the user probably wants to find it."
2874   (message-narrow-to-headers)
2875   (cond
2876    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2877     (search-backward ":" )
2878     (widen)
2879     (forward-char 1)
2880     (if (= (following-char) ? )
2881         (forward-char 1)
2882       (insert " ")))
2883    (t
2884     (goto-char (point-max))
2885     (widen)
2886     (forward-line 1)
2887     (unless (looking-at "$")
2888       (forward-line 2)))
2889    (sit-for 0)))
2890
2891 (defun message-buffer-name (type &optional to group)
2892   "Return a new (unique) buffer name based on TYPE and TO."
2893   (cond
2894    ;; Check whether `message-generate-new-buffers' is a function,
2895    ;; and if so, call it.
2896    ((message-functionp message-generate-new-buffers)
2897     (funcall message-generate-new-buffers type to group))
2898    ;; Generate a new buffer name The Message Way.
2899    (message-generate-new-buffers
2900     (generate-new-buffer-name
2901      (concat "*" type
2902              (if to
2903                  (concat " to "
2904                          (or (car (mail-extract-address-components to))
2905                              to) "")
2906                "")
2907              (if (and group (not (string= group ""))) (concat " on " group) "")
2908              "*")))
2909    ;; Use standard name.
2910    (t
2911     (format "*%s message*" type))))
2912
2913 (defun message-pop-to-buffer (name)
2914   "Pop to buffer NAME, and warn if it already exists and is modified."
2915   (let ((buffer (get-buffer name)))
2916     (if (and buffer
2917              (buffer-name buffer))
2918         (progn
2919           (set-buffer (pop-to-buffer buffer))
2920           (when (and (buffer-modified-p)
2921                      (not (y-or-n-p
2922                            "Message already being composed; erase? ")))
2923             (error "Message being composed")))
2924       (set-buffer (pop-to-buffer name))))
2925   (erase-buffer)
2926   (message-mode))
2927
2928 (defun message-do-send-housekeeping ()
2929   "Kill old message buffers."
2930   ;; We might have sent this buffer already.  Delete it from the
2931   ;; list of buffers.
2932   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2933   (while (and message-max-buffers
2934               message-buffer-list
2935               (>= (length message-buffer-list) message-max-buffers))
2936     ;; Kill the oldest buffer -- unless it has been changed.
2937     (let ((buffer (pop message-buffer-list)))
2938       (when (and (buffer-name buffer)
2939                  (not (buffer-modified-p buffer)))
2940         (kill-buffer buffer))))
2941   ;; Rename the buffer.
2942   (if message-send-rename-function
2943       (funcall message-send-rename-function)
2944     (when (string-match "\\`\\*" (buffer-name))
2945       (rename-buffer
2946        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2947   ;; Push the current buffer onto the list.
2948   (when message-max-buffers
2949     (setq message-buffer-list
2950           (nconc message-buffer-list (list (current-buffer))))))
2951
2952 (defvar mc-modes-alist)
2953 (defun message-setup (headers &optional replybuffer actions)
2954   (when (and (boundp 'mc-modes-alist)
2955              (not (assq 'message-mode mc-modes-alist)))
2956     (push '(message-mode (encrypt . mc-encrypt-message)
2957                          (sign . mc-sign-message))
2958           mc-modes-alist))
2959   (when actions
2960     (setq message-send-actions actions))
2961   (setq message-reply-buffer replybuffer)
2962   (goto-char (point-min))
2963   ;; Insert all the headers.
2964   (mail-header-format
2965    (let ((h headers)
2966          (alist message-header-format-alist))
2967      (while h
2968        (unless (assq (caar h) message-header-format-alist)
2969          (push (list (caar h)) alist))
2970        (pop h))
2971      alist)
2972    headers)
2973   (delete-region (point) (progn (forward-line -1) (point)))
2974   (when message-default-headers
2975     (insert message-default-headers))
2976   (put-text-property
2977    (point)
2978    (progn
2979      (insert mail-header-separator "\n")
2980      (1- (point)))
2981    'read-only nil)
2982   (forward-line -1)
2983   (when (message-news-p)
2984     (when message-default-news-headers
2985       (insert message-default-news-headers))
2986     (when message-generate-headers-first
2987       (message-generate-headers
2988        (delq 'Lines
2989              (delq 'Subject
2990                    (copy-sequence message-required-news-headers))))))
2991   (when (message-mail-p)
2992     (when message-default-mail-headers
2993       (insert message-default-mail-headers))
2994     (when message-generate-headers-first
2995       (message-generate-headers
2996        (delq 'Lines
2997              (delq 'Subject
2998                    (copy-sequence message-required-mail-headers))))))
2999   (run-hooks 'message-signature-setup-hook)
3000   (message-insert-signature)
3001   (message-set-auto-save-file-name)
3002   (save-restriction
3003     (message-narrow-to-headers)
3004     (run-hooks 'message-header-setup-hook))
3005   (set-buffer-modified-p nil)
3006   (setq buffer-undo-list nil)
3007   (run-hooks 'message-setup-hook)
3008   (message-position-point)
3009   (undo-boundary))
3010
3011 (defun message-set-auto-save-file-name ()
3012   "Associate the message buffer with a file in the drafts directory."
3013   (when message-autosave-directory
3014     (unless (file-exists-p message-autosave-directory)
3015       (make-directory message-autosave-directory t))
3016     (let ((name (make-temp-name
3017                  (expand-file-name
3018                   (concat (file-name-as-directory message-autosave-directory)
3019                           "msg."
3020                           (nnheader-replace-chars-in-string
3021                            (nnheader-replace-chars-in-string
3022                             (buffer-name) ?* ?.)
3023                            ?/ ?-))))))
3024       (setq buffer-auto-save-file-name
3025             (save-excursion
3026               (prog1
3027                   (progn
3028                     (set-buffer (get-buffer-create " *draft tmp*"))
3029                     (setq buffer-file-name name)
3030                     (make-auto-save-file-name))
3031                 (kill-buffer (current-buffer)))))
3032       (clear-visited-file-modtime))))
3033
3034 \f
3035
3036 ;;;
3037 ;;; Commands for interfacing with message
3038 ;;;
3039
3040 ;;;###autoload
3041 (defun message-mail (&optional to subject
3042                                other-headers continue switch-function
3043                                yank-action send-actions)
3044   "Start editing a mail message to be sent."
3045   (interactive)
3046   (let ((message-this-is-mail t))
3047     (message-pop-to-buffer (message-buffer-name "mail" to))
3048     (message-setup
3049      (nconc
3050       `((To . ,(or to "")) (Subject . ,(or subject "")))
3051       (when other-headers other-headers)))))
3052
3053 ;;;###autoload
3054 (defun message-news (&optional newsgroups subject)
3055   "Start editing a news article to be sent."
3056   (interactive)
3057   (let ((message-this-is-news t))
3058     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3059     (message-setup `((Newsgroups . ,(or newsgroups ""))
3060                      (Subject . ,(or subject ""))))))
3061
3062 ;;;###autoload
3063 (defun message-reply (&optional to-address wide ignore-reply-to)
3064   "Start editing a reply to the article in the current buffer."
3065   (interactive)
3066   (let ((cur (current-buffer))
3067         from subject date reply-to to cc
3068         references message-id follow-to
3069         (inhibit-point-motion-hooks t)
3070         mct never-mct gnus-warning)
3071     (save-restriction
3072       (message-narrow-to-head)
3073       ;; Allow customizations to have their say.
3074       (if (not wide)
3075           ;; This is a regular reply.
3076           (if (message-functionp message-reply-to-function)
3077               (setq follow-to (funcall message-reply-to-function)))
3078         ;; This is a followup.
3079         (if (message-functionp message-wide-reply-to-function)
3080             (save-excursion
3081               (setq follow-to
3082                     (funcall message-wide-reply-to-function)))))
3083       ;; Find all relevant headers we need.
3084       (setq from (message-fetch-field "from")
3085             date (message-fetch-field "date")
3086             subject (or (message-fetch-field "subject") "none")
3087             to (message-fetch-field "to")
3088             cc (message-fetch-field "cc")
3089             mct (message-fetch-field "mail-copies-to")
3090             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
3091             references (message-fetch-field "references")
3092             message-id (message-fetch-field "message-id" t))
3093       ;; Remove any (buggy) Re:'s that are present and make a
3094       ;; proper one.
3095       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3096         (setq subject (substring subject (match-end 0))))
3097       (setq subject (concat "Re: " subject))
3098
3099       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3100                  (string-match "<[^>]+>" gnus-warning))
3101         (setq message-id (match-string 0 gnus-warning)))
3102
3103       ;; Handle special values of Mail-Copies-To.
3104       (when mct
3105         (cond ((equal (downcase mct) "never")
3106                (setq never-mct t)
3107                (setq mct nil))
3108               ((equal (downcase mct) "always")
3109                (setq mct (or reply-to from)))))
3110
3111       (unless follow-to
3112         (if (or (not wide)
3113                 to-address)
3114             (setq follow-to (list (cons 'To (or to-address reply-to from))))
3115           (let (ccalist)
3116             (save-excursion
3117               (message-set-work-buffer)
3118               (unless never-mct
3119                 (insert (or reply-to from "")))
3120               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3121               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3122               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3123               (goto-char (point-min))
3124               (while (re-search-forward "[ \t]+" nil t)
3125                 (replace-match " " t t))
3126               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3127               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3128                         (erase-buffer)))
3129               (goto-char (point-min))
3130               ;; Perhaps Mail-Copies-To: never removed the only address?
3131               (when (eobp)
3132                 (insert (or reply-to from "")))
3133               (setq ccalist
3134                     (mapcar
3135                      (lambda (addr)
3136                        (cons (mail-strip-quoted-names addr) addr))
3137                      (message-tokenize-header (buffer-string))))
3138               (let ((s ccalist))
3139                 (while s
3140                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3141             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3142             (when ccalist
3143               (let ((ccs (cons 'Cc (mapconcat
3144                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3145                 (when (string-match "^ +" (cdr ccs))
3146                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3147                 (push ccs follow-to))))))
3148       (widen))
3149
3150     (message-pop-to-buffer (message-buffer-name
3151                             (if wide "wide reply" "reply") from
3152                             (if wide to-address nil)))
3153
3154     (setq message-reply-headers
3155           (vector 0 subject from date message-id references 0 0 ""))
3156
3157     (message-setup
3158      `((Subject . ,subject)
3159        ,@follow-to
3160        ,@(if (or references message-id)
3161              `((References . ,(concat (or references "") (and references " ")
3162                                       (or message-id ""))))
3163            nil))
3164      cur)))
3165
3166 ;;;###autoload
3167 (defun message-wide-reply (&optional to-address ignore-reply-to)
3168   "Make a \"wide\" reply to the message in the current buffer."
3169   (interactive)
3170   (message-reply to-address t ignore-reply-to))
3171
3172 ;;;###autoload
3173 (defun message-followup (&optional to-newsgroups)
3174   "Follow up to the message in the current buffer.
3175 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3176   (interactive)
3177   (let ((cur (current-buffer))
3178         from subject date reply-to mct
3179         references message-id follow-to
3180         (inhibit-point-motion-hooks t)
3181         (message-this-is-news t)
3182         followup-to distribution newsgroups gnus-warning posted-to)
3183     (save-restriction
3184       (narrow-to-region
3185        (goto-char (point-min))
3186        (if (search-forward "\n\n" nil t)
3187            (1- (point))
3188          (point-max)))
3189       (when (message-functionp message-followup-to-function)
3190         (setq follow-to
3191               (funcall message-followup-to-function)))
3192       (setq from (message-fetch-field "from")
3193             date (message-fetch-field "date")
3194             subject (or (message-fetch-field "subject") "none")
3195             references (message-fetch-field "references")
3196             message-id (message-fetch-field "message-id" t)
3197             followup-to (message-fetch-field "followup-to")
3198             newsgroups (message-fetch-field "newsgroups")
3199             posted-to (message-fetch-field "posted-to")
3200             reply-to (message-fetch-field "reply-to")
3201             distribution (message-fetch-field "distribution")
3202             mct (message-fetch-field "mail-copies-to"))
3203       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3204                  (string-match "<[^>]+>" gnus-warning))
3205         (setq message-id (match-string 0 gnus-warning)))
3206       ;; Remove bogus distribution.
3207       (when (and (stringp distribution)
3208                  (let ((case-fold-search t))
3209                    (string-match "world" distribution)))
3210         (setq distribution nil))
3211       ;; Remove any (buggy) Re:'s that are present and make a
3212       ;; proper one.
3213       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3214         (setq subject (substring subject (match-end 0))))
3215       (setq subject (concat "Re: " subject))
3216       (widen))
3217
3218     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3219
3220     (message-setup
3221      `((Subject . ,subject)
3222        ,@(cond
3223           (to-newsgroups
3224            (list (cons 'Newsgroups to-newsgroups)))
3225           (follow-to follow-to)
3226           ((and followup-to message-use-followup-to)
3227            (list
3228             (cond
3229              ((equal (downcase followup-to) "poster")
3230               (if (or (eq message-use-followup-to 'use)
3231                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3232 You should normally obey the Followup-To: header.
3233
3234 `Followup-To: poster' sends your response via e-mail instead of news.
3235
3236 A typical situation where `Followup-To: poster' is used is when the poster
3237 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3238                   (progn
3239                     (setq message-this-is-news nil)
3240                     (cons 'To (or reply-to from "")))
3241                 (cons 'Newsgroups newsgroups)))
3242              (t
3243               (if (or (equal followup-to newsgroups)
3244                       (not (eq message-use-followup-to 'ask))
3245                       (message-y-or-n-p
3246                        (concat "Obey Followup-To: " followup-to "? ") t "\
3247 You should normally obey the Followup-To: header.
3248
3249         `Followup-To: " followup-to "'
3250 directs your response to " (if (string-match "," followup-to)
3251                                "the specified newsgroups"
3252                              "that newsgroup only") ".
3253
3254 If a message is posted to several newsgroups, Followup-To is often
3255 used to direct the following discussion to one newsgroup only,
3256 because discussions that are spread over several newsgroup tend to
3257 be fragmented and very difficult to follow.
3258
3259 Also, some source/announcement newsgroups are not indented for discussion;
3260 responses here are directed to other newsgroups."))
3261                   (cons 'Newsgroups followup-to)
3262                 (cons 'Newsgroups newsgroups))))))
3263           (posted-to
3264            `((Newsgroups . ,posted-to)))
3265           (t
3266            `((Newsgroups . ,newsgroups))))
3267        ,@(and distribution (list (cons 'Distribution distribution)))
3268        ,@(if (or references message-id)
3269              `((References . ,(concat (or references "") (and references " ")
3270                                       (or message-id "")))))
3271        ,@(when (and mct
3272                     (not (equal (downcase mct) "never")))
3273            (list (cons 'Cc (if (equal (downcase mct) "always")
3274                                (or reply-to from "")
3275                              mct)))))
3276
3277      cur)
3278
3279     (setq message-reply-headers
3280           (vector 0 subject from date message-id references 0 0 ""))))
3281
3282
3283 ;;;###autoload
3284 (defun message-cancel-news ()
3285   "Cancel an article you posted."
3286   (interactive)
3287   (unless (message-news-p)
3288     (error "This is not a news article; canceling is impossible"))
3289   (when (yes-or-no-p "Do you really want to cancel this article? ")
3290     (let (from newsgroups message-id distribution buf)
3291       (save-excursion
3292         ;; Get header info. from original article.
3293         (save-restriction
3294           (message-narrow-to-head)
3295           (setq from (message-fetch-field "from")
3296                 newsgroups (message-fetch-field "newsgroups")
3297                 message-id (message-fetch-field "message-id" t)
3298                 distribution (message-fetch-field "distribution")))
3299         ;; Make sure that this article was written by the user.
3300         (unless (string-equal
3301                  (downcase (cadr (mail-extract-address-components from)))
3302                  (downcase (message-make-address)))
3303           (error "This article is not yours"))
3304         ;; Make control message.
3305         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3306         (buffer-disable-undo (current-buffer))
3307         (erase-buffer)
3308         (insert "Newsgroups: " newsgroups "\n"
3309                 "From: " (message-make-from) "\n"
3310                 "Subject: cmsg cancel " message-id "\n"
3311                 "Control: cancel " message-id "\n"
3312                 (if distribution
3313                     (concat "Distribution: " distribution "\n")
3314                   "")
3315                 mail-header-separator "\n"
3316                 message-cancel-message)
3317         (message "Canceling your article...")
3318         (if (let ((message-syntax-checks
3319                    'dont-check-for-anything-just-trust-me))
3320               (funcall message-send-news-function))
3321             (message "Canceling your article...done"))
3322         (kill-buffer buf)))))
3323
3324 ;;;###autoload
3325 (defun message-supersede ()
3326   "Start composing a message to supersede the current message.
3327 This is done simply by taking the old article and adding a Supersedes
3328 header line with the old Message-ID."
3329   (interactive)
3330   (let ((cur (current-buffer)))
3331     ;; Check whether the user owns the article that is to be superseded.
3332     (unless (string-equal
3333              (downcase (cadr (mail-extract-address-components
3334                               (message-fetch-field "from"))))
3335              (downcase (message-make-address)))
3336       (error "This article is not yours"))
3337     ;; Get a normal message buffer.
3338     (message-pop-to-buffer (message-buffer-name "supersede"))
3339     (insert-buffer-substring cur)
3340     (message-narrow-to-head)
3341     ;; Remove unwanted headers.
3342     (when message-ignored-supersedes-headers
3343       (message-remove-header message-ignored-supersedes-headers t))
3344     (goto-char (point-min))
3345     (if (not (re-search-forward "^Message-ID: " nil t))
3346         (error "No Message-ID in this article")
3347       (replace-match "Supersedes: " t t))
3348     (goto-char (point-max))
3349     (insert mail-header-separator)
3350     (widen)
3351     (forward-line 1)))
3352
3353 ;;;###autoload
3354 (defun message-recover ()
3355   "Reread contents of current buffer from its last auto-save file."
3356   (interactive)
3357   (let ((file-name (make-auto-save-file-name)))
3358     (cond ((save-window-excursion
3359              (if (not (eq system-type 'vax-vms))
3360                  (with-output-to-temp-buffer "*Directory*"
3361                    (buffer-disable-undo standard-output)
3362                    (let ((default-directory "/"))
3363                      (call-process
3364                       "ls" nil standard-output nil "-l" file-name))))
3365              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3366            (let ((buffer-read-only nil))
3367              (erase-buffer)
3368              (insert-file-contents file-name nil)))
3369           (t (error "message-recover cancelled")))))
3370
3371 ;;; Forwarding messages.
3372
3373 (defun message-make-forward-subject ()
3374   "Return a Subject header suitable for the message in the current buffer."
3375   (save-excursion
3376     (save-restriction
3377       (current-buffer)
3378       (message-narrow-to-head)
3379       (concat "[" (or (message-fetch-field
3380                        (if (message-news-p) "newsgroups" "from"))
3381                       "(nowhere)")
3382               "] " (or (message-fetch-field "Subject") "")))))
3383
3384 ;;;###autoload
3385 (defun message-forward (&optional news)
3386   "Forward the current message via mail.
3387 Optional NEWS will use news to forward instead of mail."
3388   (interactive "P")
3389   (let ((cur (current-buffer))
3390         (subject (message-make-forward-subject))
3391         art-beg)
3392     (if news (message-news nil subject) (message-mail nil subject))
3393     ;; Put point where we want it before inserting the forwarded
3394     ;; message.
3395     (if message-signature-before-forwarded-message
3396         (goto-char (point-max))
3397       (message-goto-body))
3398     ;; Make sure we're at the start of the line.
3399     (unless (eolp)
3400       (insert "\n"))
3401     ;; Narrow to the area we are to insert.
3402     (narrow-to-region (point) (point))
3403     ;; Insert the separators and the forwarded buffer.
3404     (insert message-forward-start-separator)
3405     (setq art-beg (point))
3406     (insert-buffer-substring cur)
3407     (goto-char (point-max))
3408     (insert message-forward-end-separator)
3409     (set-text-properties (point-min) (point-max) nil)
3410     ;; Remove all unwanted headers.
3411     (goto-char art-beg)
3412     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3413                                   (1- (point))
3414                                 (point)))
3415     (goto-char (point-min))
3416     (message-remove-header message-included-forward-headers t nil t)
3417     (widen)
3418     (message-position-point)))
3419
3420 ;;;###autoload
3421 (defun message-resend (address)
3422   "Resend the current article to ADDRESS."
3423   (interactive "sResend message to: ")
3424   (message "Resending message to %s..." address)
3425   (save-excursion
3426     (let ((cur (current-buffer))
3427           beg)
3428       ;; We first set up a normal mail buffer.
3429       (set-buffer (get-buffer-create " *message resend*"))
3430       (buffer-disable-undo (current-buffer))
3431       (erase-buffer)
3432       (message-setup `((To . ,address)))
3433       ;; Insert our usual headers.
3434       (message-generate-headers '(From Date To))
3435       (message-narrow-to-headers)
3436       ;; Rename them all to "Resent-*".
3437       (while (re-search-forward "^[A-Za-z]" nil t)
3438         (forward-char -1)
3439         (insert "Resent-"))
3440       (widen)
3441       (forward-line)
3442       (delete-region (point) (point-max))
3443       (setq beg (point))
3444       ;; Insert the message to be resent.
3445       (insert-buffer-substring cur)
3446       (goto-char (point-min))
3447       (search-forward "\n\n")
3448       (forward-char -1)
3449       (save-restriction
3450         (narrow-to-region beg (point))
3451         (message-remove-header message-ignored-resent-headers t)
3452         (goto-char (point-max)))
3453       (insert mail-header-separator)
3454       ;; Rename all old ("Also-")Resent headers.
3455       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
3456         (beginning-of-line)
3457         (insert "Also-"))
3458       ;; Quote any "From " lines at the beginning.
3459       (goto-char beg)
3460       (when (looking-at "From ")
3461         (replace-match "X-From-Line: "))
3462       ;; Send it.
3463       (message-send-mail)
3464       (kill-buffer (current-buffer)))
3465     (message "Resending message to %s...done" address)))
3466
3467 ;;;###autoload
3468 (defun message-bounce ()
3469   "Re-mail the current message.
3470 This only makes sense if the current message is a bounce message than
3471 contains some mail you have written which has been bounced back to
3472 you."
3473   (interactive)
3474   (let ((cur (current-buffer))
3475         boundary)
3476     (message-pop-to-buffer (message-buffer-name "bounce"))
3477     (insert-buffer-substring cur)
3478     (undo-boundary)
3479     (message-narrow-to-head)
3480     (if (and (message-fetch-field "Mime-Version")
3481              (setq boundary (message-fetch-field "Content-Type")))
3482         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3483             (setq boundary (concat (match-string 1 boundary) " *\n"
3484                                    "Content-Type: message/rfc822"))
3485           (setq boundary nil)))
3486     (widen)
3487     (goto-char (point-min))
3488     (search-forward "\n\n" nil t)
3489     (or (and boundary
3490              (re-search-forward boundary nil t)
3491              (forward-line 2))
3492         (and (re-search-forward message-unsent-separator nil t)
3493              (forward-line 1))
3494         (re-search-forward "^Return-Path:.*\n" nil t))
3495     ;; We remove everything before the bounced mail.
3496     (delete-region
3497      (point-min)
3498      (if (re-search-forward "^[^ \n\t]+:" nil t)
3499          (match-beginning 0)
3500        (point)))
3501     (save-restriction
3502       (message-narrow-to-head)
3503       (message-remove-header message-ignored-bounced-headers t)
3504       (goto-char (point-max))
3505       (insert mail-header-separator))
3506     (message-position-point)))
3507
3508 ;;;
3509 ;;; Interactive entry points for new message buffers.
3510 ;;;
3511
3512 ;;;###autoload
3513 (defun message-mail-other-window (&optional to subject)
3514   "Like `message-mail' command, but display mail buffer in another window."
3515   (interactive)
3516   (let ((pop-up-windows t)
3517         (special-display-buffer-names nil)
3518         (special-display-regexps nil)
3519         (same-window-buffer-names nil)
3520         (same-window-regexps nil))
3521     (message-pop-to-buffer (message-buffer-name "mail" to)))
3522   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3523
3524 ;;;###autoload
3525 (defun message-mail-other-frame (&optional to subject)
3526   "Like `message-mail' command, but display mail buffer in another frame."
3527   (interactive)
3528   (let ((pop-up-frames t)
3529         (special-display-buffer-names nil)
3530         (special-display-regexps nil)
3531         (same-window-buffer-names nil)
3532         (same-window-regexps nil))
3533     (message-pop-to-buffer (message-buffer-name "mail" to)))
3534   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3535
3536 ;;;###autoload
3537 (defun message-news-other-window (&optional newsgroups subject)
3538   "Start editing a news article to be sent."
3539   (interactive)
3540   (let ((pop-up-windows t)
3541         (special-display-buffer-names nil)
3542         (special-display-regexps nil)
3543         (same-window-buffer-names nil)
3544         (same-window-regexps nil))
3545     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3546   (message-setup `((Newsgroups . ,(or newsgroups ""))
3547                    (Subject . ,(or subject "")))))
3548
3549 ;;;###autoload
3550 (defun message-news-other-frame (&optional newsgroups subject)
3551   "Start editing a news article to be sent."
3552   (interactive)
3553   (let ((pop-up-frames t)
3554         (special-display-buffer-names nil)
3555         (special-display-regexps nil)
3556         (same-window-buffer-names nil)
3557         (same-window-regexps nil))
3558     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3559   (message-setup `((Newsgroups . ,(or newsgroups ""))
3560                    (Subject . ,(or subject "")))))
3561
3562 ;;; underline.el
3563
3564 ;; This code should be moved to underline.el (from which it is stolen).
3565
3566 ;;;###autoload
3567 (defun bold-region (start end)
3568   "Bold all nonblank characters in the region.
3569 Works by overstriking characters.
3570 Called from program, takes two arguments START and END
3571 which specify the range to operate on."
3572   (interactive "r")
3573   (save-excursion
3574     (let ((end1 (make-marker)))
3575       (move-marker end1 (max start end))
3576       (goto-char (min start end))
3577       (while (< (point) end1)
3578         (or (looking-at "[_\^@- ]")
3579             (insert (following-char) "\b"))
3580         (forward-char 1)))))
3581
3582 ;;;###autoload
3583 (defun unbold-region (start end)
3584   "Remove all boldness (overstruck characters) in the region.
3585 Called from program, takes two arguments START and END
3586 which specify the range to operate on."
3587   (interactive "r")
3588   (save-excursion
3589     (let ((end1 (make-marker)))
3590       (move-marker end1 (max start end))
3591       (goto-char (min start end))
3592       (while (re-search-forward "\b" end1 t)
3593         (if (eq (following-char) (char-after (- (point) 2)))
3594             (delete-char -2))))))
3595
3596 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3597
3598 ;; Support for toolbar
3599 (when (string-match "XEmacs\\|Lucid" emacs-version)
3600   (require 'messagexmas))
3601
3602 ;;; Group name completion.
3603
3604 (defvar message-newgroups-header-regexp
3605   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
3606   "Regexp that match headers that lists groups.")
3607
3608 (defun message-tab ()
3609   "Expand group names in Newsgroups and Followup-To headers.
3610 Do a `tab-to-tab-stop' if not in those headers."
3611   (interactive)
3612   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3613         (mail-abbrev-in-expansion-header-p))
3614       (message-expand-group)
3615     (tab-to-tab-stop)))
3616
3617 (defvar gnus-active-hashtb)
3618 (defun message-expand-group ()
3619   (let* ((b (save-excursion
3620               (save-restriction
3621                 (narrow-to-region
3622                  (save-excursion
3623                    (beginning-of-line)
3624                    (skip-chars-forward "^:")
3625                    (1+ (point)))
3626                  (point))
3627                 (skip-chars-backward "^, \t\n") (point))))
3628          (completion-ignore-case t)
3629          (string (buffer-substring b (point)))
3630          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3631          (completions (all-completions string hashtb))
3632          (cur (current-buffer))
3633          comp)
3634     (delete-region b (point))
3635     (cond
3636      ((= (length completions) 1)
3637       (if (string= (car completions) string)
3638           (progn
3639             (insert string)
3640             (message "Only matching group"))
3641         (insert (car completions))))
3642      ((and (setq comp (try-completion string hashtb))
3643            (not (string= comp string)))
3644       (insert comp))
3645      (t
3646       (insert string)
3647       (if (not comp)
3648           (message "No matching groups")
3649         (save-selected-window
3650           (pop-to-buffer "*Completions*")
3651           (buffer-disable-undo (current-buffer))
3652           (let ((buffer-read-only nil))
3653             (erase-buffer)
3654             (let ((standard-output (current-buffer)))
3655               (display-completion-list (sort completions 'string<)))
3656             (goto-char (point-min))
3657             (delete-region (point) (progn (forward-line 3) (point))))))))))
3658
3659 ;;; Help stuff.
3660
3661 (defun message-talkative-question (ask question show &rest text)
3662   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
3663 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
3664 The following arguments may contain lists of values."
3665   (if (and show
3666            (setq text (message-flatten-list text)))
3667       (save-window-excursion
3668         (save-excursion
3669           (with-output-to-temp-buffer " *MESSAGE information message*"
3670             (set-buffer " *MESSAGE information message*")
3671             (mapcar 'princ text)
3672             (goto-char (point-min))))
3673         (funcall ask question))
3674     (funcall ask question)))
3675
3676 (defun message-flatten-list (list)
3677   "Return a new, flat list that contains all elements of LIST.
3678
3679 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3680 => (1 2 3 4 5 6 7)"
3681   (cond ((consp list)
3682          (apply 'append (mapcar 'message-flatten-list list)))
3683         (list
3684          (list list))))
3685
3686 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3687   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3688 Then clone the local variables and values from the old buffer to the
3689 new one, cloning only the locals having a substring matching the
3690 regexp varstr."
3691   (let ((oldbuf (current-buffer)))
3692     (save-excursion
3693       (set-buffer (generate-new-buffer name))
3694       (message-clone-locals oldbuf)
3695       (current-buffer))))
3696
3697 (defun message-clone-locals (buffer)
3698   "Clone the local variables from BUFFER to the current buffer."
3699   (let ((locals (save-excursion
3700                   (set-buffer buffer)
3701                   (buffer-local-variables)))
3702         (regexp "^gnus\\|^nn\\|^message"))
3703     (mapcar
3704      (lambda (local)
3705        (when (and (car local)
3706                   (string-match regexp (symbol-name (car local))))
3707          (ignore-errors
3708            (set (make-local-variable (car local))
3709                 (cdr local)))))
3710      locals)))
3711
3712 (run-hooks 'message-load-hook)
3713
3714 (provide 'message)
3715
3716 ;;; message.el ends here