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