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