* lisp/message.el (message-send-mail-with-smtp): Change error handling 'cause delete...
[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:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:"
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 (static-if (fboundp 'smtp-send-buffer)
3073                           (condition-case error
3074                               (progn
3075                                 (smtp-send-buffer user-mail-address recipients
3076                                                   (current-buffer))
3077                                 t)
3078                             (error
3079                              (format "%d %s"
3080                                      (car (cdr error)) (cdr (cdr error)))))
3081                         (smtp-via-smtp user-mail-address
3082                                        recipients
3083                                        (current-buffer)))))
3084           (unless (eq result t)
3085             (error "Sending failed; %s" result)))
3086       (error "Sending failed; no recipients"))))
3087
3088 (defsubst message-maybe-split-and-send-news (method)
3089   "Split a message if necessary, and send it via news.
3090 Returns nil if sending succeeded, returns t if sending failed.
3091 This sub function is for exclusive use of `message-send-news'."
3092   (let ((mime-edit-split-ignored-field-regexp
3093          mime-edit-split-ignored-field-regexp)
3094         (case-fold-search t))
3095     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3096       (setq mime-edit-split-ignored-field-regexp
3097             (concat (substring mime-edit-split-ignored-field-regexp
3098                                0 (match-beginning 0))
3099                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3100                     "_so_don't_rape_it!"
3101                     (substring mime-edit-split-ignored-field-regexp
3102                                (match-end 0)))))
3103     (or
3104      (catch 'message-sending-news-failure
3105        (mime-edit-maybe-split-and-send
3106         (function
3107          (lambda ()
3108            (interactive)
3109            (save-restriction
3110              (std11-narrow-to-header mail-header-separator)
3111              (goto-char (point-min))
3112              (when (re-search-forward "^Message-ID:" nil t)
3113                (delete-region (match-end 0) (std11-field-end))
3114                (insert " " (message-make-message-id))))
3115            (unless (funcall message-send-news-function method)
3116              (throw 'message-sending-news-failure t)))))
3117        nil)
3118      (not (funcall message-send-news-function method)))))
3119
3120 (defun message-send-news (&optional arg)
3121   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3122          (case-fold-search nil)
3123          (method (if (message-functionp message-post-method)
3124                      (funcall message-post-method arg)
3125                    message-post-method))
3126          (group-name-charset (gnus-group-name-charset method ""))
3127          (message-syntax-checks
3128           (if arg
3129               (cons '(existing-newsgroups . disabled)
3130                     message-syntax-checks)
3131             message-syntax-checks))
3132          (message-this-is-news t)
3133          result)
3134     (save-restriction
3135       (message-narrow-to-headers)
3136       ;; Insert some headers.
3137       (message-generate-headers message-required-news-headers)
3138       ;; Let the user do all of the above.
3139       (run-hooks 'message-header-hook))
3140     (if group-name-charset
3141         (setq message-syntax-checks
3142               (cons '(valid-newsgroups . disabled)
3143                     message-syntax-checks)))
3144     (message-cleanup-headers)
3145     (if (not (message-check-news-syntax))
3146         nil
3147       (unwind-protect
3148           (save-excursion
3149             (set-buffer tembuf)
3150             (buffer-disable-undo)
3151             (erase-buffer)
3152             (insert-buffer message-encoding-buffer)
3153             ;; Remove some headers.
3154             (save-restriction
3155               (message-narrow-to-headers)
3156 ;; We Semi-gnus people have no use for it.
3157 ;;            ;; We (re)generate the Lines header.
3158 ;;            (when (memq 'Lines message-required-mail-headers)
3159 ;;              (message-generate-headers '(Lines)))
3160               ;; Remove some headers.
3161               (message-remove-header message-ignored-news-headers t))
3162             (goto-char (point-max))
3163             ;; require one newline at the end.
3164             (or (= (preceding-char) ?\n)
3165                 (insert ?\n))
3166             (setq result (message-maybe-split-and-send-news method)))
3167         (kill-buffer tembuf))
3168       (set-buffer message-edit-buffer)
3169       (if result
3170           (progn
3171             (message "Couldn't send message via news: %s"
3172                      (nnheader-get-report (car method)))
3173             nil)
3174         (push 'news message-sent-message-via)))))
3175
3176 ;; 1997-09-29 by MORIOKA Tomohiko
3177 (defun message-send-news-with-gnus (method)
3178   (let ((case-fold-search t))
3179     ;; Remove the delimiter.
3180     (goto-char (point-min))
3181     (re-search-forward
3182      (concat "^" (regexp-quote mail-header-separator) "\n"))
3183     (replace-match "\n")
3184     (backward-char 1)
3185     (run-hooks 'message-send-news-hook)
3186     (gnus-open-server method)
3187     (gnus-request-post method)
3188     ))
3189
3190 ;;;
3191 ;;; Header generation & syntax checking.
3192 ;;;
3193
3194 (defun message-check-element (type)
3195   "Returns non-nil if this type is not to be checked."
3196   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3197       t
3198     (let ((able (assq type message-syntax-checks)))
3199       (and (consp able)
3200            (eq (cdr able) 'disabled)))))
3201
3202 (defun message-check-news-syntax ()
3203   "Check the syntax of the message."
3204   (save-excursion
3205     (save-restriction
3206       (widen)
3207       (and
3208        ;; We narrow to the headers and check them first.
3209        (save-excursion
3210          (save-restriction
3211            (message-narrow-to-headers)
3212            (message-check-news-header-syntax)))
3213        ;; Check the body.
3214        (save-excursion
3215          (set-buffer message-edit-buffer)
3216          (message-check-news-body-syntax))))))
3217
3218 (defun message-check-news-header-syntax ()
3219   (and
3220    ;; Check Newsgroups header.
3221    (message-check 'newsgroups
3222      (let ((group (message-fetch-field "newsgroups")))
3223        (or
3224         (and group
3225              (not (string-match "\\`[ \t]*\\'" group)))
3226         (ignore
3227          (message
3228           "The newsgroups field is empty or missing.  Posting is denied.")))))
3229    ;; Check the Subject header.
3230    (message-check 'subject
3231      (let* ((case-fold-search t)
3232             (subject (message-fetch-field "subject")))
3233        (or
3234         (and subject
3235              (not (string-match "\\`[ \t]*\\'" subject)))
3236         (ignore
3237          (message
3238           "The subject field is empty or missing.  Posting is denied.")))))
3239    ;; Check for commands in Subject.
3240    (message-check 'subject-cmsg
3241      (if (string-match "^cmsg " (message-fetch-field "subject"))
3242          (y-or-n-p
3243           "The control code \"cmsg\" is in the subject.  Really post? ")
3244        t))
3245    ;; Check for multiple identical headers.
3246    (message-check 'multiple-headers
3247      (let (found)
3248        (while (and (not found)
3249                    (re-search-forward "^[^ \t:]+: " nil t))
3250          (save-excursion
3251            (or (re-search-forward
3252                 (concat "^"
3253                         (regexp-quote
3254                          (setq found
3255                                (buffer-substring
3256                                 (match-beginning 0) (- (match-end 0) 2))))
3257                         ":")
3258                 nil t)
3259                (setq found nil))))
3260        (if found
3261            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3262          t)))
3263    ;; Check for Version and Sendsys.
3264    (message-check 'sendsys
3265      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3266          (y-or-n-p
3267           (format "The article contains a %s command.  Really post? "
3268                   (buffer-substring (match-beginning 0)
3269                                     (1- (match-end 0)))))
3270        t))
3271    ;; See whether we can shorten Followup-To.
3272    (message-check 'shorten-followup-to
3273      (let ((newsgroups (message-fetch-field "newsgroups"))
3274            (followup-to (message-fetch-field "followup-to"))
3275            to)
3276        (when (and newsgroups
3277                   (string-match "," newsgroups)
3278                   (not followup-to)
3279                   (not
3280                    (zerop
3281                     (length
3282                      (setq to (completing-read
3283                                "Followups to: (default all groups) "
3284                                (mapcar (lambda (g) (list g))
3285                                        (cons "poster"
3286                                              (message-tokenize-header
3287                                               newsgroups)))))))))
3288          (goto-char (point-min))
3289          (insert "Followup-To: " to "\n"))
3290        t))
3291    ;; Check "Shoot me".
3292    (message-check 'shoot
3293      (if (re-search-forward
3294           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3295          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3296        t))
3297    ;; Check for Approved.
3298    (message-check 'approved
3299      (if (re-search-forward "^Approved:" nil t)
3300          (y-or-n-p "The article contains an Approved header.  Really post? ")
3301        t))
3302    ;; Check the Message-ID header.
3303    (message-check 'message-id
3304      (let* ((case-fold-search t)
3305             (message-id (message-fetch-field "message-id" t)))
3306        (or (not message-id)
3307            ;; Is there an @ in the ID?
3308            (and (string-match "@" message-id)
3309                 ;; Is there a dot in the ID?
3310                 (string-match "@[^.]*\\." message-id)
3311                 ;; Does the ID end with a dot?
3312                 (not (string-match "\\.>" message-id)))
3313            (y-or-n-p
3314             (format "The Message-ID looks strange: \"%s\".  Really post? "
3315                     message-id)))))
3316    ;; Check the Newsgroups & Followup-To headers.
3317    (message-check 'existing-newsgroups
3318      (let* ((case-fold-search t)
3319             (newsgroups (message-fetch-field "newsgroups"))
3320             (followup-to (message-fetch-field "followup-to"))
3321             (groups (message-tokenize-header
3322                      (if followup-to
3323                          (concat newsgroups "," followup-to)
3324                        newsgroups)))
3325             (hashtb (and (boundp 'gnus-active-hashtb)
3326                          gnus-active-hashtb))
3327             errors)
3328        (if (or (not hashtb)
3329                (not (boundp 'gnus-read-active-file))
3330                (not gnus-read-active-file)
3331                (eq gnus-read-active-file 'some))
3332            t
3333          (while groups
3334            (when (and (not (boundp (intern (car groups) hashtb)))
3335                       (not (equal (car groups) "poster")))
3336              (push (car groups) errors))
3337            (pop groups))
3338          (if (not errors)
3339              t
3340            (y-or-n-p
3341             (format
3342              "Really post to %s unknown group%s: %s "
3343              (if (= (length errors) 1) "this" "these")
3344              (if (= (length errors) 1) "" "s")
3345              (mapconcat 'identity errors ", ")))))))
3346    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3347    (message-check 'valid-newsgroups
3348      (let ((case-fold-search t)
3349            (headers '("Newsgroups" "Followup-To"))
3350            header error)
3351        (while (and headers (not error))
3352          (when (setq header (mail-fetch-field (car headers)))
3353            (if (or
3354                 (not
3355                  (string-match
3356                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3357                   header))
3358                 (memq
3359                  nil (mapcar
3360                       (lambda (g)
3361                         (not (string-match "\\.\\'\\|\\.\\." g)))
3362                       (message-tokenize-header header ","))))
3363                (setq error t)))
3364          (unless error
3365            (pop headers)))
3366        (if (not error)
3367            t
3368          (y-or-n-p
3369           (format "The %s header looks odd: \"%s\".  Really post? "
3370                   (car headers) header)))))
3371    (message-check 'repeated-newsgroups
3372      (let ((case-fold-search t)
3373            (headers '("Newsgroups" "Followup-To"))
3374            header error groups group)
3375        (while (and headers
3376                    (not error))
3377          (when (setq header (mail-fetch-field (pop headers)))
3378            (setq groups (message-tokenize-header header ","))
3379            (while (setq group (pop groups))
3380              (when (member group groups)
3381                (setq error group
3382                      groups nil)))))
3383        (if (not error)
3384            t
3385          (y-or-n-p
3386           (format "Group %s is repeated in headers.  Really post? " error)))))
3387    ;; Check the From header.
3388    (message-check 'from
3389      (let* ((case-fold-search t)
3390             (from (message-fetch-field "from"))
3391             ad)
3392        (cond
3393         ((not from)
3394          (message "There is no From line.  Posting is denied.")
3395          nil)
3396         ((or (not (string-match
3397                    "@[^\\.]*\\."
3398                    (setq ad (nth 1 (mail-extract-address-components
3399                                     from))))) ;larsi@ifi
3400              (string-match "\\.\\." ad) ;larsi@ifi..uio
3401              (string-match "@\\." ad)   ;larsi@.ifi.uio
3402              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3403              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3404              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3405          (message
3406           "Denied posting -- the From looks strange: \"%s\"." from)
3407          nil)
3408         (t t))))))
3409
3410 (defun message-check-news-body-syntax ()
3411   (and
3412    ;; Check for long lines.
3413    (message-check 'long-lines
3414      (goto-char (point-min))
3415      (re-search-forward
3416       (concat "^" (regexp-quote mail-header-separator) "$"))
3417      (while (and
3418              (progn
3419                (end-of-line)
3420                (< (current-column) 80))
3421              (zerop (forward-line 1))))
3422      (or (bolp)
3423          (eobp)
3424          (y-or-n-p
3425           "You have lines longer than 79 characters.  Really post? ")))
3426    ;; Check whether the article is empty.
3427    (message-check 'empty
3428      (goto-char (point-min))
3429      (re-search-forward
3430       (concat "^" (regexp-quote mail-header-separator) "$"))
3431      (forward-line 1)
3432      (let ((b (point)))
3433        (goto-char (point-max))
3434        (re-search-backward message-signature-separator nil t)
3435        (beginning-of-line)
3436        (or (re-search-backward "[^ \n\t]" b t)
3437            (y-or-n-p "Empty article.  Really post? "))))
3438    ;; Check for control characters.
3439    (message-check 'control-chars
3440      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3441          (y-or-n-p
3442           "The article contains control characters.  Really post? ")
3443        t))
3444    ;; Check 8bit characters.
3445    (message-check '8bit
3446      (message-check-8bit))
3447    ;; Check excessive size.
3448    (message-check 'size
3449      (if (> (buffer-size) 60000)
3450          (y-or-n-p
3451           (format "The article is %d octets long.  Really post? "
3452                   (buffer-size)))
3453        t))
3454    ;; Check whether any new text has been added.
3455    (message-check 'new-text
3456      (or
3457       (not message-checksum)
3458       (not (eq (message-checksum) message-checksum))
3459       (y-or-n-p
3460        "It looks like no new text has been added.  Really post? ")))
3461    ;; Check the length of the signature.
3462    (message-check 'signature
3463      (goto-char (point-max))
3464      (if (> (count-lines (point) (point-max)) 5)
3465          (y-or-n-p
3466           (format
3467            "Your .sig is %d lines; it should be max 4.  Really post? "
3468            (1- (count-lines (point) (point-max)))))
3469        t))))
3470
3471 (defun message-check-mail-syntax ()
3472   "Check the syntax of the message."
3473   (save-excursion
3474     (save-restriction
3475       (widen)
3476       (and
3477        ;; We narrow to the headers and check them first.
3478        (save-excursion
3479          (save-restriction
3480            (message-narrow-to-headers)
3481            (message-check-mail-header-syntax)))
3482        ;; Check the body.
3483        (save-excursion
3484          (set-buffer message-edit-buffer)
3485          (message-check-mail-body-syntax))))))
3486
3487 (defun message-check-mail-header-syntax ()
3488   t)
3489
3490 (defun message-check-mail-body-syntax ()
3491   (and
3492    ;; Check 8bit characters.
3493    (message-check '8bit
3494      (message-check-8bit)
3495      )))
3496
3497 (defun message-check-8bit ()
3498   "Check the article contains 8bit characters."
3499   (save-excursion
3500     (set-buffer message-encoding-buffer)
3501     (message-narrow-to-headers)
3502     (let* ((case-fold-search t)
3503            (field-value (message-fetch-field "content-transfer-encoding")))
3504       (if (and field-value
3505                (member (downcase field-value) message-8bit-encoding-list))
3506           t
3507         (widen)
3508         (set-buffer (get-buffer-create " message syntax"))
3509         (erase-buffer)
3510         (goto-char (point-min))
3511         (set-buffer-multibyte nil)
3512         (insert-buffer message-encoding-buffer)
3513         (goto-char (point-min))
3514         (if (re-search-forward "[^\x00-\x7f]" nil t)
3515             (y-or-n-p
3516              "The article contains 8bit characters.  Really post? ")
3517           t)))))
3518
3519 (defun message-checksum ()
3520   "Return a \"checksum\" for the current buffer."
3521   (let ((sum 0))
3522     (save-excursion
3523       (goto-char (point-min))
3524       (re-search-forward
3525        (concat "^" (regexp-quote mail-header-separator) "$"))
3526       (while (not (eobp))
3527         (when (not (looking-at "[ \t\n]"))
3528           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3529                             (char-after))))
3530         (forward-char 1)))
3531     sum))
3532
3533 (defun message-do-fcc ()
3534   "Process Fcc headers in the current buffer."
3535   (let ((case-fold-search t)
3536         (coding-system-for-write 'raw-text)
3537         (output-coding-system 'raw-text)
3538         list file)
3539     (save-excursion
3540       (set-buffer (get-buffer-create " *message temp*"))
3541       (erase-buffer)
3542       (insert-buffer-substring message-encoding-buffer)
3543       (save-restriction
3544         (message-narrow-to-headers)
3545         (while (setq file (message-fetch-field "fcc"))
3546           (push file list)
3547           (message-remove-header "fcc" nil t)))
3548       (goto-char (point-min))
3549       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
3550       (replace-match "" t t)
3551       ;; Process FCC operations.
3552       (while list
3553         (setq file (pop list))
3554         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3555             ;; Pipe the article to the program in question.
3556             (call-process-region (point-min) (point-max) shell-file-name
3557                                  nil nil nil shell-command-switch
3558                                  (match-string 1 file))
3559           ;; Save the article.
3560           (setq file (expand-file-name file))
3561           (unless (file-exists-p (file-name-directory file))
3562             (make-directory (file-name-directory file) t))
3563           (if (and message-fcc-handler-function
3564                    (not (eq message-fcc-handler-function 'rmail-output)))
3565               (funcall message-fcc-handler-function file)
3566             (if (and (file-readable-p file) (mail-file-babyl-p file))
3567                 (rmail-output file 1 nil t)
3568               (let ((mail-use-rfc822 t))
3569                 (rmail-output file 1 t t))))))
3570       (kill-buffer (current-buffer)))))
3571
3572 (defun message-output (filename)
3573   "Append this article to Unix/babyl mail file.."
3574   (if (and (file-readable-p filename)
3575            (mail-file-babyl-p filename))
3576       (gnus-output-to-rmail filename t)
3577     (gnus-output-to-mail filename t)))
3578
3579 (defun message-cleanup-headers ()
3580   "Do various automatic cleanups of the headers."
3581   ;; Remove empty lines in the header.
3582   (save-restriction
3583     (message-narrow-to-headers)
3584     ;; Remove blank lines.
3585     (while (re-search-forward "^[ \t]*\n" nil t)
3586       (replace-match "" t t))
3587
3588     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3589     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3590     ;; embedded line breaks.
3591     (goto-char (point-min))
3592     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3593       (save-restriction
3594         (narrow-to-region
3595          (point)
3596          (if (re-search-forward "^[^ \t]" nil t)
3597              (match-beginning 0)
3598            (forward-line 1)
3599            (point)))
3600         (goto-char (point-min))
3601         (while (re-search-forward "\n[ \t]+" nil t)
3602           (replace-match " " t t))      ;No line breaks (too confusing)
3603         (goto-char (point-min))
3604         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3605           (replace-match "," t t))
3606         (goto-char (point-min))
3607         ;; Remove trailing commas.
3608         (when (re-search-forward ",+$" nil t)
3609           (replace-match "" t t))))))
3610
3611 (defun message-make-date (&optional now)
3612   "Make a valid data header.
3613 If NOW, use that time instead."
3614   (let* ((now (or now (current-time)))
3615          (zone (nth 8 (decode-time now)))
3616          (sign "+"))
3617     (when (< zone 0)
3618       (setq sign "-")
3619       (setq zone (- zone)))
3620     (concat
3621      (format-time-string "%d" now)
3622      ;; The month name of the %b spec is locale-specific.  Pfff.
3623      (format " %s "
3624              (capitalize (car (rassoc (nth 4 (decode-time now))
3625                                       parse-time-months))))
3626      (format-time-string "%Y %H:%M:%S " now)
3627      ;; We do all of this because XEmacs doesn't have the %z spec.
3628      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3629
3630 (defun message-make-followup-subject (subject)
3631   "Make a followup Subject."
3632   (cond
3633    ((and (eq message-use-subject-re 'guess)
3634          (string-match message-subject-encoded-re-regexp subject))
3635     subject)
3636    (message-use-subject-re
3637     (concat "Re: " (message-strip-subject-re subject)))
3638    (t subject)))
3639
3640 (defun message-make-message-id ()
3641   "Make a unique Message-ID."
3642   (concat "<" (message-unique-id)
3643           (let ((psubject (save-excursion (message-fetch-field "subject")))
3644                 (psupersedes
3645                  (save-excursion (message-fetch-field "supersedes"))))
3646             (if (or
3647                  (and message-reply-headers
3648                       (mail-header-references message-reply-headers)
3649                       (mail-header-subject message-reply-headers)
3650                       psubject
3651                       (mail-header-subject message-reply-headers)
3652                       (not (string=
3653                             (message-strip-subject-re
3654                              (mail-header-subject message-reply-headers))
3655                             (message-strip-subject-re psubject))))
3656                  (and psupersedes
3657                       (string-match "_-_@" psupersedes)))
3658                 "_-_" ""))
3659           "@" (message-make-fqdn) ">"))
3660
3661 (defvar message-unique-id-char nil)
3662
3663 ;; If you ever change this function, make sure the new version
3664 ;; cannot generate IDs that the old version could.
3665 ;; You might for example insert a "." somewhere (not next to another dot
3666 ;; or string boundary), or modify the "fsf" string.
3667 (defun message-unique-id ()
3668   ;; Don't use microseconds from (current-time), they may be unsupported.
3669   ;; Instead we use this randomly inited counter.
3670   (setq message-unique-id-char
3671         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3672            ;; (current-time) returns 16-bit ints,
3673            ;; and 2^16*25 just fits into 4 digits i base 36.
3674            (* 25 25)))
3675   (let ((tm (current-time)))
3676     (concat
3677      (if (memq system-type '(ms-dos emx vax-vms))
3678          (let ((user (downcase (user-login-name))))
3679            (while (string-match "[^a-z0-9_]" user)
3680              (aset user (match-beginning 0) ?_))
3681            user)
3682        (message-number-base36 (user-uid) -1))
3683      (message-number-base36 (+ (car   tm)
3684                                (lsh (% message-unique-id-char 25) 16)) 4)
3685      (message-number-base36 (+ (nth 1 tm)
3686                                (lsh (/ message-unique-id-char 25) 16)) 4)
3687      ;; Append the newsreader name, because while the generated
3688      ;; ID is unique to this newsreader, other newsreaders might
3689      ;; otherwise generate the same ID via another algorithm.
3690      ".fsf")))
3691
3692 (defun message-number-base36 (num len)
3693   (if (if (< len 0)
3694           (<= num 0)
3695         (= len 0))
3696       ""
3697     (concat (message-number-base36 (/ num 36) (1- len))
3698             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3699                                   (% num 36))))))
3700
3701 (defun message-make-organization ()
3702   "Make an Organization header."
3703   (let* ((organization
3704           (when message-user-organization
3705             (if (message-functionp message-user-organization)
3706                 (funcall message-user-organization)
3707               message-user-organization))))
3708     (save-excursion
3709       (message-set-work-buffer)
3710       (cond ((stringp organization)
3711              (insert organization))
3712             ((and (eq t organization)
3713                   message-user-organization-file
3714                   (file-exists-p message-user-organization-file))
3715              (insert-file-contents message-user-organization-file)))
3716       (goto-char (point-min))
3717       (while (re-search-forward "[\t\n]+" nil t)
3718         (replace-match "" t t))
3719       (unless (zerop (buffer-size))
3720         (buffer-string)))))
3721
3722 (defun message-make-lines ()
3723   "Count the number of lines and return numeric string."
3724   (save-excursion
3725     (save-restriction
3726       (widen)
3727       (goto-char (point-min))
3728       (re-search-forward
3729        (concat "^" (regexp-quote mail-header-separator) "$"))
3730       (forward-line 1)
3731       (int-to-string (count-lines (point) (point-max))))))
3732
3733 (defun message-make-in-reply-to ()
3734   "Return the In-Reply-To header for this message."
3735   (when message-reply-headers
3736     (let ((mid (mail-header-message-id message-reply-headers))
3737           (from (mail-header-from message-reply-headers))
3738           (date (mail-header-date message-reply-headers)))
3739       (when mid
3740         (concat mid
3741                 (when from
3742                   (let ((pair (std11-extract-address-components from)))
3743                     (concat "\n ("
3744                             (or (car pair) (cadr pair))
3745                             "'s message of \""
3746                             (if (or (not date) (string= date ""))
3747                                 "(unknown date)" date)
3748                             "\")"))))))))
3749
3750 (defun message-make-distribution ()
3751   "Make a Distribution header."
3752   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3753     (cond ((message-functionp message-distribution-function)
3754            (funcall message-distribution-function))
3755           (t orig-distribution))))
3756
3757 (defun message-make-expires ()
3758   "Return an Expires header based on `message-expires'."
3759   (let ((current (current-time))
3760         (future (* 1.0 message-expires 60 60 24)))
3761     ;; Add the future to current.
3762     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3763     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3764     (message-make-date current)))
3765
3766 (defun message-make-path ()
3767   "Return uucp path."
3768   (let ((login-name (user-login-name)))
3769     (cond ((null message-user-path)
3770            (concat (system-name) "!" login-name))
3771           ((stringp message-user-path)
3772            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3773            (concat message-user-path "!" login-name))
3774           (t login-name))))
3775
3776 (defun message-make-from ()
3777   "Make a From header."
3778   (let* ((style message-from-style)
3779          (login (message-make-address))
3780          (fullname
3781           (or (and (boundp 'user-full-name)
3782                    user-full-name)
3783               (user-full-name))))
3784     (when (string= fullname "&")
3785       (setq fullname (user-login-name)))
3786     (save-excursion
3787       (message-set-work-buffer)
3788       (cond
3789        ((or (null style)
3790             (equal fullname ""))
3791         (insert login))
3792        ((or (eq style 'angles)
3793             (and (not (eq style 'parens))
3794                  ;; Use angles if no quoting is needed, or if parens would
3795                  ;; need quoting too.
3796                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3797                      (let ((tmp (concat fullname nil)))
3798                        (while (string-match "([^()]*)" tmp)
3799                          (aset tmp (match-beginning 0) ?-)
3800                          (aset tmp (1- (match-end 0)) ?-))
3801                        (string-match "[\\()]" tmp)))))
3802         (insert fullname)
3803         (goto-char (point-min))
3804         ;; Look for a character that cannot appear unquoted
3805         ;; according to RFC 822.
3806         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3807           ;; Quote fullname, escaping specials.
3808           (goto-char (point-min))
3809           (insert "\"")
3810           (while (re-search-forward "[\"\\]" nil 1)
3811             (replace-match "\\\\\\&" t))
3812           (insert "\""))
3813         (insert " <" login ">"))
3814        (t                               ; 'parens or default
3815         (insert login " (")
3816         (let ((fullname-start (point)))
3817           (insert fullname)
3818           (goto-char fullname-start)
3819           ;; RFC 822 says \ and nonmatching parentheses
3820           ;; must be escaped in comments.
3821           ;; Escape every instance of ()\ ...
3822           (while (re-search-forward "[()\\]" nil 1)
3823             (replace-match "\\\\\\&" t))
3824           ;; ... then undo escaping of matching parentheses,
3825           ;; including matching nested parentheses.
3826           (goto-char fullname-start)
3827           (while (re-search-forward
3828                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3829                   nil 1)
3830             (replace-match "\\1(\\3)" t)
3831             (goto-char fullname-start)))
3832         (insert ")")))
3833       (buffer-string))))
3834
3835 (defun message-make-sender ()
3836   "Return the \"real\" user address.
3837 This function tries to ignore all user modifications, and
3838 give as trustworthy answer as possible."
3839   (concat (user-login-name) "@" (system-name)))
3840
3841 (defun message-make-address ()
3842   "Make the address of the user."
3843   (or (message-user-mail-address)
3844       (concat (user-login-name) "@" (message-make-domain))))
3845
3846 (defun message-user-mail-address ()
3847   "Return the pertinent part of `user-mail-address'."
3848   (when user-mail-address
3849     (if (string-match " " user-mail-address)
3850         (nth 1 (std11-extract-address-components user-mail-address))
3851       user-mail-address)))
3852
3853 (defun message-make-fqdn ()
3854   "Return user's fully qualified domain name."
3855   (let ((system-name (system-name))
3856         (user-mail (message-user-mail-address)))
3857     (cond
3858      ((string-match "[^.]\\.[^.]" system-name)
3859       ;; `system-name' returned the right result.
3860       system-name)
3861      ;; Try `mail-host-address'.
3862      ((and (boundp 'mail-host-address)
3863            (stringp mail-host-address)
3864            (string-match "\\." mail-host-address))
3865       mail-host-address)
3866      ;; We try `user-mail-address' as a backup.
3867      ((and user-mail
3868            (string-match "\\." user-mail)
3869            (string-match "@\\(.*\\)\\'" user-mail))
3870       (match-string 1 user-mail))
3871      ;; Default to this bogus thing.
3872      (t
3873       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3874
3875 (defun message-make-host-name ()
3876   "Return the name of the host."
3877   (let ((fqdn (message-make-fqdn)))
3878     (string-match "^[^.]+\\." fqdn)
3879     (substring fqdn 0 (1- (match-end 0)))))
3880
3881 (defun message-make-domain ()
3882   "Return the domain name."
3883   (or mail-host-address
3884       (message-make-fqdn)))
3885
3886 ;; Dummy to avoid byte-compile warning.
3887 (defvar mule-version)
3888 (defvar emacs-beta-version)
3889 (defvar xemacs-codename)
3890 (defvar gnus-inviolable-extended-version)
3891
3892 (defun message-make-user-agent ()
3893   "Return user-agent info if the value `message-user-agent' is non-nil. If the
3894 \"User-Agent\" field has already exist, it's value will be added in the return
3895 string."
3896   (when message-user-agent
3897     (save-excursion
3898       (goto-char (point-min))
3899       (let ((case-fold-search t)
3900             user-agent start p end)
3901         (if (re-search-forward "^User-Agent:[\t ]*" nil t)
3902             (progn
3903               (setq start (match-beginning 0)
3904                     p (match-end 0)
3905                     end (std11-field-end)
3906                     user-agent (buffer-substring-no-properties p end))
3907               (delete-region start (1+ end))
3908               (concat message-user-agent " " user-agent))
3909           message-user-agent)))))
3910
3911 (defun message-generate-headers (headers)
3912   "Prepare article HEADERS.
3913 Headers already prepared in the buffer are not modified."
3914   (save-restriction
3915     (message-narrow-to-headers)
3916     (let* ((Date (message-make-date))
3917            (Message-ID (message-make-message-id))
3918            (Organization (message-make-organization))
3919            (From (message-make-from))
3920            (Path (message-make-path))
3921            (Subject nil)
3922            (Newsgroups nil)
3923            (In-Reply-To (message-make-in-reply-to))
3924            (To nil)
3925            (Distribution (message-make-distribution))
3926            (Lines (message-make-lines))
3927            (User-Agent (message-make-user-agent))
3928            (Expires (message-make-expires))
3929            (case-fold-search t)
3930            header value elem)
3931       ;; First we remove any old generated headers.
3932       (let ((headers message-deletable-headers))
3933         (unless (buffer-modified-p)
3934           (setq headers (delq 'Message-ID (copy-sequence headers))))
3935         (while headers
3936           (goto-char (point-min))
3937           (and (re-search-forward
3938                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3939                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3940                (message-delete-line))
3941           (pop headers)))
3942       ;; Go through all the required headers and see if they are in the
3943       ;; articles already.  If they are not, or are empty, they are
3944       ;; inserted automatically - except for Subject, Newsgroups and
3945       ;; Distribution.
3946       (while headers
3947         (goto-char (point-min))
3948         (setq elem (pop headers))
3949         (if (consp elem)
3950             (if (eq (car elem) 'optional)
3951                 (setq header (cdr elem))
3952               (setq header (car elem)))
3953           (setq header elem))
3954         (when (or (not (re-search-forward
3955                         (concat "^"
3956                                 (regexp-quote
3957                                  (downcase
3958                                   (if (stringp header)
3959                                       header
3960                                     (symbol-name header))))
3961                                 ":")
3962                         nil t))
3963                   (progn
3964                     ;; The header was found.  We insert a space after the
3965                     ;; colon, if there is none.
3966                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3967                     ;; Find out whether the header is empty...
3968                     (looking-at "[ \t]*\n[^ \t]")))
3969           ;; So we find out what value we should insert.
3970           (setq value
3971                 (cond
3972                  ((and (consp elem) (eq (car elem) 'optional))
3973                   ;; This is an optional header.  If the cdr of this
3974                   ;; is something that is nil, then we do not insert
3975                   ;; this header.
3976                   (setq header (cdr elem))
3977                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3978                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3979                  ((consp elem)
3980                   ;; The element is a cons.  Either the cdr is a
3981                   ;; string to be inserted verbatim, or it is a
3982                   ;; function, and we insert the value returned from
3983                   ;; this function.
3984                   (or (and (stringp (cdr elem)) (cdr elem))
3985                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3986                  ((and (boundp header) (symbol-value header))
3987                   ;; The element is a symbol.  We insert the value
3988                   ;; of this symbol, if any.
3989                   (symbol-value header))
3990                  ((not (message-check-element header))
3991                   ;; We couldn't generate a value for this header,
3992                   ;; so we just ask the user.
3993                   (read-from-minibuffer
3994                    (format "Empty header for %s; enter value: " header)))))
3995           ;; Finally insert the header.
3996           (when (and value
3997                      (not (equal value "")))
3998             (save-excursion
3999               (if (bolp)
4000                   (progn
4001                     ;; This header didn't exist, so we insert it.
4002                     (goto-char (point-max))
4003                     (insert (if (stringp header) header (symbol-name header))
4004                             ": " value)
4005                     (unless (bolp)
4006                       (insert "\n"))
4007                     (forward-line -1))
4008                 ;; The value of this header was empty, so we clear
4009                 ;; totally and insert the new value.
4010                 (delete-region (point) (gnus-point-at-eol))
4011                 (insert value)
4012                 (when (bolp)
4013                   (delete-char -1)))
4014               ;; Add the deletable property to the headers that require it.
4015               (and (memq header message-deletable-headers)
4016                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4017                    (add-text-properties
4018                     (point) (match-end 0)
4019                     '(message-deletable t face italic) (current-buffer)))))))
4020       ;; Insert new Sender if the From is strange.
4021       (let ((from (message-fetch-field "from"))
4022             (sender (message-fetch-field "sender"))
4023             (secure-sender (message-make-sender)))
4024         (when (and from
4025                    (not (message-check-element 'sender))
4026                    (not (string=
4027                          (downcase
4028                           (cadr (std11-extract-address-components from)))
4029                          (downcase secure-sender)))
4030                    (or (null sender)
4031                        (not
4032                         (string=
4033                          (downcase
4034                           (cadr (std11-extract-address-components sender)))
4035                          (downcase secure-sender)))))
4036           (goto-char (point-min))
4037           ;; Rename any old Sender headers to Original-Sender.
4038           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4039             (beginning-of-line)
4040             (insert "Original-")
4041             (beginning-of-line))
4042           (when (or (message-news-p)
4043                     (string-match "@.+\\.." secure-sender))
4044             (insert "Sender: " secure-sender "\n")))))))
4045
4046 (defun message-insert-courtesy-copy ()
4047   "Insert a courtesy message in mail copies of combined messages."
4048   (let (newsgroups)
4049     (save-excursion
4050       (save-restriction
4051         (message-narrow-to-headers)
4052         (when (setq newsgroups (message-fetch-field "newsgroups"))
4053           (goto-char (point-max))
4054           (insert "Posted-To: " newsgroups "\n")))
4055       (forward-line 1)
4056       (when message-courtesy-message
4057         (cond
4058          ((string-match "%s" message-courtesy-message)
4059           (insert (format message-courtesy-message newsgroups)))
4060          (t
4061           (insert message-courtesy-message)))))))
4062
4063 ;;;
4064 ;;; Setting up a message buffer
4065 ;;;
4066
4067 (defun message-fill-address (header value)
4068   (save-restriction
4069     (narrow-to-region (point) (point))
4070     (insert (capitalize (symbol-name header))
4071             ": "
4072             (if (consp value) (car value) value)
4073             "\n")
4074     (narrow-to-region (point-min) (1- (point-max)))
4075     (let (quoted last)
4076       (goto-char (point-min))
4077       (while (not (eobp))
4078         (skip-chars-forward "^,\"" (point-max))
4079         (if (or (eq (char-after) ?,)
4080                 (eobp))
4081             (when (not quoted)
4082               (if (and (> (current-column) 78)
4083                        last)
4084                   (save-excursion
4085                     (goto-char last)
4086                     (looking-at "[ \t]*")
4087                     (replace-match "\n " t t)))
4088               (setq last (1+ (point))))
4089           (setq quoted (not quoted)))
4090         (unless (eobp)
4091           (forward-char 1))))
4092     (goto-char (point-max))
4093     (widen)
4094     (forward-line 1)))
4095
4096 (defun message-fill-references (header value)
4097   (insert (capitalize (symbol-name header))
4098           ": "
4099           (std11-fill-msg-id-list-string
4100           (if (consp value) (car value) value))
4101           "\n"))
4102
4103 (defun message-fill-header (header value)
4104   (let ((begin (point))
4105         (fill-column 78)
4106         (fill-prefix " "))
4107     (insert (capitalize (symbol-name header))
4108             ": "
4109             (if (consp value) (car value) value)
4110             "\n")
4111     (save-restriction
4112       (narrow-to-region begin (point))
4113       (fill-region-as-paragraph begin (point))
4114       ;; Tapdance around looong Message-IDs.
4115       (forward-line -1)
4116       (when (looking-at "[ \t]*$")
4117         (message-delete-line))
4118       (goto-char begin)
4119       (re-search-forward ":" nil t)
4120       (when (looking-at "\n[ \t]+")
4121         (replace-match " " t t))
4122       (goto-char (point-max)))))
4123
4124 (defun message-shorten-1 (list cut surplus)
4125   ;; Cut SURPLUS elements out of LIST, beginning with CUTth one.
4126   (setcdr (nthcdr (- cut 2) list)
4127           (nthcdr (+ (- cut 2) surplus 1) list)))
4128
4129 (defun message-shorten-references (header references)
4130   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
4131 If folding is disallowed, also check that the REFERENCES are less
4132 than 988 characters long, and if they are not, trim them until they are."
4133   (let ((maxcount 31)
4134         (count 0)
4135         (cut 6)
4136         refs)
4137     (with-temp-buffer
4138       (insert references)
4139       (goto-char (point-min))
4140       ;; Cons a list of valid references.
4141       (while (re-search-forward "<[^>]+>" nil t)
4142         (push (match-string 0) refs))
4143       (setq refs (nreverse refs)
4144             count (length refs)))
4145
4146     ;; If the list has more than MAXCOUNT elements, trim it by
4147     ;; removing the CUTth element and the required number of
4148     ;; elements that follow.
4149     (when (> count maxcount)
4150       (let ((surplus (- count maxcount)))
4151         (message-shorten-1 refs cut surplus)
4152         (decf count surplus)))
4153
4154     ;; If folding is disallowed, make sure the total length (including
4155     ;; the spaces between) will be less than MAXSIZE characters.
4156     ;;
4157     ;; Only disallow folding for News messages. At this point the headers
4158     ;; have not been generated, thus we use message-this-is-news directly.
4159     (when (and message-this-is-news message-cater-to-broken-inn)
4160       (let ((maxsize 988)
4161             (totalsize (+ (apply #'+ (mapcar #'length refs))
4162                           (1- count)))
4163             (surplus 0)
4164             (ptr (nthcdr (1- cut) refs)))
4165         ;; Decide how many elements to cut off...
4166         (while (> totalsize maxsize)
4167           (decf totalsize (1+ (length (car ptr))))
4168           (incf surplus)
4169           (setq ptr (cdr ptr)))
4170         ;; ...and do it.
4171         (when (> surplus 0)
4172           (message-shorten-1 refs cut surplus))))
4173
4174     ;; Finally, collect the references back into a string and insert
4175     ;; it into the buffer.
4176     (let ((refstring (mapconcat #'identity refs " ")))
4177       (if (and message-this-is-news message-cater-to-broken-inn)
4178           (insert (capitalize (symbol-name header)) ": "
4179                   refstring "\n")
4180         (message-fill-header header refstring)))))
4181
4182 (defun message-position-point ()
4183   "Move point to where the user probably wants to find it."
4184   (message-narrow-to-headers)
4185   (cond
4186    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4187     (search-backward ":" )
4188     (widen)
4189     (forward-char 1)
4190     (if (eq (char-after) ? )
4191         (forward-char 1)
4192       (insert " ")))
4193    (t
4194     (goto-char (point-max))
4195     (widen)
4196     (forward-line 1)
4197     (unless (looking-at "$")
4198       (forward-line 2)))
4199    (sit-for 0)))
4200
4201 (defun message-buffer-name (type &optional to group)
4202   "Return a new (unique) buffer name based on TYPE and TO."
4203   (cond
4204    ;; Generate a new buffer name The Message Way.
4205    ((eq message-generate-new-buffers 'unique)
4206     (generate-new-buffer-name
4207      (concat "*" type
4208              (if to
4209                  (concat " to "
4210                          (or (car (std11-extract-address-components to))
4211                              to) "")
4212                "")
4213              (if (and group (not (string= group ""))) (concat " on " group) "")
4214              "*")))
4215    ;; Check whether `message-generate-new-buffers' is a function,
4216    ;; and if so, call it.
4217    ((message-functionp message-generate-new-buffers)
4218     (funcall message-generate-new-buffers type to group))
4219    ((eq message-generate-new-buffers 'unsent)
4220     (generate-new-buffer-name
4221      (concat "*unsent " type
4222              (if to
4223                  (concat " to "
4224                          (or (car (mail-extract-address-components to))
4225                              to) "")
4226                "")
4227              (if (and group (not (string= group ""))) (concat " on " group) "")
4228              "*")))
4229    ;; Use standard name.
4230    (t
4231     (format "*%s message*" type))))
4232
4233 (defmacro message-pop-to-buffer-1 (buffer)
4234   `(if pop-up-frames
4235        (let (special-display-buffer-names
4236              special-display-regexps
4237              same-window-buffer-names
4238              same-window-regexps)
4239          (pop-to-buffer ,buffer))
4240      (pop-to-buffer ,buffer)))
4241
4242 (defun message-pop-to-buffer (name)
4243   "Pop to buffer NAME, and warn if it already exists and is modified."
4244   (let ((buffer (get-buffer name))
4245         (pop-up-frames (and (or (static-if (featurep 'xemacs)
4246                                     (device-on-window-system-p)
4247                                   window-system)
4248                                 (>= emacs-major-version 20))
4249                             message-use-multi-frames)))
4250     (if (and buffer
4251              (buffer-name buffer))
4252         (progn
4253           (message-pop-to-buffer-1 buffer)
4254           (when (and (buffer-modified-p)
4255                      (not (y-or-n-p
4256                            "Message already being composed; erase? ")))
4257             (error "Message being composed")))
4258       (message-pop-to-buffer-1 name))
4259     (erase-buffer)
4260     (message-mode)
4261     (when pop-up-frames
4262       (set (make-local-variable 'message-original-frame) (selected-frame)))))
4263
4264 (defun message-do-send-housekeeping ()
4265   "Kill old message buffers."
4266   ;; We might have sent this buffer already.  Delete it from the
4267   ;; list of buffers.
4268   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4269   (while (and message-max-buffers
4270               message-buffer-list
4271               (>= (length message-buffer-list) message-max-buffers))
4272     ;; Kill the oldest buffer -- unless it has been changed.
4273     (let ((buffer (pop message-buffer-list)))
4274       (when (and (buffer-name buffer)
4275                  (not (buffer-modified-p buffer)))
4276         (kill-buffer buffer))))
4277   ;; Rename the buffer.
4278   (if message-send-rename-function
4279       (funcall message-send-rename-function)
4280     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
4281       (rename-buffer
4282        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
4283   ;; Push the current buffer onto the list.
4284   (when message-max-buffers
4285     (setq message-buffer-list
4286           (nconc message-buffer-list (list (current-buffer))))))
4287
4288 (defvar mc-modes-alist)
4289 (defun message-setup (headers &optional replybuffer actions)
4290   (when (and (boundp 'mc-modes-alist)
4291              (not (assq 'message-mode mc-modes-alist)))
4292     (push '(message-mode (encrypt . mc-encrypt-message)
4293                          (sign . mc-sign-message))
4294           mc-modes-alist))
4295   (when actions
4296     (setq message-send-actions actions))
4297   (setq message-reply-buffer
4298         (or (message-get-parameter 'reply-buffer)
4299             replybuffer))
4300   (goto-char (point-min))
4301   ;; Insert all the headers.
4302   (mail-header-format
4303    (let ((h headers)
4304          (alist message-header-format-alist))
4305      (while h
4306        (unless (assq (caar h) message-header-format-alist)
4307          (push (list (caar h)) alist))
4308        (pop h))
4309      alist)
4310    headers)
4311   (delete-region (point) (progn (forward-line -1) (point)))
4312   (when message-default-headers
4313     (insert message-default-headers)
4314     (or (bolp) (insert ?\n)))
4315   (put-text-property
4316    (point)
4317    (progn
4318      (insert mail-header-separator "\n")
4319      (1- (point)))
4320    'read-only nil)
4321   (forward-line -1)
4322   (when (message-news-p)
4323     (when message-default-news-headers
4324       (insert message-default-news-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-news-headers))))))
4331   (when (message-mail-p)
4332     (when message-default-mail-headers
4333       (insert message-default-mail-headers)
4334       (or (bolp) (insert ?\n)))
4335     (when message-generate-headers-first
4336       (message-generate-headers
4337        (delq 'Lines
4338              (delq 'Subject
4339                    (copy-sequence message-required-mail-headers))))))
4340   (run-hooks 'message-signature-setup-hook)
4341   (message-insert-signature)
4342   (save-restriction
4343     (message-narrow-to-headers)
4344     (run-hooks 'message-header-setup-hook))
4345   (set-buffer-modified-p nil)
4346   (setq buffer-undo-list nil)
4347   (run-hooks 'message-setup-hook)
4348   (message-position-point)
4349   (undo-boundary))
4350
4351 (defun message-set-auto-save-file-name ()
4352   "Associate the message buffer with a file in the drafts directory."
4353   (when message-auto-save-directory
4354     (if (gnus-alive-p)
4355         (setq message-draft-article
4356               (nndraft-request-associate-buffer "drafts"))
4357       (setq buffer-file-name (expand-file-name "*message*"
4358                                                message-auto-save-directory))
4359       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4360     (clear-visited-file-modtime)
4361     (static-if (boundp 'MULE)
4362         (set-file-coding-system message-draft-coding-system)
4363       (setq buffer-file-coding-system message-draft-coding-system))))
4364
4365 (defun message-disassociate-draft ()
4366   "Disassociate the message buffer from the drafts directory."
4367   (when message-draft-article
4368     (nndraft-request-expire-articles
4369      (list message-draft-article) "drafts" nil t)))
4370
4371 (defun message-insert-headers ()
4372   "Generate the headers for the article."
4373   (interactive)
4374   (save-excursion
4375     (save-restriction
4376       (message-narrow-to-headers)
4377       (when (message-news-p)
4378         (message-generate-headers
4379          (delq 'Lines
4380                (delq 'Subject
4381                      (copy-sequence message-required-news-headers)))))
4382       (when (message-mail-p)
4383         (message-generate-headers
4384          (delq 'Lines
4385                (delq 'Subject
4386                      (copy-sequence message-required-mail-headers))))))))
4387
4388 \f
4389
4390 ;;;
4391 ;;; Commands for interfacing with message
4392 ;;;
4393
4394 ;;;###autoload
4395 (defun message-mail (&optional to subject
4396                                other-headers continue switch-function
4397                                yank-action send-actions)
4398   "Start editing a mail message to be sent.
4399 OTHER-HEADERS is an alist of header/value pairs."
4400   (interactive)
4401   (let ((message-this-is-mail t))
4402     (message-pop-to-buffer (message-buffer-name "mail" to))
4403     (message-setup
4404      (nconc
4405       `((To . ,(or to "")) (Subject . ,(or subject "")))
4406       (when other-headers other-headers)))))
4407
4408 ;;;###autoload
4409 (defun message-news (&optional newsgroups subject)
4410   "Start editing a news article to be sent."
4411   (interactive)
4412   (let ((message-this-is-news t))
4413     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
4414     (message-setup `((Newsgroups . ,(or newsgroups ""))
4415                      (Subject . ,(or subject ""))))))
4416
4417 (defun message-get-reply-headers (wide &optional to-address)
4418   (let (follow-to mct never-mct from to cc reply-to mft)
4419     ;; Find all relevant headers we need.
4420     (setq from (message-fetch-field "from")
4421           to (message-fetch-field "to")
4422           cc (message-fetch-field "cc")
4423           mct (when message-use-mail-copies-to
4424                 (message-fetch-field "mail-copies-to"))
4425           reply-to (when message-use-mail-reply-to
4426                      (or (message-fetch-field "mail-reply-to")
4427                          (message-fetch-field "reply-to")))
4428           mft (when (and (not to-address)
4429                          (not reply-to)
4430                          message-use-mail-followup-to)
4431                 (message-fetch-field "mail-followup-to")))
4432
4433     ;; Handle special values of Mail-Copies-To.
4434     (when mct
4435       (cond
4436        ((and (or (equal (downcase mct) "never")
4437                  (equal (downcase mct) "nobody"))
4438              (or (not (eq message-use-mail-copies-to 'ask))
4439                  (message-y-or-n-p
4440                   (concat "Obey Mail-Copies-To: never? ") t "\
4441 You should normally obey the Mail-Copies-To: header.
4442
4443         `Mail-Copies-To: never'
4444 directs you not to send your response to the author.")))
4445         (setq never-mct t)
4446         (setq mct nil))
4447        ((and (or (equal (downcase mct) "always")
4448                  (equal (downcase mct) "poster"))
4449              (or (not (eq message-use-mail-copies-to 'ask))
4450                  (message-y-or-n-p
4451                   (concat "Obey Mail-Copies-To: always? ") t "\
4452 You should normally obey the Mail-Copies-To: header.
4453
4454         `Mail-Copies-To: always'
4455 sends a copy of your response to the author.")))
4456         (setq mct (or reply-to from)))
4457        ((and (eq message-use-mail-copies-to 'ask)
4458              (not
4459               (message-y-or-n-p
4460                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
4461 You should normally obey the Mail-Copies-To: header.
4462
4463         `Mail-Copies-To: " mct "'
4464 sends a copy of your response to " (if (string-match "," mct)
4465                                        "the specified addresses"
4466                                      "that address") ".")))
4467         (setq mct nil))))
4468
4469     ;; Handle Mail-Followup-To.
4470     (when (and mft
4471                (eq message-use-mail-followup-to 'ask)
4472                (not (message-y-or-n-p
4473                      (concat "Obey Mail-Followup-To: " mft "? ") t "\
4474 You should normally obey the Mail-Followup-To: header.
4475
4476         `Mail-Followup-To: " mft "'
4477 directs your response to " (if (string-match "," mft)
4478                                "the specified addresses"
4479                              "that address only") ".
4480
4481 A typical situation where Mail-Followup-To is used is when the author thinks
4482 that further discussion should take place only in "
4483                              (if (string-match "," mft)
4484                                  "the specified mailing lists"
4485                                "that mailing list") ".")))
4486       (setq mft nil))
4487
4488     (if (or (not wide)
4489             to-address)
4490         (progn
4491           (setq follow-to (list (cons 'To (or to-address reply-to mft from))))
4492           (when (and wide mct)
4493             (push (cons 'Cc mct) follow-to)))
4494       (let (ccalist)
4495         (save-excursion
4496           (message-set-work-buffer)
4497           (unless never-mct
4498             (insert (or reply-to from "")))
4499           (insert (if mft (concat (if (bolp) "" ", ") mft "") ""))
4500           (insert (if to (concat (if (bolp) "" ", ") to "") ""))
4501           (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
4502           (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
4503           (goto-char (point-min))
4504           (while (re-search-forward "[ \t]+" nil t)
4505             (replace-match " " t t))
4506           ;; Remove addresses that match `rmail-dont-reply-to-names'.
4507           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4508             (insert (prog1 (rmail-dont-reply-to (buffer-string))
4509                       (erase-buffer))))
4510           (goto-char (point-min))
4511           ;; Perhaps "Mail-Copies-To: never" removed the only address?
4512           (when (eobp)
4513             (insert (or reply-to from "")))
4514           (setq ccalist
4515                 (mapcar
4516                  (lambda (addr)
4517                    (cons (mail-strip-quoted-names addr) addr))
4518                  (message-tokenize-header (buffer-string))))
4519           (let ((s ccalist))
4520             (while s
4521               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
4522         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
4523         (when ccalist
4524           (let ((ccs (cons 'Cc (mapconcat
4525                                 (lambda (addr) (cdr addr)) ccalist ", "))))
4526             (when (string-match "^ +" (cdr ccs))
4527               (setcdr ccs (substring (cdr ccs) (match-end 0))))
4528             (push ccs follow-to)))))
4529     follow-to))
4530
4531 ;;;###autoload
4532 (defun message-reply (&optional to-address wide)
4533   "Start editing a reply to the article in the current buffer."
4534   (interactive)
4535   (require 'gnus-sum)                   ; for gnus-list-identifiers
4536   (let ((cur (current-buffer))
4537         from subject date
4538         references message-id follow-to
4539         (inhibit-point-motion-hooks t)
4540         (message-this-is-mail t)
4541         gnus-warning in-reply-to)
4542     (save-restriction
4543       (message-narrow-to-head)
4544       ;; Allow customizations to have their say.
4545       (if (not wide)
4546           ;; This is a regular reply.
4547           (if (message-functionp message-reply-to-function)
4548               (setq follow-to (funcall message-reply-to-function)))
4549         ;; This is a followup.
4550         (if (message-functionp message-wide-reply-to-function)
4551             (save-excursion
4552               (setq follow-to
4553                     (funcall message-wide-reply-to-function)))))
4554       (setq message-id (message-fetch-field "message-id" t)
4555             references (message-fetch-field "references")
4556             date (message-fetch-field "date")
4557             from (message-fetch-field "from")
4558             subject (or (message-fetch-field "subject") "none"))
4559       (if gnus-list-identifiers
4560           (setq subject (message-strip-list-identifiers subject)))
4561       (setq subject (message-make-followup-subject subject))
4562
4563       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4564                  (string-match "<[^>]+>" gnus-warning))
4565         (setq message-id (match-string 0 gnus-warning)))
4566
4567       (unless follow-to
4568         (setq follow-to (message-get-reply-headers wide to-address)))
4569
4570       ;; Get the references from "In-Reply-To" field if there were
4571       ;; no references and "In-Reply-To" field looks promising.
4572       (unless references
4573         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
4574                    (string-match "<[^>]+>" in-reply-to))
4575           (setq references (match-string 0 in-reply-to)))))
4576
4577     (message-pop-to-buffer
4578      (message-buffer-name
4579       (if wide "wide reply" "reply") from
4580       (if wide to-address nil)))
4581
4582     (setq message-reply-headers
4583           (make-full-mail-header-from-decoded-header
4584            0 subject from date message-id references 0 0 ""))
4585
4586     (message-setup
4587      `((Subject . ,subject)
4588        ,@follow-to
4589        ,@(if (or references message-id)
4590              `((References . ,(concat (or references "") (and references " ")
4591                                       (or message-id ""))))
4592            nil))
4593      cur)))
4594
4595 ;;;###autoload
4596 (defun message-wide-reply (&optional to-address)
4597   "Make a \"wide\" reply to the message in the current buffer."
4598   (interactive)
4599   (message-reply to-address t))
4600
4601 ;;;###autoload
4602 (defun message-followup (&optional to-newsgroups)
4603   "Follow up to the message in the current buffer.
4604 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4605   (interactive)
4606   (let ((cur (current-buffer))
4607         from subject date mct
4608         references message-id follow-to
4609         (inhibit-point-motion-hooks t)
4610         (message-this-is-news t)
4611         followup-to distribution newsgroups gnus-warning posted-to mft mrt)
4612     (save-restriction
4613       (message-narrow-to-head)
4614       (when (message-functionp message-followup-to-function)
4615         (setq follow-to
4616               (funcall message-followup-to-function)))
4617       (setq from (message-fetch-field "from")
4618             date (message-fetch-field "date" t)
4619             subject (or (message-fetch-field "subject") "none")
4620             references (message-fetch-field "references")
4621             message-id (message-fetch-field "message-id" t)
4622             followup-to (when message-use-followup-to
4623                           (message-fetch-field "followup-to"))
4624             distribution (message-fetch-field "distribution")
4625             newsgroups (message-fetch-field "newsgroups")
4626             posted-to (message-fetch-field "posted-to")
4627             mct (when message-use-mail-copies-to
4628                   (message-fetch-field "mail-copies-to"))
4629             mft (when message-use-mail-followup-to
4630                   (message-fetch-field "mail-followup-to"))
4631             mrt (when message-use-mail-reply-to
4632                   (or (message-fetch-field "mail-reply-to")
4633                       (message-fetch-field "reply-to")))
4634             gnus-warning (message-fetch-field "gnus-warning"))
4635       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
4636         (setq message-id (match-string 0 gnus-warning)))
4637       ;; Remove bogus distribution.
4638       (when (and (stringp distribution)
4639                  (let ((case-fold-search t))
4640                    (string-match "world" distribution)))
4641         (setq distribution nil))
4642       (if gnus-list-identifiers
4643           (setq subject (message-strip-list-identifiers subject)))
4644       (setq subject (message-make-followup-subject subject))
4645       (widen))
4646
4647     ;; Handle special values of Mail-Copies-To.
4648     (when mct
4649       (cond
4650        ((and (or (equal (downcase mct) "never")
4651                  (equal (downcase mct) "nobody"))
4652              (or (not (eq message-use-mail-copies-to 'ask))
4653                  (message-y-or-n-p
4654                   (concat "Obey Mail-Copies-To: never? ") t "\
4655 You should normally obey the Mail-Copies-To: header.
4656
4657         `Mail-Copies-To: never'
4658 directs you not to send your response to the author.")))
4659         (setq mct nil))
4660        ((and (or (equal (downcase mct) "always")
4661                  (equal (downcase mct) "poster"))
4662              (or (not (eq message-use-mail-copies-to 'ask))
4663                  (message-y-or-n-p
4664                   (concat "Obey Mail-Copies-To: always? ") t "\
4665 You should normally obey the Mail-Copies-To: header.
4666
4667         `Mail-Copies-To: always'
4668 sends a copy of your response to the author.")))
4669         (setq mct (or mrt from)))
4670        ((and (eq message-use-mail-copies-to 'ask)
4671              (not
4672               (message-y-or-n-p
4673                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
4674 You should normally obey the Mail-Copies-To: header.
4675
4676         `Mail-Copies-To: " mct "'
4677 sends a copy of your response to " (if (string-match "," mct)
4678                                        "the specified addresses"
4679                                      "that address") ".")))
4680         (setq mct nil))
4681        ))
4682
4683     (unless follow-to
4684       (cond
4685        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
4686        ;; Handle Followup-To.
4687        (followup-to
4688         (cond
4689          ((equal (downcase followup-to) "poster")
4690           (if (or (eq message-use-followup-to 'use)
4691                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
4692 You should normally obey the Followup-To: header.
4693
4694         `Followup-To: poster'
4695 sends your response via e-mail instead of news.
4696
4697 A typical situation where `Followup-To: poster' is used is when the author
4698 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4699               (setq message-this-is-news nil
4700                     distribution nil
4701                     follow-to (list (cons 'To (or mrt from ""))))
4702             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
4703          (t
4704           (if (or (equal followup-to newsgroups)
4705                   (not (eq message-use-followup-to 'ask))
4706                   (message-y-or-n-p
4707                    (concat "Obey Followup-To: " followup-to "? ") t "\
4708 You should normally obey the Followup-To: header.
4709
4710         `Followup-To: " followup-to "'
4711 directs your response to " (if (string-match "," followup-to)
4712                                "the specified newsgroups"
4713                              "that newsgroup only") ".
4714
4715 If a message is posted to several newsgroups, Followup-To is often
4716 used to direct the following discussion to one newsgroup only,
4717 because discussions that are spread over several newsgroup tend to
4718 be fragmented and very difficult to follow.
4719
4720 Also, some source/announcement newsgroups are not indented for discussion;
4721 responses here are directed to other newsgroups."))
4722               (setq follow-to (list (cons 'Newsgroups followup-to)))
4723             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
4724        ;; Handle Mail-Followup-To, followup via e-mail.
4725        ((and mft
4726              (or (not (eq message-use-mail-followup-to 'ask))
4727                  (message-y-or-n-p
4728                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
4729 You should normally obey the Mail-Followup-To: header.
4730
4731         `Mail-Followup-To: " mft "'
4732 directs your response to " (if (string-match "," mft)
4733                                "the specified addresses"
4734                              "that address only") " instead of news.
4735
4736 A typical situation where Mail-Followup-To is used is when the author thinks
4737 that further discussion should take place only in "
4738                              (if (string-match "," mft)
4739                                  "the specified mailing lists"
4740                                "that mailing list") ".")))
4741         (setq message-this-is-news nil
4742               distribution nil
4743               follow-to (list (cons 'To mft))))
4744        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
4745        (t
4746         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
4747
4748     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4749
4750     (setq message-reply-headers
4751           (make-full-mail-header-from-decoded-header
4752            0 subject from date message-id references 0 0 ""))
4753
4754     (message-setup
4755      `((Subject . ,subject)
4756        ,@follow-to
4757        ,@(and mct (list (cons 'Cc mct)))
4758        ,@(and distribution (list (cons 'Distribution distribution)))
4759        ,@(if (or references message-id)
4760              `((References . ,(concat (or references "") (and references " ")
4761                                       (or message-id ""))))))
4762      cur)))
4763
4764 ;;;###autoload
4765 (defun message-cancel-news (&optional arg)
4766   "Cancel an article you posted.
4767 If ARG, allow editing of the cancellation message."
4768   (interactive "P")
4769   (unless (message-news-p)
4770     (error "This is not a news article; canceling is impossible"))
4771   (when (yes-or-no-p "Do you really want to cancel this article? ")
4772     (let (from newsgroups message-id distribution buf sender)
4773       (save-excursion
4774         ;; Get header info from original article.
4775         (save-restriction
4776           (message-narrow-to-head)
4777           (setq from (message-fetch-field "from")
4778                 sender (message-fetch-field "sender")
4779                 newsgroups (message-fetch-field "newsgroups")
4780                 message-id (message-fetch-field "message-id" t)
4781                 distribution (message-fetch-field "distribution")))
4782         ;; Make sure that this article was written by the user.
4783         (unless (or (and sender
4784                          (string-equal
4785                           (downcase sender)
4786                           (downcase (message-make-sender))))
4787                     (string-equal
4788                      (downcase (cadr (std11-extract-address-components
4789                                       from)))
4790                      (downcase (cadr (std11-extract-address-components
4791                                       (message-make-from))))))
4792           (error "This article is not yours"))
4793         ;; Make control message.
4794         (if arg
4795             (message-news)
4796           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4797         (erase-buffer)
4798         (insert "Newsgroups: " newsgroups "\n"
4799                 "From: " (message-make-from) "\n"
4800                 "Subject: cmsg cancel " message-id "\n"
4801                 "Control: cancel " message-id "\n"
4802                 (if distribution
4803                     (concat "Distribution: " distribution "\n")
4804                   "")
4805                 mail-header-separator "\n"
4806                 message-cancel-message)
4807         (run-hooks 'message-cancel-hook)
4808         (message "Canceling your article...")
4809         (unless arg
4810           (if (let ((message-syntax-checks
4811                      'dont-check-for-anything-just-trust-me)
4812                     (message-encoding-buffer (current-buffer))
4813                     (message-edit-buffer (current-buffer)))
4814                 (message-send-news))
4815               (message "Canceling your article...done"))
4816           (kill-buffer buf))))))
4817
4818 (defun message-supersede-setup-for-mime-edit ()
4819   (set (make-local-variable 'message-setup-hook) nil)
4820   (mime-edit-again))
4821
4822 ;;;###autoload
4823 (defun message-supersede ()
4824   "Start composing a message to supersede the current message.
4825 This is done simply by taking the old article and adding a Supersedes
4826 header line with the old Message-ID."
4827   (interactive)
4828   (let ((cur (current-buffer))
4829         (sender (message-fetch-field "sender"))
4830         (from (message-fetch-field "from")))
4831     ;; Check whether the user owns the article that is to be superseded.
4832     (unless (or (and sender
4833                      (string-equal
4834                       (downcase sender)
4835                       (downcase (message-make-sender))))
4836                 (string-equal
4837                  (downcase (cadr (std11-extract-address-components from)))
4838                  (downcase (cadr (std11-extract-address-components
4839                                   (message-make-from))))))
4840       (error "This article is not yours"))
4841     ;; Get a normal message buffer.
4842     (message-pop-to-buffer (message-buffer-name "supersede"))
4843     (insert-buffer-substring cur)
4844     (message-narrow-to-head)
4845     ;; Remove unwanted headers.
4846     (when message-ignored-supersedes-headers
4847       (message-remove-header message-ignored-supersedes-headers t))
4848     (goto-char (point-min))
4849     (if (not (re-search-forward "^Message-ID: " nil t))
4850         (error "No Message-ID in this article")
4851       (replace-match "Supersedes: " t t))
4852     (goto-char (point-max))
4853     (insert mail-header-separator)
4854     (widen)
4855     (when message-supersede-setup-function
4856       (funcall message-supersede-setup-function))
4857     (run-hooks 'message-supersede-setup-hook)
4858     (goto-char (point-min))
4859     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
4860
4861 ;;;###autoload
4862 (defun message-recover ()
4863   "Reread contents of current buffer from its last auto-save file."
4864   (interactive)
4865   (let ((file-name (make-auto-save-file-name)))
4866     (cond ((save-window-excursion
4867              (if (not (eq system-type 'vax-vms))
4868                  (with-output-to-temp-buffer "*Directory*"
4869                    (with-current-buffer standard-output
4870                      (fundamental-mode)) ; for Emacs 20.4+
4871                    (buffer-disable-undo standard-output)
4872                    (let ((default-directory "/"))
4873                      (call-process
4874                       "ls" nil standard-output nil "-l" file-name))))
4875              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4876            (let ((buffer-read-only nil))
4877              (erase-buffer)
4878              (insert-file-contents file-name nil)))
4879           (t (error "message-recover cancelled")))))
4880
4881 ;;; Washing Subject:
4882
4883 (defun message-wash-subject (subject)
4884   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4885   (with-temp-buffer
4886     (insert-string subject)
4887     (goto-char (point-min))
4888     ;; strip Re/Fwd stuff off the beginning
4889     (while (re-search-forward
4890             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4891       (replace-match ""))
4892
4893     ;; and gnus-style forwards [foo@bar.com] subject
4894     (goto-char (point-min))
4895     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4896       (replace-match ""))
4897
4898     ;; and off the end
4899     (goto-char (point-max))
4900     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4901       (replace-match ""))
4902
4903     ;; and finally, any whitespace that was left-over
4904     (goto-char (point-min))
4905     (while (re-search-forward "^[ \t]+" nil t)
4906       (replace-match ""))
4907     (goto-char (point-max))
4908     (while (re-search-backward "[ \t]+$" nil t)
4909       (replace-match ""))
4910
4911     (buffer-string)))
4912
4913 ;;; Forwarding messages.
4914
4915 (defun message-forward-subject-author-subject (subject)
4916   "Generate a subject for a forwarded message.
4917 The form is: [Source] Subject, where if the original message was mail,
4918 Source is the sender, and if the original message was news, Source is
4919 the list of newsgroups is was posted to."
4920   (concat "["
4921           (or (message-fetch-field
4922                (if (message-news-p) "newsgroups" "from"))
4923               "(nowhere)")
4924           "] " subject))
4925
4926 (defun message-forward-subject-fwd (subject)
4927   "Generate a subject for a forwarded message.
4928 The form is: Fwd: Subject, where Subject is the original subject of
4929 the message."
4930   (concat "Fwd: " subject))
4931
4932 (defun message-make-forward-subject ()
4933   "Return a Subject header suitable for the message in the current buffer."
4934   (save-excursion
4935     (save-restriction
4936       (message-narrow-to-head)
4937       (let ((funcs message-make-forward-subject-function)
4938             (subject (message-fetch-field "Subject")))
4939         (setq subject
4940               (if subject
4941                   (if message-wash-forwarded-subjects
4942                       (message-wash-subject
4943                        (nnheader-decode-subject subject))
4944                     (nnheader-decode-subject subject))
4945                 "(none)"))
4946         ;; Make sure funcs is a list.
4947         (and funcs
4948              (not (listp funcs))
4949              (setq funcs (list funcs)))
4950         ;; Apply funcs in order, passing subject generated by previous
4951         ;; func to the next one.
4952         (while funcs
4953           (when (message-functionp (car funcs))
4954             (setq subject (funcall (car funcs) subject)))
4955           (setq funcs (cdr funcs)))
4956         subject))))
4957
4958 ;;;###autoload
4959 (defun message-forward (&optional news)
4960   "Forward the current message via mail.
4961 Optional NEWS will use news to forward instead of mail."
4962   (interactive "P")
4963   (let ((cur (current-buffer))
4964         (subject (message-make-forward-subject))
4965         art-beg)
4966     (if news
4967         (message-news nil subject)
4968       (message-mail nil subject))
4969     ;; Put point where we want it before inserting the forwarded
4970     ;; message.
4971     (if message-forward-before-signature
4972         (message-goto-body)
4973       (goto-char (point-max)))
4974     ;; Make sure we're at the start of the line.
4975     (unless (bolp)
4976       (insert "\n"))
4977     ;; Narrow to the area we are to insert.
4978     (narrow-to-region (point) (point))
4979     ;; Insert the separators and the forwarded buffer.
4980     (insert message-forward-start-separator)
4981     (setq art-beg (point))
4982     (insert-buffer-substring cur)
4983     (goto-char (point-max))
4984     (insert message-forward-end-separator)
4985     (set-text-properties (point-min) (point-max) nil)
4986     ;; Remove all unwanted headers.
4987     (goto-char art-beg)
4988     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4989                                   (1- (point))
4990                                 (point)))
4991     (goto-char (point-min))
4992     (message-remove-header message-included-forward-headers t nil t)
4993     (widen)
4994     (message-position-point)))
4995
4996 ;;;###autoload
4997 (defun message-resend (address)
4998   "Resend the current article to ADDRESS."
4999   (interactive
5000    (list (message-read-from-minibuffer "Resend message to: ")))
5001   (message "Resending message to %s..." address)
5002   (save-excursion
5003     (let ((cur (current-buffer))
5004           beg)
5005       ;; We first set up a normal mail buffer.
5006       (set-buffer (get-buffer-create " *message resend*"))
5007       (erase-buffer)
5008       ;; avoid to turn-on-mime-edit
5009       (let (message-setup-hook)
5010         (message-setup `((To . ,address)))
5011         )
5012       ;; Insert our usual headers.
5013       (message-generate-headers '(From Date To))
5014       (message-narrow-to-headers)
5015       ;; Rename them all to "Resent-*".
5016       (while (re-search-forward "^[A-Za-z]" nil t)
5017         (forward-char -1)
5018         (insert "Resent-"))
5019       (widen)
5020       (forward-line)
5021       (delete-region (point) (point-max))
5022       (setq beg (point))
5023       ;; Insert the message to be resent.
5024       (insert-buffer-substring cur)
5025       (goto-char (point-min))
5026       (search-forward "\n\n")
5027       (forward-char -1)
5028       (save-restriction
5029         (narrow-to-region beg (point))
5030         (message-remove-header message-ignored-resent-headers t)
5031         (goto-char (point-max)))
5032       (insert mail-header-separator)
5033       ;; Rename all old ("Also-")Resent headers.
5034       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5035         (beginning-of-line)
5036         (insert "Also-"))
5037       ;; Quote any "From " lines at the beginning.
5038       (goto-char beg)
5039       (when (looking-at "From ")
5040         (replace-match "X-From-Line: "))
5041       ;; Send it.
5042       (let ((message-encoding-buffer (current-buffer))
5043             (message-edit-buffer (current-buffer)))
5044         (let (message-required-mail-headers)
5045           (message-send-mail)))
5046       (kill-buffer (current-buffer)))
5047     (message "Resending message to %s...done" address)))
5048
5049 (defun message-bounce-setup-for-mime-edit ()
5050   (set (make-local-variable 'message-setup-hook) nil)
5051   (mime-edit-again))
5052
5053 ;;;###autoload
5054 (defun message-bounce ()
5055   "Re-mail the current message.
5056 This only makes sense if the current message is a bounce message that
5057 contains some mail you have written which has been bounced back to
5058 you."
5059   (interactive)
5060   (let ((cur (current-buffer))
5061         boundary)
5062     (message-pop-to-buffer (message-buffer-name "bounce"))
5063     (insert-buffer-substring cur)
5064     (undo-boundary)
5065     (message-narrow-to-head)
5066     (if (and (message-fetch-field "MIME-Version")
5067              (setq boundary (message-fetch-field "Content-Type")))
5068         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
5069             (setq boundary (concat (match-string 1 boundary) " *\n"
5070                                    "Content-Type: message/rfc822"))
5071           (setq boundary nil)))
5072     (widen)
5073     (goto-char (point-min))
5074     (search-forward "\n\n" nil t)
5075     (or (and boundary
5076              (re-search-forward boundary nil t)
5077              (forward-line 2))
5078         (and (re-search-forward message-unsent-separator nil t)
5079              (forward-line 1))
5080         (re-search-forward "^Return-Path:.*\n" nil t))
5081     ;; We remove everything before the bounced mail.
5082     (delete-region
5083      (point-min)
5084      (if (re-search-forward "^[^ \n\t]+:" nil t)
5085          (match-beginning 0)
5086        (point)))
5087     (save-restriction
5088       (message-narrow-to-head)
5089       (message-remove-header message-ignored-bounced-headers t)
5090       (goto-char (point-max))
5091       (insert mail-header-separator))
5092     (when message-bounce-setup-function
5093       (funcall message-bounce-setup-function))
5094     (run-hooks 'message-bounce-setup-hook)
5095     (message-position-point)))
5096
5097 ;;;
5098 ;;; Interactive entry points for new message buffers.
5099 ;;;
5100
5101 ;;;###autoload
5102 (defun message-mail-other-window (&optional to subject)
5103   "Like `message-mail' command, but display mail buffer in another window."
5104   (interactive)
5105   (let ((pop-up-windows t)
5106         (special-display-buffer-names nil)
5107         (special-display-regexps nil)
5108         (same-window-buffer-names nil)
5109         (same-window-regexps nil))
5110     (message-pop-to-buffer (message-buffer-name "mail" to)))
5111   (let ((message-this-is-mail t))
5112     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
5113
5114 ;;;###autoload
5115 (defun message-mail-other-frame (&optional to subject)
5116   "Like `message-mail' command, but display mail buffer in another frame."
5117   (interactive)
5118   (let ((pop-up-frames t)
5119         (special-display-buffer-names nil)
5120         (special-display-regexps nil)
5121         (same-window-buffer-names nil)
5122         (same-window-regexps nil))
5123     (message-pop-to-buffer (message-buffer-name "mail" to)))
5124   (let ((message-this-is-mail t))
5125     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
5126
5127 ;;;###autoload
5128 (defun message-news-other-window (&optional newsgroups subject)
5129   "Start editing a news article to be sent."
5130   (interactive)
5131   (let ((pop-up-windows t)
5132         (special-display-buffer-names nil)
5133         (special-display-regexps nil)
5134         (same-window-buffer-names nil)
5135         (same-window-regexps nil))
5136     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5137   (let ((message-this-is-news t))
5138     (message-setup `((Newsgroups . ,(or newsgroups ""))
5139                      (Subject . ,(or subject ""))))))
5140
5141 ;;;###autoload
5142 (defun message-news-other-frame (&optional newsgroups subject)
5143   "Start editing a news article to be sent."
5144   (interactive)
5145   (let ((pop-up-frames t)
5146         (special-display-buffer-names nil)
5147         (special-display-regexps nil)
5148         (same-window-buffer-names nil)
5149         (same-window-regexps nil))
5150     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5151   (let ((message-this-is-news t))
5152     (message-setup `((Newsgroups . ,(or newsgroups ""))
5153                      (Subject . ,(or subject ""))))))
5154
5155 ;;; underline.el
5156
5157 ;; This code should be moved to underline.el (from which it is stolen).
5158
5159 ;;;###autoload
5160 (defun bold-region (start end)
5161   "Bold all nonblank characters in the region.
5162 Works by overstriking characters.
5163 Called from program, takes two arguments START and END
5164 which specify the range to operate on."
5165   (interactive "r")
5166   (save-excursion
5167     (let ((end1 (make-marker)))
5168       (move-marker end1 (max start end))
5169       (goto-char (min start end))
5170       (while (< (point) end1)
5171         (or (looking-at "[_\^@- ]")
5172             (insert (char-after) "\b"))
5173         (forward-char 1)))))
5174
5175 ;;;###autoload
5176 (defun unbold-region (start end)
5177   "Remove all boldness (overstruck characters) in the region.
5178 Called from program, takes two arguments START and END
5179 which specify the range to operate on."
5180   (interactive "r")
5181   (save-excursion
5182     (let ((end1 (make-marker)))
5183       (move-marker end1 (max start end))
5184       (goto-char (min start end))
5185       (while (re-search-forward "\b" end1 t)
5186         (if (eq (char-after) (char-after (- (point) 2)))
5187             (delete-char -2))))))
5188
5189 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5190
5191 ;; Support for toolbar
5192 (when (string-match "XEmacs\\|Lucid" emacs-version)
5193   (require 'messagexmas))
5194
5195 ;;; Group name completion.
5196
5197 (defvar message-newgroups-header-regexp
5198   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5199   "Regexp that match headers that lists groups.")
5200
5201 (defun message-tab ()
5202   "Expand group names in Newsgroups and Followup-To headers.
5203 Do a `tab-to-tab-stop' if not in those headers."
5204   (interactive)
5205   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
5206         (mail-abbrev-in-expansion-header-p))
5207       (message-expand-group)
5208     (tab-to-tab-stop)))
5209
5210 (defvar gnus-active-hashtb)
5211 (defun message-expand-group ()
5212   "Expand the group name under point."
5213   (let* ((b (save-excursion
5214               (save-restriction
5215                 (narrow-to-region
5216                  (save-excursion
5217                    (beginning-of-line)
5218                    (skip-chars-forward "^:")
5219                    (1+ (point)))
5220                  (point))
5221                 (skip-chars-backward "^, \t\n") (point))))
5222          (completion-ignore-case t)
5223          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5224                                             (point))))
5225          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5226          (completions (all-completions string hashtb))
5227          comp)
5228     (delete-region b (point))
5229     (cond
5230      ((= (length completions) 1)
5231       (if (string= (car completions) string)
5232           (progn
5233             (insert string)
5234             (message "Only matching group"))
5235         (insert (car completions))))
5236      ((and (setq comp (try-completion string hashtb))
5237            (not (string= comp string)))
5238       (insert comp))
5239      (t
5240       (insert string)
5241       (if (not comp)
5242           (message "No matching groups")
5243         (save-selected-window
5244           (pop-to-buffer "*Completions*")
5245           (buffer-disable-undo)
5246           (let ((buffer-read-only nil))
5247             (erase-buffer)
5248             (let ((standard-output (current-buffer)))
5249               (display-completion-list (sort completions 'string<)))
5250             (goto-char (point-min))
5251             (delete-region (point) (progn (forward-line 3) (point))))))))))
5252
5253 ;;; Help stuff.
5254
5255 (defun message-talkative-question (ask question show &rest text)
5256   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
5257 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
5258 The following arguments may contain lists of values."
5259   (if (and show
5260            (setq text (message-flatten-list text)))
5261       (save-window-excursion
5262         (save-excursion
5263           (with-output-to-temp-buffer " *MESSAGE information message*"
5264             (set-buffer " *MESSAGE information message*")
5265             (fundamental-mode)          ; for Emacs 20.4+
5266             (mapcar 'princ text)
5267             (goto-char (point-min))))
5268         (funcall ask question))
5269     (funcall ask question)))
5270
5271 (defun message-flatten-list (list)
5272   "Return a new, flat list that contains all elements of LIST.
5273
5274 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
5275 => (1 2 3 4 5 6 7)"
5276   (cond ((consp list)
5277          (apply 'append (mapcar 'message-flatten-list list)))
5278         (list
5279          (list list))))
5280
5281 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
5282   "Create and return a buffer with a name based on NAME using generate-new-buffer.
5283 Then clone the local variables and values from the old buffer to the
5284 new one, cloning only the locals having a substring matching the
5285 regexp varstr."
5286   (let ((oldbuf (current-buffer)))
5287     (save-excursion
5288       (set-buffer (generate-new-buffer name))
5289       (message-clone-locals oldbuf varstr)
5290       (current-buffer))))
5291
5292 (defun message-clone-locals (buffer &optional varstr)
5293   "Clone the local variables from BUFFER to the current buffer."
5294   (let ((locals (save-excursion
5295                   (set-buffer buffer)
5296                   (buffer-local-variables)))
5297         (regexp
5298          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
5299     (mapcar
5300      (lambda (local)
5301        (when (and (consp local)
5302                   (car local)
5303                   (string-match regexp (symbol-name (car local)))
5304                   (or (null varstr)
5305                       (string-match varstr (symbol-name (car local)))))
5306          (ignore-errors
5307            (set (make-local-variable (car local))
5308                 (cdr local)))))
5309      locals)))
5310
5311
5312 ;;; @ for MIME Edit mode
5313 ;;;
5314
5315 (defun message-maybe-encode ()
5316   (when message-mime-mode
5317     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
5318     (let ((pgp-processing (with-current-buffer message-edit-buffer
5319                             mime-edit-pgp-processing)))
5320       (setq mime-edit-pgp-processing pgp-processing))
5321     (run-hooks 'mime-edit-translate-hook)
5322     (if (catch 'mime-edit-error
5323           (save-excursion
5324             (mime-edit-pgp-enclose-buffer)
5325             (mime-edit-translate-body)
5326             ))
5327         (error "Translation error!")
5328       )
5329     (end-of-invisible)
5330     (run-hooks 'mime-edit-exit-hook)
5331     ))
5332
5333 (defun message-mime-insert-article (&optional full-headers)
5334   (interactive "P")
5335   (let ((message-cite-function 'mime-edit-inserted-message-filter)
5336         (message-reply-buffer
5337          (message-get-parameter-with-eval 'original-buffer))
5338         (start (point)))
5339     (message-yank-original nil)
5340     (save-excursion
5341       (narrow-to-region (goto-char start)
5342                         (if (search-forward "\n\n" nil t)
5343                             (1- (point))
5344                           (point-max)))
5345       (goto-char (point-min))
5346       (let ((message-included-forward-headers
5347              (if full-headers "" message-included-forward-headers)))
5348         (message-remove-header message-included-forward-headers t nil t))
5349       (widen))))
5350
5351 (set-alist 'mime-edit-message-inserter-alist
5352            'message-mode (function message-mime-insert-article))
5353
5354 ;;; Miscellaneous functions
5355
5356 ;; stolen (and renamed) from nnheader.el
5357 (if (fboundp 'subst-char-in-string)
5358     (defsubst message-replace-chars-in-string (string from to)
5359       (subst-char-in-string from to string))
5360   (defun message-replace-chars-in-string (string from to)
5361     "Replace characters in STRING from FROM to TO."
5362     (let ((string (substring string 0)) ;Copy string.
5363           (len (length string))
5364           (idx 0))
5365       ;; Replace all occurrences of FROM with TO.
5366       (while (< idx len)
5367         (when (= (aref string idx) from)
5368           (aset string idx to))
5369         (setq idx (1+ idx)))
5370       string)))
5371
5372 ;;;
5373 ;;; MIME functions
5374 ;;;
5375
5376 (defvar message-inhibit-body-encoding t)
5377
5378 (defun message-encode-message-body ()
5379   (unless message-inhibit-body-encoding
5380     (let ((mail-parse-charset (or mail-parse-charset
5381                                   message-default-charset))
5382           (case-fold-search t)
5383           lines content-type-p)
5384       (message-goto-body)
5385       (save-restriction
5386         (narrow-to-region (point) (point-max))
5387         (let ((new (mml-generate-mime)))
5388           (when new
5389             (delete-region (point-min) (point-max))
5390             (insert new)
5391             (goto-char (point-min))
5392             (if (eq (aref new 0) ?\n)
5393                 (delete-char 1)
5394               (search-forward "\n\n")
5395               (setq lines (buffer-substring (point-min) (1- (point))))
5396               (delete-region (point-min) (point))))))
5397       (save-restriction
5398         (message-narrow-to-headers-or-head)
5399         (message-remove-header "Mime-Version")
5400         (goto-char (point-max))
5401         (insert "MIME-Version: 1.0\n")
5402         (when lines
5403           (insert lines))
5404         (setq content-type-p
5405               (re-search-backward "^Content-Type:" nil t)))
5406       (save-restriction
5407         (message-narrow-to-headers-or-head)
5408         (message-remove-first-header "Content-Type")
5409         (message-remove-first-header "Content-Transfer-Encoding"))
5410       ;; We always make sure that the message has a Content-Type header.
5411       ;; This is because some broken MTAs and MUAs get awfully confused
5412       ;; when confronted with a message with a MIME-Version header and
5413       ;; without a Content-Type header.  For instance, Solaris'
5414       ;; /usr/bin/mail.
5415       (unless content-type-p
5416         (goto-char (point-min))
5417         (re-search-forward "^MIME-Version:")
5418         (forward-line 1)
5419         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
5420
5421 (defun message-read-from-minibuffer (prompt)
5422   "Read from the minibuffer while providing abbrev expansion."
5423   (if (fboundp 'mail-abbrevs-setup)
5424       (let ((mail-abbrev-mode-regexp "")
5425             (minibuffer-setup-hook 'mail-abbrevs-setup))
5426         (read-from-minibuffer prompt))
5427     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
5428       (read-string prompt))))
5429
5430 (defun message-save-drafts ()
5431   "Postponing the message."
5432   (interactive)
5433   (message "Saving %s..." buffer-file-name)
5434   (let ((reply-headers message-reply-headers)
5435         (msg (buffer-substring-no-properties (point-min) (point-max))))
5436     (with-temp-file buffer-file-name
5437       (insert msg)
5438       (setq message-reply-headers reply-headers)
5439       (message-generate-headers '((optional . In-Reply-To)))
5440       (mime-edit-translate-buffer))
5441     (set-buffer-modified-p nil))
5442   (message "Saving %s...done" buffer-file-name))
5443
5444 (provide 'message)
5445
5446 (run-hooks 'message-load-hook)
5447
5448 ;; Local Variables:
5449 ;; coding: iso-8859-1
5450 ;; End:
5451
5452 ;;; message.el ends here