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