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