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