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