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