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