5134cae397999c67f0f3a706bda6271a9070266a
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;;      Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
8 ;;      Keiichi Suzuki   <kei-suzu@mail.wbs.ne.jp>
9 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
10 ;;      Katsumi Yamaoka  <yamaoka@jpl.org>
11 ;;      Kiyokazu SUTO    <suto@merry.xmath.ous.ac.jp>
12 ;; Keywords: mail, news, MIME
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
28 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
29 ;; Boston, MA 02111-1307, USA.
30
31 ;;; Commentary:
32
33 ;; This mode provides mail-sending facilities from within Emacs.  It
34 ;; consists mainly of large chunks of code from the sendmail.el,
35 ;; gnus-msg.el and rnewspost.el files.
36
37 ;;; Code:
38
39 (eval-when-compile
40   (require 'cl)
41   (require 'smtp)
42   (defvar gnus-list-identifiers)) ; gnus-sum is required where necessary
43 (eval-and-compile
44   (if (boundp 'MULE)
45       (progn
46         (require 'base64)
47         (require 'canlock-om))
48     (require 'canlock)))
49 (require 'mailheader)
50 (require 'nnheader)
51 ;; This is apparently necessary even though things are autoloaded.
52 ;; Because we dynamically bind mail-abbrev-mode-regexp, we'd better
53 ;; require mailabbrev here.
54 (if (featurep 'xemacs)
55     (require 'mail-abbrevs)
56   (require 'mailabbrev))
57 (require 'mime-edit)
58 (eval-when-compile (require 'static))
59
60 ;; Avoid byte-compile warnings.
61 (eval-when-compile
62   (require 'mail-parse)
63   (require 'mml))
64
65 (require 'rfc822)
66 (eval-and-compile
67   (autoload 'sha1 "sha1-el")
68   (autoload 'customize-save-variable "cus-edit"));; for Mule 2.
69
70 (defgroup message '((user-mail-address custom-variable)
71                     (user-full-name custom-variable))
72   "Mail and news message composing."
73   :link '(custom-manual "(message)Top")
74   :group 'mail
75   :group 'news)
76
77 (put 'user-mail-address 'custom-type 'string)
78 (put 'user-full-name 'custom-type 'string)
79
80 (defgroup message-various nil
81   "Various Message Variables"
82   :link '(custom-manual "(message)Various Message Variables")
83   :group 'message)
84
85 (defgroup message-buffers nil
86   "Message Buffers"
87   :link '(custom-manual "(message)Message Buffers")
88   :group 'message)
89
90 (defgroup message-sending nil
91   "Message Sending"
92   :link '(custom-manual "(message)Sending Variables")
93   :group 'message)
94
95 (defgroup message-interface nil
96   "Message Interface"
97   :link '(custom-manual "(message)Interface")
98   :group 'message)
99
100 (defgroup message-forwarding nil
101   "Message Forwarding"
102   :link '(custom-manual "(message)Forwarding")
103   :group 'message-interface)
104
105 (defgroup message-insertion nil
106   "Message Insertion"
107   :link '(custom-manual "(message)Insertion")
108   :group 'message)
109
110 (defgroup message-headers nil
111   "Message Headers"
112   :link '(custom-manual "(message)Message Headers")
113   :group 'message)
114
115 (defgroup message-news nil
116   "Composing News Messages"
117   :group 'message)
118
119 (defgroup message-mail nil
120   "Composing Mail Messages"
121   :group 'message)
122
123 (defgroup message-faces nil
124   "Faces used for message composing."
125   :group 'message
126   :group 'faces)
127
128 (defgroup message-frames nil
129   "Message frames"
130   :group 'message)
131
132 (defcustom message-directory "~/Mail/"
133   "*Directory from which all other mail file variables are derived."
134   :group 'message-various
135   :type 'directory)
136
137 (defcustom message-max-buffers 10
138   "*How many buffers to keep before starting to kill them off."
139   :group 'message-buffers
140   :type 'integer)
141
142 (defcustom message-send-rename-function nil
143   "Function called to rename the buffer after sending it."
144   :group 'message-buffers
145   :type '(choice function (const nil)))
146
147 (defcustom message-fcc-handler-function 'message-output
148   "*A function called to save outgoing articles.
149 This function will be called with the name of the file to store the
150 article in.  The default function is `message-output' which saves in Unix
151 mailbox format."
152   :type '(radio (function-item message-output)
153                 (function :tag "Other"))
154   :group 'message-sending)
155
156 (defcustom message-encode-function 'message-maybe-encode
157   "*A function called to encode messages."
158   :group 'message-sending
159   :type 'function)
160
161 (defcustom message-8bit-encoding-list '(8bit binary)
162   "*8bit encoding type in Content-Transfer-Encoding field."
163   :group 'message-sending
164   :type '(repeat (symbol :tag "Type")))
165
166 (defcustom message-fcc-externalize-attachments nil
167   "If non-nil, attachments are included as external parts in Fcc copies."
168   :type 'boolean
169   :group 'message-sending)
170
171 (defcustom message-courtesy-message
172   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
173   "*This is inserted at the start of a mailed copy of a posted message.
174 If the string contains the format spec \"%s\", the Newsgroups
175 the article has been posted to will be inserted there.
176 If this variable is nil, no such courtesy message will be added."
177   :group 'message-sending
178   :type 'string)
179
180 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
181   "*Regexp that matches headers to be removed in resent bounced mail."
182   :group 'message-interface
183   :type 'regexp)
184
185 (defcustom message-bounce-setup-function 'message-bounce-setup-for-mime-edit
186   "Function to setup a re-sending bounced message."
187   :group 'message-sending
188   :type 'function)
189
190 ;;; Start of variables adopted from `message-utils.el'.
191
192 (defcustom message-subject-trailing-was-query 'ask
193   ;; should it default to nil or ask?
194   "*What to do with trailing \"(was: <old subject>)\" in subject lines.
195 If nil, leave the subject unchanged.  If it is the symbol `ask', query
196 the user what do do.  In this case, the subject is matched against
197 `message-subject-trailing-was-ask-regexp'.  If
198 `message-subject-trailing-was-query' is t, always strip the trailing
199 old subject.  In this case, `message-subject-trailing-was-regexp' is
200 used."
201   :type '(choice (const :tag "never" nil)
202                  (const :tag "always strip" t)
203                  (const ask))
204   :group 'message-various)
205
206 (defcustom message-subject-trailing-was-ask-regexp
207   "[ \t]*\\([[(]+[Ww][Aa][Ss][ \t]*.*[\])]+\\)"
208   "*Regexp matching \"(was: <old subject>)\" in the subject line.
209
210 The function `message-strip-subject-trailing-was' uses this regexp if
211 `message-subject-trailing-was-query' is set to the symbol `ask'.  If
212 the variable is t instead of `ask', use
213 `message-subject-trailing-was-regexp' instead.
214
215 It is okay to create some false positives here, as the user is asked."
216   :group 'message-various
217   :type 'regexp)
218
219 (defcustom message-subject-trailing-was-regexp
220   "[ \t]*\\((*[Ww][Aa][Ss]:[ \t]*.*)\\)"
221   "*Regexp matching \"(was: <old subject>)\" in the subject line.
222
223 If `message-subject-trailing-was-query' is set to t, the subject is
224 matched against `message-subject-trailing-was-regexp' in
225 `message-strip-subject-trailing-was'.  You should use a regexp creating very
226 few false positives here."
227   :group 'message-various
228   :type 'regexp)
229
230 ;;; marking inserted text
231
232 ;;;###autoload
233 (defcustom message-mark-insert-begin
234   "--8<---------------cut here---------------start------------->8---\n"
235   "How to mark the beginning of some inserted text."
236   :type 'string
237   :group 'message-various)
238
239 ;;;###autoload
240 (defcustom message-mark-insert-end
241   "--8<---------------cut here---------------end--------------->8---\n"
242   "How to mark the end of some inserted text."
243   :type 'string
244   :group 'message-various)
245
246 ;;;###autoload
247 (defcustom message-archive-header
248   "X-No-Archive: Yes\n"
249   "Header to insert when you don't want your article to be archived.
250 Archives \(such as groups.googgle.com\) respect this header."
251   :type 'string
252   :group 'message-various)
253
254 ;;;###autoload
255 (defcustom message-archive-note
256   "X-No-Archive: Yes - save http://groups.google.com/"
257   "Note to insert why you wouldn't want this posting archived.
258 If nil, don't insert any text in the body."
259   :type 'string
260   :group 'message-various)
261
262 ;;; Crossposts and Followups
263 ;; inspired by JoH-followup-to by Jochem Huhman <joh  at gmx.de>
264 ;; new suggestions by R. Weikusat <rw at another.de>
265
266 (defvar message-cross-post-old-target nil
267   "Old target for cross-posts or follow-ups.")
268 (make-variable-buffer-local 'message-cross-post-old-target)
269
270 ;;;###autoload
271 (defcustom message-cross-post-default t
272   "When non-nil `message-cross-post-followup-to' will perform a crosspost.
273 If nil, `message-cross-post-followup-to' will only do a followup.  Note that
274 you can explicitly override this setting by calling
275 `message-cross-post-followup-to' with a prefix."
276   :type 'boolean
277   :group 'message-various)
278
279 ;;;###autoload
280 (defcustom message-cross-post-note
281   "Crosspost & Followup-To: "
282   "Note to insert before signature to notify of xpost and follow-up."
283   :type 'string
284   :group 'message-various)
285
286 ;;;###autoload
287 (defcustom message-followup-to-note
288   "Followup-To: "
289   "Note to insert before signature to notify of follow-up only."
290   :type 'string
291   :group 'message-various)
292
293 ;;;###autoload
294 (defcustom message-cross-post-note-function
295   'message-cross-post-insert-note
296   "Function to use to insert note about Crosspost or Followup-To.
297 The function will be called with four arguments.  The function should not only
298 insert a note, but also ensure old notes are deleted.  See the documentation
299 for `message-cross-post-insert-note'."
300   :type 'function
301   :group 'message-various)
302
303 ;;; End of variables adopted from `message-utils.el'.
304
305 ;;;###autoload
306 (defcustom message-from-style 'default
307   "*Specifies how \"From\" headers look.
308
309 If nil, they contain just the return address like:
310         king@grassland.com
311 If `parens', they look like:
312         king@grassland.com (Elvis Parsley)
313 If `angles', they look like:
314         Elvis Parsley <king@grassland.com>
315
316 Otherwise, most addresses look like `angles', but they look like
317 `parens' if `angles' would need quoting and `parens' would not."
318   :type '(choice (const :tag "simple" nil)
319                  (const parens)
320                  (const angles)
321                  (const default))
322   :group 'message-headers)
323
324 (defcustom message-insert-canlock t
325   "Whether to insert a Cancel-Lock header in news postings."
326   :version "21.3"
327   :group 'message-headers
328   :type 'boolean)
329
330 (defcustom message-syntax-checks
331   (if message-insert-canlock '((sender . disabled)) nil)
332   ;; Guess this one shouldn't be easy to customize...
333   "*Controls what syntax checks should not be performed on outgoing posts.
334 To disable checking of long signatures, for instance, add
335  `(signature . disabled)' to this list.
336
337 Don't touch this variable unless you really know what you're doing.
338
339 Checks include `subject-cmsg', `multiple-headers', `sendsys',
340 `message-id', `from', `long-lines', `control-chars', `size',
341 `new-text', `quoting-style', `redirected-followup', `signature',
342 `approved', `sender', `empty', `empty-headers', `message-id', `from',
343 `subject', `shorten-followup-to', `existing-newsgroups',
344 `buffer-file-name', `unchanged', `newsgroups', `reply-to',
345 'continuation-headers', and `long-header-lines'."
346   :group 'message-news
347   :type '(repeat sexp))                 ; Fixme: improve this
348
349 (defcustom message-required-headers '((optional . References) From)
350   "*Headers to be generated or prompted for when sending a message.
351 Also see `message-required-news-headers' and
352 `message-required-mail-headers'."
353   :group 'message-news
354   :group 'message-headers
355   :type '(repeat sexp))
356
357 (defcustom message-draft-headers '(References From)
358   "*Headers to be generated when saving a draft message."
359   :group 'message-news
360   :group 'message-headers
361   :type '(repeat sexp))
362
363 (defcustom message-required-news-headers
364   '(From Newsgroups Subject Date Message-ID
365          (optional . Organization)
366          (optional . User-Agent))
367   "*Headers to be generated or prompted for when posting an article.
368 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
369 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
370 User-Agent are optional.  If don't you want message to insert some
371 header, remove it from this list."
372   :group 'message-news
373   :group 'message-headers
374   :type '(repeat sexp))
375
376 (defcustom message-required-mail-headers
377   '(From Subject Date (optional . In-Reply-To) Message-ID
378          (optional . User-Agent))
379   "*Headers to be generated or prompted for when mailing a message.
380 It is recommended that From, Date, To, Subject and Message-ID be
381 included.  Organization and User-Agent are optional."
382   :group 'message-mail
383   :group 'message-headers
384   :type '(repeat sexp))
385
386 (defcustom message-deletable-headers '(Message-ID Date Lines)
387   "Headers to be deleted if they already exist and were generated by message previously."
388   :group 'message-headers
389   :type 'sexp)
390
391 (defcustom message-ignored-news-headers
392   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
393   "*Regexp of headers to be removed unconditionally before posting."
394   :group 'message-news
395   :group 'message-headers
396   :type 'regexp)
397
398 (defcustom message-ignored-mail-headers
399   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
400   "*Regexp of headers to be removed unconditionally before mailing."
401   :group 'message-mail
402   :group 'message-headers
403   :type 'regexp)
404
405 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:\\|^Cancel-Lock:\\|^Cancel-Key:\\|^X-Hashcash:"
406   "*Header lines matching this regexp will be deleted before posting.
407 It's best to delete old Path and Date headers before posting to avoid
408 any confusion."
409   :group 'message-interface
410   :type 'regexp)
411
412 (defcustom message-supersede-setup-function
413   'message-supersede-setup-for-mime-edit
414   "Function to setup a supersede message."
415   :group 'message-sending
416   :type 'function)
417
418 (defcustom message-subject-re-regexp
419   "^[ \t]*\\([Rr][Ee]\\(\\[[0-9]*\\]\\)*:[ \t]*\\)*[ \t]*"
420   "*Regexp matching \"Re: \" in the subject line."
421   :group 'message-various
422   :type 'regexp)
423
424 ;;; Some sender agents encode the whole subject including leading "Re: ".
425 ;;; And if followup agent does not decode it for some reason (e.g. unknown
426 ;;; charset) and just add a new "Re: " in front of the encoded-word, the
427 ;;; result will contain multiple "Re: "'s.
428 (defcustom message-subject-encoded-re-regexp
429   (concat
430    "^[ \t]*"
431    (regexp-quote "=?")
432    "[-!#$%&'*+0-9A-Z^_`a-z{|}~]+" ; charset
433    (regexp-quote "?")
434    "\\("
435    "[Bb]" (regexp-quote "?") ; B encoding
436    "\\(\\(CQk\\|CSA\\|IAk\\|ICA\\)[Jg]\\)*" ; \([ \t][ \t][ \t]\)*
437    "\\("
438    "[Uc][km]U6" ; [Rr][Ee]:
439    "\\|"
440    "\\(C[VX]\\|I[FH]\\)J[Fl]O[g-v]" ; [ \t][Rr][Ee]:
441    "\\|"
442    "\\(CQl\\|CSB\\|IAl\\|ICB\\)[Sy][RZ]T[o-r]" ; [ \t][ \t][Rr][Ee]:
443    "\\)"
444    "\\|"
445    "[Qb]" (regexp-quote "?") ; Q encoding
446    "\\(_\\|=09\\|=20\\)*"
447    "\\([Rr]\\|=[57]2\\)\\([Ee]\\|=[46]5\\)\\(:\\|=3[Aa]\\)"
448    "\\)"
449    )
450   "*Regexp matching \"Re: \" in the subject line.
451 Unlike `message-subject-re-regexp', this regexp matches \"Re: \" within
452 an encoded-word."
453   :group 'message-various
454   :type 'regexp)
455
456 (defcustom message-use-subject-re t
457   "*If t, remove any (buggy) \"Re: \"'s from the subject of the precursor
458 and add a new \"Re: \".  If it is nil, use the subject \"as-is\".  If it
459 is the symbol `guess', try to detect \"Re: \" within an encoded-word."
460   :group 'message-various
461   :type '(choice (const :tag "off" nil)
462                  (const :tag "on" t)
463                  (const guess)))
464
465 ;;;###autoload
466 (defcustom message-signature-separator "^-- *$"
467   "Regexp matching the signature separator."
468   :type 'regexp
469   :group 'message-various)
470
471 (defcustom message-signature-separator-for-insertion "-- \n"
472   "*Signature separator. This value will be inserted as signature separator
473 when composing message. Default value is \"-- \\n\". Notice: Changing this
474 value may go against RFC-1036 and draft-ietf-usefor-article-05.txt. "
475   :type 'string
476   :group 'message-insertion)
477
478 (defcustom message-elide-ellipsis "\n[...]\n\n"
479   "*The string which is inserted for elided text."
480   :type 'string
481   :group 'message-various)
482
483 (defcustom message-interactive t
484   "Non-nil means when sending a message wait for and display errors.
485 nil means let mailer mail back a message to report errors."
486   :group 'message-sending
487   :group 'message-mail
488   :type 'boolean)
489
490 (defcustom message-generate-new-buffers 'unique
491   "*Non-nil means create a new message buffer whenever `message-setup' is called.
492 If this is a function, call that function with three parameters:  The type,
493 the to address and the group name.  (Any of these may be nil.)  The function
494 should return the new buffer name."
495   :group 'message-buffers
496   :type '(choice (const :tag "off" nil)
497                  (const :tag "unique" unique)
498                  (const :tag "unsent" unsent)
499                  (function fun)))
500
501 (defcustom message-kill-buffer-on-exit nil
502   "*Non-nil means that the message buffer will be killed after sending a message."
503   :group 'message-buffers
504   :type 'boolean)
505
506 (defcustom message-kill-buffer-query-function 'yes-or-no-p
507   "*Function used to prompt user whether to kill the message buffer.  If
508 it is t, the buffer will be killed unconditionally."
509   :type '(radio (function-item yes-or-no-p)
510                 (function-item y-or-n-p)
511                 (function-item nnheader-Y-or-n-p)
512                 (function :tag "Other" t))
513   :group 'message-buffers)
514
515 (defcustom message-kill-buffer-and-remove-file t
516   "*Non-nil means that the associated file will be removed before
517 removing the message buffer.  However, it is treated as nil when the
518 command `message-mimic-kill-buffer' is used."
519   :group 'message-buffers
520   :type 'boolean)
521
522 (eval-when-compile
523   (defvar gnus-local-organization))
524 (defcustom message-user-organization
525   (or (and (boundp 'gnus-local-organization)
526            (stringp gnus-local-organization)
527            gnus-local-organization)
528       (getenv "ORGANIZATION")
529       t)
530   "*String to be used as an Organization header.
531 If t, use `message-user-organization-file'."
532   :group 'message-headers
533   :type '(choice string
534                  (const :tag "consult file" t)))
535
536 ;;;###autoload
537 (defcustom message-user-organization-file "/usr/lib/news/organization"
538   "*Local news organization file."
539   :type 'file
540   :group 'message-headers)
541
542 (defcustom message-forward-start-separator
543   (concat (mime-make-tag "message" "rfc822") "\n")
544   "*Delimiter inserted before forwarded messages."
545   :group 'message-forwarding
546   :type 'string)
547
548 (defcustom message-forward-end-separator
549   (concat (mime-make-tag "text" "plain") "\n")
550   "*Delimiter inserted after forwarded messages."
551   :group 'message-forwarding
552   :type 'string)
553
554 (defcustom message-included-forward-headers
555   "^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:"
556   "*Regexp matching headers to be included in forwarded messages."
557   :group 'message-forwarding
558   :type 'regexp)
559
560 (defcustom message-make-forward-subject-function
561   'message-forward-subject-author-subject
562   "*List of functions called to generate subject headers for forwarded messages.
563 The subject generated by the previous function is passed into each
564 successive function.
565
566 The provided functions are:
567
568 * `message-forward-subject-author-subject' (Source of article (author or
569       newsgroup)), in brackets followed by the subject
570 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
571       to it."
572   :group 'message-forwarding
573   :type '(radio (function-item message-forward-subject-author-subject)
574                 (function-item message-forward-subject-fwd)
575                 (repeat :tag "List of functions" function)))
576
577 (defcustom message-forward-as-mime t
578   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
579   :version "21.1"
580   :group 'message-forwarding
581   :type 'boolean)
582
583 (defcustom message-forward-show-mml t
584   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
585   :version "21.1"
586   :group 'message-forwarding
587   :type 'boolean)
588
589 (defcustom message-forward-before-signature t
590   "*If non-nil, put forwarded message before signature, else after."
591   :group 'message-forwarding
592   :type 'boolean)
593
594 (defcustom message-wash-forwarded-subjects nil
595   "*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."
596   :group 'message-forwarding
597   :type 'boolean)
598
599 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:\\|^>?From "
600   "*All headers that match this regexp will be deleted when resending a message."
601   :group 'message-interface
602   :type 'regexp)
603
604 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
605   "*All headers that match this regexp will be deleted when forwarding a message."
606   :version "21.1"
607   :group 'message-forwarding
608   :type '(choice (const :tag "None" nil)
609                  regexp))
610
611 (defcustom message-ignored-cited-headers "."
612   "*Delete these headers from the messages you yank."
613   :group 'message-insertion
614   :type 'regexp)
615
616 (defcustom message-cite-prefix-regexp
617   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
618       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>|}+]\\)+"
619     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
620     (let ((old-table (syntax-table))
621           non-word-constituents)
622       (set-syntax-table text-mode-syntax-table)
623       (setq non-word-constituents
624             (concat
625              (if (string-match "\\w" "-")  "" "-")
626              (if (string-match "\\w" "_")  "" "_")
627              (if (string-match "\\w" ".")  "" ".")))
628       (set-syntax-table old-table)
629       (if (equal non-word-constituents "")
630           "\\([ \t]*\\(\\w\\)+>+\\|[ \t]*[]>|}+]\\)+"
631         (concat "\\([ \t]*\\(\\w\\|["
632                 non-word-constituents
633                 "]\\)+>+\\|[ \t]*[]>|}+]\\)+"))))
634   "*Regexp matching the longest possible citation prefix on a line."
635   :group 'message-insertion
636   :type 'regexp)
637
638 (defcustom message-cancel-message "I am canceling my own article.\n"
639   "Message to be inserted in the cancel message."
640   :group 'message-interface
641   :type 'string)
642
643 ;; Useful to set in site-init.el
644 ;;;###autoload
645 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
646   "Function to call to send the current buffer as mail.
647 The headers should be delimited by a line whose contents match the
648 variable `mail-header-separator'.
649
650 Valid values include `message-send-mail-with-sendmail' (the default),
651 `message-send-mail-with-mh', `message-send-mail-with-qmail',
652 `message-send-mail-with-smtp', `message-smtpmail-send-it',
653 `smtpmail-send-it' and `feedmail-send-it'.
654
655 See also `send-mail-function'."
656   :type '(radio (function-item message-send-mail-with-sendmail)
657                 (function-item message-send-mail-with-mh)
658                 (function-item message-send-mail-with-qmail)
659                 (function-item message-send-mail-with-smtp)
660                 (function-item message-smtpmail-send-it)
661                 (function-item smtpmail-send-it)
662                 (function-item feedmail-send-it)
663                 (function :tag "Other"))
664   :group 'message-sending
665   :group 'message-mail)
666
667 ;; 1997-09-29 by MORIOKA Tomohiko
668 (defcustom message-send-news-function 'message-send-news-with-gnus
669   "Function to call to send the current buffer as news.
670 The headers should be delimited by a line whose contents match the
671 variable `mail-header-separator'."
672   :group 'message-sending
673   :group 'message-news
674   :type 'function)
675
676 (defcustom message-reply-to-function nil
677   "If non-nil, function that should return a list of headers.
678 This function should pick out addresses from the To, Cc, and From headers
679 and respond with new To and Cc headers."
680   :group 'message-interface
681   :type '(choice function (const nil)))
682
683 (defcustom message-wide-reply-to-function nil
684   "If non-nil, function that should return a list of headers.
685 This function should pick out addresses from the To, Cc, and From headers
686 and respond with new To and Cc headers."
687   :group 'message-interface
688   :type '(choice function (const nil)))
689
690 (defcustom message-followup-to-function nil
691   "If non-nil, function that should return a list of headers.
692 This function should pick out addresses from the To, Cc, and From headers
693 and respond with new To and Cc headers."
694   :group 'message-interface
695   :type '(choice function (const nil)))
696
697 (defcustom message-use-followup-to 'ask
698   "*Specifies what to do with Followup-To header.
699 If nil, always ignore the header.  If it is t, use its value, but
700 query before using the \"poster\" value.  If it is the symbol `ask',
701 always query the user whether to use the value.  If it is the symbol
702 `use', always use the value."
703   :group 'message-interface
704   :type '(choice (const :tag "ignore" nil)
705                  (const :tag "use & query" t)
706                  (const :tag "maybe" t)
707                  (const :tag "always" use)
708                  (const :tag "ask" ask)))
709
710 (defcustom message-use-mail-copies-to 'ask
711   "*Specifies what to do with Mail-Copies-To header.
712 If nil, always ignore the header.  If it is t, use its value, but
713 query before using the value other than \"always\" or \"never\".
714 If it is the symbol `ask', always query the user whether to use
715 the value.  If it is the symbol `use', always use the value."
716   :group 'message-interface
717   :type '(choice (const :tag "ignore" nil)
718                  (const :tag "maybe" t)
719                  (const :tag "always" use)
720                  (const :tag "ask" ask)))
721
722 ;;; XXX: 'ask and 'use are not implemented yet.
723 (defcustom message-use-mail-reply-to 'ask
724   "*Specifies what to do with Mail-Reply-To/Reply-To header.
725 If nil, always ignore the header.  If it is t or the symbol `use', use
726 its value.  If it is the symbol `ask', always query the user whether to
727 use the value.  Note that if \"Reply-To\" is marked as \"broken\", its value
728 is never used."
729   :group 'message-interface
730   :type '(choice (const :tag "ignore" nil)
731                  (const :tag "maybe" t)
732                  (const :tag "always" use)
733                  (const :tag "ask" ask)))
734
735 (defcustom message-use-mail-followup-to 'use
736   "*Specifies what to do with Mail-Followup-To header.
737 If nil, always ignore the header.  If it is the symbol `ask', always
738 query the user whether to use the value.  If it is t or the symbol
739 `use', always use the value."
740   :group 'message-interface
741   :type '(choice (const :tag "ignore" nil)
742                  (const :tag "maybe" t)
743                  (const :tag "always" use)
744                  (const :tag "ask" ask)))
745
746 (defcustom message-subscribed-address-functions nil
747   "*Specifies functions for determining list subscription.
748 If nil, do not attempt to determine list subscribtion with functions.
749 If non-nil, this variable contains a list of functions which return
750 regular expressions to match lists.  These functions can be used in
751 conjunction with `message-subscribed-regexps' and
752 `message-subscribed-addresses'."
753   :group 'message-interface
754   :type '(repeat sexp))
755
756 (defcustom message-subscribed-address-file nil
757   "*A file containing addresses the user is subscribed to.
758 If nil, do not look at any files to determine list subscriptions.  If
759 non-nil, each line of this file should be a mailing list address."
760   :group 'message-interface
761   :type 'string)
762
763 (defcustom message-subscribed-addresses nil
764   "*Specifies a list of addresses the user is subscribed to.
765 If nil, do not use any predefined list subscriptions.  This list of
766 addresses can be used in conjuction with
767 `message-subscribed-address-functions' and `message-subscribed-regexps'."
768   :group 'message-interface
769   :type '(repeat string))
770
771 (defcustom message-subscribed-regexps nil
772   "*Specifies a list of addresses the user is subscribed to.
773 If nil, do not use any predefined list subscriptions.  This list of
774 regular expressions can be used in conjuction with
775 `message-subscribed-address-functions' and `message-subscribed-addresses'."
776   :group 'message-interface
777   :type '(repeat regexp))
778
779 (defcustom message-allow-no-recipients 'ask
780   "Specifies what to do when there are no recipients other than Gcc/Fcc.
781 If it is the symbol `always', the posting is allowed.  If it is the
782 symbol `never', the posting is not allowed.  If it is the symbol
783 `ask', you are prompted."
784   :group 'message-interface
785   :type '(choice (const always)
786                  (const never)
787                  (const ask)))
788
789 (defcustom message-sendmail-f-is-evil nil
790   "*Non-nil means don't add \"-f username\" to the sendmail command line.
791 Doing so would be even more evil than leaving it out."
792   :group 'message-sending
793   :type 'boolean)
794
795 (defcustom message-sendmail-envelope-from nil
796   "*Envelope-from when sending mail with sendmail.
797 If this is nil, use `user-mail-address'.  If it is the symbol
798 `header', use the From: header of the message."
799   :type '(choice (string :tag "From name")
800                  (const :tag "Use From: header from message" header)
801                  (const :tag "Use `user-mail-address'" nil))
802   :group 'message-sending)
803
804 ;; qmail-related stuff
805 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
806   "Location of the qmail-inject program."
807   :group 'message-sending
808   :type 'file)
809
810 (defcustom message-qmail-inject-args nil
811   "Arguments passed to qmail-inject programs.
812 This should be a list of strings, one string for each argument.  It
813 may also be a function.
814
815 For e.g., if you wish to set the envelope sender address so that bounces
816 go to the right place or to deal with listserv's usage of that address, you
817 might set this variable to '(\"-f\" \"you@some.where\")."
818   :group 'message-sending
819   :type '(choice (function)
820                  (repeat string)))
821
822 (defvar message-cater-to-broken-inn t
823   "Non-nil means Gnus should not fold the `References' header.
824 Folding `References' makes ancient versions of INN create incorrect
825 NOV lines.")
826
827 (eval-when-compile
828   (defvar gnus-post-method)
829   (defvar gnus-select-method))
830 (defcustom message-post-method
831   (cond ((and (boundp 'gnus-post-method)
832               (listp gnus-post-method)
833               gnus-post-method)
834          gnus-post-method)
835         ((boundp 'gnus-select-method)
836          gnus-select-method)
837         (t '(nnspool "")))
838   "*Method used to post news.
839 Note that when posting from inside Gnus, for instance, this
840 variable isn't used."
841   :group 'message-news
842   :group 'message-sending
843   ;; This should be the `gnus-select-method' widget, but that might
844   ;; create a dependence to `gnus.el'.
845   :type 'sexp)
846
847 (defcustom message-generate-headers-first nil
848   "*If non-nil, generate all required headers before composing.
849 The variables `message-required-news-headers' and
850 `message-required-mail-headers' specify which headers to generate.
851 This can also be a list of headers that should be generated before
852 composing.
853
854 Note that the variable `message-deletable-headers' specifies headers which
855 are to be deleted and then re-generated before sending, so this variable
856 will not have a visible effect for those headers."
857   :group 'message-headers
858   :type '(choice (const :tag "None" nil)
859                  (const :tag "All" t)
860                  (repeat (sexp :tag "Header"))))
861
862 (defcustom message-setup-hook '(turn-on-mime-edit)
863   "Normal hook, run each time a new outgoing message is initialized.
864 The function `message-setup' runs this hook."
865   :group 'message-various
866   :type 'hook)
867
868 (defcustom message-cancel-hook nil
869   "Hook run when cancelling articles."
870   :group 'message-various
871   :type 'hook)
872
873 (defcustom message-signature-setup-hook nil
874   "Normal hook, run each time a new outgoing message is initialized.
875 It is run after the headers have been inserted and before
876 the signature is inserted."
877   :group 'message-various
878   :type 'hook)
879
880 (defcustom message-bounce-setup-hook nil
881   "Normal hook, run each time a re-sending bounced message is initialized.
882 The function `message-bounce' runs this hook."
883   :group 'message-various
884   :type 'hook)
885
886 (defcustom message-supersede-setup-hook nil
887   "Normal hook, run each time a supersede message is initialized.
888 The function `message-supersede' runs this hook."
889   :group 'message-various
890   :type 'hook)
891
892 (defcustom message-mode-hook nil
893   "Hook run in message mode buffers."
894   :group 'message-various
895   :type 'hook)
896
897 (defcustom message-header-hook '((lambda () (mime-encode-header-in-buffer t)))
898   "Hook run in a message mode buffer narrowed to the headers."
899   :group 'message-various
900   :type 'hook)
901
902 (defcustom message-header-setup-hook nil
903   "Hook called narrowed to the headers when setting up a message buffer."
904   :group 'message-various
905   :type 'hook)
906
907 (defcustom message-minibuffer-local-map
908   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
909     (set-keymap-parent map minibuffer-local-map)
910     map)
911   "Keymap for `message-read-from-minibuffer'.")
912
913 ;;;###autoload
914 (defcustom message-citation-line-function 'message-insert-citation-line
915   "*Function called to insert the \"Whomever writes:\" line.
916
917 Note that Gnus provides a feature where the reader can click on
918 `writes:' to hide the cited text.  If you change this line too much,
919 people who read your message will have to change their Gnus
920 configuration.  See the variable `gnus-cite-attribution-suffix'."
921   :type 'function
922   :group 'message-insertion)
923
924 ;;;###autoload
925 (defcustom message-yank-prefix "> "
926   "*Prefix inserted on the lines of yanked messages.
927 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
928 See also `message-yank-cited-prefix'."
929   :type 'string
930   :group 'message-insertion)
931
932 (defcustom message-yank-add-new-references t
933   "Non-nil means new IDs will be added to \"References\" field when an
934 article is yanked by the command `message-yank-original' interactively.
935 If it is a symbol `message-id-only', only an ID from \"Message-ID\" field
936 is used, otherwise IDs extracted from \"References\", \"In-Reply-To\" and
937 \"Message-ID\" fields are used."
938   :type '(radio (const :tag "Do not add anything" nil)
939                 (const :tag "From Message-Id, References and In-Reply-To fields" t)
940                 (const :tag "From only Message-Id field." message-id-only))
941   :group 'message-insertion)
942
943 (defcustom message-list-references-add-position nil
944   "Integer value means position for adding to \"References\" field when
945 an article is yanked by the command `message-yank-original' interactively."
946   :type '(radio (const :tag "Add to last" nil)
947                 (integer :tag "Position from last ID"))
948   :group 'message-insertion)
949
950 (defcustom message-yank-cited-prefix ">"
951   "*Prefix inserted on cited or empty lines of yanked messages.
952 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
953 See also `message-yank-prefix'."
954   :type 'string
955   :group 'message-insertion)
956
957 (defcustom message-indentation-spaces 3
958   "*Number of spaces to insert at the beginning of each cited line.
959 Used by `message-yank-original' via `message-yank-cite'."
960   :group 'message-insertion
961   :type 'integer)
962
963 ;;;###autoload
964 (defcustom message-cite-function 'message-cite-original
965   "*Function for citing an original message.
966 Predefined functions include `message-cite-original' and
967 `message-cite-original-without-signature'.
968 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
969   :type '(radio (function-item message-cite-original)
970                 (function-item message-cite-original-without-signature)
971                 (function-item mu-cite-original)
972                 (function-item sc-cite-original)
973                 (function :tag "Other"))
974   :group 'message-insertion)
975
976 ;;;###autoload
977 (defcustom message-suspend-font-lock-when-citing nil
978   "Non-nil means suspend font-lock'ing while citing an original message.
979 Some lazy demand-driven fontification tools (or Emacs itself) have a
980 bug that they often miss a buffer to be fontified.  It will mostly
981 occur when Emacs prompts user for any inputs in the minibuffer.
982 Setting this option to non-nil may help you to avoid unpleasant errors
983 even if it is an add-hoc expedient."
984   :type 'boolean
985   :group 'message-insertion)
986
987 ;;;###autoload
988 (defcustom message-indent-citation-function 'message-indent-citation
989   "*Function for modifying a citation just inserted in the mail buffer.
990 This can also be a list of functions.  Each function can find the
991 citation between (point) and (mark t).  And each function should leave
992 point and mark around the citation text as modified."
993   :type 'function
994   :group 'message-insertion)
995
996 ;;;###autoload
997 (defcustom message-signature t
998   "*String to be inserted at the end of the message buffer.
999 If t, the `message-signature-file' file will be inserted instead.
1000 If a function, the result from the function will be used instead.
1001 If a form, the result from the form will be used instead."
1002   :type 'sexp
1003   :group 'message-insertion)
1004
1005 ;;;###autoload
1006 (defcustom message-signature-file "~/.signature"
1007   "*Name of file containing the text inserted at end of message buffer.
1008 Ignored if the named file doesn't exist.
1009 If nil, don't insert a signature."
1010   :type '(choice file (const :tags "None" nil))
1011   :group 'message-insertion)
1012
1013 ;;;###autoload
1014 (defcustom message-signature-insert-empty-line t
1015   "*If non-nil, insert an empty line before the signature separator."
1016   :type 'boolean
1017   :group 'message-insertion)
1018
1019 (defcustom message-distribution-function nil
1020   "*Function called to return a Distribution header."
1021   :group 'message-news
1022   :group 'message-headers
1023   :type '(choice function (const nil)))
1024
1025 (defcustom message-expires 14
1026   "Number of days before your article expires."
1027   :group 'message-news
1028   :group 'message-headers
1029   :link '(custom-manual "(message)News Headers")
1030   :type 'integer)
1031
1032 (defcustom message-user-path nil
1033   "If nil, use the NNTP server name in the Path header.
1034 If stringp, use this; if non-nil, use no host name (user name only)."
1035   :group 'message-news
1036   :group 'message-headers
1037   :link '(custom-manual "(message)News Headers")
1038   :type '(choice (const :tag "nntp" nil)
1039                  (string :tag "name")
1040                  (sexp :tag "none" :format "%t" t)))
1041
1042 (defvar message-reply-buffer nil)
1043 (defvar message-reply-headers nil
1044   "The headers of the current replied article.
1045 It is a vector of the following headers:
1046 \[number subject from date id references chars lines xref extra].")
1047 (defvar message-sent-message-via nil)
1048 (defvar message-checksum nil)
1049 (defvar message-send-actions nil
1050   "A list of actions to be performed upon successful sending of a message.")
1051 (defvar message-exit-actions nil
1052   "A list of actions to be performed upon exiting after sending a message.")
1053 (defvar message-kill-actions nil
1054   "A list of actions to be performed before killing a message buffer.")
1055 (defvar message-postpone-actions nil
1056   "A list of actions to be performed after postponing a message.")
1057 (defvar message-original-frame nil)
1058 (defvar message-parameter-alist nil)
1059 (defvar message-startup-parameter-alist nil)
1060
1061 (define-widget 'message-header-lines 'text
1062   "All header lines must be LFD terminated."
1063   :format "%{%t%}:%n%v"
1064   :valid-regexp "^\\'"
1065   :error "All header lines must be newline terminated")
1066
1067 (defcustom message-default-headers ""
1068   "*A string containing header lines to be inserted in outgoing messages.
1069 It is inserted before you edit the message, so you can edit or delete
1070 these lines."
1071   :group 'message-headers
1072   :type 'message-header-lines)
1073
1074 (defcustom message-default-mail-headers ""
1075   "*A string of header lines to be inserted in outgoing mails."
1076   :group 'message-headers
1077   :group 'message-mail
1078   :type 'message-header-lines)
1079
1080 (defcustom message-default-news-headers ""
1081   "*A string of header lines to be inserted in outgoing news articles."
1082   :group 'message-headers
1083   :group 'message-news
1084   :type 'message-header-lines)
1085
1086 ;; Note: could use /usr/ucb/mail instead of sendmail;
1087 ;; options -t, and -v if not interactive.
1088 (defcustom message-mailer-swallows-blank-line
1089   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
1090                          system-configuration)
1091            (file-readable-p "/etc/sendmail.cf")
1092            (let ((buffer (get-buffer-create " *temp*")))
1093              (unwind-protect
1094                  (save-excursion
1095                    (set-buffer buffer)
1096                    (insert-file-contents "/etc/sendmail.cf")
1097                    (goto-char (point-min))
1098                    (let ((case-fold-search nil))
1099                      (re-search-forward "^OR\\>" nil t)))
1100                (kill-buffer buffer))))
1101       ;; According to RFC822, "The field-name must be composed of printable
1102       ;; ASCII characters (i. e., characters that have decimal values between
1103       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
1104       ;; space, or colon.
1105       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
1106   "*Set this non-nil if the system's mailer runs the header and body together.
1107 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
1108 The value should be an expression to test whether the problem will
1109 actually occur."
1110   :group 'message-sending
1111   :type 'sexp)
1112
1113 ;;; XXX: This symbol is overloaded!  See below.
1114 (defvar message-user-agent nil
1115   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
1116
1117 (static-when (boundp 'MULE)
1118   (require 'reporter));; `define-mail-user-agent' is here.
1119
1120 ;;;###autoload
1121 (define-mail-user-agent 'message-user-agent
1122   'message-mail 'message-send-and-exit
1123   'message-kill-buffer 'message-send-hook)
1124
1125 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
1126   "If non-nil, delete the deletable headers before feeding to mh.")
1127
1128 (defvar message-send-method-alist
1129   '((news message-news-p message-send-via-news)
1130     (mail message-mail-p message-send-via-mail))
1131   "Alist of ways to send outgoing messages.
1132 Each element has the form
1133
1134   \(TYPE PREDICATE FUNCTION)
1135
1136 where TYPE is a symbol that names the method; PREDICATE is a function
1137 called without any parameters to determine whether the message is
1138 a message of type TYPE; and FUNCTION is a function to be called if
1139 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
1140 the prefix.")
1141
1142 (defcustom message-mail-alias-type 'abbrev
1143   "*What alias expansion type to use in Message buffers.
1144 The default is `abbrev', which uses mailabbrev.  nil switches
1145 mail aliases off."
1146   :group 'message
1147   :link '(custom-manual "(message)Mail Aliases")
1148   :type '(choice (const :tag "Use Mailabbrev" abbrev)
1149                  (const :tag "No expansion" nil)))
1150
1151 (defcustom message-auto-save-directory
1152   (file-name-as-directory (nnheader-concat message-directory "drafts"))
1153   "*Directory where Message auto-saves buffers if Gnus isn't running.
1154 If nil, Message won't auto-save."
1155   :group 'message-buffers
1156   :type '(choice directory (const :tag "Don't auto-save" nil)))
1157
1158 (defcustom message-default-charset
1159   (and (featurep 'xemacs) (not (featurep 'mule)) 'iso-8859-1)
1160   "Default charset used in non-MULE XEmacsen."
1161   :version "21.1"
1162   :group 'message
1163   :type 'symbol)
1164
1165 (defcustom message-dont-reply-to-names
1166   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
1167   "*A regexp specifying addresses to prune when doing wide replies.
1168 A value of nil means exclude your own user name only."
1169   :version "21.1"
1170   :group 'message
1171   :type '(choice (const :tag "Yourself" nil)
1172                  regexp))
1173
1174 (defvar message-shoot-gnksa-feet nil
1175   "*A list of GNKSA feet you are allowed to shoot.
1176 Gnus gives you all the opportunity you could possibly want for
1177 shooting yourself in the foot.  Also, Gnus allows you to shoot the
1178 feet of Good Net-Keeping Seal of Approval.  The following are foot
1179 candidates:
1180 `empty-article'     Allow you to post an empty article;
1181 `quoted-text-only'  Allow you to post quoted text only;
1182 `multiple-copies'   Allow you to post multiple copies;
1183 `cancel-messages'   Allow you to cancel or supersede messages from
1184                     your other email addresses.")
1185
1186 (defsubst message-gnksa-enable-p (feature)
1187   (or (not (listp message-shoot-gnksa-feet))
1188       (memq feature message-shoot-gnksa-feet)))
1189
1190 ;;; Internal variables.
1191 ;;; Well, not really internal.
1192
1193 (defvar message-mode-syntax-table
1194   (let ((table (copy-syntax-table text-mode-syntax-table)))
1195     (modify-syntax-entry ?% ". " table)
1196     (modify-syntax-entry ?> ". " table)
1197     (modify-syntax-entry ?< ". " table)
1198     table)
1199   "Syntax table used while in Message mode.")
1200
1201 (defface message-header-to-face
1202   '((((class color)
1203       (background dark))
1204      (:foreground "green2" :bold t))
1205     (((class color)
1206       (background light))
1207      (:foreground "MidnightBlue" :bold t))
1208     (t
1209      (:bold t :italic t)))
1210   "Face used for displaying From headers."
1211   :group 'message-faces)
1212
1213 (defface message-header-cc-face
1214   '((((class color)
1215       (background dark))
1216      (:foreground "green4" :bold t))
1217     (((class color)
1218       (background light))
1219      (:foreground "MidnightBlue"))
1220     (t
1221      (:bold t)))
1222   "Face used for displaying Cc headers."
1223   :group 'message-faces)
1224
1225 (defface message-header-subject-face
1226   '((((class color)
1227       (background dark))
1228      (:foreground "green3"))
1229     (((class color)
1230       (background light))
1231      (:foreground "navy blue" :bold t))
1232     (t
1233      (:bold t)))
1234   "Face used for displaying subject headers."
1235   :group 'message-faces)
1236
1237 (defface message-header-newsgroups-face
1238   '((((class color)
1239       (background dark))
1240      (:foreground "yellow" :bold t :italic t))
1241     (((class color)
1242       (background light))
1243      (:foreground "blue4" :bold t :italic t))
1244     (t
1245      (:bold t :italic t)))
1246   "Face used for displaying newsgroups headers."
1247   :group 'message-faces)
1248
1249 (defface message-header-other-face
1250   '((((class color)
1251       (background dark))
1252      (:foreground "#b00000"))
1253     (((class color)
1254       (background light))
1255      (:foreground "steel blue"))
1256     (t
1257      (:bold t :italic t)))
1258   "Face used for displaying newsgroups headers."
1259   :group 'message-faces)
1260
1261 (defface message-header-name-face
1262   '((((class color)
1263       (background dark))
1264      (:foreground "DarkGreen"))
1265     (((class color)
1266       (background light))
1267      (:foreground "cornflower blue"))
1268     (t
1269      (:bold t)))
1270   "Face used for displaying header names."
1271   :group 'message-faces)
1272
1273 (defface message-header-xheader-face
1274   '((((class color)
1275       (background dark))
1276      (:foreground "blue"))
1277     (((class color)
1278       (background light))
1279      (:foreground "blue"))
1280     (t
1281      (:bold t)))
1282   "Face used for displaying X-Header headers."
1283   :group 'message-faces)
1284
1285 (defface message-separator-face
1286   '((((class color)
1287       (background dark))
1288      (:foreground "blue3"))
1289     (((class color)
1290       (background light))
1291      (:foreground "brown"))
1292     (t
1293      (:bold t)))
1294   "Face used for displaying the separator."
1295   :group 'message-faces)
1296
1297 (defface message-cited-text-face
1298   '((((class color)
1299       (background dark))
1300      (:foreground "red"))
1301     (((class color)
1302       (background light))
1303      (:foreground "red"))
1304     (t
1305      (:bold t)))
1306   "Face used for displaying cited text names."
1307   :group 'message-faces)
1308
1309 (defface message-mml-face
1310   '((((class color)
1311       (background dark))
1312      (:foreground "ForestGreen"))
1313     (((class color)
1314       (background light))
1315      (:foreground "ForestGreen"))
1316     (t
1317      (:bold t)))
1318   "Face used for displaying MML."
1319   :group 'message-faces)
1320
1321 (defun message-font-lock-make-header-matcher (regexp)
1322   (let ((form
1323          `(lambda (limit)
1324             (let ((start (point)))
1325               (save-restriction
1326                 (widen)
1327                 (goto-char (point-min))
1328                 (if (re-search-forward
1329                      (concat "^" (regexp-quote mail-header-separator) "$")
1330                      nil t)
1331                     (setq limit (min limit (match-beginning 0))))
1332                 (goto-char start))
1333               (and (< start limit)
1334                    (re-search-forward ,regexp limit t))))))
1335     (if (featurep 'bytecomp)
1336         (byte-compile form)
1337       form)))
1338
1339 (defvar message-font-lock-keywords
1340   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
1341     `((,(message-font-lock-make-header-matcher
1342          (concat "^\\([Tt]o:\\)" content))
1343        (1 'message-header-name-face)
1344        (2 'message-header-to-face nil t))
1345       (,(message-font-lock-make-header-matcher
1346          (concat "^\\([GBF]?[Cc][Cc]:\\|[Rr]eply-[Tt]o:\\|"
1347                  "[Mm]ail-[Cc]opies-[Tt]o:\\|"
1348                  "[Mm]ail-[Rr]eply-[Tt]o:\\|"
1349                  "[Mm]ail-[Ff]ollowup-[Tt]o:\\)" content))
1350        (1 'message-header-name-face)
1351        (2 'message-header-cc-face nil t))
1352       (,(message-font-lock-make-header-matcher
1353          (concat "^\\([Ss]ubject:\\)" content))
1354        (1 'message-header-name-face)
1355        (2 'message-header-subject-face nil t))
1356       (,(message-font-lock-make-header-matcher
1357          (concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content))
1358        (1 'message-header-name-face)
1359        (2 'message-header-newsgroups-face nil t))
1360       (,(message-font-lock-make-header-matcher
1361          (concat "^\\([A-Z][^: \n\t]+:\\)" content))
1362        (1 'message-header-name-face)
1363        (2 'message-header-other-face nil t))
1364       (,(message-font-lock-make-header-matcher
1365          (concat "^\\(X-[A-Za-z0-9-]+:\\|In-Reply-To:\\)" content))
1366        (1 'message-header-name-face)
1367        (2 'message-header-name-face))
1368       ,@(if (and mail-header-separator
1369                  (not (equal mail-header-separator "")))
1370             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
1371                1 'message-separator-face))
1372           nil)
1373       ((lambda (limit)
1374          (re-search-forward (concat "^\\("
1375                                     message-cite-prefix-regexp
1376                                     "\\).*")
1377                             limit t))
1378        (0 'message-cited-text-face))
1379       (,mime-edit-tag-regexp
1380        (0 'message-mml-face))))
1381   "Additional expressions to highlight in Message mode.")
1382
1383 ;; XEmacs does it like this.  For Emacs, we have to set the
1384 ;; `font-lock-defaults' buffer-local variable.
1385 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
1386
1387 (defvar message-face-alist
1388   '((bold . bold-region)
1389     (underline . underline-region)
1390     (default . (lambda (b e)
1391                  (unbold-region b e)
1392                  (ununderline-region b e))))
1393   "Alist of mail and news faces for facemenu.
1394 The cdr of each entry is a function for applying the face to a region.")
1395
1396 (defcustom message-send-hook nil
1397   "Hook run before sending messages.
1398 This hook is run quite early when sending."
1399   :group 'message-various
1400   :options '(ispell-message)
1401   :type 'hook)
1402
1403 (defcustom message-send-mail-hook nil
1404   "Hook run before sending mail messages.
1405 This hook is run very late -- just before the message is sent as
1406 mail."
1407   :group 'message-various
1408   :type 'hook)
1409
1410 (defcustom message-send-news-hook nil
1411   "Hook run before sending news messages.
1412 This hook is run very late -- just before the message is sent as
1413 news."
1414   :group 'message-various
1415   :type 'hook)
1416
1417 (defcustom message-sent-hook nil
1418   "Hook run after sending messages."
1419   :group 'message-various
1420   :type 'hook)
1421
1422 (defcustom message-use-multi-frames nil
1423   "Make new frame when sending messages."
1424   :group 'message-frames
1425   :type 'boolean)
1426
1427 (defcustom message-delete-frame-on-exit nil
1428   "Delete frame after sending messages."
1429   :group 'message-frames
1430   :type '(choice (const :tag "off" nil)
1431                  (const :tag "always" t)
1432                  (const :tag "ask" ask)))
1433
1434 (defvar message-draft-coding-system
1435   nnheader-auto-save-coding-system
1436   "*Coding system to compose mail.
1437 If you'd like to make it possible to share draft files between XEmacs
1438 and Emacs, you may use `iso-2022-7bit' for this value at your own risk.
1439 Note that the coding-system `iso-2022-7bit' isn't suitable to all data.")
1440
1441 (defcustom message-send-mail-partially-limit 1000000
1442   "The limitation of messages sent as message/partial.
1443 The lower bound of message size in characters, beyond which the message
1444 should be sent in several parts.  If it is nil, the size is unlimited."
1445   :version "21.1"
1446   :group 'message-buffers
1447   :type '(choice (const :tag "unlimited" nil)
1448                  (integer 1000000)))
1449
1450 (defcustom message-alternative-emails nil
1451   "A regexp to match the alternative email addresses.
1452 The first matched address (not primary one) is used in the From field."
1453   :group 'message-headers
1454   :type '(choice (const :tag "Always use primary" nil)
1455                  regexp))
1456
1457 (defcustom message-hierarchical-addresses nil
1458   "A list of hierarchical mail address definitions.
1459
1460 Inside each entry, the first address is the \"top\" address, and
1461 subsequent addresses are subaddresses; this is used to indicate that
1462 mail sent to the first address will automatically be delivered to the
1463 subaddresses.  So if the first address appears in the recipient list
1464 for a message, the subaddresses will be removed (if present) before
1465 the mail is sent.  All addresses in this structure should be
1466 downcased."
1467   :group 'message-headers
1468   :type '(repeat (repeat string)))
1469
1470 (defcustom message-mail-user-agent nil
1471   "Like `mail-user-agent'.
1472 Except if it is nil, use Gnus native MUA; if it is t, use
1473 `mail-user-agent'."
1474   :type '(radio (const :tag "Gnus native"
1475                        :format "%t\n"
1476                        nil)
1477                 (const :tag "`mail-user-agent'"
1478                        :format "%t\n"
1479                        t)
1480                 (function-item :tag "Default Emacs mail"
1481                                :format "%t\n"
1482                                sendmail-user-agent)
1483                 (function-item :tag "Emacs interface to MH"
1484                                :format "%t\n"
1485                                mh-e-user-agent)
1486                 (function :tag "Other"))
1487   :version "21.1"
1488   :group 'message)
1489
1490 (defcustom message-wide-reply-confirm-recipients nil
1491   "Whether to confirm a wide reply to multiple email recipients.
1492 If this variable is nil, don't ask whether to reply to all recipients.
1493 If this variable is non-nil, pose the question \"Reply to all
1494 recipients?\" before a wide reply to multiple recipients.  If the user
1495 answers yes, reply to all recipients as usual.  If the user answers
1496 no, only reply back to the author."
1497   :version "21.3"
1498   :group 'message-headers
1499   :type 'boolean)
1500
1501 (defcustom message-user-fqdn nil
1502   "*Domain part of Messsage-Ids."
1503   :group 'message-headers
1504   :link '(custom-manual "(message)News Headers")
1505   :type 'string)
1506
1507 ;;; Internal variables.
1508
1509 (defvar message-sending-message "Sending...")
1510 (defvar message-buffer-list nil)
1511 (defvar message-this-is-news nil)
1512 (defvar message-this-is-mail nil)
1513 (defvar message-draft-article nil)
1514 (defvar message-mime-part nil)
1515 (defvar message-posting-charset nil)
1516
1517 ;; Byte-compiler warning
1518 (eval-when-compile
1519   (defvar gnus-active-hashtb)
1520   (defvar gnus-read-active-file))
1521
1522 ;;; Regexp matching the delimiter of messages in UNIX mail format
1523 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1524 ;;; of rmail.el's rmail-unix-mail-delimiter.
1525 (defvar message-unix-mail-delimiter
1526   (let ((time-zone-regexp
1527          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1528                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1529                  "\\|"
1530                  "\\) *")))
1531     (concat
1532      "From "
1533
1534      ;; Many things can happen to an RFC 822 mailbox before it is put into
1535      ;; a `From' line.  The leading phrase can be stripped, e.g.
1536      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1537      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1538      ;; can be removed, e.g.
1539      ;;         From: joe@y.z (Joe      K
1540      ;;                 User)
1541      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1542      ;;         From: Joe User
1543      ;;                 <joe@y.z>
1544      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1545      ;; The mailbox can be removed or be replaced by white space, e.g.
1546      ;;         From: "Joe User"{space}{tab}
1547      ;;                 <joe@y.z>
1548      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1549      ;; where {space} and {tab} represent the Ascii space and tab characters.
1550      ;; We want to match the results of any of these manglings.
1551      ;; The following regexp rejects names whose first characters are
1552      ;; obviously bogus, but after that anything goes.
1553      "\\([^\0-\b\n-\r\^?].*\\)?"
1554
1555      ;; The time the message was sent.
1556      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1557      "\\([^\0-\r \^?]+\\) +"            ; month
1558      "\\([0-3]?[0-9]\\) +"              ; day of month
1559      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1560
1561      ;; Perhaps a time zone, specified by an abbreviation, or by a
1562      ;; numeric offset.
1563      time-zone-regexp
1564
1565      ;; The year.
1566      " \\([0-9][0-9]+\\) *"
1567
1568      ;; On some systems the time zone can appear after the year, too.
1569      time-zone-regexp
1570
1571      ;; Old uucp cruft.
1572      "\\(remote from .*\\)?"
1573
1574      "\n"))
1575   "Regexp matching the delimiter of messages in UNIX mail format.")
1576
1577 (defvar message-unsent-separator
1578   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1579           "^ *---+ +Returned message +---+ *$\\|"
1580           "^Start of returned message$\\|"
1581           "^ *---+ +Original message +---+ *$\\|"
1582           "^ *--+ +begin message +--+ *$\\|"
1583           "^ *---+ +Original message follows +---+ *$\\|"
1584           "^ *---+ +Undelivered message follows +---+ *$\\|"
1585           "^|? *---+ +Message text follows: +---+ *|?$")
1586   "A regexp that matches the separator before the text of a failed message.")
1587
1588 (defvar message-header-format-alist
1589   `((Newsgroups)
1590     (To . message-fill-address)
1591     (Cc . message-fill-address)
1592     (Subject)
1593     (In-Reply-To)
1594     (Fcc)
1595     (Bcc)
1596     (Date)
1597     (Organization)
1598     (Distribution)
1599     (Lines)
1600     (Expires)
1601     (Message-ID)
1602     (References . message-shorten-references)
1603     (User-Agent))
1604   "Alist used for formatting headers.")
1605
1606 (defvar message-options nil
1607   "Some saved answers when sending message.")
1608
1609 (defvar message-send-mail-real-function nil
1610   "Internal send mail function.")
1611
1612 (defvar message-bogus-system-names "^localhost\\."
1613   "The regexp of bogus system names.")
1614
1615 (defcustom message-valid-fqdn-regexp
1616   (concat "[a-z0-9][-.a-z0-9]+\\." ;; [hostname.subdomain.]domain.
1617           ;; valid TLDs:
1618           "\\([a-z][a-z]" ;; two letter country TDLs
1619           "\\|biz\\|com\\|edu\\|gov\\|int\\|mil\\|net\\|org"
1620           "\\|aero\\|coop\\|info\\|name\\|museum"
1621           "\\|arpa\\|pro\\|uucp\\|bitnet\\|bofh" ;; old style?
1622           "\\)")
1623   "Regular expression that matches a valid FQDN."
1624   ;; see also: gnus-button-valid-fqdn-regexp
1625   :group 'message-headers
1626   :type 'regexp)
1627
1628 (eval-and-compile
1629   (autoload 'message-setup-toolbar "messagexmas")
1630   (autoload 'mh-new-draft-name "mh-comp")
1631   (autoload 'mh-send-letter "mh-comp")
1632   (autoload 'gnus-point-at-eol "gnus-util")
1633   (autoload 'gnus-point-at-bol "gnus-util")
1634   (autoload 'gnus-output-to-rmail "gnus-util")
1635   (autoload 'gnus-output-to-mail "gnus-util")
1636   (autoload 'nndraft-request-associate-buffer "nndraft")
1637   (autoload 'nndraft-request-expire-articles "nndraft")
1638   (autoload 'gnus-open-server "gnus-int")
1639   (autoload 'gnus-request-post "gnus-int")
1640   (autoload 'gnus-copy-article-buffer "gnus-msg")
1641   (autoload 'gnus-alive-p "gnus-util")
1642   (autoload 'gnus-server-string "gnus")
1643   (autoload 'gnus-group-name-charset "gnus-group")
1644   (autoload 'gnus-group-name-decode "gnus-group")
1645   (autoload 'gnus-groups-from-server "gnus")
1646   (autoload 'rmail-output "rmailout")
1647   (autoload 'gnus-delay-article "gnus-delay")
1648   (autoload 'mu-cite-original "mu-cite"))
1649
1650 \f
1651
1652 ;;;
1653 ;;; Utility functions.
1654 ;;;
1655 (defun message-eval-parameter (parameter)
1656   (condition-case ()
1657       (if (symbolp parameter)
1658           (if (functionp parameter)
1659               (funcall parameter)
1660             (eval parameter))
1661         parameter)
1662     (error nil)))
1663
1664 (defsubst message-get-parameter (key &optional alist)
1665   (unless alist
1666     (setq alist message-parameter-alist))
1667   (cdr (assq key alist)))
1668
1669 (defmacro message-get-parameter-with-eval (key &optional alist)
1670   `(message-eval-parameter (message-get-parameter ,key ,alist)))
1671
1672 (defmacro message-y-or-n-p (question show &rest text)
1673   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1674   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1675
1676 (defmacro message-delete-line (&optional n)
1677   "Delete the current line (and the next N lines)."
1678   `(delete-region (progn (beginning-of-line) (point))
1679                   (progn (forward-line ,(or n 1)) (point))))
1680
1681 (defun message-mark-active-p ()
1682   "Non-nil means the mark and region are currently active in this buffer."
1683   mark-active)
1684
1685 (defun message-unquote-tokens (elems)
1686   "Remove double quotes (\") from strings in list ELEMS."
1687   (mapcar (lambda (item)
1688             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1689               (setq item (concat (match-string 1 item)
1690                                  (match-string 2 item))))
1691             item)
1692           elems))
1693
1694 (defun message-tokenize-header (header &optional separator)
1695   "Split HEADER into a list of header elements.
1696 SEPARATOR is a string of characters to be used as separators.  \",\"
1697 is used by default."
1698   (if (not header)
1699       nil
1700     (let ((regexp (format "[%s]+" (or separator ",")))
1701           (beg 1)
1702           (first t)
1703           quoted elems paren)
1704       (save-excursion
1705         (message-set-work-buffer)
1706         (insert header)
1707         (goto-char (point-min))
1708         (while (not (eobp))
1709           (if first
1710               (setq first nil)
1711             (forward-char 1))
1712           (cond ((and (> (point) beg)
1713                       (or (eobp)
1714                           (and (looking-at regexp)
1715                                (not quoted)
1716                                (not paren))))
1717                  (push (buffer-substring beg (point)) elems)
1718                  (setq beg (match-end 0)))
1719                 ((eq (char-after) ?\")
1720                  (setq quoted (not quoted)))
1721                 ((and (eq (char-after) ?\()
1722                       (not quoted))
1723                  (setq paren t))
1724                 ((and (eq (char-after) ?\))
1725                       (not quoted))
1726                  (setq paren nil))))
1727         (nreverse elems)))))
1728
1729 (defun message-mail-file-mbox-p (file)
1730   "Say whether FILE looks like a Unix mbox file."
1731   (when (and (file-exists-p file)
1732              (file-readable-p file)
1733              (file-regular-p file))
1734     (with-temp-buffer
1735       (nnheader-insert-file-contents file)
1736       (goto-char (point-min))
1737       (looking-at message-unix-mail-delimiter))))
1738
1739 (defun message-fetch-field (header &optional not-all)
1740   "The same as `mail-fetch-field', only remove all newlines."
1741   (let* ((inhibit-point-motion-hooks t)
1742          (case-fold-search t)
1743          (value (mail-fetch-field header nil (not not-all))))
1744     (when value
1745       (while (string-match "\n[\t ]+" value)
1746         (setq value (replace-match " " t t value)))
1747       (set-text-properties 0 (length value) nil value)
1748       value)))
1749
1750 (defun message-narrow-to-field ()
1751   "Narrow the buffer to the header on the current line."
1752   (beginning-of-line)
1753   (narrow-to-region
1754    (point)
1755    (progn
1756      (forward-line 1)
1757      (if (re-search-forward "^[^ \n\t]" nil t)
1758          (progn
1759            (beginning-of-line)
1760            (point))
1761        (point-max))))
1762   (goto-char (point-min)))
1763
1764 (defun message-add-header (&rest headers)
1765   "Add the HEADERS to the message header, skipping those already present."
1766   (while headers
1767     (let (hclean)
1768       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1769         (error "Invalid header `%s'" (car headers)))
1770       (setq hclean (match-string 1 (car headers)))
1771       (save-restriction
1772         (message-narrow-to-headers)
1773         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1774           (goto-char (point-max))
1775           (if (string-match "\n$" (car headers))
1776               (insert (car headers))
1777             (insert (car headers) ?\n)))))
1778     (setq headers (cdr headers))))
1779
1780 (defmacro message-with-reply-buffer (&rest forms)
1781   "Evaluate FORMS in the reply buffer, if it exists."
1782   `(let ((buffer (message-eval-parameter message-reply-buffer)))
1783      (when (and buffer
1784                 (buffer-name buffer))
1785        (save-excursion
1786          (set-buffer buffer)
1787          ,@forms))))
1788
1789 (put 'message-with-reply-buffer 'lisp-indent-function 0)
1790 (put 'message-with-reply-buffer 'edebug-form-spec '(body))
1791
1792 (defun message-fetch-reply-field (header)
1793   "Fetch field HEADER from the message we're replying to."
1794   (message-with-reply-buffer
1795     (save-restriction
1796       (mail-narrow-to-head)
1797       (message-fetch-field header))))
1798
1799 (defun message-set-work-buffer ()
1800   (if (get-buffer " *message work*")
1801       (progn
1802         (set-buffer " *message work*")
1803         (erase-buffer))
1804     (set-buffer (get-buffer-create " *message work*"))
1805     (kill-all-local-variables)))
1806
1807 (defun message-functionp (form)
1808   "Return non-nil if FORM is funcallable."
1809   (or (and (symbolp form) (fboundp form))
1810       (and (listp form) (eq (car form) 'lambda))
1811       (byte-code-function-p form)))
1812
1813 (defun message-strip-list-identifiers (subject)
1814   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1815   (require 'gnus-sum)                   ; for gnus-list-identifiers
1816   (let ((regexp (if (stringp gnus-list-identifiers)
1817                     gnus-list-identifiers
1818                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1819     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1820                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1821         (concat (substring subject 0 (match-beginning 1))
1822                 (or (match-string 3 subject)
1823                     (match-string 5 subject))
1824                 (substring subject
1825                            (match-end 1)))
1826       subject)))
1827
1828 (defun message-strip-subject-re (subject)
1829   "Remove \"Re:\" from subject lines in string SUBJECT."
1830   (if (string-match message-subject-re-regexp subject)
1831       (substring subject (match-end 0))
1832     subject))
1833
1834 ;;; Start of functions adopted from `message-utils.el'.
1835
1836 (defun message-strip-subject-trailing-was (subject)
1837   "Remove trailing \"(Was: <old subject>)\" from SUBJECT lines.
1838 Leading \"Re: \" is not stripped by this function.  Use the function
1839 `message-strip-subject-re' for this."
1840   (let* ((query message-subject-trailing-was-query)
1841          (new) (found))
1842     (setq found
1843           (string-match
1844            (if (eq query 'ask)
1845                message-subject-trailing-was-ask-regexp
1846              message-subject-trailing-was-regexp)
1847            subject))
1848     (if found
1849         (setq new (substring subject 0 (match-beginning 0))))
1850     (if (or (not found) (eq query nil))
1851         subject
1852       (if (eq query 'ask)
1853           (if (message-y-or-n-p
1854                "Strip `(was: <old subject>)' in subject? " t
1855                (concat
1856                 "Strip `(was: <old subject>)' in subject "
1857                 "and use the new one instead?\n\n"
1858                 "Current subject is:   \""
1859                 subject "\"\n\n"
1860                 "New subject would be: \""
1861                 new "\"\n\n"
1862                 "See the variable `message-subject-trailing-was-query' "
1863                 "to get rid of this query."
1864                 ))
1865               new subject)
1866         new))))
1867
1868 ;;; Suggested by Jonas Steverud  @  www.dtek.chalmers.se/~d4jonas/
1869
1870 ;;;###autoload
1871 (defun message-change-subject (new-subject)
1872   "Ask for NEW-SUBJECT header, append (was: <Old Subject>)."
1873   (interactive
1874    (list
1875     (read-from-minibuffer "New subject: ")))
1876   (cond ((and (not (or (null new-subject) ; new subject not empty
1877                        (zerop (string-width new-subject))
1878                        (string-match "^[ \t]*$" new-subject))))
1879          (save-excursion
1880            (let ((old-subject (message-fetch-field "Subject")))
1881              (cond ((not old-subject)
1882                     (error "No current subject"))
1883                    ((not (string-match
1884                           (concat "^[ \t]*"
1885                                   (regexp-quote new-subject)
1886                                   " \t]*$")
1887                           old-subject))  ; yes, it really is a new subject
1888                     ;; delete eventual Re: prefix
1889                     (setq old-subject
1890                           (message-strip-subject-re old-subject))
1891                     (message-goto-subject)
1892                     (message-delete-line)
1893                     (insert (concat "Subject: "
1894                                     new-subject
1895                                     " (was: "
1896                                     old-subject ")\n")))))))))
1897
1898 ;;;###autoload
1899 (defun message-mark-inserted-region (beg end)
1900   "Mark some region in the current article with enclosing tags.
1901 See `message-mark-insert-begin' and `message-mark-insert-end'."
1902   (interactive "r")
1903   (save-excursion
1904     ; add to the end of the region first, otherwise end would be invalid
1905     (goto-char end)
1906     (insert message-mark-insert-end)
1907     (goto-char beg)
1908     (insert message-mark-insert-begin)))
1909
1910 ;;;###autoload
1911 (defun message-mark-insert-file (file)
1912   "Insert FILE at point, marking it with enclosing tags.
1913 See `message-mark-insert-begin' and `message-mark-insert-end'."
1914   (interactive "fFile to insert: ")
1915     ;; reverse insertion to get correct result.
1916   (let ((p (point)))
1917     (insert message-mark-insert-end)
1918     (goto-char p)
1919     (insert-file-contents file)
1920     (goto-char p)
1921     (insert message-mark-insert-begin)))
1922
1923 ;;;###autoload
1924 (defun message-add-archive-header ()
1925   "Insert \"X-No-Archive: Yes\" in the header and a note in the body.
1926 The note can be customized using `message-archive-note'.  When called with a
1927 prefix argument, ask for a text to insert.  If you don't want the note in the
1928 body, set  `message-archive-note' to nil."
1929   (interactive)
1930   (if current-prefix-arg
1931       (setq message-archive-note
1932             (read-from-minibuffer "Reason for No-Archive: "
1933                                   (cons message-archive-note 0))))
1934     (save-excursion
1935       (if (message-goto-signature)
1936           (re-search-backward message-signature-separator))
1937       (when message-archive-note
1938         (insert message-archive-note)
1939         (newline))
1940       (message-add-header message-archive-header)
1941       (message-sort-headers)))
1942
1943 ;;;###autoload
1944 (defun message-cross-post-followup-to-header (target-group)
1945   "Mangles FollowUp-To and Newsgroups header to point to TARGET-GROUP.
1946 With prefix-argument just set Follow-Up, don't cross-post."
1947   (interactive
1948    (list ; Completion based on Gnus
1949     (completing-read "Followup To: "
1950                      (if (boundp 'gnus-newsrc-alist)
1951                          gnus-newsrc-alist)
1952                      nil nil '("poster" . 0)
1953                      (if (boundp 'gnus-group-history)
1954                          'gnus-group-history))))
1955   (message-remove-header "Follow[Uu]p-[Tt]o" t)
1956   (message-goto-newsgroups)
1957   (beginning-of-line)
1958   ;; if we already did a crosspost before, kill old target
1959   (if (and message-cross-post-old-target
1960            (re-search-forward
1961             (regexp-quote (concat "," message-cross-post-old-target))
1962             nil t))
1963       (replace-match ""))
1964   ;; unless (followup is to poster or user explicitly asked not
1965   ;; to cross-post, or target-group is already in Newsgroups)
1966   ;; add target-group to Newsgroups line.
1967   (cond ((and (or
1968                ;; def: cross-post, req:no
1969                (and message-cross-post-default (not current-prefix-arg))
1970                ;; def: no-cross-post, req:yes
1971                (and (not message-cross-post-default) current-prefix-arg))
1972               (not (string-match "poster" target-group))
1973               (not (string-match (regexp-quote target-group)
1974                                  (message-fetch-field "Newsgroups"))))
1975          (end-of-line)
1976          (insert (concat "," target-group))))
1977   (end-of-line) ; ensure Followup: comes after Newsgroups:
1978   ;; unless new followup would be identical to Newsgroups line
1979   ;; make a new Followup-To line
1980   (if (not (string-match (concat "^[ \t]*"
1981                                  target-group
1982                                  "[ \t]*$")
1983                          (message-fetch-field "Newsgroups")))
1984       (insert (concat "\nFollowup-To: " target-group)))
1985   (setq message-cross-post-old-target target-group))
1986
1987 ;;;###autoload
1988 (defun message-cross-post-insert-note (target-group cross-post in-old
1989                                                     old-groups)
1990   "Insert a in message body note about a set Followup or Crosspost.
1991 If there have been previous notes, delete them.  TARGET-GROUP specifies the
1992 group to Followup-To.  When CROSS-POST is t, insert note about
1993 crossposting.  IN-OLD specifies whether TARGET-GROUP is a member of
1994 OLD-GROUPS.  OLD-GROUPS lists the old-groups the posting would have
1995 been made to before the user asked for a Crosspost."
1996   ;; start scanning body for previous uses
1997   (message-goto-signature)
1998   (let ((head (re-search-backward
1999                (concat "^" mail-header-separator)
2000                nil t))) ; just search in body
2001     (message-goto-signature)
2002     (while (re-search-backward
2003             (concat "^" (regexp-quote message-cross-post-note) ".*")
2004             head t)
2005       (message-delete-line))
2006     (message-goto-signature)
2007     (while (re-search-backward
2008             (concat "^" (regexp-quote message-followup-to-note) ".*")
2009             head t)
2010       (message-delete-line))
2011     ;; insert new note
2012     (if (message-goto-signature)
2013         (re-search-backward message-signature-separator))
2014     (if (or in-old
2015             (not cross-post)
2016             (string-match "^[ \t]*poster[ \t]*$" target-group))
2017         (insert (concat message-followup-to-note target-group "\n"))
2018       (insert (concat message-cross-post-note target-group "\n")))))
2019
2020 ;;;###autoload
2021 (defun message-cross-post-followup-to (target-group)
2022   "Crossposts message and set Followup-To to TARGET-GROUP.
2023 With prefix-argument just set Follow-Up, don't cross-post."
2024   (interactive
2025    (list ; Completion based on Gnus
2026     (completing-read "Followup To: "
2027                      (if (boundp 'gnus-newsrc-alist)
2028                          gnus-newsrc-alist)
2029                      nil nil '("poster" . 0)
2030                      (if (boundp 'gnus-group-history)
2031                          'gnus-group-history))))
2032   (cond ((not (or (null target-group) ; new subject not empty
2033                   (zerop (string-width target-group))
2034                   (string-match "^[ \t]*$" target-group)))
2035          (save-excursion
2036            (let* ((old-groups (message-fetch-field "Newsgroups"))
2037                   (in-old (string-match
2038                            (regexp-quote target-group)
2039                            (or old-groups ""))))
2040              ;; check whether target exactly matches old Newsgroups
2041              (cond ((not old-groups)
2042                     (error "No current newsgroup"))
2043                    ((or (not in-old)
2044                         (not (string-match
2045                               (concat "^[ \t]*"
2046                                       (regexp-quote target-group)
2047                                       "[ \t]*$")
2048                               old-groups)))
2049                     ;; yes, Newsgroups line must change
2050                     (message-cross-post-followup-to-header target-group)
2051                     ;; insert note whether we do cross-post or followup-to
2052                     (funcall message-cross-post-note-function
2053                              target-group
2054                              (if (or (and message-cross-post-default
2055                                           (not current-prefix-arg))
2056                                      (and (not message-cross-post-default)
2057                                           current-prefix-arg)) t)
2058                              in-old old-groups))))))))
2059
2060 ;;; Reduce To: to Cc: or Bcc: header
2061
2062 ;;;###autoload
2063 (defun message-reduce-to-to-cc ()
2064  "Replace contents of To: header with contents of Cc: or Bcc: header."
2065  (interactive)
2066  (let ((cc-content (message-fetch-field "cc"))
2067        (bcc nil))
2068    (if (and (not cc-content)
2069             (setq cc-content (message-fetch-field "bcc")))
2070        (setq bcc t))
2071    (cond (cc-content
2072           (save-excursion
2073             (message-goto-to)
2074             (message-delete-line)
2075             (insert (concat "To: " cc-content "\n"))
2076             (message-remove-header (if bcc
2077                                        "bcc"
2078                                      "cc")))))))
2079
2080 ;;; End of functions adopted from `message-utils.el'.
2081
2082 (defun message-remove-header (header &optional is-regexp first reverse)
2083   "Remove HEADER in the narrowed buffer.
2084 If IS-REGEXP, HEADER is a regular expression.
2085 If FIRST, only remove the first instance of the header.
2086 Return the number of headers removed."
2087   (goto-char (point-min))
2088   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
2089         (number 0)
2090         (case-fold-search t)
2091         last)
2092     (while (and (not (eobp))
2093                 (not last))
2094       (if (if reverse
2095               (not (looking-at regexp))
2096             (looking-at regexp))
2097           (progn
2098             (incf number)
2099             (when first
2100               (setq last t))
2101             (delete-region
2102              (point)
2103              ;; There might be a continuation header, so we have to search
2104              ;; until we find a new non-continuation line.
2105              (progn
2106                (forward-line 1)
2107                (if (re-search-forward "^[^ \t]" nil t)
2108                    (goto-char (match-beginning 0))
2109                  (point-max)))))
2110         (forward-line 1)
2111         (if (re-search-forward "^[^ \t]" nil t)
2112             (goto-char (match-beginning 0))
2113           (goto-char (point-max)))))
2114     number))
2115
2116 (defun message-remove-first-header (header)
2117   "Remove the first instance of HEADER if there is more than one."
2118   (let ((count 0)
2119         (regexp (concat "^" (regexp-quote header) ":")))
2120     (save-excursion
2121       (goto-char (point-min))
2122       (while (re-search-forward regexp nil t)
2123         (incf count)))
2124     (while (> count 1)
2125       (message-remove-header header nil t)
2126       (decf count))))
2127
2128 (defun message-narrow-to-headers ()
2129   "Narrow the buffer to the head of the message."
2130   (widen)
2131   (narrow-to-region
2132    (goto-char (point-min))
2133    (if (re-search-forward
2134         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2135        (match-beginning 0)
2136      (point-max)))
2137   (goto-char (point-min)))
2138
2139 (defun message-narrow-to-head-1 ()
2140   "Like `message-narrow-to-head'.  Don't widen."
2141   (narrow-to-region
2142    (goto-char (point-min))
2143    (if (search-forward "\n\n" nil 1)
2144        (1- (point))
2145      (point-max)))
2146   (goto-char (point-min)))
2147
2148 (defun message-narrow-to-head ()
2149   "Narrow the buffer to the head of the message.
2150 Point is left at the beginning of the narrowed-to region."
2151   (widen)
2152   (message-narrow-to-head-1))
2153
2154 (defun message-narrow-to-headers-or-head ()
2155   "Narrow the buffer to the head of the message."
2156   (widen)
2157   (narrow-to-region
2158    (goto-char (point-min))
2159    (cond
2160     ((re-search-forward
2161       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2162      (match-beginning 0))
2163     ((search-forward "\n\n" nil t)
2164      (1- (point)))
2165     (t
2166      (point-max))))
2167   (goto-char (point-min)))
2168
2169 (defun message-news-p ()
2170   "Say whether the current buffer contains a news message."
2171   (and (not message-this-is-mail)
2172        (or message-this-is-news
2173            (save-excursion
2174              (save-restriction
2175                (message-narrow-to-headers)
2176                (and (message-fetch-field "newsgroups")
2177                     (not (message-fetch-field "posted-to"))))))))
2178
2179 (defun message-mail-p ()
2180   "Say whether the current buffer contains a mail message."
2181   (and (not message-this-is-news)
2182        (or message-this-is-mail
2183            (save-excursion
2184              (save-restriction
2185                (message-narrow-to-headers)
2186                (or (message-fetch-field "to")
2187                    (message-fetch-field "cc")
2188                    (message-fetch-field "bcc")))))))
2189
2190 (defun message-subscribed-p ()
2191   "Say whether we need to insert a MFT header."
2192   (or message-subscribed-regexps
2193       message-subscribed-addresses
2194       message-subscribed-address-file
2195       message-subscribed-address-functions))
2196
2197 (defun message-next-header ()
2198   "Go to the beginning of the next header."
2199   (beginning-of-line)
2200   (or (eobp) (forward-char 1))
2201   (not (if (re-search-forward "^[^ \t]" nil t)
2202            (beginning-of-line)
2203          (goto-char (point-max)))))
2204
2205 (defun message-sort-headers-1 ()
2206   "Sort the buffer as headers using `message-rank' text props."
2207   (goto-char (point-min))
2208   (require 'sort)
2209   (sort-subr
2210    nil 'message-next-header
2211    (lambda ()
2212      (message-next-header)
2213      (unless (bobp)
2214        (forward-char -1)))
2215    (lambda ()
2216      (or (get-text-property (point) 'message-rank)
2217          10000))))
2218
2219 (defun message-sort-headers ()
2220   "Sort the headers of the current message according to `message-header-format-alist'."
2221   (interactive)
2222   (save-excursion
2223     (save-restriction
2224       (let ((max (1+ (length message-header-format-alist)))
2225             rank)
2226         (message-narrow-to-headers)
2227         (while (re-search-forward "^[^ \n]+:" nil t)
2228           (put-text-property
2229            (match-beginning 0) (1+ (match-beginning 0))
2230            'message-rank
2231            (if (setq rank (length (memq (assq (intern (buffer-substring
2232                                                        (match-beginning 0)
2233                                                        (1- (match-end 0))))
2234                                               message-header-format-alist)
2235                                         message-header-format-alist)))
2236                (- max rank)
2237              (1+ max)))))
2238       (message-sort-headers-1))))
2239
2240 \f
2241
2242 ;;;
2243 ;;; Message mode
2244 ;;;
2245
2246 ;;; Set up keymap.
2247
2248 (defvar message-mode-map nil)
2249
2250 (unless message-mode-map
2251   (setq message-mode-map (make-keymap))
2252   (set-keymap-parent message-mode-map text-mode-map)
2253   (define-key message-mode-map "\C-c?" 'describe-mode)
2254
2255   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
2256   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
2257   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
2258   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
2259   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
2260   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
2261   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
2262   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
2263   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2264   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
2265   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
2266   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
2267   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2268   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
2269   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
2270   (define-key message-mode-map "\C-c\C-f\C-i"
2271     'message-insert-or-toggle-importance)
2272   (define-key message-mode-map "\C-c\C-f\C-a"
2273     'message-generate-unsubscribed-mail-followup-to)
2274
2275   ;; modify headers (and insert notes in body)
2276   (define-key message-mode-map "\C-c\C-fs"    'message-change-subject)
2277   ;;
2278   (define-key message-mode-map "\C-c\C-fx"    'message-cross-post-followup-to)
2279   ;; prefix+message-cross-post-followup-to = same w/o cross-post
2280   (define-key message-mode-map "\C-c\C-ft"    'message-reduce-to-to-cc)
2281   (define-key message-mode-map "\C-c\C-fa"    'message-add-archive-header)
2282   ;; mark inserted text
2283   (define-key message-mode-map "\C-c\M-m" 'message-mark-inserted-region)
2284   (define-key message-mode-map "\C-c\M-f" 'message-mark-insert-file)
2285
2286   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
2287   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
2288   (define-key message-mode-map "\C-c\C-fc" 'message-goto-mail-copies-to)
2289
2290   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
2291   (define-key message-mode-map "\C-c\C-fw" 'message-insert-wide-reply)
2292   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
2293   (define-key message-mode-map "\C-c\C-l" 'message-to-list-only)
2294
2295   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
2296   (define-key message-mode-map "\C-c\M-n"
2297     'message-insert-disposition-notification-to)
2298
2299   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
2300   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
2301   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
2302   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
2303   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
2304   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
2305   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
2306   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
2307
2308   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
2309   (define-key message-mode-map "\C-c\C-s" 'message-send)
2310   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
2311   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
2312   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
2313
2314   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
2315   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
2316   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
2317   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
2318   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
2319
2320   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
2321   (define-key message-mode-map "\t" 'message-tab)
2322   (define-key message-mode-map "\M-;" 'comment-region)
2323
2324   (define-key message-mode-map "\C-xk" 'message-mimic-kill-buffer))
2325
2326 (easy-menu-define
2327  message-mode-menu message-mode-map "Message Menu."
2328  `("Message"
2329    ["Yank Original" message-yank-original t]
2330    ["Fill Yanked Message" message-fill-yanked-message t]
2331    ["Insert Signature" message-insert-signature t]
2332    ["Caesar (rot13) Message" message-caesar-buffer-body t]
2333    ["Caesar (rot13) Region" message-caesar-region (message-mark-active-p)]
2334    ["Elide Region" message-elide-region
2335     :active (message-mark-active-p)
2336     ,@(if (featurep 'xemacs) nil
2337         '(:help "Replace text in region with an ellipsis"))]
2338    ["Delete Outside Region" message-delete-not-region
2339     :active (message-mark-active-p)
2340     ,@(if (featurep 'xemacs) nil
2341         '(:help "Delete all quoted text outside region"))]
2342    ["Kill To Signature" message-kill-to-signature t]
2343    ["Newline and Reformat" message-newline-and-reformat t]
2344    ["Rename buffer" message-rename-buffer t]
2345    ["Spellcheck" ispell-message
2346     ,@(if (featurep 'xemacs) '(t)
2347         '(:help "Spellcheck this message"))]
2348    ["Attach file as MIME" mime-edit-insert-file
2349     ,@(if (featurep 'xemacs) '(t)
2350         '(:help "Attach a file at point"))]
2351    "----"
2352    ["Insert Region Marked" message-mark-inserted-region
2353     :active (message-mark-active-p)
2354     ,@(if (featurep 'xemacs) nil
2355         '(:help "Mark region with enclosing tags"))]
2356    ["Insert File Marked..." message-mark-insert-file
2357     ,@(if (featurep 'xemacs) '(t)
2358         '(:help "Insert file at point marked with enclosing tags"))]
2359    "----"
2360    ["Send Message" message-send-and-exit
2361     ,@(if (featurep 'xemacs) '(t)
2362         '(:help "Send this message"))]
2363    ["Postpone Message" message-dont-send
2364     ,@(if (featurep 'xemacs) '(t)
2365         '(:help "File this draft message and exit"))]
2366    ["Send at Specific Time..." gnus-delay-article
2367     ,@(if (featurep 'xemacs) '(t)
2368         '(:help "Ask, then arrange to send message at that time"))]
2369    ["Kill Message" message-kill-buffer
2370     ,@(if (featurep 'xemacs) '(t)
2371         '(:help "Delete this message without sending"))]))
2372
2373 (easy-menu-define
2374  message-mode-field-menu message-mode-map ""
2375  `("Field"
2376    ["Fetch To" message-insert-to t]
2377    ["Fetch Newsgroups" message-insert-newsgroups t]
2378    "----"
2379    ["To" message-goto-to t]
2380    ["From" message-goto-from t]
2381    ["Subject" message-goto-subject t]
2382    ["Change subject..." message-change-subject t]
2383    ["Cc" message-goto-cc t]
2384    ["Bcc" message-goto-bcc t]
2385    ["Fcc" message-goto-fcc t]
2386    ["Reply-To" message-goto-reply-to t]
2387    ["Flag As Important" message-insert-importance-high
2388     ,@(if (featurep 'xemacs) '(t)
2389         '(:help "Mark this message as important"))]
2390    ["Flag As Unimportant" message-insert-importance-low
2391     ,@(if (featurep 'xemacs) '(t)
2392         '(:help "Mark this message as unimportant"))]
2393    ["Request Receipt"
2394     message-insert-disposition-notification-to
2395     ,@(if (featurep 'xemacs) '(t)
2396         '(:help "Request a receipt notification"))]
2397    "----"
2398    ;; (typical) news stuff
2399    ["Summary" message-goto-summary t]
2400    ["Keywords" message-goto-keywords t]
2401    ["Newsgroups" message-goto-newsgroups t]
2402    ["Followup-To" message-goto-followup-to t]
2403    ;; ["Followup-To (with note in body)" message-cross-post-followup-to t]
2404    ["Crosspost / Followup-To..." message-cross-post-followup-to t]
2405    ["Distribution" message-goto-distribution t]
2406    ["X-No-Archive:" message-add-archive-header t ]
2407    "----"
2408    ;; (typical) mailing-lists stuff
2409    ["Send to list only" message-to-list-only t]
2410    ["Mail-Followup-To" message-goto-mail-followup-to t]
2411    ["Mail-Reply-To" message-goto-mail-reply-to t]
2412    ["Mail-Copies-To" message-goto-mail-copies-to t]
2413    ["Reduce To: to Cc:" message-reduce-to-to-cc t]
2414    "----"
2415    ["Sort Headers" message-sort-headers t]
2416    ["Goto Body" message-goto-body t]
2417    ["Goto Signature" message-goto-signature t]))
2418
2419 (defvar message-tool-bar-map nil)
2420
2421 (eval-when-compile
2422   (defvar facemenu-add-face-function)
2423   (defvar facemenu-remove-face-function))
2424
2425 ;;; Forbidden properties
2426 ;;
2427 ;; We use `after-change-functions' to keep special text properties
2428 ;; that interfer with the normal function of message mode out of the
2429 ;; buffer.
2430
2431 (defcustom message-strip-special-text-properties t
2432   "Strip special properties from the message buffer.
2433
2434 Emacs has a number of special text properties which can break message
2435 composing in various ways.  If this option is set, message will strip
2436 these properties from the message composition buffer.  However, some
2437 packages requires these properties to be present in order to work.
2438 If you use one of these packages, turn this option off, and hope the
2439 message composition doesn't break too bad."
2440   :group 'message-various
2441   :type 'boolean)
2442
2443 (defconst message-forbidden-properties
2444   ;; No reason this should be clutter up customize.  We make it a
2445   ;; property list (rather than a list of property symbols), to be
2446   ;; directly useful for `remove-text-properties'.
2447   '(field nil read-only nil intangible nil invisible nil
2448           mouse-face nil modification-hooks nil insert-in-front-hooks nil
2449           insert-behind-hooks nil point-entered nil point-left nil)
2450   ;; Other special properties:
2451   ;; category, face, display: probably doesn't do any harm.
2452   ;; fontified: is used by font-lock.
2453   ;; syntax-table, local-map: I dunno.
2454   ;; We need to add XEmacs names to the list.
2455   "Property list of with properties.forbidden in message buffers.
2456 The values of the properties are ignored, only the property names are used.")
2457
2458 (defun message-tamago-not-in-use-p (pos)
2459   "Return t when tamago version 4 is not in use at the cursor position.
2460 Tamago version 4 is a popular input method for writing Japanese text.
2461 It uses the properties `intangible', `invisible', `modification-hooks'
2462 and `read-only' when translating ascii or kana text to kanji text.
2463 These properties are essential to work, so we should never strip them."
2464   (not (and (boundp 'egg-modefull-mode)
2465             (symbol-value 'egg-modefull-mode)
2466             (or (memq (get-text-property pos 'intangible)
2467                       '(its-part-1 its-part-2))
2468                 (get-text-property pos 'egg-end)
2469                 (get-text-property pos 'egg-lang)
2470                 (get-text-property pos 'egg-start)))))
2471
2472 (defun message-strip-forbidden-properties (begin end &optional old-length)
2473   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
2474 This function is intended to be called from `after-change-functions'.
2475 See also `message-forbidden-properties'."
2476   (when (and message-strip-special-text-properties
2477              (message-tamago-not-in-use-p begin)
2478              ;; Check whether the invisible MIME part is not inserted.
2479              (not (text-property-any begin end 'mime-edit-invisible t)))
2480     (remove-text-properties begin end message-forbidden-properties)))
2481
2482 ;;;###autoload
2483 (define-derived-mode message-mode text-mode "Message"
2484   "Major mode for editing mail and news to be sent.
2485 Like Text Mode but with these additional commands:\\<message-mode-map>
2486 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2487 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2488 C-c C-f  move to a header field (and create it if there isn't):
2489          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2490          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2491          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2492          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2493          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2494          C-c C-f C-o  move to From (\"Originator\")
2495          C-c C-f C-f  move to Followup-To
2496          C-c C-f C-m  move to Mail-Followup-To
2497          C-c C-f c    move to Mail-Copies-To
2498          C-c C-f C-i  cycle through Importance values
2499          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2500          C-c C-f x    crossposting with FollowUp-To header and note in body
2501          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2502          C-c C-f a    Insert X-No-Archive: header and a note in the body
2503 C-c C-t  `message-insert-to' (add a To header to a news followup)
2504 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2505 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2506 C-c C-b  `message-goto-body' (move to beginning of message text).
2507 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2508 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2509 C-c C-y  `message-yank-original' (insert current message, if any).
2510 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2511 C-c C-e  `message-elide-region' (elide the text between point and mark).
2512 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2513 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2514 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2515 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2516 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2517 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2518 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2519 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2520   (setq local-abbrev-table text-mode-abbrev-table)
2521   (set (make-local-variable 'message-reply-buffer) nil)
2522   (make-local-variable 'message-send-actions)
2523   (make-local-variable 'message-exit-actions)
2524   (make-local-variable 'message-kill-actions)
2525   (make-local-variable 'message-postpone-actions)
2526   (make-local-variable 'message-draft-article)
2527   (setq buffer-offer-save t)
2528   (set (make-local-variable 'facemenu-add-face-function)
2529        (lambda (face end)
2530          (let ((face-fun (cdr (assq face message-face-alist))))
2531            (if face-fun
2532                (funcall face-fun (point) end)
2533              (error "Face %s not configured for %s mode" face mode-name)))
2534          ""))
2535   (set (make-local-variable 'facemenu-remove-face-function) t)
2536   (set (make-local-variable 'message-reply-headers) nil)
2537   (make-local-variable 'message-user-agent)
2538   (make-local-variable 'message-post-method)
2539   (set (make-local-variable 'message-sent-message-via) nil)
2540   (set (make-local-variable 'message-checksum) nil)
2541   (make-local-variable 'message-parameter-alist)
2542   (setq message-parameter-alist
2543         (copy-sequence message-startup-parameter-alist))
2544   (message-setup-fill-variables)
2545   (set
2546    (make-local-variable 'paragraph-separate)
2547    (format "\\(%s\\)\\|\\(%s\\)"
2548            paragraph-separate
2549            "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)"))
2550   ;; Allow using comment commands to add/remove quoting.
2551   (set (make-local-variable 'comment-start) message-yank-prefix)
2552   (if (featurep 'xemacs)
2553       (message-setup-toolbar)
2554     (set (make-local-variable 'font-lock-defaults)
2555          '(message-font-lock-keywords t))
2556     (if (boundp 'tool-bar-map)
2557         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2558   (easy-menu-add message-mode-menu message-mode-map)
2559   (easy-menu-add message-mode-field-menu message-mode-map)
2560   ;; make-local-hook is harmless though obsolete in Emacs 21.
2561   ;; Emacs 20 and XEmacs need make-local-hook.
2562   (make-local-hook 'after-change-functions)
2563   ;; Mmmm... Forbidden properties...
2564   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2565             nil 'local)
2566   ;; Allow mail alias things.
2567   (when (eq message-mail-alias-type 'abbrev)
2568     (if (fboundp 'mail-abbrevs-setup)
2569         (mail-abbrevs-setup)
2570       (mail-aliases-setup)))
2571   (unless buffer-file-name
2572     (message-set-auto-save-file-name))
2573   (set (make-local-variable 'indent-tabs-mode) nil)) ;No tabs for indentation.
2574
2575 (defun message-setup-fill-variables ()
2576   "Setup message fill variables."
2577   (set (make-local-variable 'fill-paragraph-function)
2578        'message-fill-paragraph)
2579   (make-local-variable 'paragraph-separate)
2580   (make-local-variable 'paragraph-start)
2581   (make-local-variable 'adaptive-fill-regexp)
2582   (unless (boundp 'adaptive-fill-first-line-regexp)
2583     (setq adaptive-fill-first-line-regexp nil))
2584   (make-local-variable 'adaptive-fill-first-line-regexp)
2585   (let ((quote-prefix-regexp
2586          ;; User should change message-cite-prefix-regexp if
2587          ;; message-yank-prefix is set to an abnormal value.
2588          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2589     (setq paragraph-start
2590           (concat
2591            (regexp-quote mail-header-separator) "$\\|"
2592            "[ \t]*$\\|"                 ; blank lines
2593            "-- $\\|"                    ; signature delimiter
2594            "---+$\\|"                   ; delimiters for forwarded messages
2595            page-delimiter "$\\|"        ; spoiler warnings
2596            ".*wrote:$\\|"               ; attribution lines
2597            quote-prefix-regexp "$"))    ; empty lines in quoted text
2598     (setq paragraph-separate paragraph-start)
2599     (setq adaptive-fill-regexp
2600           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2601     (setq adaptive-fill-first-line-regexp
2602           (concat quote-prefix-regexp "\\|"
2603                   adaptive-fill-first-line-regexp)))
2604   (make-local-variable 'auto-fill-inhibit-regexp)
2605   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2606   (setq auto-fill-inhibit-regexp nil)
2607   (make-local-variable 'normal-auto-fill-function)
2608   (setq normal-auto-fill-function 'message-do-auto-fill)
2609   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2610   ;; In that case, ensure that it uses the right function.  The real
2611   ;; solution would be not to use `define-derived-mode', and run
2612   ;; `text-mode-hook' ourself at the end of the mode.
2613   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2614   (when auto-fill-function
2615     (setq auto-fill-function normal-auto-fill-function)))
2616
2617 \f
2618
2619 ;;;
2620 ;;; Message mode commands
2621 ;;;
2622
2623 ;;; Movement commands
2624
2625 (defun message-goto-to ()
2626   "Move point to the To header."
2627   (interactive)
2628   (message-position-on-field "To"))
2629
2630 (defun message-goto-from ()
2631   "Move point to the From header."
2632   (interactive)
2633   (message-position-on-field "From"))
2634
2635 (defun message-goto-subject ()
2636   "Move point to the Subject header."
2637   (interactive)
2638   (message-position-on-field "Subject"))
2639
2640 (defun message-goto-cc ()
2641   "Move point to the Cc header."
2642   (interactive)
2643   (message-position-on-field "Cc" "To"))
2644
2645 (defun message-goto-bcc ()
2646   "Move point to the Bcc  header."
2647   (interactive)
2648   (message-position-on-field "Bcc" "Cc" "To"))
2649
2650 (defun message-goto-fcc ()
2651   "Move point to the Fcc header."
2652   (interactive)
2653   (message-position-on-field "Fcc" "To" "Newsgroups"))
2654
2655 (defun message-goto-reply-to ()
2656   "Move point to the Reply-To header."
2657   (interactive)
2658   (message-position-on-field "Reply-To" "Subject"))
2659
2660 (defun message-goto-mail-reply-to ()
2661   "Move point to the Mail-Reply-To header."
2662   (interactive)
2663   (message-position-on-field "Mail-Reply-To" "Subject"))
2664
2665 (defun message-goto-mail-copies-to ()
2666   "Move point to the Mail-Copies-To header.  If the header is newly created,
2667 a string \"never\" is inserted in default."
2668   (interactive)
2669   (unless (message-position-on-field "Mail-Copies-To" "Subject")
2670     (insert "never")
2671     (backward-char 5)))
2672
2673 (defun message-goto-newsgroups ()
2674   "Move point to the Newsgroups header."
2675   (interactive)
2676   (message-position-on-field "Newsgroups"))
2677
2678 (defun message-goto-distribution ()
2679   "Move point to the Distribution header."
2680   (interactive)
2681   (message-position-on-field "Distribution"))
2682
2683 (defun message-goto-followup-to ()
2684   "Move point to the Followup-To header."
2685   (interactive)
2686   (message-position-on-field "Followup-To" "Newsgroups"))
2687
2688 (defun message-goto-mail-followup-to ()
2689   "Move point to the Mail-Followup-To header.  If the header is newly created
2690 and To field contains only one address, the address is inserted in default."
2691   (interactive)
2692   (unless (message-position-on-field "Mail-Followup-To" "Subject")
2693     (let ((start (point))
2694           addresses)
2695       (save-restriction
2696         (message-narrow-to-headers)
2697         (setq addresses (split-string (mail-strip-quoted-names
2698                                        (or (std11-fetch-field "to") ""))
2699                                       "[ \f\t\n\r\v,]+"))
2700         (when (eq 1 (length addresses))
2701           (goto-char start)
2702           (insert (car addresses))
2703           (goto-char start))))))
2704
2705 (defun message-goto-keywords ()
2706   "Move point to the Keywords header."
2707   (interactive)
2708   (message-position-on-field "Keywords" "Subject"))
2709
2710 (defun message-goto-summary ()
2711   "Move point to the Summary header."
2712   (interactive)
2713   (message-position-on-field "Summary" "Subject"))
2714
2715 (defun message-goto-body (&optional interactivep)
2716   "Move point to the beginning of the message body."
2717   (interactive (list t))
2718   (when (and interactivep
2719              (looking-at "[ \t]*\n"))
2720     (expand-abbrev))
2721   (goto-char (point-min))
2722   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2723       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2724
2725 (defun message-goto-eoh ()
2726   "Move point to the end of the headers."
2727   (interactive)
2728   (message-goto-body)
2729   (forward-line -1))
2730
2731 (defun message-goto-signature ()
2732   "Move point to the beginning of the message signature.
2733 If there is no signature in the article, go to the end and
2734 return nil."
2735   (interactive)
2736   (goto-char (point-min))
2737   (if (re-search-forward message-signature-separator nil t)
2738       (forward-line 1)
2739     (goto-char (point-max))
2740     nil))
2741
2742 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
2743   "Insert a reasonable MFT header in a post to an unsubscribed list.
2744 When making original posts to a mailing list you are not subscribed to,
2745 you have to type in a MFT header by hand.  The contents, usually, are
2746 the addresses of the list and your own address.  This function inserts
2747 such a header automatically.  It fetches the contents of the To: header
2748 in the current mail buffer, and appends the current `user-mail-address'.
2749
2750 If the optional argument INCLUDE-CC is non-nil, the addresses in the
2751 Cc: header are also put into the MFT."
2752
2753   (interactive "P")
2754   (message-remove-header "Mail-Followup-To")
2755   (let* ((cc (and include-cc (message-fetch-field "Cc")))
2756          (tos (if cc
2757                   (concat (message-fetch-field "To") "," cc)
2758                 (message-fetch-field "To"))))
2759     (message-goto-mail-followup-to)
2760     (insert (concat tos ", " user-mail-address))))
2761
2762 \f
2763
2764 (defun message-insert-to (&optional force)
2765   "Insert a To header that points to the author of the article being replied to.
2766 If the original author requested not to be sent mail, the function signals
2767 an error.
2768 With the prefix argument FORCE, insert the header anyway."
2769   (interactive "P")
2770   (let ((co (message-fetch-reply-field "mail-copies-to")))
2771     (when (and (null force)
2772                co
2773                (or (equal (downcase co) "never")
2774                    (equal (downcase co) "nobody")))
2775       (error "The user has requested not to have copies sent via mail")))
2776   (message-carefully-insert-headers
2777    (list (cons 'To
2778                (or (message-fetch-reply-field "mail-reply-to")
2779                    (message-fetch-reply-field "reply-to")
2780                    (message-fetch-reply-field "from")
2781                    "")))))
2782
2783 (defun message-insert-wide-reply ()
2784   "Insert To and Cc headers as if you were doing a wide reply."
2785   (interactive)
2786   (let ((headers (message-with-reply-buffer
2787                    (message-get-reply-headers t))))
2788     (message-carefully-insert-headers headers)))
2789
2790 (defun message-carefully-insert-headers (headers)
2791   (dolist (header headers)
2792     (let ((header-name (symbol-name (car header))))
2793       (when (and (message-position-on-field header-name)
2794                  (mail-fetch-field header-name)
2795                  (not (string-match "\\` *\\'"
2796                                     (mail-fetch-field header-name))))
2797         (insert ", "))
2798       (insert (cdr header)))))
2799
2800 (defun message-widen-reply ()
2801   "Widen the reply to include maximum recipients."
2802   (interactive)
2803   (let ((follow-to
2804          (and message-reply-buffer
2805               (buffer-name message-reply-buffer)
2806               (save-excursion
2807                 (set-buffer message-reply-buffer)
2808                 (message-get-reply-headers t)))))
2809     (save-excursion
2810       (save-restriction
2811         (message-narrow-to-headers)
2812         (dolist (elem follow-to)
2813           (message-remove-header (symbol-name (car elem)))
2814           (goto-char (point-min))
2815           (insert (symbol-name (car elem)) ": "
2816                   (cdr elem) "\n"))))))
2817
2818 (defun message-insert-newsgroups ()
2819   "Insert the Newsgroups header from the article being replied to."
2820   (interactive)
2821   (when (and (message-position-on-field "Newsgroups")
2822              (mail-fetch-field "newsgroups")
2823              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2824     (insert ","))
2825   (insert (or (message-fetch-reply-field "newsgroups") "")))
2826
2827 \f
2828
2829 ;;; Various commands
2830
2831 (defun message-delete-not-region (beg end)
2832   "Delete everything in the body of the current message outside of the region."
2833   (interactive "r")
2834   (let (citeprefix)
2835     (save-excursion
2836       (goto-char beg)
2837       ;; snarf citation prefix, if appropriate
2838       (unless (eq (point) (progn (beginning-of-line) (point)))
2839         (when (looking-at message-cite-prefix-regexp)
2840           (setq citeprefix (match-string 0))))
2841       (goto-char end)
2842       (delete-region (point) (if (not (message-goto-signature))
2843                                  (point)
2844                                (forward-line -2)
2845                                (point)))
2846       (insert "\n")
2847       (goto-char beg)
2848       (delete-region beg (progn (message-goto-body)
2849                                 (forward-line 2)
2850                                 (point)))
2851       (when citeprefix
2852         (insert citeprefix))))
2853   (when (message-goto-signature)
2854     (forward-line -2)))
2855
2856 (defun message-kill-to-signature ()
2857   "Deletes all text up to the signature."
2858   (interactive)
2859   (let ((point (point)))
2860     (message-goto-signature)
2861     (unless (eobp)
2862       (forward-line -2))
2863     (kill-region point (point))
2864     (unless (bolp)
2865       (insert "\n"))))
2866
2867 (defun message-newline-and-reformat (&optional arg not-break)
2868   "Insert four newlines, and then reformat if inside quoted text.
2869 Prefix arg means justify as well."
2870   (interactive (list (if current-prefix-arg 'full)))
2871   (let (quoted point beg end leading-space bolp)
2872     (setq point (point))
2873     (beginning-of-line)
2874     (setq beg (point))
2875     (setq bolp (= beg point))
2876     ;; Find first line of the paragraph.
2877     (if not-break
2878         (while (and (not (eobp))
2879                     (not (looking-at message-cite-prefix-regexp))
2880                     (looking-at paragraph-start))
2881           (forward-line 1)))
2882     ;; Find the prefix
2883     (when (looking-at message-cite-prefix-regexp)
2884       (setq quoted (match-string 0))
2885       (goto-char (match-end 0))
2886       (looking-at "[ \t]*")
2887       (setq leading-space (match-string 0)))
2888     (if (and quoted
2889              (not not-break)
2890              (not bolp)
2891              (< (- point beg) (length quoted)))
2892         ;; break inside the cite prefix.
2893         (setq quoted nil
2894               end nil))
2895     (if quoted
2896         (progn
2897           (forward-line 1)
2898           (while (and (not (eobp))
2899                       (not (looking-at paragraph-separate))
2900                       (looking-at message-cite-prefix-regexp)
2901                       (equal quoted (match-string 0)))
2902             (goto-char (match-end 0))
2903             (looking-at "[ \t]*")
2904             (if (> (length leading-space) (length (match-string 0)))
2905                 (setq leading-space (match-string 0)))
2906             (forward-line 1))
2907           (setq end (point))
2908           (goto-char beg)
2909           (while (and (if (bobp) nil (forward-line -1) t)
2910                       (not (looking-at paragraph-start))
2911                       (looking-at message-cite-prefix-regexp)
2912                       (equal quoted (match-string 0)))
2913             (setq beg (point))
2914             (goto-char (match-end 0))
2915             (looking-at "[ \t]*")
2916             (if (> (length leading-space) (length (match-string 0)))
2917                 (setq leading-space (match-string 0)))))
2918       (while (and (not (eobp))
2919                   (not (looking-at paragraph-separate))
2920                   (not (looking-at message-cite-prefix-regexp)))
2921         (forward-line 1))
2922       (setq end (point))
2923       (goto-char beg)
2924       (while (and (if (bobp) nil (forward-line -1) t)
2925                   (not (looking-at paragraph-start))
2926                   (not (looking-at message-cite-prefix-regexp)))
2927         (setq beg (point))))
2928     (goto-char point)
2929     (save-restriction
2930       (narrow-to-region beg end)
2931       (if not-break
2932           (setq point nil)
2933         (if bolp
2934             (newline)
2935           (newline)
2936           (newline))
2937         (setq point (point))
2938         ;; (newline 2) doesn't mark both newline's as hard, so call
2939         ;; newline twice. -jas
2940         (newline)
2941         (newline)
2942         (delete-region (point) (re-search-forward "[ \t]*"))
2943         (when (and quoted (not bolp))
2944           (insert quoted leading-space)))
2945       (if quoted
2946           (let* ((adaptive-fill-regexp
2947                   (regexp-quote (concat quoted leading-space)))
2948                  (adaptive-fill-first-line-regexp
2949                   adaptive-fill-regexp ))
2950             (fill-paragraph arg))
2951         (fill-paragraph arg))
2952       (if point (goto-char point)))))
2953
2954 (defun message-fill-paragraph (&optional arg)
2955   "Like `fill-paragraph'."
2956   (interactive (list (if current-prefix-arg 'full)))
2957   (if (and (boundp 'filladapt-mode) filladapt-mode)
2958       nil
2959     (message-newline-and-reformat arg t)
2960     t))
2961
2962 ;; Is it better to use `mail-header-end'?
2963 (defun message-point-in-header-p ()
2964   "Return t if point is in the header."
2965   (save-excursion
2966     (let ((p (point)))
2967       (goto-char (point-min))
2968       (not (re-search-forward
2969             (concat "^" (regexp-quote mail-header-separator) "\n")
2970             p t)))))
2971
2972 (defun message-do-auto-fill ()
2973   "Like `do-auto-fill', but don't fill in message header."
2974   (unless (message-point-in-header-p)
2975     (do-auto-fill)))
2976
2977 (defun message-insert-signature (&optional force)
2978   "Insert a signature.  See documentation for variable `message-signature'."
2979   (interactive (list 0))
2980   (let* ((signature
2981           (cond
2982            ((and (null message-signature)
2983                  (eq force 0))
2984             (save-excursion
2985               (goto-char (point-max))
2986               (not (re-search-backward message-signature-separator nil t))))
2987            ((and (null message-signature)
2988                  force)
2989             t)
2990            ((message-functionp message-signature)
2991             (funcall message-signature))
2992            ((listp message-signature)
2993             (eval message-signature))
2994            (t message-signature)))
2995          (signature
2996           (cond ((stringp signature)
2997                  signature)
2998                 ((and (eq t signature)
2999                       message-signature-file
3000                       (file-exists-p message-signature-file))
3001                  signature))))
3002     (when signature
3003       (goto-char (point-max))
3004       ;; Insert the signature.
3005       (unless (bolp)
3006         (insert "\n"))
3007       (when message-signature-insert-empty-line
3008         (insert "\n"))
3009       (insert "\n" message-signature-separator-for-insertion)
3010       (unless (bolp)
3011         (insert "\n"))
3012       (if (eq signature t)
3013           (insert-file-contents message-signature-file)
3014         (insert signature))
3015       (goto-char (point-max))
3016       (or (bolp) (insert "\n")))))
3017
3018 (defun message-insert-importance-high ()
3019   "Insert header to mark message as important."
3020   (interactive)
3021   (save-excursion
3022     (message-remove-header "Importance")
3023     (message-goto-eoh)
3024     (insert "Importance: high\n")))
3025
3026 (defun message-insert-importance-low ()
3027   "Insert header to mark message as unimportant."
3028   (interactive)
3029   (save-excursion
3030     (message-remove-header "Importance")
3031     (message-goto-eoh)
3032     (insert "Importance: low\n")))
3033
3034 (defun message-insert-or-toggle-importance ()
3035   "Insert a \"Importance: high\" header, or cycle through the header values.
3036 The three allowed values according to RFC 1327 are `high', `normal'
3037 and `low'."
3038   (interactive)
3039   (save-excursion
3040     (let ((valid '("high" "normal" "low"))
3041           (new "high")
3042           cur)
3043       (when (setq cur (message-fetch-field "Importance"))
3044         (message-remove-header "Importance")
3045         (setq new (cond ((string= cur "high")
3046                          "low")
3047                         ((string= cur "low")
3048                          "normal")
3049                         (t
3050                          "high"))))
3051       (message-goto-eoh)
3052       (insert (format "Importance: %s\n" new)))))
3053
3054 (defun message-insert-disposition-notification-to ()
3055   "Request a disposition notification (return receipt) to this message.
3056 Note that this should not be used in newsgroups."
3057   (interactive)
3058   (save-excursion
3059     (message-remove-header "Disposition-Notification-To")
3060     (message-goto-eoh)
3061     (insert (format "Disposition-Notification-To: %s\n"
3062                     (or (message-fetch-field "From") (message-make-from))))))
3063
3064 (defun message-elide-region (b e)
3065   "Elide the text in the region.
3066 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3067 text was killed."
3068   (interactive "r")
3069   (kill-region b e)
3070   (insert message-elide-ellipsis))
3071
3072 (defvar message-caesar-translation-table nil)
3073
3074 (defun message-caesar-region (b e &optional n)
3075   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3076   (interactive
3077    (list
3078     (min (point) (or (mark t) (point)))
3079     (max (point) (or (mark t) (point)))
3080     (when current-prefix-arg
3081       (prefix-numeric-value current-prefix-arg))))
3082
3083   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3084   (unless (or (zerop n)                 ; no action needed for a rot of 0
3085               (= b e))                  ; no region to rotate
3086     ;; We build the table, if necessary.
3087     (when (or (not message-caesar-translation-table)
3088               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3089       (setq message-caesar-translation-table
3090             (message-make-caesar-translation-table n)))
3091     (translate-region b e message-caesar-translation-table)))
3092
3093 (defun message-make-caesar-translation-table (n)
3094   "Create a rot table with offset N."
3095   (let ((i -1)
3096         (table (make-string 256 0)))
3097     (while (< (incf i) 256)
3098       (aset table i i))
3099     (concat
3100      (substring table 0 ?A)
3101      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3102      (substring table ?A (+ ?A n))
3103      (substring table (+ ?A 26) ?a)
3104      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3105      (substring table ?a (+ ?a n))
3106      (substring table (+ ?a 26) 255))))
3107
3108 (defun message-caesar-buffer-body (&optional rotnum)
3109   "Caesar rotate all letters in the current buffer by 13 places.
3110 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3111 With prefix arg, specifies the number of places to rotate each letter forward.
3112 Mail and USENET news headers are not rotated."
3113   (interactive (if current-prefix-arg
3114                    (list (prefix-numeric-value current-prefix-arg))
3115                  (list nil)))
3116   (save-excursion
3117     (save-restriction
3118       (when (message-goto-body)
3119         (narrow-to-region (point) (point-max)))
3120       (message-caesar-region (point-min) (point-max) rotnum))))
3121
3122 (defun message-pipe-buffer-body (program)
3123   "Pipe the message body in the current buffer through PROGRAM."
3124   (save-excursion
3125     (save-restriction
3126       (when (message-goto-body)
3127         (narrow-to-region (point) (point-max)))
3128       (shell-command-on-region
3129        (point-min) (point-max) program nil t))))
3130
3131 (defun message-rename-buffer (&optional enter-string)
3132   "Rename the *message* buffer to \"*message* RECIPIENT\".
3133 If the function is run with a prefix, it will ask for a new buffer
3134 name, rather than giving an automatic name."
3135   (interactive "Pbuffer name: ")
3136   (save-excursion
3137     (save-restriction
3138       (goto-char (point-min))
3139       (narrow-to-region (point)
3140                         (search-forward mail-header-separator nil 'end))
3141       (let* ((mail-to (or
3142                        (if (message-news-p) (message-fetch-field "Newsgroups")
3143                          (message-fetch-field "To"))
3144                        ""))
3145              (mail-trimmed-to
3146               (if (string-match "," mail-to)
3147                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3148                 mail-to))
3149              (name-default (concat "*message* " mail-trimmed-to))
3150              (name (if enter-string
3151                        (read-string "New buffer name: " name-default)
3152                      name-default)))
3153         (rename-buffer name t)))))
3154
3155 (defun message-fill-yanked-message (&optional justifyp)
3156   "Fill the paragraphs of a message yanked into this one.
3157 Numeric argument means justify as well."
3158   (interactive "P")
3159   (save-excursion
3160     (goto-char (point-min))
3161     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3162     (let ((fill-prefix message-yank-prefix))
3163       (fill-individual-paragraphs (point) (point-max) justifyp))))
3164
3165 (defun message-indent-citation ()
3166   "Modify text just inserted from a message to be cited.
3167 The inserted text should be the region.
3168 When this function returns, the region is again around the modified text.
3169
3170 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3171 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3172   (let ((start (point)))
3173     ;; Remove unwanted headers.
3174     (when message-ignored-cited-headers
3175       (let (all-removed)
3176         (save-restriction
3177           (narrow-to-region
3178            (goto-char start)
3179            (if (search-forward "\n\n" nil t)
3180                (1- (point))
3181              (point)))
3182           (message-remove-header message-ignored-cited-headers t)
3183           (when (= (point-min) (point-max))
3184             (setq all-removed t))
3185           (goto-char (point-max)))
3186         (if all-removed
3187             (goto-char start)
3188           (forward-line 1))))
3189     ;; Delete blank lines at the start of the buffer.
3190     (while (and (point-min)
3191                 (eolp)
3192                 (not (eobp)))
3193       (message-delete-line))
3194     ;; Delete blank lines at the end of the buffer.
3195     (goto-char (point-max))
3196     (unless (bolp)
3197       (insert "\n"))
3198     (while (and (zerop (forward-line -1))
3199                 (looking-at "$"))
3200       (message-delete-line))
3201     ;; Do the indentation.
3202     (if (null message-yank-prefix)
3203         (indent-rigidly start (mark t) message-indentation-spaces)
3204       (save-excursion
3205         (goto-char start)
3206         (while (< (point) (mark t))
3207           (if (or (looking-at ">") (looking-at "^$"))
3208               (insert message-yank-cited-prefix)
3209             (insert message-yank-prefix))
3210           (forward-line 1))))
3211     (goto-char start)))
3212
3213 (defun message-list-references (refs-list &rest refs-strs)
3214   "Add `Message-ID's which appear in REFS-STRS but not in REFS-LIST,
3215 to REFS-LIST."
3216   (let (refs ref id saved-id)
3217     (when (and refs-list
3218                (integerp message-list-references-add-position))
3219       (let ((pos message-list-references-add-position))
3220         (while (and refs-list
3221                     (> pos 0))
3222           (push (pop refs-list) saved-id)
3223           (setq pos (1- pos)))))
3224     (while refs-strs
3225       (when (setq refs (pop refs-strs))
3226         (setq refs (std11-parse-msg-ids (std11-lexical-analyze refs)))
3227         (while refs
3228           (when (eq (car (setq ref (pop refs))) 'msg-id)
3229             (setq id (concat "<" (mapconcat 'cdr (cdr ref) "") ">"))
3230             (or (member id refs-list)
3231                 (member id saved-id)
3232                 (push id refs-list))))))
3233     (while saved-id
3234       (push (pop saved-id) refs-list))
3235     refs-list))
3236
3237 (defvar gnus-article-copy)
3238 (defun message-yank-original (&optional arg)
3239   "Insert the message being replied to, if any.
3240 Puts point before the text and mark after.
3241 Normally indents each nonblank line ARG spaces (default 3).  However,
3242 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3243
3244 This function uses `message-cite-function' to do the actual citing.
3245
3246 Just \\[universal-argument] as argument means don't indent, insert no
3247 prefix, and don't delete any headers.
3248
3249 In addition, if `message-yank-add-new-references' is non-nil and this
3250 command is called interactively, new IDs from the yanked article will
3251 be added to \"References\" field.
3252 \(See also `message-yank-add-new-references'.)"
3253   (interactive "P")
3254   (let ((modified (buffer-modified-p))
3255         (buffer (message-eval-parameter message-reply-buffer))
3256         start end refs)
3257     (when (and buffer
3258                message-cite-function)
3259       (delete-windows-on buffer t)
3260       (insert-buffer buffer) ; mark will be set at the end of article.
3261       (setq start (point)
3262             end (mark t))
3263
3264       ;; Add new IDs to References field.
3265       (when (and message-yank-add-new-references (interactive-p))
3266         (save-excursion
3267           (save-restriction
3268             (message-narrow-to-headers)
3269             (setq refs (message-list-references
3270                         nil
3271                         (message-fetch-field "References")))
3272             (widen)
3273             (narrow-to-region start end)
3274             (std11-narrow-to-header)
3275             (when (setq refs (message-list-references
3276                               refs
3277                               (unless (eq message-yank-add-new-references
3278                                           'message-id-only)
3279                                 (or (message-fetch-field "References")
3280                                     (message-fetch-field "In-Reply-To")))
3281                               (message-fetch-field "Message-ID")))
3282               (widen)
3283               (message-narrow-to-headers)
3284               (goto-char (point-min))
3285               (let ((case-fold-search t))
3286                 (if (re-search-forward "^References:\\([\t ]+.+\n\\)+" nil t)
3287                     (replace-match "")
3288                   (goto-char (point-max))))
3289               (mail-header-format
3290                (list (or (assq 'References message-header-format-alist)
3291                          '(References . message-fill-references)))
3292                (list (cons 'References
3293                            (mapconcat 'identity (nreverse refs) " "))))
3294               (backward-delete-char 1)))))
3295
3296       (unless arg
3297         (if (and message-suspend-font-lock-when-citing
3298                  (boundp 'font-lock-mode)
3299                  (symbol-value 'font-lock-mode))
3300             (unwind-protect
3301                 (progn
3302                   (sit-for 0)
3303                   (font-lock-mode 0)
3304                   (funcall message-cite-function))
3305               (font-lock-mode 1))
3306           (funcall message-cite-function)))
3307       (message-exchange-point-and-mark)
3308       (unless (bolp)
3309         (insert ?\n))
3310       (unless modified
3311         (setq message-checksum (message-checksum))))))
3312
3313 (defun message-yank-buffer (buffer)
3314   "Insert BUFFER into the current buffer and quote it."
3315   (interactive "bYank buffer: ")
3316   (let ((message-reply-buffer buffer))
3317     (save-window-excursion
3318       (message-yank-original))))
3319
3320 (defun message-buffers ()
3321   "Return a list of active message buffers."
3322   (let (buffers)
3323     (save-excursion
3324       (dolist (buffer (buffer-list t))
3325         (set-buffer buffer)
3326         (when (and (eq major-mode 'message-mode)
3327                    (null message-sent-message-via))
3328           (push (buffer-name buffer) buffers))))
3329     (nreverse buffers)))
3330
3331 (defun message-cite-original-without-signature ()
3332   "Cite function in the standard Message manner."
3333   (let ((start (point))
3334         (end (mark t))
3335         (functions
3336          (when message-indent-citation-function
3337            (if (listp message-indent-citation-function)
3338                message-indent-citation-function
3339              (list message-indent-citation-function))))
3340         (message-reply-headers (or message-reply-headers
3341                                    (make-mail-header))))
3342     (mail-header-set-from message-reply-headers
3343                           (save-restriction
3344                             (narrow-to-region
3345                              (point)
3346                              (if (search-forward "\n\n" nil t)
3347                                  (1- (point))
3348                                (point-max)))
3349                             (or (message-fetch-field "from")
3350                                 "unknown sender")))
3351     ;; Allow undoing.
3352     (undo-boundary)
3353     (goto-char end)
3354     (when (re-search-backward message-signature-separator start t)
3355       ;; Also peel off any blank lines before the signature.
3356       (forward-line -1)
3357       (while (looking-at "^[ \t]*$")
3358         (forward-line -1))
3359       (forward-line 1)
3360       (delete-region (point) end)
3361       (unless (search-backward "\n\n" start t)
3362         ;; Insert a blank line if it is peeled off.
3363         (insert "\n")))
3364     (goto-char start)
3365     (while functions
3366       (funcall (pop functions)))
3367     (when message-citation-line-function
3368       (unless (bolp)
3369         (insert "\n"))
3370       (funcall message-citation-line-function))))
3371
3372 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
3373 (defun message-cite-original ()
3374   "Cite function in the standard Message manner."
3375   (if (and (boundp 'mail-citation-hook)
3376            mail-citation-hook)
3377       (run-hooks 'mail-citation-hook)
3378     (let ((start (point))
3379           (end (mark t))
3380           (functions
3381            (when message-indent-citation-function
3382              (if (listp message-indent-citation-function)
3383                  message-indent-citation-function
3384                (list message-indent-citation-function))))
3385           (message-reply-headers (or message-reply-headers
3386                                      (make-mail-header))))
3387       (mail-header-set-from message-reply-headers
3388                             (save-restriction
3389                               (narrow-to-region
3390                                (point)
3391                                (if (search-forward "\n\n" nil t)
3392                                    (1- (point))
3393                                  (point-max)))
3394                               (or (message-fetch-field "from")
3395                                   "unknown sender")))
3396       (goto-char start)
3397       (while functions
3398         (funcall (pop functions)))
3399       (when message-citation-line-function
3400         (unless (bolp)
3401           (insert "\n"))
3402         (funcall message-citation-line-function)))))
3403
3404 (defun message-insert-citation-line ()
3405   "Insert a simple citation line."
3406   (when message-reply-headers
3407     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3408
3409 (defun message-position-on-field (header &rest afters)
3410   (let ((case-fold-search t))
3411     (save-restriction
3412       (narrow-to-region
3413        (goto-char (point-min))
3414        (progn
3415          (re-search-forward
3416           (concat "^" (regexp-quote mail-header-separator) "$"))
3417          (match-beginning 0)))
3418       (goto-char (point-min))
3419       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3420           (progn
3421             (re-search-forward "^[^ \t]" nil 'move)
3422             (beginning-of-line)
3423             (skip-chars-backward "\n")
3424             t)
3425         (while (and afters
3426                     (not (re-search-forward
3427                           (concat "^" (regexp-quote (car afters)) ":")
3428                           nil t)))
3429           (pop afters))
3430         (when afters
3431           (re-search-forward "^[^ \t]" nil 'move)
3432           (beginning-of-line))
3433         (insert header ": \n")
3434         (forward-char -1)
3435         nil))))
3436
3437 (defun message-remove-signature ()
3438   "Remove the signature from the text between point and mark.
3439 The text will also be indented the normal way."
3440   (save-excursion
3441     (let ((start (point))
3442           mark)
3443       (if (not (re-search-forward message-signature-separator (mark t) t))
3444           ;; No signature here, so we just indent the cited text.
3445           (message-indent-citation)
3446         ;; Find the last non-empty line.
3447         (forward-line -1)
3448         (while (looking-at "[ \t]*$")
3449           (forward-line -1))
3450         (forward-line 1)
3451         (setq mark (set-marker (make-marker) (point)))
3452         (goto-char start)
3453         (message-indent-citation)
3454         ;; Enable undoing the deletion.
3455         (undo-boundary)
3456         (delete-region mark (mark t))
3457         (set-marker mark nil)))))
3458
3459 \f
3460
3461 ;;;
3462 ;;; Sending messages
3463 ;;;
3464
3465 ;; Avoid byte-compile warning.
3466 (defvar message-encoding-buffer nil)
3467 (defvar message-edit-buffer nil)
3468 (defvar message-mime-mode nil)
3469
3470 (defun message-send-and-exit (&optional arg)
3471   "Send message like `message-send', then, if no errors, exit from mail buffer."
3472   (interactive "P")
3473   (let ((buf (current-buffer))
3474         (actions message-exit-actions)
3475         (frame (selected-frame))
3476         (org-frame message-original-frame))
3477     (when (and (message-send arg)
3478                (buffer-name buf))
3479       (if message-kill-buffer-on-exit
3480           (kill-buffer buf)
3481         (bury-buffer buf)
3482         (when (eq buf (current-buffer))
3483           (message-bury buf)))
3484       (message-do-actions actions)
3485       (message-delete-frame frame org-frame)
3486       t)))
3487
3488 (defun message-dont-send ()
3489   "Don't send the message you have been editing.
3490 Instead, just auto-save the buffer and then bury it."
3491   (interactive)
3492   (set-buffer-modified-p t)
3493   (save-buffer)
3494   (let ((actions message-postpone-actions)
3495         (frame (selected-frame))
3496         (org-frame message-original-frame))
3497     (message-bury (current-buffer))
3498     (message-do-actions actions)
3499     (message-delete-frame frame org-frame)))
3500
3501 (defun message-kill-buffer ()
3502   "Kill the current buffer."
3503   (interactive)
3504   (when (or (not (buffer-modified-p))
3505             (eq t message-kill-buffer-query-function)
3506             (funcall message-kill-buffer-query-function
3507                      "The buffer modified; kill anyway? "))
3508     (let ((actions message-kill-actions)
3509           (draft-article message-draft-article)
3510           (auto-save-file-name buffer-auto-save-file-name)
3511           (file-name buffer-file-name)
3512           (modified (buffer-modified-p))
3513           (frame (selected-frame))
3514           (org-frame message-original-frame))
3515       (setq buffer-file-name nil)
3516       (kill-buffer (current-buffer))
3517       (when (and message-kill-buffer-and-remove-file
3518                  (or (and auto-save-file-name
3519                           (file-exists-p auto-save-file-name))
3520                      (and file-name
3521                           (file-exists-p file-name)))
3522                  (yes-or-no-p (format "Remove the backup file%s? "
3523                                       (if modified " too" ""))))
3524         (ignore-errors
3525           (delete-file auto-save-file-name))
3526         (let ((message-draft-article draft-article))
3527           (message-disassociate-draft)))
3528       (message-do-actions actions)
3529       (message-delete-frame frame org-frame)))
3530   (message ""))
3531
3532 (defun message-mimic-kill-buffer ()
3533   "Kill the current buffer with query.  This is an imitation for
3534 `kill-buffer', but it will delete a message frame."
3535   (interactive)
3536   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
3537                                       (buffer-name))))
3538         message-kill-buffer-and-remove-file)
3539     (when (or (not bufname)
3540               (string-equal bufname "")
3541               (string-equal bufname (buffer-name)))
3542       (message-kill-buffer))))
3543
3544 (defun message-delete-frame (frame org-frame)
3545   "Delete frame for editing message."
3546   (when (and (or (static-if (featurep 'xemacs)
3547                      (device-on-window-system-p)
3548                    window-system)
3549                  (>= emacs-major-version 20))
3550              (or (and (eq message-delete-frame-on-exit t)
3551                       (select-frame frame)
3552                       (or (eq frame org-frame)
3553                           (prog1
3554                               (y-or-n-p "Delete this frame?")
3555                             (message ""))))
3556                  (and (eq message-delete-frame-on-exit 'ask)
3557                       (select-frame frame)
3558                       (prog1
3559                           (y-or-n-p "Delete this frame?")
3560                         (message "")))))
3561     (delete-frame frame)))
3562
3563 (defun message-bury (buffer)
3564   "Bury this mail BUFFER."
3565   (let ((newbuf (other-buffer buffer)))
3566     (bury-buffer buffer)
3567     (if (and (fboundp 'frame-parameters)
3568              (cdr (assq 'dedicated (frame-parameters)))
3569              (not (null (delq (selected-frame) (visible-frame-list)))))
3570         (delete-frame (selected-frame))
3571       (switch-to-buffer newbuf))))
3572
3573 (defun message-send (&optional arg)
3574   "Send the message in the current buffer.
3575 If `message-interactive' is non-nil, wait for success indication or
3576 error messages, and inform user.
3577 Otherwise any failure is reported in a message back to the user from
3578 the mailer.
3579 The usage of ARG is defined by the instance that called Message.
3580 It should typically alter the sending method in some way or other."
3581   (interactive "P")
3582   ;; Disabled test.
3583   (when (or (buffer-modified-p)
3584             (message-check-element 'unchanged)
3585             (y-or-n-p "No changes in the buffer; really send? "))
3586     ;; Make it possible to undo the coming changes.
3587     (undo-boundary)
3588     (let ((inhibit-read-only t))
3589       (put-text-property (point-min) (point-max) 'read-only nil))
3590     (run-hooks 'message-send-hook)
3591     (message-fix-before-sending)
3592     (message message-sending-message)
3593     (let ((message-encoding-buffer
3594            (message-generate-new-buffer-clone-locals " message encoding"))
3595           (message-edit-buffer (current-buffer))
3596           (message-mime-mode mime-edit-mode-flag)
3597           (alist message-send-method-alist)
3598           (success t)
3599           elem sent dont-barf-on-no-method
3600           (message-options message-options))
3601       (unwind-protect
3602           (progn
3603             (message-options-set-recipient)
3604             (save-excursion
3605               (set-buffer message-encoding-buffer)
3606               (erase-buffer)
3607               ;; ;; Avoid copying text props (except hard newlines).
3608               ;; T-gnus change: copy all text props from the editing buffer
3609               ;; into the encoding buffer.
3610               (insert-buffer-substring message-edit-buffer)
3611               (funcall message-encode-function)
3612               (while (and success
3613                           (setq elem (pop alist)))
3614                 (when (funcall (cadr elem))
3615                   (when (and
3616                          (or (not (memq (car elem)
3617                                         message-sent-message-via))
3618                              (not (message-fetch-field "supersedes"))
3619                              (if (or (message-gnksa-enable-p 'multiple-copies)
3620                                      (not (eq (car elem) 'news)))
3621                                  (y-or-n-p
3622                                   (format
3623                                    "Already sent message via %s; resend? "
3624                                    (car elem)))
3625                                (error "Denied posting -- multiple copies")))
3626                          (setq success (funcall (caddr elem) arg)))
3627                     (setq sent t)))))
3628             (unless
3629                 (or
3630                  sent
3631                  (not success)
3632                  (let ((fcc (message-fetch-field "Fcc"))
3633                        (gcc (message-fetch-field "Gcc")))
3634                    (when (or fcc gcc)
3635                      (or
3636                       (eq message-allow-no-recipients 'always)
3637                       (and (not (eq message-allow-no-recipients 'never))
3638                            (setq dont-barf-on-no-method
3639                                  (gnus-y-or-n-p
3640                                   (format "No receiver, perform %s anyway? "
3641                                           (cond ((and fcc gcc) "Fcc and Gcc")
3642                                                 (fcc "Fcc")
3643                                                 (t "Gcc"))))))))))
3644               (error "No methods specified to send by"))
3645             (when (or dont-barf-on-no-method
3646                       (and success sent))
3647               (message-do-fcc)
3648               (save-excursion
3649                 (run-hooks 'message-sent-hook))
3650               (message "Sending...done")
3651               ;; Mark the buffer as unmodified and delete auto-save.
3652               (set-buffer-modified-p nil)
3653               (delete-auto-save-file-if-necessary t)
3654               (message-disassociate-draft)
3655               ;; Delete other mail buffers and stuff.
3656               (message-do-send-housekeeping)
3657               (message-do-actions message-send-actions)
3658               ;; Return success.
3659               t))
3660         (kill-buffer message-encoding-buffer)))))
3661
3662 (defun message-send-via-mail (arg)
3663   "Send the current message via mail."
3664   (message-send-mail arg))
3665
3666 (defun message-send-via-news (arg)
3667   "Send the current message via news."
3668   (message-send-news arg))
3669
3670 (defmacro message-check (type &rest forms)
3671   "Eval FORMS if TYPE is to be checked."
3672   `(or (message-check-element ,type)
3673        (save-excursion
3674          ,@forms)))
3675
3676 (put 'message-check 'lisp-indent-function 1)
3677 (put 'message-check 'edebug-form-spec '(form body))
3678
3679 ;; Advise the function `invisible-region'.
3680 (let (current-load-list)
3681   (eval
3682    `(defadvice invisible-region (around add-mime-edit-invisible (start end)
3683                                         activate)
3684       "Advised by T-gnus Message.
3685 Add the text property `mime-edit-invisible' to an invisible text when
3686 the buffer's major mode is `message-mode'.  The added property will be
3687 used to distinguish whether the invisible text is a MIME part or not."
3688       ,(if (featurep 'xemacs)
3689            '(if (eq ?\n (char-after start))
3690                 (setq start (1+ start)))
3691          '(if (eq ?\n (char-after (1- end)))
3692               (setq end (1- end))))
3693       (setq ad-return-value
3694             (if (eq 'message-mode major-mode)
3695                 (add-text-properties start end
3696                                      '(invisible t mime-edit-invisible t))
3697               (put-text-property start end 'invisible t))))))
3698
3699 (defun message-text-with-property (prop)
3700   "Return a list of all points where the text has PROP."
3701   (let ((points nil)
3702         (point (point-min)))
3703     (save-excursion
3704       (while (< point (point-max))
3705         (when (get-text-property point prop)
3706           (push point points))
3707         (incf point)))
3708     (nreverse points)))
3709
3710 (defun message-fix-before-sending ()
3711   "Do various things to make the message nice before sending it."
3712   ;; Make sure there's a newline at the end of the message.
3713   (widen)
3714   (goto-char (point-max))
3715   (unless (bolp)
3716     (insert "\n"))
3717   ;; Delete all invisible text except for the mime parts which might
3718   ;; be inserted by the MIME-Edit.
3719   (message-check 'invisible-text
3720     (let (from
3721           (to (point-min))
3722           mime-from mime-to hidden-start)
3723       (while (setq from (text-property-any to (point-max) 'invisible t))
3724         (setq to (or (text-property-not-all from (point-max) 'invisible t)
3725                      (point-max))
3726               mime-to from)
3727         (while (setq mime-from (text-property-any mime-to to
3728                                                   'mime-edit-invisible t))
3729           (when (> mime-from mime-to)
3730             (setq hidden-start (or hidden-start mime-to))
3731             (add-text-properties mime-to mime-from
3732                                  '(invisible nil face highlight
3733                                              font-lock-face highlight)))
3734           (setq mime-to (or (text-property-not-all mime-from to
3735                                                    'mime-edit-invisible t)
3736                             to)))
3737         (when (< mime-to to)
3738           (setq hidden-start (or hidden-start mime-to))
3739           (add-text-properties mime-to to
3740                                '(invisible nil face highlight
3741                                            font-lock-face highlight))))
3742       (when hidden-start
3743         (goto-char hidden-start)
3744         (set-window-start (selected-window) (gnus-point-at-bol))
3745         (unless (yes-or-no-p
3746                  "Invisible text found and made visible; continue posting? ")
3747           (error "Invisible text found and made visible")))))
3748   (message-check 'illegible-text
3749     (let ((mm-7bit-chars "\x20-\x7f\r\n\t\x7\x8\xb\xc\x1f\x1b")
3750           found choice)
3751       (message-goto-body)
3752       (skip-chars-forward mm-7bit-chars)
3753       (while (not (eobp))
3754         (when (let ((char (char-after)))
3755                 (or (< (mm-char-int char) 128)
3756                     (and (mm-multibyte-p)
3757                          (memq (char-charset char)
3758                                '(eight-bit-control eight-bit-graphic
3759                                                    control-1)))))
3760           (add-text-properties (point) (1+ (point))
3761                                '(font-lock-face highlight face highlight))
3762           (setq found t))
3763         (forward-char)
3764         (skip-chars-forward mm-7bit-chars))
3765       (when found
3766         (setq choice
3767               (gnus-multiple-choice
3768                "Illegible text found.  Continue posting?"
3769                '((?d "Remove and continue posting")
3770                  (?r "Replace with dots and continue posting")
3771                  (?i "Ignore and continue posting")
3772                  (?e "Continue editing"))))
3773         (if (eq choice ?e)
3774           (error "Illegible text found"))
3775         (message-goto-body)
3776         (skip-chars-forward mm-7bit-chars)
3777         (while (not (eobp))
3778           (when (let ((char (char-after)))
3779                   (or (< (mm-char-int char) 128)
3780                       (and (mm-multibyte-p)
3781                            (memq (char-charset char)
3782                                  '(eight-bit-control eight-bit-graphic
3783                                                      control-1)))))
3784             (if (eq choice ?i)
3785                 (remove-text-properties (point) (1+ (point))
3786                                         '(font-lock-face highlight face highlight))
3787               (delete-char 1)
3788               (when (eq choice ?r)
3789                 (insert "."))))
3790           (forward-char)
3791           (skip-chars-forward mm-7bit-chars))))))
3792
3793 (defun message-add-action (action &rest types)
3794   "Add ACTION to be performed when doing an exit of type TYPES."
3795   (while types
3796     (add-to-list (intern (format "message-%s-actions" (pop types)))
3797                  action)))
3798
3799 (defun message-delete-action (action &rest types)
3800   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3801   (let (var)
3802     (while types
3803       (set (setq var (intern (format "message-%s-actions" (pop types))))
3804            (delq action (symbol-value var))))))
3805
3806 (defun message-do-actions (actions)
3807   "Perform all actions in ACTIONS."
3808   ;; Now perform actions on successful sending.
3809   (while actions
3810     (ignore-errors
3811       (cond
3812        ;; A simple function.
3813        ((message-functionp (car actions))
3814         (funcall (car actions)))
3815        ;; Something to be evaled.
3816        (t
3817         (eval (car actions)))))
3818     (pop actions)))
3819
3820 (defsubst message-maybe-split-and-send-mail ()
3821   "Split a message if necessary, and send it via mail.
3822 Returns nil if sending succeeded, returns any string if sending failed.
3823 This sub function is for exclusive use of `message-send-mail'."
3824   (let ((mime-edit-split-ignored-field-regexp
3825          mime-edit-split-ignored-field-regexp)
3826         (case-fold-search t)
3827         failure)
3828     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3829       (setq mime-edit-split-ignored-field-regexp
3830             (concat (substring mime-edit-split-ignored-field-regexp
3831                                0 (match-beginning 0))
3832                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3833                     "_so_don't_rape_it!"
3834                     (substring mime-edit-split-ignored-field-regexp
3835                                (match-end 0)))))
3836     (setq failure
3837           (or
3838            (catch 'message-sending-mail-failure
3839              (mime-edit-maybe-split-and-send
3840               (function
3841                (lambda ()
3842                  (interactive)
3843                  (save-restriction
3844                    (std11-narrow-to-header mail-header-separator)
3845                    (goto-char (point-min))
3846                    (when (re-search-forward "^Message-ID:" nil t)
3847                      (delete-region (match-end 0) (std11-field-end))
3848                      (insert " " (message-make-message-id))))
3849                  (condition-case err
3850                      (funcall (or message-send-mail-real-function
3851                                   message-send-mail-function))
3852                    (error
3853                     (throw 'message-sending-mail-failure err))))))
3854              nil)
3855            (condition-case err
3856                (progn
3857                  (funcall (or message-send-mail-real-function
3858                               message-send-mail-function))
3859                  nil)
3860              (error err))))
3861     (when failure
3862       (if (eq 'error (car failure))
3863           (cadr failure)
3864         (prin1-to-string failure)))))
3865
3866 (defun message-send-mail-partially ()
3867   "Send mail as message/partial."
3868   ;; replace the header delimiter with a blank line
3869   (goto-char (point-min))
3870   (re-search-forward
3871    (concat "^" (regexp-quote mail-header-separator) "\n"))
3872   (replace-match "\n")
3873   (run-hooks 'message-send-mail-hook)
3874   (let ((p (goto-char (point-min)))
3875         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3876         (curbuf (current-buffer))
3877         (id (message-make-message-id)) (n 1)
3878         plist total  header required-mail-headers)
3879     (while (not (eobp))
3880       (if (< (point-max) (+ p message-send-mail-partially-limit))
3881           (goto-char (point-max))
3882         (goto-char (+ p message-send-mail-partially-limit))
3883         (beginning-of-line)
3884         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3885       (push p plist)
3886       (setq p (point)))
3887     (setq total (length plist))
3888     (push (point-max) plist)
3889     (setq plist (nreverse plist))
3890     (unwind-protect
3891         (save-excursion
3892           (setq p (pop plist))
3893           (while plist
3894             (set-buffer curbuf)
3895             (copy-to-buffer tembuf p (car plist))
3896             (set-buffer tembuf)
3897             (goto-char (point-min))
3898             (if header
3899                 (progn
3900                   (goto-char (point-min))
3901                   (narrow-to-region (point) (point))
3902                   (insert header))
3903               (message-goto-eoh)
3904               (setq header (buffer-substring (point-min) (point)))
3905               (goto-char (point-min))
3906               (narrow-to-region (point) (point))
3907               (insert header)
3908               (message-remove-header "Mime-Version")
3909               (message-remove-header "Content-Type")
3910               (message-remove-header "Content-Transfer-Encoding")
3911               (message-remove-header "Message-ID")
3912               (message-remove-header "Lines")
3913               (goto-char (point-max))
3914               (insert "Mime-Version: 1.0\n")
3915               (setq header (buffer-string)))
3916             (goto-char (point-max))
3917             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3918                             id n total))
3919             (forward-char -1)
3920             (let ((mail-header-separator ""))
3921               (when (memq 'Message-ID message-required-mail-headers)
3922                 (insert "Message-ID: " (message-make-message-id) "\n"))
3923               (when (memq 'Lines message-required-mail-headers)
3924                 (insert "Lines: " (message-make-lines) "\n"))
3925               (message-goto-subject)
3926               (end-of-line)
3927               (insert (format " (%d/%d)" n total))
3928               (widen)
3929               (mm-with-unibyte-current-buffer
3930                 (funcall (or message-send-mail-real-function
3931                              message-send-mail-function))))
3932             (setq n (+ n 1))
3933             (setq p (pop plist))
3934             (erase-buffer)))
3935       (kill-buffer tembuf))))
3936
3937 (defun message-send-mail (&optional arg)
3938   (require 'mail-utils)
3939   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3940          (case-fold-search nil)
3941          (news (message-news-p))
3942          (message-this-is-mail t)
3943          (headers message-required-mail-headers)
3944          failure)
3945     (save-restriction
3946       (message-narrow-to-headers)
3947       ;; Generate the Mail-Followup-To header if the header is not there...
3948       (if (and (message-subscribed-p)
3949                (not (mail-fetch-field "mail-followup-to")))
3950           (setq headers
3951                 (cons
3952                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
3953                  message-required-mail-headers))
3954         ;; otherwise, delete the MFT header if the field is empty
3955         (when (equal "" (mail-fetch-field "mail-followup-to"))
3956           (message-remove-header "^Mail-Followup-To:")))
3957       ;; Insert some headers.
3958       (let ((message-deletable-headers
3959              (if news nil message-deletable-headers)))
3960         (message-generate-headers headers))
3961       ;; Let the user do all of the above.
3962       (run-hooks 'message-header-hook))
3963     (if (not (message-check-mail-syntax))
3964         (progn
3965           (message "")
3966           nil)
3967       (unwind-protect
3968           (save-excursion
3969             (set-buffer tembuf)
3970             (erase-buffer)
3971             ;; ;; Avoid copying text props (except hard newlines).
3972             ;; T-gnus change: copy all text props from the editing buffer
3973             ;; into the encoding buffer.
3974             (insert-buffer-substring message-encoding-buffer)
3975             ;; Remove some headers.
3976             (save-restriction
3977               (message-narrow-to-headers)
3978 ;; We Semi-gnus people have no use for it.
3979 ;;            ;; We (re)generate the Lines header.
3980 ;;            (when (memq 'Lines message-required-mail-headers)
3981 ;;              (message-generate-headers '(Lines)))
3982               (message-remove-header message-ignored-mail-headers t))
3983             (goto-char (point-max))
3984             ;; require one newline at the end.
3985             (or (= (preceding-char) ?\n)
3986                 (insert ?\n))
3987             (message-cleanup-headers)
3988             (when
3989                 (save-restriction
3990                   (message-narrow-to-headers)
3991                   (and news
3992                        (or (message-fetch-field "cc")
3993                            (message-fetch-field "to"))
3994                        (let ((ct (mime-read-Content-Type)))
3995                          (or (not ct)
3996                              (and (eq 'text (cdr (assq 'type ct)))
3997                                   (eq 'plain (cdr (assq 'subtype ct))))))))
3998               (message-insert-courtesy-copy))
3999             (setq failure (message-maybe-split-and-send-mail)))
4000         (kill-buffer tembuf))
4001       (set-buffer message-edit-buffer)
4002       (if failure
4003           (progn
4004             (message "Couldn't send message via mail: %s" failure)
4005             nil)
4006         (push 'mail message-sent-message-via)))))
4007
4008 (defun message-send-mail-with-sendmail ()
4009   "Send off the prepared buffer with sendmail."
4010   (let ((errbuf (if message-interactive
4011                     (message-generate-new-buffer-clone-locals
4012                      " sendmail errors")
4013                   0))
4014         resend-to-addresses delimline)
4015     (unwind-protect
4016         (progn
4017           (let ((case-fold-search t))
4018             (save-restriction
4019               (message-narrow-to-headers)
4020               (setq resend-to-addresses (message-fetch-field "resent-to")))
4021             ;; Change header-delimiter to be what sendmail expects.
4022             (goto-char (point-min))
4023             (re-search-forward
4024              (concat "^" (regexp-quote mail-header-separator) "\n"))
4025             (replace-match "\n")
4026             (backward-char 1)
4027             (setq delimline (point-marker))
4028             (run-hooks 'message-send-mail-hook)
4029             ;; Insert an extra newline if we need it to work around
4030             ;; Sun's bug that swallows newlines.
4031             (goto-char (1+ delimline))
4032             (when (eval message-mailer-swallows-blank-line)
4033               (newline))
4034             (when message-interactive
4035               (save-excursion
4036                 (set-buffer errbuf)
4037                 (erase-buffer))))
4038           (let* ((default-directory "/")
4039                  (cpr (as-binary-process
4040                        (apply
4041                         'call-process-region
4042                         (append
4043                          (list (point-min) (point-max)
4044                                (if (boundp 'sendmail-program)
4045                                    sendmail-program
4046                                  "/usr/lib/sendmail")
4047                                nil errbuf nil "-oi")
4048                          ;; Always specify who from,
4049                          ;; since some systems have broken sendmails.
4050                          ;; But some systems are more broken with -f, so
4051                          ;; we'll let users override this.
4052                          (if (null message-sendmail-f-is-evil)
4053                              (list "-f" (message-sendmail-envelope-from)))
4054                          ;; These mean "report errors by mail"
4055                          ;; and "deliver in background".
4056                          (if (null message-interactive) '("-oem" "-odb"))
4057                          ;; Get the addresses from the message
4058                          ;; unless this is a resend.
4059                          ;; We must not do that for a resend
4060                          ;; because we would find the original addresses.
4061                          ;; For a resend, include the specific addresses.
4062                          (if resend-to-addresses
4063                              (list resend-to-addresses)
4064                            '("-t")))))))
4065             (unless (or (null cpr) (zerop cpr))
4066               (error "Sending...failed with exit value %d" cpr)))
4067           (when message-interactive
4068             (save-excursion
4069               (set-buffer errbuf)
4070               (goto-char (point-min))
4071               (while (re-search-forward "\n\n* *" nil t)
4072                 (replace-match "; "))
4073               (if (not (zerop (buffer-size)))
4074                   (error "Sending...failed to %s"
4075                          (buffer-string))))))
4076       (when (bufferp errbuf)
4077         (kill-buffer errbuf)))))
4078
4079 (defun message-send-mail-with-qmail ()
4080   "Pass the prepared message buffer to qmail-inject.
4081 Refer to the documentation for the variable `message-send-mail-function'
4082 to find out how to use this."
4083   ;; replace the header delimiter with a blank line
4084   (goto-char (point-min))
4085   (re-search-forward
4086    (concat "^" (regexp-quote mail-header-separator) "\n"))
4087   (replace-match "\n")
4088   (backward-char 1)
4089   (run-hooks 'message-send-mail-hook)
4090   ;; send the message
4091   (case
4092       (as-binary-process
4093        (apply
4094         'call-process-region 1 (point-max) message-qmail-inject-program
4095         nil nil nil
4096         ;; qmail-inject's default behaviour is to look for addresses on the
4097         ;; command line; if there're none, it scans the headers.
4098         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4099         ;;
4100         ;; in general, ALL of qmail-inject's defaults are perfect for simply
4101         ;; reading a formatted (i. e., at least a To: or Resent-To header)
4102         ;; message from stdin.
4103         ;;
4104         ;; qmail also has the advantage of not having been raped by
4105         ;; various vendors, so we don't have to allow for that, either --
4106         ;; compare this with message-send-mail-with-sendmail and weep
4107         ;; for sendmail's lost innocence.
4108         ;;
4109         ;; all this is way cool coz it lets us keep the arguments entirely
4110         ;; free for -inject-arguments -- a big win for the user and for us
4111         ;; since we don't have to play that double-guessing game and the user
4112         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4113         (if (functionp message-qmail-inject-args)
4114             (funcall message-qmail-inject-args)
4115           message-qmail-inject-args)))
4116     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4117     ;; we have to look at the retval instead
4118     (0 nil)
4119     (100 (error "qmail-inject reported permanent failure"))
4120     (111 (error "qmail-inject reported transient failure"))
4121     ;; should never happen
4122     (t   (error "qmail-inject reported unknown failure"))))
4123
4124 (defun message-send-mail-with-mh ()
4125   "Send the prepared message buffer with mh."
4126   (let ((mh-previous-window-config nil)
4127         (name (mh-new-draft-name)))
4128     (setq buffer-file-name name)
4129     ;; MH wants to generate these headers itself.
4130     (when message-mh-deletable-headers
4131       (let ((headers message-mh-deletable-headers))
4132         (while headers
4133           (goto-char (point-min))
4134           (and (re-search-forward
4135                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4136                (message-delete-line))
4137           (pop headers))))
4138     (run-hooks 'message-send-mail-hook)
4139     ;; Pass it on to mh.
4140     (mh-send-letter)))
4141
4142 (defun message-send-mail-with-smtp ()
4143   "Send off the prepared buffer with SMTP."
4144   (require 'smtp) ; XXX
4145   (let ((case-fold-search t)
4146         recipients)
4147     (save-restriction
4148       (message-narrow-to-headers)
4149       (setq recipients
4150             ;; XXX: Should be replaced by better one.
4151             (smtp-deduce-address-list (current-buffer)
4152                                       (point-min) (point-max)))
4153       ;; Remove BCC lines.
4154       (message-remove-header "bcc"))
4155     ;; replace the header delimiter with a blank line.
4156     (goto-char (point-min))
4157     (re-search-forward
4158      (concat "^" (regexp-quote mail-header-separator) "\n"))
4159     (replace-match "\n")
4160     (backward-char 1)
4161     (run-hooks 'message-send-mail-hook)
4162     (if recipients
4163         (smtp-send-buffer user-mail-address recipients (current-buffer))
4164       (error "Sending failed; no recipients"))))
4165
4166 (defsubst message-maybe-split-and-send-news (method)
4167   "Split a message if necessary, and send it via news.
4168 Returns nil if sending succeeded, returns t if sending failed.
4169 This sub function is for exclusive use of `message-send-news'."
4170   (let ((mime-edit-split-ignored-field-regexp
4171          mime-edit-split-ignored-field-regexp)
4172         (case-fold-search t))
4173     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4174       (setq mime-edit-split-ignored-field-regexp
4175             (concat (substring mime-edit-split-ignored-field-regexp
4176                                0 (match-beginning 0))
4177                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4178                     "_so_don't_rape_it!"
4179                     (substring mime-edit-split-ignored-field-regexp
4180                                (match-end 0)))))
4181     (or
4182      (catch 'message-sending-news-failure
4183        (mime-edit-maybe-split-and-send
4184         (function
4185          (lambda ()
4186            (interactive)
4187            (save-restriction
4188              (std11-narrow-to-header mail-header-separator)
4189              (goto-char (point-min))
4190              (when (re-search-forward "^Message-ID:" nil t)
4191                (delete-region (match-end 0) (std11-field-end))
4192                (insert " " (message-make-message-id))))
4193            (unless (funcall message-send-news-function method)
4194              (throw 'message-sending-news-failure t)))))
4195        nil)
4196      (not (funcall message-send-news-function method)))))
4197
4198 (defun message-smtpmail-send-it ()
4199   "Send the prepared message buffer with `smtpmail-send-it'.
4200 This only differs from `smtpmail-send-it' that this command evaluates
4201 `message-send-mail-hook' just before sending a message.  It is useful
4202 if your ISP requires the POP-before-SMTP authentication.  See the
4203 documentation for the function `mail-source-touch-pop'."
4204   (run-hooks 'message-send-mail-hook)
4205   (smtpmail-send-it))
4206
4207 (defun message-canlock-generate ()
4208   "Return a string that is non-trival to guess.
4209 Do not use this for anything important, it is cryptographically weak."
4210   (let (sha1-maximum-internal-length)
4211     (sha1 (concat (message-unique-id)
4212                   (format "%x%x%x" (random) (random t) (random))
4213                   (prin1-to-string (recent-keys))
4214                   (prin1-to-string (garbage-collect))))))
4215
4216 (defun message-canlock-password ()
4217   "The password used by message for cancel locks.
4218 This is the value of `canlock-password', if that option is non-nil.
4219 Otherwise, generate and save a value for `canlock-password' first."
4220   (unless canlock-password
4221     (customize-save-variable 'canlock-password (message-canlock-generate))
4222     (setq canlock-password-for-verify canlock-password))
4223   canlock-password)
4224
4225 (defun message-insert-canlock ()
4226   (when message-insert-canlock
4227     (message-canlock-password)
4228     (canlock-insert-header)))
4229
4230 (defun message-send-news (&optional arg)
4231   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4232          (case-fold-search nil)
4233          (method (if (message-functionp message-post-method)
4234                      (funcall message-post-method arg)
4235                    message-post-method))
4236          (newsgroups-field (save-restriction
4237                              (message-narrow-to-headers-or-head)
4238                              (message-fetch-field "Newsgroups")))
4239          (followup-field (save-restriction
4240                            (message-narrow-to-headers-or-head)
4241                            (message-fetch-field "Followup-To")))
4242          ;; BUG: We really need to get the charset for each name in the
4243          ;; Newsgroups and Followup-To lines to allow crossposting
4244          ;; between group namess with incompatible character sets.
4245          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4246          (group-field-charset
4247           (gnus-group-name-charset method newsgroups-field))
4248          (followup-field-charset
4249           (gnus-group-name-charset method (or followup-field "")))
4250          (mime-field-encoding-method-alist
4251           (append (when group-field-charset
4252                     (list (cons "Newsgroups" group-field-charset)))
4253                   (when followup-field-charset
4254                     (list (cons "Followup-To" followup-field-charset)))
4255                   mime-field-encoding-method-alist))
4256          (message-syntax-checks
4257           (if (and arg
4258                    (listp message-syntax-checks))
4259               (cons '(existing-newsgroups . disabled)
4260                     message-syntax-checks)
4261             message-syntax-checks))
4262          (message-this-is-news t)
4263          result)
4264     (save-restriction
4265       (message-narrow-to-headers)
4266       ;; Insert some headers.
4267       (message-generate-headers message-required-news-headers)
4268       (message-insert-canlock)
4269       ;; Let the user do all of the above.
4270       (run-hooks 'message-header-hook))
4271     ;; Note: This check will be disabled by the ".*" default value for
4272     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4273     (when (and group-field-charset
4274                (listp message-syntax-checks))
4275       (setq message-syntax-checks
4276             (cons '(valid-newsgroups . disabled)
4277                   message-syntax-checks)))
4278     (message-cleanup-headers)
4279     (if (not (let ((message-post-method method))
4280                (message-check-news-syntax)))
4281         nil
4282       (unwind-protect
4283           (save-excursion
4284             (set-buffer tembuf)
4285             (buffer-disable-undo)
4286             (erase-buffer)
4287             (insert-buffer-substring message-encoding-buffer)
4288             ;; Remove some headers.
4289             (save-restriction
4290               (message-narrow-to-headers)
4291 ;; We Semi-gnus people have no use for it.
4292 ;;            ;; We (re)generate the Lines header.
4293 ;;            (when (memq 'Lines message-required-mail-headers)
4294 ;;              (message-generate-headers '(Lines)))
4295               ;; Remove some headers.
4296               (message-remove-header message-ignored-news-headers t))
4297             (goto-char (point-max))
4298             ;; require one newline at the end.
4299             (or (= (preceding-char) ?\n)
4300                 (insert ?\n))
4301             (setq result (message-maybe-split-and-send-news method)))
4302         (kill-buffer tembuf))
4303       (set-buffer message-edit-buffer)
4304       (if result
4305           (progn
4306             (message "Couldn't send message via news: %s"
4307                      (nnheader-get-report (car method)))
4308             nil)
4309         (push 'news message-sent-message-via)))))
4310
4311 ;; 1997-09-29 by MORIOKA Tomohiko
4312 (defun message-send-news-with-gnus (method)
4313   (let ((case-fold-search t))
4314     ;; Remove the delimiter.
4315     (goto-char (point-min))
4316     (re-search-forward
4317      (concat "^" (regexp-quote mail-header-separator) "\n"))
4318     (replace-match "\n")
4319     (backward-char 1)
4320     (run-hooks 'message-send-news-hook)
4321     (gnus-open-server method)
4322     (message "Sending news via %s..." (gnus-server-string method))
4323     (gnus-request-post method)
4324     ))
4325
4326 ;;;
4327 ;;; Header generation & syntax checking.
4328 ;;;
4329
4330 (defun message-check-element (type)
4331   "Return non-nil if this TYPE is not to be checked."
4332   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4333       t
4334     (let ((able (assq type message-syntax-checks)))
4335       (and (consp able)
4336            (eq (cdr able) 'disabled)))))
4337
4338 (defun message-check-news-syntax ()
4339   "Check the syntax of the message."
4340   (save-excursion
4341     (save-restriction
4342       (widen)
4343       (and
4344        ;; We narrow to the headers and check them first.
4345        (save-excursion
4346          (save-restriction
4347            (message-narrow-to-headers)
4348            (message-check-news-header-syntax)))
4349        ;; Check the body.
4350        (save-excursion
4351          (set-buffer message-edit-buffer)
4352          (message-check-news-body-syntax))))))
4353
4354 (defun message-check-news-header-syntax ()
4355   (and
4356    ;; Check Newsgroups header.
4357    (message-check 'newsgroups
4358      (let ((group (message-fetch-field "newsgroups")))
4359        (or
4360         (and group
4361              (not (string-match "\\`[ \t]*\\'" group)))
4362         (ignore
4363          (message
4364           "The newsgroups field is empty or missing.  Posting is denied.")))))
4365    ;; Check the Subject header.
4366    (message-check 'subject
4367      (let* ((case-fold-search t)
4368             (subject (message-fetch-field "subject")))
4369        (or
4370         (and subject
4371              (not (string-match "\\`[ \t]*\\'" subject)))
4372         (ignore
4373          (message
4374           "The subject field is empty or missing.  Posting is denied.")))))
4375    ;; Check for commands in Subject.
4376    (message-check 'subject-cmsg
4377      (if (string-match "^cmsg " (message-fetch-field "subject"))
4378          (y-or-n-p
4379           "The control code \"cmsg\" is in the subject.  Really post? ")
4380        t))
4381    ;; Check long header lines.
4382    (message-check 'long-header-lines
4383      (let ((start (point))
4384            (header nil)
4385            (length 0)
4386            found)
4387        (while (and (not found)
4388                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4389          (if (> (- (point) (match-beginning 0)) 998)
4390              (setq found t
4391                    length (- (point) (match-beginning 0)))
4392            (setq header (match-string-no-properties 1)))
4393          (setq start (match-beginning 0))
4394          (forward-line 1))
4395        (if found
4396            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4397                              header length))
4398          t)))
4399    ;; Check for multiple identical headers.
4400    (message-check 'multiple-headers
4401      (let (found)
4402        (while (and (not found)
4403                    (re-search-forward "^[^ \t:]+: " nil t))
4404          (save-excursion
4405            (or (re-search-forward
4406                 (concat "^"
4407                         (regexp-quote
4408                          (setq found
4409                                (buffer-substring
4410                                 (match-beginning 0) (- (match-end 0) 2))))
4411                         ":")
4412                 nil t)
4413                (setq found nil))))
4414        (if found
4415            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4416          t)))
4417    ;; Check for Version and Sendsys.
4418    (message-check 'sendsys
4419      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4420          (y-or-n-p
4421           (format "The article contains a %s command.  Really post? "
4422                   (buffer-substring (match-beginning 0)
4423                                     (1- (match-end 0)))))
4424        t))
4425    ;; See whether we can shorten Followup-To.
4426    (message-check 'shorten-followup-to
4427      (let ((newsgroups (message-fetch-field "newsgroups"))
4428            (followup-to (message-fetch-field "followup-to"))
4429            to)
4430        (when (and newsgroups
4431                   (string-match "," newsgroups)
4432                   (not followup-to)
4433                   (not
4434                    (zerop
4435                     (length
4436                      (setq to (completing-read
4437                                "Followups to (default: no Followup-To header) "
4438                                (mapcar (lambda (g) (list g))
4439                                        (cons "poster"
4440                                              (message-tokenize-header
4441                                               newsgroups)))))))))
4442          (goto-char (point-min))
4443          (insert "Followup-To: " to "\n"))
4444        t))
4445    ;; Check "Shoot me".
4446    (message-check 'shoot
4447      (if (re-search-forward
4448           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
4449          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4450        t))
4451    ;; Check for Approved.
4452    (message-check 'approved
4453      (if (re-search-forward "^Approved:" nil t)
4454          (y-or-n-p "The article contains an Approved header.  Really post? ")
4455        t))
4456    ;; Check the Message-ID header.
4457    (message-check 'message-id
4458      (let* ((case-fold-search t)
4459             (message-id (message-fetch-field "message-id" t)))
4460        (or (not message-id)
4461            ;; Is there an @ in the ID?
4462            (and (string-match "@" message-id)
4463                 ;; Is there a dot in the ID?
4464                 (string-match "@[^.]*\\." message-id)
4465                 ;; Does the ID end with a dot?
4466                 (not (string-match "\\.>" message-id)))
4467            (y-or-n-p
4468             (format "The Message-ID looks strange: \"%s\".  Really post? "
4469                     message-id)))))
4470    ;; Check the Newsgroups & Followup-To headers.
4471    (message-check 'existing-newsgroups
4472      (let* ((case-fold-search t)
4473             (newsgroups (message-fetch-field "newsgroups"))
4474             (followup-to (message-fetch-field "followup-to"))
4475             (groups (message-tokenize-header
4476                      (if followup-to
4477                          (concat newsgroups "," followup-to)
4478                        newsgroups)))
4479             (post-method (if (message-functionp message-post-method)
4480                              (funcall message-post-method)
4481                            message-post-method))
4482             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4483             ;; would probably involve a new nnoo function.
4484             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4485             (method (if (and (consp post-method)
4486                              (eq (car post-method) 'nnvirtual)
4487                              gnus-message-group-art)
4488                         (let ((group (car (nnvirtual-find-group-art
4489                                            (car gnus-message-group-art)
4490                                            (cdr gnus-message-group-art)))))
4491                           (gnus-find-method-for-group group))
4492                       post-method))
4493             (known-groups
4494              (mapcar (lambda (n)
4495                        (gnus-group-name-decode
4496                         (gnus-group-real-name n)
4497                         (gnus-group-name-charset method n)))
4498                      (gnus-groups-from-server method)))
4499             errors)
4500        (while groups
4501          (unless (or (equal (car groups) "poster")
4502                      (member (car groups) known-groups))
4503            (push (car groups) errors))
4504          (pop groups))
4505        (cond
4506         ;; Gnus is not running.
4507         ((or (not (and (boundp 'gnus-active-hashtb)
4508                        gnus-active-hashtb))
4509              (not (boundp 'gnus-read-active-file)))
4510          t)
4511         ;; We don't have all the group names.
4512         ((and (or (not gnus-read-active-file)
4513                   (eq gnus-read-active-file 'some))
4514               errors)
4515          (y-or-n-p
4516           (format
4517            "Really post to %s possibly unknown group%s: %s? "
4518            (if (= (length errors) 1) "this" "these")
4519            (if (= (length errors) 1) "" "s")
4520            (mapconcat 'identity errors ", "))))
4521         ;; There were no errors.
4522         ((not errors)
4523          t)
4524         ;; There are unknown groups.
4525         (t
4526          (y-or-n-p
4527           (format
4528            "Really post to %s unknown group%s: %s? "
4529            (if (= (length errors) 1) "this" "these")
4530            (if (= (length errors) 1) "" "s")
4531            (mapconcat 'identity errors ", ")))))))
4532    ;; Check continuation headers.
4533    (message-check 'continuation-headers
4534      (goto-char (point-min))
4535      (let ((do-posting t))
4536        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4537          (if (y-or-n-p "Fix continuation lines? ")
4538              (progn
4539                (goto-char (match-beginning 0))
4540                (insert " "))
4541            (unless (y-or-n-p "Send anyway? ")
4542              (setq do-posting nil))))
4543        do-posting))
4544    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4545    (message-check 'valid-newsgroups
4546      (let ((case-fold-search t)
4547            (headers '("Newsgroups" "Followup-To"))
4548            header error)
4549        (while (and headers (not error))
4550          (when (setq header (mail-fetch-field (car headers)))
4551            (if (or
4552                 (not
4553                  (string-match
4554                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4555                   header))
4556                 (memq
4557                  nil (mapcar
4558                       (lambda (g)
4559                         (not (string-match "\\.\\'\\|\\.\\." g)))
4560                       (message-tokenize-header header ","))))
4561                (setq error t)))
4562          (unless error
4563            (pop headers)))
4564        (if (not error)
4565            t
4566          (y-or-n-p
4567           (format "The %s header looks odd: \"%s\".  Really post? "
4568                   (car headers) header)))))
4569    (message-check 'repeated-newsgroups
4570      (let ((case-fold-search t)
4571            (headers '("Newsgroups" "Followup-To"))
4572            header error groups group)
4573        (while (and headers
4574                    (not error))
4575          (when (setq header (mail-fetch-field (pop headers)))
4576            (setq groups (message-tokenize-header header ","))
4577            (while (setq group (pop groups))
4578              (when (member group groups)
4579                (setq error group
4580                      groups nil)))))
4581        (if (not error)
4582            t
4583          (y-or-n-p
4584           (format "Group %s is repeated in headers.  Really post? " error)))))
4585    ;; Check the From header.
4586    (message-check 'from
4587      (let* ((case-fold-search t)
4588             (from (message-fetch-field "from"))
4589             ad)
4590        (cond
4591         ((not from)
4592          (message "There is no From line.  Posting is denied.")
4593          nil)
4594         ((or (not (string-match
4595                    "@[^\\.]*\\."
4596                    (setq ad (nth 1 (mail-extract-address-components
4597                                     from))))) ;larsi@ifi
4598              (string-match "\\.\\." ad) ;larsi@ifi..uio
4599              (string-match "@\\." ad)   ;larsi@.ifi.uio
4600              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4601              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4602              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4603          (message
4604           "Denied posting -- the From looks strange: \"%s\"." from)
4605          nil)
4606         ((let ((addresses (rfc822-addresses from)))
4607            (while (and addresses
4608                        (not (eq (string-to-char (car addresses)) ?\()))
4609              (setq addresses (cdr addresses)))
4610            addresses)
4611          (message
4612           "Denied posting -- bad From address: \"%s\"." from)
4613          nil)
4614         (t t))))
4615    ;; Check the Reply-To header.
4616    (message-check 'reply-to
4617      (let* ((case-fold-search t)
4618             (reply-to (message-fetch-field "reply-to"))
4619             ad)
4620        (cond
4621         ((not reply-to)
4622          t)
4623         ((string-match "," reply-to)
4624          (y-or-n-p
4625           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4626                   reply-to)))
4627         ((or (not (string-match
4628                    "@[^\\.]*\\."
4629                    (setq ad (nth 1 (mail-extract-address-components
4630                                     reply-to))))) ;larsi@ifi
4631              (string-match "\\.\\." ad) ;larsi@ifi..uio
4632              (string-match "@\\." ad)   ;larsi@.ifi.uio
4633              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4634              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4635              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4636          (y-or-n-p
4637           (format
4638            "The Reply-To looks strange: \"%s\". Really post? "
4639            reply-to)))
4640         (t t))))))
4641
4642 (defun message-check-news-body-syntax ()
4643   (and
4644    ;; Check for long lines.
4645    (message-check 'long-lines
4646      (goto-char (point-min))
4647      (re-search-forward
4648       (concat "^" (regexp-quote mail-header-separator) "$"))
4649      (forward-line 1)
4650      (while (and
4651              (or (looking-at
4652                   mime-edit-tag-regexp)
4653                  (let ((p (point)))
4654                    (end-of-line)
4655                    (< (- (point) p) 80)))
4656              (zerop (forward-line 1))))
4657      (or (bolp)
4658          (eobp)
4659          (y-or-n-p
4660           "You have lines longer than 79 characters.  Really post? ")))
4661    ;; Check whether the article is empty.
4662    (message-check 'empty
4663      (goto-char (point-min))
4664      (re-search-forward
4665       (concat "^" (regexp-quote mail-header-separator) "$"))
4666      (forward-line 1)
4667      (let ((b (point)))
4668        (goto-char (point-max))
4669        (re-search-backward message-signature-separator nil t)
4670        (beginning-of-line)
4671        (or (re-search-backward "[^ \n\t]" b t)
4672            (if (message-gnksa-enable-p 'empty-article)
4673                (y-or-n-p "Empty article.  Really post? ")
4674              (message "Denied posting -- Empty article.")
4675              nil))))
4676    ;; Check for control characters.
4677    (message-check 'control-chars
4678      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4679          (y-or-n-p
4680           "The article contains control characters.  Really post? ")
4681        t))
4682    ;; Check 8bit characters.
4683    (message-check '8bit
4684      (message-check-8bit))
4685    ;; Check excessive size.
4686    (message-check 'size
4687      (if (> (buffer-size) 60000)
4688          (y-or-n-p
4689           (format "The article is %d octets long.  Really post? "
4690                   (buffer-size)))
4691        t))
4692    ;; Check whether any new text has been added.
4693    (message-check 'new-text
4694      (or
4695       (not message-checksum)
4696       (not (eq (message-checksum) message-checksum))
4697       (if (message-gnksa-enable-p 'quoted-text-only)
4698           (y-or-n-p
4699            "It looks like no new text has been added.  Really post? ")
4700         (message "Denied posting -- no new text has been added.")
4701         nil)))
4702    ;; Check the length of the signature.
4703    (message-check 'signature
4704      (goto-char (point-max))
4705      (if (> (count-lines (point) (point-max)) 5)
4706          (y-or-n-p
4707           (format
4708            "Your .sig is %d lines; it should be max 4.  Really post? "
4709            (1- (count-lines (point) (point-max)))))
4710        t))
4711    ;; Ensure that text follows last quoted portion.
4712    (message-check 'quoting-style
4713      (goto-char (point-max))
4714      (let ((no-problem t))
4715        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4716          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4717        (if no-problem
4718            t
4719          (if (message-gnksa-enable-p 'quoted-text-only)
4720              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4721            ;; Ensure that
4722            (goto-char (point-min))
4723            (re-search-forward
4724             (concat "^" (regexp-quote mail-header-separator) "$"))
4725            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4726                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4727              (message "Denied posting -- only quoted text.")
4728              nil)))))))
4729
4730 (defun message-check-mail-syntax ()
4731   "Check the syntax of the message."
4732   (save-excursion
4733     (save-restriction
4734       (widen)
4735       (and
4736        ;; We narrow to the headers and check them first.
4737        (save-excursion
4738          (save-restriction
4739            (message-narrow-to-headers)
4740            (message-check-mail-header-syntax)))
4741        ;; Check the body.
4742        (save-excursion
4743          (set-buffer message-edit-buffer)
4744          (message-check-mail-body-syntax))))))
4745
4746 (defun message-check-mail-header-syntax ()
4747   t)
4748
4749 (defun message-check-mail-body-syntax ()
4750   (and
4751    ;; Check 8bit characters.
4752    (message-check '8bit
4753      (message-check-8bit)
4754      )))
4755
4756 (defun message-check-8bit ()
4757   "Check the article contains 8bit characters."
4758   (save-excursion
4759     (set-buffer message-encoding-buffer)
4760     (message-narrow-to-headers)
4761     (let* ((case-fold-search t)
4762            (field-value (message-fetch-field "content-transfer-encoding")))
4763       (if (and field-value
4764                (member (downcase field-value) message-8bit-encoding-list))
4765           t
4766         (widen)
4767         (set-buffer (get-buffer-create " message syntax"))
4768         (erase-buffer)
4769         (goto-char (point-min))
4770         (set-buffer-multibyte nil)
4771         (insert-buffer-substring message-encoding-buffer)
4772         (goto-char (point-min))
4773         (if (re-search-forward "[^\x00-\x7f]" nil t)
4774             (y-or-n-p
4775              "The article contains 8bit characters.  Really post? ")
4776           t)))))
4777
4778 (defun message-checksum ()
4779   "Return a \"checksum\" for the current buffer."
4780   (let ((sum 0))
4781     (save-excursion
4782       (goto-char (point-min))
4783       (re-search-forward
4784        (concat "^" (regexp-quote mail-header-separator) "$"))
4785       (while (not (eobp))
4786         (when (not (looking-at "[ \t\n]"))
4787           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4788                             (char-after))))
4789         (forward-char 1)))
4790     sum))
4791
4792 (defun message-do-fcc ()
4793   "Process Fcc headers in the current buffer."
4794   (let ((case-fold-search t)
4795         (coding-system-for-write 'raw-text)
4796         (output-coding-system 'raw-text)
4797         list file
4798         (mml-externalize-attachments message-fcc-externalize-attachments))
4799     (save-excursion
4800       (save-restriction
4801         (message-narrow-to-headers)
4802         (setq file (message-fetch-field "fcc" t)))
4803       (when file
4804         (set-buffer (get-buffer-create " *message temp*"))
4805         (erase-buffer)
4806         (insert-buffer-substring message-encoding-buffer)
4807         (save-restriction
4808           (message-narrow-to-headers)
4809           (while (setq file (message-fetch-field "fcc"))
4810             (push file list)
4811             (message-remove-header "fcc" nil t)))
4812         (goto-char (point-min))
4813         (when (re-search-forward
4814                (concat "^" (regexp-quote mail-header-separator) "$")
4815                nil t)
4816           (replace-match "" t t))
4817         ;; Process FCC operations.
4818         (while list
4819           (setq file (pop list))
4820           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4821               ;; Pipe the article to the program in question.
4822               (call-process-region (point-min) (point-max) shell-file-name
4823                                    nil nil nil shell-command-switch
4824                                    (match-string 1 file))
4825             ;; Save the article.
4826             (setq file (expand-file-name file))
4827             (unless (file-exists-p (file-name-directory file))
4828               (make-directory (file-name-directory file) t))
4829             (if (and message-fcc-handler-function
4830                      (not (eq message-fcc-handler-function 'rmail-output)))
4831                 (funcall message-fcc-handler-function file)
4832               (if (and (file-readable-p file) (mail-file-babyl-p file))
4833                   (rmail-output file 1 nil t)
4834                 (let ((mail-use-rfc822 t))
4835                   (rmail-output file 1 t t))))))
4836         (kill-buffer (current-buffer))))))
4837
4838 (defun message-output (filename)
4839   "Append this article to Unix/babyl mail file FILENAME."
4840   (if (and (file-readable-p filename)
4841            (mail-file-babyl-p filename))
4842       (gnus-output-to-rmail filename t)
4843     (gnus-output-to-mail filename t)))
4844
4845 (defun message-cleanup-headers ()
4846   "Do various automatic cleanups of the headers."
4847   ;; Remove empty lines in the header.
4848   (save-restriction
4849     (message-narrow-to-headers)
4850     ;; Remove blank lines.
4851     (while (re-search-forward "^[ \t]*\n" nil t)
4852       (replace-match "" t t))
4853
4854     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4855     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4856     ;; embedded line breaks.
4857     (goto-char (point-min))
4858     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4859       (save-restriction
4860         (narrow-to-region
4861          (point)
4862          (if (re-search-forward "^[^ \t]" nil t)
4863              (match-beginning 0)
4864            (forward-line 1)
4865            (point)))
4866         (goto-char (point-min))
4867         (while (re-search-forward "\n[ \t]+" nil t)
4868           (replace-match " " t t))      ;No line breaks (too confusing)
4869         (goto-char (point-min))
4870         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4871           (replace-match "," t t))
4872         (goto-char (point-min))
4873         ;; Remove trailing commas.
4874         (when (re-search-forward ",+$" nil t)
4875           (replace-match "" t t))))))
4876
4877 (defun message-make-date (&optional now)
4878   "Make a valid data header.
4879 If NOW, use that time instead."
4880   (let* ((now (or now (current-time)))
4881          (zone (nth 8 (decode-time now)))
4882          (sign "+"))
4883     (when (< zone 0)
4884       (setq sign "-")
4885       (setq zone (- zone)))
4886     (concat
4887      ;; The day name of the %a spec is locale-specific.  Pfff.
4888      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4889                                              parse-time-weekdays))))
4890      (format-time-string "%d" now)
4891      ;; The month name of the %b spec is locale-specific.  Pfff.
4892      (format " %s "
4893              (capitalize (car (rassoc (nth 4 (decode-time now))
4894                                       parse-time-months))))
4895      (format-time-string "%Y %H:%M:%S " now)
4896      ;; We do all of this because XEmacs doesn't have the %z spec.
4897      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4898
4899 (defun message-make-followup-subject (subject)
4900   "Make a followup Subject."
4901   (cond
4902    ((and (eq message-use-subject-re 'guess)
4903          (string-match message-subject-encoded-re-regexp subject))
4904     subject)
4905    (message-use-subject-re
4906     (concat "Re: " (message-strip-subject-re subject)))
4907    (t subject)))
4908
4909 (defun message-make-message-id ()
4910   "Make a unique Message-ID."
4911   (concat "<" (message-unique-id)
4912           (let ((psubject (save-excursion (message-fetch-field "subject")))
4913                 (psupersedes
4914                  (save-excursion (message-fetch-field "supersedes"))))
4915             (if (or
4916                  (and message-reply-headers
4917                       (mail-header-references message-reply-headers)
4918                       (mail-header-subject message-reply-headers)
4919                       psubject
4920                       (not (string=
4921                             (message-strip-subject-re
4922                              (mail-header-subject message-reply-headers))
4923                             (message-strip-subject-re psubject))))
4924                  (and psupersedes
4925                       (string-match "_-_@" psupersedes)))
4926                 "_-_" ""))
4927           "@" (message-make-fqdn) ">"))
4928
4929 (defvar message-unique-id-char nil)
4930
4931 ;; If you ever change this function, make sure the new version
4932 ;; cannot generate IDs that the old version could.
4933 ;; You might for example insert a "." somewhere (not next to another dot
4934 ;; or string boundary), or modify the "fsf" string.
4935 (defun message-unique-id ()
4936   ;; Don't use microseconds from (current-time), they may be unsupported.
4937   ;; Instead we use this randomly inited counter.
4938   (setq message-unique-id-char
4939         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4940            ;; (current-time) returns 16-bit ints,
4941            ;; and 2^16*25 just fits into 4 digits i base 36.
4942            (* 25 25)))
4943   (let ((tm (current-time)))
4944     (concat
4945      (if (memq system-type '(ms-dos emx vax-vms))
4946          (let ((user (downcase (user-login-name))))
4947            (while (string-match "[^a-z0-9_]" user)
4948              (aset user (match-beginning 0) ?_))
4949            user)
4950        (message-number-base36 (user-uid) -1))
4951      (message-number-base36 (+ (car tm)
4952                                (lsh (% message-unique-id-char 25) 16)) 4)
4953      (message-number-base36 (+ (nth 1 tm)
4954                                (lsh (/ message-unique-id-char 25) 16)) 4)
4955      ;; Append the newsreader name, because while the generated
4956      ;; ID is unique to this newsreader, other newsreaders might
4957      ;; otherwise generate the same ID via another algorithm.
4958      ".fsf")))
4959
4960 (defun message-number-base36 (num len)
4961   (if (if (< len 0)
4962           (<= num 0)
4963         (= len 0))
4964       ""
4965     (concat (message-number-base36 (/ num 36) (1- len))
4966             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4967                                   (% num 36))))))
4968
4969 (defun message-make-organization ()
4970   "Make an Organization header."
4971   (let* ((organization
4972           (when message-user-organization
4973             (if (message-functionp message-user-organization)
4974                 (funcall message-user-organization)
4975               message-user-organization))))
4976     (save-excursion
4977       (message-set-work-buffer)
4978       (cond ((stringp organization)
4979              (insert organization))
4980             ((and (eq t organization)
4981                   message-user-organization-file
4982                   (file-exists-p message-user-organization-file))
4983              (insert-file-contents message-user-organization-file)))
4984       (goto-char (point-min))
4985       (while (re-search-forward "[\t\n]+" nil t)
4986         (replace-match "" t t))
4987       (unless (zerop (buffer-size))
4988         (buffer-string)))))
4989
4990 (defun message-make-lines ()
4991   "Count the number of lines and return numeric string."
4992   (save-excursion
4993     (save-restriction
4994       (widen)
4995       (message-goto-body)
4996       (int-to-string (count-lines (point) (point-max))))))
4997
4998 (defun message-make-references ()
4999   "Return the References header for this message."
5000   (when message-reply-headers
5001     (let ((message-id (mail-header-message-id message-reply-headers))
5002           (references (mail-header-references message-reply-headers))
5003           new-references)
5004       (if (or references message-id)
5005           (concat (or references "") (and references " ")
5006                   (or message-id ""))
5007         nil))))
5008
5009 (defun message-make-in-reply-to ()
5010   "Return the In-Reply-To header for this message."
5011   (when message-reply-headers
5012     (let ((from (mail-header-from message-reply-headers))
5013           (date (mail-header-date message-reply-headers))
5014           (msg-id (mail-header-message-id message-reply-headers)))
5015       (when msg-id
5016         (concat msg-id
5017                 (when from
5018                   (let ((pair (std11-extract-address-components from)))
5019                     (concat "\n ("
5020                             (or (car pair) (cadr pair))
5021                             "'s message of \""
5022                             (if (or (not date) (string= date ""))
5023                                 "(unknown date)" date)
5024                             "\")"))))))))
5025
5026 (defun message-make-distribution ()
5027   "Make a Distribution header."
5028   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5029     (cond ((message-functionp message-distribution-function)
5030            (funcall message-distribution-function))
5031           (t orig-distribution))))
5032
5033 (defun message-make-expires ()
5034   "Return an Expires header based on `message-expires'."
5035   (let ((current (current-time))
5036         (future (* 1.0 message-expires 60 60 24)))
5037     ;; Add the future to current.
5038     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5039     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5040     (message-make-date current)))
5041
5042 (defun message-make-path ()
5043   "Return uucp path."
5044   (let ((login-name (user-login-name)))
5045     (cond ((null message-user-path)
5046            (concat (system-name) "!" login-name))
5047           ((stringp message-user-path)
5048            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5049            (concat message-user-path "!" login-name))
5050           (t login-name))))
5051
5052 (defun message-make-from ()
5053   "Make a From header."
5054   (let* ((style message-from-style)
5055          (login (message-make-address))
5056          (fullname
5057           (or (and (boundp 'user-full-name)
5058                    user-full-name)
5059               (user-full-name))))
5060     (when (string= fullname "&")
5061       (setq fullname (user-login-name)))
5062     (save-excursion
5063       (message-set-work-buffer)
5064       (cond
5065        ((or (null style)
5066             (equal fullname ""))
5067         (insert login))
5068        ((or (eq style 'angles)
5069             (and (not (eq style 'parens))
5070                  ;; Use angles if no quoting is needed, or if parens would
5071                  ;; need quoting too.
5072                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5073                      (let ((tmp (concat fullname nil)))
5074                        (while (string-match "([^()]*)" tmp)
5075                          (aset tmp (match-beginning 0) ?-)
5076                          (aset tmp (1- (match-end 0)) ?-))
5077                        (string-match "[\\()]" tmp)))))
5078         (insert fullname)
5079         (insert " <" login ">"))
5080        (t                               ; 'parens or default
5081         (insert login " (")
5082         (let ((fullname-start (point)))
5083           (insert fullname)
5084           (goto-char fullname-start)
5085           ;; RFC 822 says \ and nonmatching parentheses
5086           ;; must be escaped in comments.
5087           ;; Escape every instance of ()\ ...
5088           (while (re-search-forward "[()\\]" nil 1)
5089             (replace-match "\\\\\\&" t))
5090           ;; ... then undo escaping of matching parentheses,
5091           ;; including matching nested parentheses.
5092           (goto-char fullname-start)
5093           (while (re-search-forward
5094                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5095                   nil 1)
5096             (replace-match "\\1(\\3)" t)
5097             (goto-char fullname-start)))
5098         (insert ")")))
5099       (buffer-string))))
5100
5101 (defun message-make-sender ()
5102   "Return the \"real\" user address.
5103 This function tries to ignore all user modifications, and
5104 give as trustworthy answer as possible."
5105   (concat (user-login-name) "@" (system-name)))
5106
5107 (defun message-make-address ()
5108   "Make the address of the user."
5109   (or (message-user-mail-address)
5110       (concat (user-login-name) "@" (message-make-domain))))
5111
5112 (defun message-user-mail-address ()
5113   "Return the pertinent part of `user-mail-address'."
5114   (when (and user-mail-address
5115              (string-match "@.*\\." user-mail-address))
5116     (if (string-match " " user-mail-address)
5117         (nth 1 (std11-extract-address-components user-mail-address))
5118       user-mail-address)))
5119
5120 (defun message-sendmail-envelope-from ()
5121   "Return the envelope from."
5122   (cond ((eq message-sendmail-envelope-from 'header)
5123          (nth 1 (mail-extract-address-components
5124                  (message-fetch-field "from"))))
5125         ((stringp message-sendmail-envelope-from)
5126          message-sendmail-envelope-from)
5127         (t
5128          (message-make-address))))
5129
5130 (defun message-make-fqdn ()
5131   "Return user's fully qualified domain name."
5132   (let* ((system-name (system-name))
5133          (user-mail (message-user-mail-address))
5134          (user-domain
5135           (if (and user-mail
5136                    (string-match "@\\(.*\\)\\'" user-mail))
5137               (match-string 1 user-mail))))
5138     (cond
5139      ((and message-user-fqdn
5140            (stringp message-user-fqdn)
5141            (string-match message-valid-fqdn-regexp message-user-fqdn)
5142            (not (string-match message-bogus-system-names message-user-fqdn)))
5143       message-user-fqdn)
5144      ;; `message-user-fqdn' seems to be valid
5145      ((and (string-match message-valid-fqdn-regexp system-name)
5146            (not (string-match message-bogus-system-names system-name)))
5147       ;; `system-name' returned the right result.
5148       system-name)
5149      ;; Try `mail-host-address'.
5150      ((and (boundp 'mail-host-address)
5151            (stringp mail-host-address)
5152            (string-match message-valid-fqdn-regexp mail-host-address)
5153            (not (string-match message-bogus-system-names mail-host-address)))
5154       mail-host-address)
5155      ;; We try `user-mail-address' as a backup.
5156      ((and user-domain
5157            (stringp user-domain)
5158            (string-match message-valid-fqdn-regexp user-domain)
5159            (not (string-match message-bogus-system-names user-domain)))
5160       user-domain)
5161      ;; Default to this bogus thing.
5162      (t
5163       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
5164
5165 (defun message-make-host-name ()
5166   "Return the name of the host."
5167   (let ((fqdn (message-make-fqdn)))
5168     (string-match "^[^.]+\\." fqdn)
5169     (substring fqdn 0 (1- (match-end 0)))))
5170
5171 (defun message-make-domain ()
5172   "Return the domain name."
5173   (or mail-host-address
5174       (message-make-fqdn)))
5175
5176 (defun message-to-list-only ()
5177   "Send a message to the list only.
5178 Remove all addresses but the list address from To and Cc headers."
5179   (interactive)
5180   (let ((listaddr (message-make-mail-followup-to t)))
5181     (when listaddr
5182       (save-excursion
5183         (message-remove-header "to")
5184         (message-remove-header "cc")
5185         (message-position-on-field "To" "X-Draft-From")
5186         (insert listaddr)))))
5187
5188 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5189   "Return the Mail-Followup-To header.
5190 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5191 subscribed address (and not the additional To and Cc header contents)."
5192   (let* ((case-fold-search t)
5193          (to (message-fetch-field "To"))
5194          (cc (message-fetch-field "cc"))
5195          (msg-recipients (concat to (and to cc ", ") cc))
5196          (recipients
5197           (mapcar 'mail-strip-quoted-names
5198                   (message-tokenize-header msg-recipients)))
5199          (file-regexps
5200           (if message-subscribed-address-file
5201               (let (begin end item re)
5202                 (save-excursion
5203                   (with-temp-buffer
5204                     (insert-file-contents message-subscribed-address-file)
5205                     (while (not (eobp))
5206                       (setq begin (point))
5207                       (forward-line 1)
5208                       (setq end (point))
5209                       (if (bolp) (setq end (1- end)))
5210                       (setq item (regexp-quote (buffer-substring begin end)))
5211                       (if re (setq re (concat re "\\|" item))
5212                         (setq re (concat "\\`\\(" item))))
5213                     (and re (list (concat re "\\)\\'"))))))))
5214          (mft-regexps (apply 'append message-subscribed-regexps
5215                              (mapcar 'regexp-quote
5216                                      message-subscribed-addresses)
5217                              file-regexps
5218                              (mapcar 'funcall
5219                                      message-subscribed-address-functions))))
5220     (save-match-data
5221       (let ((subscribed-lists nil)
5222             (list
5223              (loop for recipient in recipients
5224                when (loop for regexp in mft-regexps
5225                       when (string-match regexp recipient) return t)
5226                return recipient)))
5227         (when list
5228           (if only-show-subscribed
5229               list
5230             msg-recipients))))))
5231
5232 ;; Dummy to avoid byte-compile warning.
5233 (defvar mule-version)
5234 (defvar emacs-beta-version)
5235 (defvar xemacs-codename)
5236 (defvar gnus-inviolable-extended-version)
5237
5238 (defun message-make-user-agent ()
5239   "Return user-agent info if the value `message-user-agent' is non-nil. If the
5240 \"User-Agent\" field has already exist, it's value will be added in the return
5241 string."
5242   (when message-user-agent
5243     (save-excursion
5244       (goto-char (point-min))
5245       (let ((case-fold-search t)
5246             user-agent start p end)
5247         (if (re-search-forward
5248              (concat "^User-Agent:[\t ]*\\("
5249                      (regexp-quote gnus-product-name)
5250                      "/[0-9.]+\\([ \t\r\n]*([^)]+)\\)*\\)?[\t ]*")
5251              nil t)
5252             (progn
5253               (setq start (match-beginning 0)
5254                     p (match-end 0)
5255                     end (std11-field-end)
5256                     user-agent (buffer-substring-no-properties p end))
5257               (delete-region start (1+ end))
5258               (concat message-user-agent " " user-agent))
5259           message-user-agent)))))
5260
5261 (defun message-generate-headers (headers)
5262   "Prepare article HEADERS.
5263 Headers already prepared in the buffer are not modified."
5264   (setq headers (append headers message-required-headers))
5265   (save-restriction
5266     (message-narrow-to-headers)
5267     (let* ((Date (message-make-date))
5268            (Message-ID (message-make-message-id))
5269            (Organization (message-make-organization))
5270            (From (message-make-from))
5271            (Path (message-make-path))
5272            (Subject nil)
5273            (Newsgroups nil)
5274            (In-Reply-To (message-make-in-reply-to))
5275            (References (message-make-references))
5276            (To nil)
5277            (Distribution (message-make-distribution))
5278            (Lines (message-make-lines))
5279            (User-Agent (message-make-user-agent))
5280            (Expires (message-make-expires))
5281            (case-fold-search t)
5282            (optionalp nil)
5283            header value elem)
5284       ;; First we remove any old generated headers.
5285       (let ((headers message-deletable-headers))
5286         (unless (buffer-modified-p)
5287           (setq headers (delq 'Message-ID (copy-sequence headers))))
5288         (while headers
5289           (goto-char (point-min))
5290           (and (re-search-forward
5291                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5292                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5293                (message-delete-line))
5294           (pop headers)))
5295       ;; Go through all the required headers and see if they are in the
5296       ;; articles already.  If they are not, or are empty, they are
5297       ;; inserted automatically - except for Subject, Newsgroups and
5298       ;; Distribution.
5299       (while headers
5300         (goto-char (point-min))
5301         (setq elem (pop headers))
5302         (if (consp elem)
5303             (if (eq (car elem) 'optional)
5304                 (setq header (cdr elem)
5305                       optionalp t)
5306               (setq header (car elem)))
5307           (setq header elem))
5308         (when (or (not (re-search-forward
5309                         (concat "^"
5310                                 (regexp-quote
5311                                  (downcase
5312                                   (if (stringp header)
5313                                       header
5314                                     (symbol-name header))))
5315                                 ":")
5316                         nil t))
5317                   (progn
5318                     ;; The header was found.  We insert a space after the
5319                     ;; colon, if there is none.
5320                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5321                     ;; Find out whether the header is empty.
5322                     (looking-at "[ \t]*\n[^ \t]")))
5323           ;; So we find out what value we should insert.
5324           (setq value
5325                 (cond
5326                  ((and (consp elem)
5327                        (eq (car elem) 'optional))
5328                   ;; This is an optional header.  If the cdr of this
5329                   ;; is something that is nil, then we do not insert
5330                   ;; this header.
5331                   (setq header (cdr elem))
5332                   (or (and (message-functionp (cdr elem))
5333                            (funcall (cdr elem)))
5334                       (and (boundp (cdr elem))
5335                            (symbol-value (cdr elem)))))
5336                  ((consp elem)
5337                   ;; The element is a cons.  Either the cdr is a
5338                   ;; string to be inserted verbatim, or it is a
5339                   ;; function, and we insert the value returned from
5340                   ;; this function.
5341                   (or (and (stringp (cdr elem))
5342                            (cdr elem))
5343                       (and (message-functionp (cdr elem))
5344                            (funcall (cdr elem)))))
5345                  ((and (boundp header)
5346                        (symbol-value header))
5347                   ;; The element is a symbol.  We insert the value
5348                   ;; of this symbol, if any.
5349                   (symbol-value header))
5350                  ((not (message-check-element header))
5351                   ;; We couldn't generate a value for this header,
5352                   ;; so we just ask the user.
5353                   (read-from-minibuffer
5354                    (format "Empty header for %s; enter value: " header)))))
5355           ;; Finally insert the header.
5356           (when (and value
5357                      (not (equal value "")))
5358             (save-excursion
5359               (if (bolp)
5360                   (progn
5361                     ;; This header didn't exist, so we insert it.
5362                     (goto-char (point-max))
5363                     (let ((formatter
5364                            (cdr (assq header message-header-format-alist))))
5365                       (if formatter
5366                           (funcall formatter header value)
5367                         (insert (if (stringp header)
5368                                     header (symbol-name header))
5369                                 ": " value))
5370                       ;; We check whether the value was ended by a
5371                       ;; newline.  If now, we insert one.
5372                       (unless (bolp)
5373                         (insert "\n"))
5374                       (forward-line -1)))
5375                 ;; The value of this header was empty, so we clear
5376                 ;; totally and insert the new value.
5377                 (delete-region (point) (gnus-point-at-eol))
5378                 ;; If the header is optional, and the header was
5379                 ;; empty, we can't insert it anyway.
5380                 (unless optionalp
5381                   (insert value)
5382                   (when (bolp)
5383                     (delete-char -1))))
5384               ;; Add the deletable property to the headers that require it.
5385               (and (memq header message-deletable-headers)
5386                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5387                    (add-text-properties
5388                     (point) (match-end 0)
5389                     '(message-deletable t face italic) (current-buffer)))))))
5390       ;; Insert new Sender if the From is strange.
5391       (let ((from (message-fetch-field "from"))
5392             (sender (message-fetch-field "sender"))
5393             (secure-sender (message-make-sender)))
5394         (when (and from
5395                    (not (message-check-element 'sender))
5396                    (not (string=
5397                          (downcase
5398                           (cadr (std11-extract-address-components from)))
5399                          (downcase secure-sender)))
5400                    (or (null sender)
5401                        (not
5402                         (string=
5403                          (downcase
5404                           (cadr (std11-extract-address-components sender)))
5405                          (downcase secure-sender)))))
5406           (goto-char (point-min))
5407           ;; Rename any old Sender headers to Original-Sender.
5408           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5409             (beginning-of-line)
5410             (insert "Original-")
5411             (beginning-of-line))
5412           (when (or (message-news-p)
5413                     (string-match "@.+\\.." secure-sender))
5414             (insert "Sender: " secure-sender "\n")))))))
5415
5416 (defun message-insert-courtesy-copy ()
5417   "Insert a courtesy message in mail copies of combined messages."
5418   (let (newsgroups)
5419     (save-excursion
5420       (save-restriction
5421         (message-narrow-to-headers)
5422         (when (setq newsgroups (message-fetch-field "newsgroups"))
5423           (goto-char (point-max))
5424           (insert "Posted-To: " newsgroups "\n")))
5425       (forward-line 1)
5426       (when message-courtesy-message
5427         (cond
5428          ((string-match "%s" message-courtesy-message)
5429           (insert (format message-courtesy-message newsgroups)))
5430          (t
5431           (insert message-courtesy-message)))))))
5432
5433 ;;;
5434 ;;; Setting up a message buffer
5435 ;;;
5436
5437 (defun message-fill-address (header value)
5438   (save-restriction
5439     (narrow-to-region (point) (point))
5440     (insert (capitalize (symbol-name header))
5441             ": "
5442             (if (consp value) (car value) value)
5443             "\n")
5444     (narrow-to-region (point-min) (1- (point-max)))
5445     (let (quoted last)
5446       (goto-char (point-min))
5447       (while (not (eobp))
5448         (skip-chars-forward "^,\"" (point-max))
5449         (if (or (eq (char-after) ?,)
5450                 (eobp))
5451             (when (not quoted)
5452               (if (and (> (current-column) 78)
5453                        last)
5454                   (save-excursion
5455                     (goto-char last)
5456                     (looking-at "[ \t]*")
5457                     (replace-match "\n " t t)))
5458               (setq last (1+ (point))))
5459           (setq quoted (not quoted)))
5460         (unless (eobp)
5461           (forward-char 1))))
5462     (goto-char (point-max))
5463     (widen)
5464     (forward-line 1)))
5465
5466 (defun message-fill-references (header value)
5467   (insert (capitalize (symbol-name header))
5468           ": "
5469           (std11-fill-msg-id-list-string
5470            (if (consp value) (car value) value))
5471           "\n"))
5472
5473 (defun message-fill-header (header value)
5474   (let ((begin (point))
5475         (fill-column 78)
5476         (fill-prefix " "))
5477     (insert (capitalize (symbol-name header))
5478             ": "
5479             (if (consp value) (car value) value)
5480             "\n")
5481     (save-restriction
5482       (narrow-to-region begin (point))
5483       (fill-region-as-paragraph begin (point))
5484       ;; Tapdance around looong Message-IDs.
5485       (forward-line -1)
5486       (when (looking-at "[ \t]*$")
5487         (message-delete-line))
5488       (goto-char begin)
5489       (re-search-forward ":" nil t)
5490       (when (looking-at "\n[ \t]+")
5491         (replace-match " " t t))
5492       (goto-char (point-max)))))
5493
5494 (defun message-shorten-1 (list cut surplus)
5495   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5496   (setcdr (nthcdr (- cut 2) list)
5497           (nthcdr (+ (- cut 2) surplus 1) list)))
5498
5499 (defun message-shorten-references (header references)
5500   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5501 If folding is disallowed, also check that the REFERENCES are less
5502 than 988 characters long, and if they are not, trim them until they are."
5503   (let ((maxcount 21)
5504         (count 0)
5505         (cut 2)
5506         refs)
5507     (with-temp-buffer
5508       (insert references)
5509       (goto-char (point-min))
5510       ;; Cons a list of valid references.
5511       (while (re-search-forward "<[^>]+>" nil t)
5512         (push (match-string 0) refs))
5513       (setq refs (nreverse refs)
5514             count (length refs)))
5515
5516     ;; If the list has more than MAXCOUNT elements, trim it by
5517     ;; removing the CUTth element and the required number of
5518     ;; elements that follow.
5519     (when (> count maxcount)
5520       (let ((surplus (- count maxcount)))
5521         (message-shorten-1 refs cut surplus)
5522         (decf count surplus)))
5523
5524     ;; If folding is disallowed, make sure the total length (including
5525     ;; the spaces between) will be less than MAXSIZE characters.
5526     ;;
5527     ;; Only disallow folding for News messages. At this point the headers
5528     ;; have not been generated, thus we use message-this-is-news directly.
5529     (when (and message-this-is-news message-cater-to-broken-inn)
5530       (let ((maxsize 988)
5531             (totalsize (+ (apply #'+ (mapcar #'length refs))
5532                           (1- count)))
5533             (surplus 0)
5534             (ptr (nthcdr (1- cut) refs)))
5535         ;; Decide how many elements to cut off...
5536         (while (> totalsize maxsize)
5537           (decf totalsize (1+ (length (car ptr))))
5538           (incf surplus)
5539           (setq ptr (cdr ptr)))
5540         ;; ...and do it.
5541         (when (> surplus 0)
5542           (message-shorten-1 refs cut surplus))))
5543
5544     ;; Finally, collect the references back into a string and insert
5545     ;; it into the buffer.
5546     (let ((refstring (mapconcat #'identity refs " ")))
5547       (if (and message-this-is-news message-cater-to-broken-inn)
5548           (insert (capitalize (symbol-name header)) ": "
5549                   refstring "\n")
5550         (message-fill-header header refstring)))))
5551
5552 (defun message-position-point ()
5553   "Move point to where the user probably wants to find it."
5554   (message-narrow-to-headers)
5555   (cond
5556    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5557     (search-backward ":" )
5558     (widen)
5559     (forward-char 1)
5560     (if (eq (char-after) ? )
5561         (forward-char 1)
5562       (insert " ")))
5563    (t
5564     (goto-char (point-max))
5565     (widen)
5566     (forward-line 1)
5567     (unless (looking-at "$")
5568       (forward-line 2)))
5569    (sit-for 0)))
5570
5571 (defcustom message-beginning-of-line t
5572   "Whether C-a goes to beginning of header values."
5573   :group 'message-buffers
5574   :type 'boolean)
5575
5576 (defun message-beginning-of-line (&optional n)
5577   "Move point to beginning of header value or to beginning of line."
5578   (interactive "p")
5579   (let ((zrs 'zmacs-region-stays))
5580     (when (and (interactive-p) (boundp zrs))
5581       (set zrs t)))
5582   (if (and message-beginning-of-line
5583            (message-point-in-header-p))
5584       (let* ((here (point))
5585              (bol (progn (beginning-of-line n) (point)))
5586              (eol (gnus-point-at-eol))
5587              (eoh (re-search-forward ": *" eol t)))
5588         (if (or (not eoh) (equal here eoh))
5589             (goto-char bol)
5590           (goto-char eoh)))
5591     (beginning-of-line n)))
5592
5593 (defun message-buffer-name (type &optional to group)
5594   "Return a new (unique) buffer name based on TYPE and TO."
5595   (cond
5596    ;; Generate a new buffer name The Message Way.
5597    ((eq message-generate-new-buffers 'unique)
5598     (generate-new-buffer-name
5599      (concat "*" type
5600              (if to
5601                  (concat " to "
5602                          (or (car (std11-extract-address-components to))
5603                              to) "")
5604                "")
5605              (if (and group (not (string= group ""))) (concat " on " group) "")
5606              "*")))
5607    ;; Check whether `message-generate-new-buffers' is a function,
5608    ;; and if so, call it.
5609    ((message-functionp message-generate-new-buffers)
5610     (funcall message-generate-new-buffers type to group))
5611    ((eq message-generate-new-buffers 'unsent)
5612     (generate-new-buffer-name
5613      (concat "*unsent " type
5614              (if to
5615                  (concat " to "
5616                          (or (car (mail-extract-address-components to))
5617                              to) "")
5618                "")
5619              (if (and group (not (string= group ""))) (concat " on " group) "")
5620              "*")))
5621    ;; Use standard name.
5622    (t
5623     (format "*%s message*" type))))
5624
5625 (defmacro message-pop-to-buffer-1 (buffer)
5626   `(if pop-up-frames
5627        (let (special-display-buffer-names
5628              special-display-regexps
5629              same-window-buffer-names
5630              same-window-regexps)
5631          (pop-to-buffer ,buffer))
5632      (pop-to-buffer ,buffer)))
5633
5634 (defun message-pop-to-buffer (name)
5635   "Pop to buffer NAME, and warn if it already exists and is modified."
5636   (let ((buffer (get-buffer name))
5637         (pop-up-frames (and (or (static-if (featurep 'xemacs)
5638                                     (device-on-window-system-p)
5639                                   window-system)
5640                                 (>= emacs-major-version 20))
5641                             message-use-multi-frames)))
5642     (if (and buffer
5643              (buffer-name buffer))
5644         (progn
5645           (message-pop-to-buffer-1 buffer)
5646           (when (and (buffer-modified-p)
5647                      (not (y-or-n-p
5648                            "Message already being composed; erase? ")))
5649             (error "Message being composed")))
5650       (message-pop-to-buffer-1 name))
5651     (erase-buffer)
5652     (message-mode)
5653     (when pop-up-frames
5654       (set (make-local-variable 'message-original-frame) (selected-frame)))))
5655
5656 (defun message-do-send-housekeeping ()
5657   "Kill old message buffers."
5658   ;; We might have sent this buffer already.  Delete it from the
5659   ;; list of buffers.
5660   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5661   (while (and message-max-buffers
5662               message-buffer-list
5663               (>= (length message-buffer-list) message-max-buffers))
5664     ;; Kill the oldest buffer -- unless it has been changed.
5665     (let ((buffer (pop message-buffer-list)))
5666       (when (and (buffer-name buffer)
5667                  (not (buffer-modified-p buffer)))
5668         (kill-buffer buffer))))
5669   ;; Rename the buffer.
5670   (if message-send-rename-function
5671       (funcall message-send-rename-function)
5672     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5673     (when (string-match
5674            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5675            (buffer-name))
5676       (let ((name (match-string 2 (buffer-name)))
5677             to group)
5678         (if (not (or (null name)
5679                      (string-equal name "mail")
5680                      (string-equal name "posting")))
5681             (setq name (concat "*sent " name "*"))
5682           (message-narrow-to-headers)
5683           (setq to (message-fetch-field "to"))
5684           (setq group (message-fetch-field "newsgroups"))
5685           (widen)
5686           (setq name
5687                 (cond
5688                  (to (concat "*sent mail to "
5689                              (or (car (mail-extract-address-components to))
5690                                  to) "*"))
5691                  ((and group (not (string= group "")))
5692                   (concat "*sent posting on " group "*"))
5693                  (t "*sent mail*"))))
5694         (unless (string-equal name (buffer-name))
5695           (rename-buffer name t)))))
5696   ;; Push the current buffer onto the list.
5697   (when message-max-buffers
5698     (setq message-buffer-list
5699           (nconc message-buffer-list (list (current-buffer))))))
5700
5701 (defun message-mail-user-agent ()
5702   (let ((mua (cond
5703               ((not message-mail-user-agent) nil)
5704               ((eq message-mail-user-agent t) mail-user-agent)
5705               (t message-mail-user-agent))))
5706     (if (memq mua '(message-user-agent gnus-user-agent))
5707         nil
5708       mua)))
5709
5710 (defun message-setup (headers &optional replybuffer actions switch-function)
5711   (let ((mua (message-mail-user-agent))
5712         subject to field yank-action)
5713     (if (not (and message-this-is-mail mua))
5714         (message-setup-1 headers replybuffer actions)
5715       (if replybuffer
5716           (setq yank-action (list 'insert-buffer replybuffer)))
5717       (setq headers (copy-sequence headers))
5718       (setq field (assq 'Subject headers))
5719       (when field
5720         (setq subject (cdr field))
5721         (setq headers (delq field headers)))
5722       (setq field (assq 'To headers))
5723       (when field
5724         (setq to (cdr field))
5725         (setq headers (delq field headers)))
5726       (let ((mail-user-agent mua))
5727         (compose-mail to subject
5728                       (mapcar (lambda (item)
5729                                 (cons
5730                                  (format "%s" (car item))
5731                                  (cdr item)))
5732                               headers)
5733                       nil switch-function yank-action actions)))))
5734
5735 (defun message-headers-to-generate (headers included-headers excluded-headers)
5736   "Return a list that includes all headers from HEADERS.
5737 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5738 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5739 are not included."
5740   (let ((result nil)
5741         header-name)
5742     (dolist (header headers)
5743       (setq header-name (cond
5744                          ((and (consp header)
5745                                (eq (car header) 'optional))
5746                           ;; On the form (optional . Header)
5747                           (cdr header))
5748                          ((consp header)
5749                           ;; On the form (Header . function)
5750                           (car header))
5751                          (t
5752                           ;; Just a Header.
5753                           header)))
5754       (when (and (not (memq header-name excluded-headers))
5755                  (or (eq included-headers t)
5756                      (memq header-name included-headers)))
5757         (push header result)))
5758     (nreverse result)))
5759
5760 (defun message-setup-1 (headers &optional replybuffer actions)
5761   (dolist (action actions)
5762     (condition-case nil
5763         (add-to-list 'message-send-actions
5764                      `(apply ',(car action) ',(cdr action)))))
5765   (setq message-reply-buffer
5766         (or (message-get-parameter 'reply-buffer)
5767             replybuffer))
5768   (goto-char (point-min))
5769   ;; Insert all the headers.
5770   (mail-header-format
5771    (let ((h headers)
5772          (alist message-header-format-alist))
5773      (while h
5774        (unless (assq (caar h) message-header-format-alist)
5775          (push (list (caar h)) alist))
5776        (pop h))
5777      alist)
5778    headers)
5779   (delete-region (point) (progn (forward-line -1) (point)))
5780   (when message-default-headers
5781     (insert message-default-headers)
5782     (or (bolp) (insert ?\n)))
5783   (put-text-property
5784    (point)
5785    (progn
5786      (insert mail-header-separator "\n")
5787      (1- (point)))
5788    'read-only nil)
5789   (forward-line -1)
5790   (when (message-news-p)
5791     (when message-default-news-headers
5792       (insert message-default-news-headers)
5793       (or (bolp) (insert ?\n)))
5794     (when message-generate-headers-first
5795       (message-generate-headers
5796        (message-headers-to-generate
5797         (append message-required-news-headers
5798                 message-required-headers)
5799         message-generate-headers-first
5800         '(Lines Subject)))))
5801   (when (message-mail-p)
5802     (when message-default-mail-headers
5803       (insert message-default-mail-headers)
5804       (or (bolp) (insert ?\n)))
5805     (when message-generate-headers-first
5806       (message-generate-headers
5807        (message-headers-to-generate
5808         (append message-required-mail-headers
5809                 message-required-headers)
5810         message-generate-headers-first
5811         '(Lines Subject)))))
5812   (run-hooks 'message-signature-setup-hook)
5813   (message-insert-signature)
5814   (save-restriction
5815     (message-narrow-to-headers)
5816     (if (and replybuffer
5817              message-alternative-emails)
5818         (message-use-alternative-email-as-from))
5819     (run-hooks 'message-header-setup-hook))
5820   (set-buffer-modified-p nil)
5821   (setq buffer-undo-list nil)
5822   (run-hooks 'message-setup-hook)
5823   (message-position-point)
5824   (undo-boundary))
5825
5826 (defun message-set-auto-save-file-name ()
5827   "Associate the message buffer with a file in the drafts directory."
5828   (when message-auto-save-directory
5829     (unless (file-directory-p
5830              (directory-file-name message-auto-save-directory))
5831       (make-directory message-auto-save-directory t))
5832     (if (gnus-alive-p)
5833         (setq message-draft-article
5834               (nndraft-request-associate-buffer "drafts"))
5835       (setq buffer-file-name (expand-file-name
5836                               (if (memq system-type
5837                                         '(ms-dos ms-windows windows-nt
5838                                                  cygwin cygwin32 win32 w32
5839                                                  mswindows))
5840                                   "message"
5841                                 "*message*")
5842                               message-auto-save-directory))
5843       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5844     (clear-visited-file-modtime)
5845     (static-if (boundp 'MULE)
5846         (set-file-coding-system message-draft-coding-system)
5847       (setq buffer-file-coding-system message-draft-coding-system))))
5848
5849 (defun message-disassociate-draft ()
5850   "Disassociate the message buffer from the drafts directory."
5851   (when message-draft-article
5852     (nndraft-request-expire-articles
5853      (list message-draft-article) "drafts" nil t)))
5854
5855 (defun message-insert-headers ()
5856   "Generate the headers for the article."
5857   (interactive)
5858   (save-excursion
5859     (save-restriction
5860       (message-narrow-to-headers)
5861       (when (message-news-p)
5862         (message-generate-headers
5863          (delq 'Lines
5864                (delq 'Subject
5865                      (copy-sequence message-required-news-headers)))))
5866       (when (message-mail-p)
5867         (message-generate-headers
5868          (delq 'Lines
5869                (delq 'Subject
5870                      (copy-sequence message-required-mail-headers))))))))
5871
5872 \f
5873
5874 ;;;
5875 ;;; Commands for interfacing with message
5876 ;;;
5877
5878 ;;;###autoload
5879 (defun message-mail (&optional to subject
5880                                other-headers continue switch-function
5881                                yank-action send-actions)
5882   "Start editing a mail message to be sent.
5883 OTHER-HEADERS is an alist of header/value pairs."
5884   (interactive)
5885   (let ((message-this-is-mail t) replybuffer)
5886     (unless (message-mail-user-agent)
5887       (message-pop-to-buffer (message-buffer-name "mail" to)))
5888     ;; FIXME: message-mail should do something if YANK-ACTION is not
5889     ;; insert-buffer.
5890     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5891          (setq replybuffer (nth 1 yank-action)))
5892     (message-setup
5893      (nconc
5894       `((To . ,(or to "")) (Subject . ,(or subject "")))
5895       (when other-headers other-headers))
5896      replybuffer send-actions)
5897     ;; FIXME: Should return nil if failure.
5898     t))
5899
5900 ;;;###autoload
5901 (defun message-news (&optional newsgroups subject)
5902   "Start editing a news article to be sent."
5903   (interactive)
5904   (let ((message-this-is-news t))
5905     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5906     (message-setup `((Newsgroups . ,(or newsgroups ""))
5907                      (Subject . ,(or subject ""))))))
5908
5909 (defun message-get-reply-headers (wide &optional to-address address-headers)
5910   (let (follow-to mct never-mct to cc author mft recipients)
5911     ;; Find all relevant headers we need.
5912     (let ((mrt (when message-use-mail-reply-to
5913                  (message-fetch-field "mail-reply-to")))
5914           (reply-to (message-fetch-field "reply-to")))
5915       (setq to (message-fetch-field "to")
5916             cc (message-fetch-field "cc")
5917             mct (when message-use-mail-copies-to
5918                   (message-fetch-field "mail-copies-to"))
5919             author (or mrt
5920                        reply-to
5921                        (message-fetch-field "from")
5922                        "")
5923             mft (when (and (not (or to-address mrt reply-to))
5924                            message-use-mail-followup-to)
5925                   (message-fetch-field "mail-followup-to"))))
5926
5927     (save-match-data
5928       ;; Handle special values of Mail-Copies-To.
5929       (when mct
5930         (cond ((or (equal (downcase mct) "never")
5931                    (equal (downcase mct) "nobody"))
5932                (when (or (not (eq message-use-mail-copies-to 'ask))
5933                          (message-y-or-n-p
5934                           (concat "Obey Mail-Copies-To: never? ") t "\
5935 You should normally obey the Mail-Copies-To: header.
5936
5937         `Mail-Copies-To: " mct "'
5938 directs you not to send your response to the author."))
5939                  (setq never-mct t))
5940                (setq mct nil))
5941               ((or (equal (downcase mct) "always")
5942                    (equal (downcase mct) "poster"))
5943                (if (or (not (eq message-use-mail-copies-to 'ask))
5944                        (message-y-or-n-p
5945                         (concat "Obey Mail-Copies-To: always? ") t "\
5946 You should normally obey the Mail-Copies-To: header.
5947
5948         `Mail-Copies-To: " mct "'
5949 sends a copy of your response to the author."))
5950                    (setq mct author)
5951                  (setq mct nil)))
5952               ((and (eq message-use-mail-copies-to 'ask)
5953                     (not (message-y-or-n-p
5954                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5955 You should normally obey the Mail-Copies-To: header.
5956
5957         `Mail-Copies-To: " mct "'
5958 sends a copy of your response to " (if (string-match "," mct)
5959                                        "the specified addresses"
5960                                      "that address") ".")))
5961                (setq mct nil))))
5962
5963       ;; Build (textual) list of new recipient addresses.
5964       (cond
5965        ((not wide)
5966         (setq recipients (concat ", " author)))
5967        (address-headers
5968         (dolist (header address-headers)
5969           (let ((value (message-fetch-field header)))
5970             (when value
5971               (setq recipients (concat recipients ", " value))))))
5972        ((and mft
5973              (string-match "[^ \t,]" mft)
5974              (or (not (eq message-use-mail-followup-to 'ask))
5975                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5976 You should normally obey the Mail-Followup-To: header.  In this
5977 article, it has the value of
5978
5979 " mft "
5980
5981 which directs your response to " (if (string-match "," mft)
5982                                      "the specified addresses"
5983                                    "that address only") ".
5984
5985 Most commonly, Mail-Followup-To is used by a mailing list poster to
5986 express that responses should be sent to just the list, and not the
5987 poster as well.
5988
5989 If a message is posted to several mailing lists, Mail-Followup-To may
5990 also be used to direct the following discussion to one list only,
5991 because discussions that are spread over several lists tend to be
5992 fragmented and very difficult to follow.
5993
5994 Also, some source/announcement lists are not intended for discussion;
5995 responses here are directed to other addresses.")))
5996         (setq recipients (concat ", " mft)))
5997        (to-address
5998         (setq recipients (concat ", " to-address))
5999         ;; If the author explicitly asked for a copy, we don't deny it to them.
6000         (if mct (setq recipients (concat recipients ", " mct))))
6001        (t
6002         (setq recipients (if never-mct "" (concat ", " author)))
6003         (if to  (setq recipients (concat recipients ", " to)))
6004         (if cc  (setq recipients (concat recipients ", " cc)))
6005         (if mct (setq recipients (concat recipients ", " mct)))))
6006       (if (>= (length recipients) 2)
6007           ;; Strip the leading ", ".
6008           (setq recipients (substring recipients 2)))
6009       ;; Squeeze whitespace.
6010       (while (string-match "[ \t][ \t]+" recipients)
6011         (setq recipients (replace-match " " t t recipients)))
6012       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6013       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
6014         (setq recipients (rmail-dont-reply-to recipients)))
6015       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6016       (if (string-equal recipients "")
6017           (setq recipients author))
6018       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6019       (setq recipients
6020             (mapcar
6021              (lambda (addr)
6022                (cons (downcase (mail-strip-quoted-names addr)) addr))
6023              (message-tokenize-header recipients)))
6024       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6025       (let ((s recipients))
6026         (while s
6027           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6028
6029       ;; Remove hierarchical lists that are contained within each other,
6030       ;; if message-hierarchical-addresses is defined.
6031       (when message-hierarchical-addresses
6032         (let ((plain-addrs (mapcar 'car recipients))
6033               subaddrs recip)
6034           (while plain-addrs
6035             (setq subaddrs (assoc (car plain-addrs)
6036                                   message-hierarchical-addresses)
6037                   plain-addrs (cdr plain-addrs))
6038             (when subaddrs
6039               (setq subaddrs (cdr subaddrs))
6040               (while subaddrs
6041                 (setq recip (assoc (car subaddrs) recipients)
6042                       subaddrs (cdr subaddrs))
6043                 (if recip
6044                     (setq recipients (delq recip recipients))))))))
6045
6046       ;; Build the header alist.  Allow the user to be asked whether
6047       ;; or not to reply to all recipients in a wide reply.
6048       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6049       (when (and recipients
6050                  (or (not message-wide-reply-confirm-recipients)
6051                      (y-or-n-p "Reply to all recipients? ")))
6052         (setq recipients (mapconcat
6053                           (lambda (addr) (cdr addr)) recipients ", "))
6054         (if (string-match "^ +" recipients)
6055             (setq recipients (substring recipients (match-end 0))))
6056         (push (cons 'Cc recipients) follow-to)))
6057     follow-to))
6058
6059 ;;;###autoload
6060 (defun message-reply (&optional to-address wide)
6061   "Start editing a reply to the article in the current buffer."
6062   (interactive)
6063   (require 'gnus-sum)                   ; for gnus-list-identifiers
6064   (let ((cur (current-buffer))
6065         from subject date
6066         references message-id follow-to
6067         (inhibit-point-motion-hooks t)
6068         (message-this-is-mail t)
6069         gnus-warning in-reply-to)
6070     (save-restriction
6071       (message-narrow-to-head-1)
6072       ;; Allow customizations to have their say.
6073       (if (not wide)
6074           ;; This is a regular reply.
6075           (when (message-functionp message-reply-to-function)
6076             (save-excursion
6077               (setq follow-to (funcall message-reply-to-function))))
6078         ;; This is a followup.
6079         (when (message-functionp message-wide-reply-to-function)
6080           (save-excursion
6081             (setq follow-to
6082                   (funcall message-wide-reply-to-function)))))
6083       (setq message-id (message-fetch-field "message-id" t)
6084             references (message-fetch-field "references")
6085             date (message-fetch-field "date")
6086             from (message-fetch-field "from")
6087             subject (or (message-fetch-field "subject") "none"))
6088       (when gnus-list-identifiers
6089         (setq subject (message-strip-list-identifiers subject)))
6090       (setq subject (message-make-followup-subject subject))
6091       (when message-subject-trailing-was-query
6092         (setq subject (message-strip-subject-trailing-was subject)))
6093
6094       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6095                  (string-match "<[^>]+>" gnus-warning))
6096         (setq message-id (match-string 0 gnus-warning)))
6097
6098       (unless follow-to
6099         (setq follow-to (message-get-reply-headers wide to-address)))
6100
6101       ;; Get the references from "In-Reply-To" field if there were
6102       ;; no references and "In-Reply-To" field looks promising.
6103       (unless references
6104         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
6105                    (string-match "<[^>]+>" in-reply-to))
6106           (setq references (match-string 0 in-reply-to)))))
6107
6108     (unless (message-mail-user-agent)
6109       (message-pop-to-buffer
6110        (message-buffer-name
6111         (if wide "wide reply" "reply") from
6112         (if wide to-address nil))))
6113
6114     (setq message-reply-headers
6115           (make-full-mail-header-from-decoded-header
6116            0 subject from date message-id references 0 0 ""))
6117
6118     (message-setup
6119      `((Subject . ,subject)
6120        ,@follow-to)
6121      cur)))
6122
6123 ;;;###autoload
6124 (defun message-wide-reply (&optional to-address)
6125   "Make a \"wide\" reply to the message in the current buffer."
6126   (interactive)
6127   (message-reply to-address t))
6128
6129 ;;;###autoload
6130 (defun message-followup (&optional to-newsgroups)
6131   "Follow up to the message in the current buffer.
6132 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6133   (interactive)
6134   (require 'gnus-sum)                   ; for gnus-list-identifiers
6135   (let ((cur (current-buffer))
6136         from subject date reply-to mrt mct mft
6137         references message-id follow-to
6138         (inhibit-point-motion-hooks t)
6139         (message-this-is-news t)
6140         followup-to distribution newsgroups gnus-warning posted-to)
6141     (save-restriction
6142       (message-narrow-to-head)
6143       (when (message-functionp message-followup-to-function)
6144         (setq follow-to
6145               (funcall message-followup-to-function)))
6146       (setq from (message-fetch-field "from")
6147             date (message-fetch-field "date")
6148             subject (or (message-fetch-field "subject") "none")
6149             references (message-fetch-field "references")
6150             message-id (message-fetch-field "message-id" t)
6151             followup-to (message-fetch-field "followup-to")
6152             newsgroups (message-fetch-field "newsgroups")
6153             posted-to (message-fetch-field "posted-to")
6154             reply-to (message-fetch-field "reply-to")
6155             mrt (when message-use-mail-reply-to
6156                   (message-fetch-field "mail-reply-to"))
6157             distribution (message-fetch-field "distribution")
6158             mct (when message-use-mail-copies-to
6159                   (message-fetch-field "mail-copies-to"))
6160             mft (when message-use-mail-followup-to
6161                   (message-fetch-field "mail-followup-to")))
6162       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6163                  (string-match "<[^>]+>" gnus-warning))
6164         (setq message-id (match-string 0 gnus-warning)))
6165       ;; Remove bogus distribution.
6166       (when (and (stringp distribution)
6167                  (let ((case-fold-search t))
6168                    (string-match "world" distribution)))
6169         (setq distribution nil))
6170       (if gnus-list-identifiers
6171           (setq subject (message-strip-list-identifiers subject)))
6172       (setq subject (message-make-followup-subject subject))
6173       (when message-subject-trailing-was-query
6174         (setq subject (message-strip-subject-trailing-was subject)))
6175       (widen))
6176
6177     ;; Handle special values of Mail-Copies-To.
6178     (when mct
6179       (cond
6180        ((and (or (equal (downcase mct) "never")
6181                  (equal (downcase mct) "nobody")))
6182         (setq mct nil))
6183        ((and (or (equal (downcase mct) "always")
6184                  (equal (downcase mct) "poster")))
6185         (if (or (not (eq message-use-mail-copies-to 'ask))
6186                 (message-y-or-n-p
6187                  (concat "Obey Mail-Copies-To: always? ") t "\
6188 You should normally obey the Mail-Copies-To: header.
6189
6190         `Mail-Copies-To: " mct "'
6191 sends a copy of your response to the author."))
6192             (setq mct (or mrt reply-to from))
6193           (setq mct nil)))
6194        ((and (eq message-use-mail-copies-to 'ask)
6195              (not
6196               (message-y-or-n-p
6197                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6198 You should normally obey the Mail-Copies-To: header.
6199
6200         `Mail-Copies-To: " mct "'
6201 sends a copy of your response to " (if (string-match "," mct)
6202                                        "the specified addresses"
6203                                      "that address") ".")))
6204         (setq mct nil))))
6205
6206     (unless follow-to
6207       (cond
6208        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
6209        ;; Handle Followup-To.
6210        (followup-to
6211         (cond
6212          ((equal (downcase followup-to) "poster")
6213           (if (or (and followup-to (eq message-use-followup-to 'use))
6214                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
6215 You should normally obey the Followup-To: header.
6216
6217         `Followup-To: poster'
6218 sends your response via e-mail instead of news.
6219
6220 A typical situation where `Followup-To: poster' is used is when the author
6221 does not read the newsgroup, so he wouldn't see any replies sent to it."))
6222               (setq message-this-is-news nil
6223                     distribution nil
6224                     follow-to (list (cons 'To (or mrt reply-to from ""))))
6225             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
6226          (t
6227           (if (or (equal followup-to newsgroups)
6228                   (not (and followup-to (eq message-use-followup-to 'ask)))
6229                   (message-y-or-n-p
6230                    (concat "Obey Followup-To: " followup-to "? ") t "\
6231 You should normally obey the Followup-To: header.
6232
6233         `Followup-To: " followup-to "'
6234 directs your response to " (if (string-match "," followup-to)
6235                                "the specified newsgroups"
6236                              "that newsgroup only") ".
6237
6238 If a message is posted to several newsgroups, Followup-To is often
6239 used to direct the following discussion to one newsgroup only,
6240 because discussions that are spread over several newsgroup tend to
6241 be fragmented and very difficult to follow.
6242
6243 Also, some source/announcement newsgroups are not intended for discussion;
6244 responses here are directed to other newsgroups."))
6245               (setq follow-to (list (cons 'Newsgroups followup-to)))
6246             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
6247        ;; Handle Mail-Followup-To, followup via e-mail.
6248        ((and mft
6249              (or (not (eq message-use-mail-followup-to 'ask))
6250                  (message-y-or-n-p
6251                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
6252 You should normally obey the Mail-Followup-To: header.
6253
6254         `Mail-Followup-To: " mft "'
6255 directs your response to " (if (string-match "," mft)
6256                                "the specified addresses"
6257                              "that address only") " instead of news.
6258
6259 A typical situation where Mail-Followup-To is used is when the author thinks
6260 that further discussion should take place only in "
6261                              (if (string-match "," mft)
6262                                  "the specified mailing lists"
6263                                "that mailing list") ".")))
6264         (setq message-this-is-news nil
6265               distribution nil
6266               follow-to (list (cons 'To mft))))
6267        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
6268        (t
6269         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
6270
6271     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6272
6273     (setq message-reply-headers
6274           (make-full-mail-header-from-decoded-header
6275            0 subject from date message-id references 0 0 ""))
6276
6277     (message-setup
6278      `((Subject . ,subject)
6279        ,@follow-to
6280        ,@(and mct (list (cons 'Cc mct)))
6281        ,@(and distribution (list (cons 'Distribution distribution))))
6282      cur)))
6283
6284 ;;;###autoload
6285 (defun message-cancel-news (&optional arg)
6286   "Cancel an article you posted.
6287 If ARG, allow editing of the cancellation message."
6288   (interactive "P")
6289   (unless (message-news-p)
6290     (error "This is not a news article; canceling is impossible"))
6291   (let (from newsgroups message-id distribution buf sender)
6292     (save-excursion
6293       ;; Get header info from original article.
6294       (save-restriction
6295         (message-narrow-to-head-1)
6296         (setq from (message-fetch-field "from")
6297               sender (message-fetch-field "sender")
6298               newsgroups (message-fetch-field "newsgroups")
6299               message-id (message-fetch-field "message-id" t)
6300               distribution (message-fetch-field "distribution")))
6301       ;; Make sure that this article was written by the user.
6302       (unless (or
6303                ;; Canlock-logic as suggested by Per Abrahamsen
6304                ;; <abraham@dina.kvl.dk>
6305                ;;
6306                ;; IF article has cancel-lock THEN
6307                ;;   IF we can verify it THEN
6308                ;;     issue cancel
6309                ;;   ELSE
6310                ;;     error: cancellock: article is not yours
6311                ;; ELSE
6312                ;;   Use old rules, comparing sender...
6313                (if (message-fetch-field "Cancel-Lock")
6314                    (if (null (canlock-verify))
6315                        t
6316                      (error "Failed to verify Cancel-lock: This article is not yours"))
6317                  nil)
6318                (message-gnksa-enable-p 'cancel-messages)
6319                (and sender
6320                     (string-equal
6321                      (downcase sender)
6322                      (downcase (message-make-sender))))
6323                (string-equal
6324                 (downcase (cadr (std11-extract-address-components from)))
6325                 (downcase (cadr (std11-extract-address-components
6326                                  (message-make-from))))))
6327         (error "This article is not yours"))
6328       (when (yes-or-no-p "Do you really want to cancel this article? ")
6329         ;; Make control message.
6330         (if arg
6331             (message-news)
6332           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6333         (erase-buffer)
6334         (insert "Newsgroups: " newsgroups "\n"
6335                 "From: " from "\n"
6336                 "Subject: cmsg cancel " message-id "\n"
6337                 "Control: cancel " message-id "\n"
6338                 (if distribution
6339                     (concat "Distribution: " distribution "\n")
6340                   "")
6341                 mail-header-separator "\n"
6342                 message-cancel-message)
6343         (run-hooks 'message-cancel-hook)
6344         (unless arg
6345           (message "Canceling your article...")
6346           (if (let ((message-syntax-checks
6347                      'dont-check-for-anything-just-trust-me)
6348                     (message-encoding-buffer (current-buffer))
6349                     (message-edit-buffer (current-buffer)))
6350                 (message-send-news))
6351               (message "Canceling your article...done"))
6352           (kill-buffer buf))))))
6353
6354 (defun message-supersede-setup-for-mime-edit ()
6355   (set (make-local-variable 'message-setup-hook) nil)
6356   (mime-edit-again))
6357
6358 ;;;###autoload
6359 (defun message-supersede ()
6360   "Start composing a message to supersede the current message.
6361 This is done simply by taking the old article and adding a Supersedes
6362 header line with the old Message-ID."
6363   (interactive)
6364   (let ((cur (current-buffer))
6365         (sender (message-fetch-field "sender"))
6366         (from (message-fetch-field "from")))
6367     ;; Check whether the user owns the article that is to be superseded.
6368     (unless (or
6369              ;; Canlock-logic as suggested by Per Abrahamsen
6370              ;; <abraham@dina.kvl.dk>
6371              ;;
6372              ;; IF article has cancel-lock THEN
6373              ;;   IF we can verify it THEN
6374              ;;     issue cancel
6375              ;;   ELSE
6376              ;;     error: cancellock: article is not yours
6377              ;; ELSE
6378              ;;   Use old rules, comparing sender...
6379              (if (message-fetch-field "Cancel-Lock")
6380                  (if (null (canlock-verify))
6381                      t
6382                    (error "Failed to verify Cancel-lock: This article is not yours"))
6383                nil)
6384              (message-gnksa-enable-p 'cancel-messages)
6385              (and sender
6386                   (string-equal
6387                    (downcase sender)
6388                    (downcase (message-make-sender))))
6389              (string-equal
6390               (downcase (cadr (std11-extract-address-components from)))
6391               (downcase (cadr (std11-extract-address-components
6392                                (message-make-from))))))
6393       (error "This article is not yours"))
6394     ;; Get a normal message buffer.
6395     (message-pop-to-buffer (message-buffer-name "supersede"))
6396     (insert-buffer-substring cur)
6397     (message-narrow-to-head-1)
6398     ;; Remove unwanted headers.
6399     (when message-ignored-supersedes-headers
6400       (message-remove-header message-ignored-supersedes-headers t))
6401     (goto-char (point-min))
6402     (if (not (re-search-forward "^Message-ID: " nil t))
6403         (error "No Message-ID in this article")
6404       (replace-match "Supersedes: " t t))
6405     (goto-char (point-max))
6406     (insert mail-header-separator)
6407     (widen)
6408     (when message-supersede-setup-function
6409       (funcall message-supersede-setup-function))
6410     (run-hooks 'message-supersede-setup-hook)
6411     (goto-char (point-min))
6412     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
6413
6414 ;;;###autoload
6415 (defun message-recover ()
6416   "Reread contents of current buffer from its last auto-save file."
6417   (interactive)
6418   (let ((file-name (make-auto-save-file-name)))
6419     (cond ((save-window-excursion
6420              (if (not (eq system-type 'vax-vms))
6421                  (with-output-to-temp-buffer "*Directory*"
6422                    (with-current-buffer standard-output
6423                      (fundamental-mode)) ; for Emacs 20.4+
6424                    (buffer-disable-undo standard-output)
6425                    (let ((default-directory "/"))
6426                      (call-process
6427                       "ls" nil standard-output nil "-l" file-name))))
6428              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6429            (let ((buffer-read-only nil))
6430              (erase-buffer)
6431              (insert-file-contents file-name nil)))
6432           (t (error "message-recover cancelled")))))
6433
6434 ;;; Washing Subject:
6435
6436 (defun message-wash-subject (subject)
6437   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6438 Previous forwarders, replyers, etc. may add it."
6439   (with-temp-buffer
6440     (insert subject)
6441     (goto-char (point-min))
6442     ;; strip Re/Fwd stuff off the beginning
6443     (while (re-search-forward
6444             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6445       (replace-match ""))
6446
6447     ;; and gnus-style forwards [foo@bar.com] subject
6448     (goto-char (point-min))
6449     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6450       (replace-match ""))
6451
6452     ;; and off the end
6453     (goto-char (point-max))
6454     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6455       (replace-match ""))
6456
6457     ;; and finally, any whitespace that was left-over
6458     (goto-char (point-min))
6459     (while (re-search-forward "^[ \t]+" nil t)
6460       (replace-match ""))
6461     (goto-char (point-max))
6462     (while (re-search-backward "[ \t]+$" nil t)
6463       (replace-match ""))
6464
6465     (buffer-string)))
6466
6467 ;;; Forwarding messages.
6468
6469 (defvar message-forward-decoded-p nil
6470   "Non-nil means the original message is decoded.")
6471
6472 (defun message-forward-subject-author-subject (subject)
6473   "Generate a SUBJECT for a forwarded message.
6474 The form is: [Source] Subject, where if the original message was mail,
6475 Source is the sender, and if the original message was news, Source is
6476 the list of newsgroups is was posted to."
6477   (concat "["
6478           (let ((prefix (message-fetch-field "newsgroups")))
6479             (or prefix
6480                 (and (setq prefix (message-fetch-field "from"))
6481                      (nnheader-decode-from prefix))
6482                 "(nowhere)"))
6483           "] " subject))
6484
6485 (defun message-forward-subject-fwd (subject)
6486   "Generate a SUBJECT for a forwarded message.
6487 The form is: Fwd: Subject, where Subject is the original subject of
6488 the message."
6489   (concat "Fwd: " subject))
6490
6491 (defun message-make-forward-subject ()
6492   "Return a Subject header suitable for the message in the current buffer."
6493   (save-excursion
6494     (save-restriction
6495       (message-narrow-to-head-1)
6496       (let ((funcs message-make-forward-subject-function)
6497             (subject (message-fetch-field "Subject")))
6498         (setq subject
6499               (if subject
6500                   (if message-forward-decoded-p
6501                       subject
6502                     (nnheader-decode-subject subject))
6503                 ""))
6504         (if message-wash-forwarded-subjects
6505             (setq subject (message-wash-subject subject)))
6506         ;; Make sure funcs is a list.
6507         (and funcs
6508              (not (listp funcs))
6509              (setq funcs (list funcs)))
6510         ;; Apply funcs in order, passing subject generated by previous
6511         ;; func to the next one.
6512         (while funcs
6513           (when (message-functionp (car funcs))
6514             (setq subject (funcall (car funcs) subject)))
6515           (setq funcs (cdr funcs)))
6516         subject))))
6517
6518 ;;;###autoload
6519 (defun message-forward (&optional news)
6520   "Forward the current message via mail.
6521 Optional NEWS will use news to forward instead of mail."
6522   (interactive "P")
6523   (let ((cur (current-buffer))
6524         (subject (message-make-forward-subject)))
6525     (if news
6526         (message-news nil subject)
6527       (message-mail nil subject))
6528     (message-forward-make-body cur)))
6529
6530 ;;;###autoload
6531 (defun message-forward-make-body (forward-buffer)
6532   ;; Put point where we want it before inserting the forwarded
6533   ;; message.
6534   ;; Note that this function definition for T-gnus is totally different
6535   ;; from the original Gnus."
6536   (if message-forward-before-signature
6537       (message-goto-body)
6538     (goto-char (point-max)))
6539   ;; Make sure we're at the start of the line.
6540   (unless (bolp)
6541     (insert "\n"))
6542   ;; Narrow to the area we are to insert.
6543   (narrow-to-region (point) (point))
6544   ;; Insert the separators and the forwarded buffer.
6545   (insert message-forward-start-separator)
6546   (let ((art-beg (point)))
6547     (insert-buffer-substring forward-buffer)
6548     (goto-char (point-max))
6549     (insert message-forward-end-separator)
6550     (set-text-properties (point-min) (point-max) nil)
6551     ;; Remove all unwanted headers.
6552     (goto-char art-beg)
6553     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
6554                                   (1- (point))
6555                                 (point)))
6556     (goto-char (point-min))
6557     (message-remove-header message-included-forward-headers t nil t)
6558     (widen)
6559     (message-position-point)))
6560
6561 ;;;###autoload
6562 (defun message-forward-rmail-make-body (forward-buffer)
6563   (save-window-excursion
6564     (set-buffer forward-buffer)
6565     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
6566     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
6567     (if (rmail-msg-is-pruned)
6568         (rmail-msg-restore-non-pruned-header)))
6569   (message-forward-make-body forward-buffer))
6570
6571 ;;;###autoload
6572 (defun message-insinuate-rmail ()
6573   "Let RMAIL uses message to forward."
6574   (interactive)
6575   (setq rmail-enable-mime-composing t)
6576   (setq rmail-insert-mime-forwarded-message-function
6577         'message-forward-rmail-make-body))
6578
6579 ;;;###autoload
6580 (defun message-resend (address)
6581   "Resend the current article to ADDRESS."
6582   (interactive
6583    (list (message-read-from-minibuffer "Resend message to: ")))
6584   (message "Resending message to %s..." address)
6585   (save-excursion
6586     (let ((cur (current-buffer))
6587           beg)
6588       ;; We first set up a normal mail buffer.
6589       (unless (message-mail-user-agent)
6590         (set-buffer (get-buffer-create " *message resend*"))
6591         (erase-buffer))
6592       (let ((message-this-is-mail t)
6593             message-setup-hook)
6594         (message-setup `((To . ,address))))
6595       ;; Insert our usual headers.
6596       (message-generate-headers '(From Date To))
6597       (message-narrow-to-headers)
6598       ;; Remove X-Draft-From header etc.
6599       (message-remove-header message-ignored-mail-headers t)
6600       ;; Rename them all to "Resent-*".
6601       (goto-char (point-min))
6602       (while (re-search-forward "^[A-Za-z]" nil t)
6603         (forward-char -1)
6604         (insert "Resent-"))
6605       (widen)
6606       (forward-line)
6607       (delete-region (point) (point-max))
6608       (setq beg (point))
6609       ;; Insert the message to be resent.
6610       (insert-buffer-substring cur)
6611       (goto-char (point-min))
6612       (search-forward "\n\n")
6613       (forward-char -1)
6614       (save-restriction
6615         (narrow-to-region beg (point))
6616         (message-remove-header message-ignored-resent-headers t)
6617         (goto-char (point-max)))
6618       (insert mail-header-separator)
6619       ;; Rename all old ("Also-")Resent headers.
6620       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6621         (beginning-of-line)
6622         (insert "Also-"))
6623       ;; Quote any "From " lines at the beginning.
6624       (goto-char beg)
6625       (when (looking-at "From ")
6626         (replace-match "X-From-Line: "))
6627       ;; Send it.
6628       (let ((message-encoding-buffer (current-buffer))
6629             (message-edit-buffer (current-buffer))
6630             message-required-mail-headers)
6631         (message-send-mail))
6632       (kill-buffer (current-buffer)))
6633     (message "Resending message to %s...done" address)))
6634
6635 (defun message-bounce-setup-for-mime-edit ()
6636   (set (make-local-variable 'message-setup-hook) nil)
6637   (mime-edit-again))
6638
6639 ;;;###autoload
6640 (defun message-bounce ()
6641   "Re-mail the current message.
6642 This only makes sense if the current message is a bounce message that
6643 contains some mail you have written which has been bounced back to
6644 you."
6645   (interactive)
6646   (let ((cur (current-buffer))
6647         boundary)
6648     (message-pop-to-buffer (message-buffer-name "bounce"))
6649     (insert-buffer-substring cur)
6650     (undo-boundary)
6651     (message-narrow-to-head)
6652     (if (and (message-fetch-field "MIME-Version")
6653              (setq boundary (message-fetch-field "Content-Type")))
6654         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
6655             (setq boundary (concat (match-string 1 boundary) " *\n"
6656                                    "Content-Type: message/rfc822"))
6657           (setq boundary nil)))
6658     (widen)
6659     (goto-char (point-min))
6660     (search-forward "\n\n" nil t)
6661     (if (or (and boundary
6662                  (re-search-forward boundary nil t)
6663                  (forward-line 2))
6664             (and (re-search-forward message-unsent-separator nil t)
6665                  (forward-line 1))
6666             (re-search-forward "^Return-Path:.*\n" nil t))
6667         ;; We remove everything before the bounced mail.
6668         (delete-region
6669          (point-min)
6670          (if (re-search-forward "^[^ \n\t]+:" nil t)
6671              (match-beginning 0)
6672            (point)))
6673       (when (re-search-backward "^.?From .*\n" nil t)
6674         (delete-region (match-beginning 0) (match-end 0))))
6675     (save-restriction
6676       (message-narrow-to-head-1)
6677       (message-remove-header message-ignored-bounced-headers t)
6678       (goto-char (point-max))
6679       (insert mail-header-separator))
6680     (when message-bounce-setup-function
6681       (funcall message-bounce-setup-function))
6682     (run-hooks 'message-bounce-setup-hook)
6683     (message-position-point)))
6684
6685 ;;;
6686 ;;; Interactive entry points for new message buffers.
6687 ;;;
6688
6689 ;;;###autoload
6690 (defun message-mail-other-window (&optional to subject)
6691   "Like `message-mail' command, but display mail buffer in another window."
6692   (interactive)
6693   (unless (message-mail-user-agent)
6694     (let ((pop-up-windows t)
6695           (special-display-buffer-names nil)
6696           (special-display-regexps nil)
6697           (same-window-buffer-names nil)
6698           (same-window-regexps nil))
6699       (message-pop-to-buffer (message-buffer-name "mail" to))))
6700   (let ((message-this-is-mail t))
6701     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6702                    nil nil 'switch-to-buffer-other-window)))
6703
6704 ;;;###autoload
6705 (defun message-mail-other-frame (&optional to subject)
6706   "Like `message-mail' command, but display mail buffer in another frame."
6707   (interactive)
6708   (unless (message-mail-user-agent)
6709     (let ((pop-up-frames t)
6710           (special-display-buffer-names nil)
6711           (special-display-regexps nil)
6712           (same-window-buffer-names nil)
6713           (same-window-regexps nil))
6714       (message-pop-to-buffer (message-buffer-name "mail" to))))
6715   (let ((message-this-is-mail t))
6716     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6717                    nil nil 'switch-to-buffer-other-frame)))
6718
6719 ;;;###autoload
6720 (defun message-news-other-window (&optional newsgroups subject)
6721   "Start editing a news article to be sent."
6722   (interactive)
6723   (let ((pop-up-windows t)
6724         (special-display-buffer-names nil)
6725         (special-display-regexps nil)
6726         (same-window-buffer-names nil)
6727         (same-window-regexps nil))
6728     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6729   (let ((message-this-is-news t))
6730     (message-setup `((Newsgroups . ,(or newsgroups ""))
6731                      (Subject . ,(or subject ""))))))
6732
6733 ;;;###autoload
6734 (defun message-news-other-frame (&optional newsgroups subject)
6735   "Start editing a news article to be sent."
6736   (interactive)
6737   (let ((pop-up-frames t)
6738         (special-display-buffer-names nil)
6739         (special-display-regexps nil)
6740         (same-window-buffer-names nil)
6741         (same-window-regexps nil))
6742     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6743   (let ((message-this-is-news t))
6744     (message-setup `((Newsgroups . ,(or newsgroups ""))
6745                      (Subject . ,(or subject ""))))))
6746
6747 ;;; underline.el
6748
6749 ;; This code should be moved to underline.el (from which it is stolen).
6750
6751 ;;;###autoload
6752 (defun bold-region (start end)
6753   "Bold all nonblank characters in the region.
6754 Works by overstriking characters.
6755 Called from program, takes two arguments START and END
6756 which specify the range to operate on."
6757   (interactive "r")
6758   (save-excursion
6759     (let ((end1 (make-marker)))
6760       (move-marker end1 (max start end))
6761       (goto-char (min start end))
6762       (while (< (point) end1)
6763         (or (looking-at "[_\^@- ]")
6764             (insert (char-after) "\b"))
6765         (forward-char 1)))))
6766
6767 ;;;###autoload
6768 (defun unbold-region (start end)
6769   "Remove all boldness (overstruck characters) in the region.
6770 Called from program, takes two arguments START and END
6771 which specify the range to operate on."
6772   (interactive "r")
6773   (save-excursion
6774     (let ((end1 (make-marker)))
6775       (move-marker end1 (max start end))
6776       (goto-char (min start end))
6777       (while (re-search-forward "\b" end1 t)
6778         (if (eq (char-after) (char-after (- (point) 2)))
6779             (delete-char -2))))))
6780
6781 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
6782
6783 ;; Support for toolbar
6784 (eval-when-compile
6785   (defvar tool-bar-map)
6786   (defvar tool-bar-mode))
6787
6788 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6789   ;; We need to make tool bar entries in local keymaps with
6790   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6791   (if (fboundp 'tool-bar-local-item-from-menu)
6792       ;; This is for Emacs 21.3
6793       (tool-bar-local-item-from-menu command icon in-map from-map props)
6794     (tool-bar-add-item-from-menu command icon from-map props)))
6795
6796 (defun message-tool-bar-map ()
6797   (or message-tool-bar-map
6798       (setq message-tool-bar-map
6799             (and
6800              (condition-case nil (require 'tool-bar) (error nil))
6801              (fboundp 'tool-bar-add-item-from-menu)
6802              tool-bar-mode
6803              (let ((tool-bar-map (copy-keymap tool-bar-map))
6804                    (load-path (mm-image-load-path)))
6805                ;; Zap some items which aren't so relevant and take
6806                ;; up space.
6807                (dolist (key '(print-buffer kill-buffer save-buffer
6808                                            write-file dired open-file))
6809                  (define-key tool-bar-map (vector key) nil))
6810                (message-tool-bar-local-item-from-menu
6811                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
6812                (message-tool-bar-local-item-from-menu
6813                 'message-kill-buffer "close" tool-bar-map message-mode-map)
6814                (message-tool-bar-local-item-from-menu
6815                 'message-dont-send "cancel" tool-bar-map message-mode-map)
6816 ;;             (message-tool-bar-local-item-from-menu
6817 ;;              'mime-edit-insert-file "attach"
6818 ;;              tool-bar-map mime-edit-mode-map)
6819                (message-tool-bar-local-item-from-menu
6820                 'ispell-message "spell" tool-bar-map message-mode-map)
6821 ;;             (message-tool-bar-local-item-from-menu
6822 ;;              'mime-edit-preview-message "preview"
6823 ;;              tool-bar-map mime-edit-mode-map)
6824                (message-tool-bar-local-item-from-menu
6825                 'message-insert-importance-high "important"
6826                 tool-bar-map message-mode-map)
6827                (message-tool-bar-local-item-from-menu
6828                 'message-insert-importance-low "unimportant"
6829                 tool-bar-map message-mode-map)
6830                (message-tool-bar-local-item-from-menu
6831                 'message-insert-disposition-notification-to "receipt"
6832                 tool-bar-map message-mode-map)
6833                tool-bar-map)))))
6834
6835 ;;; Group name completion.
6836
6837 (defcustom message-newgroups-header-regexp
6838   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6839   "Regexp that match headers that lists groups."
6840   :group 'message
6841   :type 'regexp)
6842
6843 (defcustom message-completion-alist
6844   (list (cons message-newgroups-header-regexp 'message-expand-group)
6845         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6846         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6847           . message-expand-name)
6848         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6849           . message-expand-name))
6850   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6851   :group 'message
6852   :type '(alist :key-type regexp :value-type function))
6853
6854 (defcustom message-expand-name-function
6855   (if (fboundp 'bbdb-complete-name)
6856       'bbdb-complete-name
6857     (if (fboundp 'lsdb-complete-name)
6858         'lsdb-complete-name
6859       'expand-abbrev))
6860   "*A function called to expand addresses in field body."
6861   :group 'message
6862   :type 'function)
6863
6864 (defcustom message-tab-body-function nil
6865   "*Function to execute when `message-tab' (TAB) is executed in the body.
6866 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6867   :group 'message
6868   :type 'function)
6869
6870 (defun message-tab ()
6871   "Complete names according to `message-completion-alist'.
6872 Execute function specified by `message-tab-body-function' when not in
6873 those headers."
6874   (interactive)
6875   (let ((alist message-completion-alist))
6876     (while (and alist
6877                 (let ((mail-abbrev-mode-regexp (caar alist)))
6878                   (not (mail-abbrev-in-expansion-header-p))))
6879       (setq alist (cdr alist)))
6880     (funcall (or (cdar alist) message-tab-body-function
6881                  (lookup-key text-mode-map "\t")
6882                  (lookup-key global-map "\t")
6883                  'indent-relative))))
6884
6885 (defun message-expand-group ()
6886   "Expand the group name under point."
6887   (let* ((b (save-excursion
6888               (save-restriction
6889                 (narrow-to-region
6890                  (save-excursion
6891                    (beginning-of-line)
6892                    (skip-chars-forward "^:")
6893                    (1+ (point)))
6894                  (point))
6895                 (skip-chars-backward "^, \t\n") (point))))
6896          (completion-ignore-case t)
6897          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6898                                             (point))))
6899          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6900          (completions (all-completions string hashtb))
6901          comp)
6902     (delete-region b (point))
6903     (cond
6904      ((= (length completions) 1)
6905       (if (string= (car completions) string)
6906           (progn
6907             (insert string)
6908             (message "Only matching group"))
6909         (insert (car completions))))
6910      ((and (setq comp (try-completion string hashtb))
6911            (not (string= comp string)))
6912       (insert comp))
6913      (t
6914       (insert string)
6915       (if (not comp)
6916           (message "No matching groups")
6917         (save-selected-window
6918           (pop-to-buffer "*Completions*")
6919           (buffer-disable-undo)
6920           (let ((buffer-read-only nil))
6921             (erase-buffer)
6922             (let ((standard-output (current-buffer)))
6923               (display-completion-list (sort completions 'string<)))
6924             (goto-char (point-min))
6925             (delete-region (point) (progn (forward-line 3) (point))))))))))
6926
6927 (defun message-expand-name ()
6928   (funcall message-expand-name-function))
6929
6930 ;;; Help stuff.
6931
6932 (defun message-talkative-question (ask question show &rest text)
6933   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6934 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6935 The following arguments may contain lists of values."
6936   (if (and show
6937            (setq text (message-flatten-list text)))
6938       (save-window-excursion
6939         (save-excursion
6940           (with-output-to-temp-buffer " *MESSAGE information message*"
6941             (set-buffer " *MESSAGE information message*")
6942             (fundamental-mode)          ; for Emacs 20.4+
6943             (mapcar 'princ text)
6944             (goto-char (point-min))))
6945         (funcall ask question))
6946     (funcall ask question)))
6947
6948 (defun message-flatten-list (list)
6949   "Return a new, flat list that contains all elements of LIST.
6950
6951 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6952 => (1 2 3 4 5 6 7)"
6953   (cond ((consp list)
6954          (apply 'append (mapcar 'message-flatten-list list)))
6955         (list
6956          (list list))))
6957
6958 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6959   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6960 Then clone the local variables and values from the old buffer to the
6961 new one, cloning only the locals having a substring matching the
6962 regexp varstr."
6963   (let ((oldbuf (current-buffer)))
6964     (save-excursion
6965       (set-buffer (generate-new-buffer name))
6966       (message-clone-locals oldbuf varstr)
6967       (current-buffer))))
6968
6969 (defun message-clone-locals (buffer &optional varstr)
6970   "Clone the local variables from BUFFER to the current buffer."
6971   (let ((locals (save-excursion
6972                   (set-buffer buffer)
6973                   (buffer-local-variables)))
6974         (regexp
6975          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
6976     (mapcar
6977      (lambda (local)
6978        (when (and (consp local)
6979                   (car local)
6980                   (string-match regexp (symbol-name (car local)))
6981                   (or (null varstr)
6982                       (string-match varstr (symbol-name (car local)))))
6983          (ignore-errors
6984            (set (make-local-variable (car local))
6985                 (cdr local)))))
6986      locals)))
6987
6988
6989 ;;; @ for MIME Edit mode
6990 ;;;
6991
6992 (defun message-maybe-encode ()
6993   (when message-mime-mode
6994     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
6995     (let ((pgp-processing (with-current-buffer message-edit-buffer
6996                             mime-edit-pgp-processing)))
6997       (setq mime-edit-pgp-processing pgp-processing))
6998     (run-hooks 'mime-edit-translate-hook)
6999     (if (catch 'mime-edit-error
7000           (save-excursion
7001             (mime-edit-pgp-enclose-buffer)
7002             (mime-edit-translate-body)))
7003         (error "Translation error!"))
7004     (run-hooks 'mime-edit-exit-hook)))
7005
7006 (defun message-mime-insert-article (&optional full-headers)
7007   (interactive "P")
7008   (let ((message-cite-function 'mime-edit-inserted-message-filter)
7009         (message-reply-buffer
7010          (message-get-parameter-with-eval 'original-buffer))
7011         (start (point)))
7012     (message-yank-original nil)
7013     (save-excursion
7014       (narrow-to-region (goto-char start)
7015                         (if (search-forward "\n\n" nil t)
7016                             (1- (point))
7017                           (point-max)))
7018       (goto-char (point-min))
7019       (let ((message-included-forward-headers
7020              (if full-headers "" message-included-forward-headers)))
7021         (message-remove-header message-included-forward-headers t nil t))
7022       (widen))))
7023
7024 (set-alist 'mime-edit-message-inserter-alist
7025            'message-mode (function message-mime-insert-article))
7026
7027 ;;; Miscellaneous functions
7028
7029 ;; stolen (and renamed) from nnheader.el
7030 (static-if (fboundp 'subst-char-in-string)
7031     (defsubst message-replace-chars-in-string (string from to)
7032       (subst-char-in-string from to string))
7033   (defun message-replace-chars-in-string (string from to)
7034     "Replace characters in STRING from FROM to TO."
7035     (let ((string (substring string 0)) ;Copy string.
7036           (len (length string))
7037           (idx 0))
7038       ;; Replace all occurrences of FROM with TO.
7039       (while (< idx len)
7040         (when (= (aref string idx) from)
7041           (aset string idx to))
7042         (setq idx (1+ idx)))
7043       string)))
7044
7045 ;;;
7046 ;;; MIME functions
7047 ;;;
7048
7049 (defvar message-inhibit-body-encoding t)
7050
7051 (defun message-encode-message-body ()
7052   (unless message-inhibit-body-encoding
7053     (let ((mail-parse-charset (or mail-parse-charset
7054                                   message-default-charset))
7055           (case-fold-search t)
7056           lines content-type-p)
7057       (message-goto-body)
7058       (save-restriction
7059         (narrow-to-region (point) (point-max))
7060         (let ((new (mml-generate-mime)))
7061           (when new
7062             (delete-region (point-min) (point-max))
7063             (insert new)
7064             (goto-char (point-min))
7065             (if (eq (aref new 0) ?\n)
7066                 (delete-char 1)
7067               (search-forward "\n\n")
7068               (setq lines (buffer-substring (point-min) (1- (point))))
7069               (delete-region (point-min) (point))))))
7070       (save-restriction
7071         (message-narrow-to-headers-or-head)
7072         (message-remove-header "Mime-Version")
7073         (goto-char (point-max))
7074         (insert "MIME-Version: 1.0\n")
7075         (when lines
7076           (insert lines))
7077         (setq content-type-p
7078               (or mml-boundary
7079                   (re-search-backward "^Content-Type:" nil t))))
7080       (save-restriction
7081         (message-narrow-to-headers-or-head)
7082         (message-remove-first-header "Content-Type")
7083         (message-remove-first-header "Content-Transfer-Encoding"))
7084       ;; We always make sure that the message has a Content-Type
7085       ;; header.  This is because some broken MTAs and MUAs get
7086       ;; awfully confused when confronted with a message with a
7087       ;; MIME-Version header and without a Content-Type header.  For
7088       ;; instance, Solaris' /usr/bin/mail.
7089       (unless content-type-p
7090         (goto-char (point-min))
7091         ;; For unknown reason, MIME-Version doesn't exist.
7092         (when (re-search-forward "^MIME-Version:" nil t)
7093           (forward-line 1)
7094           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7095
7096 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7097   "Read from the minibuffer while providing abbrev expansion."
7098   (if (fboundp 'mail-abbrevs-setup)
7099       (let ((mail-abbrev-mode-regexp "")
7100             (minibuffer-setup-hook 'mail-abbrevs-setup)
7101             (minibuffer-local-map message-minibuffer-local-map))
7102         (read-from-minibuffer prompt initial-contents))
7103     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7104           (minibuffer-local-map message-minibuffer-local-map))
7105       (read-string prompt initial-contents))))
7106
7107 (defun message-use-alternative-email-as-from ()
7108   (require 'mail-utils)
7109   (let* ((fields '("To" "Cc"))
7110          (emails
7111           (split-string
7112            (mail-strip-quoted-names
7113             (mapconcat 'message-fetch-reply-field fields ","))
7114            "[ \f\t\n\r\v,]+"))
7115          email)
7116     (while emails
7117       (if (string-match message-alternative-emails (car emails))
7118           (setq email (car emails)
7119                 emails nil))
7120       (pop emails))
7121     (unless (or (not email) (equal email user-mail-address))
7122       (goto-char (point-max))
7123       (insert "From: " email "\n"))))
7124
7125 (defun message-options-get (symbol)
7126   (cdr (assq symbol message-options)))
7127
7128 (defun message-options-set (symbol value)
7129   (let ((the-cons (assq symbol message-options)))
7130     (if the-cons
7131         (if value
7132             (setcdr the-cons value)
7133           (setq message-options (delq the-cons message-options)))
7134       (and value
7135            (push (cons symbol value) message-options))))
7136   value)
7137
7138 (defun message-options-set-recipient ()
7139   (save-restriction
7140     (message-narrow-to-headers-or-head)
7141     (message-options-set 'message-sender
7142                          (mail-strip-quoted-names
7143                           (message-fetch-field "from")))
7144     (message-options-set 'message-recipients
7145                          (mail-strip-quoted-names
7146                           (let ((to (message-fetch-field "to"))
7147                                 (cc (message-fetch-field "cc"))
7148                                 (bcc (message-fetch-field "bcc")))
7149                             (concat
7150                              (or to "")
7151                              (if (and to cc) ", ")
7152                              (or cc "")
7153                              (if (and (or to cc) bcc) ", ")
7154                              (or bcc "")))))))
7155
7156 (when (featurep 'xemacs)
7157   (require 'messagexmas)
7158   (message-xmas-redefine))
7159
7160 (provide 'message)
7161
7162 (run-hooks 'message-load-hook)
7163
7164 ;; Local Variables:
7165 ;; coding: iso-8859-1
7166 ;; End:
7167
7168 ;;; message.el ends here