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