T-gnus 6.15.16 r00.
[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 "bcc")
3994                            (message-fetch-field "to"))
3995                        (let ((ct (mime-read-Content-Type)))
3996                          (or (not ct)
3997                              (and (eq 'text (cdr (assq 'type ct)))
3998                                   (eq 'plain (cdr (assq 'subtype ct))))))))
3999               (message-insert-courtesy-copy))
4000             (setq failure (message-maybe-split-and-send-mail)))
4001         (kill-buffer tembuf))
4002       (set-buffer message-edit-buffer)
4003       (if failure
4004           (progn
4005             (message "Couldn't send message via mail: %s" failure)
4006             nil)
4007         (push 'mail message-sent-message-via)))))
4008
4009 (defun message-send-mail-with-sendmail ()
4010   "Send off the prepared buffer with sendmail."
4011   (let ((errbuf (if message-interactive
4012                     (message-generate-new-buffer-clone-locals
4013                      " sendmail errors")
4014                   0))
4015         resend-to-addresses delimline)
4016     (unwind-protect
4017         (progn
4018           (let ((case-fold-search t))
4019             (save-restriction
4020               (message-narrow-to-headers)
4021               (setq resend-to-addresses (message-fetch-field "resent-to")))
4022             ;; Change header-delimiter to be what sendmail expects.
4023             (goto-char (point-min))
4024             (re-search-forward
4025              (concat "^" (regexp-quote mail-header-separator) "\n"))
4026             (replace-match "\n")
4027             (backward-char 1)
4028             (setq delimline (point-marker))
4029             (run-hooks 'message-send-mail-hook)
4030             ;; Insert an extra newline if we need it to work around
4031             ;; Sun's bug that swallows newlines.
4032             (goto-char (1+ delimline))
4033             (when (eval message-mailer-swallows-blank-line)
4034               (newline))
4035             (when message-interactive
4036               (save-excursion
4037                 (set-buffer errbuf)
4038                 (erase-buffer))))
4039           (let* ((default-directory "/")
4040                  (cpr (as-binary-process
4041                        (apply
4042                         'call-process-region
4043                         (append
4044                          (list (point-min) (point-max)
4045                                (if (boundp 'sendmail-program)
4046                                    sendmail-program
4047                                  "/usr/lib/sendmail")
4048                                nil errbuf nil "-oi")
4049                          ;; Always specify who from,
4050                          ;; since some systems have broken sendmails.
4051                          ;; But some systems are more broken with -f, so
4052                          ;; we'll let users override this.
4053                          (if (null message-sendmail-f-is-evil)
4054                              (list "-f" (message-sendmail-envelope-from)))
4055                          ;; These mean "report errors by mail"
4056                          ;; and "deliver in background".
4057                          (if (null message-interactive) '("-oem" "-odb"))
4058                          ;; Get the addresses from the message
4059                          ;; unless this is a resend.
4060                          ;; We must not do that for a resend
4061                          ;; because we would find the original addresses.
4062                          ;; For a resend, include the specific addresses.
4063                          (if resend-to-addresses
4064                              (list resend-to-addresses)
4065                            '("-t")))))))
4066             (unless (or (null cpr) (zerop cpr))
4067               (error "Sending...failed with exit value %d" cpr)))
4068           (when message-interactive
4069             (save-excursion
4070               (set-buffer errbuf)
4071               (goto-char (point-min))
4072               (while (re-search-forward "\n\n* *" nil t)
4073                 (replace-match "; "))
4074               (if (not (zerop (buffer-size)))
4075                   (error "Sending...failed to %s"
4076                          (buffer-string))))))
4077       (when (bufferp errbuf)
4078         (kill-buffer errbuf)))))
4079
4080 (defun message-send-mail-with-qmail ()
4081   "Pass the prepared message buffer to qmail-inject.
4082 Refer to the documentation for the variable `message-send-mail-function'
4083 to find out how to use this."
4084   ;; replace the header delimiter with a blank line
4085   (goto-char (point-min))
4086   (re-search-forward
4087    (concat "^" (regexp-quote mail-header-separator) "\n"))
4088   (replace-match "\n")
4089   (backward-char 1)
4090   (run-hooks 'message-send-mail-hook)
4091   ;; send the message
4092   (case
4093       (as-binary-process
4094        (apply
4095         'call-process-region 1 (point-max) message-qmail-inject-program
4096         nil nil nil
4097         ;; qmail-inject's default behaviour is to look for addresses on the
4098         ;; command line; if there're none, it scans the headers.
4099         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4100         ;;
4101         ;; in general, ALL of qmail-inject's defaults are perfect for simply
4102         ;; reading a formatted (i. e., at least a To: or Resent-To header)
4103         ;; message from stdin.
4104         ;;
4105         ;; qmail also has the advantage of not having been raped by
4106         ;; various vendors, so we don't have to allow for that, either --
4107         ;; compare this with message-send-mail-with-sendmail and weep
4108         ;; for sendmail's lost innocence.
4109         ;;
4110         ;; all this is way cool coz it lets us keep the arguments entirely
4111         ;; free for -inject-arguments -- a big win for the user and for us
4112         ;; since we don't have to play that double-guessing game and the user
4113         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4114         (if (functionp message-qmail-inject-args)
4115             (funcall message-qmail-inject-args)
4116           message-qmail-inject-args)))
4117     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4118     ;; we have to look at the retval instead
4119     (0 nil)
4120     (100 (error "qmail-inject reported permanent failure"))
4121     (111 (error "qmail-inject reported transient failure"))
4122     ;; should never happen
4123     (t   (error "qmail-inject reported unknown failure"))))
4124
4125 (defun message-send-mail-with-mh ()
4126   "Send the prepared message buffer with mh."
4127   (let ((mh-previous-window-config nil)
4128         (name (mh-new-draft-name)))
4129     (setq buffer-file-name name)
4130     ;; MH wants to generate these headers itself.
4131     (when message-mh-deletable-headers
4132       (let ((headers message-mh-deletable-headers))
4133         (while headers
4134           (goto-char (point-min))
4135           (and (re-search-forward
4136                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4137                (message-delete-line))
4138           (pop headers))))
4139     (run-hooks 'message-send-mail-hook)
4140     ;; Pass it on to mh.
4141     (mh-send-letter)))
4142
4143 (defun message-send-mail-with-smtp ()
4144   "Send off the prepared buffer with SMTP."
4145   (require 'smtp) ; XXX
4146   (let ((case-fold-search t)
4147         recipients)
4148     (save-restriction
4149       (message-narrow-to-headers)
4150       (setq recipients
4151             ;; XXX: Should be replaced by better one.
4152             (smtp-deduce-address-list (current-buffer)
4153                                       (point-min) (point-max)))
4154       ;; Remove BCC lines.
4155       (message-remove-header "bcc"))
4156     ;; replace the header delimiter with a blank line.
4157     (goto-char (point-min))
4158     (re-search-forward
4159      (concat "^" (regexp-quote mail-header-separator) "\n"))
4160     (replace-match "\n")
4161     (backward-char 1)
4162     (run-hooks 'message-send-mail-hook)
4163     (if recipients
4164         (smtp-send-buffer user-mail-address recipients (current-buffer))
4165       (error "Sending failed; no recipients"))))
4166
4167 (defsubst message-maybe-split-and-send-news (method)
4168   "Split a message if necessary, and send it via news.
4169 Returns nil if sending succeeded, returns t if sending failed.
4170 This sub function is for exclusive use of `message-send-news'."
4171   (let ((mime-edit-split-ignored-field-regexp
4172          mime-edit-split-ignored-field-regexp)
4173         (case-fold-search t))
4174     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4175       (setq mime-edit-split-ignored-field-regexp
4176             (concat (substring mime-edit-split-ignored-field-regexp
4177                                0 (match-beginning 0))
4178                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4179                     "_so_don't_rape_it!"
4180                     (substring mime-edit-split-ignored-field-regexp
4181                                (match-end 0)))))
4182     (or
4183      (catch 'message-sending-news-failure
4184        (mime-edit-maybe-split-and-send
4185         (function
4186          (lambda ()
4187            (interactive)
4188            (save-restriction
4189              (std11-narrow-to-header mail-header-separator)
4190              (goto-char (point-min))
4191              (when (re-search-forward "^Message-ID:" nil t)
4192                (delete-region (match-end 0) (std11-field-end))
4193                (insert " " (message-make-message-id))))
4194            (unless (funcall message-send-news-function method)
4195              (throw 'message-sending-news-failure t)))))
4196        nil)
4197      (not (funcall message-send-news-function method)))))
4198
4199 (defun message-smtpmail-send-it ()
4200   "Send the prepared message buffer with `smtpmail-send-it'.
4201 This only differs from `smtpmail-send-it' that this command evaluates
4202 `message-send-mail-hook' just before sending a message.  It is useful
4203 if your ISP requires the POP-before-SMTP authentication.  See the
4204 documentation for the function `mail-source-touch-pop'."
4205   (run-hooks 'message-send-mail-hook)
4206   (smtpmail-send-it))
4207
4208 (defun message-canlock-generate ()
4209   "Return a string that is non-trival to guess.
4210 Do not use this for anything important, it is cryptographically weak."
4211   (let (sha1-maximum-internal-length)
4212     (sha1 (concat (message-unique-id)
4213                   (format "%x%x%x" (random) (random t) (random))
4214                   (prin1-to-string (recent-keys))
4215                   (prin1-to-string (garbage-collect))))))
4216
4217 (defun message-canlock-password ()
4218   "The password used by message for cancel locks.
4219 This is the value of `canlock-password', if that option is non-nil.
4220 Otherwise, generate and save a value for `canlock-password' first."
4221   (unless canlock-password
4222     (customize-save-variable 'canlock-password (message-canlock-generate))
4223     (setq canlock-password-for-verify canlock-password))
4224   canlock-password)
4225
4226 (defun message-insert-canlock ()
4227   (when message-insert-canlock
4228     (message-canlock-password)
4229     (canlock-insert-header)))
4230
4231 (defun message-send-news (&optional arg)
4232   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4233          (case-fold-search nil)
4234          (method (if (message-functionp message-post-method)
4235                      (funcall message-post-method arg)
4236                    message-post-method))
4237          (newsgroups-field (save-restriction
4238                              (message-narrow-to-headers-or-head)
4239                              (message-fetch-field "Newsgroups")))
4240          (followup-field (save-restriction
4241                            (message-narrow-to-headers-or-head)
4242                            (message-fetch-field "Followup-To")))
4243          ;; BUG: We really need to get the charset for each name in the
4244          ;; Newsgroups and Followup-To lines to allow crossposting
4245          ;; between group namess with incompatible character sets.
4246          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4247          (group-field-charset
4248           (gnus-group-name-charset method newsgroups-field))
4249          (followup-field-charset
4250           (gnus-group-name-charset method (or followup-field "")))
4251          (mime-field-encoding-method-alist
4252           (append (when group-field-charset
4253                     (list (cons "Newsgroups" group-field-charset)))
4254                   (when followup-field-charset
4255                     (list (cons "Followup-To" followup-field-charset)))
4256                   mime-field-encoding-method-alist))
4257          (message-syntax-checks
4258           (if (and arg
4259                    (listp message-syntax-checks))
4260               (cons '(existing-newsgroups . disabled)
4261                     message-syntax-checks)
4262             message-syntax-checks))
4263          (message-this-is-news t)
4264          result)
4265     (save-restriction
4266       (message-narrow-to-headers)
4267       ;; Insert some headers.
4268       (message-generate-headers message-required-news-headers)
4269       (message-insert-canlock)
4270       ;; Let the user do all of the above.
4271       (run-hooks 'message-header-hook))
4272     ;; Note: This check will be disabled by the ".*" default value for
4273     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4274     (when (and group-field-charset
4275                (listp message-syntax-checks))
4276       (setq message-syntax-checks
4277             (cons '(valid-newsgroups . disabled)
4278                   message-syntax-checks)))
4279     (message-cleanup-headers)
4280     (if (not (let ((message-post-method method))
4281                (message-check-news-syntax)))
4282         nil
4283       (unwind-protect
4284           (save-excursion
4285             (set-buffer tembuf)
4286             (buffer-disable-undo)
4287             (erase-buffer)
4288             (insert-buffer-substring message-encoding-buffer)
4289             ;; Remove some headers.
4290             (save-restriction
4291               (message-narrow-to-headers)
4292 ;; We Semi-gnus people have no use for it.
4293 ;;            ;; We (re)generate the Lines header.
4294 ;;            (when (memq 'Lines message-required-mail-headers)
4295 ;;              (message-generate-headers '(Lines)))
4296               ;; Remove some headers.
4297               (message-remove-header message-ignored-news-headers t))
4298             (goto-char (point-max))
4299             ;; require one newline at the end.
4300             (or (= (preceding-char) ?\n)
4301                 (insert ?\n))
4302             (setq result (message-maybe-split-and-send-news method)))
4303         (kill-buffer tembuf))
4304       (set-buffer message-edit-buffer)
4305       (if result
4306           (progn
4307             (message "Couldn't send message via news: %s"
4308                      (nnheader-get-report (car method)))
4309             nil)
4310         (push 'news message-sent-message-via)))))
4311
4312 ;; 1997-09-29 by MORIOKA Tomohiko
4313 (defun message-send-news-with-gnus (method)
4314   (let ((case-fold-search t))
4315     ;; Remove the delimiter.
4316     (goto-char (point-min))
4317     (re-search-forward
4318      (concat "^" (regexp-quote mail-header-separator) "\n"))
4319     (replace-match "\n")
4320     (backward-char 1)
4321     (run-hooks 'message-send-news-hook)
4322     (gnus-open-server method)
4323     (message "Sending news via %s..." (gnus-server-string method))
4324     (gnus-request-post method)
4325     ))
4326
4327 ;;;
4328 ;;; Header generation & syntax checking.
4329 ;;;
4330
4331 (defun message-check-element (type)
4332   "Return non-nil if this TYPE is not to be checked."
4333   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4334       t
4335     (let ((able (assq type message-syntax-checks)))
4336       (and (consp able)
4337            (eq (cdr able) 'disabled)))))
4338
4339 (defun message-check-news-syntax ()
4340   "Check the syntax of the message."
4341   (save-excursion
4342     (save-restriction
4343       (widen)
4344       (and
4345        ;; We narrow to the headers and check them first.
4346        (save-excursion
4347          (save-restriction
4348            (message-narrow-to-headers)
4349            (message-check-news-header-syntax)))
4350        ;; Check the body.
4351        (save-excursion
4352          (set-buffer message-edit-buffer)
4353          (message-check-news-body-syntax))))))
4354
4355 (defun message-check-news-header-syntax ()
4356   (and
4357    ;; Check Newsgroups header.
4358    (message-check 'newsgroups
4359      (let ((group (message-fetch-field "newsgroups")))
4360        (or
4361         (and group
4362              (not (string-match "\\`[ \t]*\\'" group)))
4363         (ignore
4364          (message
4365           "The newsgroups field is empty or missing.  Posting is denied.")))))
4366    ;; Check the Subject header.
4367    (message-check 'subject
4368      (let* ((case-fold-search t)
4369             (subject (message-fetch-field "subject")))
4370        (or
4371         (and subject
4372              (not (string-match "\\`[ \t]*\\'" subject)))
4373         (ignore
4374          (message
4375           "The subject field is empty or missing.  Posting is denied.")))))
4376    ;; Check for commands in Subject.
4377    (message-check 'subject-cmsg
4378      (if (string-match "^cmsg " (message-fetch-field "subject"))
4379          (y-or-n-p
4380           "The control code \"cmsg\" is in the subject.  Really post? ")
4381        t))
4382    ;; Check long header lines.
4383    (message-check 'long-header-lines
4384      (let ((start (point))
4385            (header nil)
4386            (length 0)
4387            found)
4388        (while (and (not found)
4389                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4390          (if (> (- (point) (match-beginning 0)) 998)
4391              (setq found t
4392                    length (- (point) (match-beginning 0)))
4393            (setq header (match-string-no-properties 1)))
4394          (setq start (match-beginning 0))
4395          (forward-line 1))
4396        (if found
4397            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4398                              header length))
4399          t)))
4400    ;; Check for multiple identical headers.
4401    (message-check 'multiple-headers
4402      (let (found)
4403        (while (and (not found)
4404                    (re-search-forward "^[^ \t:]+: " nil t))
4405          (save-excursion
4406            (or (re-search-forward
4407                 (concat "^"
4408                         (regexp-quote
4409                          (setq found
4410                                (buffer-substring
4411                                 (match-beginning 0) (- (match-end 0) 2))))
4412                         ":")
4413                 nil t)
4414                (setq found nil))))
4415        (if found
4416            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4417          t)))
4418    ;; Check for Version and Sendsys.
4419    (message-check 'sendsys
4420      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4421          (y-or-n-p
4422           (format "The article contains a %s command.  Really post? "
4423                   (buffer-substring (match-beginning 0)
4424                                     (1- (match-end 0)))))
4425        t))
4426    ;; See whether we can shorten Followup-To.
4427    (message-check 'shorten-followup-to
4428      (let ((newsgroups (message-fetch-field "newsgroups"))
4429            (followup-to (message-fetch-field "followup-to"))
4430            to)
4431        (when (and newsgroups
4432                   (string-match "," newsgroups)
4433                   (not followup-to)
4434                   (not
4435                    (zerop
4436                     (length
4437                      (setq to (completing-read
4438                                "Followups to (default: no Followup-To header) "
4439                                (mapcar (lambda (g) (list g))
4440                                        (cons "poster"
4441                                              (message-tokenize-header
4442                                               newsgroups)))))))))
4443          (goto-char (point-min))
4444          (insert "Followup-To: " to "\n"))
4445        t))
4446    ;; Check "Shoot me".
4447    (message-check 'shoot
4448      (if (re-search-forward
4449           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
4450          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4451        t))
4452    ;; Check for Approved.
4453    (message-check 'approved
4454      (if (re-search-forward "^Approved:" nil t)
4455          (y-or-n-p "The article contains an Approved header.  Really post? ")
4456        t))
4457    ;; Check the Message-ID header.
4458    (message-check 'message-id
4459      (let* ((case-fold-search t)
4460             (message-id (message-fetch-field "message-id" t)))
4461        (or (not message-id)
4462            ;; Is there an @ in the ID?
4463            (and (string-match "@" message-id)
4464                 ;; Is there a dot in the ID?
4465                 (string-match "@[^.]*\\." message-id)
4466                 ;; Does the ID end with a dot?
4467                 (not (string-match "\\.>" message-id)))
4468            (y-or-n-p
4469             (format "The Message-ID looks strange: \"%s\".  Really post? "
4470                     message-id)))))
4471    ;; Check the Newsgroups & Followup-To headers.
4472    (message-check 'existing-newsgroups
4473      (let* ((case-fold-search t)
4474             (newsgroups (message-fetch-field "newsgroups"))
4475             (followup-to (message-fetch-field "followup-to"))
4476             (groups (message-tokenize-header
4477                      (if followup-to
4478                          (concat newsgroups "," followup-to)
4479                        newsgroups)))
4480             (post-method (if (message-functionp message-post-method)
4481                              (funcall message-post-method)
4482                            message-post-method))
4483             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4484             ;; would probably involve a new nnoo function.
4485             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4486             (method (if (and (consp post-method)
4487                              (eq (car post-method) 'nnvirtual)
4488                              gnus-message-group-art)
4489                         (let ((group (car (nnvirtual-find-group-art
4490                                            (car gnus-message-group-art)
4491                                            (cdr gnus-message-group-art)))))
4492                           (gnus-find-method-for-group group))
4493                       post-method))
4494             (known-groups
4495              (mapcar (lambda (n)
4496                        (gnus-group-name-decode
4497                         (gnus-group-real-name n)
4498                         (gnus-group-name-charset method n)))
4499                      (gnus-groups-from-server method)))
4500             errors)
4501        (while groups
4502          (when (and (not (equal (car groups) "poster"))
4503                     (not (member (car groups) known-groups))
4504                     (not (member (car groups) errors)))
4505            (push (car groups) errors))
4506          (pop groups))
4507        (cond
4508         ;; Gnus is not running.
4509         ((or (not (and (boundp 'gnus-active-hashtb)
4510                        gnus-active-hashtb))
4511              (not (boundp 'gnus-read-active-file)))
4512          t)
4513         ;; We don't have all the group names.
4514         ((and (or (not gnus-read-active-file)
4515                   (eq gnus-read-active-file 'some))
4516               errors)
4517          (y-or-n-p
4518           (format
4519            "Really post to %s possibly unknown group%s: %s? "
4520            (if (= (length errors) 1) "this" "these")
4521            (if (= (length errors) 1) "" "s")
4522            (mapconcat 'identity errors ", "))))
4523         ;; There were no errors.
4524         ((not errors)
4525          t)
4526         ;; There are unknown groups.
4527         (t
4528          (y-or-n-p
4529           (format
4530            "Really post to %s unknown group%s: %s? "
4531            (if (= (length errors) 1) "this" "these")
4532            (if (= (length errors) 1) "" "s")
4533            (mapconcat 'identity errors ", ")))))))
4534    ;; Check continuation headers.
4535    (message-check 'continuation-headers
4536      (goto-char (point-min))
4537      (let ((do-posting t))
4538        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4539          (if (y-or-n-p "Fix continuation lines? ")
4540              (progn
4541                (goto-char (match-beginning 0))
4542                (insert " "))
4543            (unless (y-or-n-p "Send anyway? ")
4544              (setq do-posting nil))))
4545        do-posting))
4546    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4547    (message-check 'valid-newsgroups
4548      (let ((case-fold-search t)
4549            (headers '("Newsgroups" "Followup-To"))
4550            header error)
4551        (while (and headers (not error))
4552          (when (setq header (mail-fetch-field (car headers)))
4553            (if (or
4554                 (not
4555                  (string-match
4556                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4557                   header))
4558                 (memq
4559                  nil (mapcar
4560                       (lambda (g)
4561                         (not (string-match "\\.\\'\\|\\.\\." g)))
4562                       (message-tokenize-header header ","))))
4563                (setq error t)))
4564          (unless error
4565            (pop headers)))
4566        (if (not error)
4567            t
4568          (y-or-n-p
4569           (format "The %s header looks odd: \"%s\".  Really post? "
4570                   (car headers) header)))))
4571    (message-check 'repeated-newsgroups
4572      (let ((case-fold-search t)
4573            (headers '("Newsgroups" "Followup-To"))
4574            header error groups group)
4575        (while (and headers
4576                    (not error))
4577          (when (setq header (mail-fetch-field (pop headers)))
4578            (setq groups (message-tokenize-header header ","))
4579            (while (setq group (pop groups))
4580              (when (member group groups)
4581                (setq error group
4582                      groups nil)))))
4583        (if (not error)
4584            t
4585          (y-or-n-p
4586           (format "Group %s is repeated in headers.  Really post? " error)))))
4587    ;; Check the From header.
4588    (message-check 'from
4589      (let* ((case-fold-search t)
4590             (from (message-fetch-field "from"))
4591             ad)
4592        (cond
4593         ((not from)
4594          (message "There is no From line.  Posting is denied.")
4595          nil)
4596         ((or (not (string-match
4597                    "@[^\\.]*\\."
4598                    (setq ad (nth 1 (mail-extract-address-components
4599                                     from))))) ;larsi@ifi
4600              (string-match "\\.\\." ad) ;larsi@ifi..uio
4601              (string-match "@\\." ad)   ;larsi@.ifi.uio
4602              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4603              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4604              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4605          (message
4606           "Denied posting -- the From looks strange: \"%s\"." from)
4607          nil)
4608         ((let ((addresses (rfc822-addresses from)))
4609            (while (and addresses
4610                        (not (eq (string-to-char (car addresses)) ?\()))
4611              (setq addresses (cdr addresses)))
4612            addresses)
4613          (message
4614           "Denied posting -- bad From address: \"%s\"." from)
4615          nil)
4616         (t t))))
4617    ;; Check the Reply-To header.
4618    (message-check 'reply-to
4619      (let* ((case-fold-search t)
4620             (reply-to (message-fetch-field "reply-to"))
4621             ad)
4622        (cond
4623         ((not reply-to)
4624          t)
4625         ((string-match "," reply-to)
4626          (y-or-n-p
4627           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4628                   reply-to)))
4629         ((or (not (string-match
4630                    "@[^\\.]*\\."
4631                    (setq ad (nth 1 (mail-extract-address-components
4632                                     reply-to))))) ;larsi@ifi
4633              (string-match "\\.\\." ad) ;larsi@ifi..uio
4634              (string-match "@\\." ad)   ;larsi@.ifi.uio
4635              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4636              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4637              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4638          (y-or-n-p
4639           (format
4640            "The Reply-To looks strange: \"%s\". Really post? "
4641            reply-to)))
4642         (t t))))))
4643
4644 (defun message-check-news-body-syntax ()
4645   (and
4646    ;; Check for long lines.
4647    (message-check 'long-lines
4648      (goto-char (point-min))
4649      (re-search-forward
4650       (concat "^" (regexp-quote mail-header-separator) "$"))
4651      (forward-line 1)
4652      (while (and
4653              (or (looking-at
4654                   mime-edit-tag-regexp)
4655                  (let ((p (point)))
4656                    (end-of-line)
4657                    (< (- (point) p) 80)))
4658              (zerop (forward-line 1))))
4659      (or (bolp)
4660          (eobp)
4661          (y-or-n-p
4662           "You have lines longer than 79 characters.  Really post? ")))
4663    ;; Check whether the article is empty.
4664    (message-check 'empty
4665      (goto-char (point-min))
4666      (re-search-forward
4667       (concat "^" (regexp-quote mail-header-separator) "$"))
4668      (forward-line 1)
4669      (let ((b (point)))
4670        (goto-char (point-max))
4671        (re-search-backward message-signature-separator nil t)
4672        (beginning-of-line)
4673        (or (re-search-backward "[^ \n\t]" b t)
4674            (if (message-gnksa-enable-p 'empty-article)
4675                (y-or-n-p "Empty article.  Really post? ")
4676              (message "Denied posting -- Empty article.")
4677              nil))))
4678    ;; Check for control characters.
4679    (message-check 'control-chars
4680      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4681          (y-or-n-p
4682           "The article contains control characters.  Really post? ")
4683        t))
4684    ;; Check 8bit characters.
4685    (message-check '8bit
4686      (message-check-8bit))
4687    ;; Check excessive size.
4688    (message-check 'size
4689      (if (> (buffer-size) 60000)
4690          (y-or-n-p
4691           (format "The article is %d octets long.  Really post? "
4692                   (buffer-size)))
4693        t))
4694    ;; Check whether any new text has been added.
4695    (message-check 'new-text
4696      (or
4697       (not message-checksum)
4698       (not (eq (message-checksum) message-checksum))
4699       (if (message-gnksa-enable-p 'quoted-text-only)
4700           (y-or-n-p
4701            "It looks like no new text has been added.  Really post? ")
4702         (message "Denied posting -- no new text has been added.")
4703         nil)))
4704    ;; Check the length of the signature.
4705    (message-check 'signature
4706      (goto-char (point-max))
4707      (if (> (count-lines (point) (point-max)) 5)
4708          (y-or-n-p
4709           (format
4710            "Your .sig is %d lines; it should be max 4.  Really post? "
4711            (1- (count-lines (point) (point-max)))))
4712        t))
4713    ;; Ensure that text follows last quoted portion.
4714    (message-check 'quoting-style
4715      (goto-char (point-max))
4716      (let ((no-problem t))
4717        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4718          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4719        (if no-problem
4720            t
4721          (if (message-gnksa-enable-p 'quoted-text-only)
4722              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4723            ;; Ensure that
4724            (goto-char (point-min))
4725            (re-search-forward
4726             (concat "^" (regexp-quote mail-header-separator) "$"))
4727            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4728                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4729              (message "Denied posting -- only quoted text.")
4730              nil)))))))
4731
4732 (defun message-check-mail-syntax ()
4733   "Check the syntax of the message."
4734   (save-excursion
4735     (save-restriction
4736       (widen)
4737       (and
4738        ;; We narrow to the headers and check them first.
4739        (save-excursion
4740          (save-restriction
4741            (message-narrow-to-headers)
4742            (message-check-mail-header-syntax)))
4743        ;; Check the body.
4744        (save-excursion
4745          (set-buffer message-edit-buffer)
4746          (message-check-mail-body-syntax))))))
4747
4748 (defun message-check-mail-header-syntax ()
4749   t)
4750
4751 (defun message-check-mail-body-syntax ()
4752   (and
4753    ;; Check 8bit characters.
4754    (message-check '8bit
4755      (message-check-8bit)
4756      )))
4757
4758 (defun message-check-8bit ()
4759   "Check the article contains 8bit characters."
4760   (save-excursion
4761     (set-buffer message-encoding-buffer)
4762     (message-narrow-to-headers)
4763     (let* ((case-fold-search t)
4764            (field-value (message-fetch-field "content-transfer-encoding")))
4765       (if (and field-value
4766                (member (downcase field-value) message-8bit-encoding-list))
4767           t
4768         (widen)
4769         (set-buffer (get-buffer-create " message syntax"))
4770         (erase-buffer)
4771         (goto-char (point-min))
4772         (set-buffer-multibyte nil)
4773         (insert-buffer-substring message-encoding-buffer)
4774         (goto-char (point-min))
4775         (if (re-search-forward "[^\x00-\x7f]" nil t)
4776             (y-or-n-p
4777              "The article contains 8bit characters.  Really post? ")
4778           t)))))
4779
4780 (defun message-checksum ()
4781   "Return a \"checksum\" for the current buffer."
4782   (let ((sum 0))
4783     (save-excursion
4784       (goto-char (point-min))
4785       (re-search-forward
4786        (concat "^" (regexp-quote mail-header-separator) "$"))
4787       (while (not (eobp))
4788         (when (not (looking-at "[ \t\n]"))
4789           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4790                             (char-after))))
4791         (forward-char 1)))
4792     sum))
4793
4794 (defun message-do-fcc ()
4795   "Process Fcc headers in the current buffer."
4796   (let ((case-fold-search t)
4797         (coding-system-for-write 'raw-text)
4798         (output-coding-system 'raw-text)
4799         list file
4800         (mml-externalize-attachments message-fcc-externalize-attachments))
4801     (save-excursion
4802       (save-restriction
4803         (message-narrow-to-headers)
4804         (setq file (message-fetch-field "fcc" t)))
4805       (when file
4806         (set-buffer (get-buffer-create " *message temp*"))
4807         (erase-buffer)
4808         (insert-buffer-substring message-encoding-buffer)
4809         (save-restriction
4810           (message-narrow-to-headers)
4811           (while (setq file (message-fetch-field "fcc"))
4812             (push file list)
4813             (message-remove-header "fcc" nil t)))
4814         (goto-char (point-min))
4815         (when (re-search-forward
4816                (concat "^" (regexp-quote mail-header-separator) "$")
4817                nil t)
4818           (replace-match "" t t))
4819         ;; Process FCC operations.
4820         (while list
4821           (setq file (pop list))
4822           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4823               ;; Pipe the article to the program in question.
4824               (call-process-region (point-min) (point-max) shell-file-name
4825                                    nil nil nil shell-command-switch
4826                                    (match-string 1 file))
4827             ;; Save the article.
4828             (setq file (expand-file-name file))
4829             (unless (file-exists-p (file-name-directory file))
4830               (make-directory (file-name-directory file) t))
4831             (if (and message-fcc-handler-function
4832                      (not (eq message-fcc-handler-function 'rmail-output)))
4833                 (funcall message-fcc-handler-function file)
4834               (if (and (file-readable-p file) (mail-file-babyl-p file))
4835                   (rmail-output file 1 nil t)
4836                 (let ((mail-use-rfc822 t))
4837                   (rmail-output file 1 t t))))))
4838         (kill-buffer (current-buffer))))))
4839
4840 (defun message-output (filename)
4841   "Append this article to Unix/babyl mail file FILENAME."
4842   (if (and (file-readable-p filename)
4843            (mail-file-babyl-p filename))
4844       (gnus-output-to-rmail filename t)
4845     (gnus-output-to-mail filename t)))
4846
4847 (defun message-cleanup-headers ()
4848   "Do various automatic cleanups of the headers."
4849   ;; Remove empty lines in the header.
4850   (save-restriction
4851     (message-narrow-to-headers)
4852     ;; Remove blank lines.
4853     (while (re-search-forward "^[ \t]*\n" nil t)
4854       (replace-match "" t t))
4855
4856     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4857     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4858     ;; embedded line breaks.
4859     (goto-char (point-min))
4860     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4861       (save-restriction
4862         (narrow-to-region
4863          (point)
4864          (if (re-search-forward "^[^ \t]" nil t)
4865              (match-beginning 0)
4866            (forward-line 1)
4867            (point)))
4868         (goto-char (point-min))
4869         (while (re-search-forward "\n[ \t]+" nil t)
4870           (replace-match " " t t))      ;No line breaks (too confusing)
4871         (goto-char (point-min))
4872         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4873           (replace-match "," t t))
4874         (goto-char (point-min))
4875         ;; Remove trailing commas.
4876         (when (re-search-forward ",+$" nil t)
4877           (replace-match "" t t))))))
4878
4879 (defun message-make-date (&optional now)
4880   "Make a valid data header.
4881 If NOW, use that time instead."
4882   (let* ((now (or now (current-time)))
4883          (zone (nth 8 (decode-time now)))
4884          (sign "+"))
4885     (when (< zone 0)
4886       (setq sign "-")
4887       (setq zone (- zone)))
4888     (concat
4889      ;; The day name of the %a spec is locale-specific.  Pfff.
4890      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4891                                              parse-time-weekdays))))
4892      (format-time-string "%d" now)
4893      ;; The month name of the %b spec is locale-specific.  Pfff.
4894      (format " %s "
4895              (capitalize (car (rassoc (nth 4 (decode-time now))
4896                                       parse-time-months))))
4897      (format-time-string "%Y %H:%M:%S " now)
4898      ;; We do all of this because XEmacs doesn't have the %z spec.
4899      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4900
4901 (defun message-make-followup-subject (subject)
4902   "Make a followup Subject."
4903   (cond
4904    ((and (eq message-use-subject-re 'guess)
4905          (string-match message-subject-encoded-re-regexp subject))
4906     subject)
4907    (message-use-subject-re
4908     (concat "Re: " (message-strip-subject-re subject)))
4909    (t subject)))
4910
4911 (defun message-make-message-id ()
4912   "Make a unique Message-ID."
4913   (concat "<" (message-unique-id)
4914           (let ((psubject (save-excursion (message-fetch-field "subject")))
4915                 (psupersedes
4916                  (save-excursion (message-fetch-field "supersedes"))))
4917             (if (or
4918                  (and message-reply-headers
4919                       (mail-header-references message-reply-headers)
4920                       (mail-header-subject message-reply-headers)
4921                       psubject
4922                       (not (string=
4923                             (message-strip-subject-re
4924                              (mail-header-subject message-reply-headers))
4925                             (message-strip-subject-re psubject))))
4926                  (and psupersedes
4927                       (string-match "_-_@" psupersedes)))
4928                 "_-_" ""))
4929           "@" (message-make-fqdn) ">"))
4930
4931 (defvar message-unique-id-char nil)
4932
4933 ;; If you ever change this function, make sure the new version
4934 ;; cannot generate IDs that the old version could.
4935 ;; You might for example insert a "." somewhere (not next to another dot
4936 ;; or string boundary), or modify the "fsf" string.
4937 (defun message-unique-id ()
4938   ;; Don't use microseconds from (current-time), they may be unsupported.
4939   ;; Instead we use this randomly inited counter.
4940   (setq message-unique-id-char
4941         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4942            ;; (current-time) returns 16-bit ints,
4943            ;; and 2^16*25 just fits into 4 digits i base 36.
4944            (* 25 25)))
4945   (let ((tm (current-time)))
4946     (concat
4947      (if (memq system-type '(ms-dos emx vax-vms))
4948          (let ((user (downcase (user-login-name))))
4949            (while (string-match "[^a-z0-9_]" user)
4950              (aset user (match-beginning 0) ?_))
4951            user)
4952        (message-number-base36 (user-uid) -1))
4953      (message-number-base36 (+ (car tm)
4954                                (lsh (% message-unique-id-char 25) 16)) 4)
4955      (message-number-base36 (+ (nth 1 tm)
4956                                (lsh (/ message-unique-id-char 25) 16)) 4)
4957      ;; Append the newsreader name, because while the generated
4958      ;; ID is unique to this newsreader, other newsreaders might
4959      ;; otherwise generate the same ID via another algorithm.
4960      ".fsf")))
4961
4962 (defun message-number-base36 (num len)
4963   (if (if (< len 0)
4964           (<= num 0)
4965         (= len 0))
4966       ""
4967     (concat (message-number-base36 (/ num 36) (1- len))
4968             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4969                                   (% num 36))))))
4970
4971 (defun message-make-organization ()
4972   "Make an Organization header."
4973   (let* ((organization
4974           (when message-user-organization
4975             (if (message-functionp message-user-organization)
4976                 (funcall message-user-organization)
4977               message-user-organization))))
4978     (save-excursion
4979       (message-set-work-buffer)
4980       (cond ((stringp organization)
4981              (insert organization))
4982             ((and (eq t organization)
4983                   message-user-organization-file
4984                   (file-exists-p message-user-organization-file))
4985              (insert-file-contents message-user-organization-file)))
4986       (goto-char (point-min))
4987       (while (re-search-forward "[\t\n]+" nil t)
4988         (replace-match "" t t))
4989       (unless (zerop (buffer-size))
4990         (buffer-string)))))
4991
4992 (defun message-make-lines ()
4993   "Count the number of lines and return numeric string."
4994   (save-excursion
4995     (save-restriction
4996       (widen)
4997       (message-goto-body)
4998       (int-to-string (count-lines (point) (point-max))))))
4999
5000 (defun message-make-references ()
5001   "Return the References header for this message."
5002   (when message-reply-headers
5003     (let ((message-id (mail-header-message-id message-reply-headers))
5004           (references (mail-header-references message-reply-headers))
5005           new-references)
5006       (if (or references message-id)
5007           (concat (or references "") (and references " ")
5008                   (or message-id ""))
5009         nil))))
5010
5011 (defun message-make-in-reply-to ()
5012   "Return the In-Reply-To header for this message."
5013   (when message-reply-headers
5014     (let ((from (mail-header-from message-reply-headers))
5015           (date (mail-header-date message-reply-headers))
5016           (msg-id (mail-header-message-id message-reply-headers)))
5017       (when msg-id
5018         (concat msg-id
5019                 (when from
5020                   (let ((pair (std11-extract-address-components from)))
5021                     (concat "\n ("
5022                             (or (car pair) (cadr pair))
5023                             "'s message of \""
5024                             (if (or (not date) (string= date ""))
5025                                 "(unknown date)" date)
5026                             "\")"))))))))
5027
5028 (defun message-make-distribution ()
5029   "Make a Distribution header."
5030   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5031     (cond ((message-functionp message-distribution-function)
5032            (funcall message-distribution-function))
5033           (t orig-distribution))))
5034
5035 (defun message-make-expires ()
5036   "Return an Expires header based on `message-expires'."
5037   (let ((current (current-time))
5038         (future (* 1.0 message-expires 60 60 24)))
5039     ;; Add the future to current.
5040     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5041     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5042     (message-make-date current)))
5043
5044 (defun message-make-path ()
5045   "Return uucp path."
5046   (let ((login-name (user-login-name)))
5047     (cond ((null message-user-path)
5048            (concat (system-name) "!" login-name))
5049           ((stringp message-user-path)
5050            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5051            (concat message-user-path "!" login-name))
5052           (t login-name))))
5053
5054 (defun message-make-from ()
5055   "Make a From header."
5056   (let* ((style message-from-style)
5057          (login (message-make-address))
5058          (fullname
5059           (or (and (boundp 'user-full-name)
5060                    user-full-name)
5061               (user-full-name))))
5062     (when (string= fullname "&")
5063       (setq fullname (user-login-name)))
5064     (save-excursion
5065       (message-set-work-buffer)
5066       (cond
5067        ((or (null style)
5068             (equal fullname ""))
5069         (insert login))
5070        ((or (eq style 'angles)
5071             (and (not (eq style 'parens))
5072                  ;; Use angles if no quoting is needed, or if parens would
5073                  ;; need quoting too.
5074                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5075                      (let ((tmp (concat fullname nil)))
5076                        (while (string-match "([^()]*)" tmp)
5077                          (aset tmp (match-beginning 0) ?-)
5078                          (aset tmp (1- (match-end 0)) ?-))
5079                        (string-match "[\\()]" tmp)))))
5080         (insert fullname)
5081         (insert " <" login ">"))
5082        (t                               ; 'parens or default
5083         (insert login " (")
5084         (let ((fullname-start (point)))
5085           (insert fullname)
5086           (goto-char fullname-start)
5087           ;; RFC 822 says \ and nonmatching parentheses
5088           ;; must be escaped in comments.
5089           ;; Escape every instance of ()\ ...
5090           (while (re-search-forward "[()\\]" nil 1)
5091             (replace-match "\\\\\\&" t))
5092           ;; ... then undo escaping of matching parentheses,
5093           ;; including matching nested parentheses.
5094           (goto-char fullname-start)
5095           (while (re-search-forward
5096                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5097                   nil 1)
5098             (replace-match "\\1(\\3)" t)
5099             (goto-char fullname-start)))
5100         (insert ")")))
5101       (buffer-string))))
5102
5103 (defun message-make-sender ()
5104   "Return the \"real\" user address.
5105 This function tries to ignore all user modifications, and
5106 give as trustworthy answer as possible."
5107   (concat (user-login-name) "@" (system-name)))
5108
5109 (defun message-make-address ()
5110   "Make the address of the user."
5111   (or (message-user-mail-address)
5112       (concat (user-login-name) "@" (message-make-domain))))
5113
5114 (defun message-user-mail-address ()
5115   "Return the pertinent part of `user-mail-address'."
5116   (when (and user-mail-address
5117              (string-match "@.*\\." user-mail-address))
5118     (if (string-match " " user-mail-address)
5119         (nth 1 (std11-extract-address-components user-mail-address))
5120       user-mail-address)))
5121
5122 (defun message-sendmail-envelope-from ()
5123   "Return the envelope from."
5124   (cond ((eq message-sendmail-envelope-from 'header)
5125          (nth 1 (mail-extract-address-components
5126                  (message-fetch-field "from"))))
5127         ((stringp message-sendmail-envelope-from)
5128          message-sendmail-envelope-from)
5129         (t
5130          (message-make-address))))
5131
5132 (defun message-make-fqdn ()
5133   "Return user's fully qualified domain name."
5134   (let* ((system-name (system-name))
5135          (user-mail (message-user-mail-address))
5136          (user-domain
5137           (if (and user-mail
5138                    (string-match "@\\(.*\\)\\'" user-mail))
5139               (match-string 1 user-mail))))
5140     (cond
5141      ((and message-user-fqdn
5142            (stringp message-user-fqdn)
5143            (string-match message-valid-fqdn-regexp message-user-fqdn)
5144            (not (string-match message-bogus-system-names message-user-fqdn)))
5145       message-user-fqdn)
5146      ;; `message-user-fqdn' seems to be valid
5147      ((and (string-match message-valid-fqdn-regexp system-name)
5148            (not (string-match message-bogus-system-names system-name)))
5149       ;; `system-name' returned the right result.
5150       system-name)
5151      ;; Try `mail-host-address'.
5152      ((and (boundp 'mail-host-address)
5153            (stringp mail-host-address)
5154            (string-match message-valid-fqdn-regexp mail-host-address)
5155            (not (string-match message-bogus-system-names mail-host-address)))
5156       mail-host-address)
5157      ;; We try `user-mail-address' as a backup.
5158      ((and user-domain
5159            (stringp user-domain)
5160            (string-match message-valid-fqdn-regexp user-domain)
5161            (not (string-match message-bogus-system-names user-domain)))
5162       user-domain)
5163      ;; Default to this bogus thing.
5164      (t
5165       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
5166
5167 (defun message-make-host-name ()
5168   "Return the name of the host."
5169   (let ((fqdn (message-make-fqdn)))
5170     (string-match "^[^.]+\\." fqdn)
5171     (substring fqdn 0 (1- (match-end 0)))))
5172
5173 (defun message-make-domain ()
5174   "Return the domain name."
5175   (or mail-host-address
5176       (message-make-fqdn)))
5177
5178 (defun message-to-list-only ()
5179   "Send a message to the list only.
5180 Remove all addresses but the list address from To and Cc headers."
5181   (interactive)
5182   (let ((listaddr (message-make-mail-followup-to t)))
5183     (when listaddr
5184       (save-excursion
5185         (message-remove-header "to")
5186         (message-remove-header "cc")
5187         (message-position-on-field "To" "X-Draft-From")
5188         (insert listaddr)))))
5189
5190 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5191   "Return the Mail-Followup-To header.
5192 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5193 subscribed address (and not the additional To and Cc header contents)."
5194   (let* ((case-fold-search t)
5195          (to (message-fetch-field "To"))
5196          (cc (message-fetch-field "cc"))
5197          (msg-recipients (concat to (and to cc ", ") cc))
5198          (recipients
5199           (mapcar 'mail-strip-quoted-names
5200                   (message-tokenize-header msg-recipients)))
5201          (file-regexps
5202           (if message-subscribed-address-file
5203               (let (begin end item re)
5204                 (save-excursion
5205                   (with-temp-buffer
5206                     (insert-file-contents message-subscribed-address-file)
5207                     (while (not (eobp))
5208                       (setq begin (point))
5209                       (forward-line 1)
5210                       (setq end (point))
5211                       (if (bolp) (setq end (1- end)))
5212                       (setq item (regexp-quote (buffer-substring begin end)))
5213                       (if re (setq re (concat re "\\|" item))
5214                         (setq re (concat "\\`\\(" item))))
5215                     (and re (list (concat re "\\)\\'"))))))))
5216          (mft-regexps (apply 'append message-subscribed-regexps
5217                              (mapcar 'regexp-quote
5218                                      message-subscribed-addresses)
5219                              file-regexps
5220                              (mapcar 'funcall
5221                                      message-subscribed-address-functions))))
5222     (save-match-data
5223       (let ((subscribed-lists nil)
5224             (list
5225              (loop for recipient in recipients
5226                when (loop for regexp in mft-regexps
5227                       when (string-match regexp recipient) return t)
5228                return recipient)))
5229         (when list
5230           (if only-show-subscribed
5231               list
5232             msg-recipients))))))
5233
5234 ;; Dummy to avoid byte-compile warning.
5235 (defvar mule-version)
5236 (defvar emacs-beta-version)
5237 (defvar xemacs-codename)
5238 (defvar gnus-inviolable-extended-version)
5239
5240 (defun message-make-user-agent ()
5241   "Return user-agent info if the value `message-user-agent' is non-nil. If the
5242 \"User-Agent\" field has already exist, it's value will be added in the return
5243 string."
5244   (when message-user-agent
5245     (save-excursion
5246       (goto-char (point-min))
5247       (let ((case-fold-search t)
5248             user-agent start p end)
5249         (if (re-search-forward
5250              (concat "^User-Agent:[\t ]*\\("
5251                      (regexp-quote gnus-product-name)
5252                      "/[0-9.]+\\([ \t\r\n]*([^)]+)\\)*\\)?[\t ]*")
5253              nil t)
5254             (progn
5255               (setq start (match-beginning 0)
5256                     p (match-end 0)
5257                     end (std11-field-end)
5258                     user-agent (buffer-substring-no-properties p end))
5259               (delete-region start (1+ end))
5260               (concat message-user-agent " " user-agent))
5261           message-user-agent)))))
5262
5263 (defun message-generate-headers (headers)
5264   "Prepare article HEADERS.
5265 Headers already prepared in the buffer are not modified."
5266   (setq headers (append headers message-required-headers))
5267   (save-restriction
5268     (message-narrow-to-headers)
5269     (let* ((Date (message-make-date))
5270            (Message-ID (message-make-message-id))
5271            (Organization (message-make-organization))
5272            (From (message-make-from))
5273            (Path (message-make-path))
5274            (Subject nil)
5275            (Newsgroups nil)
5276            (In-Reply-To (message-make-in-reply-to))
5277            (References (message-make-references))
5278            (To nil)
5279            (Distribution (message-make-distribution))
5280            (Lines (message-make-lines))
5281            (User-Agent (message-make-user-agent))
5282            (Expires (message-make-expires))
5283            (case-fold-search t)
5284            (optionalp nil)
5285            header value elem)
5286       ;; First we remove any old generated headers.
5287       (let ((headers message-deletable-headers))
5288         (unless (buffer-modified-p)
5289           (setq headers (delq 'Message-ID (copy-sequence headers))))
5290         (while headers
5291           (goto-char (point-min))
5292           (and (re-search-forward
5293                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5294                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5295                (message-delete-line))
5296           (pop headers)))
5297       ;; Go through all the required headers and see if they are in the
5298       ;; articles already.  If they are not, or are empty, they are
5299       ;; inserted automatically - except for Subject, Newsgroups and
5300       ;; Distribution.
5301       (while headers
5302         (goto-char (point-min))
5303         (setq elem (pop headers))
5304         (if (consp elem)
5305             (if (eq (car elem) 'optional)
5306                 (setq header (cdr elem)
5307                       optionalp t)
5308               (setq header (car elem)))
5309           (setq header elem))
5310         (when (or (not (re-search-forward
5311                         (concat "^"
5312                                 (regexp-quote
5313                                  (downcase
5314                                   (if (stringp header)
5315                                       header
5316                                     (symbol-name header))))
5317                                 ":")
5318                         nil t))
5319                   (progn
5320                     ;; The header was found.  We insert a space after the
5321                     ;; colon, if there is none.
5322                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5323                     ;; Find out whether the header is empty.
5324                     (looking-at "[ \t]*\n[^ \t]")))
5325           ;; So we find out what value we should insert.
5326           (setq value
5327                 (cond
5328                  ((and (consp elem)
5329                        (eq (car elem) 'optional))
5330                   ;; This is an optional header.  If the cdr of this
5331                   ;; is something that is nil, then we do not insert
5332                   ;; this header.
5333                   (setq header (cdr elem))
5334                   (or (and (message-functionp (cdr elem))
5335                            (funcall (cdr elem)))
5336                       (and (boundp (cdr elem))
5337                            (symbol-value (cdr elem)))))
5338                  ((consp elem)
5339                   ;; The element is a cons.  Either the cdr is a
5340                   ;; string to be inserted verbatim, or it is a
5341                   ;; function, and we insert the value returned from
5342                   ;; this function.
5343                   (or (and (stringp (cdr elem))
5344                            (cdr elem))
5345                       (and (message-functionp (cdr elem))
5346                            (funcall (cdr elem)))))
5347                  ((and (boundp header)
5348                        (symbol-value header))
5349                   ;; The element is a symbol.  We insert the value
5350                   ;; of this symbol, if any.
5351                   (symbol-value header))
5352                  ((not (message-check-element header))
5353                   ;; We couldn't generate a value for this header,
5354                   ;; so we just ask the user.
5355                   (read-from-minibuffer
5356                    (format "Empty header for %s; enter value: " header)))))
5357           ;; Finally insert the header.
5358           (when (and value
5359                      (not (equal value "")))
5360             (save-excursion
5361               (if (bolp)
5362                   (progn
5363                     ;; This header didn't exist, so we insert it.
5364                     (goto-char (point-max))
5365                     (let ((formatter
5366                            (cdr (assq header message-header-format-alist))))
5367                       (if formatter
5368                           (funcall formatter header value)
5369                         (insert (if (stringp header)
5370                                     header (symbol-name header))
5371                                 ": " value))
5372                       ;; We check whether the value was ended by a
5373                       ;; newline.  If now, we insert one.
5374                       (unless (bolp)
5375                         (insert "\n"))
5376                       (forward-line -1)))
5377                 ;; The value of this header was empty, so we clear
5378                 ;; totally and insert the new value.
5379                 (delete-region (point) (gnus-point-at-eol))
5380                 ;; If the header is optional, and the header was
5381                 ;; empty, we can't insert it anyway.
5382                 (unless optionalp
5383                   (insert value)
5384                   (when (bolp)
5385                     (delete-char -1))))
5386               ;; Add the deletable property to the headers that require it.
5387               (and (memq header message-deletable-headers)
5388                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5389                    (add-text-properties
5390                     (point) (match-end 0)
5391                     '(message-deletable t face italic) (current-buffer)))))))
5392       ;; Insert new Sender if the From is strange.
5393       (let ((from (message-fetch-field "from"))
5394             (sender (message-fetch-field "sender"))
5395             (secure-sender (message-make-sender)))
5396         (when (and from
5397                    (not (message-check-element 'sender))
5398                    (not (string=
5399                          (downcase
5400                           (cadr (std11-extract-address-components from)))
5401                          (downcase secure-sender)))
5402                    (or (null sender)
5403                        (not
5404                         (string=
5405                          (downcase
5406                           (cadr (std11-extract-address-components sender)))
5407                          (downcase secure-sender)))))
5408           (goto-char (point-min))
5409           ;; Rename any old Sender headers to Original-Sender.
5410           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5411             (beginning-of-line)
5412             (insert "Original-")
5413             (beginning-of-line))
5414           (when (or (message-news-p)
5415                     (string-match "@.+\\.." secure-sender))
5416             (insert "Sender: " secure-sender "\n")))))))
5417
5418 (defun message-insert-courtesy-copy ()
5419   "Insert a courtesy message in mail copies of combined messages."
5420   (let (newsgroups)
5421     (save-excursion
5422       (save-restriction
5423         (message-narrow-to-headers)
5424         (when (setq newsgroups (message-fetch-field "newsgroups"))
5425           (goto-char (point-max))
5426           (insert "Posted-To: " newsgroups "\n")))
5427       (forward-line 1)
5428       (when message-courtesy-message
5429         (cond
5430          ((string-match "%s" message-courtesy-message)
5431           (insert (format message-courtesy-message newsgroups)))
5432          (t
5433           (insert message-courtesy-message)))))))
5434
5435 ;;;
5436 ;;; Setting up a message buffer
5437 ;;;
5438
5439 (defun message-fill-address (header value)
5440   (save-restriction
5441     (narrow-to-region (point) (point))
5442     (insert (capitalize (symbol-name header))
5443             ": "
5444             (if (consp value) (car value) value)
5445             "\n")
5446     (narrow-to-region (point-min) (1- (point-max)))
5447     (let (quoted last)
5448       (goto-char (point-min))
5449       (while (not (eobp))
5450         (skip-chars-forward "^,\"" (point-max))
5451         (if (or (eq (char-after) ?,)
5452                 (eobp))
5453             (when (not quoted)
5454               (if (and (> (current-column) 78)
5455                        last)
5456                   (save-excursion
5457                     (goto-char last)
5458                     (looking-at "[ \t]*")
5459                     (replace-match "\n " t t)))
5460               (setq last (1+ (point))))
5461           (setq quoted (not quoted)))
5462         (unless (eobp)
5463           (forward-char 1))))
5464     (goto-char (point-max))
5465     (widen)
5466     (forward-line 1)))
5467
5468 (defun message-fill-references (header value)
5469   (insert (capitalize (symbol-name header))
5470           ": "
5471           (std11-fill-msg-id-list-string
5472            (if (consp value) (car value) value))
5473           "\n"))
5474
5475 (defun message-fill-header (header value)
5476   (let ((begin (point))
5477         (fill-column 78)
5478         (fill-prefix " "))
5479     (insert (capitalize (symbol-name header))
5480             ": "
5481             (if (consp value) (car value) value)
5482             "\n")
5483     (save-restriction
5484       (narrow-to-region begin (point))
5485       (fill-region-as-paragraph begin (point))
5486       ;; Tapdance around looong Message-IDs.
5487       (forward-line -1)
5488       (when (looking-at "[ \t]*$")
5489         (message-delete-line))
5490       (goto-char begin)
5491       (re-search-forward ":" nil t)
5492       (when (looking-at "\n[ \t]+")
5493         (replace-match " " t t))
5494       (goto-char (point-max)))))
5495
5496 (defun message-shorten-1 (list cut surplus)
5497   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5498   (setcdr (nthcdr (- cut 2) list)
5499           (nthcdr (+ (- cut 2) surplus 1) list)))
5500
5501 (defun message-shorten-references (header references)
5502   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5503 If folding is disallowed, also check that the REFERENCES are less
5504 than 988 characters long, and if they are not, trim them until they are."
5505   (let ((maxcount 21)
5506         (count 0)
5507         (cut 2)
5508         refs)
5509     (with-temp-buffer
5510       (insert references)
5511       (goto-char (point-min))
5512       ;; Cons a list of valid references.
5513       (while (re-search-forward "<[^>]+>" nil t)
5514         (push (match-string 0) refs))
5515       (setq refs (nreverse refs)
5516             count (length refs)))
5517
5518     ;; If the list has more than MAXCOUNT elements, trim it by
5519     ;; removing the CUTth element and the required number of
5520     ;; elements that follow.
5521     (when (> count maxcount)
5522       (let ((surplus (- count maxcount)))
5523         (message-shorten-1 refs cut surplus)
5524         (decf count surplus)))
5525
5526     ;; If folding is disallowed, make sure the total length (including
5527     ;; the spaces between) will be less than MAXSIZE characters.
5528     ;;
5529     ;; Only disallow folding for News messages. At this point the headers
5530     ;; have not been generated, thus we use message-this-is-news directly.
5531     (when (and message-this-is-news message-cater-to-broken-inn)
5532       (let ((maxsize 988)
5533             (totalsize (+ (apply #'+ (mapcar #'length refs))
5534                           (1- count)))
5535             (surplus 0)
5536             (ptr (nthcdr (1- cut) refs)))
5537         ;; Decide how many elements to cut off...
5538         (while (> totalsize maxsize)
5539           (decf totalsize (1+ (length (car ptr))))
5540           (incf surplus)
5541           (setq ptr (cdr ptr)))
5542         ;; ...and do it.
5543         (when (> surplus 0)
5544           (message-shorten-1 refs cut surplus))))
5545
5546     ;; Finally, collect the references back into a string and insert
5547     ;; it into the buffer.
5548     (let ((refstring (mapconcat #'identity refs " ")))
5549       (if (and message-this-is-news message-cater-to-broken-inn)
5550           (insert (capitalize (symbol-name header)) ": "
5551                   refstring "\n")
5552         (message-fill-header header refstring)))))
5553
5554 (defun message-position-point ()
5555   "Move point to where the user probably wants to find it."
5556   (message-narrow-to-headers)
5557   (cond
5558    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5559     (search-backward ":" )
5560     (widen)
5561     (forward-char 1)
5562     (if (eq (char-after) ? )
5563         (forward-char 1)
5564       (insert " ")))
5565    (t
5566     (goto-char (point-max))
5567     (widen)
5568     (forward-line 1)
5569     (unless (looking-at "$")
5570       (forward-line 2)))
5571    (sit-for 0)))
5572
5573 (defcustom message-beginning-of-line t
5574   "Whether C-a goes to beginning of header values."
5575   :group 'message-buffers
5576   :type 'boolean)
5577
5578 (defun message-beginning-of-line (&optional n)
5579   "Move point to beginning of header value or to beginning of line."
5580   (interactive "p")
5581   (let ((zrs 'zmacs-region-stays))
5582     (when (and (interactive-p) (boundp zrs))
5583       (set zrs t)))
5584   (if (and message-beginning-of-line
5585            (message-point-in-header-p))
5586       (let* ((here (point))
5587              (bol (progn (beginning-of-line n) (point)))
5588              (eol (gnus-point-at-eol))
5589              (eoh (re-search-forward ": *" eol t)))
5590         (if (or (not eoh) (equal here eoh))
5591             (goto-char bol)
5592           (goto-char eoh)))
5593     (beginning-of-line n)))
5594
5595 (defun message-buffer-name (type &optional to group)
5596   "Return a new (unique) buffer name based on TYPE and TO."
5597   (cond
5598    ;; Generate a new buffer name The Message Way.
5599    ((eq message-generate-new-buffers 'unique)
5600     (generate-new-buffer-name
5601      (concat "*" type
5602              (if to
5603                  (concat " to "
5604                          (or (car (std11-extract-address-components to))
5605                              to) "")
5606                "")
5607              (if (and group (not (string= group ""))) (concat " on " group) "")
5608              "*")))
5609    ;; Check whether `message-generate-new-buffers' is a function,
5610    ;; and if so, call it.
5611    ((message-functionp message-generate-new-buffers)
5612     (funcall message-generate-new-buffers type to group))
5613    ((eq message-generate-new-buffers 'unsent)
5614     (generate-new-buffer-name
5615      (concat "*unsent " type
5616              (if to
5617                  (concat " to "
5618                          (or (car (mail-extract-address-components to))
5619                              to) "")
5620                "")
5621              (if (and group (not (string= group ""))) (concat " on " group) "")
5622              "*")))
5623    ;; Use standard name.
5624    (t
5625     (format "*%s message*" type))))
5626
5627 (defmacro message-pop-to-buffer-1 (buffer)
5628   `(if pop-up-frames
5629        (let (special-display-buffer-names
5630              special-display-regexps
5631              same-window-buffer-names
5632              same-window-regexps)
5633          (pop-to-buffer ,buffer))
5634      (pop-to-buffer ,buffer)))
5635
5636 (defun message-pop-to-buffer (name)
5637   "Pop to buffer NAME, and warn if it already exists and is modified."
5638   (let ((buffer (get-buffer name))
5639         (pop-up-frames (and (or (static-if (featurep 'xemacs)
5640                                     (device-on-window-system-p)
5641                                   window-system)
5642                                 (>= emacs-major-version 20))
5643                             message-use-multi-frames)))
5644     (if (and buffer
5645              (buffer-name buffer))
5646         (progn
5647           (message-pop-to-buffer-1 buffer)
5648           (when (and (buffer-modified-p)
5649                      (not (y-or-n-p
5650                            "Message already being composed; erase? ")))
5651             (error "Message being composed")))
5652       (message-pop-to-buffer-1 name))
5653     (erase-buffer)
5654     (message-mode)
5655     (when pop-up-frames
5656       (set (make-local-variable 'message-original-frame) (selected-frame)))))
5657
5658 (defun message-do-send-housekeeping ()
5659   "Kill old message buffers."
5660   ;; We might have sent this buffer already.  Delete it from the
5661   ;; list of buffers.
5662   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5663   (while (and message-max-buffers
5664               message-buffer-list
5665               (>= (length message-buffer-list) message-max-buffers))
5666     ;; Kill the oldest buffer -- unless it has been changed.
5667     (let ((buffer (pop message-buffer-list)))
5668       (when (and (buffer-name buffer)
5669                  (not (buffer-modified-p buffer)))
5670         (kill-buffer buffer))))
5671   ;; Rename the buffer.
5672   (if message-send-rename-function
5673       (funcall message-send-rename-function)
5674     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5675     (when (string-match
5676            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5677            (buffer-name))
5678       (let ((name (match-string 2 (buffer-name)))
5679             to group)
5680         (if (not (or (null name)
5681                      (string-equal name "mail")
5682                      (string-equal name "posting")))
5683             (setq name (concat "*sent " name "*"))
5684           (message-narrow-to-headers)
5685           (setq to (message-fetch-field "to"))
5686           (setq group (message-fetch-field "newsgroups"))
5687           (widen)
5688           (setq name
5689                 (cond
5690                  (to (concat "*sent mail to "
5691                              (or (car (mail-extract-address-components to))
5692                                  to) "*"))
5693                  ((and group (not (string= group "")))
5694                   (concat "*sent posting on " group "*"))
5695                  (t "*sent mail*"))))
5696         (unless (string-equal name (buffer-name))
5697           (rename-buffer name t)))))
5698   ;; Push the current buffer onto the list.
5699   (when message-max-buffers
5700     (setq message-buffer-list
5701           (nconc message-buffer-list (list (current-buffer))))))
5702
5703 (defun message-mail-user-agent ()
5704   (let ((mua (cond
5705               ((not message-mail-user-agent) nil)
5706               ((eq message-mail-user-agent t) mail-user-agent)
5707               (t message-mail-user-agent))))
5708     (if (memq mua '(message-user-agent gnus-user-agent))
5709         nil
5710       mua)))
5711
5712 (defun message-setup (headers &optional replybuffer actions switch-function)
5713   (let ((mua (message-mail-user-agent))
5714         subject to field yank-action)
5715     (if (not (and message-this-is-mail mua))
5716         (message-setup-1 headers replybuffer actions)
5717       (if replybuffer
5718           (setq yank-action (list 'insert-buffer replybuffer)))
5719       (setq headers (copy-sequence headers))
5720       (setq field (assq 'Subject headers))
5721       (when field
5722         (setq subject (cdr field))
5723         (setq headers (delq field headers)))
5724       (setq field (assq 'To headers))
5725       (when field
5726         (setq to (cdr field))
5727         (setq headers (delq field headers)))
5728       (let ((mail-user-agent mua))
5729         (compose-mail to subject
5730                       (mapcar (lambda (item)
5731                                 (cons
5732                                  (format "%s" (car item))
5733                                  (cdr item)))
5734                               headers)
5735                       nil switch-function yank-action actions)))))
5736
5737 (defun message-headers-to-generate (headers included-headers excluded-headers)
5738   "Return a list that includes all headers from HEADERS.
5739 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5740 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5741 are not included."
5742   (let ((result nil)
5743         header-name)
5744     (dolist (header headers)
5745       (setq header-name (cond
5746                          ((and (consp header)
5747                                (eq (car header) 'optional))
5748                           ;; On the form (optional . Header)
5749                           (cdr header))
5750                          ((consp header)
5751                           ;; On the form (Header . function)
5752                           (car header))
5753                          (t
5754                           ;; Just a Header.
5755                           header)))
5756       (when (and (not (memq header-name excluded-headers))
5757                  (or (eq included-headers t)
5758                      (memq header-name included-headers)))
5759         (push header result)))
5760     (nreverse result)))
5761
5762 (defun message-setup-1 (headers &optional replybuffer actions)
5763   (dolist (action actions)
5764     (condition-case nil
5765         (add-to-list 'message-send-actions
5766                      `(apply ',(car action) ',(cdr action)))))
5767   (setq message-reply-buffer
5768         (or (message-get-parameter 'reply-buffer)
5769             replybuffer))
5770   (goto-char (point-min))
5771   ;; Insert all the headers.
5772   (mail-header-format
5773    (let ((h headers)
5774          (alist message-header-format-alist))
5775      (while h
5776        (unless (assq (caar h) message-header-format-alist)
5777          (push (list (caar h)) alist))
5778        (pop h))
5779      alist)
5780    headers)
5781   (delete-region (point) (progn (forward-line -1) (point)))
5782   (when message-default-headers
5783     (insert message-default-headers)
5784     (or (bolp) (insert ?\n)))
5785   (put-text-property
5786    (point)
5787    (progn
5788      (insert mail-header-separator "\n")
5789      (1- (point)))
5790    'read-only nil)
5791   (forward-line -1)
5792   (when (message-news-p)
5793     (when message-default-news-headers
5794       (insert message-default-news-headers)
5795       (or (bolp) (insert ?\n)))
5796     (when message-generate-headers-first
5797       (message-generate-headers
5798        (message-headers-to-generate
5799         (append message-required-news-headers
5800                 message-required-headers)
5801         message-generate-headers-first
5802         '(Lines Subject)))))
5803   (when (message-mail-p)
5804     (when message-default-mail-headers
5805       (insert message-default-mail-headers)
5806       (or (bolp) (insert ?\n)))
5807     (when message-generate-headers-first
5808       (message-generate-headers
5809        (message-headers-to-generate
5810         (append message-required-mail-headers
5811                 message-required-headers)
5812         message-generate-headers-first
5813         '(Lines Subject)))))
5814   (run-hooks 'message-signature-setup-hook)
5815   (message-insert-signature)
5816   (save-restriction
5817     (message-narrow-to-headers)
5818     (if (and replybuffer
5819              message-alternative-emails)
5820         (message-use-alternative-email-as-from))
5821     (run-hooks 'message-header-setup-hook))
5822   (set-buffer-modified-p nil)
5823   (setq buffer-undo-list nil)
5824   (run-hooks 'message-setup-hook)
5825   (message-position-point)
5826   (undo-boundary))
5827
5828 (defun message-set-auto-save-file-name ()
5829   "Associate the message buffer with a file in the drafts directory."
5830   (when message-auto-save-directory
5831     (unless (file-directory-p
5832              (directory-file-name message-auto-save-directory))
5833       (make-directory message-auto-save-directory t))
5834     (if (gnus-alive-p)
5835         (setq message-draft-article
5836               (nndraft-request-associate-buffer "drafts"))
5837       (setq buffer-file-name (expand-file-name
5838                               (if (memq system-type
5839                                         '(ms-dos ms-windows windows-nt
5840                                                  cygwin cygwin32 win32 w32
5841                                                  mswindows))
5842                                   "message"
5843                                 "*message*")
5844                               message-auto-save-directory))
5845       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5846     (clear-visited-file-modtime)
5847     (static-if (boundp 'MULE)
5848         (set-file-coding-system message-draft-coding-system)
5849       (setq buffer-file-coding-system message-draft-coding-system))))
5850
5851 (defun message-disassociate-draft ()
5852   "Disassociate the message buffer from the drafts directory."
5853   (when message-draft-article
5854     (nndraft-request-expire-articles
5855      (list message-draft-article) "drafts" nil t)))
5856
5857 (defun message-insert-headers ()
5858   "Generate the headers for the article."
5859   (interactive)
5860   (save-excursion
5861     (save-restriction
5862       (message-narrow-to-headers)
5863       (when (message-news-p)
5864         (message-generate-headers
5865          (delq 'Lines
5866                (delq 'Subject
5867                      (copy-sequence message-required-news-headers)))))
5868       (when (message-mail-p)
5869         (message-generate-headers
5870          (delq 'Lines
5871                (delq 'Subject
5872                      (copy-sequence message-required-mail-headers))))))))
5873
5874 \f
5875
5876 ;;;
5877 ;;; Commands for interfacing with message
5878 ;;;
5879
5880 ;;;###autoload
5881 (defun message-mail (&optional to subject
5882                                other-headers continue switch-function
5883                                yank-action send-actions)
5884   "Start editing a mail message to be sent.
5885 OTHER-HEADERS is an alist of header/value pairs."
5886   (interactive)
5887   (let ((message-this-is-mail t) replybuffer)
5888     (unless (message-mail-user-agent)
5889       (message-pop-to-buffer (message-buffer-name "mail" to)))
5890     ;; FIXME: message-mail should do something if YANK-ACTION is not
5891     ;; insert-buffer.
5892     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5893          (setq replybuffer (nth 1 yank-action)))
5894     (message-setup
5895      (nconc
5896       `((To . ,(or to "")) (Subject . ,(or subject "")))
5897       (when other-headers other-headers))
5898      replybuffer send-actions)
5899     ;; FIXME: Should return nil if failure.
5900     t))
5901
5902 ;;;###autoload
5903 (defun message-news (&optional newsgroups subject)
5904   "Start editing a news article to be sent."
5905   (interactive)
5906   (let ((message-this-is-news t))
5907     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5908     (message-setup `((Newsgroups . ,(or newsgroups ""))
5909                      (Subject . ,(or subject ""))))))
5910
5911 (defun message-get-reply-headers (wide &optional to-address address-headers)
5912   (let (follow-to mct never-mct to cc author mft recipients)
5913     ;; Find all relevant headers we need.
5914     (let ((mrt (when message-use-mail-reply-to
5915                  (message-fetch-field "mail-reply-to")))
5916           (reply-to (message-fetch-field "reply-to")))
5917       (setq to (message-fetch-field "to")
5918             cc (message-fetch-field "cc")
5919             mct (when message-use-mail-copies-to
5920                   (message-fetch-field "mail-copies-to"))
5921             author (or mrt
5922                        reply-to
5923                        (message-fetch-field "from")
5924                        "")
5925             mft (when (and (not (or to-address mrt reply-to))
5926                            message-use-mail-followup-to)
5927                   (message-fetch-field "mail-followup-to"))))
5928
5929     (save-match-data
5930       ;; Handle special values of Mail-Copies-To.
5931       (when mct
5932         (cond ((or (equal (downcase mct) "never")
5933                    (equal (downcase mct) "nobody"))
5934                (when (or (not (eq message-use-mail-copies-to 'ask))
5935                          (message-y-or-n-p
5936                           (concat "Obey Mail-Copies-To: never? ") t "\
5937 You should normally obey the Mail-Copies-To: header.
5938
5939         `Mail-Copies-To: " mct "'
5940 directs you not to send your response to the author."))
5941                  (setq never-mct t))
5942                (setq mct nil))
5943               ((or (equal (downcase mct) "always")
5944                    (equal (downcase mct) "poster"))
5945                (if (or (not (eq message-use-mail-copies-to 'ask))
5946                        (message-y-or-n-p
5947                         (concat "Obey Mail-Copies-To: always? ") t "\
5948 You should normally obey the Mail-Copies-To: header.
5949
5950         `Mail-Copies-To: " mct "'
5951 sends a copy of your response to the author."))
5952                    (setq mct author)
5953                  (setq mct nil)))
5954               ((and (eq message-use-mail-copies-to 'ask)
5955                     (not (message-y-or-n-p
5956                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5957 You should normally obey the Mail-Copies-To: header.
5958
5959         `Mail-Copies-To: " mct "'
5960 sends a copy of your response to " (if (string-match "," mct)
5961                                        "the specified addresses"
5962                                      "that address") ".")))
5963                (setq mct nil))))
5964
5965       ;; Build (textual) list of new recipient addresses.
5966       (cond
5967        ((not wide)
5968         (setq recipients (concat ", " author)))
5969        (address-headers
5970         (dolist (header address-headers)
5971           (let ((value (message-fetch-field header)))
5972             (when value
5973               (setq recipients (concat recipients ", " value))))))
5974        ((and mft
5975              (string-match "[^ \t,]" mft)
5976              (or (not (eq message-use-mail-followup-to 'ask))
5977                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5978 You should normally obey the Mail-Followup-To: header.  In this
5979 article, it has the value of
5980
5981 " mft "
5982
5983 which directs your response to " (if (string-match "," mft)
5984                                      "the specified addresses"
5985                                    "that address only") ".
5986
5987 Most commonly, Mail-Followup-To is used by a mailing list poster to
5988 express that responses should be sent to just the list, and not the
5989 poster as well.
5990
5991 If a message is posted to several mailing lists, Mail-Followup-To may
5992 also be used to direct the following discussion to one list only,
5993 because discussions that are spread over several lists tend to be
5994 fragmented and very difficult to follow.
5995
5996 Also, some source/announcement lists are not intended for discussion;
5997 responses here are directed to other addresses.")))
5998         (setq recipients (concat ", " mft)))
5999        (to-address
6000         (setq recipients (concat ", " to-address))
6001         ;; If the author explicitly asked for a copy, we don't deny it to them.
6002         (if mct (setq recipients (concat recipients ", " mct))))
6003        (t
6004         (setq recipients (if never-mct "" (concat ", " author)))
6005         (if to  (setq recipients (concat recipients ", " to)))
6006         (if cc  (setq recipients (concat recipients ", " cc)))
6007         (if mct (setq recipients (concat recipients ", " mct)))))
6008       (if (>= (length recipients) 2)
6009           ;; Strip the leading ", ".
6010           (setq recipients (substring recipients 2)))
6011       ;; Squeeze whitespace.
6012       (while (string-match "[ \t][ \t]+" recipients)
6013         (setq recipients (replace-match " " t t recipients)))
6014       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6015       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
6016         (setq recipients (rmail-dont-reply-to recipients)))
6017       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6018       (if (string-equal recipients "")
6019           (setq recipients author))
6020       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6021       (setq recipients
6022             (mapcar
6023              (lambda (addr)
6024                (cons (downcase (mail-strip-quoted-names addr)) addr))
6025              (message-tokenize-header recipients)))
6026       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6027       (let ((s recipients))
6028         (while s
6029           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6030
6031       ;; Remove hierarchical lists that are contained within each other,
6032       ;; if message-hierarchical-addresses is defined.
6033       (when message-hierarchical-addresses
6034         (let ((plain-addrs (mapcar 'car recipients))
6035               subaddrs recip)
6036           (while plain-addrs
6037             (setq subaddrs (assoc (car plain-addrs)
6038                                   message-hierarchical-addresses)
6039                   plain-addrs (cdr plain-addrs))
6040             (when subaddrs
6041               (setq subaddrs (cdr subaddrs))
6042               (while subaddrs
6043                 (setq recip (assoc (car subaddrs) recipients)
6044                       subaddrs (cdr subaddrs))
6045                 (if recip
6046                     (setq recipients (delq recip recipients))))))))
6047
6048       ;; Build the header alist.  Allow the user to be asked whether
6049       ;; or not to reply to all recipients in a wide reply.
6050       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6051       (when (and recipients
6052                  (or (not message-wide-reply-confirm-recipients)
6053                      (y-or-n-p "Reply to all recipients? ")))
6054         (setq recipients (mapconcat
6055                           (lambda (addr) (cdr addr)) recipients ", "))
6056         (if (string-match "^ +" recipients)
6057             (setq recipients (substring recipients (match-end 0))))
6058         (push (cons 'Cc recipients) follow-to)))
6059     follow-to))
6060
6061 ;;;###autoload
6062 (defun message-reply (&optional to-address wide)
6063   "Start editing a reply to the article in the current buffer."
6064   (interactive)
6065   (require 'gnus-sum)                   ; for gnus-list-identifiers
6066   (let ((cur (current-buffer))
6067         from subject date
6068         references message-id follow-to
6069         (inhibit-point-motion-hooks t)
6070         (message-this-is-mail t)
6071         gnus-warning in-reply-to)
6072     (save-restriction
6073       (message-narrow-to-head-1)
6074       ;; Allow customizations to have their say.
6075       (if (not wide)
6076           ;; This is a regular reply.
6077           (when (message-functionp message-reply-to-function)
6078             (save-excursion
6079               (setq follow-to (funcall message-reply-to-function))))
6080         ;; This is a followup.
6081         (when (message-functionp message-wide-reply-to-function)
6082           (save-excursion
6083             (setq follow-to
6084                   (funcall message-wide-reply-to-function)))))
6085       (setq message-id (message-fetch-field "message-id" t)
6086             references (message-fetch-field "references")
6087             date (message-fetch-field "date")
6088             from (message-fetch-field "from")
6089             subject (or (message-fetch-field "subject") "none"))
6090       (when gnus-list-identifiers
6091         (setq subject (message-strip-list-identifiers subject)))
6092       (setq subject (message-make-followup-subject subject))
6093       (when message-subject-trailing-was-query
6094         (setq subject (message-strip-subject-trailing-was subject)))
6095
6096       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6097                  (string-match "<[^>]+>" gnus-warning))
6098         (setq message-id (match-string 0 gnus-warning)))
6099
6100       (unless follow-to
6101         (setq follow-to (message-get-reply-headers wide to-address)))
6102
6103       ;; Get the references from "In-Reply-To" field if there were
6104       ;; no references and "In-Reply-To" field looks promising.
6105       (unless references
6106         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
6107                    (string-match "<[^>]+>" in-reply-to))
6108           (setq references (match-string 0 in-reply-to)))))
6109
6110     (unless (message-mail-user-agent)
6111       (message-pop-to-buffer
6112        (message-buffer-name
6113         (if wide "wide reply" "reply") from
6114         (if wide to-address nil))))
6115
6116     (setq message-reply-headers
6117           (make-full-mail-header-from-decoded-header
6118            0 subject from date message-id references 0 0 ""))
6119
6120     (message-setup
6121      `((Subject . ,subject)
6122        ,@follow-to)
6123      cur)))
6124
6125 ;;;###autoload
6126 (defun message-wide-reply (&optional to-address)
6127   "Make a \"wide\" reply to the message in the current buffer."
6128   (interactive)
6129   (message-reply to-address t))
6130
6131 ;;;###autoload
6132 (defun message-followup (&optional to-newsgroups)
6133   "Follow up to the message in the current buffer.
6134 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6135   (interactive)
6136   (require 'gnus-sum)                   ; for gnus-list-identifiers
6137   (let ((cur (current-buffer))
6138         from subject date reply-to mrt mct mft
6139         references message-id follow-to
6140         (inhibit-point-motion-hooks t)
6141         (message-this-is-news t)
6142         followup-to distribution newsgroups gnus-warning posted-to)
6143     (save-restriction
6144       (message-narrow-to-head)
6145       (when (message-functionp message-followup-to-function)
6146         (setq follow-to
6147               (funcall message-followup-to-function)))
6148       (setq from (message-fetch-field "from")
6149             date (message-fetch-field "date")
6150             subject (or (message-fetch-field "subject") "none")
6151             references (message-fetch-field "references")
6152             message-id (message-fetch-field "message-id" t)
6153             followup-to (message-fetch-field "followup-to")
6154             newsgroups (message-fetch-field "newsgroups")
6155             posted-to (message-fetch-field "posted-to")
6156             reply-to (message-fetch-field "reply-to")
6157             mrt (when message-use-mail-reply-to
6158                   (message-fetch-field "mail-reply-to"))
6159             distribution (message-fetch-field "distribution")
6160             mct (when message-use-mail-copies-to
6161                   (message-fetch-field "mail-copies-to"))
6162             mft (when message-use-mail-followup-to
6163                   (message-fetch-field "mail-followup-to")))
6164       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6165                  (string-match "<[^>]+>" gnus-warning))
6166         (setq message-id (match-string 0 gnus-warning)))
6167       ;; Remove bogus distribution.
6168       (when (and (stringp distribution)
6169                  (let ((case-fold-search t))
6170                    (string-match "world" distribution)))
6171         (setq distribution nil))
6172       (if gnus-list-identifiers
6173           (setq subject (message-strip-list-identifiers subject)))
6174       (setq subject (message-make-followup-subject subject))
6175       (when message-subject-trailing-was-query
6176         (setq subject (message-strip-subject-trailing-was subject)))
6177       (widen))
6178
6179     ;; Handle special values of Mail-Copies-To.
6180     (when mct
6181       (cond
6182        ((and (or (equal (downcase mct) "never")
6183                  (equal (downcase mct) "nobody")))
6184         (setq mct nil))
6185        ((and (or (equal (downcase mct) "always")
6186                  (equal (downcase mct) "poster")))
6187         (if (or (not (eq message-use-mail-copies-to 'ask))
6188                 (message-y-or-n-p
6189                  (concat "Obey Mail-Copies-To: always? ") t "\
6190 You should normally obey the Mail-Copies-To: header.
6191
6192         `Mail-Copies-To: " mct "'
6193 sends a copy of your response to the author."))
6194             (setq mct (or mrt reply-to from))
6195           (setq mct nil)))
6196        ((and (eq message-use-mail-copies-to 'ask)
6197              (not
6198               (message-y-or-n-p
6199                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6200 You should normally obey the Mail-Copies-To: header.
6201
6202         `Mail-Copies-To: " mct "'
6203 sends a copy of your response to " (if (string-match "," mct)
6204                                        "the specified addresses"
6205                                      "that address") ".")))
6206         (setq mct nil))))
6207
6208     (unless follow-to
6209       (cond
6210        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
6211        ;; Handle Followup-To.
6212        (followup-to
6213         (cond
6214          ((equal (downcase followup-to) "poster")
6215           (if (or (and followup-to (eq message-use-followup-to 'use))
6216                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
6217 You should normally obey the Followup-To: header.
6218
6219         `Followup-To: poster'
6220 sends your response via e-mail instead of news.
6221
6222 A typical situation where `Followup-To: poster' is used is when the author
6223 does not read the newsgroup, so he wouldn't see any replies sent to it."))
6224               (setq message-this-is-news nil
6225                     distribution nil
6226                     follow-to (list (cons 'To (or mrt reply-to from ""))))
6227             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
6228          (t
6229           (if (or (equal followup-to newsgroups)
6230                   (not (and followup-to (eq message-use-followup-to 'ask)))
6231                   (message-y-or-n-p
6232                    (concat "Obey Followup-To: " followup-to "? ") t "\
6233 You should normally obey the Followup-To: header.
6234
6235         `Followup-To: " followup-to "'
6236 directs your response to " (if (string-match "," followup-to)
6237                                "the specified newsgroups"
6238                              "that newsgroup only") ".
6239
6240 If a message is posted to several newsgroups, Followup-To is often
6241 used to direct the following discussion to one newsgroup only,
6242 because discussions that are spread over several newsgroup tend to
6243 be fragmented and very difficult to follow.
6244
6245 Also, some source/announcement newsgroups are not intended for discussion;
6246 responses here are directed to other newsgroups."))
6247               (setq follow-to (list (cons 'Newsgroups followup-to)))
6248             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
6249        ;; Handle Mail-Followup-To, followup via e-mail.
6250        ((and mft
6251              (or (not (eq message-use-mail-followup-to 'ask))
6252                  (message-y-or-n-p
6253                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
6254 You should normally obey the Mail-Followup-To: header.
6255
6256         `Mail-Followup-To: " mft "'
6257 directs your response to " (if (string-match "," mft)
6258                                "the specified addresses"
6259                              "that address only") " instead of news.
6260
6261 A typical situation where Mail-Followup-To is used is when the author thinks
6262 that further discussion should take place only in "
6263                              (if (string-match "," mft)
6264                                  "the specified mailing lists"
6265                                "that mailing list") ".")))
6266         (setq message-this-is-news nil
6267               distribution nil
6268               follow-to (list (cons 'To mft))))
6269        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
6270        (t
6271         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
6272
6273     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6274
6275     (setq message-reply-headers
6276           (make-full-mail-header-from-decoded-header
6277            0 subject from date message-id references 0 0 ""))
6278
6279     (message-setup
6280      `((Subject . ,subject)
6281        ,@follow-to
6282        ,@(and mct (list (cons 'Cc mct)))
6283        ,@(and distribution (list (cons 'Distribution distribution))))
6284      cur)))
6285
6286 ;;;###autoload
6287 (defun message-cancel-news (&optional arg)
6288   "Cancel an article you posted.
6289 If ARG, allow editing of the cancellation message."
6290   (interactive "P")
6291   (unless (message-news-p)
6292     (error "This is not a news article; canceling is impossible"))
6293   (let (from newsgroups message-id distribution buf sender)
6294     (save-excursion
6295       ;; Get header info from original article.
6296       (save-restriction
6297         (message-narrow-to-head-1)
6298         (setq from (message-fetch-field "from")
6299               sender (message-fetch-field "sender")
6300               newsgroups (message-fetch-field "newsgroups")
6301               message-id (message-fetch-field "message-id" t)
6302               distribution (message-fetch-field "distribution")))
6303       ;; Make sure that this article was written by the user.
6304       (unless (or
6305                ;; Canlock-logic as suggested by Per Abrahamsen
6306                ;; <abraham@dina.kvl.dk>
6307                ;;
6308                ;; IF article has cancel-lock THEN
6309                ;;   IF we can verify it THEN
6310                ;;     issue cancel
6311                ;;   ELSE
6312                ;;     error: cancellock: article is not yours
6313                ;; ELSE
6314                ;;   Use old rules, comparing sender...
6315                (if (message-fetch-field "Cancel-Lock")
6316                    (if (null (canlock-verify))
6317                        t
6318                      (error "Failed to verify Cancel-lock: This article is not yours"))
6319                  nil)
6320                (message-gnksa-enable-p 'cancel-messages)
6321                (and sender
6322                     (string-equal
6323                      (downcase sender)
6324                      (downcase (message-make-sender))))
6325                (string-equal
6326                 (downcase (cadr (std11-extract-address-components from)))
6327                 (downcase (cadr (std11-extract-address-components
6328                                  (message-make-from))))))
6329         (error "This article is not yours"))
6330       (when (yes-or-no-p "Do you really want to cancel this article? ")
6331         ;; Make control message.
6332         (if arg
6333             (message-news)
6334           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6335         (erase-buffer)
6336         (insert "Newsgroups: " newsgroups "\n"
6337                 "From: " from "\n"
6338                 "Subject: cmsg cancel " message-id "\n"
6339                 "Control: cancel " message-id "\n"
6340                 (if distribution
6341                     (concat "Distribution: " distribution "\n")
6342                   "")
6343                 mail-header-separator "\n"
6344                 message-cancel-message)
6345         (run-hooks 'message-cancel-hook)
6346         (unless arg
6347           (message "Canceling your article...")
6348           (if (let ((message-syntax-checks
6349                      'dont-check-for-anything-just-trust-me)
6350                     (message-encoding-buffer (current-buffer))
6351                     (message-edit-buffer (current-buffer)))
6352                 (message-send-news))
6353               (message "Canceling your article...done"))
6354           (kill-buffer buf))))))
6355
6356 (defun message-supersede-setup-for-mime-edit ()
6357   (set (make-local-variable 'message-setup-hook) nil)
6358   (mime-edit-again))
6359
6360 ;;;###autoload
6361 (defun message-supersede ()
6362   "Start composing a message to supersede the current message.
6363 This is done simply by taking the old article and adding a Supersedes
6364 header line with the old Message-ID."
6365   (interactive)
6366   (let ((cur (current-buffer))
6367         (sender (message-fetch-field "sender"))
6368         (from (message-fetch-field "from")))
6369     ;; Check whether the user owns the article that is to be superseded.
6370     (unless (or
6371              ;; Canlock-logic as suggested by Per Abrahamsen
6372              ;; <abraham@dina.kvl.dk>
6373              ;;
6374              ;; IF article has cancel-lock THEN
6375              ;;   IF we can verify it THEN
6376              ;;     issue cancel
6377              ;;   ELSE
6378              ;;     error: cancellock: article is not yours
6379              ;; ELSE
6380              ;;   Use old rules, comparing sender...
6381              (if (message-fetch-field "Cancel-Lock")
6382                  (if (null (canlock-verify))
6383                      t
6384                    (error "Failed to verify Cancel-lock: This article is not yours"))
6385                nil)
6386              (message-gnksa-enable-p 'cancel-messages)
6387              (and sender
6388                   (string-equal
6389                    (downcase sender)
6390                    (downcase (message-make-sender))))
6391              (string-equal
6392               (downcase (cadr (std11-extract-address-components from)))
6393               (downcase (cadr (std11-extract-address-components
6394                                (message-make-from))))))
6395       (error "This article is not yours"))
6396     ;; Get a normal message buffer.
6397     (message-pop-to-buffer (message-buffer-name "supersede"))
6398     (insert-buffer-substring cur)
6399     (message-narrow-to-head-1)
6400     ;; Remove unwanted headers.
6401     (when message-ignored-supersedes-headers
6402       (message-remove-header message-ignored-supersedes-headers t))
6403     (goto-char (point-min))
6404     (if (not (re-search-forward "^Message-ID: " nil t))
6405         (error "No Message-ID in this article")
6406       (replace-match "Supersedes: " t t))
6407     (goto-char (point-max))
6408     (insert mail-header-separator)
6409     (widen)
6410     (when message-supersede-setup-function
6411       (funcall message-supersede-setup-function))
6412     (run-hooks 'message-supersede-setup-hook)
6413     (goto-char (point-min))
6414     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
6415
6416 ;;;###autoload
6417 (defun message-recover ()
6418   "Reread contents of current buffer from its last auto-save file."
6419   (interactive)
6420   (let ((file-name (make-auto-save-file-name)))
6421     (cond ((save-window-excursion
6422              (if (not (eq system-type 'vax-vms))
6423                  (with-output-to-temp-buffer "*Directory*"
6424                    (with-current-buffer standard-output
6425                      (fundamental-mode)) ; for Emacs 20.4+
6426                    (buffer-disable-undo standard-output)
6427                    (let ((default-directory "/"))
6428                      (call-process
6429                       "ls" nil standard-output nil "-l" file-name))))
6430              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6431            (let ((buffer-read-only nil))
6432              (erase-buffer)
6433              (insert-file-contents file-name nil)))
6434           (t (error "message-recover cancelled")))))
6435
6436 ;;; Washing Subject:
6437
6438 (defun message-wash-subject (subject)
6439   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6440 Previous forwarders, replyers, etc. may add it."
6441   (with-temp-buffer
6442     (insert subject)
6443     (goto-char (point-min))
6444     ;; strip Re/Fwd stuff off the beginning
6445     (while (re-search-forward
6446             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6447       (replace-match ""))
6448
6449     ;; and gnus-style forwards [foo@bar.com] subject
6450     (goto-char (point-min))
6451     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6452       (replace-match ""))
6453
6454     ;; and off the end
6455     (goto-char (point-max))
6456     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6457       (replace-match ""))
6458
6459     ;; and finally, any whitespace that was left-over
6460     (goto-char (point-min))
6461     (while (re-search-forward "^[ \t]+" nil t)
6462       (replace-match ""))
6463     (goto-char (point-max))
6464     (while (re-search-backward "[ \t]+$" nil t)
6465       (replace-match ""))
6466
6467     (buffer-string)))
6468
6469 ;;; Forwarding messages.
6470
6471 (defvar message-forward-decoded-p nil
6472   "Non-nil means the original message is decoded.")
6473
6474 (defun message-forward-subject-author-subject (subject)
6475   "Generate a SUBJECT for a forwarded message.
6476 The form is: [Source] Subject, where if the original message was mail,
6477 Source is the sender, and if the original message was news, Source is
6478 the list of newsgroups is was posted to."
6479   (concat "["
6480           (let ((prefix (message-fetch-field "newsgroups")))
6481             (or prefix
6482                 (and (setq prefix (message-fetch-field "from"))
6483                      (nnheader-decode-from prefix))
6484                 "(nowhere)"))
6485           "] " subject))
6486
6487 (defun message-forward-subject-fwd (subject)
6488   "Generate a SUBJECT for a forwarded message.
6489 The form is: Fwd: Subject, where Subject is the original subject of
6490 the message."
6491   (concat "Fwd: " subject))
6492
6493 (defun message-make-forward-subject ()
6494   "Return a Subject header suitable for the message in the current buffer."
6495   (save-excursion
6496     (save-restriction
6497       (message-narrow-to-head-1)
6498       (let ((funcs message-make-forward-subject-function)
6499             (subject (message-fetch-field "Subject")))
6500         (setq subject
6501               (if subject
6502                   (if message-forward-decoded-p
6503                       subject
6504                     (nnheader-decode-subject subject))
6505                 ""))
6506         (if message-wash-forwarded-subjects
6507             (setq subject (message-wash-subject subject)))
6508         ;; Make sure funcs is a list.
6509         (and funcs
6510              (not (listp funcs))
6511              (setq funcs (list funcs)))
6512         ;; Apply funcs in order, passing subject generated by previous
6513         ;; func to the next one.
6514         (while funcs
6515           (when (message-functionp (car funcs))
6516             (setq subject (funcall (car funcs) subject)))
6517           (setq funcs (cdr funcs)))
6518         subject))))
6519
6520 ;;;###autoload
6521 (defun message-forward (&optional news)
6522   "Forward the current message via mail.
6523 Optional NEWS will use news to forward instead of mail."
6524   (interactive "P")
6525   (let ((cur (current-buffer))
6526         (subject (message-make-forward-subject)))
6527     (if news
6528         (message-news nil subject)
6529       (message-mail nil subject))
6530     (message-forward-make-body cur)))
6531
6532 ;;;###autoload
6533 (defun message-forward-make-body (forward-buffer)
6534   ;; Put point where we want it before inserting the forwarded
6535   ;; message.
6536   ;; Note that this function definition for T-gnus is totally different
6537   ;; from the original Gnus."
6538   (if message-forward-before-signature
6539       (message-goto-body)
6540     (goto-char (point-max)))
6541   ;; Make sure we're at the start of the line.
6542   (unless (bolp)
6543     (insert "\n"))
6544   ;; Narrow to the area we are to insert.
6545   (narrow-to-region (point) (point))
6546   ;; Insert the separators and the forwarded buffer.
6547   (insert message-forward-start-separator)
6548   (let ((art-beg (point)))
6549     (insert-buffer-substring forward-buffer)
6550     (goto-char (point-max))
6551     (insert message-forward-end-separator)
6552     (set-text-properties (point-min) (point-max) nil)
6553     ;; Remove all unwanted headers.
6554     (goto-char art-beg)
6555     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
6556                                   (1- (point))
6557                                 (point)))
6558     (goto-char (point-min))
6559     (message-remove-header message-included-forward-headers t nil t)
6560     (widen)
6561     (message-position-point)))
6562
6563 ;;;###autoload
6564 (defun message-forward-rmail-make-body (forward-buffer)
6565   (save-window-excursion
6566     (set-buffer forward-buffer)
6567     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
6568     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
6569     (if (rmail-msg-is-pruned)
6570         (rmail-msg-restore-non-pruned-header)))
6571   (message-forward-make-body forward-buffer))
6572
6573 ;;;###autoload
6574 (defun message-insinuate-rmail ()
6575   "Let RMAIL uses message to forward."
6576   (interactive)
6577   (setq rmail-enable-mime-composing t)
6578   (setq rmail-insert-mime-forwarded-message-function
6579         'message-forward-rmail-make-body))
6580
6581 ;;;###autoload
6582 (defun message-resend (address)
6583   "Resend the current article to ADDRESS."
6584   (interactive
6585    (list (message-read-from-minibuffer "Resend message to: ")))
6586   (message "Resending message to %s..." address)
6587   (save-excursion
6588     (let ((cur (current-buffer))
6589           beg)
6590       ;; We first set up a normal mail buffer.
6591       (unless (message-mail-user-agent)
6592         (set-buffer (get-buffer-create " *message resend*"))
6593         (erase-buffer))
6594       (let ((message-this-is-mail t)
6595             message-setup-hook)
6596         (message-setup `((To . ,address))))
6597       ;; Insert our usual headers.
6598       (message-generate-headers '(From Date To))
6599       (message-narrow-to-headers)
6600       ;; Remove X-Draft-From header etc.
6601       (message-remove-header message-ignored-mail-headers t)
6602       ;; Rename them all to "Resent-*".
6603       (goto-char (point-min))
6604       (while (re-search-forward "^[A-Za-z]" nil t)
6605         (forward-char -1)
6606         (insert "Resent-"))
6607       (widen)
6608       (forward-line)
6609       (delete-region (point) (point-max))
6610       (setq beg (point))
6611       ;; Insert the message to be resent.
6612       (insert-buffer-substring cur)
6613       (goto-char (point-min))
6614       (search-forward "\n\n")
6615       (forward-char -1)
6616       (save-restriction
6617         (narrow-to-region beg (point))
6618         (message-remove-header message-ignored-resent-headers t)
6619         (goto-char (point-max)))
6620       (insert mail-header-separator)
6621       ;; Rename all old ("Also-")Resent headers.
6622       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6623         (beginning-of-line)
6624         (insert "Also-"))
6625       ;; Quote any "From " lines at the beginning.
6626       (goto-char beg)
6627       (when (looking-at "From ")
6628         (replace-match "X-From-Line: "))
6629       ;; Send it.
6630       (let ((message-encoding-buffer (current-buffer))
6631             (message-edit-buffer (current-buffer))
6632             message-required-mail-headers)
6633         (message-send-mail))
6634       (kill-buffer (current-buffer)))
6635     (message "Resending message to %s...done" address)))
6636
6637 (defun message-bounce-setup-for-mime-edit ()
6638   (set (make-local-variable 'message-setup-hook) nil)
6639   (mime-edit-again))
6640
6641 ;;;###autoload
6642 (defun message-bounce ()
6643   "Re-mail the current message.
6644 This only makes sense if the current message is a bounce message that
6645 contains some mail you have written which has been bounced back to
6646 you."
6647   (interactive)
6648   (let ((cur (current-buffer))
6649         boundary)
6650     (message-pop-to-buffer (message-buffer-name "bounce"))
6651     (insert-buffer-substring cur)
6652     (undo-boundary)
6653     (message-narrow-to-head)
6654     (if (and (message-fetch-field "MIME-Version")
6655              (setq boundary (message-fetch-field "Content-Type")))
6656         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
6657             (setq boundary (concat (match-string 1 boundary) " *\n"
6658                                    "Content-Type: message/rfc822"))
6659           (setq boundary nil)))
6660     (widen)
6661     (goto-char (point-min))
6662     (search-forward "\n\n" nil t)
6663     (if (or (and boundary
6664                  (re-search-forward boundary nil t)
6665                  (forward-line 2))
6666             (and (re-search-forward message-unsent-separator nil t)
6667                  (forward-line 1))
6668             (re-search-forward "^Return-Path:.*\n" nil t))
6669         ;; We remove everything before the bounced mail.
6670         (delete-region
6671          (point-min)
6672          (if (re-search-forward "^[^ \n\t]+:" nil t)
6673              (match-beginning 0)
6674            (point)))
6675       (when (re-search-backward "^.?From .*\n" nil t)
6676         (delete-region (match-beginning 0) (match-end 0))))
6677     (save-restriction
6678       (message-narrow-to-head-1)
6679       (message-remove-header message-ignored-bounced-headers t)
6680       (goto-char (point-max))
6681       (insert mail-header-separator))
6682     (when message-bounce-setup-function
6683       (funcall message-bounce-setup-function))
6684     (run-hooks 'message-bounce-setup-hook)
6685     (message-position-point)))
6686
6687 ;;;
6688 ;;; Interactive entry points for new message buffers.
6689 ;;;
6690
6691 ;;;###autoload
6692 (defun message-mail-other-window (&optional to subject)
6693   "Like `message-mail' command, but display mail buffer in another window."
6694   (interactive)
6695   (unless (message-mail-user-agent)
6696     (let ((pop-up-windows t)
6697           (special-display-buffer-names nil)
6698           (special-display-regexps nil)
6699           (same-window-buffer-names nil)
6700           (same-window-regexps nil))
6701       (message-pop-to-buffer (message-buffer-name "mail" to))))
6702   (let ((message-this-is-mail t))
6703     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6704                    nil nil 'switch-to-buffer-other-window)))
6705
6706 ;;;###autoload
6707 (defun message-mail-other-frame (&optional to subject)
6708   "Like `message-mail' command, but display mail buffer in another frame."
6709   (interactive)
6710   (unless (message-mail-user-agent)
6711     (let ((pop-up-frames t)
6712           (special-display-buffer-names nil)
6713           (special-display-regexps nil)
6714           (same-window-buffer-names nil)
6715           (same-window-regexps nil))
6716       (message-pop-to-buffer (message-buffer-name "mail" to))))
6717   (let ((message-this-is-mail t))
6718     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6719                    nil nil 'switch-to-buffer-other-frame)))
6720
6721 ;;;###autoload
6722 (defun message-news-other-window (&optional newsgroups subject)
6723   "Start editing a news article to be sent."
6724   (interactive)
6725   (let ((pop-up-windows t)
6726         (special-display-buffer-names nil)
6727         (special-display-regexps nil)
6728         (same-window-buffer-names nil)
6729         (same-window-regexps nil))
6730     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6731   (let ((message-this-is-news t))
6732     (message-setup `((Newsgroups . ,(or newsgroups ""))
6733                      (Subject . ,(or subject ""))))))
6734
6735 ;;;###autoload
6736 (defun message-news-other-frame (&optional newsgroups subject)
6737   "Start editing a news article to be sent."
6738   (interactive)
6739   (let ((pop-up-frames t)
6740         (special-display-buffer-names nil)
6741         (special-display-regexps nil)
6742         (same-window-buffer-names nil)
6743         (same-window-regexps nil))
6744     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6745   (let ((message-this-is-news t))
6746     (message-setup `((Newsgroups . ,(or newsgroups ""))
6747                      (Subject . ,(or subject ""))))))
6748
6749 ;;; underline.el
6750
6751 ;; This code should be moved to underline.el (from which it is stolen).
6752
6753 ;;;###autoload
6754 (defun bold-region (start end)
6755   "Bold all nonblank characters in the region.
6756 Works by overstriking characters.
6757 Called from program, takes two arguments START and END
6758 which specify the range to operate on."
6759   (interactive "r")
6760   (save-excursion
6761     (let ((end1 (make-marker)))
6762       (move-marker end1 (max start end))
6763       (goto-char (min start end))
6764       (while (< (point) end1)
6765         (or (looking-at "[_\^@- ]")
6766             (insert (char-after) "\b"))
6767         (forward-char 1)))))
6768
6769 ;;;###autoload
6770 (defun unbold-region (start end)
6771   "Remove all boldness (overstruck characters) in the region.
6772 Called from program, takes two arguments START and END
6773 which specify the range to operate on."
6774   (interactive "r")
6775   (save-excursion
6776     (let ((end1 (make-marker)))
6777       (move-marker end1 (max start end))
6778       (goto-char (min start end))
6779       (while (re-search-forward "\b" end1 t)
6780         (if (eq (char-after) (char-after (- (point) 2)))
6781             (delete-char -2))))))
6782
6783 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
6784
6785 ;; Support for toolbar
6786 (eval-when-compile
6787   (defvar tool-bar-map)
6788   (defvar tool-bar-mode))
6789
6790 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6791   ;; We need to make tool bar entries in local keymaps with
6792   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6793   (if (fboundp 'tool-bar-local-item-from-menu)
6794       ;; This is for Emacs 21.3
6795       (tool-bar-local-item-from-menu command icon in-map from-map props)
6796     (tool-bar-add-item-from-menu command icon from-map props)))
6797
6798 (defun message-tool-bar-map ()
6799   (or message-tool-bar-map
6800       (setq message-tool-bar-map
6801             (and
6802              (condition-case nil (require 'tool-bar) (error nil))
6803              (fboundp 'tool-bar-add-item-from-menu)
6804              tool-bar-mode
6805              (let ((tool-bar-map (copy-keymap tool-bar-map))
6806                    (load-path (mm-image-load-path)))
6807                ;; Zap some items which aren't so relevant and take
6808                ;; up space.
6809                (dolist (key '(print-buffer kill-buffer save-buffer
6810                                            write-file dired open-file))
6811                  (define-key tool-bar-map (vector key) nil))
6812                (message-tool-bar-local-item-from-menu
6813                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
6814                (message-tool-bar-local-item-from-menu
6815                 'message-kill-buffer "close" tool-bar-map message-mode-map)
6816                (message-tool-bar-local-item-from-menu
6817                 'message-dont-send "cancel" tool-bar-map message-mode-map)
6818 ;;             (message-tool-bar-local-item-from-menu
6819 ;;              'mime-edit-insert-file "attach"
6820 ;;              tool-bar-map mime-edit-mode-map)
6821                (message-tool-bar-local-item-from-menu
6822                 'ispell-message "spell" tool-bar-map message-mode-map)
6823 ;;             (message-tool-bar-local-item-from-menu
6824 ;;              'mime-edit-preview-message "preview"
6825 ;;              tool-bar-map mime-edit-mode-map)
6826                (message-tool-bar-local-item-from-menu
6827                 'message-insert-importance-high "important"
6828                 tool-bar-map message-mode-map)
6829                (message-tool-bar-local-item-from-menu
6830                 'message-insert-importance-low "unimportant"
6831                 tool-bar-map message-mode-map)
6832                (message-tool-bar-local-item-from-menu
6833                 'message-insert-disposition-notification-to "receipt"
6834                 tool-bar-map message-mode-map)
6835                tool-bar-map)))))
6836
6837 ;;; Group name completion.
6838
6839 (defcustom message-newgroups-header-regexp
6840   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6841   "Regexp that match headers that lists groups."
6842   :group 'message
6843   :type 'regexp)
6844
6845 (defcustom message-completion-alist
6846   (list (cons message-newgroups-header-regexp 'message-expand-group)
6847         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6848         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6849           . message-expand-name)
6850         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6851           . message-expand-name))
6852   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6853   :group 'message
6854   :type '(alist :key-type regexp :value-type function))
6855
6856 (defcustom message-expand-name-function
6857   (if (fboundp 'bbdb-complete-name)
6858       'bbdb-complete-name
6859     (if (fboundp 'lsdb-complete-name)
6860         'lsdb-complete-name
6861       'expand-abbrev))
6862   "*A function called to expand addresses in field body."
6863   :group 'message
6864   :type 'function)
6865
6866 (defcustom message-tab-body-function nil
6867   "*Function to execute when `message-tab' (TAB) is executed in the body.
6868 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6869   :group 'message
6870   :type 'function)
6871
6872 (defun message-tab ()
6873   "Complete names according to `message-completion-alist'.
6874 Execute function specified by `message-tab-body-function' when not in
6875 those headers."
6876   (interactive)
6877   (let ((alist message-completion-alist))
6878     (while (and alist
6879                 (let ((mail-abbrev-mode-regexp (caar alist)))
6880                   (not (mail-abbrev-in-expansion-header-p))))
6881       (setq alist (cdr alist)))
6882     (funcall (or (cdar alist) message-tab-body-function
6883                  (lookup-key text-mode-map "\t")
6884                  (lookup-key global-map "\t")
6885                  'indent-relative))))
6886
6887 (defun message-expand-group ()
6888   "Expand the group name under point."
6889   (let* ((b (save-excursion
6890               (save-restriction
6891                 (narrow-to-region
6892                  (save-excursion
6893                    (beginning-of-line)
6894                    (skip-chars-forward "^:")
6895                    (1+ (point)))
6896                  (point))
6897                 (skip-chars-backward "^, \t\n") (point))))
6898          (completion-ignore-case t)
6899          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6900                                             (point))))
6901          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6902          (completions (all-completions string hashtb))
6903          comp)
6904     (delete-region b (point))
6905     (cond
6906      ((= (length completions) 1)
6907       (if (string= (car completions) string)
6908           (progn
6909             (insert string)
6910             (message "Only matching group"))
6911         (insert (car completions))))
6912      ((and (setq comp (try-completion string hashtb))
6913            (not (string= comp string)))
6914       (insert comp))
6915      (t
6916       (insert string)
6917       (if (not comp)
6918           (message "No matching groups")
6919         (save-selected-window
6920           (pop-to-buffer "*Completions*")
6921           (buffer-disable-undo)
6922           (let ((buffer-read-only nil))
6923             (erase-buffer)
6924             (let ((standard-output (current-buffer)))
6925               (display-completion-list (sort completions 'string<)))
6926             (goto-char (point-min))
6927             (delete-region (point) (progn (forward-line 3) (point))))))))))
6928
6929 (defun message-expand-name ()
6930   (funcall message-expand-name-function))
6931
6932 ;;; Help stuff.
6933
6934 (defun message-talkative-question (ask question show &rest text)
6935   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6936 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6937 The following arguments may contain lists of values."
6938   (if (and show
6939            (setq text (message-flatten-list text)))
6940       (save-window-excursion
6941         (save-excursion
6942           (with-output-to-temp-buffer " *MESSAGE information message*"
6943             (set-buffer " *MESSAGE information message*")
6944             (fundamental-mode)          ; for Emacs 20.4+
6945             (mapcar 'princ text)
6946             (goto-char (point-min))))
6947         (funcall ask question))
6948     (funcall ask question)))
6949
6950 (defun message-flatten-list (list)
6951   "Return a new, flat list that contains all elements of LIST.
6952
6953 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6954 => (1 2 3 4 5 6 7)"
6955   (cond ((consp list)
6956          (apply 'append (mapcar 'message-flatten-list list)))
6957         (list
6958          (list list))))
6959
6960 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6961   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6962 Then clone the local variables and values from the old buffer to the
6963 new one, cloning only the locals having a substring matching the
6964 regexp varstr."
6965   (let ((oldbuf (current-buffer)))
6966     (save-excursion
6967       (set-buffer (generate-new-buffer name))
6968       (message-clone-locals oldbuf varstr)
6969       (current-buffer))))
6970
6971 (defun message-clone-locals (buffer &optional varstr)
6972   "Clone the local variables from BUFFER to the current buffer."
6973   (let ((locals (save-excursion
6974                   (set-buffer buffer)
6975                   (buffer-local-variables)))
6976         (regexp
6977          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
6978     (mapcar
6979      (lambda (local)
6980        (when (and (consp local)
6981                   (car local)
6982                   (string-match regexp (symbol-name (car local)))
6983                   (or (null varstr)
6984                       (string-match varstr (symbol-name (car local)))))
6985          (ignore-errors
6986            (set (make-local-variable (car local))
6987                 (cdr local)))))
6988      locals)))
6989
6990
6991 ;;; @ for MIME Edit mode
6992 ;;;
6993
6994 (defun message-maybe-encode ()
6995   (when message-mime-mode
6996     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
6997     (let ((pgp-processing (with-current-buffer message-edit-buffer
6998                             mime-edit-pgp-processing)))
6999       (setq mime-edit-pgp-processing pgp-processing))
7000     (run-hooks 'mime-edit-translate-hook)
7001     (if (catch 'mime-edit-error
7002           (save-excursion
7003             (mime-edit-pgp-enclose-buffer)
7004             (mime-edit-translate-body)))
7005         (error "Translation error!"))
7006     (run-hooks 'mime-edit-exit-hook)))
7007
7008 (defun message-mime-insert-article (&optional full-headers)
7009   (interactive "P")
7010   (let ((message-cite-function 'mime-edit-inserted-message-filter)
7011         (message-reply-buffer
7012          (message-get-parameter-with-eval 'original-buffer))
7013         (start (point)))
7014     (message-yank-original nil)
7015     (save-excursion
7016       (narrow-to-region (goto-char start)
7017                         (if (search-forward "\n\n" nil t)
7018                             (1- (point))
7019                           (point-max)))
7020       (goto-char (point-min))
7021       (let ((message-included-forward-headers
7022              (if full-headers "" message-included-forward-headers)))
7023         (message-remove-header message-included-forward-headers t nil t))
7024       (widen))))
7025
7026 (set-alist 'mime-edit-message-inserter-alist
7027            'message-mode (function message-mime-insert-article))
7028
7029 ;;; Miscellaneous functions
7030
7031 ;; stolen (and renamed) from nnheader.el
7032 (static-if (fboundp 'subst-char-in-string)
7033     (defsubst message-replace-chars-in-string (string from to)
7034       (subst-char-in-string from to string))
7035   (defun message-replace-chars-in-string (string from to)
7036     "Replace characters in STRING from FROM to TO."
7037     (let ((string (substring string 0)) ;Copy string.
7038           (len (length string))
7039           (idx 0))
7040       ;; Replace all occurrences of FROM with TO.
7041       (while (< idx len)
7042         (when (= (aref string idx) from)
7043           (aset string idx to))
7044         (setq idx (1+ idx)))
7045       string)))
7046
7047 ;;;
7048 ;;; MIME functions
7049 ;;;
7050
7051 (defvar message-inhibit-body-encoding t)
7052
7053 (defun message-encode-message-body ()
7054   (unless message-inhibit-body-encoding
7055     (let ((mail-parse-charset (or mail-parse-charset
7056                                   message-default-charset))
7057           (case-fold-search t)
7058           lines content-type-p)
7059       (message-goto-body)
7060       (save-restriction
7061         (narrow-to-region (point) (point-max))
7062         (let ((new (mml-generate-mime)))
7063           (when new
7064             (delete-region (point-min) (point-max))
7065             (insert new)
7066             (goto-char (point-min))
7067             (if (eq (aref new 0) ?\n)
7068                 (delete-char 1)
7069               (search-forward "\n\n")
7070               (setq lines (buffer-substring (point-min) (1- (point))))
7071               (delete-region (point-min) (point))))))
7072       (save-restriction
7073         (message-narrow-to-headers-or-head)
7074         (message-remove-header "Mime-Version")
7075         (goto-char (point-max))
7076         (insert "MIME-Version: 1.0\n")
7077         (when lines
7078           (insert lines))
7079         (setq content-type-p
7080               (or mml-boundary
7081                   (re-search-backward "^Content-Type:" nil t))))
7082       (save-restriction
7083         (message-narrow-to-headers-or-head)
7084         (message-remove-first-header "Content-Type")
7085         (message-remove-first-header "Content-Transfer-Encoding"))
7086       ;; We always make sure that the message has a Content-Type
7087       ;; header.  This is because some broken MTAs and MUAs get
7088       ;; awfully confused when confronted with a message with a
7089       ;; MIME-Version header and without a Content-Type header.  For
7090       ;; instance, Solaris' /usr/bin/mail.
7091       (unless content-type-p
7092         (goto-char (point-min))
7093         ;; For unknown reason, MIME-Version doesn't exist.
7094         (when (re-search-forward "^MIME-Version:" nil t)
7095           (forward-line 1)
7096           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7097
7098 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7099   "Read from the minibuffer while providing abbrev expansion."
7100   (if (fboundp 'mail-abbrevs-setup)
7101       (let ((mail-abbrev-mode-regexp "")
7102             (minibuffer-setup-hook 'mail-abbrevs-setup)
7103             (minibuffer-local-map message-minibuffer-local-map))
7104         (read-from-minibuffer prompt initial-contents))
7105     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7106           (minibuffer-local-map message-minibuffer-local-map))
7107       (read-string prompt initial-contents))))
7108
7109 (defun message-use-alternative-email-as-from ()
7110   (require 'mail-utils)
7111   (let* ((fields '("To" "Cc"))
7112          (emails
7113           (split-string
7114            (mail-strip-quoted-names
7115             (mapconcat 'message-fetch-reply-field fields ","))
7116            "[ \f\t\n\r\v,]+"))
7117          email)
7118     (while emails
7119       (if (string-match message-alternative-emails (car emails))
7120           (setq email (car emails)
7121                 emails nil))
7122       (pop emails))
7123     (unless (or (not email) (equal email user-mail-address))
7124       (goto-char (point-max))
7125       (insert "From: " email "\n"))))
7126
7127 (defun message-options-get (symbol)
7128   (cdr (assq symbol message-options)))
7129
7130 (defun message-options-set (symbol value)
7131   (let ((the-cons (assq symbol message-options)))
7132     (if the-cons
7133         (if value
7134             (setcdr the-cons value)
7135           (setq message-options (delq the-cons message-options)))
7136       (and value
7137            (push (cons symbol value) message-options))))
7138   value)
7139
7140 (defun message-options-set-recipient ()
7141   (save-restriction
7142     (message-narrow-to-headers-or-head)
7143     (message-options-set 'message-sender
7144                          (mail-strip-quoted-names
7145                           (message-fetch-field "from")))
7146     (message-options-set 'message-recipients
7147                          (mail-strip-quoted-names
7148                           (let ((to (message-fetch-field "to"))
7149                                 (cc (message-fetch-field "cc"))
7150                                 (bcc (message-fetch-field "bcc")))
7151                             (concat
7152                              (or to "")
7153                              (if (and to cc) ", ")
7154                              (or cc "")
7155                              (if (and (or to cc) bcc) ", ")
7156                              (or bcc "")))))))
7157
7158 (when (featurep 'xemacs)
7159   (require 'messagexmas)
7160   (message-xmas-redefine))
7161
7162 (provide 'message)
7163
7164 (run-hooks 'message-load-hook)
7165
7166 ;; Local Variables:
7167 ;; coding: iso-8859-1
7168 ;; End:
7169
7170 ;;; message.el ends here