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