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