*** 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   (nnheader-concat 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 (defvar message-draft-article nil)
809
810 ;; Byte-compiler warning
811 (defvar gnus-active-hashtb)
812 (defvar gnus-read-active-file)
813
814 ;;; Regexp matching the delimiter of messages in UNIX mail format
815 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
816 ;;; of rmail.el's rmail-unix-mail-delimiter.
817 (defvar message-unix-mail-delimiter
818   (let ((time-zone-regexp
819          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
820                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
821                  "\\|"
822                  "\\) *")))
823     (concat
824      "From "
825
826      ;; Many things can happen to an RFC 822 mailbox before it is put into
827      ;; a `From' line.  The leading phrase can be stripped, e.g.
828      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
829      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
830      ;; can be removed, e.g.
831      ;;         From: joe@y.z (Joe      K
832      ;;                 User)
833      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
834      ;;         From: Joe User
835      ;;                 <joe@y.z>
836      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
837      ;; The mailbox can be removed or be replaced by white space, e.g.
838      ;;         From: "Joe User"{space}{tab}
839      ;;                 <joe@y.z>
840      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
841      ;; where {space} and {tab} represent the Ascii space and tab characters.
842      ;; We want to match the results of any of these manglings.
843      ;; The following regexp rejects names whose first characters are
844      ;; obviously bogus, but after that anything goes.
845      "\\([^\0-\b\n-\r\^?].*\\)? "
846
847      ;; The time the message was sent.
848      "\\([^\0-\r \^?]+\\) +"                            ; day of the week
849      "\\([^\0-\r \^?]+\\) +"                            ; month
850      "\\([0-3]?[0-9]\\) +"                              ; day of month
851      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"  ; time of day
852
853      ;; Perhaps a time zone, specified by an abbreviation, or by a
854      ;; numeric offset.
855      time-zone-regexp
856
857      ;; The year.
858      " \\([0-9][0-9]+\\) *"
859
860      ;; On some systems the time zone can appear after the year, too.
861      time-zone-regexp
862
863      ;; Old uucp cruft.
864      "\\(remote from .*\\)?"
865
866      "\n"))
867   "Regexp matching the delimiter of messages in UNIX mail format.")
868
869 (defvar message-unsent-separator
870   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
871           "^ *---+ +Returned message +---+ *$\\|"
872           "^Start of returned message$\\|"
873           "^ *---+ +Original message +---+ *$\\|"
874           "^ *--+ +begin message +--+ *$\\|"
875           "^ *---+ +Original message follows +---+ *$\\|"
876           "^|? *---+ +Message text follows: +---+ *|?$")
877   "A regexp that matches the separator before the text of a failed message.")
878
879 (defvar message-header-format-alist
880   `((Newsgroups)
881     (To . message-fill-address)
882     (Cc . message-fill-address)
883     (Subject)
884     (In-Reply-To)
885     (Fcc)
886     (Bcc)
887     (Date)
888     (Organization)
889     (Distribution)
890     (Lines)
891     (Expires)
892     (Message-ID)
893     (References)
894     (X-Mailer)
895     (X-Newsreader))
896   "Alist used for formatting headers.")
897
898 (eval-and-compile
899   (autoload 'message-setup-toolbar "messagexmas")
900   (autoload 'mh-send-letter "mh-comp")
901   (autoload 'gnus-point-at-eol "gnus-util")
902   (autoload 'gnus-point-at-bol "gnus-util")
903   (autoload 'gnus-output-to-mail "gnus-util")
904   (autoload 'gnus-output-to-rmail "gnus-util")
905   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev"))
906
907 \f
908
909 ;;;
910 ;;; Utility functions.
911 ;;;
912
913 (defmacro message-y-or-n-p (question show &rest text)
914   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
915   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
916
917 ;; Delete the current line (and the next N lines.);
918 (defmacro message-delete-line (&optional n)
919   `(delete-region (progn (beginning-of-line) (point))
920                   (progn (forward-line ,(or n 1)) (point))))
921
922 (defun message-tokenize-header (header &optional separator)
923   "Split HEADER into a list of header elements.
924 \",\" is used as the separator."
925   (if (not header)
926       nil
927     (let ((regexp (format "[%s]+" (or separator ",")))
928           (beg 1)
929           (first t)
930           quoted elems paren)
931       (save-excursion
932         (message-set-work-buffer)
933         (insert header)
934         (goto-char (point-min))
935         (while (not (eobp))
936           (if first
937               (setq first nil)
938             (forward-char 1))
939           (cond ((and (> (point) beg)
940                       (or (eobp)
941                           (and (looking-at regexp)
942                                (not quoted)
943                                (not paren))))
944                  (push (buffer-substring beg (point)) elems)
945                  (setq beg (match-end 0)))
946                 ((= (following-char) ?\")
947                  (setq quoted (not quoted)))
948                 ((and (= (following-char) ?\()
949                       (not quoted))
950                  (setq paren t))
951                 ((and (= (following-char) ?\))
952                       (not quoted))
953                  (setq paren nil))))
954         (nreverse elems)))))
955
956 (defun message-mail-file-mbox-p (file)
957   "Say whether FILE looks like a Unix mbox file."
958   (when (and (file-exists-p file)
959              (file-readable-p file)
960              (file-regular-p file))
961     (nnheader-temp-write nil
962       (nnheader-insert-file-contents file)
963       (goto-char (point-min))
964       (looking-at message-unix-mail-delimiter))))
965
966 (defun message-fetch-field (header &optional not-all)
967   "The same as `mail-fetch-field', only remove all newlines."
968   (let ((value (mail-fetch-field header nil (not not-all))))
969     (when value
970       (nnheader-replace-chars-in-string value ?\n ? ))))
971
972 (defun message-add-header (&rest headers)
973   "Add the HEADERS to the message header, skipping those already present."
974   (while headers
975     (let (hclean)
976       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
977         (error "Invalid header `%s'" (car headers)))
978       (setq hclean (match-string 1 (car headers)))
979     (save-restriction
980       (message-narrow-to-headers)
981       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
982         (insert (car headers) ?\n))))
983     (setq headers (cdr headers))))
984
985 (defun message-fetch-reply-field (header)
986   "Fetch FIELD from the message we're replying to."
987   (when (and message-reply-buffer
988              (buffer-name message-reply-buffer))
989     (save-excursion
990       (set-buffer message-reply-buffer)
991       (message-fetch-field header))))
992
993 (defun message-set-work-buffer ()
994   (if (get-buffer " *message work*")
995       (progn
996         (set-buffer " *message work*")
997         (erase-buffer))
998     (set-buffer (get-buffer-create " *message work*"))
999     (kill-all-local-variables)
1000     (buffer-disable-undo (current-buffer))))
1001
1002 (defun message-functionp (form)
1003   "Return non-nil if FORM is funcallable."
1004   (or (and (symbolp form) (fboundp form))
1005       (and (listp form) (eq (car form) 'lambda))
1006       (compiled-function-p form)))
1007
1008 (defun message-strip-subject-re (subject)
1009   "Remove \"Re:\" from subject lines."
1010   (if (string-match "^[Rr][Ee]: *" subject)
1011       (substring subject (match-end 0))
1012     subject))
1013
1014 (defun message-remove-header (header &optional is-regexp first reverse)
1015   "Remove HEADER in the narrowed buffer.
1016 If REGEXP, HEADER is a regular expression.
1017 If FIRST, only remove the first instance of the header.
1018 Return the number of headers removed."
1019   (goto-char (point-min))
1020   (let ((regexp (if is-regexp header (concat "^" header ":")))
1021         (number 0)
1022         (case-fold-search t)
1023         last)
1024     (while (and (not (eobp))
1025                 (not last))
1026       (if (if reverse
1027               (not (looking-at regexp))
1028             (looking-at regexp))
1029           (progn
1030             (incf number)
1031             (when first
1032               (setq last t))
1033             (delete-region
1034              (point)
1035              ;; There might be a continuation header, so we have to search
1036              ;; until we find a new non-continuation line.
1037              (progn
1038                (forward-line 1)
1039                (if (re-search-forward "^[^ \t]" nil t)
1040                    (goto-char (match-beginning 0))
1041                  (point-max)))))
1042         (forward-line 1)
1043         (if (re-search-forward "^[^ \t]" nil t)
1044             (goto-char (match-beginning 0))
1045           (point-max))))
1046     number))
1047
1048 (defun message-narrow-to-headers ()
1049   "Narrow the buffer to the head of the message."
1050   (widen)
1051   (narrow-to-region
1052    (goto-char (point-min))
1053    (if (re-search-forward
1054         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1055        (match-beginning 0)
1056      (point-max)))
1057   (goto-char (point-min)))
1058
1059 (defun message-narrow-to-head ()
1060   "Narrow the buffer to the head of the message."
1061   (widen)
1062   (narrow-to-region
1063    (goto-char (point-min))
1064    (if (search-forward "\n\n" nil 1)
1065        (1- (point))
1066      (point-max)))
1067   (goto-char (point-min)))
1068
1069 (defun message-news-p ()
1070   "Say whether the current buffer contains a news message."
1071   (or message-this-is-news
1072       (save-excursion
1073         (save-restriction
1074           (message-narrow-to-headers)
1075           (message-fetch-field "newsgroups")))))
1076
1077 (defun message-mail-p ()
1078   "Say whether the current buffer contains a mail message."
1079   (or message-this-is-mail
1080       (save-excursion
1081         (save-restriction
1082           (message-narrow-to-headers)
1083           (or (message-fetch-field "to")
1084               (message-fetch-field "cc")
1085               (message-fetch-field "bcc"))))))
1086
1087 (defun message-next-header ()
1088   "Go to the beginning of the next header."
1089   (beginning-of-line)
1090   (or (eobp) (forward-char 1))
1091   (not (if (re-search-forward "^[^ \t]" nil t)
1092            (beginning-of-line)
1093          (goto-char (point-max)))))
1094
1095 (defun message-sort-headers-1 ()
1096   "Sort the buffer as headers using `message-rank' text props."
1097   (goto-char (point-min))
1098   (sort-subr
1099    nil 'message-next-header
1100    (lambda ()
1101      (message-next-header)
1102      (unless (bobp)
1103        (forward-char -1)))
1104    (lambda ()
1105      (or (get-text-property (point) 'message-rank)
1106          10000))))
1107
1108 (defun message-sort-headers ()
1109   "Sort the headers of the current message according to `message-header-format-alist'."
1110   (interactive)
1111   (save-excursion
1112     (save-restriction
1113       (let ((max (1+ (length message-header-format-alist)))
1114             rank)
1115         (message-narrow-to-headers)
1116         (while (re-search-forward "^[^ \n]+:" nil t)
1117           (put-text-property
1118            (match-beginning 0) (1+ (match-beginning 0))
1119            'message-rank
1120            (if (setq rank (length (memq (assq (intern (buffer-substring
1121                                                        (match-beginning 0)
1122                                                        (1- (match-end 0))))
1123                                               message-header-format-alist)
1124                                         message-header-format-alist)))
1125                (- max rank)
1126              (1+ max)))))
1127       (message-sort-headers-1))))
1128
1129 \f
1130
1131 ;;;
1132 ;;; Message mode
1133 ;;;
1134
1135 ;;; Set up keymap.
1136
1137 (defvar message-mode-map nil)
1138
1139 (unless message-mode-map
1140   (setq message-mode-map (copy-keymap text-mode-map))
1141   (define-key message-mode-map "\C-c?" 'describe-mode)
1142
1143   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1144   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1145   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1146   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1147   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1148   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1149   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1150   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1151   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1152   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1153   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1154   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1155   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1156
1157   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1158   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1159
1160   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1161   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1162   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1163   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1164   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1165   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1166
1167   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1168   (define-key message-mode-map "\C-c\C-s" 'message-send)
1169   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1170   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1171
1172   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1173   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1174
1175   (define-key message-mode-map "\t" 'message-tab))
1176
1177 (easy-menu-define
1178  message-mode-menu message-mode-map "Message Menu."
1179  '("Message"
1180    ["Sort Headers" message-sort-headers t]
1181    ["Yank Original" message-yank-original t]
1182    ["Fill Yanked Message" message-fill-yanked-message t]
1183    ["Insert Signature" message-insert-signature t]
1184    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1185    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1186    ["Elide Region" message-elide-region (mark t)]
1187    ["Delete Outside Region" message-delete-not-region (mark t)]
1188    ["Rename buffer" message-rename-buffer t]
1189    ["Spellcheck" ispell-message t]
1190    "----"
1191    ["Send Message" message-send-and-exit t]
1192    ["Abort Message" message-dont-send t]))
1193
1194 (easy-menu-define
1195  message-mode-field-menu message-mode-map ""
1196  '("Field"
1197    ["Fetch To" message-insert-to t]
1198    ["Fetch Newsgroups" message-insert-newsgroups t]
1199    "----"
1200    ["To" message-goto-to t]
1201    ["Subject" message-goto-subject t]
1202    ["Cc" message-goto-cc t]
1203    ["Reply-To" message-goto-reply-to t]
1204    ["Summary" message-goto-summary t]
1205    ["Keywords" message-goto-keywords t]
1206    ["Newsgroups" message-goto-newsgroups t]
1207    ["Followup-To" message-goto-followup-to t]
1208    ["Distribution" message-goto-distribution t]
1209    ["Body" message-goto-body t]
1210    ["Signature" message-goto-signature t]))
1211
1212 (defvar facemenu-add-face-function)
1213 (defvar facemenu-remove-face-function)
1214
1215 ;;;###autoload
1216 (defun message-mode ()
1217   "Major mode for editing mail and news to be sent.
1218 Like Text Mode but with these additional commands:
1219 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1220 C-c C-f  move to a header field (and create it if there isn't):
1221          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1222          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1223          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1224          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1225          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1226          C-c C-f C-f  move to Followup-To
1227 C-c C-t  message-insert-to (add a To header to a news followup)
1228 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1229 C-c C-b  message-goto-body (move to beginning of message text).
1230 C-c C-i  message-goto-signature (move to the beginning of the signature).
1231 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1232 C-c C-y  message-yank-original (insert current message, if any).
1233 C-c C-q  message-fill-yanked-message (fill what was yanked).
1234 C-c C-e  message-elide-region (elide the text between point and mark).
1235 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1236   (interactive)
1237   (kill-all-local-variables)
1238   (make-local-variable 'message-reply-buffer)
1239   (setq message-reply-buffer nil)
1240   (make-local-variable 'message-send-actions) 
1241   (make-local-variable 'message-exit-actions) 
1242   (make-local-variable 'message-kill-actions)
1243   (make-local-variable 'message-postpone-actions)
1244   (make-local-variable 'message-draft-article)
1245   (make-local-hook 'kill-buffer-hook)
1246   (set-syntax-table message-mode-syntax-table)
1247   (use-local-map message-mode-map)
1248   (setq local-abbrev-table message-mode-abbrev-table)
1249   (setq major-mode 'message-mode)
1250   (setq mode-name "Message")
1251   (setq buffer-offer-save t)
1252   (make-local-variable 'font-lock-defaults)
1253   (setq font-lock-defaults '(message-font-lock-keywords t))
1254   (make-local-variable 'facemenu-add-face-function)
1255   (make-local-variable 'facemenu-remove-face-function)
1256   (setq facemenu-add-face-function
1257         (lambda (face end)
1258           (let ((face-fun (cdr (assq face message-face-alist))))
1259             (if face-fun
1260                 (funcall face-fun (point) end)
1261               (error "Face %s not configured for %s mode" face mode-name)))
1262           "")
1263         facemenu-remove-face-function t)
1264   (make-local-variable 'paragraph-separate)
1265   (make-local-variable 'paragraph-start)
1266   (setq paragraph-start (concat (regexp-quote mail-header-separator)
1267                                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
1268                                 "-- $\\|"
1269                                 paragraph-start))
1270   (setq paragraph-separate (concat (regexp-quote mail-header-separator)
1271                                    "$\\|[ \t]*[-_][-_][-_]+$\\|"
1272                                    "-- $\\|"
1273                                    paragraph-separate))
1274   (make-local-variable 'message-reply-headers)
1275   (setq message-reply-headers nil)
1276   (make-local-variable 'message-newsreader)
1277   (make-local-variable 'message-mailer)
1278   (make-local-variable 'message-post-method)
1279   (make-local-variable 'message-sent-message-via)
1280   (setq message-sent-message-via nil)
1281   (make-local-variable 'message-checksum)
1282   (setq message-checksum nil)
1283   ;;(when (fboundp 'mail-hist-define-keys)
1284   ;;  (mail-hist-define-keys))
1285   (when (string-match "XEmacs\\|Lucid" emacs-version)
1286     (message-setup-toolbar))
1287   (easy-menu-add message-mode-menu message-mode-map)
1288   (easy-menu-add message-mode-field-menu message-mode-map)
1289   ;; Allow mail alias things.
1290   (when (eq message-mail-alias-type 'abbrev)
1291     (if (fboundp 'mail-abbrevs-setup)
1292         (mail-abbrevs-setup)
1293       (funcall (intern "mail-aliases-setup"))))
1294   (message-set-auto-save-file-name)
1295   (run-hooks 'text-mode-hook 'message-mode-hook))
1296
1297 \f
1298
1299 ;;;
1300 ;;; Message mode commands
1301 ;;;
1302
1303 ;;; Movement commands
1304
1305 (defun message-goto-to ()
1306   "Move point to the To header."
1307   (interactive)
1308   (message-position-on-field "To"))
1309
1310 (defun message-goto-subject ()
1311   "Move point to the Subject header."
1312   (interactive)
1313   (message-position-on-field "Subject"))
1314
1315 (defun message-goto-cc ()
1316   "Move point to the Cc header."
1317   (interactive)
1318   (message-position-on-field "Cc" "To"))
1319
1320 (defun message-goto-bcc ()
1321   "Move point to the Bcc  header."
1322   (interactive)
1323   (message-position-on-field "Bcc" "Cc" "To"))
1324
1325 (defun message-goto-fcc ()
1326   "Move point to the Fcc header."
1327   (interactive)
1328   (message-position-on-field "Fcc" "To" "Newsgroups"))
1329
1330 (defun message-goto-reply-to ()
1331   "Move point to the Reply-To header."
1332   (interactive)
1333   (message-position-on-field "Reply-To" "Subject"))
1334
1335 (defun message-goto-newsgroups ()
1336   "Move point to the Newsgroups header."
1337   (interactive)
1338   (message-position-on-field "Newsgroups"))
1339
1340 (defun message-goto-distribution ()
1341   "Move point to the Distribution header."
1342   (interactive)
1343   (message-position-on-field "Distribution"))
1344
1345 (defun message-goto-followup-to ()
1346   "Move point to the Followup-To header."
1347   (interactive)
1348   (message-position-on-field "Followup-To" "Newsgroups"))
1349
1350 (defun message-goto-keywords ()
1351   "Move point to the Keywords header."
1352   (interactive)
1353   (message-position-on-field "Keywords" "Subject"))
1354
1355 (defun message-goto-summary ()
1356   "Move point to the Summary header."
1357   (interactive)
1358   (message-position-on-field "Summary" "Subject"))
1359
1360 (defun message-goto-body ()
1361   "Move point to the beginning of the message body."
1362   (interactive)
1363   (if (looking-at "[ \t]*\n") (expand-abbrev))
1364   (goto-char (point-min))
1365   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1366
1367 (defun message-goto-signature ()
1368   "Move point to the beginning of the message signature."
1369   (interactive)
1370   (goto-char (point-min))
1371   (if (re-search-forward message-signature-separator nil t)
1372       (forward-line 1)
1373     (goto-char (point-max))))
1374
1375 \f
1376
1377 (defun message-insert-to (&optional force)
1378   "Insert a To header that points to the author of the article being replied to.
1379 If the original author requested not to be sent mail, the function signals
1380 an error.
1381 With the prefix argument FORCE, insert the header anyway."
1382   (interactive "P")
1383   (let ((co (message-fetch-reply-field "mail-copies-to")))
1384     (when (and (null force)
1385                co
1386                (equal (downcase co) "never"))
1387       (error "The user has requested not to have copies sent via mail")))
1388   (when (and (message-position-on-field "To")
1389              (mail-fetch-field "to")
1390              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1391     (insert ", "))
1392   (insert (or (message-fetch-reply-field "reply-to")
1393               (message-fetch-reply-field "from") "")))
1394
1395 (defun message-insert-newsgroups ()
1396   "Insert the Newsgroups header from the article being replied to."
1397   (interactive)
1398   (when (and (message-position-on-field "Newsgroups")
1399              (mail-fetch-field "newsgroups")
1400              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1401     (insert ","))
1402   (insert (or (message-fetch-reply-field "newsgroups") "")))
1403
1404 \f
1405
1406 ;;; Various commands
1407
1408 (defun message-delete-not-region (beg end)
1409   "Delete everything in the body of the current message that is outside of the region."
1410   (interactive "r")
1411   (save-excursion
1412     (goto-char end)
1413     (delete-region (point) (progn (message-goto-signature)
1414                                   (forward-line -2)
1415                                   (point)))
1416     (insert "\n")
1417     (goto-char beg)
1418     (delete-region beg (progn (message-goto-body)
1419                               (forward-line 2)
1420                               (point))))
1421   (message-goto-signature)
1422   (forward-line -2))
1423
1424 (defun message-insert-signature (&optional force)
1425   "Insert a signature.  See documentation for the `message-signature' variable."
1426   (interactive (list 0))
1427   (let* ((signature
1428           (cond
1429            ((and (null message-signature)
1430                  (eq force 0))
1431             (save-excursion
1432               (goto-char (point-max))
1433               (not (re-search-backward
1434                     message-signature-separator nil t))))
1435            ((and (null message-signature)
1436                  force)
1437             t)
1438            ((message-functionp message-signature)
1439             (funcall message-signature))
1440            ((listp message-signature)
1441             (eval message-signature))
1442            (t message-signature)))
1443          (signature
1444           (cond ((stringp signature)
1445                  signature)
1446                 ((and (eq t signature)
1447                       message-signature-file
1448                       (file-exists-p message-signature-file))
1449                  signature))))
1450     (when signature
1451       (goto-char (point-max))
1452       ;; Insert the signature.
1453       (unless (bolp)
1454         (insert "\n"))
1455       (insert "\n-- \n")
1456       (if (eq signature t)
1457           (insert-file-contents message-signature-file)
1458         (insert signature))
1459       (goto-char (point-max))
1460       (or (bolp) (insert "\n")))))
1461
1462 (defun message-elide-region (b e)
1463   "Elide the text between point and mark.  An ellipsis (from
1464 message-elide-elipsis) will be inserted where the text was killed."
1465   (interactive "r")
1466   (kill-region b e)
1467   (unless (bolp)
1468     (insert "\n"))
1469   (insert message-elide-elipsis))
1470
1471 (defvar message-caesar-translation-table nil)
1472
1473 (defun message-caesar-region (b e &optional n)
1474   "Caesar rotation of region by N, default 13, for decrypting netnews."
1475   (interactive
1476    (list
1477     (min (point) (or (mark t) (point)))
1478     (max (point) (or (mark t) (point)))
1479     (when current-prefix-arg
1480       (prefix-numeric-value current-prefix-arg))))
1481
1482   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1483   (unless (or (zerop n)                 ; no action needed for a rot of 0
1484               (= b e))                  ; no region to rotate
1485     ;; We build the table, if necessary.
1486     (when (or (not message-caesar-translation-table)
1487               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1488         (setq message-caesar-translation-table
1489               (message-make-caesar-translation-table n)))
1490     ;; Then we translate the region.  Do it this way to retain
1491     ;; text properties.
1492     (while (< b e)
1493       (subst-char-in-region
1494        b (1+ b) (char-after b)
1495        (aref message-caesar-translation-table (char-after b)))
1496       (incf b))))
1497
1498 (defun message-make-caesar-translation-table (n)
1499   "Create a rot table with offset N."
1500   (let ((i -1)
1501         (table (make-string 256 0)))
1502     (while (< (incf i) 256)
1503       (aset table i i))
1504     (concat
1505      (substring table 0 ?A)
1506      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1507      (substring table ?A (+ ?A n))
1508      (substring table (+ ?A 26) ?a)
1509      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1510      (substring table ?a (+ ?a n))
1511      (substring table (+ ?a 26) 255))))
1512
1513 (defun message-caesar-buffer-body (&optional rotnum)
1514   "Caesar rotates all letters in the current buffer by 13 places.
1515 Used to encode/decode possibly offensive messages (commonly in net.jokes).
1516 With prefix arg, specifies the number of places to rotate each letter forward.
1517 Mail and USENET news headers are not rotated."
1518   (interactive (if current-prefix-arg
1519                    (list (prefix-numeric-value current-prefix-arg))
1520                  (list nil)))
1521   (save-excursion
1522     (save-restriction
1523       (when (message-goto-body)
1524         (narrow-to-region (point) (point-max)))
1525       (message-caesar-region (point-min) (point-max) rotnum))))
1526
1527 (defun message-pipe-buffer-body (program)
1528   "Pipe the message body in the current buffer through PROGRAM."
1529   (save-excursion
1530     (save-restriction
1531       (when (message-goto-body)
1532         (narrow-to-region (point) (point-max)))
1533       (let ((body (buffer-substring (point-min) (point-max))))
1534         (unless (equal 0 (call-process-region
1535                            (point-min) (point-max) program t t))
1536             (insert body)
1537             (message "%s failed." program))))))
1538
1539 (defun message-rename-buffer (&optional enter-string)
1540   "Rename the *message* buffer to \"*message* RECIPIENT\".
1541 If the function is run with a prefix, it will ask for a new buffer
1542 name, rather than giving an automatic name."
1543   (interactive "Pbuffer name: ")
1544   (save-excursion
1545     (save-restriction
1546       (goto-char (point-min))
1547       (narrow-to-region (point)
1548                         (search-forward mail-header-separator nil 'end))
1549       (let* ((mail-to (or
1550                        (if (message-news-p) (message-fetch-field "Newsgroups")
1551                          (message-fetch-field "To"))
1552                        ""))
1553              (mail-trimmed-to
1554               (if (string-match "," mail-to)
1555                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1556                 mail-to))
1557              (name-default (concat "*message* " mail-trimmed-to))
1558              (name (if enter-string
1559                        (read-string "New buffer name: " name-default)
1560                      name-default))
1561              (default-directory
1562                (file-name-as-directory message-autosave-directory)))
1563         (rename-buffer name t)))))
1564
1565 (defun message-fill-yanked-message (&optional justifyp)
1566   "Fill the paragraphs of a message yanked into this one.
1567 Numeric argument means justify as well."
1568   (interactive "P")
1569   (save-excursion
1570     (goto-char (point-min))
1571     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1572     (let ((fill-prefix message-yank-prefix))
1573       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1574
1575 (defun message-indent-citation ()
1576   "Modify text just inserted from a message to be cited.
1577 The inserted text should be the region.
1578 When this function returns, the region is again around the modified text.
1579
1580 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1581 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1582   (let ((start (point)))
1583     ;; Remove unwanted headers.
1584     (when message-ignored-cited-headers
1585       (let (all-removed)
1586         (save-restriction
1587           (narrow-to-region
1588            (goto-char start)
1589            (if (search-forward "\n\n" nil t)
1590                (1- (point))
1591              (point)))
1592           (message-remove-header message-ignored-cited-headers t)
1593           (when (= (point-min) (point-max))
1594             (setq all-removed t))
1595           (goto-char (point-max)))
1596         (if all-removed
1597             (goto-char start)
1598           (forward-line 1))))
1599     ;; Delete blank lines at the start of the buffer.
1600     (while (and (point-min)
1601                 (eolp)
1602                 (not (eobp)))
1603       (message-delete-line))
1604     ;; Delete blank lines at the end of the buffer.
1605     (goto-char (point-max))
1606     (unless (eolp)
1607       (insert "\n"))
1608     (while (and (zerop (forward-line -1))
1609                 (looking-at "$"))
1610       (message-delete-line))
1611     ;; Do the indentation.
1612     (if (null message-yank-prefix)
1613         (indent-rigidly start (mark t) message-indentation-spaces)
1614       (save-excursion
1615         (goto-char start)
1616         (while (< (point) (mark t))
1617           (insert message-yank-prefix)
1618           (forward-line 1))))
1619     (goto-char start)))
1620
1621 (defun message-yank-original (&optional arg)
1622   "Insert the message being replied to, if any.
1623 Puts point before the text and mark after.
1624 Normally indents each nonblank line ARG spaces (default 3).  However,
1625 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1626
1627 This function uses `message-cite-function' to do the actual citing.
1628
1629 Just \\[universal-argument] as argument means don't indent, insert no
1630 prefix, and don't delete any headers."
1631   (interactive "P")
1632   (let ((modified (buffer-modified-p)))
1633     (when (and message-reply-buffer
1634                message-cite-function)
1635       (delete-windows-on message-reply-buffer t)
1636       (insert-buffer message-reply-buffer)
1637       (funcall message-cite-function)
1638       (message-exchange-point-and-mark)
1639       (unless (bolp)
1640         (insert ?\n))
1641       (unless modified
1642         (setq message-checksum (cons (message-checksum) (buffer-size)))))))
1643
1644 (defun message-cite-original ()
1645   "Cite function in the standard Message manner."
1646   (let ((start (point))
1647         (functions
1648          (when message-indent-citation-function
1649            (if (listp message-indent-citation-function)
1650                message-indent-citation-function
1651              (list message-indent-citation-function)))))
1652     (goto-char start)
1653     (while functions
1654       (funcall (pop functions)))
1655     (when message-citation-line-function
1656       (unless (bolp)
1657         (insert "\n"))
1658       (funcall message-citation-line-function))))
1659
1660 (defun message-insert-citation-line ()
1661   "Function that inserts a simple citation line."
1662   (when message-reply-headers
1663     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1664
1665 (defun message-position-on-field (header &rest afters)
1666   (let ((case-fold-search t))
1667     (save-restriction
1668       (narrow-to-region
1669        (goto-char (point-min))
1670        (progn
1671          (re-search-forward
1672           (concat "^" (regexp-quote mail-header-separator) "$"))
1673          (match-beginning 0)))
1674       (goto-char (point-min))
1675       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1676           (progn
1677             (re-search-forward "^[^ \t]" nil 'move)
1678             (beginning-of-line)
1679             (skip-chars-backward "\n")
1680             t)
1681         (while (and afters
1682                     (not (re-search-forward
1683                           (concat "^" (regexp-quote (car afters)) ":")
1684                           nil t)))
1685           (pop afters))
1686         (when afters
1687           (re-search-forward "^[^ \t]" nil 'move)
1688           (beginning-of-line))
1689         (insert header ": \n")
1690         (forward-char -1)
1691         nil))))
1692
1693 (defun message-remove-signature ()
1694   "Remove the signature from the text between point and mark.
1695 The text will also be indented the normal way."
1696   (save-excursion
1697     (let ((start (point))
1698           mark)
1699       (if (not (re-search-forward message-signature-separator (mark t) t))
1700           ;; No signature here, so we just indent the cited text.
1701           (message-indent-citation)
1702         ;; Find the last non-empty line.
1703         (forward-line -1)
1704         (while (looking-at "[ \t]*$")
1705           (forward-line -1))
1706         (forward-line 1)
1707         (setq mark (set-marker (make-marker) (point)))
1708         (goto-char start)
1709         (message-indent-citation)
1710         ;; Enable undoing the deletion.
1711         (undo-boundary)
1712         (delete-region mark (mark t))
1713         (set-marker mark nil)))))
1714
1715 \f
1716
1717 ;;;
1718 ;;; Sending messages
1719 ;;;
1720
1721 (defun message-send-and-exit (&optional arg)
1722   "Send message like `message-send', then, if no errors, exit from mail buffer."
1723   (interactive "P")
1724   (let ((buf (current-buffer))
1725         (actions message-exit-actions))
1726     (when (and (message-send arg)
1727                (buffer-name buf))
1728       (if message-kill-buffer-on-exit
1729           (kill-buffer buf)
1730         (bury-buffer buf)
1731         (when (eq buf (current-buffer))
1732           (message-bury buf)))
1733       (message-do-actions actions))))
1734
1735 (defun message-dont-send ()
1736   "Don't send the message you have been editing."
1737   (interactive)
1738   (let ((actions message-postpone-actions))
1739     (message-bury (current-buffer))
1740     (message-do-actions actions)))
1741
1742 (defun message-kill-buffer ()
1743   "Kill the current buffer."
1744   (interactive)
1745   (when (or (not (buffer-modified-p))
1746             (yes-or-no-p "Message modified; kill anyway? "))
1747     (let ((actions message-kill-actions))
1748       (setq buffer-file-name nil)
1749       (kill-buffer (current-buffer))
1750       (message-do-actions actions))))
1751
1752 (defun message-bury (buffer)
1753   "Bury this mail buffer."
1754   (let ((newbuf (other-buffer buffer)))
1755     (bury-buffer buffer)
1756     (if (and (fboundp 'frame-parameters)
1757              (cdr (assq 'dedicated (frame-parameters)))
1758              (not (null (delq (selected-frame) (visible-frame-list)))))
1759         (delete-frame (selected-frame))
1760       (switch-to-buffer newbuf))))
1761
1762 (defun message-send (&optional arg)
1763   "Send the message in the current buffer.
1764 If `message-interactive' is non-nil, wait for success indication
1765 or error messages, and inform user.
1766 Otherwise any failure is reported in a message back to
1767 the user from the mailer."
1768   (interactive "P")
1769   ;; Disabled test.
1770   (when (if (and nil buffer-file-name)
1771             (y-or-n-p (format "Send buffer contents as %s message? "
1772                               (if (message-mail-p)
1773                                   (if (message-news-p) "mail and news" "mail")
1774                                 "news")))
1775           (or (buffer-modified-p)
1776               (y-or-n-p "No changes in the buffer; really send? ")))
1777     ;; Make it possible to undo the coming changes.
1778     (undo-boundary)
1779     (let ((inhibit-read-only t))
1780       (put-text-property (point-min) (point-max) 'read-only nil))
1781     (message-fix-before-sending)
1782     (run-hooks 'message-send-hook)
1783     (message "Sending...")
1784     (let ((alist message-send-method-alist)
1785           (success t)
1786           elem sent)
1787       (while (and success
1788                   (setq elem (pop alist)))
1789         (when (and (or (not (funcall (cadr elem)))
1790                        (and (or (not (memq (car elem)
1791                                            message-sent-message-via))
1792                                 (y-or-n-p
1793                                  (format
1794                                   "Already sent message via %s; resend? "
1795                                   (car elem))))
1796                             (setq success (funcall (caddr elem) arg)))))
1797           (setq sent t)))
1798       (when (and success sent)
1799         (message-do-fcc)
1800         ;;(when (fboundp 'mail-hist-put-headers-into-history)
1801         ;; (mail-hist-put-headers-into-history))
1802         (run-hooks 'message-sent-hook)
1803         (message "Sending...done")
1804         ;; Mark the buffer as unmodified and delete autosave.
1805         (set-buffer-modified-p nil)
1806         (delete-auto-save-file-if-necessary t)
1807         (message-disassociate-draft)
1808         ;; Delete other mail buffers and stuff.
1809         (message-do-send-housekeeping)
1810         (message-do-actions message-send-actions)
1811         ;; Return success.
1812         t))))
1813
1814 (defun message-send-via-mail (arg)
1815   "Send the current message via mail."  
1816   (message-send-mail arg))
1817
1818 (defun message-send-via-news (arg)
1819   "Send the current message via news."
1820   (funcall message-send-news-function arg))
1821
1822 (defun message-fix-before-sending ()
1823   "Do various things to make the message nice before sending it."
1824   ;; Make sure there's a newline at the end of the message.
1825   (goto-char (point-max))
1826   (unless (bolp)
1827     (insert "\n")))
1828
1829 (defun message-add-action (action &rest types)
1830   "Add ACTION to be performed when doing an exit of type TYPES."
1831   (let (var)
1832     (while types
1833       (set (setq var (intern (format "message-%s-actions" (pop types))))
1834            (nconc (symbol-value var) (list action))))))
1835
1836 (defun message-do-actions (actions)
1837   "Perform all actions in ACTIONS."
1838   ;; Now perform actions on successful sending.
1839   (while actions
1840     (ignore-errors
1841       (cond
1842        ;; A simple function.
1843        ((message-functionp (car actions))
1844         (funcall (car actions)))
1845        ;; Something to be evaled.
1846        (t
1847         (eval (car actions)))))
1848     (pop actions)))
1849
1850 (defun message-send-mail (&optional arg)
1851   (require 'mail-utils)
1852   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
1853         (case-fold-search nil)
1854         (news (message-news-p))
1855         (mailbuf (current-buffer)))
1856     (save-restriction
1857       (message-narrow-to-headers)
1858       ;; Insert some headers.
1859       (let ((message-deletable-headers
1860              (if news nil message-deletable-headers)))
1861         (message-generate-headers message-required-mail-headers))
1862       ;; Let the user do all of the above.
1863       (run-hooks 'message-header-hook))
1864     (unwind-protect
1865         (save-excursion
1866           (set-buffer tembuf)
1867           (erase-buffer)
1868           ;; Avoid copying text props.
1869           (insert (format
1870                    "%s" (save-excursion
1871                           (set-buffer mailbuf)
1872                           (buffer-string))))
1873           ;; Remove some headers.
1874           (save-restriction
1875             (message-narrow-to-headers)
1876             ;; Remove some headers.
1877             (message-remove-header message-ignored-mail-headers t))
1878           (goto-char (point-max))
1879           ;; require one newline at the end.
1880           (or (= (preceding-char) ?\n)
1881               (insert ?\n))
1882           (when (and news
1883                      (or (message-fetch-field "cc")
1884                          (message-fetch-field "to")))
1885             (message-insert-courtesy-copy))
1886           (funcall message-send-mail-function))
1887       (kill-buffer tembuf))
1888     (set-buffer mailbuf)
1889     (push 'mail message-sent-message-via)))
1890
1891 (defun message-send-mail-with-sendmail ()
1892   "Send off the prepared buffer with sendmail."
1893   (let ((errbuf (if message-interactive
1894                     (generate-new-buffer " sendmail errors")
1895                   0))
1896         resend-to-addresses delimline)
1897     (let ((case-fold-search t))
1898       (save-restriction
1899         (message-narrow-to-headers)
1900         (setq resend-to-addresses (message-fetch-field "resent-to")))
1901       ;; Change header-delimiter to be what sendmail expects.
1902       (goto-char (point-min))
1903       (re-search-forward
1904        (concat "^" (regexp-quote mail-header-separator) "\n"))
1905       (replace-match "\n")
1906       (backward-char 1)
1907       (setq delimline (point-marker))
1908       (run-hooks 'message-send-mail-hook)
1909       ;; Insert an extra newline if we need it to work around
1910       ;; Sun's bug that swallows newlines.
1911       (goto-char (1+ delimline))
1912       (when (eval message-mailer-swallows-blank-line)
1913         (newline))
1914       (when message-interactive
1915         (save-excursion
1916           (set-buffer errbuf)
1917           (erase-buffer))))
1918     (let ((default-directory "/"))
1919       (apply 'call-process-region
1920              (append (list (point-min) (point-max)
1921                            (if (boundp 'sendmail-program)
1922                                sendmail-program
1923                              "/usr/lib/sendmail")
1924                            nil errbuf nil "-oi")
1925                      ;; Always specify who from,
1926                      ;; since some systems have broken sendmails.
1927                      ;; But some systems are more broken with -f, so
1928                      ;; we'll let users override this.
1929                      (if (null message-sendmail-f-is-evil)
1930                          (list "-f" (user-login-name)))
1931                      ;; These mean "report errors by mail"
1932                      ;; and "deliver in background".
1933                      (if (null message-interactive) '("-oem" "-odb"))
1934                      ;; Get the addresses from the message
1935                      ;; unless this is a resend.
1936                      ;; We must not do that for a resend
1937                      ;; because we would find the original addresses.
1938                      ;; For a resend, include the specific addresses.
1939                      (if resend-to-addresses
1940                          (list resend-to-addresses)
1941                        '("-t")))))
1942     (when message-interactive
1943       (save-excursion
1944         (set-buffer errbuf)
1945         (goto-char (point-min))
1946         (while (re-search-forward "\n\n* *" nil t)
1947           (replace-match "; "))
1948         (if (not (zerop (buffer-size)))
1949             (error "Sending...failed to %s"
1950                    (buffer-substring (point-min) (point-max)))))
1951       (when (bufferp errbuf)
1952         (kill-buffer errbuf)))))
1953
1954 (defun message-send-mail-with-qmail ()
1955   "Pass the prepared message buffer to qmail-inject.
1956 Refer to the documentation for the variable `message-send-mail-function'
1957 to find out how to use this."
1958   ;; replace the header delimiter with a blank line
1959   (goto-char (point-min))
1960   (re-search-forward
1961    (concat "^" (regexp-quote mail-header-separator) "\n"))
1962   (replace-match "\n")
1963   (run-hooks 'message-send-mail-hook)
1964   ;; send the message
1965   (case
1966       (apply
1967        'call-process-region 1 (point-max) message-qmail-inject-program
1968        nil nil nil
1969        ;; qmail-inject's default behaviour is to look for addresses on the
1970        ;; command line; if there're none, it scans the headers.
1971        ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
1972        ;;
1973        ;; in general, ALL of qmail-inject's defaults are perfect for simply
1974        ;; reading a formatted (i. e., at least a To: or Resent-To header)
1975        ;; message from stdin.
1976        ;;
1977        ;; qmail also has the advantage of not having been raped by
1978        ;; various vendors, so we don't have to allow for that, either --
1979        ;; compare this with message-send-mail-with-sendmail and weep
1980        ;; for sendmail's lost innocence.
1981        ;;
1982        ;; all this is way cool coz it lets us keep the arguments entirely
1983        ;; free for -inject-arguments -- a big win for the user and for us
1984        ;; since we don't have to play that double-guessing game and the user
1985        ;; gets full control (no gestapo'ish -f's, for instance).  --sj
1986        message-qmail-inject-args)
1987     ;; qmail-inject doesn't say anything on it's stdout/stderr,
1988     ;; we have to look at the retval instead
1989     (0 nil)
1990     (1   (error "qmail-inject reported permanent failure"))
1991     (111 (error "qmail-inject reported transient failure"))
1992     ;; should never happen
1993     (t   (error "qmail-inject reported unknown failure"))))
1994
1995 (defun message-send-mail-with-mh ()
1996   "Send the prepared message buffer with mh."
1997   (let ((mh-previous-window-config nil)
1998         (name (make-temp-name
1999                (concat (file-name-as-directory
2000                         (expand-file-name message-autosave-directory))
2001                        "msg."))))
2002     (setq buffer-file-name name)
2003     ;; MH wants to generate these headers itself.
2004     (when message-mh-deletable-headers
2005       (let ((headers message-mh-deletable-headers))
2006         (while headers
2007           (goto-char (point-min))
2008           (and (re-search-forward
2009                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2010                (message-delete-line))
2011           (pop headers))))
2012     (run-hooks 'message-send-mail-hook)
2013     ;; Pass it on to mh.
2014     (mh-send-letter)))
2015
2016 (defun message-send-news (&optional arg)
2017   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2018         (case-fold-search nil)
2019         (method (if (message-functionp message-post-method)
2020                     (funcall message-post-method arg)
2021                   message-post-method))
2022         (messbuf (current-buffer))
2023         (message-syntax-checks
2024          (if arg
2025              (cons '(existing-newsgroups . disabled)
2026                    message-syntax-checks)
2027            message-syntax-checks))
2028         result)
2029     (save-restriction
2030       (message-narrow-to-headers)
2031       ;; Insert some headers.
2032       (message-generate-headers message-required-news-headers)
2033       ;; Let the user do all of the above.
2034       (run-hooks 'message-header-hook))
2035     (message-cleanup-headers)
2036     (if (not (message-check-news-syntax))
2037         (progn
2038           ;;(message "Posting not performed")
2039           nil)
2040       (unwind-protect
2041           (save-excursion
2042             (set-buffer tembuf)
2043             (buffer-disable-undo (current-buffer))
2044             (erase-buffer)
2045             ;; Avoid copying text props.
2046             (insert (format
2047                      "%s" (save-excursion
2048                             (set-buffer messbuf)
2049                             (buffer-string))))
2050             ;; Remove some headers.
2051             (save-restriction
2052               (message-narrow-to-headers)
2053               ;; Remove some headers.
2054               (message-remove-header message-ignored-news-headers t))
2055             (goto-char (point-max))
2056             ;; require one newline at the end.
2057             (or (= (preceding-char) ?\n)
2058                 (insert ?\n))
2059             (let ((case-fold-search t))
2060               ;; Remove the delimiter.
2061               (goto-char (point-min))
2062               (re-search-forward
2063                (concat "^" (regexp-quote mail-header-separator) "\n"))
2064               (replace-match "\n")
2065               (backward-char 1))
2066             (run-hooks 'message-send-news-hook)
2067             ;;(require (car method))
2068             ;;(funcall (intern (format "%s-open-server" (car method)))
2069             ;;(cadr method) (cddr method))
2070             ;;(setq result
2071             ;;    (funcall (intern (format "%s-request-post" (car method)))
2072             ;;             (cadr method)))
2073             (gnus-open-server method)
2074             (setq result (gnus-request-post method)))
2075         (kill-buffer tembuf))
2076       (set-buffer messbuf)
2077       (if result
2078           (push 'news message-sent-message-via)
2079         (message "Couldn't send message via news: %s"
2080                  (nnheader-get-report (car method)))
2081         nil))))
2082
2083 ;;;
2084 ;;; Header generation & syntax checking.
2085 ;;;
2086
2087 (defmacro message-check (type &rest forms)
2088   "Eval FORMS if TYPE is to be checked."
2089   `(or (message-check-element ,type)
2090        (save-excursion
2091          ,@forms)))
2092
2093 (put 'message-check 'lisp-indent-function 1)
2094 (put 'message-check 'edebug-form-spec '(form body))
2095
2096 (defun message-check-element (type)
2097   "Returns non-nil if this type is not to be checked."
2098   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2099       t
2100     (let ((able (assq type message-syntax-checks)))
2101       (and (consp able)
2102            (eq (cdr able) 'disabled)))))
2103
2104 (defun message-check-news-syntax ()
2105   "Check the syntax of the message."
2106   (save-excursion
2107     (save-restriction
2108       (widen)
2109       (and
2110        ;; We narrow to the headers and check them first.
2111        (save-excursion
2112          (save-restriction
2113            (message-narrow-to-headers)
2114            (message-check-news-header-syntax)))
2115        ;; Check the body.
2116        (message-check-news-body-syntax)))))
2117
2118 (defun message-check-news-header-syntax ()
2119   (and
2120    ;; Check the Subject header.
2121    (message-check 'subject
2122      (let* ((case-fold-search t)
2123             (subject (message-fetch-field "subject")))
2124        (or
2125         (and subject
2126              (not (string-match "\\`[ \t]*\\'" subject)))
2127         (ignore
2128          (message
2129           "The subject field is empty or missing.  Posting is denied.")))))
2130    ;; Check for commands in Subject.
2131    (message-check 'subject-cmsg
2132      (if (string-match "^cmsg " (message-fetch-field "subject"))
2133          (y-or-n-p
2134           "The control code \"cmsg\" is in the subject.  Really post? ")
2135        t))
2136    ;; Check for multiple identical headers.
2137    (message-check 'multiple-headers
2138      (let (found)
2139        (while (and (not found)
2140                    (re-search-forward "^[^ \t:]+: " nil t))
2141          (save-excursion
2142            (or (re-search-forward
2143                 (concat "^"
2144                         (regexp-quote
2145                          (setq found
2146                                (buffer-substring
2147                                 (match-beginning 0) (- (match-end 0) 2))))
2148                         ":")
2149                 nil t)
2150                (setq found nil))))
2151        (if found
2152            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2153          t)))
2154    ;; Check for Version and Sendsys.
2155    (message-check 'sendsys
2156      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2157          (y-or-n-p
2158           (format "The article contains a %s command.  Really post? "
2159                   (buffer-substring (match-beginning 0)
2160                                     (1- (match-end 0)))))
2161        t))
2162    ;; See whether we can shorten Followup-To.
2163    (message-check 'shorten-followup-to
2164      (let ((newsgroups (message-fetch-field "newsgroups"))
2165            (followup-to (message-fetch-field "followup-to"))
2166            to)
2167        (when (and newsgroups
2168                   (string-match "," newsgroups)
2169                   (not followup-to)
2170                   (not
2171                    (zerop
2172                     (length
2173                      (setq to (completing-read
2174                                "Followups to: (default all groups) "
2175                                (mapcar (lambda (g) (list g))
2176                                        (cons "poster"
2177                                              (message-tokenize-header
2178                                               newsgroups)))))))))
2179          (goto-char (point-min))
2180          (insert "Followup-To: " to "\n"))
2181        t))
2182    ;; Check "Shoot me".
2183    (message-check 'shoot
2184      (if (re-search-forward
2185           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2186          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2187        t))
2188    ;; Check for Approved.
2189    (message-check 'approved
2190      (if (re-search-forward "^Approved:" nil t)
2191          (y-or-n-p "The article contains an Approved header.  Really post? ")
2192        t))
2193    ;; Check the Message-ID header.
2194    (message-check 'message-id
2195      (let* ((case-fold-search t)
2196             (message-id (message-fetch-field "message-id" t)))
2197        (or (not message-id)
2198            (and (string-match "@" message-id)
2199                 (string-match "@[^\\.]*\\." message-id))
2200            (y-or-n-p
2201             (format "The Message-ID looks strange: \"%s\".  Really post? "
2202                     message-id)))))
2203    ;; Check the Newsgroups & Followup-To headers.
2204    (message-check 'existing-newsgroups
2205      (let* ((case-fold-search t)
2206             (newsgroups (message-fetch-field "newsgroups"))
2207             (followup-to (message-fetch-field "followup-to"))
2208             (groups (message-tokenize-header
2209                      (if followup-to
2210                          (concat newsgroups "," followup-to)
2211                        newsgroups)))
2212             (hashtb (and (boundp 'gnus-active-hashtb)
2213                          gnus-active-hashtb))
2214             errors)
2215        (if (or (not hashtb)
2216                (not (boundp 'gnus-read-active-file))
2217                (not gnus-read-active-file)
2218                (eq gnus-read-active-file 'some))
2219            t
2220          (while groups
2221            (when (and (not (boundp (intern (car groups) hashtb)))
2222                       (not (equal (car groups) "poster")))
2223              (push (car groups) errors))
2224            (pop groups))
2225          (if (not errors)
2226              t
2227            (y-or-n-p
2228             (format
2229              "Really post to %s unknown group%s: %s "
2230              (if (= (length errors) 1) "this" "these")
2231              (if (= (length errors) 1) "" "s")
2232              (mapconcat 'identity errors ", ")))))))
2233    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2234    (message-check 'valid-newsgroups
2235      (let ((case-fold-search t)
2236            (headers '("Newsgroups" "Followup-To"))
2237            header error)
2238        (while (and headers (not error))
2239          (when (setq header (mail-fetch-field (car headers)))
2240            (if (or
2241                 (not
2242                  (string-match
2243                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2244                   header))
2245                 (memq
2246                  nil (mapcar
2247                       (lambda (g)
2248                         (not (string-match "\\.\\'\\|\\.\\." g)))
2249                       (message-tokenize-header header ","))))
2250                (setq error t)))
2251          (unless error
2252            (pop headers)))
2253        (if (not error)
2254            t
2255          (y-or-n-p
2256           (format "The %s header looks odd: \"%s\".  Really post? "
2257                   (car headers) header)))))
2258    (message-check 'repeated-newsgroups
2259      (let ((case-fold-search t)
2260            (headers '("Newsgroups" "Followup-To"))
2261            header error groups group)
2262        (while (and headers
2263                    (not error))
2264          (when (setq header (mail-fetch-field (pop headers)))
2265            (setq groups (message-tokenize-header header ","))
2266            (while (setq group (pop groups))
2267              (when (member group groups)
2268                (setq error group
2269                      groups nil)))))
2270        (if (not error)
2271            t
2272          (y-or-n-p
2273           (format "Group %s is repeated in headers.  Really post? " error)))))
2274    ;; Check the From header.
2275    (message-check 'from
2276      (let* ((case-fold-search t)
2277             (from (message-fetch-field "from"))
2278             (ad (nth 1 (mail-extract-address-components from))))
2279        (cond
2280         ((not from)
2281          (message "There is no From line.  Posting is denied.")
2282          nil)
2283         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2284              (string-match "\\.\\." ad) ;larsi@ifi..uio
2285              (string-match "@\\." ad)   ;larsi@.ifi.uio
2286              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2287              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2288              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2289          (message
2290           "Denied posting -- the From looks strange: \"%s\"." from)
2291          nil)
2292         (t t))))))
2293
2294 (defun message-check-news-body-syntax ()
2295   (and
2296    ;; Check for long lines.
2297    (message-check 'long-lines
2298      (goto-char (point-min))
2299      (re-search-forward
2300       (concat "^" (regexp-quote mail-header-separator) "$"))
2301      (while (and
2302              (progn
2303                (end-of-line)
2304                (< (current-column) 80))
2305              (zerop (forward-line 1))))
2306      (or (bolp)
2307          (eobp)
2308          (y-or-n-p
2309           "You have lines longer than 79 characters.  Really post? ")))
2310    ;; Check whether the article is empty.
2311    (message-check 'empty
2312      (goto-char (point-min))
2313      (re-search-forward
2314       (concat "^" (regexp-quote mail-header-separator) "$"))
2315      (forward-line 1)
2316      (let ((b (point)))
2317        (goto-char (point-max))
2318        (re-search-backward message-signature-separator nil t)
2319        (beginning-of-line)
2320        (or (re-search-backward "[^ \n\t]" b t)
2321            (y-or-n-p "Empty article.  Really post? "))))
2322    ;; Check for control characters.
2323    (message-check 'control-chars
2324      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2325          (y-or-n-p
2326           "The article contains control characters.  Really post? ")
2327        t))
2328    ;; Check excessive size.
2329    (message-check 'size
2330      (if (> (buffer-size) 60000)
2331          (y-or-n-p
2332           (format "The article is %d octets long.  Really post? "
2333                   (buffer-size)))
2334        t))
2335    ;; Check whether any new text has been added.
2336    (message-check 'new-text
2337      (or
2338       (not message-checksum)
2339       (not (and (eq (message-checksum) (car message-checksum))
2340                 (eq (buffer-size) (cdr message-checksum))))
2341       (y-or-n-p
2342        "It looks like no new text has been added.  Really post? ")))
2343    ;; Check the length of the signature.
2344    (message-check 'signature
2345      (goto-char (point-max))
2346      (if (or (not (re-search-backward message-signature-separator nil t))
2347              (search-forward message-forward-end-separator nil t))
2348          t
2349        (if (> (count-lines (point) (point-max)) 5)
2350            (y-or-n-p
2351             (format
2352              "Your .sig is %d lines; it should be max 4.  Really post? "
2353              (1- (count-lines (point) (point-max)))))
2354          t)))))
2355
2356 (defun message-checksum ()
2357   "Return a \"checksum\" for the current buffer."
2358   (let ((sum 0))
2359     (save-excursion
2360       (goto-char (point-min))
2361       (re-search-forward
2362        (concat "^" (regexp-quote mail-header-separator) "$"))
2363       (while (not (eobp))
2364         (when (not (looking-at "[ \t\n]"))
2365           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2366                             (following-char))))
2367         (forward-char 1)))
2368     sum))
2369
2370 (defun message-do-fcc ()
2371   "Process Fcc headers in the current buffer."
2372   (let ((case-fold-search t)
2373         (buf (current-buffer))
2374         list file)
2375     (save-excursion
2376       (set-buffer (get-buffer-create " *message temp*"))
2377       (buffer-disable-undo (current-buffer))
2378       (erase-buffer)
2379       (insert-buffer-substring buf)
2380       (save-restriction
2381         (message-narrow-to-headers)
2382         (while (setq file (message-fetch-field "fcc"))
2383           (push file list)
2384           (message-remove-header "fcc" nil t)))
2385       (goto-char (point-min))
2386       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2387       (replace-match "" t t)
2388       ;; Process FCC operations.
2389       (while list
2390         (setq file (pop list))
2391         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2392             ;; Pipe the article to the program in question.
2393             (call-process-region (point-min) (point-max) shell-file-name
2394                                  nil nil nil shell-command-switch
2395                                  (match-string 1 file))
2396           ;; Save the article.
2397           (setq file (expand-file-name file))
2398           (unless (file-exists-p (file-name-directory file))
2399             (make-directory (file-name-directory file) t))
2400           (if (and message-fcc-handler-function
2401                    (not (eq message-fcc-handler-function 'rmail-output)))
2402               (funcall message-fcc-handler-function file)
2403             (if (and (file-readable-p file) (mail-file-babyl-p file))
2404                 (rmail-output file 1 nil t)
2405               (let ((mail-use-rfc822 t))
2406                 (rmail-output file 1 t t))))))
2407
2408       (kill-buffer (current-buffer)))))
2409
2410 (defun message-output (filename)
2411   "Append this article to Unix/babyl mail file.."
2412   (if (and (file-readable-p filename)
2413            (mail-file-babyl-p filename))
2414       (gnus-output-to-rmail filename t)
2415     (gnus-output-to-mail filename t)))
2416
2417 (defun message-cleanup-headers ()
2418   "Do various automatic cleanups of the headers."
2419   ;; Remove empty lines in the header.
2420   (save-restriction
2421     (message-narrow-to-headers)
2422     ;; Remove blank lines.
2423     (while (re-search-forward "^[ \t]*\n" nil t)
2424       (replace-match "" t t))
2425
2426     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2427     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2428     ;; embedded line breaks.
2429     (goto-char (point-min))
2430     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2431       (save-restriction
2432         (narrow-to-region
2433          (point)
2434          (if (re-search-forward "^[^ \t]" nil t)
2435              (match-beginning 0)
2436            (forward-line 1)
2437            (point)))
2438         (goto-char (point-min))
2439         (while (re-search-forward "\n[ \t]+" nil t)
2440           (replace-match " " t t))      ;No line breaks (too confusing)
2441         (goto-char (point-min))
2442         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2443           (replace-match "," t t))
2444         (goto-char (point-min))
2445         ;; Remove trailing commas.
2446         (when (re-search-forward ",+$" nil t)
2447           (replace-match "" t t))))))
2448
2449 (defun message-make-date ()
2450   "Make a valid data header."
2451   (let ((now (current-time)))
2452     (timezone-make-date-arpa-standard
2453      (current-time-string now) (current-time-zone now))))
2454
2455 (defun message-make-message-id ()
2456   "Make a unique Message-ID."
2457   (concat "<" (message-unique-id)
2458           (let ((psubject (save-excursion (message-fetch-field "subject")))
2459                 (psupersedes
2460                  (save-excursion (message-fetch-field "supersedes"))))
2461             (if (or
2462                  (and message-reply-headers
2463                       (mail-header-references message-reply-headers)
2464                       (mail-header-subject message-reply-headers)
2465                       psubject
2466                       (mail-header-subject message-reply-headers)
2467                       (not (string=
2468                             (message-strip-subject-re
2469                              (mail-header-subject message-reply-headers))
2470                             (message-strip-subject-re psubject))))
2471                  (and psupersedes
2472                       (string-match "_-_@" psupersedes)))
2473                 "_-_" ""))
2474           "@" (message-make-fqdn) ">"))
2475
2476 (defvar message-unique-id-char nil)
2477
2478 ;; If you ever change this function, make sure the new version
2479 ;; cannot generate IDs that the old version could.
2480 ;; You might for example insert a "." somewhere (not next to another dot
2481 ;; or string boundary), or modify the "fsf" string.
2482 (defun message-unique-id ()
2483   ;; Don't use microseconds from (current-time), they may be unsupported.
2484   ;; Instead we use this randomly inited counter.
2485   (setq message-unique-id-char
2486         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2487            ;; (current-time) returns 16-bit ints,
2488            ;; and 2^16*25 just fits into 4 digits i base 36.
2489            (* 25 25)))
2490   (let ((tm (current-time)))
2491     (concat
2492      (if (memq system-type '(ms-dos emx vax-vms))
2493          (let ((user (downcase (user-login-name))))
2494            (while (string-match "[^a-z0-9_]" user)
2495              (aset user (match-beginning 0) ?_))
2496            user)
2497        (message-number-base36 (user-uid) -1))
2498      (message-number-base36 (+ (car   tm)
2499                                (lsh (% message-unique-id-char 25) 16)) 4)
2500      (message-number-base36 (+ (nth 1 tm)
2501                                (lsh (/ message-unique-id-char 25) 16)) 4)
2502      ;; Append the newsreader name, because while the generated
2503      ;; ID is unique to this newsreader, other newsreaders might
2504      ;; otherwise generate the same ID via another algorithm.
2505      ".fsf")))
2506
2507 (defun message-number-base36 (num len)
2508   (if (if (< len 0)
2509           (<= num 0)
2510         (= len 0))
2511       ""
2512     (concat (message-number-base36 (/ num 36) (1- len))
2513             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2514                                   (% num 36))))))
2515
2516 (defun message-make-organization ()
2517   "Make an Organization header."
2518   (let* ((organization
2519           (or (getenv "ORGANIZATION")
2520               (when message-user-organization
2521                 (if (message-functionp message-user-organization)
2522                     (funcall message-user-organization)
2523                   message-user-organization)))))
2524     (save-excursion
2525       (message-set-work-buffer)
2526       (cond ((stringp organization)
2527              (insert organization))
2528             ((and (eq t organization)
2529                   message-user-organization-file
2530                   (file-exists-p message-user-organization-file))
2531              (insert-file-contents message-user-organization-file)))
2532       (goto-char (point-min))
2533       (while (re-search-forward "[\t\n]+" nil t)
2534         (replace-match "" t t))
2535       (unless (zerop (buffer-size))
2536         (buffer-string)))))
2537
2538 (defun message-make-lines ()
2539   "Count the number of lines and return numeric string."
2540   (save-excursion
2541     (save-restriction
2542       (widen)
2543       (goto-char (point-min))
2544       (re-search-forward
2545        (concat "^" (regexp-quote mail-header-separator) "$"))
2546       (forward-line 1)
2547       (int-to-string (count-lines (point) (point-max))))))
2548
2549 (defun message-make-in-reply-to ()
2550   "Return the In-Reply-To header for this message."
2551   (when message-reply-headers
2552     (let ((from (mail-header-from message-reply-headers))
2553           (date (mail-header-date message-reply-headers)))
2554       (when from
2555         (let ((stop-pos
2556                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2557           (concat (if stop-pos (substring from 0 stop-pos) from)
2558                   "'s message of \""
2559                   (if (or (not date) (string= date ""))
2560                       "(unknown date)" date)
2561                   "\""))))))
2562
2563 (defun message-make-distribution ()
2564   "Make a Distribution header."
2565   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2566     (cond ((message-functionp message-distribution-function)
2567            (funcall message-distribution-function))
2568           (t orig-distribution))))
2569
2570 (defun message-make-expires ()
2571   "Return an Expires header based on `message-expires'."
2572   (let ((current (current-time))
2573         (future (* 1.0 message-expires 60 60 24)))
2574     ;; Add the future to current.
2575     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2576     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2577     ;; Return the date in the future in UT.
2578     (timezone-make-date-arpa-standard
2579      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2580
2581 (defun message-make-path ()
2582   "Return uucp path."
2583   (let ((login-name (user-login-name)))
2584     (cond ((null message-user-path)
2585            (concat (system-name) "!" login-name))
2586           ((stringp message-user-path)
2587            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2588            (concat message-user-path "!" login-name))
2589           (t login-name))))
2590
2591 (defun message-make-from ()
2592   "Make a From header."
2593   (let* ((style message-from-style)
2594          (login (message-make-address))
2595          (fullname
2596           (or (and (boundp 'user-full-name)
2597                    user-full-name)
2598               (user-full-name))))
2599     (when (string= fullname "&")
2600       (setq fullname (user-login-name)))
2601     (save-excursion
2602       (message-set-work-buffer)
2603       (cond
2604        ((or (null style)
2605             (equal fullname ""))
2606         (insert login))
2607        ((or (eq style 'angles)
2608             (and (not (eq style 'parens))
2609                  ;; Use angles if no quoting is needed, or if parens would
2610                  ;; need quoting too.
2611                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2612                      (let ((tmp (concat fullname nil)))
2613                        (while (string-match "([^()]*)" tmp)
2614                          (aset tmp (match-beginning 0) ?-)
2615                          (aset tmp (1- (match-end 0)) ?-))
2616                        (string-match "[\\()]" tmp)))))
2617         (insert fullname)
2618         (goto-char (point-min))
2619         ;; Look for a character that cannot appear unquoted
2620         ;; according to RFC 822.
2621         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2622           ;; Quote fullname, escaping specials.
2623           (goto-char (point-min))
2624           (insert "\"")
2625           (while (re-search-forward "[\"\\]" nil 1)
2626             (replace-match "\\\\\\&" t))
2627           (insert "\""))
2628         (insert " <" login ">"))
2629        (t                               ; 'parens or default
2630         (insert login " (")
2631         (let ((fullname-start (point)))
2632           (insert fullname)
2633           (goto-char fullname-start)
2634           ;; RFC 822 says \ and nonmatching parentheses
2635           ;; must be escaped in comments.
2636           ;; Escape every instance of ()\ ...
2637           (while (re-search-forward "[()\\]" nil 1)
2638             (replace-match "\\\\\\&" t))
2639           ;; ... then undo escaping of matching parentheses,
2640           ;; including matching nested parentheses.
2641           (goto-char fullname-start)
2642           (while (re-search-forward
2643                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2644                   nil 1)
2645             (replace-match "\\1(\\3)" t)
2646             (goto-char fullname-start)))
2647         (insert ")")))
2648       (buffer-string))))
2649
2650 (defun message-make-sender ()
2651   "Return the \"real\" user address.
2652 This function tries to ignore all user modifications, and
2653 give as trustworthy answer as possible."
2654   (concat (user-login-name) "@" (system-name)))
2655
2656 (defun message-make-address ()
2657   "Make the address of the user."
2658   (or (message-user-mail-address)
2659       (concat (user-login-name) "@" (message-make-domain))))
2660
2661 (defun message-user-mail-address ()
2662   "Return the pertinent part of `user-mail-address'."
2663   (when user-mail-address
2664     (if (string-match " " user-mail-address)
2665         (nth 1 (mail-extract-address-components user-mail-address))
2666       user-mail-address)))
2667
2668 (defun message-make-fqdn ()
2669   "Return user's fully qualified domain name."
2670   (let ((system-name (system-name))
2671         (user-mail (message-user-mail-address)))
2672     (cond
2673      ((string-match "[^.]\\.[^.]" system-name)
2674       ;; `system-name' returned the right result.
2675       system-name)
2676      ;; Try `mail-host-address'.
2677      ((and (boundp 'mail-host-address)
2678            (stringp mail-host-address)
2679            (string-match "\\." mail-host-address))
2680       mail-host-address)
2681      ;; We try `user-mail-address' as a backup.
2682      ((and (string-match "\\." user-mail)
2683            (string-match "@\\(.*\\)\\'" user-mail))
2684       (match-string 1 user-mail))
2685      ;; Default to this bogus thing.
2686      (t
2687       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2688
2689 (defun message-make-host-name ()
2690   "Return the name of the host."
2691   (let ((fqdn (message-make-fqdn)))
2692     (string-match "^[^.]+\\." fqdn)
2693     (substring fqdn 0 (1- (match-end 0)))))
2694
2695 (defun message-make-domain ()
2696   "Return the domain name."
2697   (or mail-host-address
2698       (message-make-fqdn)))
2699
2700 (defun message-generate-headers (headers)
2701   "Prepare article HEADERS.
2702 Headers already prepared in the buffer are not modified."
2703   (save-restriction
2704     (message-narrow-to-headers)
2705     (let* ((Date (message-make-date))
2706            (Message-ID (message-make-message-id))
2707            (Organization (message-make-organization))
2708            (From (message-make-from))
2709            (Path (message-make-path))
2710            (Subject nil)
2711            (Newsgroups nil)
2712            (In-Reply-To (message-make-in-reply-to))
2713            (To nil)
2714            (Distribution (message-make-distribution))
2715            (Lines (message-make-lines))
2716            (X-Newsreader message-newsreader)
2717            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2718                           message-mailer))
2719            (Expires (message-make-expires))
2720            (case-fold-search t)
2721            header value elem)
2722       ;; First we remove any old generated headers.
2723       (let ((headers message-deletable-headers))
2724         (unless (buffer-modified-p)
2725           (setq headers (delq 'Message-ID (copy-sequence headers))))
2726         (while headers
2727           (goto-char (point-min))
2728           (and (re-search-forward
2729                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2730                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2731                (message-delete-line))
2732           (pop headers)))
2733       ;; Go through all the required headers and see if they are in the
2734       ;; articles already.  If they are not, or are empty, they are
2735       ;; inserted automatically - except for Subject, Newsgroups and
2736       ;; Distribution.
2737       (while headers
2738         (goto-char (point-min))
2739         (setq elem (pop headers))
2740         (if (consp elem)
2741             (if (eq (car elem) 'optional)
2742                 (setq header (cdr elem))
2743               (setq header (car elem)))
2744           (setq header elem))
2745         (when (or (not (re-search-forward
2746                         (concat "^" (downcase (symbol-name header)) ":")
2747                         nil t))
2748                   (progn
2749                     ;; The header was found.  We insert a space after the
2750                     ;; colon, if there is none.
2751                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2752                     ;; Find out whether the header is empty...
2753                     (looking-at "[ \t]*$")))
2754           ;; So we find out what value we should insert.
2755           (setq value
2756                 (cond
2757                  ((and (consp elem) (eq (car elem) 'optional))
2758                   ;; This is an optional header.  If the cdr of this
2759                   ;; is something that is nil, then we do not insert
2760                   ;; this header.
2761                   (setq header (cdr elem))
2762                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2763                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2764                  ((consp elem)
2765                   ;; The element is a cons.  Either the cdr is a
2766                   ;; string to be inserted verbatim, or it is a
2767                   ;; function, and we insert the value returned from
2768                   ;; this function.
2769                   (or (and (stringp (cdr elem)) (cdr elem))
2770                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2771                  ((and (boundp header) (symbol-value header))
2772                   ;; The element is a symbol.  We insert the value
2773                   ;; of this symbol, if any.
2774                   (symbol-value header))
2775                  (t
2776                   ;; We couldn't generate a value for this header,
2777                   ;; so we just ask the user.
2778                   (read-from-minibuffer
2779                    (format "Empty header for %s; enter value: " header)))))
2780           ;; Finally insert the header.
2781           (when (and value
2782                      (not (equal value "")))
2783             (save-excursion
2784               (if (bolp)
2785                   (progn
2786                     ;; This header didn't exist, so we insert it.
2787                     (goto-char (point-max))
2788                     (insert (symbol-name header) ": " value "\n")
2789                     (forward-line -1))
2790                 ;; The value of this header was empty, so we clear
2791                 ;; totally and insert the new value.
2792                 (delete-region (point) (gnus-point-at-eol))
2793                 (insert value))
2794               ;; Add the deletable property to the headers that require it.
2795               (and (memq header message-deletable-headers)
2796                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2797                    (add-text-properties
2798                     (point) (match-end 0)
2799                     '(message-deletable t face italic) (current-buffer)))))))
2800       ;; Insert new Sender if the From is strange.
2801       (let ((from (message-fetch-field "from"))
2802             (sender (message-fetch-field "sender"))
2803             (secure-sender (message-make-sender)))
2804         (when (and from
2805                    (not (message-check-element 'sender))
2806                    (not (string=
2807                          (downcase
2808                           (cadr (mail-extract-address-components from)))
2809                          (downcase secure-sender)))
2810                    (or (null sender)
2811                        (not
2812                         (string=
2813                          (downcase
2814                           (cadr (mail-extract-address-components sender)))
2815                          (downcase secure-sender)))))
2816           (goto-char (point-min))
2817           ;; Rename any old Sender headers to Original-Sender.
2818           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2819             (beginning-of-line)
2820             (insert "Original-")
2821             (beginning-of-line))
2822           (when (or (message-news-p)
2823                     (string-match "^[^@]@.+\\..+" secure-sender))
2824             (insert "Sender: " secure-sender "\n")))))))
2825
2826 (defun message-insert-courtesy-copy ()
2827   "Insert a courtesy message in mail copies of combined messages."
2828   (let (newsgroups)
2829     (save-excursion
2830       (save-restriction
2831         (message-narrow-to-headers)
2832         (when (setq newsgroups (message-fetch-field "newsgroups"))
2833           (goto-char (point-max))
2834           (insert "Posted-To: " newsgroups "\n")))
2835       (forward-line 1)
2836       (when message-courtesy-message
2837         (cond
2838          ((string-match "%s" message-courtesy-message)
2839           (insert (format message-courtesy-message newsgroups)))
2840          (t
2841           (insert message-courtesy-message)))))))
2842
2843 ;;;
2844 ;;; Setting up a message buffer
2845 ;;;
2846
2847 (defun message-fill-address (header value)
2848   (save-restriction
2849     (narrow-to-region (point) (point))
2850     (insert (capitalize (symbol-name header))
2851             ": "
2852             (if (consp value) (car value) value)
2853             "\n")
2854     (narrow-to-region (point-min) (1- (point-max)))
2855     (let (quoted last)
2856       (goto-char (point-min))
2857       (while (not (eobp))
2858         (skip-chars-forward "^,\"" (point-max))
2859         (if (or (= (following-char) ?,)
2860                 (eobp))
2861             (when (not quoted)
2862               (if (and (> (current-column) 78)
2863                        last)
2864                   (progn
2865                     (save-excursion
2866                       (goto-char last)
2867                       (insert "\n\t"))
2868                     (setq last (1+ (point))))
2869                 (setq last (1+ (point)))))
2870           (setq quoted (not quoted)))
2871         (unless (eobp)
2872           (forward-char 1))))
2873     (goto-char (point-max))
2874     (widen)
2875     (forward-line 1)))
2876
2877 (defun message-fill-header (header value)
2878   (let ((begin (point))
2879         (fill-column 78)
2880         (fill-prefix "\t"))
2881     (insert (capitalize (symbol-name header))
2882             ": "
2883             (if (consp value) (car value) value)
2884             "\n")
2885     (save-restriction
2886       (narrow-to-region begin (point))
2887       (fill-region-as-paragraph begin (point))
2888       ;; Tapdance around looong Message-IDs.
2889       (forward-line -1)
2890       (when (looking-at "[ \t]*$")
2891         (message-delete-line))
2892       (goto-char begin)
2893       (re-search-forward ":" nil t)
2894       (when (looking-at "\n[ \t]+")
2895         (replace-match " " t t))
2896       (goto-char (point-max)))))
2897
2898 (defun message-position-point ()
2899   "Move point to where the user probably wants to find it."
2900   (message-narrow-to-headers)
2901   (cond
2902    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2903     (search-backward ":" )
2904     (widen)
2905     (forward-char 1)
2906     (if (= (following-char) ? )
2907         (forward-char 1)
2908       (insert " ")))
2909    (t
2910     (goto-char (point-max))
2911     (widen)
2912     (forward-line 1)
2913     (unless (looking-at "$")
2914       (forward-line 2)))
2915    (sit-for 0)))
2916
2917 (defun message-buffer-name (type &optional to group)
2918   "Return a new (unique) buffer name based on TYPE and TO."
2919   (cond
2920    ;; Check whether `message-generate-new-buffers' is a function,
2921    ;; and if so, call it.
2922    ((message-functionp message-generate-new-buffers)
2923     (funcall message-generate-new-buffers type to group))
2924    ;; Generate a new buffer name The Message Way.
2925    (message-generate-new-buffers
2926     (generate-new-buffer-name
2927      (concat "*" type
2928              (if to
2929                  (concat " to "
2930                          (or (car (mail-extract-address-components to))
2931                              to) "")
2932                "")
2933              (if (and group (not (string= group ""))) (concat " on " group) "")
2934              "*")))
2935    ;; Use standard name.
2936    (t
2937     (format "*%s message*" type))))
2938
2939 (defun message-pop-to-buffer (name)
2940   "Pop to buffer NAME, and warn if it already exists and is modified."
2941   (let ((buffer (get-buffer name)))
2942     (if (and buffer
2943              (buffer-name buffer))
2944         (progn
2945           (set-buffer (pop-to-buffer buffer))
2946           (when (and (buffer-modified-p)
2947                      (not (y-or-n-p
2948                            "Message already being composed; erase? ")))
2949             (error "Message being composed")))
2950       (set-buffer (pop-to-buffer name))))
2951   (erase-buffer)
2952   (message-mode))
2953
2954 (defun message-do-send-housekeeping ()
2955   "Kill old message buffers."
2956   ;; We might have sent this buffer already.  Delete it from the
2957   ;; list of buffers.
2958   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2959   (while (and message-max-buffers
2960               message-buffer-list
2961               (>= (length message-buffer-list) message-max-buffers))
2962     ;; Kill the oldest buffer -- unless it has been changed.
2963     (let ((buffer (pop message-buffer-list)))
2964       (when (and (buffer-name buffer)
2965                  (not (buffer-modified-p buffer)))
2966         (kill-buffer buffer))))
2967   ;; Rename the buffer.
2968   (if message-send-rename-function
2969       (funcall message-send-rename-function)
2970     (when (string-match "\\`\\*" (buffer-name))
2971       (rename-buffer
2972        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2973   ;; Push the current buffer onto the list.
2974   (when message-max-buffers
2975     (setq message-buffer-list
2976           (nconc message-buffer-list (list (current-buffer))))))
2977
2978 (defvar mc-modes-alist)
2979 (defun message-setup (headers &optional replybuffer actions)
2980   (when (and (boundp 'mc-modes-alist)
2981              (not (assq 'message-mode mc-modes-alist)))
2982     (push '(message-mode (encrypt . mc-encrypt-message)
2983                          (sign . mc-sign-message))
2984           mc-modes-alist))
2985   (when actions
2986     (setq message-send-actions actions))
2987   (setq message-reply-buffer replybuffer)
2988   (goto-char (point-min))
2989   ;; Insert all the headers.
2990   (mail-header-format
2991    (let ((h headers)
2992          (alist message-header-format-alist))
2993      (while h
2994        (unless (assq (caar h) message-header-format-alist)
2995          (push (list (caar h)) alist))
2996        (pop h))
2997      alist)
2998    headers)
2999   (delete-region (point) (progn (forward-line -1) (point)))
3000   (when message-default-headers
3001     (insert message-default-headers))
3002   (put-text-property
3003    (point)
3004    (progn
3005      (insert mail-header-separator "\n")
3006      (1- (point)))
3007    'read-only nil)
3008   (forward-line -1)
3009   (when (message-news-p)
3010     (when message-default-news-headers
3011       (insert message-default-news-headers))
3012     (when message-generate-headers-first
3013       (message-generate-headers
3014        (delq 'Lines
3015              (delq 'Subject
3016                    (copy-sequence message-required-news-headers))))))
3017   (when (message-mail-p)
3018     (when message-default-mail-headers
3019       (insert message-default-mail-headers))
3020     (when message-generate-headers-first
3021       (message-generate-headers
3022        (delq 'Lines
3023              (delq 'Subject
3024                    (copy-sequence message-required-mail-headers))))))
3025   (run-hooks 'message-signature-setup-hook)
3026   (message-insert-signature)
3027   (save-restriction
3028     (message-narrow-to-headers)
3029     (run-hooks 'message-header-setup-hook))
3030   (set-buffer-modified-p nil)
3031   (setq buffer-undo-list nil)
3032   (run-hooks 'message-setup-hook)
3033   (message-position-point)
3034   (undo-boundary))
3035
3036 (defun message-set-auto-save-file-name ()
3037   "Associate the message buffer with a file in the drafts directory."
3038   (when message-autosave-directory
3039     (setq message-draft-article (nndraft-request-associate-buffer "drafts"))
3040     (clear-visited-file-modtime)))
3041
3042 (defun message-disassociate-draft ()
3043   "Disassociate the message buffer from the drafts directory."
3044   (when message-draft-article
3045     (nndraft-request-expire-articles
3046      (list message-draft-article) "drafts" nil t)))
3047
3048 \f
3049
3050 ;;;
3051 ;;; Commands for interfacing with message
3052 ;;;
3053
3054 ;;;###autoload
3055 (defun message-mail (&optional to subject
3056                                other-headers continue switch-function
3057                                yank-action send-actions)
3058   "Start editing a mail message to be sent."
3059   (interactive)
3060   (let ((message-this-is-mail t))
3061     (message-pop-to-buffer (message-buffer-name "mail" to))
3062     (message-setup
3063      (nconc
3064       `((To . ,(or to "")) (Subject . ,(or subject "")))
3065       (when other-headers other-headers)))))
3066
3067 ;;;###autoload
3068 (defun message-news (&optional newsgroups subject)
3069   "Start editing a news article to be sent."
3070   (interactive)
3071   (let ((message-this-is-news t))
3072     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3073     (message-setup `((Newsgroups . ,(or newsgroups ""))
3074                      (Subject . ,(or subject ""))))))
3075
3076 ;;;###autoload
3077 (defun message-reply (&optional to-address wide ignore-reply-to)
3078   "Start editing a reply to the article in the current buffer."
3079   (interactive)
3080   (let ((cur (current-buffer))
3081         from subject date reply-to to cc
3082         references message-id follow-to
3083         (inhibit-point-motion-hooks t)
3084         mct never-mct gnus-warning)
3085     (save-restriction
3086       (message-narrow-to-head)
3087       ;; Allow customizations to have their say.
3088       (if (not wide)
3089           ;; This is a regular reply.
3090           (if (message-functionp message-reply-to-function)
3091               (setq follow-to (funcall message-reply-to-function)))
3092         ;; This is a followup.
3093         (if (message-functionp message-wide-reply-to-function)
3094             (save-excursion
3095               (setq follow-to
3096                     (funcall message-wide-reply-to-function)))))
3097       ;; Find all relevant headers we need.
3098       (setq from (message-fetch-field "from")
3099             date (message-fetch-field "date")
3100             subject (or (message-fetch-field "subject") "none")
3101             to (message-fetch-field "to")
3102             cc (message-fetch-field "cc")
3103             mct (message-fetch-field "mail-copies-to")
3104             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
3105             references (message-fetch-field "references")
3106             message-id (message-fetch-field "message-id" t))
3107       ;; Remove any (buggy) Re:'s that are present and make a
3108       ;; proper one.
3109       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3110         (setq subject (substring subject (match-end 0))))
3111       (setq subject (concat "Re: " subject))
3112
3113       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3114                  (string-match "<[^>]+>" gnus-warning))
3115         (setq message-id (match-string 0 gnus-warning)))
3116
3117       ;; Handle special values of Mail-Copies-To.
3118       (when mct
3119         (cond ((equal (downcase mct) "never")
3120                (setq never-mct t)
3121                (setq mct nil))
3122               ((equal (downcase mct) "always")
3123                (setq mct (or reply-to from)))))
3124
3125       (unless follow-to
3126         (if (or (not wide)
3127                 to-address)
3128             (setq follow-to (list (cons 'To (or to-address reply-to from))))
3129           (let (ccalist)
3130             (save-excursion
3131               (message-set-work-buffer)
3132               (unless never-mct
3133                 (insert (or reply-to from "")))
3134               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3135               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3136               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3137               (goto-char (point-min))
3138               (while (re-search-forward "[ \t]+" nil t)
3139                 (replace-match " " t t))
3140               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3141               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3142                         (erase-buffer)))
3143               (goto-char (point-min))
3144               ;; Perhaps Mail-Copies-To: never removed the only address?
3145               (when (eobp)
3146                 (insert (or reply-to from "")))
3147               (setq ccalist
3148                     (mapcar
3149                      (lambda (addr)
3150                        (cons (mail-strip-quoted-names addr) addr))
3151                      (message-tokenize-header (buffer-string))))
3152               (let ((s ccalist))
3153                 (while s
3154                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3155             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3156             (when ccalist
3157               (let ((ccs (cons 'Cc (mapconcat
3158                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3159                 (when (string-match "^ +" (cdr ccs))
3160                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3161                 (push ccs follow-to))))))
3162       (widen))
3163
3164     (message-pop-to-buffer (message-buffer-name
3165                             (if wide "wide reply" "reply") from
3166                             (if wide to-address nil)))
3167
3168     (setq message-reply-headers
3169           (vector 0 subject from date message-id references 0 0 ""))
3170
3171     (message-setup
3172      `((Subject . ,subject)
3173        ,@follow-to
3174        ,@(if (or references message-id)
3175              `((References . ,(concat (or references "") (and references " ")
3176                                       (or message-id ""))))
3177            nil))
3178      cur)))
3179
3180 ;;;###autoload
3181 (defun message-wide-reply (&optional to-address ignore-reply-to)
3182   "Make a \"wide\" reply to the message in the current buffer."
3183   (interactive)
3184   (message-reply to-address t ignore-reply-to))
3185
3186 ;;;###autoload
3187 (defun message-followup (&optional to-newsgroups)
3188   "Follow up to the message in the current buffer.
3189 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3190   (interactive)
3191   (let ((cur (current-buffer))
3192         from subject date reply-to mct
3193         references message-id follow-to
3194         (inhibit-point-motion-hooks t)
3195         (message-this-is-news t)
3196         followup-to distribution newsgroups gnus-warning posted-to)
3197     (save-restriction
3198       (narrow-to-region
3199        (goto-char (point-min))
3200        (if (search-forward "\n\n" nil t)
3201            (1- (point))
3202          (point-max)))
3203       (when (message-functionp message-followup-to-function)
3204         (setq follow-to
3205               (funcall message-followup-to-function)))
3206       (setq from (message-fetch-field "from")
3207             date (message-fetch-field "date")
3208             subject (or (message-fetch-field "subject") "none")
3209             references (message-fetch-field "references")
3210             message-id (message-fetch-field "message-id" t)
3211             followup-to (message-fetch-field "followup-to")
3212             newsgroups (message-fetch-field "newsgroups")
3213             posted-to (message-fetch-field "posted-to")
3214             reply-to (message-fetch-field "reply-to")
3215             distribution (message-fetch-field "distribution")
3216             mct (message-fetch-field "mail-copies-to"))
3217       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3218                  (string-match "<[^>]+>" gnus-warning))
3219         (setq message-id (match-string 0 gnus-warning)))
3220       ;; Remove bogus distribution.
3221       (when (and (stringp distribution)
3222                  (let ((case-fold-search t))
3223                    (string-match "world" distribution)))
3224         (setq distribution nil))
3225       ;; Remove any (buggy) Re:'s that are present and make a
3226       ;; proper one.
3227       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3228         (setq subject (substring subject (match-end 0))))
3229       (setq subject (concat "Re: " subject))
3230       (widen))
3231
3232     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3233
3234     (message-setup
3235      `((Subject . ,subject)
3236        ,@(cond
3237           (to-newsgroups
3238            (list (cons 'Newsgroups to-newsgroups)))
3239           (follow-to follow-to)
3240           ((and followup-to message-use-followup-to)
3241            (list
3242             (cond
3243              ((equal (downcase followup-to) "poster")
3244               (if (or (eq message-use-followup-to 'use)
3245                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3246 You should normally obey the Followup-To: header.
3247
3248 `Followup-To: poster' sends your response via e-mail instead of news.
3249
3250 A typical situation where `Followup-To: poster' is used is when the poster
3251 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3252                   (progn
3253                     (setq message-this-is-news nil)
3254                     (cons 'To (or reply-to from "")))
3255                 (cons 'Newsgroups newsgroups)))
3256              (t
3257               (if (or (equal followup-to newsgroups)
3258                       (not (eq message-use-followup-to 'ask))
3259                       (message-y-or-n-p
3260                        (concat "Obey Followup-To: " followup-to "? ") t "\
3261 You should normally obey the Followup-To: header.
3262
3263         `Followup-To: " followup-to "'
3264 directs your response to " (if (string-match "," followup-to)
3265                                "the specified newsgroups"
3266                              "that newsgroup only") ".
3267
3268 If a message is posted to several newsgroups, Followup-To is often
3269 used to direct the following discussion to one newsgroup only,
3270 because discussions that are spread over several newsgroup tend to
3271 be fragmented and very difficult to follow.
3272
3273 Also, some source/announcement newsgroups are not indented for discussion;
3274 responses here are directed to other newsgroups."))
3275                   (cons 'Newsgroups followup-to)
3276                 (cons 'Newsgroups newsgroups))))))
3277           (posted-to
3278            `((Newsgroups . ,posted-to)))
3279           (t
3280            `((Newsgroups . ,newsgroups))))
3281        ,@(and distribution (list (cons 'Distribution distribution)))
3282        ,@(if (or references message-id)
3283              `((References . ,(concat (or references "") (and references " ")
3284                                       (or message-id "")))))
3285        ,@(when (and mct
3286                     (not (equal (downcase mct) "never")))
3287            (list (cons 'Cc (if (equal (downcase mct) "always")
3288                                (or reply-to from "")
3289                              mct)))))
3290
3291      cur)
3292
3293     (setq message-reply-headers
3294           (vector 0 subject from date message-id references 0 0 ""))))
3295
3296
3297 ;;;###autoload
3298 (defun message-cancel-news ()
3299   "Cancel an article you posted."
3300   (interactive)
3301   (unless (message-news-p)
3302     (error "This is not a news article; canceling is impossible"))
3303   (when (yes-or-no-p "Do you really want to cancel this article? ")
3304     (let (from newsgroups message-id distribution buf)
3305       (save-excursion
3306         ;; Get header info. from original article.
3307         (save-restriction
3308           (message-narrow-to-head)
3309           (setq from (message-fetch-field "from")
3310                 newsgroups (message-fetch-field "newsgroups")
3311                 message-id (message-fetch-field "message-id" t)
3312                 distribution (message-fetch-field "distribution")))
3313         ;; Make sure that this article was written by the user.
3314         (unless (string-equal
3315                  (downcase (cadr (mail-extract-address-components from)))
3316                  (downcase (message-make-address)))
3317           (error "This article is not yours"))
3318         ;; Make control message.
3319         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3320         (buffer-disable-undo (current-buffer))
3321         (erase-buffer)
3322         (insert "Newsgroups: " newsgroups "\n"
3323                 "From: " (message-make-from) "\n"
3324                 "Subject: cmsg cancel " message-id "\n"
3325                 "Control: cancel " message-id "\n"
3326                 (if distribution
3327                     (concat "Distribution: " distribution "\n")
3328                   "")
3329                 mail-header-separator "\n"
3330                 message-cancel-message)
3331         (message "Canceling your article...")
3332         (if (let ((message-syntax-checks
3333                    'dont-check-for-anything-just-trust-me))
3334               (funcall message-send-news-function))
3335             (message "Canceling your article...done"))
3336         (kill-buffer buf)))))
3337
3338 ;;;###autoload
3339 (defun message-supersede ()
3340   "Start composing a message to supersede the current message.
3341 This is done simply by taking the old article and adding a Supersedes
3342 header line with the old Message-ID."
3343   (interactive)
3344   (let ((cur (current-buffer)))
3345     ;; Check whether the user owns the article that is to be superseded.
3346     (unless (string-equal
3347              (downcase (cadr (mail-extract-address-components
3348                               (message-fetch-field "from"))))
3349              (downcase (message-make-address)))
3350       (error "This article is not yours"))
3351     ;; Get a normal message buffer.
3352     (message-pop-to-buffer (message-buffer-name "supersede"))
3353     (insert-buffer-substring cur)
3354     (message-narrow-to-head)
3355     ;; Remove unwanted headers.
3356     (when message-ignored-supersedes-headers
3357       (message-remove-header message-ignored-supersedes-headers t))
3358     (goto-char (point-min))
3359     (if (not (re-search-forward "^Message-ID: " nil t))
3360         (error "No Message-ID in this article")
3361       (replace-match "Supersedes: " t t))
3362     (goto-char (point-max))
3363     (insert mail-header-separator)
3364     (widen)
3365     (forward-line 1)))
3366
3367 ;;;###autoload
3368 (defun message-recover ()
3369   "Reread contents of current buffer from its last auto-save file."
3370   (interactive)
3371   (let ((file-name (make-auto-save-file-name)))
3372     (cond ((save-window-excursion
3373              (if (not (eq system-type 'vax-vms))
3374                  (with-output-to-temp-buffer "*Directory*"
3375                    (buffer-disable-undo standard-output)
3376                    (let ((default-directory "/"))
3377                      (call-process
3378                       "ls" nil standard-output nil "-l" file-name))))
3379              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3380            (let ((buffer-read-only nil))
3381              (erase-buffer)
3382              (insert-file-contents file-name nil)))
3383           (t (error "message-recover cancelled")))))
3384
3385 ;;; Forwarding messages.
3386
3387 (defun message-make-forward-subject ()
3388   "Return a Subject header suitable for the message in the current buffer."
3389   (save-excursion
3390     (save-restriction
3391       (current-buffer)
3392       (message-narrow-to-head)
3393       (concat "[" (or (message-fetch-field
3394                        (if (message-news-p) "newsgroups" "from"))
3395                       "(nowhere)")
3396               "] " (or (message-fetch-field "Subject") "")))))
3397
3398 ;;;###autoload
3399 (defun message-forward (&optional news)
3400   "Forward the current message via mail.
3401 Optional NEWS will use news to forward instead of mail."
3402   (interactive "P")
3403   (let ((cur (current-buffer))
3404         (subject (message-make-forward-subject))
3405         art-beg)
3406     (if news (message-news nil subject) (message-mail nil subject))
3407     ;; Put point where we want it before inserting the forwarded
3408     ;; message.
3409     (if message-signature-before-forwarded-message
3410         (goto-char (point-max))
3411       (message-goto-body))
3412     ;; Make sure we're at the start of the line.
3413     (unless (eolp)
3414       (insert "\n"))
3415     ;; Narrow to the area we are to insert.
3416     (narrow-to-region (point) (point))
3417     ;; Insert the separators and the forwarded buffer.
3418     (insert message-forward-start-separator)
3419     (setq art-beg (point))
3420     (insert-buffer-substring cur)
3421     (goto-char (point-max))
3422     (insert message-forward-end-separator)
3423     (set-text-properties (point-min) (point-max) nil)
3424     ;; Remove all unwanted headers.
3425     (goto-char art-beg)
3426     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3427                                   (1- (point))
3428                                 (point)))
3429     (goto-char (point-min))
3430     (message-remove-header message-included-forward-headers t nil t)
3431     (widen)
3432     (message-position-point)))
3433
3434 ;;;###autoload
3435 (defun message-resend (address)
3436   "Resend the current article to ADDRESS."
3437   (interactive "sResend message to: ")
3438   (message "Resending message to %s..." address)
3439   (save-excursion
3440     (let ((cur (current-buffer))
3441           beg)
3442       ;; We first set up a normal mail buffer.
3443       (set-buffer (get-buffer-create " *message resend*"))
3444       (buffer-disable-undo (current-buffer))
3445       (erase-buffer)
3446       (message-setup `((To . ,address)))
3447       ;; Insert our usual headers.
3448       (message-generate-headers '(From Date To))
3449       (message-narrow-to-headers)
3450       ;; Rename them all to "Resent-*".
3451       (while (re-search-forward "^[A-Za-z]" nil t)
3452         (forward-char -1)
3453         (insert "Resent-"))
3454       (widen)
3455       (forward-line)
3456       (delete-region (point) (point-max))
3457       (setq beg (point))
3458       ;; Insert the message to be resent.
3459       (insert-buffer-substring cur)
3460       (goto-char (point-min))
3461       (search-forward "\n\n")
3462       (forward-char -1)
3463       (save-restriction
3464         (narrow-to-region beg (point))
3465         (message-remove-header message-ignored-resent-headers t)
3466         (goto-char (point-max)))
3467       (insert mail-header-separator)
3468       ;; Rename all old ("Also-")Resent headers.
3469       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
3470         (beginning-of-line)
3471         (insert "Also-"))
3472       ;; Quote any "From " lines at the beginning.
3473       (goto-char beg)
3474       (when (looking-at "From ")
3475         (replace-match "X-From-Line: "))
3476       ;; Send it.
3477       (message-send-mail)
3478       (kill-buffer (current-buffer)))
3479     (message "Resending message to %s...done" address)))
3480
3481 ;;;###autoload
3482 (defun message-bounce ()
3483   "Re-mail the current message.
3484 This only makes sense if the current message is a bounce message than
3485 contains some mail you have written which has been bounced back to
3486 you."
3487   (interactive)
3488   (let ((cur (current-buffer))
3489         boundary)
3490     (message-pop-to-buffer (message-buffer-name "bounce"))
3491     (insert-buffer-substring cur)
3492     (undo-boundary)
3493     (message-narrow-to-head)
3494     (if (and (message-fetch-field "Mime-Version")
3495              (setq boundary (message-fetch-field "Content-Type")))
3496         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3497             (setq boundary (concat (match-string 1 boundary) " *\n"
3498                                    "Content-Type: message/rfc822"))
3499           (setq boundary nil)))
3500     (widen)
3501     (goto-char (point-min))
3502     (search-forward "\n\n" nil t)
3503     (or (and boundary
3504              (re-search-forward boundary nil t)
3505              (forward-line 2))
3506         (and (re-search-forward message-unsent-separator nil t)
3507              (forward-line 1))
3508         (re-search-forward "^Return-Path:.*\n" nil t))
3509     ;; We remove everything before the bounced mail.
3510     (delete-region
3511      (point-min)
3512      (if (re-search-forward "^[^ \n\t]+:" nil t)
3513          (match-beginning 0)
3514        (point)))
3515     (save-restriction
3516       (message-narrow-to-head)
3517       (message-remove-header message-ignored-bounced-headers t)
3518       (goto-char (point-max))
3519       (insert mail-header-separator))
3520     (message-position-point)))
3521
3522 ;;;
3523 ;;; Interactive entry points for new message buffers.
3524 ;;;
3525
3526 ;;;###autoload
3527 (defun message-mail-other-window (&optional to subject)
3528   "Like `message-mail' command, but display mail buffer in another window."
3529   (interactive)
3530   (let ((pop-up-windows t)
3531         (special-display-buffer-names nil)
3532         (special-display-regexps nil)
3533         (same-window-buffer-names nil)
3534         (same-window-regexps nil))
3535     (message-pop-to-buffer (message-buffer-name "mail" to)))
3536   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3537
3538 ;;;###autoload
3539 (defun message-mail-other-frame (&optional to subject)
3540   "Like `message-mail' command, but display mail buffer in another frame."
3541   (interactive)
3542   (let ((pop-up-frames t)
3543         (special-display-buffer-names nil)
3544         (special-display-regexps nil)
3545         (same-window-buffer-names nil)
3546         (same-window-regexps nil))
3547     (message-pop-to-buffer (message-buffer-name "mail" to)))
3548   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3549
3550 ;;;###autoload
3551 (defun message-news-other-window (&optional newsgroups subject)
3552   "Start editing a news article to be sent."
3553   (interactive)
3554   (let ((pop-up-windows t)
3555         (special-display-buffer-names nil)
3556         (special-display-regexps nil)
3557         (same-window-buffer-names nil)
3558         (same-window-regexps nil))
3559     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3560   (message-setup `((Newsgroups . ,(or newsgroups ""))
3561                    (Subject . ,(or subject "")))))
3562
3563 ;;;###autoload
3564 (defun message-news-other-frame (&optional newsgroups subject)
3565   "Start editing a news article to be sent."
3566   (interactive)
3567   (let ((pop-up-frames t)
3568         (special-display-buffer-names nil)
3569         (special-display-regexps nil)
3570         (same-window-buffer-names nil)
3571         (same-window-regexps nil))
3572     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3573   (message-setup `((Newsgroups . ,(or newsgroups ""))
3574                    (Subject . ,(or subject "")))))
3575
3576 ;;; underline.el
3577
3578 ;; This code should be moved to underline.el (from which it is stolen).
3579
3580 ;;;###autoload
3581 (defun bold-region (start end)
3582   "Bold all nonblank characters in the region.
3583 Works by overstriking characters.
3584 Called from program, takes two arguments START and END
3585 which specify the range to operate on."
3586   (interactive "r")
3587   (save-excursion
3588     (let ((end1 (make-marker)))
3589       (move-marker end1 (max start end))
3590       (goto-char (min start end))
3591       (while (< (point) end1)
3592         (or (looking-at "[_\^@- ]")
3593             (insert (following-char) "\b"))
3594         (forward-char 1)))))
3595
3596 ;;;###autoload
3597 (defun unbold-region (start end)
3598   "Remove all boldness (overstruck characters) in the region.
3599 Called from program, takes two arguments START and END
3600 which specify the range to operate on."
3601   (interactive "r")
3602   (save-excursion
3603     (let ((end1 (make-marker)))
3604       (move-marker end1 (max start end))
3605       (goto-char (min start end))
3606       (while (re-search-forward "\b" end1 t)
3607         (if (eq (following-char) (char-after (- (point) 2)))
3608             (delete-char -2))))))
3609
3610 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3611
3612 ;; Support for toolbar
3613 (when (string-match "XEmacs\\|Lucid" emacs-version)
3614   (require 'messagexmas))
3615
3616 ;;; Group name completion.
3617
3618 (defvar message-newgroups-header-regexp
3619   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
3620   "Regexp that match headers that lists groups.")
3621
3622 (defun message-tab ()
3623   "Expand group names in Newsgroups and Followup-To headers.
3624 Do a `tab-to-tab-stop' if not in those headers."
3625   (interactive)
3626   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3627         (mail-abbrev-in-expansion-header-p))
3628       (message-expand-group)
3629     (tab-to-tab-stop)))
3630
3631 (defvar gnus-active-hashtb)
3632 (defun message-expand-group ()
3633   (let* ((b (save-excursion
3634               (save-restriction
3635                 (narrow-to-region
3636                  (save-excursion
3637                    (beginning-of-line)
3638                    (skip-chars-forward "^:")
3639                    (1+ (point)))
3640                  (point))
3641                 (skip-chars-backward "^, \t\n") (point))))
3642          (completion-ignore-case t)
3643          (string (buffer-substring b (point)))
3644          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3645          (completions (all-completions string hashtb))
3646          (cur (current-buffer))
3647          comp)
3648     (delete-region b (point))
3649     (cond
3650      ((= (length completions) 1)
3651       (if (string= (car completions) string)
3652           (progn
3653             (insert string)
3654             (message "Only matching group"))
3655         (insert (car completions))))
3656      ((and (setq comp (try-completion string hashtb))
3657            (not (string= comp string)))
3658       (insert comp))
3659      (t
3660       (insert string)
3661       (if (not comp)
3662           (message "No matching groups")
3663         (save-selected-window
3664           (pop-to-buffer "*Completions*")
3665           (buffer-disable-undo (current-buffer))
3666           (let ((buffer-read-only nil))
3667             (erase-buffer)
3668             (let ((standard-output (current-buffer)))
3669               (display-completion-list (sort completions 'string<)))
3670             (goto-char (point-min))
3671             (delete-region (point) (progn (forward-line 3) (point))))))))))
3672
3673 ;;; Help stuff.
3674
3675 (defun message-talkative-question (ask question show &rest text)
3676   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
3677 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
3678 The following arguments may contain lists of values."
3679   (if (and show
3680            (setq text (message-flatten-list text)))
3681       (save-window-excursion
3682         (save-excursion
3683           (with-output-to-temp-buffer " *MESSAGE information message*"
3684             (set-buffer " *MESSAGE information message*")
3685             (mapcar 'princ text)
3686             (goto-char (point-min))))
3687         (funcall ask question))
3688     (funcall ask question)))
3689
3690 (defun message-flatten-list (list)
3691   "Return a new, flat list that contains all elements of LIST.
3692
3693 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3694 => (1 2 3 4 5 6 7)"
3695   (cond ((consp list)
3696          (apply 'append (mapcar 'message-flatten-list list)))
3697         (list
3698          (list list))))
3699
3700 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3701   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3702 Then clone the local variables and values from the old buffer to the
3703 new one, cloning only the locals having a substring matching the
3704 regexp varstr."
3705   (let ((oldbuf (current-buffer)))
3706     (save-excursion
3707       (set-buffer (generate-new-buffer name))
3708       (message-clone-locals oldbuf)
3709       (current-buffer))))
3710
3711 (defun message-clone-locals (buffer)
3712   "Clone the local variables from BUFFER to the current buffer."
3713   (let ((locals (save-excursion
3714                   (set-buffer buffer)
3715                   (buffer-local-variables)))
3716         (regexp "^gnus\\|^nn\\|^message"))
3717     (mapcar
3718      (lambda (local)
3719        (when (and (consp local)
3720                   (car local)
3721                   (string-match regexp (symbol-name (car local))))
3722          (ignore-errors
3723            (set (make-local-variable (car local))
3724                 (cdr local)))))
3725      locals)))
3726
3727 (run-hooks 'message-load-hook)
3728
3729 (provide 'message)
3730
3731 ;;; message.el ends here