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