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