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