(message-send-mail-with-sendmail): Use with-current-buffer.
[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:"
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       (set-text-properties 0 (length value) nil value)
1646       value)))
1647
1648 (defun message-field-value (header &optional not-all)
1649   "The same as `message-fetch-field', only narrow to the headers first."
1650   (save-excursion
1651     (save-restriction
1652       (message-narrow-to-headers-or-head)
1653       (message-fetch-field header not-all))))
1654
1655 (defun message-narrow-to-field ()
1656   "Narrow the buffer to the header on the current line."
1657   (beginning-of-line)
1658   (while (looking-at "[ \t]")
1659     (forward-line -1))
1660   (narrow-to-region
1661    (point)
1662    (progn
1663      (forward-line 1)
1664      (if (re-search-forward "^[^ \n\t]" nil t)
1665          (point-at-bol)
1666        (point-max))))
1667   (goto-char (point-min)))
1668
1669 (defun message-add-header (&rest headers)
1670   "Add the HEADERS to the message header, skipping those already present."
1671   (while headers
1672     (let (hclean)
1673       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1674         (error "Invalid header `%s'" (car headers)))
1675       (setq hclean (match-string 1 (car headers)))
1676       (save-restriction
1677         (message-narrow-to-headers)
1678         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1679           (goto-char (point-max))
1680           (if (string-match "\n$" (car headers))
1681               (insert (car headers))
1682             (insert (car headers) ?\n)))))
1683     (setq headers (cdr headers))))
1684
1685 (defmacro message-with-reply-buffer (&rest forms)
1686   "Evaluate FORMS in the reply buffer, if it exists."
1687   `(when (and message-reply-buffer
1688               (buffer-name message-reply-buffer))
1689      (save-excursion
1690        (set-buffer message-reply-buffer)
1691        ,@forms)))
1692
1693 (put 'message-with-reply-buffer 'lisp-indent-function 0)
1694 (put 'message-with-reply-buffer 'edebug-form-spec '(body))
1695
1696 (defun message-fetch-reply-field (header)
1697   "Fetch field HEADER from the message we're replying to."
1698   (message-with-reply-buffer
1699     (save-restriction
1700       (mail-narrow-to-head)
1701       (message-fetch-field header))))
1702
1703 (defun message-strip-list-identifiers (subject)
1704   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1705   (require 'gnus-sum)                   ; for gnus-list-identifiers
1706   (let ((regexp (if (stringp gnus-list-identifiers)
1707                     gnus-list-identifiers
1708                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1709     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1710                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1711         (concat (substring subject 0 (match-beginning 1))
1712                 (or (match-string 3 subject)
1713                     (match-string 5 subject))
1714                 (substring subject
1715                            (match-end 1)))
1716       subject)))
1717
1718 (defun message-strip-subject-re (subject)
1719   "Remove \"Re:\" from subject lines in string SUBJECT."
1720   (if (string-match message-subject-re-regexp subject)
1721       (substring subject (match-end 0))
1722     subject))
1723
1724 ;;; Start of functions adopted from `message-utils.el'.
1725
1726 (defun message-strip-subject-trailing-was (subject)
1727   "Remove trailing \"(Was: <old subject>)\" from SUBJECT lines.
1728 Leading \"Re: \" is not stripped by this function.  Use the function
1729 `message-strip-subject-re' for this."
1730   (let* ((query message-subject-trailing-was-query)
1731          (new) (found))
1732     (setq found
1733           (string-match
1734            (if (eq query 'ask)
1735                message-subject-trailing-was-ask-regexp
1736              message-subject-trailing-was-regexp)
1737            subject))
1738     (if found
1739         (setq new (substring subject 0 (match-beginning 0))))
1740     (if (or (not found) (eq query nil))
1741         subject
1742       (if (eq query 'ask)
1743           (if (message-y-or-n-p
1744                "Strip `(was: <old subject>)' in subject? " t
1745                (concat
1746                 "Strip `(was: <old subject>)' in subject "
1747                 "and use the new one instead?\n\n"
1748                 "Current subject is:   \""
1749                 subject "\"\n\n"
1750                 "New subject would be: \""
1751                 new "\"\n\n"
1752                 "See the variable `message-subject-trailing-was-query' "
1753                 "to get rid of this query."
1754                 ))
1755               new subject)
1756         new))))
1757
1758 ;;; Suggested by Jonas Steverud  @  www.dtek.chalmers.se/~d4jonas/
1759
1760 ;;;###autoload
1761 (defun message-change-subject (new-subject)
1762   "Ask for NEW-SUBJECT header, append (was: <Old Subject>)."
1763   ;; <URL:http://www.landfield.com/usefor/drafts/draft-ietf-usefor-useage--1.02.unpaged>
1764   (interactive
1765    (list
1766     (read-from-minibuffer "New subject: ")))
1767   (cond ((and (not (or (null new-subject) ; new subject not empty
1768                        (zerop (string-width new-subject))
1769                        (string-match "^[ \t]*$" new-subject))))
1770          (save-excursion
1771            (let ((old-subject
1772                   (save-restriction
1773                     (message-narrow-to-headers)
1774                     (message-fetch-field "Subject"))))
1775              (cond ((not old-subject)
1776                     (error "No current subject"))
1777                    ((not (string-match
1778                           (concat "^[ \t]*"
1779                                   (regexp-quote new-subject)
1780                                   " \t]*$")
1781                           old-subject))  ; yes, it really is a new subject
1782                     ;; delete eventual Re: prefix
1783                     (setq old-subject
1784                           (message-strip-subject-re old-subject))
1785                     (message-goto-subject)
1786                     (message-delete-line)
1787                     (insert (concat "Subject: "
1788                                     new-subject
1789                                     " (was: "
1790                                     old-subject ")\n")))))))))
1791
1792 ;;;###autoload
1793 (defun message-mark-inserted-region (beg end)
1794   "Mark some region in the current article with enclosing tags.
1795 See `message-mark-insert-begin' and `message-mark-insert-end'."
1796   (interactive "r")
1797   (save-excursion
1798     ;; add to the end of the region first, otherwise end would be invalid
1799     (goto-char end)
1800     (insert message-mark-insert-end)
1801     (goto-char beg)
1802     (insert message-mark-insert-begin)))
1803
1804 ;;;###autoload
1805 (defun message-mark-insert-file (file)
1806   "Insert FILE at point, marking it with enclosing tags.
1807 See `message-mark-insert-begin' and `message-mark-insert-end'."
1808   (interactive "fFile to insert: ")
1809     ;; reverse insertion to get correct result.
1810   (let ((p (point)))
1811     (insert message-mark-insert-end)
1812     (goto-char p)
1813     (insert-file-contents file)
1814     (goto-char p)
1815     (insert message-mark-insert-begin)))
1816
1817 ;;;###autoload
1818 (defun message-add-archive-header ()
1819   "Insert \"X-No-Archive: Yes\" in the header and a note in the body.
1820 The note can be customized using `message-archive-note'.  When called with a
1821 prefix argument, ask for a text to insert.  If you don't want the note in the
1822 body, set  `message-archive-note' to nil."
1823   (interactive)
1824   (if current-prefix-arg
1825       (setq message-archive-note
1826             (read-from-minibuffer "Reason for No-Archive: "
1827                                   (cons message-archive-note 0))))
1828     (save-excursion
1829       (if (message-goto-signature)
1830           (re-search-backward message-signature-separator))
1831       (when message-archive-note
1832         (insert message-archive-note)
1833         (newline))
1834       (message-add-header message-archive-header)
1835       (message-sort-headers)))
1836
1837 ;;;###autoload
1838 (defun message-cross-post-followup-to-header (target-group)
1839   "Mangles FollowUp-To and Newsgroups header to point to TARGET-GROUP.
1840 With prefix-argument just set Follow-Up, don't cross-post."
1841   (interactive
1842    (list ; Completion based on Gnus
1843     (completing-read "Followup To: "
1844                      (if (boundp 'gnus-newsrc-alist)
1845                          gnus-newsrc-alist)
1846                      nil nil '("poster" . 0)
1847                      (if (boundp 'gnus-group-history)
1848                          'gnus-group-history))))
1849   (message-remove-header "Follow[Uu]p-[Tt]o" t)
1850   (message-goto-newsgroups)
1851   (beginning-of-line)
1852   ;; if we already did a crosspost before, kill old target
1853   (if (and message-cross-post-old-target
1854            (re-search-forward
1855             (regexp-quote (concat "," message-cross-post-old-target))
1856             nil t))
1857       (replace-match ""))
1858   ;; unless (followup is to poster or user explicitly asked not
1859   ;; to cross-post, or target-group is already in Newsgroups)
1860   ;; add target-group to Newsgroups line.
1861   (cond ((and (or
1862                ;; def: cross-post, req:no
1863                (and message-cross-post-default (not current-prefix-arg))
1864                ;; def: no-cross-post, req:yes
1865                (and (not message-cross-post-default) current-prefix-arg))
1866               (not (string-match "poster" target-group))
1867               (not (string-match (regexp-quote target-group)
1868                                  (message-fetch-field "Newsgroups"))))
1869          (end-of-line)
1870          (insert (concat "," target-group))))
1871   (end-of-line) ; ensure Followup: comes after Newsgroups:
1872   ;; unless new followup would be identical to Newsgroups line
1873   ;; make a new Followup-To line
1874   (if (not (string-match (concat "^[ \t]*"
1875                                  target-group
1876                                  "[ \t]*$")
1877                          (message-fetch-field "Newsgroups")))
1878       (insert (concat "\nFollowup-To: " target-group)))
1879   (setq message-cross-post-old-target target-group))
1880
1881 ;;;###autoload
1882 (defun message-cross-post-insert-note (target-group cross-post in-old
1883                                                     old-groups)
1884   "Insert a in message body note about a set Followup or Crosspost.
1885 If there have been previous notes, delete them.  TARGET-GROUP specifies the
1886 group to Followup-To.  When CROSS-POST is t, insert note about
1887 crossposting.  IN-OLD specifies whether TARGET-GROUP is a member of
1888 OLD-GROUPS.  OLD-GROUPS lists the old-groups the posting would have
1889 been made to before the user asked for a Crosspost."
1890   ;; start scanning body for previous uses
1891   (message-goto-signature)
1892   (let ((head (re-search-backward
1893                (concat "^" mail-header-separator)
1894                nil t))) ; just search in body
1895     (message-goto-signature)
1896     (while (re-search-backward
1897             (concat "^" (regexp-quote message-cross-post-note) ".*")
1898             head t)
1899       (message-delete-line))
1900     (message-goto-signature)
1901     (while (re-search-backward
1902             (concat "^" (regexp-quote message-followup-to-note) ".*")
1903             head t)
1904       (message-delete-line))
1905     ;; insert new note
1906     (if (message-goto-signature)
1907         (re-search-backward message-signature-separator))
1908     (if (or in-old
1909             (not cross-post)
1910             (string-match "^[ \t]*poster[ \t]*$" target-group))
1911         (insert (concat message-followup-to-note target-group "\n"))
1912       (insert (concat message-cross-post-note target-group "\n")))))
1913
1914 ;;;###autoload
1915 (defun message-cross-post-followup-to (target-group)
1916   "Crossposts message and set Followup-To to TARGET-GROUP.
1917 With prefix-argument just set Follow-Up, don't cross-post."
1918   (interactive
1919    (list ; Completion based on Gnus
1920     (completing-read "Followup To: "
1921                      (if (boundp 'gnus-newsrc-alist)
1922                          gnus-newsrc-alist)
1923                      nil nil '("poster" . 0)
1924                      (if (boundp 'gnus-group-history)
1925                          'gnus-group-history))))
1926   (cond ((not (or (null target-group) ; new subject not empty
1927                   (zerop (string-width target-group))
1928                   (string-match "^[ \t]*$" target-group)))
1929          (save-excursion
1930            (let* ((old-groups (message-fetch-field "Newsgroups"))
1931                   (in-old (string-match
1932                            (regexp-quote target-group)
1933                            (or old-groups ""))))
1934              ;; check whether target exactly matches old Newsgroups
1935              (cond ((not old-groups)
1936                     (error "No current newsgroup"))
1937                    ((or (not in-old)
1938                         (not (string-match
1939                               (concat "^[ \t]*"
1940                                       (regexp-quote target-group)
1941                                       "[ \t]*$")
1942                               old-groups)))
1943                     ;; yes, Newsgroups line must change
1944                     (message-cross-post-followup-to-header target-group)
1945                     ;; insert note whether we do cross-post or followup-to
1946                     (funcall message-cross-post-note-function
1947                              target-group
1948                              (if (or (and message-cross-post-default
1949                                           (not current-prefix-arg))
1950                                      (and (not message-cross-post-default)
1951                                           current-prefix-arg)) t)
1952                              in-old old-groups))))))))
1953
1954 ;;; Reduce To: to Cc: or Bcc: header
1955
1956 ;;;###autoload
1957 (defun message-reduce-to-to-cc ()
1958  "Replace contents of To: header with contents of Cc: or Bcc: header."
1959  (interactive)
1960  (let ((cc-content
1961         (save-restriction (message-narrow-to-headers)
1962                           (message-fetch-field "cc")))
1963        (bcc nil))
1964    (if (and (not cc-content)
1965             (setq cc-content
1966                   (save-restriction
1967                     (message-narrow-to-headers)
1968                     (message-fetch-field "bcc"))))
1969        (setq bcc t))
1970    (cond (cc-content
1971           (save-excursion
1972             (message-goto-to)
1973             (message-delete-line)
1974             (insert (concat "To: " cc-content "\n"))
1975             (save-restriction
1976               (message-narrow-to-headers)
1977               (message-remove-header (if bcc
1978                                          "bcc"
1979                                        "cc"))))))))
1980
1981 ;;; End of functions adopted from `message-utils.el'.
1982
1983 (defun message-remove-header (header &optional is-regexp first reverse)
1984   "Remove HEADER in the narrowed buffer.
1985 If IS-REGEXP, HEADER is a regular expression.
1986 If FIRST, only remove the first instance of the header.
1987 Return the number of headers removed."
1988   (goto-char (point-min))
1989   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1990         (number 0)
1991         (case-fold-search t)
1992         last)
1993     (while (and (not (eobp))
1994                 (not last))
1995       (if (if reverse
1996               (not (looking-at regexp))
1997             (looking-at regexp))
1998           (progn
1999             (incf number)
2000             (when first
2001               (setq last t))
2002             (delete-region
2003              (point)
2004              ;; There might be a continuation header, so we have to search
2005              ;; until we find a new non-continuation line.
2006              (progn
2007                (forward-line 1)
2008                (if (re-search-forward "^[^ \t]" nil t)
2009                    (goto-char (match-beginning 0))
2010                  (point-max)))))
2011         (forward-line 1)
2012         (if (re-search-forward "^[^ \t]" nil t)
2013             (goto-char (match-beginning 0))
2014           (goto-char (point-max)))))
2015     number))
2016
2017 (defun message-remove-first-header (header)
2018   "Remove the first instance of HEADER if there is more than one."
2019   (let ((count 0)
2020         (regexp (concat "^" (regexp-quote header) ":")))
2021     (save-excursion
2022       (goto-char (point-min))
2023       (while (re-search-forward regexp nil t)
2024         (incf count)))
2025     (while (> count 1)
2026       (message-remove-header header nil t)
2027       (decf count))))
2028
2029 (defun message-narrow-to-headers ()
2030   "Narrow the buffer to the head of the message."
2031   (widen)
2032   (narrow-to-region
2033    (goto-char (point-min))
2034    (if (re-search-forward
2035         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2036        (match-beginning 0)
2037      (point-max)))
2038   (goto-char (point-min)))
2039
2040 (defun message-narrow-to-head-1 ()
2041   "Like `message-narrow-to-head'.  Don't widen."
2042   (narrow-to-region
2043    (goto-char (point-min))
2044    (if (search-forward "\n\n" nil 1)
2045        (1- (point))
2046      (point-max)))
2047   (goto-char (point-min)))
2048
2049 (defun message-narrow-to-head ()
2050   "Narrow the buffer to the head of the message.
2051 Point is left at the beginning of the narrowed-to region."
2052   (widen)
2053   (message-narrow-to-head-1))
2054
2055 (defun message-narrow-to-headers-or-head ()
2056   "Narrow the buffer to the head of the message."
2057   (widen)
2058   (narrow-to-region
2059    (goto-char (point-min))
2060    (cond
2061     ((re-search-forward
2062       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2063      (match-beginning 0))
2064     ((search-forward "\n\n" nil t)
2065      (1- (point)))
2066     (t
2067      (point-max))))
2068   (goto-char (point-min)))
2069
2070 (defun message-news-p ()
2071   "Say whether the current buffer contains a news message."
2072   (and (not message-this-is-mail)
2073        (or message-this-is-news
2074            (save-excursion
2075              (save-restriction
2076                (message-narrow-to-headers)
2077                (and (message-fetch-field "newsgroups")
2078                     (not (message-fetch-field "posted-to"))))))))
2079
2080 (defun message-mail-p ()
2081   "Say whether the current buffer contains a mail message."
2082   (and (not message-this-is-news)
2083        (or message-this-is-mail
2084            (save-excursion
2085              (save-restriction
2086                (message-narrow-to-headers)
2087                (or (message-fetch-field "to")
2088                    (message-fetch-field "cc")
2089                    (message-fetch-field "bcc")))))))
2090
2091 (defun message-subscribed-p ()
2092   "Say whether we need to insert a MFT header."
2093   (or message-subscribed-regexps
2094       message-subscribed-addresses
2095       message-subscribed-address-file
2096       message-subscribed-address-functions))
2097
2098 (defun message-next-header ()
2099   "Go to the beginning of the next header."
2100   (beginning-of-line)
2101   (or (eobp) (forward-char 1))
2102   (not (if (re-search-forward "^[^ \t]" nil t)
2103            (beginning-of-line)
2104          (goto-char (point-max)))))
2105
2106 (defun message-sort-headers-1 ()
2107   "Sort the buffer as headers using `message-rank' text props."
2108   (goto-char (point-min))
2109   (require 'sort)
2110   (sort-subr
2111    nil 'message-next-header
2112    (lambda ()
2113      (message-next-header)
2114      (unless (bobp)
2115        (forward-char -1)))
2116    (lambda ()
2117      (or (get-text-property (point) 'message-rank)
2118          10000))))
2119
2120 (defun message-sort-headers ()
2121   "Sort the headers of the current message according to `message-header-format-alist'."
2122   (interactive)
2123   (save-excursion
2124     (save-restriction
2125       (let ((max (1+ (length message-header-format-alist)))
2126             rank)
2127         (message-narrow-to-headers)
2128         (while (re-search-forward "^[^ \n]+:" nil t)
2129           (put-text-property
2130            (match-beginning 0) (1+ (match-beginning 0))
2131            'message-rank
2132            (if (setq rank (length (memq (assq (intern (buffer-substring
2133                                                        (match-beginning 0)
2134                                                        (1- (match-end 0))))
2135                                               message-header-format-alist)
2136                                         message-header-format-alist)))
2137                (- max rank)
2138              (1+ max)))))
2139       (message-sort-headers-1))))
2140
2141 (defun message-kill-address ()
2142   "Kill the address under point."
2143   (interactive)
2144   (let ((start (point)))
2145     (message-skip-to-next-address)
2146     (kill-region start (point))))
2147
2148 \f
2149
2150 ;;;
2151 ;;; Message mode
2152 ;;;
2153
2154 ;;; Set up keymap.
2155
2156 (defvar message-mode-map nil)
2157
2158 (unless message-mode-map
2159   (setq message-mode-map (make-keymap))
2160   (set-keymap-parent message-mode-map text-mode-map)
2161   (define-key message-mode-map "\C-c?" 'describe-mode)
2162
2163   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
2164   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
2165   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
2166   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
2167   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
2168   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
2169   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
2170   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
2171   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
2172   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
2173   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2174   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
2175   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
2176   (define-key message-mode-map "\C-c\C-f\C-i"
2177     'message-insert-or-toggle-importance)
2178   (define-key message-mode-map "\C-c\C-f\C-a"
2179     'message-generate-unsubscribed-mail-followup-to)
2180
2181   ;; modify headers (and insert notes in body)
2182   (define-key message-mode-map "\C-c\C-fs"    'message-change-subject)
2183   ;;
2184   (define-key message-mode-map "\C-c\C-fx"    'message-cross-post-followup-to)
2185   ;; prefix+message-cross-post-followup-to = same w/o cross-post
2186   (define-key message-mode-map "\C-c\C-ft"    'message-reduce-to-to-cc)
2187   (define-key message-mode-map "\C-c\C-fa"    'message-add-archive-header)
2188   ;; mark inserted text
2189   (define-key message-mode-map "\C-c\M-m" 'message-mark-inserted-region)
2190   (define-key message-mode-map "\C-c\M-f" 'message-mark-insert-file)
2191
2192   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
2193   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
2194
2195   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
2196   (define-key message-mode-map "\C-c\C-fw" 'message-insert-wide-reply)
2197   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
2198   (define-key message-mode-map "\C-c\C-l" 'message-to-list-only)
2199
2200   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
2201   (define-key message-mode-map "\C-c\M-n"
2202     'message-insert-disposition-notification-to)
2203
2204   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
2205   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
2206   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
2207   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
2208   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
2209   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
2210   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
2211   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
2212
2213   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
2214   (define-key message-mode-map "\C-c\C-s" 'message-send)
2215   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
2216   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
2217   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
2218
2219   (define-key message-mode-map "\C-c\M-k" 'message-kill-address)
2220   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
2221   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
2222   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
2223   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
2224   (define-key message-mode-map [remap split-line]  'message-split-line)
2225
2226   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
2227
2228   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
2229   (define-key message-mode-map "\t" 'message-tab)
2230   (define-key message-mode-map "\M-;" 'comment-region))
2231
2232 (easy-menu-define
2233   message-mode-menu message-mode-map "Message Menu."
2234   `("Message"
2235     ["Yank Original" message-yank-original message-reply-buffer]
2236     ["Fill Yanked Message" message-fill-yanked-message t]
2237     ["Insert Signature" message-insert-signature t]
2238     ["Caesar (rot13) Message" message-caesar-buffer-body t]
2239     ["Caesar (rot13) Region" message-caesar-region (message-mark-active-p)]
2240     ["Elide Region" message-elide-region
2241      :active (message-mark-active-p)
2242      ,@(if (featurep 'xemacs) nil
2243          '(:help "Replace text in region with an ellipsis"))]
2244     ["Delete Outside Region" message-delete-not-region
2245      :active (message-mark-active-p)
2246      ,@(if (featurep 'xemacs) nil
2247          '(:help "Delete all quoted text outside region"))]
2248     ["Kill To Signature" message-kill-to-signature t]
2249     ["Newline and Reformat" message-newline-and-reformat t]
2250     ["Rename buffer" message-rename-buffer t]
2251     ["Spellcheck" ispell-message
2252      ,@(if (featurep 'xemacs) '(t)
2253          '(:help "Spellcheck this message"))]
2254     "----"
2255     ["Insert Region Marked" message-mark-inserted-region
2256      :active (message-mark-active-p)
2257      ,@(if (featurep 'xemacs) nil
2258          '(:help "Mark region with enclosing tags"))]
2259     ["Insert File Marked..." message-mark-insert-file
2260      ,@(if (featurep 'xemacs) '(t)
2261          '(:help "Insert file at point marked with enclosing tags"))]
2262     "----"
2263     ["Send Message" message-send-and-exit
2264      ,@(if (featurep 'xemacs) '(t)
2265          '(:help "Send this message"))]
2266     ["Postpone Message" message-dont-send
2267      ,@(if (featurep 'xemacs) '(t)
2268          '(:help "File this draft message and exit"))]
2269     ["Send at Specific Time..." gnus-delay-article
2270      ,@(if (featurep 'xemacs) '(t)
2271          '(:help "Ask, then arrange to send message at that time"))]
2272     ["Kill Message" message-kill-buffer
2273      ,@(if (featurep 'xemacs) '(t)
2274          '(:help "Delete this message without sending"))]))
2275
2276 (easy-menu-define
2277   message-mode-field-menu message-mode-map ""
2278   `("Field"
2279     ["To" message-goto-to t]
2280     ["From" message-goto-from t]
2281     ["Subject" message-goto-subject t]
2282     ["Change subject..." message-change-subject t]
2283     ["Cc" message-goto-cc t]
2284     ["Bcc" message-goto-bcc t]
2285     ["Fcc" message-goto-fcc t]
2286     ["Reply-To" message-goto-reply-to t]
2287     ["Flag As Important" message-insert-importance-high
2288      ,@(if (featurep 'xemacs) '(t)
2289          '(:help "Mark this message as important"))]
2290     ["Flag As Unimportant" message-insert-importance-low
2291      ,@(if (featurep 'xemacs) '(t)
2292          '(:help "Mark this message as unimportant"))]
2293     ["Request Receipt"
2294      message-insert-disposition-notification-to
2295      ,@(if (featurep 'xemacs) '(t)
2296          '(:help "Request a receipt notification"))]
2297     "----"
2298     ;; (typical) news stuff
2299     ["Summary" message-goto-summary t]
2300     ["Keywords" message-goto-keywords t]
2301     ["Newsgroups" message-goto-newsgroups t]
2302     ["Fetch Newsgroups" message-insert-newsgroups t]
2303     ["Followup-To" message-goto-followup-to t]
2304     ;; ["Followup-To (with note in body)" message-cross-post-followup-to t]
2305     ["Crosspost / Followup-To..." message-cross-post-followup-to t]
2306     ["Distribution" message-goto-distribution t]
2307     ["X-No-Archive:" message-add-archive-header t ]
2308     "----"
2309     ;; (typical) mailing-lists stuff
2310     ["Fetch To" message-insert-to
2311      ,@(if (featurep 'xemacs) '(t)
2312          '(:help "Insert a To header that points to the author."))]
2313     ["Fetch To and Cc" message-insert-wide-reply
2314      ,@(if (featurep 'xemacs) '(t)
2315          '(:help
2316            "Insert To and Cc headers as if you were doing a wide reply."))]
2317     "----"
2318     ["Send to list only" message-to-list-only t]
2319     ["Mail-Followup-To" message-goto-mail-followup-to t]
2320     ["Unsubscribed list post" message-generate-unsubscribed-mail-followup-to
2321      ,@(if (featurep 'xemacs) '(t)
2322          '(:help "Insert a reasonable `Mail-Followup-To:' header."))]
2323     ["Reduce To: to Cc:" message-reduce-to-to-cc t]
2324     "----"
2325     ["Sort Headers" message-sort-headers t]
2326     ["Encode non-ASCII domain names" message-idna-to-ascii-rhs t]
2327     ["Goto Body" message-goto-body t]
2328     ["Goto Signature" message-goto-signature t]))
2329
2330 (defvar message-tool-bar-map nil)
2331
2332 (eval-when-compile
2333   (defvar facemenu-add-face-function)
2334   (defvar facemenu-remove-face-function))
2335
2336 ;;; Forbidden properties
2337 ;;
2338 ;; We use `after-change-functions' to keep special text properties
2339 ;; that interfer with the normal function of message mode out of the
2340 ;; buffer.
2341
2342 (defcustom message-strip-special-text-properties t
2343   "Strip special properties from the message buffer.
2344
2345 Emacs has a number of special text properties which can break message
2346 composing in various ways.  If this option is set, message will strip
2347 these properties from the message composition buffer.  However, some
2348 packages requires these properties to be present in order to work.
2349 If you use one of these packages, turn this option off, and hope the
2350 message composition doesn't break too bad."
2351   :group 'message-various
2352   :link '(custom-manual "(message)Various Message Variables")
2353   :type 'boolean)
2354
2355 (defconst message-forbidden-properties
2356   ;; No reason this should be clutter up customize.  We make it a
2357   ;; property list (rather than a list of property symbols), to be
2358   ;; directly useful for `remove-text-properties'.
2359   '(field nil read-only nil invisible nil intangible nil
2360           mouse-face nil modification-hooks nil insert-in-front-hooks nil
2361           insert-behind-hooks nil point-entered nil point-left nil)
2362   ;; Other special properties:
2363   ;; category, face, display: probably doesn't do any harm.
2364   ;; fontified: is used by font-lock.
2365   ;; syntax-table, local-map: I dunno.
2366   ;; We need to add XEmacs names to the list.
2367   "Property list of with properties.forbidden in message buffers.
2368 The values of the properties are ignored, only the property names are used.")
2369
2370 (defun message-tamago-not-in-use-p (pos)
2371   "Return t when tamago version 4 is not in use at the cursor position.
2372 Tamago version 4 is a popular input method for writing Japanese text.
2373 It uses the properties `intangible', `invisible', `modification-hooks'
2374 and `read-only' when translating ascii or kana text to kanji text.
2375 These properties are essential to work, so we should never strip them."
2376   (not (and (boundp 'egg-modefull-mode)
2377             (symbol-value 'egg-modefull-mode)
2378             (or (memq (get-text-property pos 'intangible)
2379                       '(its-part-1 its-part-2))
2380                 (get-text-property pos 'egg-end)
2381                 (get-text-property pos 'egg-lang)
2382                 (get-text-property pos 'egg-start)))))
2383
2384 (defun message-strip-forbidden-properties (begin end &optional old-length)
2385   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
2386 This function is intended to be called from `after-change-functions'.
2387 See also `message-forbidden-properties'."
2388   (when (and message-strip-special-text-properties
2389              (message-tamago-not-in-use-p begin))
2390     (dolist (from-to (message-text-with-property 'message-hidden
2391                                                  begin end t))
2392       (remove-text-properties (car from-to) (cdr from-to)
2393                               message-forbidden-properties))))
2394
2395 ;;;###autoload
2396 (define-derived-mode message-mode text-mode "Message"
2397   "Major mode for editing mail and news to be sent.
2398 Like Text Mode but with these additional commands:\\<message-mode-map>
2399 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2400 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2401 C-c C-f  move to a header field (and create it if there isn't):
2402          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2403          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2404          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2405          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2406          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2407          C-c C-f C-o  move to From (\"Originator\")
2408          C-c C-f C-f  move to Followup-To
2409          C-c C-f C-m  move to Mail-Followup-To
2410          C-c C-f C-i  cycle through Importance values
2411          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2412          C-c C-f x    crossposting with FollowUp-To header and note in body
2413          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2414          C-c C-f a    Insert X-No-Archive: header and a note in the body
2415 C-c C-t  `message-insert-to' (add a To header to a news followup)
2416 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2417 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2418 C-c C-b  `message-goto-body' (move to beginning of message text).
2419 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2420 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2421 C-c C-y  `message-yank-original' (insert current message, if any).
2422 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2423 C-c C-e  `message-elide-region' (elide the text between point and mark).
2424 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2425 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2426 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2427 C-c C-a  `mml-attach-file' (attach a file as MIME).
2428 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2429 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2430 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2431 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2432 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2433   (setq local-abbrev-table text-mode-abbrev-table)
2434   (set (make-local-variable 'message-reply-buffer) nil)
2435   (set (make-local-variable 'message-inserted-headers) nil)
2436   (set (make-local-variable 'message-send-actions) nil)
2437   (set (make-local-variable 'message-exit-actions) nil)
2438   (set (make-local-variable 'message-kill-actions) nil)
2439   (set (make-local-variable 'message-postpone-actions) nil)
2440   (set (make-local-variable 'message-draft-article) nil)
2441   (setq buffer-offer-save t)
2442   (set (make-local-variable 'facemenu-add-face-function)
2443        (lambda (face end)
2444          (let ((face-fun (cdr (assq face message-face-alist))))
2445            (if face-fun
2446                (funcall face-fun (point) end)
2447              (error "Face %s not configured for %s mode" face mode-name)))
2448          ""))
2449   (set (make-local-variable 'facemenu-remove-face-function) t)
2450   (set (make-local-variable 'message-reply-headers) nil)
2451   (make-local-variable 'message-newsreader)
2452   (make-local-variable 'message-mailer)
2453   (make-local-variable 'message-post-method)
2454   (set (make-local-variable 'message-sent-message-via) nil)
2455   (set (make-local-variable 'message-checksum) nil)
2456   (set (make-local-variable 'message-mime-part) 0)
2457   (message-setup-fill-variables)
2458   ;; Allow using comment commands to add/remove quoting.
2459   (set (make-local-variable 'comment-start) message-yank-prefix)
2460   (if (featurep 'xemacs)
2461       (message-setup-toolbar)
2462     (set (make-local-variable 'font-lock-defaults)
2463          '(message-font-lock-keywords t))
2464     (if (boundp 'tool-bar-map)
2465         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2466   (easy-menu-add message-mode-menu message-mode-map)
2467   (easy-menu-add message-mode-field-menu message-mode-map)
2468   (gnus-make-local-hook 'after-change-functions)
2469   ;; Mmmm... Forbidden properties...
2470   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2471             nil 'local)
2472   ;; Allow mail alias things.
2473   (when (eq message-mail-alias-type 'abbrev)
2474     (if (fboundp 'mail-abbrevs-setup)
2475         (mail-abbrevs-setup)
2476       (if (fboundp 'mail-aliases-setup) ; warning avoidance
2477           (mail-aliases-setup))))
2478   (unless buffer-file-name
2479     (message-set-auto-save-file-name))
2480   (unless (buffer-base-buffer)
2481     ;; Don't enable multibyte on an indirect buffer.  Maybe enabling
2482     ;; multibyte is not necessary at all. -- zsh
2483     (mm-enable-multibyte))
2484   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
2485   (mml-mode))
2486
2487 (defun message-setup-fill-variables ()
2488   "Setup message fill variables."
2489   (set (make-local-variable 'fill-paragraph-function)
2490        'message-fill-paragraph)
2491   (make-local-variable 'paragraph-separate)
2492   (make-local-variable 'paragraph-start)
2493   (make-local-variable 'adaptive-fill-regexp)
2494   (unless (boundp 'adaptive-fill-first-line-regexp)
2495     (setq adaptive-fill-first-line-regexp nil))
2496   (make-local-variable 'adaptive-fill-first-line-regexp)
2497   (let ((quote-prefix-regexp
2498          ;; User should change message-cite-prefix-regexp if
2499          ;; message-yank-prefix is set to an abnormal value.
2500          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2501     (setq paragraph-start
2502           (concat
2503            (regexp-quote mail-header-separator) "$\\|"
2504            "[ \t]*$\\|"                 ; blank lines
2505            "-- $\\|"                    ; signature delimiter
2506            "---+$\\|"              ; delimiters for forwarded messages
2507            page-delimiter "$\\|"        ; spoiler warnings
2508            ".*wrote:$\\|"               ; attribution lines
2509            quote-prefix-regexp "$\\|"   ; empty lines in quoted text
2510                                         ; mml tags
2511            "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)"))
2512     (setq paragraph-separate paragraph-start)
2513     (setq adaptive-fill-regexp
2514           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2515     (setq adaptive-fill-first-line-regexp
2516           (concat quote-prefix-regexp "\\|"
2517                   adaptive-fill-first-line-regexp)))
2518   (make-local-variable 'auto-fill-inhibit-regexp)
2519   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2520   (setq auto-fill-inhibit-regexp nil)
2521   (make-local-variable 'normal-auto-fill-function)
2522   (setq normal-auto-fill-function 'message-do-auto-fill)
2523   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2524   ;; In that case, ensure that it uses the right function.  The real
2525   ;; solution would be not to use `define-derived-mode', and run
2526   ;; `text-mode-hook' ourself at the end of the mode.
2527   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2528   (when auto-fill-function
2529     (setq auto-fill-function normal-auto-fill-function)))
2530
2531 \f
2532
2533 ;;;
2534 ;;; Message mode commands
2535 ;;;
2536
2537 ;;; Movement commands
2538
2539 (defun message-goto-to ()
2540   "Move point to the To header."
2541   (interactive)
2542   (message-position-on-field "To"))
2543
2544 (defun message-goto-from ()
2545   "Move point to the From header."
2546   (interactive)
2547   (message-position-on-field "From"))
2548
2549 (defun message-goto-subject ()
2550   "Move point to the Subject header."
2551   (interactive)
2552   (message-position-on-field "Subject"))
2553
2554 (defun message-goto-cc ()
2555   "Move point to the Cc header."
2556   (interactive)
2557   (message-position-on-field "Cc" "To"))
2558
2559 (defun message-goto-bcc ()
2560   "Move point to the Bcc  header."
2561   (interactive)
2562   (message-position-on-field "Bcc" "Cc" "To"))
2563
2564 (defun message-goto-fcc ()
2565   "Move point to the Fcc header."
2566   (interactive)
2567   (message-position-on-field "Fcc" "To" "Newsgroups"))
2568
2569 (defun message-goto-reply-to ()
2570   "Move point to the Reply-To header."
2571   (interactive)
2572   (message-position-on-field "Reply-To" "Subject"))
2573
2574 (defun message-goto-newsgroups ()
2575   "Move point to the Newsgroups header."
2576   (interactive)
2577   (message-position-on-field "Newsgroups"))
2578
2579 (defun message-goto-distribution ()
2580   "Move point to the Distribution header."
2581   (interactive)
2582   (message-position-on-field "Distribution"))
2583
2584 (defun message-goto-followup-to ()
2585   "Move point to the Followup-To header."
2586   (interactive)
2587   (message-position-on-field "Followup-To" "Newsgroups"))
2588
2589 (defun message-goto-mail-followup-to ()
2590   "Move point to the Mail-Followup-To header."
2591   (interactive)
2592   (message-position-on-field "Mail-Followup-To" "From"))
2593
2594 (defun message-goto-keywords ()
2595   "Move point to the Keywords header."
2596   (interactive)
2597   (message-position-on-field "Keywords" "Subject"))
2598
2599 (defun message-goto-summary ()
2600   "Move point to the Summary header."
2601   (interactive)
2602   (message-position-on-field "Summary" "Subject"))
2603
2604 (defun message-goto-body (&optional interactivep)
2605   "Move point to the beginning of the message body."
2606   (interactive (list t))
2607   (when (and interactivep
2608              (looking-at "[ \t]*\n"))
2609     (expand-abbrev))
2610   (goto-char (point-min))
2611   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2612       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2613
2614 (defun message-goto-eoh ()
2615   "Move point to the end of the headers."
2616   (interactive)
2617   (message-goto-body)
2618   (forward-line -1))
2619
2620 (defun message-goto-signature ()
2621   "Move point to the beginning of the message signature.
2622 If there is no signature in the article, go to the end and
2623 return nil."
2624   (interactive)
2625   (goto-char (point-min))
2626   (if (re-search-forward message-signature-separator nil t)
2627       (forward-line 1)
2628     (goto-char (point-max))
2629     nil))
2630
2631 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
2632   "Insert a reasonable MFT header in a post to an unsubscribed list.
2633 When making original posts to a mailing list you are not subscribed to,
2634 you have to type in a MFT header by hand.  The contents, usually, are
2635 the addresses of the list and your own address.  This function inserts
2636 such a header automatically.  It fetches the contents of the To: header
2637 in the current mail buffer, and appends the current `user-mail-address'.
2638
2639 If the optional argument INCLUDE-CC is non-nil, the addresses in the
2640 Cc: header are also put into the MFT."
2641
2642   (interactive "P")
2643   (let* (cc tos)
2644     (save-restriction
2645       (message-narrow-to-headers)
2646       (message-remove-header "Mail-Followup-To")
2647       (setq cc (and include-cc (message-fetch-field "Cc")))
2648       (setq tos (if cc
2649                     (concat (message-fetch-field "To") "," cc)
2650                   (message-fetch-field "To"))))
2651     (message-goto-mail-followup-to)
2652     (insert (concat tos ", " user-mail-address))))
2653
2654 \f
2655
2656 (defun message-insert-to (&optional force)
2657   "Insert a To header that points to the author of the article being replied to.
2658 If the original author requested not to be sent mail, don't insert unless the
2659 prefix FORCE is given."
2660   (interactive "P")
2661   (let* ((mct (message-fetch-reply-field "mail-copies-to"))
2662          (dont (and mct (or (equal (downcase mct) "never")
2663                             (equal (downcase mct) "nobody"))))
2664          (to (or (message-fetch-reply-field "mail-reply-to")
2665                  (message-fetch-reply-field "reply-to")
2666                  (message-fetch-reply-field "from"))))
2667     (when (and dont to)
2668       (message
2669        (if force
2670            "Ignoring the user request not to have copies sent via mail"
2671          "Complying with the user request not to have copies sent via mail")))
2672     (when (and force (not to))
2673       (error "No mail address in the article"))
2674     (when (and to (or force (not dont)))
2675       (message-carefully-insert-headers (list (cons 'To to))))))
2676
2677 (defun message-insert-wide-reply ()
2678   "Insert To and Cc headers as if you were doing a wide reply."
2679   (interactive)
2680   (let ((headers (message-with-reply-buffer
2681                    (message-get-reply-headers t))))
2682     (message-carefully-insert-headers headers)))
2683
2684 (defcustom message-header-synonyms
2685   '((To Cc Bcc))
2686   "List of lists of header synonyms.
2687 E.g., if this list contains a member list with elements `Cc' and `To',
2688 then `message-carefully-insert-headers' will not insert a `To' header
2689 when the message is already `Cc'ed to the recipient."
2690   :group 'message-headers
2691   :link '(custom-manual "(message)Message Headers")
2692   :type '(repeat sexp))
2693
2694 (defun message-carefully-insert-headers (headers)
2695   "Insert the HEADERS, an alist, into the message buffer.
2696 Does not insert the headers when they are already present there
2697 or in the synonym headers, defined by `message-header-synonyms'."
2698   ;; FIXME: Should compare only the address and not the full name.  Comparison
2699   ;; should be done case-folded (and with `string=' rather than
2700   ;; `string-match').
2701   (dolist (header headers)
2702     (let* ((header-name (symbol-name (car header)))
2703            (new-header (cdr header))
2704            (synonyms (loop for synonym in message-header-synonyms
2705                            when (memq (car header) synonym) return synonym))
2706            (old-header
2707             (loop for synonym in synonyms
2708                   for old-header = (mail-fetch-field (symbol-name synonym))
2709                   when (and old-header (string-match new-header old-header))
2710                   return synonym)))
2711       (if old-header
2712           (message "already have `%s' in `%s'" new-header old-header)
2713         (when (and (message-position-on-field header-name)
2714                    (setq old-header (mail-fetch-field header-name))
2715                    (not (string-match "\\` *\\'" old-header)))
2716           (insert ", "))
2717         (insert new-header)))))
2718
2719 (defun message-widen-reply ()
2720   "Widen the reply to include maximum recipients."
2721   (interactive)
2722   (let ((follow-to
2723          (and message-reply-buffer
2724               (buffer-name message-reply-buffer)
2725               (save-excursion
2726                 (set-buffer message-reply-buffer)
2727                 (message-get-reply-headers t)))))
2728     (save-excursion
2729       (save-restriction
2730         (message-narrow-to-headers)
2731         (dolist (elem follow-to)
2732           (message-remove-header (symbol-name (car elem)))
2733           (goto-char (point-min))
2734           (insert (symbol-name (car elem)) ": "
2735                   (cdr elem) "\n"))))))
2736
2737 (defun message-insert-newsgroups ()
2738   "Insert the Newsgroups header from the article being replied to."
2739   (interactive)
2740   (when (and (message-position-on-field "Newsgroups")
2741              (mail-fetch-field "newsgroups")
2742              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2743     (insert ","))
2744   (insert (or (message-fetch-reply-field "newsgroups") "")))
2745
2746 \f
2747
2748 ;;; Various commands
2749
2750 (defun message-delete-not-region (beg end)
2751   "Delete everything in the body of the current message outside of the region."
2752   (interactive "r")
2753   (let (citeprefix)
2754     (save-excursion
2755       (goto-char beg)
2756       ;; snarf citation prefix, if appropriate
2757       (unless (eq (point) (progn (beginning-of-line) (point)))
2758         (when (looking-at message-cite-prefix-regexp)
2759           (setq citeprefix (match-string 0))))
2760       (goto-char end)
2761       (delete-region (point) (if (not (message-goto-signature))
2762                                  (point)
2763                                (forward-line -2)
2764                                (point)))
2765       (insert "\n")
2766       (goto-char beg)
2767       (delete-region beg (progn (message-goto-body)
2768                                 (forward-line 2)
2769                                 (point)))
2770       (when citeprefix
2771         (insert citeprefix))))
2772   (when (message-goto-signature)
2773     (forward-line -2)))
2774
2775 (defun message-kill-to-signature (&optional arg)
2776   "Kill all text up to the signature.
2777 If a numberic argument or prefix arg is given, leave that number
2778 of lines before the signature intact."
2779   (interactive "p")
2780   (save-excursion
2781     (save-restriction
2782       (let ((point (point)))
2783         (narrow-to-region point (point-max))
2784         (message-goto-signature)
2785         (unless (eobp)
2786           (if (and arg (numberp arg))
2787               (forward-line (- -1 arg))
2788             (end-of-line -1)))
2789         (unless (= point (point))
2790           (kill-region point (point))
2791           (insert "\n"))))))
2792
2793 (defun message-newline-and-reformat (&optional arg not-break)
2794   "Insert four newlines, and then reformat if inside quoted text.
2795 Prefix arg means justify as well."
2796   (interactive (list (if current-prefix-arg 'full)))
2797   (let (quoted point beg end leading-space bolp)
2798     (setq point (point))
2799     (beginning-of-line)
2800     (setq beg (point))
2801     (setq bolp (= beg point))
2802     ;; Find first line of the paragraph.
2803     (if not-break
2804         (while (and (not (eobp))
2805                     (not (looking-at message-cite-prefix-regexp))
2806                     (looking-at paragraph-start))
2807           (forward-line 1)))
2808     ;; Find the prefix
2809     (when (looking-at message-cite-prefix-regexp)
2810       (setq quoted (match-string 0))
2811       (goto-char (match-end 0))
2812       (looking-at "[ \t]*")
2813       (setq leading-space (match-string 0)))
2814     (if (and quoted
2815              (not not-break)
2816              (not bolp)
2817              (< (- point beg) (length quoted)))
2818         ;; break inside the cite prefix.
2819         (setq quoted nil
2820               end nil))
2821     (if quoted
2822         (progn
2823           (forward-line 1)
2824           (while (and (not (eobp))
2825                       (not (looking-at paragraph-separate))
2826                       (looking-at message-cite-prefix-regexp)
2827                       (equal quoted (match-string 0)))
2828             (goto-char (match-end 0))
2829             (looking-at "[ \t]*")
2830             (if (> (length leading-space) (length (match-string 0)))
2831                 (setq leading-space (match-string 0)))
2832             (forward-line 1))
2833           (setq end (point))
2834           (goto-char beg)
2835           (while (and (if (bobp) nil (forward-line -1) t)
2836                       (not (looking-at paragraph-start))
2837                       (looking-at message-cite-prefix-regexp)
2838                       (equal quoted (match-string 0)))
2839             (setq beg (point))
2840             (goto-char (match-end 0))
2841             (looking-at "[ \t]*")
2842             (if (> (length leading-space) (length (match-string 0)))
2843                 (setq leading-space (match-string 0)))))
2844       (while (and (not (eobp))
2845                   (not (looking-at paragraph-separate))
2846                   (not (looking-at message-cite-prefix-regexp)))
2847         (forward-line 1))
2848       (setq end (point))
2849       (goto-char beg)
2850       (while (and (if (bobp) nil (forward-line -1) t)
2851                   (not (looking-at paragraph-start))
2852                   (not (looking-at message-cite-prefix-regexp)))
2853         (setq beg (point))))
2854     (goto-char point)
2855     (save-restriction
2856       (narrow-to-region beg end)
2857       (if not-break
2858           (setq point nil)
2859         (if bolp
2860             (newline)
2861           (newline)
2862           (newline))
2863         (setq point (point))
2864         ;; (newline 2) doesn't mark both newline's as hard, so call
2865         ;; newline twice. -jas
2866         (newline)
2867         (newline)
2868         (delete-region (point) (re-search-forward "[ \t]*"))
2869         (when (and quoted (not bolp))
2870           (insert quoted leading-space)))
2871       (undo-boundary)
2872       (if quoted
2873           (let* ((adaptive-fill-regexp
2874                   (regexp-quote (concat quoted leading-space)))
2875                  (adaptive-fill-first-line-regexp
2876                   adaptive-fill-regexp ))
2877             (fill-paragraph arg))
2878         (fill-paragraph arg))
2879       (if point (goto-char point)))))
2880
2881 (defun message-fill-paragraph (&optional arg)
2882   "Like `fill-paragraph'."
2883   (interactive (list (if current-prefix-arg 'full)))
2884   (if (if (boundp 'filladapt-mode) filladapt-mode)
2885       nil
2886     (if (message-point-in-header-p)
2887         (message-fill-field)
2888       (message-newline-and-reformat arg t))
2889     t))
2890
2891 ;; Is it better to use `mail-header-end'?
2892 (defun message-point-in-header-p ()
2893   "Return t if point is in the header."
2894   (save-excursion
2895     (let ((p (point)))
2896       (goto-char (point-min))
2897       (not (re-search-forward
2898             (concat "^" (regexp-quote mail-header-separator) "\n")
2899             p t)))))
2900
2901 (defun message-do-auto-fill ()
2902   "Like `do-auto-fill', but don't fill in message header."
2903   (unless (message-point-in-header-p)
2904     (do-auto-fill)))
2905
2906 (defun message-insert-signature (&optional force)
2907   "Insert a signature.  See documentation for variable `message-signature'."
2908   (interactive (list 0))
2909   (let* ((signature
2910           (cond
2911            ((and (null message-signature)
2912                  (eq force 0))
2913             (save-excursion
2914               (goto-char (point-max))
2915               (not (re-search-backward message-signature-separator nil t))))
2916            ((and (null message-signature)
2917                  force)
2918             t)
2919            ((functionp message-signature)
2920             (funcall message-signature))
2921            ((listp message-signature)
2922             (eval message-signature))
2923            (t message-signature)))
2924          (signature
2925           (cond ((stringp signature)
2926                  signature)
2927                 ((and (eq t signature)
2928                       message-signature-file
2929                       (file-exists-p message-signature-file))
2930                  signature))))
2931     (when signature
2932       (goto-char (point-max))
2933       ;; Insert the signature.
2934       (unless (bolp)
2935         (insert "\n"))
2936       (when message-signature-insert-empty-line
2937         (insert "\n"))
2938       (insert "-- \n")
2939       (if (eq signature t)
2940           (insert-file-contents message-signature-file)
2941         (insert signature))
2942       (goto-char (point-max))
2943       (or (bolp) (insert "\n")))))
2944
2945 (defun message-insert-importance-high ()
2946   "Insert header to mark message as important."
2947   (interactive)
2948   (save-excursion
2949     (save-restriction
2950       (message-narrow-to-headers)
2951       (message-remove-header "Importance"))
2952     (message-goto-eoh)
2953     (insert "Importance: high\n")))
2954
2955 (defun message-insert-importance-low ()
2956   "Insert header to mark message as unimportant."
2957   (interactive)
2958   (save-excursion
2959     (save-restriction
2960       (message-narrow-to-headers)
2961       (message-remove-header "Importance"))
2962     (message-goto-eoh)
2963     (insert "Importance: low\n")))
2964
2965 (defun message-insert-or-toggle-importance ()
2966   "Insert a \"Importance: high\" header, or cycle through the header values.
2967 The three allowed values according to RFC 1327 are `high', `normal'
2968 and `low'."
2969   (interactive)
2970   (save-excursion
2971     (let ((valid '("high" "normal" "low"))
2972           (new "high")
2973           cur)
2974       (save-restriction
2975         (message-narrow-to-headers)
2976         (when (setq cur (message-fetch-field "Importance"))
2977           (message-remove-header "Importance")
2978           (setq new (cond ((string= cur "high")
2979                            "low")
2980                           ((string= cur "low")
2981                            "normal")
2982                           (t
2983                            "high")))))
2984       (message-goto-eoh)
2985       (insert (format "Importance: %s\n" new)))))
2986
2987 (defun message-insert-disposition-notification-to ()
2988   "Request a disposition notification (return receipt) to this message.
2989 Note that this should not be used in newsgroups."
2990   (interactive)
2991   (save-excursion
2992     (save-restriction
2993       (message-narrow-to-headers)
2994       (message-remove-header "Disposition-Notification-To"))
2995     (message-goto-eoh)
2996     (insert (format "Disposition-Notification-To: %s\n"
2997                     (or (message-field-value "Reply-to")
2998                         (message-field-value "From")
2999                         (message-make-from))))))
3000
3001 (defun message-elide-region (b e)
3002   "Elide the text in the region.
3003 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3004 text was killed."
3005   (interactive "r")
3006   (kill-region b e)
3007   (insert message-elide-ellipsis))
3008
3009 (defvar message-caesar-translation-table nil)
3010
3011 (defun message-caesar-region (b e &optional n)
3012   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3013   (interactive
3014    (list
3015     (min (point) (or (mark t) (point)))
3016     (max (point) (or (mark t) (point)))
3017     (when current-prefix-arg
3018       (prefix-numeric-value current-prefix-arg))))
3019
3020   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3021   (unless (or (zerop n)                 ; no action needed for a rot of 0
3022               (= b e))                  ; no region to rotate
3023     ;; We build the table, if necessary.
3024     (when (or (not message-caesar-translation-table)
3025               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3026       (setq message-caesar-translation-table
3027             (message-make-caesar-translation-table n)))
3028     (translate-region b e message-caesar-translation-table)))
3029
3030 (defun message-make-caesar-translation-table (n)
3031   "Create a rot table with offset N."
3032   (let ((i -1)
3033         (table (make-string 256 0)))
3034     (while (< (incf i) 256)
3035       (aset table i i))
3036     (concat
3037      (substring table 0 ?A)
3038      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3039      (substring table ?A (+ ?A n))
3040      (substring table (+ ?A 26) ?a)
3041      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3042      (substring table ?a (+ ?a n))
3043      (substring table (+ ?a 26) 255))))
3044
3045 (defun message-caesar-buffer-body (&optional rotnum)
3046   "Caesar rotate all letters in the current buffer by 13 places.
3047 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3048 With prefix arg, specifies the number of places to rotate each letter forward.
3049 Mail and USENET news headers are not rotated."
3050   (interactive (if current-prefix-arg
3051                    (list (prefix-numeric-value current-prefix-arg))
3052                  (list nil)))
3053   (save-excursion
3054     (save-restriction
3055       (when (message-goto-body)
3056         (narrow-to-region (point) (point-max)))
3057       (message-caesar-region (point-min) (point-max) rotnum))))
3058
3059 (defun message-pipe-buffer-body (program)
3060   "Pipe the message body in the current buffer through PROGRAM."
3061   (save-excursion
3062     (save-restriction
3063       (when (message-goto-body)
3064         (narrow-to-region (point) (point-max)))
3065       (shell-command-on-region
3066        (point-min) (point-max) program nil t))))
3067
3068 (defun message-rename-buffer (&optional enter-string)
3069   "Rename the *message* buffer to \"*message* RECIPIENT\".
3070 If the function is run with a prefix, it will ask for a new buffer
3071 name, rather than giving an automatic name."
3072   (interactive "Pbuffer name: ")
3073   (save-excursion
3074     (save-restriction
3075       (goto-char (point-min))
3076       (narrow-to-region (point)
3077                         (search-forward mail-header-separator nil 'end))
3078       (let* ((mail-to (or
3079                        (if (message-news-p) (message-fetch-field "Newsgroups")
3080                          (message-fetch-field "To"))
3081                        ""))
3082              (mail-trimmed-to
3083               (if (string-match "," mail-to)
3084                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3085                 mail-to))
3086              (name-default (concat "*message* " mail-trimmed-to))
3087              (name (if enter-string
3088                        (read-string "New buffer name: " name-default)
3089                      name-default)))
3090         (rename-buffer name t)))))
3091
3092 (defun message-fill-yanked-message (&optional justifyp)
3093   "Fill the paragraphs of a message yanked into this one.
3094 Numeric argument means justify as well."
3095   (interactive "P")
3096   (save-excursion
3097     (goto-char (point-min))
3098     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3099     (let ((fill-prefix message-yank-prefix))
3100       (fill-individual-paragraphs (point) (point-max) justifyp))))
3101
3102 (defun message-indent-citation ()
3103   "Modify text just inserted from a message to be cited.
3104 The inserted text should be the region.
3105 When this function returns, the region is again around the modified text.
3106
3107 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3108 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3109   (let ((start (point)))
3110     ;; Remove unwanted headers.
3111     (when message-ignored-cited-headers
3112       (let (all-removed)
3113         (save-restriction
3114           (narrow-to-region
3115            (goto-char start)
3116            (if (search-forward "\n\n" nil t)
3117                (1- (point))
3118              (point)))
3119           (message-remove-header message-ignored-cited-headers t)
3120           (when (= (point-min) (point-max))
3121             (setq all-removed t))
3122           (goto-char (point-max)))
3123         (if all-removed
3124             (goto-char start)
3125           (forward-line 1))))
3126     ;; Delete blank lines at the start of the buffer.
3127     (while (and (point-min)
3128                 (eolp)
3129                 (not (eobp)))
3130       (message-delete-line))
3131     ;; Delete blank lines at the end of the buffer.
3132     (goto-char (point-max))
3133     (unless (eolp)
3134       (insert "\n"))
3135     (while (and (zerop (forward-line -1))
3136                 (looking-at "$"))
3137       (message-delete-line))
3138     ;; Do the indentation.
3139     (if (null message-yank-prefix)
3140         (indent-rigidly start (mark t) message-indentation-spaces)
3141       (save-excursion
3142         (goto-char start)
3143         (while (< (point) (mark t))
3144           (if (or (looking-at ">") (looking-at "^$"))
3145               (insert message-yank-cited-prefix)
3146             (insert message-yank-prefix))
3147           (forward-line 1))))
3148     (goto-char start)))
3149
3150 (defun message-yank-original (&optional arg)
3151   "Insert the message being replied to, if any.
3152 Puts point before the text and mark after.
3153 Normally indents each nonblank line ARG spaces (default 3).  However,
3154 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3155
3156 This function uses `message-cite-function' to do the actual citing.
3157
3158 Just \\[universal-argument] as argument means don't indent, insert no
3159 prefix, and don't delete any headers."
3160   (interactive "P")
3161   (let ((modified (buffer-modified-p)))
3162     (when (and message-reply-buffer
3163                message-cite-function)
3164       (delete-windows-on message-reply-buffer t)
3165       (insert-buffer message-reply-buffer)
3166       (unless arg
3167         (funcall message-cite-function))
3168       (message-exchange-point-and-mark)
3169       (unless (bolp)
3170         (insert ?\n))
3171       (unless modified
3172         (setq message-checksum (message-checksum))))))
3173
3174 (defun message-yank-buffer (buffer)
3175   "Insert BUFFER into the current buffer and quote it."
3176   (interactive "bYank buffer: ")
3177   (let ((message-reply-buffer (get-buffer buffer)))
3178     (save-window-excursion
3179       (message-yank-original))))
3180
3181 (defun message-buffers ()
3182   "Return a list of active message buffers."
3183   (let (buffers)
3184     (save-excursion
3185       (dolist (buffer (buffer-list t))
3186         (set-buffer buffer)
3187         (when (and (eq major-mode 'message-mode)
3188                    (null message-sent-message-via))
3189           (push (buffer-name buffer) buffers))))
3190     (nreverse buffers)))
3191
3192 (defun message-cite-original-without-signature ()
3193   "Cite function in the standard Message manner."
3194   (let* ((start (point))
3195          (end (mark t))
3196          (functions
3197           (when message-indent-citation-function
3198             (if (listp message-indent-citation-function)
3199                 message-indent-citation-function
3200               (list message-indent-citation-function))))
3201          ;; This function may be called by `gnus-summary-yank-message' and
3202          ;; may insert a different article from the original.  So, we will
3203          ;; modify the value of `message-reply-headers' with that article.
3204          (message-reply-headers
3205           (save-restriction
3206             (narrow-to-region start end)
3207             (message-narrow-to-head-1)
3208             (vector 0
3209                     (or (message-fetch-field "subject") "none")
3210                     (message-fetch-field "from")
3211                     (message-fetch-field "date")
3212                     (message-fetch-field "message-id" t)
3213                     (message-fetch-field "references")
3214                     0 0 ""))))
3215     (mml-quote-region start end)
3216     ;; Allow undoing.
3217     (undo-boundary)
3218     (goto-char end)
3219     (when (re-search-backward message-signature-separator start t)
3220       ;; Also peel off any blank lines before the signature.
3221       (forward-line -1)
3222       (while (looking-at "^[ \t]*$")
3223         (forward-line -1))
3224       (forward-line 1)
3225       (delete-region (point) end)
3226       (unless (search-backward "\n\n" start t)
3227         ;; Insert a blank line if it is peeled off.
3228         (insert "\n")))
3229     (goto-char start)
3230     (while functions
3231       (funcall (pop functions)))
3232     (when message-citation-line-function
3233       (unless (bolp)
3234         (insert "\n"))
3235       (funcall message-citation-line-function))))
3236
3237 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
3238 (defun message-cite-original ()
3239   "Cite function in the standard Message manner."
3240   (if (and (boundp 'mail-citation-hook)
3241            mail-citation-hook)
3242       (run-hooks 'mail-citation-hook)
3243     (let* ((start (point))
3244            (end (mark t))
3245            (x-no-archive nil)
3246            (functions
3247             (when message-indent-citation-function
3248               (if (listp message-indent-citation-function)
3249                   message-indent-citation-function
3250                 (list message-indent-citation-function))))
3251            ;; This function may be called by `gnus-summary-yank-message' and
3252            ;; may insert a different article from the original.  So, we will
3253            ;; modify the value of `message-reply-headers' with that article.
3254            (message-reply-headers
3255             (save-restriction
3256               (narrow-to-region start end)
3257               (message-narrow-to-head-1)
3258               (setq x-no-archive (message-fetch-field "x-no-archive"))
3259               (vector 0
3260                       (or (message-fetch-field "subject") "none")
3261                       (message-fetch-field "from")
3262                       (message-fetch-field "date")
3263                       (message-fetch-field "message-id" t)
3264                       (message-fetch-field "references")
3265                       0 0 ""))))
3266       (mml-quote-region start end)
3267       (goto-char start)
3268       (while functions
3269         (funcall (pop functions)))
3270       (when message-citation-line-function
3271         (unless (bolp)
3272           (insert "\n"))
3273         (funcall message-citation-line-function))
3274       (when (and x-no-archive
3275                  message-cite-articles-with-x-no-archive
3276                  (string-match "yes" x-no-archive))
3277         (undo-boundary)
3278         (delete-region (point) (mark t))
3279         (insert "> [Quoted text removed due to X-No-Archive]\n")
3280         (forward-line -1)))))
3281
3282 (defun message-insert-citation-line ()
3283   "Insert a simple citation line."
3284   (when message-reply-headers
3285     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3286
3287 (defun message-position-on-field (header &rest afters)
3288   (let ((case-fold-search t))
3289     (save-restriction
3290       (narrow-to-region
3291        (goto-char (point-min))
3292        (progn
3293          (re-search-forward
3294           (concat "^" (regexp-quote mail-header-separator) "$"))
3295          (match-beginning 0)))
3296       (goto-char (point-min))
3297       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3298           (progn
3299             (re-search-forward "^[^ \t]" nil 'move)
3300             (beginning-of-line)
3301             (skip-chars-backward "\n")
3302             t)
3303         (while (and afters
3304                     (not (re-search-forward
3305                           (concat "^" (regexp-quote (car afters)) ":")
3306                           nil t)))
3307           (pop afters))
3308         (when afters
3309           (re-search-forward "^[^ \t]" nil 'move)
3310           (beginning-of-line))
3311         (insert header ": \n")
3312         (forward-char -1)
3313         nil))))
3314
3315 (defun message-remove-signature ()
3316   "Remove the signature from the text between point and mark.
3317 The text will also be indented the normal way."
3318   (save-excursion
3319     (let ((start (point))
3320           mark)
3321       (if (not (re-search-forward message-signature-separator (mark t) t))
3322           ;; No signature here, so we just indent the cited text.
3323           (message-indent-citation)
3324         ;; Find the last non-empty line.
3325         (forward-line -1)
3326         (while (looking-at "[ \t]*$")
3327           (forward-line -1))
3328         (forward-line 1)
3329         (setq mark (set-marker (make-marker) (point)))
3330         (goto-char start)
3331         (message-indent-citation)
3332         ;; Enable undoing the deletion.
3333         (undo-boundary)
3334         (delete-region mark (mark t))
3335         (set-marker mark nil)))))
3336
3337 \f
3338
3339 ;;;
3340 ;;; Sending messages
3341 ;;;
3342
3343 (defun message-send-and-exit (&optional arg)
3344   "Send message like `message-send', then, if no errors, exit from mail buffer."
3345   (interactive "P")
3346   (let ((buf (current-buffer))
3347         (actions message-exit-actions))
3348     (when (and (message-send arg)
3349                (buffer-name buf))
3350       (if message-kill-buffer-on-exit
3351           (kill-buffer buf)
3352         (bury-buffer buf)
3353         (when (eq buf (current-buffer))
3354           (message-bury buf)))
3355       (message-do-actions actions)
3356       t)))
3357
3358 (defun message-dont-send ()
3359   "Don't send the message you have been editing.
3360 Instead, just auto-save the buffer and then bury it."
3361   (interactive)
3362   (set-buffer-modified-p t)
3363   (save-buffer)
3364   (let ((actions message-postpone-actions))
3365     (message-bury (current-buffer))
3366     (message-do-actions actions)))
3367
3368 (defun message-kill-buffer ()
3369   "Kill the current buffer."
3370   (interactive)
3371   (when (or (not (buffer-modified-p))
3372             (yes-or-no-p "Message modified; kill anyway? "))
3373     (let ((actions message-kill-actions)
3374           (draft-article message-draft-article)
3375           (auto-save-file-name buffer-auto-save-file-name)
3376           (file-name buffer-file-name)
3377           (modified (buffer-modified-p)))
3378       (setq buffer-file-name nil)
3379       (kill-buffer (current-buffer))
3380       (when (and (or (and auto-save-file-name
3381                           (file-exists-p auto-save-file-name))
3382                      (and file-name
3383                           (file-exists-p file-name)))
3384                (yes-or-no-p (format "Remove the backup file%s? "
3385                                     (if modified " too" ""))))
3386         (ignore-errors
3387           (delete-file auto-save-file-name))
3388         (let ((message-draft-article draft-article))
3389           (message-disassociate-draft)))
3390       (message-do-actions actions))))
3391
3392 (defun message-bury (buffer)
3393   "Bury this mail BUFFER."
3394   (let ((newbuf (other-buffer buffer)))
3395     (bury-buffer buffer)
3396     (if (and (fboundp 'frame-parameters)
3397              (cdr (assq 'dedicated (frame-parameters)))
3398              (not (null (delq (selected-frame) (visible-frame-list)))))
3399         (delete-frame (selected-frame))
3400       (switch-to-buffer newbuf))))
3401
3402 (defun message-send (&optional arg)
3403   "Send the message in the current buffer.
3404 If `message-interactive' is non-nil, wait for success indication or
3405 error messages, and inform user.
3406 Otherwise any failure is reported in a message back to the user from
3407 the mailer.
3408 The usage of ARG is defined by the instance that called Message.
3409 It should typically alter the sending method in some way or other."
3410   (interactive "P")
3411   ;; Make it possible to undo the coming changes.
3412   (undo-boundary)
3413   (let ((inhibit-read-only t))
3414     (put-text-property (point-min) (point-max) 'read-only nil))
3415   (message-fix-before-sending)
3416   (run-hooks 'message-send-hook)
3417   (message message-sending-message)
3418   (let ((alist message-send-method-alist)
3419         (success t)
3420         elem sent dont-barf-on-no-method
3421         (message-options message-options))
3422     (message-options-set-recipient)
3423     (while (and success
3424                 (setq elem (pop alist)))
3425       (when (funcall (cadr elem))
3426         (when (and (or (not (memq (car elem)
3427                                   message-sent-message-via))
3428                        (message-fetch-field "supersedes")
3429                        (if (or (message-gnksa-enable-p 'multiple-copies)
3430                                (not (eq (car elem) 'news)))
3431                            (y-or-n-p
3432                             (format
3433                              "Already sent message via %s; resend? "
3434                              (car elem)))
3435                          (error "Denied posting -- multiple copies")))
3436                    (setq success (funcall (caddr elem) arg)))
3437           (setq sent t))))
3438     (unless (or sent
3439                 (not success)
3440                 (let ((fcc (message-fetch-field "Fcc"))
3441                       (gcc (message-fetch-field "Gcc")))
3442                   (when (or fcc gcc)
3443                     (or (eq message-allow-no-recipients 'always)
3444                         (and (not (eq message-allow-no-recipients 'never))
3445                              (setq dont-barf-on-no-method
3446                                    (gnus-y-or-n-p
3447                                     (format "No receiver, perform %s anyway? "
3448                                             (cond ((and fcc gcc) "Fcc and Gcc")
3449                                                   (fcc "Fcc")
3450                                                   (t "Gcc"))))))))))
3451       (error "No methods specified to send by"))
3452     (when (or dont-barf-on-no-method
3453               (and success sent))
3454       (message-do-fcc)
3455       (save-excursion
3456         (run-hooks 'message-sent-hook))
3457       (message "Sending...done")
3458       ;; Mark the buffer as unmodified and delete auto-save.
3459       (set-buffer-modified-p nil)
3460       (delete-auto-save-file-if-necessary t)
3461       (message-disassociate-draft)
3462       ;; Delete other mail buffers and stuff.
3463       (message-do-send-housekeeping)
3464       (message-do-actions message-send-actions)
3465       ;; Return success.
3466       t)))
3467
3468 (defun message-send-via-mail (arg)
3469   "Send the current message via mail."
3470   (message-send-mail arg))
3471
3472 (defun message-send-via-news (arg)
3473   "Send the current message via news."
3474   (funcall message-send-news-function arg))
3475
3476 (defmacro message-check (type &rest forms)
3477   "Eval FORMS if TYPE is to be checked."
3478   `(or (message-check-element ,type)
3479        (save-excursion
3480          ,@forms)))
3481
3482 (put 'message-check 'lisp-indent-function 1)
3483 (put 'message-check 'edebug-form-spec '(form body))
3484
3485 (defun message-text-with-property (prop &optional start end reverse)
3486   "Return a list of start and end positions where the text has PROP.
3487 START and END bound the search, they default to `point-min' and
3488 `point-max' respectively.  If REVERSE is non-nil, find text which does
3489 not have PROP."
3490   (unless start
3491     (setq start (point-min)))
3492   (unless end
3493     (setq end (point-max)))
3494   (let (next regions)
3495     (if reverse
3496         (while (and start
3497                     (setq start (text-property-any start end prop nil)))
3498           (setq next (next-single-property-change start prop nil end))
3499           (push (cons start (or next end)) regions)
3500           (setq start next))
3501       (while (and start
3502                   (or (get-text-property start prop)
3503                       (and (setq start (next-single-property-change
3504                                         start prop nil end))
3505                            (get-text-property start prop))))
3506         (setq next (text-property-any start end prop nil))
3507         (push (cons start (or next end)) regions)
3508         (setq start next)))
3509     (nreverse regions)))
3510
3511 (defun message-fix-before-sending ()
3512   "Do various things to make the message nice before sending it."
3513   ;; Make sure there's a newline at the end of the message.
3514   (goto-char (point-max))
3515   (unless (bolp)
3516     (insert "\n"))
3517   ;; Make the hidden headers visible.
3518   (dolist (from-to (message-text-with-property 'message-hidden))
3519     (add-text-properties (car from-to) (cdr from-to)
3520                          '(invisible nil intangible nil)))
3521   ;; Make invisible text visible.
3522   ;; It doesn't seem as if this is useful, since the invisible property
3523   ;; is clobbered by an after-change hook anyhow.
3524   (message-check 'invisible-text
3525     (let ((regions (message-text-with-property 'invisible))
3526           from to)
3527       (when regions
3528         (while regions
3529           (setq from (caar regions)
3530                 to (cdar regions)
3531                 regions (cdr regions))
3532           (put-text-property from to 'invisible nil)
3533           (message-overlay-put (message-make-overlay from to)
3534                                'face 'highlight))
3535         (unless (yes-or-no-p
3536                  "Invisible text found and made visible; continue sending? ")
3537           (error "Invisible text found and made visible")))))
3538   (message-check 'illegible-text
3539     (let (found choice)
3540       (message-goto-body)
3541       (skip-chars-forward mm-7bit-chars)
3542       (while (not (eobp))
3543         (when (let ((char (char-after)))
3544                 (or (< (mm-char-int char) 128)
3545                     (and (mm-multibyte-p)
3546                          (memq (char-charset char)
3547                                '(eight-bit-control eight-bit-graphic
3548                                                    control-1))
3549                          (not (get-text-property
3550                                (point) 'untranslated-utf-8)))))
3551           (message-overlay-put (message-make-overlay (point) (1+ (point)))
3552                                'face 'highlight)
3553           (setq found t))
3554         (forward-char)
3555         (skip-chars-forward mm-7bit-chars))
3556       (when found
3557         (setq choice
3558               (gnus-multiple-choice
3559                "Non-printable characters found.  Continue sending?"
3560                '((?d "Remove non-printable characters and send")
3561                  (?r "Replace non-printable characters with dots and send")
3562                  (?i "Ignore non-printable characters and send")
3563                  (?e "Continue editing"))))
3564         (if (eq choice ?e)
3565           (error "Non-printable characters"))
3566         (message-goto-body)
3567         (skip-chars-forward mm-7bit-chars)
3568         (while (not (eobp))
3569           (when (let ((char (char-after)))
3570                   (or (< (mm-char-int char) 128)
3571                       (and (mm-multibyte-p)
3572                            ;; Fixme: Wrong for Emacs 22 and for things
3573                            ;; like undecable utf-8.  Should at least
3574                            ;; use find-coding-systems-region.
3575                            (memq (char-charset char)
3576                                  '(eight-bit-control eight-bit-graphic
3577                                                      control-1))
3578                            (not (get-text-property
3579                                  (point) 'untranslated-utf-8)))))
3580             (if (eq choice ?i)
3581                 (message-kill-all-overlays)
3582               (delete-char 1)
3583               (when (eq choice ?r)
3584                 (insert "."))))
3585           (forward-char)
3586           (skip-chars-forward mm-7bit-chars))))))
3587
3588 (defun message-add-action (action &rest types)
3589   "Add ACTION to be performed when doing an exit of type TYPES."
3590   (while types
3591     (add-to-list (intern (format "message-%s-actions" (pop types)))
3592                  action)))
3593
3594 (defun message-delete-action (action &rest types)
3595   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3596   (let (var)
3597     (while types
3598       (set (setq var (intern (format "message-%s-actions" (pop types))))
3599            (delq action (symbol-value var))))))
3600
3601 (defun message-do-actions (actions)
3602   "Perform all actions in ACTIONS."
3603   ;; Now perform actions on successful sending.
3604   (while actions
3605     (ignore-errors
3606       (cond
3607        ;; A simple function.
3608        ((functionp (car actions))
3609         (funcall (car actions)))
3610        ;; Something to be evaled.
3611        (t
3612         (eval (car actions)))))
3613     (pop actions)))
3614
3615 (defun message-send-mail-partially ()
3616   "Send mail as message/partial."
3617   ;; replace the header delimiter with a blank line
3618   (goto-char (point-min))
3619   (re-search-forward
3620    (concat "^" (regexp-quote mail-header-separator) "\n"))
3621   (replace-match "\n")
3622   (run-hooks 'message-send-mail-hook)
3623   (let ((p (goto-char (point-min)))
3624         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3625         (curbuf (current-buffer))
3626         (id (message-make-message-id)) (n 1)
3627         plist total  header required-mail-headers)
3628     (while (not (eobp))
3629       (if (< (point-max) (+ p message-send-mail-partially-limit))
3630           (goto-char (point-max))
3631         (goto-char (+ p message-send-mail-partially-limit))
3632         (beginning-of-line)
3633         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3634       (push p plist)
3635       (setq p (point)))
3636     (setq total (length plist))
3637     (push (point-max) plist)
3638     (setq plist (nreverse plist))
3639     (unwind-protect
3640         (save-excursion
3641           (setq p (pop plist))
3642           (while plist
3643             (set-buffer curbuf)
3644             (copy-to-buffer tembuf p (car plist))
3645             (set-buffer tembuf)
3646             (goto-char (point-min))
3647             (if header
3648                 (progn
3649                   (goto-char (point-min))
3650                   (narrow-to-region (point) (point))
3651                   (insert header))
3652               (message-goto-eoh)
3653               (setq header (buffer-substring (point-min) (point)))
3654               (goto-char (point-min))
3655               (narrow-to-region (point) (point))
3656               (insert header)
3657               (message-remove-header "Mime-Version")
3658               (message-remove-header "Content-Type")
3659               (message-remove-header "Content-Transfer-Encoding")
3660               (message-remove-header "Message-ID")
3661               (message-remove-header "Lines")
3662               (goto-char (point-max))
3663               (insert "Mime-Version: 1.0\n")
3664               (setq header (buffer-string)))
3665             (goto-char (point-max))
3666             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3667                             id n total))
3668             (forward-char -1)
3669             (let ((mail-header-separator ""))
3670               (when (memq 'Message-ID message-required-mail-headers)
3671                 (insert "Message-ID: " (message-make-message-id) "\n"))
3672               (when (memq 'Lines message-required-mail-headers)
3673                 (insert "Lines: " (message-make-lines) "\n"))
3674               (message-goto-subject)
3675               (end-of-line)
3676               (insert (format " (%d/%d)" n total))
3677               (widen)
3678               (mm-with-unibyte-current-buffer
3679                 (funcall (or message-send-mail-real-function
3680                              message-send-mail-function))))
3681             (setq n (+ n 1))
3682             (setq p (pop plist))
3683             (erase-buffer)))
3684       (kill-buffer tembuf))))
3685
3686 (defun message-send-mail (&optional arg)
3687   (require 'mail-utils)
3688   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3689          (case-fold-search nil)
3690          (news (message-news-p))
3691          (mailbuf (current-buffer))
3692          (message-this-is-mail t)
3693          (message-posting-charset
3694           (if (fboundp 'gnus-setup-posting-charset)
3695               (gnus-setup-posting-charset nil)
3696             message-posting-charset))
3697          (headers message-required-mail-headers))
3698     (save-restriction
3699       (message-narrow-to-headers)
3700       ;; Generate the Mail-Followup-To header if the header is not there...
3701       (if (and (message-subscribed-p)
3702                (not (mail-fetch-field "mail-followup-to")))
3703           (setq headers
3704                 (cons
3705                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
3706                  message-required-mail-headers))
3707         ;; otherwise, delete the MFT header if the field is empty
3708         (when (equal "" (mail-fetch-field "mail-followup-to"))
3709           (message-remove-header "^Mail-Followup-To:")))
3710       ;; Insert some headers.
3711       (let ((message-deletable-headers
3712              (if news nil message-deletable-headers)))
3713         (message-generate-headers headers))
3714       ;; Let the user do all of the above.
3715       (run-hooks 'message-header-hook))
3716     (unwind-protect
3717         (save-excursion
3718           (set-buffer tembuf)
3719           (erase-buffer)
3720           ;; Avoid copying text props (except hard newlines).
3721           (insert (with-current-buffer mailbuf
3722                     (mml-buffer-substring-no-properties-except-hard-newlines
3723                      (point-min) (point-max))))
3724           ;; Remove some headers.
3725           (message-encode-message-body)
3726           (save-restriction
3727             (message-narrow-to-headers)
3728             ;; We (re)generate the Lines header.
3729             (when (memq 'Lines message-required-mail-headers)
3730               (message-generate-headers '(Lines)))
3731             ;; Remove some headers.
3732             (message-remove-header message-ignored-mail-headers t)
3733             (let ((mail-parse-charset message-default-charset))
3734               (mail-encode-encoded-word-buffer)))
3735           (goto-char (point-max))
3736           ;; require one newline at the end.
3737           (or (= (preceding-char) ?\n)
3738               (insert ?\n))
3739           (message-cleanup-headers)
3740           ;; FIXME: we're inserting the courtesy copy after encoding.
3741           ;; This is wrong if the courtesy copy string contains
3742           ;; non-ASCII characters. -- jh
3743           (when
3744               (save-restriction
3745                 (message-narrow-to-headers)
3746                 (and news
3747                      (or (message-fetch-field "cc")
3748                          (message-fetch-field "bcc")
3749                          (message-fetch-field "to"))
3750                      (let ((content-type (message-fetch-field
3751                                           "content-type")))
3752                        (and
3753                         (or
3754                          (not content-type)
3755                          (string= "text/plain"
3756                                   (car
3757                                    (mail-header-parse-content-type
3758                                     content-type))))
3759                         (not
3760                          (string= "base64"
3761                                   (message-fetch-field
3762                                    "content-transfer-encoding")))))))
3763             (message-insert-courtesy-copy))
3764           (if (or (not message-send-mail-partially-limit)
3765                   (< (point-max) message-send-mail-partially-limit)
3766                   (not (message-y-or-n-p
3767                         "The message size is too large, split? "
3768                         t
3769                         "\
3770 The message size, "
3771                         (/ (point-max) 1000) "KB, is too large.
3772
3773 Some mail gateways (MTA's) bounce large messages.  To avoid the
3774 problem, answer `y', and the message will be split into several
3775 smaller pieces, the size of each is about "
3776                         (/ message-send-mail-partially-limit 1000)
3777                         "KB except the last
3778 one.
3779
3780 However, some mail readers (MUA's) can't read split messages, i.e.,
3781 mails in message/partially format. Answer `n', and the message will be
3782 sent in one piece.
3783
3784 The size limit is controlled by `message-send-mail-partially-limit'.
3785 If you always want Gnus to send messages in one piece, set
3786 `message-send-mail-partially-limit' to nil.
3787 ")))
3788               (mm-with-unibyte-current-buffer
3789                 (message "Sending via mail...")
3790                 (funcall (or message-send-mail-real-function
3791                              message-send-mail-function)))
3792             (message-send-mail-partially)))
3793       (kill-buffer tembuf))
3794     (set-buffer mailbuf)
3795     (push 'mail message-sent-message-via)))
3796
3797 (defun message-send-mail-with-sendmail ()
3798   "Send off the prepared buffer with sendmail."
3799   (let ((errbuf (if message-interactive
3800                     (message-generate-new-buffer-clone-locals
3801                      " sendmail errors")
3802                   0))
3803         resend-to-addresses delimline)
3804     (unwind-protect
3805         (progn
3806           (let ((case-fold-search t))
3807             (save-restriction
3808               (message-narrow-to-headers)
3809               (setq resend-to-addresses (message-fetch-field "resent-to")))
3810             ;; Change header-delimiter to be what sendmail expects.
3811             (goto-char (point-min))
3812             (re-search-forward
3813              (concat "^" (regexp-quote mail-header-separator) "\n"))
3814             (replace-match "\n")
3815             (backward-char 1)
3816             (setq delimline (point-marker))
3817             (run-hooks 'message-send-mail-hook)
3818             ;; Insert an extra newline if we need it to work around
3819             ;; Sun's bug that swallows newlines.
3820             (goto-char (1+ delimline))
3821             (when (eval message-mailer-swallows-blank-line)
3822               (newline))
3823             (when message-interactive
3824               (with-current-buffer errbuf
3825                 (erase-buffer))))
3826           (let* ((default-directory "/")
3827                  (coding-system-for-write message-send-coding-system)
3828                  (cpr (apply
3829                        'call-process-region
3830                        (append
3831                         (list (point-min) (point-max)
3832                               (if (boundp 'sendmail-program)
3833                                   sendmail-program
3834                                 "/usr/lib/sendmail")
3835                               nil errbuf nil "-oi")
3836                         ;; Always specify who from,
3837                         ;; since some systems have broken sendmails.
3838                         ;; But some systems are more broken with -f, so
3839                         ;; we'll let users override this.
3840                         (if (null message-sendmail-f-is-evil)
3841                             (list "-f" (message-sendmail-envelope-from)))
3842                         ;; These mean "report errors by mail"
3843                         ;; and "deliver in background".
3844                         (if (null message-interactive) '("-oem" "-odb"))
3845                         ;; Get the addresses from the message
3846                         ;; unless this is a resend.
3847                         ;; We must not do that for a resend
3848                         ;; because we would find the original addresses.
3849                         ;; For a resend, include the specific addresses.
3850                         (if resend-to-addresses
3851                             (list resend-to-addresses)
3852                           '("-t"))))))
3853             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
3854               (error "Sending...failed with exit value %d" cpr)))
3855           (when message-interactive
3856             (save-excursion
3857               (set-buffer errbuf)
3858               (goto-char (point-min))
3859               (while (re-search-forward "\n\n* *" nil t)
3860                 (replace-match "; "))
3861               (if (not (zerop (buffer-size)))
3862                   (error "Sending...failed to %s"
3863                          (buffer-string))))))
3864       (when (bufferp errbuf)
3865         (kill-buffer errbuf)))))
3866
3867 (defun message-send-mail-with-qmail ()
3868   "Pass the prepared message buffer to qmail-inject.
3869 Refer to the documentation for the variable `message-send-mail-function'
3870 to find out how to use this."
3871   ;; replace the header delimiter with a blank line
3872   (goto-char (point-min))
3873   (re-search-forward
3874    (concat "^" (regexp-quote mail-header-separator) "\n"))
3875   (replace-match "\n")
3876   (run-hooks 'message-send-mail-hook)
3877   ;; send the message
3878   (case
3879       (let ((coding-system-for-write message-send-coding-system))
3880         (apply
3881          'call-process-region 1 (point-max) message-qmail-inject-program
3882          nil nil nil
3883          ;; qmail-inject's default behaviour is to look for addresses on the
3884          ;; command line; if there're none, it scans the headers.
3885          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3886          ;;
3887          ;; in general, ALL of qmail-inject's defaults are perfect for simply
3888          ;; reading a formatted (i. e., at least a To: or Resent-To header)
3889          ;; message from stdin.
3890          ;;
3891          ;; qmail also has the advantage of not having been raped by
3892          ;; various vendors, so we don't have to allow for that, either --
3893          ;; compare this with message-send-mail-with-sendmail and weep
3894          ;; for sendmail's lost innocence.
3895          ;;
3896          ;; all this is way cool coz it lets us keep the arguments entirely
3897          ;; free for -inject-arguments -- a big win for the user and for us
3898          ;; since we don't have to play that double-guessing game and the user
3899          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3900          (if (functionp message-qmail-inject-args)
3901              (funcall message-qmail-inject-args)
3902            message-qmail-inject-args)))
3903     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3904     ;; we have to look at the retval instead
3905     (0 nil)
3906     (100 (error "qmail-inject reported permanent failure"))
3907     (111 (error "qmail-inject reported transient failure"))
3908     ;; should never happen
3909     (t   (error "qmail-inject reported unknown failure"))))
3910
3911 (defun message-send-mail-with-mh ()
3912   "Send the prepared message buffer with mh."
3913   (let ((mh-previous-window-config nil)
3914         (name (mh-new-draft-name)))
3915     (setq buffer-file-name name)
3916     ;; MH wants to generate these headers itself.
3917     (when message-mh-deletable-headers
3918       (let ((headers message-mh-deletable-headers))
3919         (while headers
3920           (goto-char (point-min))
3921           (and (re-search-forward
3922                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3923                (message-delete-line))
3924           (pop headers))))
3925     (run-hooks 'message-send-mail-hook)
3926     ;; Pass it on to mh.
3927     (mh-send-letter)))
3928
3929 (defun message-smtpmail-send-it ()
3930   "Send the prepared message buffer with `smtpmail-send-it'.
3931 This only differs from `smtpmail-send-it' that this command evaluates
3932 `message-send-mail-hook' just before sending a message.  It is useful
3933 if your ISP requires the POP-before-SMTP authentication.  See the Gnus
3934 manual for details."
3935   (run-hooks 'message-send-mail-hook)
3936   (smtpmail-send-it))
3937
3938 (defun message-canlock-generate ()
3939   "Return a string that is non-trivial to guess.
3940 Do not use this for anything important, it is cryptographically weak."
3941   (require 'sha1-el)
3942   (let (sha1-maximum-internal-length)
3943     (sha1 (concat (message-unique-id)
3944                   (format "%x%x%x" (random) (random t) (random))
3945                   (prin1-to-string (recent-keys))
3946                   (prin1-to-string (garbage-collect))))))
3947
3948 (defun message-canlock-password ()
3949   "The password used by message for cancel locks.
3950 This is the value of `canlock-password', if that option is non-nil.
3951 Otherwise, generate and save a value for `canlock-password' first."
3952   (unless canlock-password
3953     (customize-save-variable 'canlock-password (message-canlock-generate))
3954     (setq canlock-password-for-verify canlock-password))
3955   canlock-password)
3956
3957 (defun message-insert-canlock ()
3958   (when message-insert-canlock
3959     (message-canlock-password)
3960     (canlock-insert-header)))
3961
3962 (defun message-send-news (&optional arg)
3963   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3964          (case-fold-search nil)
3965          (method (if (functionp message-post-method)
3966                      (funcall message-post-method arg)
3967                    message-post-method))
3968          (newsgroups-field (save-restriction
3969                             (message-narrow-to-headers-or-head)
3970                             (message-fetch-field "Newsgroups")))
3971          (followup-field (save-restriction
3972                            (message-narrow-to-headers-or-head)
3973                            (message-fetch-field "Followup-To")))
3974          ;; BUG: We really need to get the charset for each name in the
3975          ;; Newsgroups and Followup-To lines to allow crossposting
3976          ;; between group namess with incompatible character sets.
3977          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3978          (group-field-charset
3979           (gnus-group-name-charset method newsgroups-field))
3980          (followup-field-charset
3981           (gnus-group-name-charset method (or followup-field "")))
3982          (rfc2047-header-encoding-alist
3983           (append (when group-field-charset
3984                     (list (cons "Newsgroups" group-field-charset)))
3985                   (when followup-field-charset
3986                     (list (cons "Followup-To" followup-field-charset)))
3987                   rfc2047-header-encoding-alist))
3988          (messbuf (current-buffer))
3989          (message-syntax-checks
3990           (if (and arg
3991                    (listp message-syntax-checks))
3992               (cons '(existing-newsgroups . disabled)
3993                     message-syntax-checks)
3994             message-syntax-checks))
3995          (message-this-is-news t)
3996          (message-posting-charset
3997           (gnus-setup-posting-charset newsgroups-field))
3998          result)
3999     (if (not (message-check-news-body-syntax))
4000         nil
4001       (save-restriction
4002         (message-narrow-to-headers)
4003         ;; Insert some headers.
4004         (message-generate-headers message-required-news-headers)
4005         (message-insert-canlock)
4006         ;; Let the user do all of the above.
4007         (run-hooks 'message-header-hook))
4008       ;; Note: This check will be disabled by the ".*" default value for
4009       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4010       (when (and group-field-charset
4011                  (listp message-syntax-checks))
4012         (setq message-syntax-checks
4013               (cons '(valid-newsgroups . disabled)
4014                     message-syntax-checks)))
4015       (message-cleanup-headers)
4016       (if (not (let ((message-post-method method))
4017                  (message-check-news-syntax)))
4018           nil
4019         (unwind-protect
4020             (save-excursion
4021               (set-buffer tembuf)
4022               (buffer-disable-undo)
4023               (erase-buffer)
4024               ;; Avoid copying text props (except hard newlines).
4025               (insert
4026                (with-current-buffer messbuf
4027                  (mml-buffer-substring-no-properties-except-hard-newlines
4028                   (point-min) (point-max))))
4029               (message-encode-message-body)
4030               ;; Remove some headers.
4031               (save-restriction
4032                 (message-narrow-to-headers)
4033                 ;; We (re)generate the Lines header.
4034                 (when (memq 'Lines message-required-mail-headers)
4035                   (message-generate-headers '(Lines)))
4036                 ;; Remove some headers.
4037                 (message-remove-header message-ignored-news-headers t)
4038                 (let ((mail-parse-charset message-default-charset))
4039                   (mail-encode-encoded-word-buffer)))
4040               (goto-char (point-max))
4041               ;; require one newline at the end.
4042               (or (= (preceding-char) ?\n)
4043                   (insert ?\n))
4044               (let ((case-fold-search t))
4045                 ;; Remove the delimiter.
4046                 (goto-char (point-min))
4047                 (re-search-forward
4048                  (concat "^" (regexp-quote mail-header-separator) "\n"))
4049                 (replace-match "\n")
4050                 (backward-char 1))
4051               (run-hooks 'message-send-news-hook)
4052               (gnus-open-server method)
4053               (message "Sending news via %s..." (gnus-server-string method))
4054               (setq result (let ((mail-header-separator ""))
4055                              (gnus-request-post method))))
4056           (kill-buffer tembuf))
4057         (set-buffer messbuf)
4058         (if result
4059             (push 'news message-sent-message-via)
4060           (message "Couldn't send message via news: %s"
4061                    (nnheader-get-report (car method)))
4062           nil)))))
4063
4064 ;;;
4065 ;;; Header generation & syntax checking.
4066 ;;;
4067
4068 (defun message-check-element (type)
4069   "Return non-nil if this TYPE is not to be checked."
4070   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4071       t
4072     (let ((able (assq type message-syntax-checks)))
4073       (and (consp able)
4074            (eq (cdr able) 'disabled)))))
4075
4076 (defun message-check-news-syntax ()
4077   "Check the syntax of the message."
4078   (save-excursion
4079     (save-restriction
4080       (widen)
4081       ;; We narrow to the headers and check them first.
4082       (save-excursion
4083         (save-restriction
4084           (message-narrow-to-headers)
4085           (message-check-news-header-syntax))))))
4086
4087 (defun message-check-news-header-syntax ()
4088   (and
4089    ;; Check Newsgroups header.
4090    (message-check 'newsgroups
4091      (let ((group (message-fetch-field "newsgroups")))
4092        (or
4093         (and group
4094              (not (string-match "\\`[ \t]*\\'" group)))
4095         (ignore
4096          (message
4097           "The newsgroups field is empty or missing.  Posting is denied.")))))
4098    ;; Check the Subject header.
4099    (message-check 'subject
4100      (let* ((case-fold-search t)
4101             (subject (message-fetch-field "subject")))
4102        (or
4103         (and subject
4104              (not (string-match "\\`[ \t]*\\'" subject)))
4105         (ignore
4106          (message
4107           "The subject field is empty or missing.  Posting is denied.")))))
4108    ;; Check for commands in Subject.
4109    (message-check 'subject-cmsg
4110      (if (string-match "^cmsg " (message-fetch-field "subject"))
4111          (y-or-n-p
4112           "The control code \"cmsg\" is in the subject.  Really post? ")
4113        t))
4114    ;; Check long header lines.
4115    (message-check 'long-header-lines
4116      (let ((start (point))
4117            (header nil)
4118            (length 0)
4119            found)
4120        (while (and (not found)
4121                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4122          (if (> (- (point) (match-beginning 0)) 998)
4123              (setq found t
4124                    length (- (point) (match-beginning 0)))
4125            (setq header (match-string-no-properties 1)))
4126          (setq start (match-beginning 0))
4127          (forward-line 1))
4128        (if found
4129            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4130                              header length))
4131          t)))
4132    ;; Check for multiple identical headers.
4133    (message-check 'multiple-headers
4134      (let (found)
4135        (while (and (not found)
4136                    (re-search-forward "^[^ \t:]+: " nil t))
4137          (save-excursion
4138            (or (re-search-forward
4139                 (concat "^"
4140                         (regexp-quote
4141                          (setq found
4142                                (buffer-substring
4143                                 (match-beginning 0) (- (match-end 0) 2))))
4144                         ":")
4145                 nil t)
4146                (setq found nil))))
4147        (if found
4148            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4149          t)))
4150    ;; Check for Version and Sendsys.
4151    (message-check 'sendsys
4152      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4153          (y-or-n-p
4154           (format "The article contains a %s command.  Really post? "
4155                   (buffer-substring (match-beginning 0)
4156                                     (1- (match-end 0)))))
4157        t))
4158    ;; See whether we can shorten Followup-To.
4159    (message-check 'shorten-followup-to
4160      (let ((newsgroups (message-fetch-field "newsgroups"))
4161            (followup-to (message-fetch-field "followup-to"))
4162            to)
4163        (when (and newsgroups
4164                   (string-match "," newsgroups)
4165                   (not followup-to)
4166                   (not
4167                    (zerop
4168                     (length
4169                      (setq to (completing-read
4170                                "Followups to (default: no Followup-To header) "
4171                                (mapcar #'list
4172                                        (cons "poster"
4173                                              (message-tokenize-header
4174                                               newsgroups)))))))))
4175          (goto-char (point-min))
4176          (insert "Followup-To: " to "\n"))
4177        t))
4178    ;; Check "Shoot me".
4179    (message-check 'shoot
4180      (if (re-search-forward
4181           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4182          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4183        t))
4184    ;; Check for Approved.
4185    (message-check 'approved
4186      (if (re-search-forward "^Approved:" nil t)
4187          (y-or-n-p "The article contains an Approved header.  Really post? ")
4188        t))
4189    ;; Check the Message-ID header.
4190    (message-check 'message-id
4191      (let* ((case-fold-search t)
4192             (message-id (message-fetch-field "message-id" t)))
4193        (or (not message-id)
4194            ;; Is there an @ in the ID?
4195            (and (string-match "@" message-id)
4196                 ;; Is there a dot in the ID?
4197                 (string-match "@[^.]*\\." message-id)
4198                 ;; Does the ID end with a dot?
4199                 (not (string-match "\\.>" message-id)))
4200            (y-or-n-p
4201             (format "The Message-ID looks strange: \"%s\".  Really post? "
4202                     message-id)))))
4203    ;; Check the Newsgroups & Followup-To headers.
4204    (message-check 'existing-newsgroups
4205      (let* ((case-fold-search t)
4206             (newsgroups (message-fetch-field "newsgroups"))
4207             (followup-to (message-fetch-field "followup-to"))
4208             (groups (message-tokenize-header
4209                      (if followup-to
4210                          (concat newsgroups "," followup-to)
4211                        newsgroups)))
4212             (post-method (if (functionp message-post-method)
4213                              (funcall message-post-method)
4214                            message-post-method))
4215             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4216             ;; would probably involve a new nnoo function.
4217             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4218             (method (if (and (consp post-method)
4219                              (eq (car post-method) 'nnvirtual)
4220                              gnus-message-group-art)
4221                         (let ((group (car (nnvirtual-find-group-art
4222                                            (car gnus-message-group-art)
4223                                            (cdr gnus-message-group-art)))))
4224                           (gnus-find-method-for-group group))
4225                       post-method))
4226             (known-groups
4227              (mapcar (lambda (n)
4228                        (gnus-group-name-decode
4229                         (gnus-group-real-name n)
4230                         (gnus-group-name-charset method n)))
4231                      (gnus-groups-from-server method)))
4232             errors)
4233        (while groups
4234          (when (and (not (equal (car groups) "poster"))
4235                     (not (member (car groups) known-groups))
4236                     (not (member (car groups) errors)))
4237            (push (car groups) errors))
4238          (pop groups))
4239        (cond
4240         ;; Gnus is not running.
4241         ((or (not (and (boundp 'gnus-active-hashtb)
4242                        gnus-active-hashtb))
4243              (not (boundp 'gnus-read-active-file)))
4244          t)
4245         ;; We don't have all the group names.
4246         ((and (or (not gnus-read-active-file)
4247                   (eq gnus-read-active-file 'some))
4248               errors)
4249          (y-or-n-p
4250           (format
4251            "Really use %s possibly unknown group%s: %s? "
4252            (if (= (length errors) 1) "this" "these")
4253            (if (= (length errors) 1) "" "s")
4254            (mapconcat 'identity errors ", "))))
4255         ;; There were no errors.
4256         ((not errors)
4257          t)
4258         ;; There are unknown groups.
4259         (t
4260          (y-or-n-p
4261           (format
4262            "Really post to %s unknown group%s: %s? "
4263            (if (= (length errors) 1) "this" "these")
4264            (if (= (length errors) 1) "" "s")
4265            (mapconcat 'identity errors ", ")))))))
4266    ;; Check continuation headers.
4267    (message-check 'continuation-headers
4268      (goto-char (point-min))
4269      (let ((do-posting t))
4270        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4271          (if (y-or-n-p "Fix continuation lines? ")
4272              (progn
4273                (goto-char (match-beginning 0))
4274                (insert " "))
4275            (unless (y-or-n-p "Send anyway? ")
4276              (setq do-posting nil))))
4277        do-posting))
4278    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4279    (message-check 'valid-newsgroups
4280      (let ((case-fold-search t)
4281            (headers '("Newsgroups" "Followup-To"))
4282            header error)
4283        (while (and headers (not error))
4284          (when (setq header (mail-fetch-field (car headers)))
4285            (if (or
4286                 (not
4287                  (string-match
4288                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4289                   header))
4290                 (memq
4291                  nil (mapcar
4292                       (lambda (g)
4293                         (not (string-match "\\.\\'\\|\\.\\." g)))
4294                       (message-tokenize-header header ","))))
4295                (setq error t)))
4296          (unless error
4297            (pop headers)))
4298        (if (not error)
4299            t
4300          (y-or-n-p
4301           (format "The %s header looks odd: \"%s\".  Really post? "
4302                   (car headers) header)))))
4303    (message-check 'repeated-newsgroups
4304      (let ((case-fold-search t)
4305            (headers '("Newsgroups" "Followup-To"))
4306            header error groups group)
4307        (while (and headers
4308                    (not error))
4309          (when (setq header (mail-fetch-field (pop headers)))
4310            (setq groups (message-tokenize-header header ","))
4311            (while (setq group (pop groups))
4312              (when (member group groups)
4313                (setq error group
4314                      groups nil)))))
4315        (if (not error)
4316            t
4317          (y-or-n-p
4318           (format "Group %s is repeated in headers.  Really post? " error)))))
4319    ;; Check the From header.
4320    (message-check 'from
4321      (let* ((case-fold-search t)
4322             (from (message-fetch-field "from"))
4323             ad)
4324        (cond
4325         ((not from)
4326          (message "There is no From line.  Posting is denied.")
4327          nil)
4328         ((or (not (string-match
4329                    "@[^\\.]*\\."
4330                    (setq ad (nth 1 (mail-extract-address-components
4331                                     from))))) ;larsi@ifi
4332              (string-match "\\.\\." ad) ;larsi@ifi..uio
4333              (string-match "@\\." ad)   ;larsi@.ifi.uio
4334              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4335              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4336              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4337          (message
4338           "Denied posting -- the From looks strange: \"%s\"." from)
4339          nil)
4340         ((let ((addresses (rfc822-addresses from)))
4341            (while (and addresses
4342                        (not (eq (string-to-char (car addresses)) ?\()))
4343              (setq addresses (cdr addresses)))
4344            addresses)
4345          (message
4346           "Denied posting -- bad From address: \"%s\"." from)
4347          nil)
4348         (t t))))
4349    ;; Check the Reply-To header.
4350    (message-check 'reply-to
4351      (let* ((case-fold-search t)
4352             (reply-to (message-fetch-field "reply-to"))
4353             ad)
4354        (cond
4355         ((not reply-to)
4356          t)
4357         ((string-match "," reply-to)
4358          (y-or-n-p
4359           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4360                   reply-to)))
4361         ((or (not (string-match
4362                    "@[^\\.]*\\."
4363                    (setq ad (nth 1 (mail-extract-address-components
4364                                     reply-to))))) ;larsi@ifi
4365              (string-match "\\.\\." ad) ;larsi@ifi..uio
4366              (string-match "@\\." ad)   ;larsi@.ifi.uio
4367              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4368              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4369              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4370          (y-or-n-p
4371           (format
4372            "The Reply-To looks strange: \"%s\". Really post? "
4373            reply-to)))
4374         (t t))))))
4375
4376 (defun message-check-news-body-syntax ()
4377   (and
4378    ;; Check for long lines.
4379    (message-check 'long-lines
4380      (goto-char (point-min))
4381      (re-search-forward
4382       (concat "^" (regexp-quote mail-header-separator) "$"))
4383      (forward-line 1)
4384      (while (and
4385              (or (looking-at
4386                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
4387                  (let ((p (point)))
4388                    (end-of-line)
4389                    (< (- (point) p) 80)))
4390              (zerop (forward-line 1))))
4391      (or (bolp)
4392          (eobp)
4393          (y-or-n-p
4394           "You have lines longer than 79 characters.  Really post? ")))
4395    ;; Check whether the article is empty.
4396    (message-check 'empty
4397      (goto-char (point-min))
4398      (re-search-forward
4399       (concat "^" (regexp-quote mail-header-separator) "$"))
4400      (forward-line 1)
4401      (let ((b (point)))
4402        (goto-char (point-max))
4403        (re-search-backward message-signature-separator nil t)
4404        (beginning-of-line)
4405        (or (re-search-backward "[^ \n\t]" b t)
4406            (if (message-gnksa-enable-p 'empty-article)
4407                (y-or-n-p "Empty article.  Really post? ")
4408              (message "Denied posting -- Empty article.")
4409              nil))))
4410    ;; Check for control characters.
4411    (message-check 'control-chars
4412      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4413          (y-or-n-p
4414           "The article contains control characters.  Really post? ")
4415        t))
4416    ;; Check excessive size.
4417    (message-check 'size
4418      (if (> (buffer-size) 60000)
4419          (y-or-n-p
4420           (format "The article is %d octets long.  Really post? "
4421                   (buffer-size)))
4422        t))
4423    ;; Check whether any new text has been added.
4424    (message-check 'new-text
4425      (or
4426       (not message-checksum)
4427       (not (eq (message-checksum) message-checksum))
4428       (if (message-gnksa-enable-p 'quoted-text-only)
4429           (y-or-n-p
4430            "It looks like no new text has been added.  Really post? ")
4431         (message "Denied posting -- no new text has been added.")
4432         nil)))
4433    ;; Check the length of the signature.
4434    (message-check 'signature
4435      (goto-char (point-max))
4436      (if (> (count-lines (point) (point-max)) 5)
4437          (y-or-n-p
4438           (format
4439            "Your .sig is %d lines; it should be max 4.  Really post? "
4440            (1- (count-lines (point) (point-max)))))
4441        t))
4442    ;; Ensure that text follows last quoted portion.
4443    (message-check 'quoting-style
4444      (goto-char (point-max))
4445      (let ((no-problem t))
4446        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4447          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4448        (if no-problem
4449            t
4450          (if (message-gnksa-enable-p 'quoted-text-only)
4451              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4452            ;; Ensure that
4453            (goto-char (point-min))
4454            (re-search-forward
4455             (concat "^" (regexp-quote mail-header-separator) "$"))
4456            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4457                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4458              (message "Denied posting -- only quoted text.")
4459              nil)))))))
4460
4461 (defun message-checksum ()
4462   "Return a \"checksum\" for the current buffer."
4463   (let ((sum 0))
4464     (save-excursion
4465       (goto-char (point-min))
4466       (re-search-forward
4467        (concat "^" (regexp-quote mail-header-separator) "$"))
4468       (while (not (eobp))
4469         (when (not (looking-at "[ \t\n]"))
4470           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4471                             (char-after))))
4472         (forward-char 1)))
4473     sum))
4474
4475 (defun message-do-fcc ()
4476   "Process Fcc headers in the current buffer."
4477   (let ((case-fold-search t)
4478         (buf (current-buffer))
4479         list file
4480         (mml-externalize-attachments message-fcc-externalize-attachments))
4481     (save-excursion
4482       (save-restriction
4483         (message-narrow-to-headers)
4484         (setq file (message-fetch-field "fcc" t)))
4485       (when file
4486         (set-buffer (get-buffer-create " *message temp*"))
4487         (erase-buffer)
4488         (insert-buffer-substring buf)
4489         (message-encode-message-body)
4490         (save-restriction
4491           (message-narrow-to-headers)
4492           (while (setq file (message-fetch-field "fcc" t))
4493             (push file list)
4494             (message-remove-header "fcc" nil t))
4495           (let ((mail-parse-charset message-default-charset)
4496                 (rfc2047-header-encoding-alist
4497                  (cons '("Newsgroups" . default)
4498                        rfc2047-header-encoding-alist)))
4499             (mail-encode-encoded-word-buffer)))
4500         (goto-char (point-min))
4501         (when (re-search-forward
4502                (concat "^" (regexp-quote mail-header-separator) "$")
4503                nil t)
4504           (replace-match "" t t ))
4505         ;; Process FCC operations.
4506         (while list
4507           (setq file (pop list))
4508           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4509               ;; Pipe the article to the program in question.
4510               (call-process-region (point-min) (point-max) shell-file-name
4511                                    nil nil nil shell-command-switch
4512                                    (match-string 1 file))
4513             ;; Save the article.
4514             (setq file (expand-file-name file))
4515             (unless (file-exists-p (file-name-directory file))
4516               (make-directory (file-name-directory file) t))
4517             (if (and message-fcc-handler-function
4518                      (not (eq message-fcc-handler-function 'rmail-output)))
4519                 (funcall message-fcc-handler-function file)
4520               (if (and (file-readable-p file) (mail-file-babyl-p file))
4521                   (rmail-output file 1 nil t)
4522                 (let ((mail-use-rfc822 t))
4523                   (rmail-output file 1 t t))))))
4524         (kill-buffer (current-buffer))))))
4525
4526 (defun message-output (filename)
4527   "Append this article to Unix/babyl mail file FILENAME."
4528   (if (and (file-readable-p filename)
4529            (mail-file-babyl-p filename))
4530       (gnus-output-to-rmail filename t)
4531     (gnus-output-to-mail filename t)))
4532
4533 (defun message-cleanup-headers ()
4534   "Do various automatic cleanups of the headers."
4535   ;; Remove empty lines in the header.
4536   (save-restriction
4537     (message-narrow-to-headers)
4538     ;; Remove blank lines.
4539     (while (re-search-forward "^[ \t]*\n" nil t)
4540       (replace-match "" t t))
4541
4542     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4543     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4544     ;; embedded line breaks.
4545     (goto-char (point-min))
4546     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4547       (save-restriction
4548         (narrow-to-region
4549          (point)
4550          (if (re-search-forward "^[^ \t]" nil t)
4551              (match-beginning 0)
4552            (forward-line 1)
4553            (point)))
4554         (goto-char (point-min))
4555         (while (re-search-forward "\n[ \t]+" nil t)
4556           (replace-match " " t t))     ;No line breaks (too confusing)
4557         (goto-char (point-min))
4558         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4559           (replace-match "," t t))
4560         (goto-char (point-min))
4561         ;; Remove trailing commas.
4562         (when (re-search-forward ",+$" nil t)
4563           (replace-match "" t t))))))
4564
4565 (defun message-make-date (&optional now)
4566   "Make a valid data header.
4567 If NOW, use that time instead."
4568   (let* ((now (or now (current-time)))
4569          (zone (nth 8 (decode-time now)))
4570          (sign "+"))
4571     (when (< zone 0)
4572       (setq sign "-")
4573       (setq zone (- zone)))
4574     (concat
4575      ;; The day name of the %a spec is locale-specific.  Pfff.
4576      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4577                                              parse-time-weekdays))))
4578      (format-time-string "%d" now)
4579      ;; The month name of the %b spec is locale-specific.  Pfff.
4580      (format " %s "
4581              (capitalize (car (rassoc (nth 4 (decode-time now))
4582                                       parse-time-months))))
4583      (format-time-string "%Y %H:%M:%S " now)
4584      ;; We do all of this because XEmacs doesn't have the %z spec.
4585      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4586
4587 (defun message-make-message-id ()
4588   "Make a unique Message-ID."
4589   (concat "<" (message-unique-id)
4590           (let ((psubject (save-excursion (message-fetch-field "subject")))
4591                 (psupersedes
4592                  (save-excursion (message-fetch-field "supersedes"))))
4593             (if (or
4594                  (and message-reply-headers
4595                       (mail-header-references message-reply-headers)
4596                       (mail-header-subject message-reply-headers)
4597                       psubject
4598                       (not (string=
4599                             (message-strip-subject-re
4600                              (mail-header-subject message-reply-headers))
4601                             (message-strip-subject-re psubject))))
4602                  (and psupersedes
4603                       (string-match "_-_@" psupersedes)))
4604                 "_-_" ""))
4605           "@" (message-make-fqdn) ">"))
4606
4607 (defvar message-unique-id-char nil)
4608
4609 ;; If you ever change this function, make sure the new version
4610 ;; cannot generate IDs that the old version could.
4611 ;; You might for example insert a "." somewhere (not next to another dot
4612 ;; or string boundary), or modify the "fsf" string.
4613 (defun message-unique-id ()
4614   ;; Don't use microseconds from (current-time), they may be unsupported.
4615   ;; Instead we use this randomly inited counter.
4616   (setq message-unique-id-char
4617         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4618            ;; (current-time) returns 16-bit ints,
4619            ;; and 2^16*25 just fits into 4 digits i base 36.
4620            (* 25 25)))
4621   (let ((tm (current-time)))
4622     (concat
4623      (if (memq system-type '(ms-dos emx vax-vms))
4624          (let ((user (downcase (user-login-name))))
4625            (while (string-match "[^a-z0-9_]" user)
4626              (aset user (match-beginning 0) ?_))
4627            user)
4628        (message-number-base36 (user-uid) -1))
4629      (message-number-base36 (+ (car tm)
4630                                (lsh (% message-unique-id-char 25) 16)) 4)
4631      (message-number-base36 (+ (nth 1 tm)
4632                                (lsh (/ message-unique-id-char 25) 16)) 4)
4633      ;; Append a given name, because while the generated ID is unique
4634      ;; to this newsreader, other newsreaders might otherwise generate
4635      ;; the same ID via another algorithm.
4636      ".fsf")))
4637
4638 (defun message-number-base36 (num len)
4639   (if (if (< len 0)
4640           (<= num 0)
4641         (= len 0))
4642       ""
4643     (concat (message-number-base36 (/ num 36) (1- len))
4644             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4645                                   (% num 36))))))
4646
4647 (defun message-make-organization ()
4648   "Make an Organization header."
4649   (let* ((organization
4650           (when message-user-organization
4651             (if (functionp message-user-organization)
4652                 (funcall message-user-organization)
4653               message-user-organization))))
4654     (with-temp-buffer
4655       (mm-enable-multibyte)
4656       (cond ((stringp organization)
4657              (insert organization))
4658             ((and (eq t organization)
4659                   message-user-organization-file
4660                   (file-exists-p message-user-organization-file))
4661              (insert-file-contents message-user-organization-file)))
4662       (goto-char (point-min))
4663       (while (re-search-forward "[\t\n]+" nil t)
4664         (replace-match "" t t))
4665       (unless (zerop (buffer-size))
4666         (buffer-string)))))
4667
4668 (defun message-make-lines ()
4669   "Count the number of lines and return numeric string."
4670   (save-excursion
4671     (save-restriction
4672       (widen)
4673       (message-goto-body)
4674       (int-to-string (count-lines (point) (point-max))))))
4675
4676 (defun message-make-references ()
4677   "Return the References header for this message."
4678   (when message-reply-headers
4679     (let ((message-id (mail-header-message-id message-reply-headers))
4680           (references (mail-header-references message-reply-headers))
4681           new-references)
4682       (if (or references message-id)
4683           (concat (or references "") (and references " ")
4684                   (or message-id ""))
4685         nil))))
4686
4687 (defun message-make-in-reply-to ()
4688   "Return the In-Reply-To header for this message."
4689   (when message-reply-headers
4690     (let ((from (mail-header-from message-reply-headers))
4691           (date (mail-header-date message-reply-headers))
4692           (msg-id (mail-header-message-id message-reply-headers)))
4693       (when from
4694         (let ((name (mail-extract-address-components from)))
4695           (concat msg-id (if msg-id " (")
4696                   (or (car name)
4697                       (nth 1 name))
4698                   "'s message of \""
4699                   (if (or (not date) (string= date ""))
4700                       "(unknown date)" date)
4701                   "\"" (if msg-id ")")))))))
4702
4703 (defun message-make-distribution ()
4704   "Make a Distribution header."
4705   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4706     (cond ((functionp message-distribution-function)
4707            (funcall message-distribution-function))
4708           (t orig-distribution))))
4709
4710 (defun message-make-expires ()
4711   "Return an Expires header based on `message-expires'."
4712   (let ((current (current-time))
4713         (future (* 1.0 message-expires 60 60 24)))
4714     ;; Add the future to current.
4715     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4716     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4717     (message-make-date current)))
4718
4719 (defun message-make-path ()
4720   "Return uucp path."
4721   (let ((login-name (user-login-name)))
4722     (cond ((null message-user-path)
4723            (concat (system-name) "!" login-name))
4724           ((stringp message-user-path)
4725            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4726            (concat message-user-path "!" login-name))
4727           (t login-name))))
4728
4729 (defun message-make-from ()
4730   "Make a From header."
4731   (let* ((style message-from-style)
4732          (login (message-make-address))
4733          (fullname
4734           (or (and (boundp 'user-full-name)
4735                    user-full-name)
4736               (user-full-name))))
4737     (when (string= fullname "&")
4738       (setq fullname (user-login-name)))
4739     (with-temp-buffer
4740       (mm-enable-multibyte)
4741       (cond
4742        ((or (null style)
4743             (equal fullname ""))
4744         (insert login))
4745        ((or (eq style 'angles)
4746             (and (not (eq style 'parens))
4747                  ;; Use angles if no quoting is needed, or if parens would
4748                  ;; need quoting too.
4749                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4750                      (let ((tmp (concat fullname nil)))
4751                        (while (string-match "([^()]*)" tmp)
4752                          (aset tmp (match-beginning 0) ?-)
4753                          (aset tmp (1- (match-end 0)) ?-))
4754                        (string-match "[\\()]" tmp)))))
4755         (insert fullname)
4756         (goto-char (point-min))
4757         ;; Look for a character that cannot appear unquoted
4758         ;; according to RFC 822.
4759         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
4760           ;; Quote fullname, escaping specials.
4761           (goto-char (point-min))
4762           (insert "\"")
4763           (while (re-search-forward "[\"\\]" nil 1)
4764             (replace-match "\\\\\\&" t))
4765           (insert "\""))
4766         (insert " <" login ">"))
4767        (t                               ; 'parens or default
4768         (insert login " (")
4769         (let ((fullname-start (point)))
4770           (insert fullname)
4771           (goto-char fullname-start)
4772           ;; RFC 822 says \ and nonmatching parentheses
4773           ;; must be escaped in comments.
4774           ;; Escape every instance of ()\ ...
4775           (while (re-search-forward "[()\\]" nil 1)
4776             (replace-match "\\\\\\&" t))
4777           ;; ... then undo escaping of matching parentheses,
4778           ;; including matching nested parentheses.
4779           (goto-char fullname-start)
4780           (while (re-search-forward
4781                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4782                   nil 1)
4783             (replace-match "\\1(\\3)" t)
4784             (goto-char fullname-start)))
4785         (insert ")")))
4786       (buffer-string))))
4787
4788 (defun message-make-sender ()
4789   "Return the \"real\" user address.
4790 This function tries to ignore all user modifications, and
4791 give as trustworthy answer as possible."
4792   (concat (user-login-name) "@" (system-name)))
4793
4794 (defun message-make-address ()
4795   "Make the address of the user."
4796   (or (message-user-mail-address)
4797       (concat (user-login-name) "@" (message-make-domain))))
4798
4799 (defun message-user-mail-address ()
4800   "Return the pertinent part of `user-mail-address'."
4801   (when (and user-mail-address
4802              (string-match "@.*\\." user-mail-address))
4803     (if (string-match " " user-mail-address)
4804         (nth 1 (mail-extract-address-components user-mail-address))
4805       user-mail-address)))
4806
4807 (defun message-sendmail-envelope-from ()
4808   "Return the envelope from."
4809   (cond ((eq message-sendmail-envelope-from 'header)
4810          (nth 1 (mail-extract-address-components
4811                  (message-fetch-field "from"))))
4812         ((stringp message-sendmail-envelope-from)
4813          message-sendmail-envelope-from)
4814         (t
4815          (message-make-address))))
4816
4817 (defun message-make-fqdn ()
4818   "Return user's fully qualified domain name."
4819   (let* ((system-name (system-name))
4820          (user-mail (message-user-mail-address))
4821          (user-domain
4822           (if (and user-mail
4823                    (string-match "@\\(.*\\)\\'" user-mail))
4824               (match-string 1 user-mail)))
4825          (case-fold-search t))
4826     (cond
4827      ((and message-user-fqdn
4828            (stringp message-user-fqdn)
4829            (string-match message-valid-fqdn-regexp message-user-fqdn)
4830            (not (string-match message-bogus-system-names message-user-fqdn)))
4831       message-user-fqdn)
4832      ;; `message-user-fqdn' seems to be valid
4833      ((and (string-match message-valid-fqdn-regexp system-name)
4834            (not (string-match message-bogus-system-names system-name)))
4835       ;; `system-name' returned the right result.
4836       system-name)
4837      ;; Try `mail-host-address'.
4838      ((and (boundp 'mail-host-address)
4839            (stringp mail-host-address)
4840            (string-match message-valid-fqdn-regexp mail-host-address)
4841            (not (string-match message-bogus-system-names mail-host-address)))
4842       mail-host-address)
4843      ;; We try `user-mail-address' as a backup.
4844      ((and user-domain
4845            (stringp user-domain)
4846            (string-match message-valid-fqdn-regexp user-domain)
4847            (not (string-match message-bogus-system-names user-domain)))
4848       user-domain)
4849      ;; Default to this bogus thing.
4850      (t
4851       (concat system-name
4852               ".i-did-not-set--mail-host-address--so-tickle-me")))))
4853
4854 (defun message-make-host-name ()
4855   "Return the name of the host."
4856   (let ((fqdn (message-make-fqdn)))
4857     (string-match "^[^.]+\\." fqdn)
4858     (substring fqdn 0 (1- (match-end 0)))))
4859
4860 (defun message-make-domain ()
4861   "Return the domain name."
4862   (or mail-host-address
4863       (message-make-fqdn)))
4864
4865 (defun message-to-list-only ()
4866   "Send a message to the list only.
4867 Remove all addresses but the list address from To and Cc headers."
4868   (interactive)
4869   (let ((listaddr (message-make-mail-followup-to t)))
4870     (when listaddr
4871       (save-excursion
4872         (message-remove-header "to")
4873         (message-remove-header "cc")
4874         (message-position-on-field "To" "X-Draft-From")
4875         (insert listaddr)))))
4876
4877 (defun message-make-mail-followup-to (&optional only-show-subscribed)
4878   "Return the Mail-Followup-To header.
4879 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
4880 subscribed address (and not the additional To and Cc header contents)."
4881   (let* ((case-fold-search t)
4882          (to (message-fetch-field "To"))
4883          (cc (message-fetch-field "cc"))
4884          (msg-recipients (concat to (and to cc ", ") cc))
4885          (recipients
4886           (mapcar 'mail-strip-quoted-names
4887                   (message-tokenize-header msg-recipients)))
4888          (file-regexps
4889           (if message-subscribed-address-file
4890               (let (begin end item re)
4891                 (save-excursion
4892                   (with-temp-buffer
4893                     (insert-file-contents message-subscribed-address-file)
4894                     (while (not (eobp))
4895                       (setq begin (point))
4896                       (forward-line 1)
4897                       (setq end (point))
4898                       (if (bolp) (setq end (1- end)))
4899                       (setq item (regexp-quote (buffer-substring begin end)))
4900                       (if re (setq re (concat re "\\|" item))
4901                         (setq re (concat "\\`\\(" item))))
4902                     (and re (list (concat re "\\)\\'"))))))))
4903          (mft-regexps (apply 'append message-subscribed-regexps
4904                              (mapcar 'regexp-quote
4905                                      message-subscribed-addresses)
4906                              file-regexps
4907                              (mapcar 'funcall
4908                                      message-subscribed-address-functions))))
4909     (save-match-data
4910       (let ((subscribed-lists nil)
4911             (list
4912              (loop for recipient in recipients
4913                when (loop for regexp in mft-regexps
4914                       when (string-match regexp recipient) return t)
4915                return recipient)))
4916         (when list
4917           (if only-show-subscribed
4918               list
4919             msg-recipients))))))
4920
4921 (defun message-idna-to-ascii-rhs-1 (header)
4922   "Interactively potentially IDNA encode domain names in HEADER."
4923   (let ((field (message-fetch-field header))
4924         rhs ace  address)
4925     (when field
4926       (dolist (address (mail-header-parse-addresses field))
4927         (setq address (car address)
4928               rhs (downcase (cadr (split-string address "@")))
4929               ace (downcase (idna-to-ascii rhs)))
4930         (when (and (not (equal rhs ace))
4931                    (or (not (eq message-use-idna 'ask))
4932                        (y-or-n-p (format "Replace %s with %s? " rhs ace))))
4933           (goto-char (point-min))
4934           (while (re-search-forward (concat "^" header ":") nil t)
4935             (message-narrow-to-field)
4936             (while (search-forward (concat "@" rhs) nil t)
4937               (replace-match (concat "@" ace) t t))
4938             (goto-char (point-max))
4939             (widen)))))))
4940
4941 (defun message-idna-to-ascii-rhs ()
4942   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
4943 See `message-idna-encode'."
4944   (interactive)
4945   (when message-use-idna
4946     (save-excursion
4947       (save-restriction
4948         (message-narrow-to-head)
4949         (message-idna-to-ascii-rhs-1 "From")
4950         (message-idna-to-ascii-rhs-1 "To")
4951         (message-idna-to-ascii-rhs-1 "Cc")))))
4952
4953 (defun message-generate-headers (headers)
4954   "Prepare article HEADERS.
4955 Headers already prepared in the buffer are not modified."
4956   (setq headers (append headers message-required-headers))
4957   (save-restriction
4958     (message-narrow-to-headers)
4959     (let* ((Date (message-make-date))
4960            (Message-ID (message-make-message-id))
4961            (Organization (message-make-organization))
4962            (From (message-make-from))
4963            (Path (message-make-path))
4964            (Subject nil)
4965            (Newsgroups nil)
4966            (In-Reply-To (message-make-in-reply-to))
4967            (References (message-make-references))
4968            (To nil)
4969            (Distribution (message-make-distribution))
4970            (Lines (message-make-lines))
4971            (User-Agent message-newsreader)
4972            (Expires (message-make-expires))
4973            (case-fold-search t)
4974            (optionalp nil)
4975            header value elem header-string)
4976       ;; First we remove any old generated headers.
4977       (let ((headers message-deletable-headers))
4978         (unless (buffer-modified-p)
4979           (setq headers (delq 'Message-ID (copy-sequence headers))))
4980         (while headers
4981           (goto-char (point-min))
4982           (and (re-search-forward
4983                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4984                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4985                (message-delete-line))
4986           (pop headers)))
4987       ;; Go through all the required headers and see if they are in the
4988       ;; articles already.  If they are not, or are empty, they are
4989       ;; inserted automatically - except for Subject, Newsgroups and
4990       ;; Distribution.
4991       (while headers
4992         (goto-char (point-min))
4993         (setq elem (pop headers))
4994         (if (consp elem)
4995             (if (eq (car elem) 'optional)
4996                 (setq header (cdr elem)
4997                       optionalp t)
4998               (setq header (car elem)))
4999           (setq header elem))
5000         (setq header-string  (if (stringp header)
5001                                  header
5002                                (symbol-name header)))
5003         (when (or (not (re-search-forward
5004                         (concat "^"
5005                                 (regexp-quote (downcase header-string))
5006                                 ":")
5007                         nil t))
5008                   (progn
5009                     ;; The header was found.  We insert a space after the
5010                     ;; colon, if there is none.
5011                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5012                     ;; Find out whether the header is empty.
5013                     (looking-at "[ \t]*\n[^ \t]")))
5014           ;; So we find out what value we should insert.
5015           (setq value
5016                 (cond
5017                  ((and (consp elem)
5018                        (eq (car elem) 'optional)
5019                        (not (member header-string message-inserted-headers)))
5020                   ;; This is an optional header.  If the cdr of this
5021                   ;; is something that is nil, then we do not insert
5022                   ;; this header.
5023                   (setq header (cdr elem))
5024                   (or (and (functionp (cdr elem))
5025                            (funcall (cdr elem)))
5026                       (and (boundp (cdr elem))
5027                            (symbol-value (cdr elem)))))
5028                  ((consp elem)
5029                   ;; The element is a cons.  Either the cdr is a
5030                   ;; string to be inserted verbatim, or it is a
5031                   ;; function, and we insert the value returned from
5032                   ;; this function.
5033                   (or (and (stringp (cdr elem))
5034                            (cdr elem))
5035                       (and (functionp (cdr elem))
5036                            (funcall (cdr elem)))))
5037                  ((and (boundp header)
5038                        (symbol-value header))
5039                   ;; The element is a symbol.  We insert the value
5040                   ;; of this symbol, if any.
5041                   (symbol-value header))
5042                  ((not (message-check-element header))
5043                   ;; We couldn't generate a value for this header,
5044                   ;; so we just ask the user.
5045                   (read-from-minibuffer
5046                    (format "Empty header for %s; enter value: " header)))))
5047           ;; Finally insert the header.
5048           (when (and value
5049                      (not (equal value "")))
5050             (save-excursion
5051               (if (bolp)
5052                   (progn
5053                     ;; This header didn't exist, so we insert it.
5054                     (goto-char (point-max))
5055                     (let ((formatter
5056                            (cdr (assq header message-header-format-alist))))
5057                       (if formatter
5058                           (funcall formatter header value)
5059                         (insert header-string ": " value))
5060                       (goto-char (message-fill-field))
5061                       ;; We check whether the value was ended by a
5062                       ;; newline.  If not, we insert one.
5063                       (unless (bolp)
5064                         (insert "\n"))
5065                       (forward-line -1)))
5066                 ;; The value of this header was empty, so we clear
5067                 ;; totally and insert the new value.
5068                 (delete-region (point) (point-at-eol))
5069                 ;; If the header is optional, and the header was
5070                 ;; empty, we con't insert it anyway.
5071                 (unless optionalp
5072                   (push header-string message-inserted-headers)
5073                   (insert value)
5074                   (message-fill-field)))
5075               ;; Add the deletable property to the headers that require it.
5076               (and (memq header message-deletable-headers)
5077                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5078                    (add-text-properties
5079                     (point) (match-end 0)
5080                     '(message-deletable t face italic) (current-buffer)))))))
5081       ;; Insert new Sender if the From is strange.
5082       (let ((from (message-fetch-field "from"))
5083             (sender (message-fetch-field "sender"))
5084             (secure-sender (message-make-sender)))
5085         (when (and from
5086                    (not (message-check-element 'sender))
5087                    (not (string=
5088                          (downcase
5089                           (cadr (mail-extract-address-components from)))
5090                          (downcase secure-sender)))
5091                    (or (null sender)
5092                        (not
5093                         (string=
5094                          (downcase
5095                           (cadr (mail-extract-address-components sender)))
5096                          (downcase secure-sender)))))
5097           (goto-char (point-min))
5098           ;; Rename any old Sender headers to Original-Sender.
5099           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5100             (beginning-of-line)
5101             (insert "Original-")
5102             (beginning-of-line))
5103           (when (or (message-news-p)
5104                     (string-match "@.+\\.." secure-sender))
5105             (insert "Sender: " secure-sender "\n"))))
5106       ;; Check for IDNA
5107       (message-idna-to-ascii-rhs))))
5108
5109 (defun message-insert-courtesy-copy ()
5110   "Insert a courtesy message in mail copies of combined messages."
5111   (let (newsgroups)
5112     (save-excursion
5113       (save-restriction
5114         (message-narrow-to-headers)
5115         (when (setq newsgroups (message-fetch-field "newsgroups"))
5116           (goto-char (point-max))
5117           (insert "Posted-To: " newsgroups "\n")))
5118       (forward-line 1)
5119       (when message-courtesy-message
5120         (cond
5121          ((string-match "%s" message-courtesy-message)
5122           (insert (format message-courtesy-message newsgroups)))
5123          (t
5124           (insert message-courtesy-message)))))))
5125
5126 ;;;
5127 ;;; Setting up a message buffer
5128 ;;;
5129
5130 (defun message-skip-to-next-address ()
5131   (let ((end (save-excursion
5132                (message-next-header)
5133                (point)))
5134         quoted char)
5135     (when (looking-at ",")
5136       (forward-char 1))
5137     (while (and (not (= (point) end))
5138                 (or (not (eq char ?,))
5139                     quoted))
5140       (skip-chars-forward "^,\"" (point-max))
5141       (when (eq (setq char (following-char)) ?\")
5142         (setq quoted (not quoted)))
5143       (unless (= (point) end)
5144         (forward-char 1)))
5145     (skip-chars-forward " \t\n")))
5146
5147 (defun message-fill-address (header value)
5148   (insert (capitalize (symbol-name header))
5149           ": "
5150           (if (consp value) (car value) value)
5151           "\n")
5152   (message-fill-field-address))
5153
5154 (defun message-split-line ()
5155   "Split current line, moving portion beyond point vertically down.
5156 If the current line has `message-yank-prefix', insert it on the new line."
5157   (interactive "*")
5158   (condition-case nil
5159       (split-line message-yank-prefix) ;; Emacs 21.3.50+ supports arg.
5160     (error
5161      (split-line))))
5162
5163 (defun message-insert-header (header value)
5164   (insert (capitalize (symbol-name header))
5165           ": "
5166           (if (consp value) (car value) value)))
5167
5168 (defun message-field-name ()
5169   (save-excursion
5170     (goto-char (point-min))
5171     (when (looking-at "\\([^:]+\\):")
5172       (intern (capitalize (match-string 1))))))
5173
5174 (defun message-fill-field ()
5175   (save-excursion
5176     (save-restriction
5177       (message-narrow-to-field)
5178       (let ((field-name (message-field-name)))
5179         (funcall (or (cadr (assq field-name message-field-fillers))
5180                      'message-fill-field-general)))
5181       (point-max))))
5182
5183 (defun message-fill-field-address ()
5184   (while (not (eobp))
5185     (message-skip-to-next-address)
5186     (let (last)
5187       (if (and (> (current-column) 78)
5188                last)
5189           (progn
5190             (save-excursion
5191               (goto-char last)
5192               (insert "\n\t"))
5193             (setq last (1+ (point))))
5194         (setq last (1+ (point)))))))
5195   
5196 (defun message-fill-field-general ()
5197   (let ((begin (point))
5198         (fill-column 78)
5199         (fill-prefix "\t"))
5200     (while (and (search-forward "\n" nil t)
5201                 (not (eobp)))
5202       (replace-match " " t t))
5203     (fill-region-as-paragraph begin (point-max))
5204     ;; Tapdance around looong Message-IDs.
5205     (forward-line -1)
5206     (when (looking-at "[ \t]*$")
5207       (message-delete-line))
5208     (goto-char begin)
5209     (re-search-forward ":" nil t)
5210     (when (looking-at "\n[ \t]+")
5211       (replace-match " " t t))
5212     (goto-char (point-max))))
5213
5214 (defun message-shorten-1 (list cut surplus)
5215   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5216   (setcdr (nthcdr (- cut 2) list)
5217           (nthcdr (+ (- cut 2) surplus 1) list)))
5218
5219 (defun message-shorten-references (header references)
5220   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5221 When sending via news, also check that the REFERENCES are less
5222 than 988 characters long, and if they are not, trim them until
5223 they are."
5224   (let ((maxcount 21)
5225         (count 0)
5226         (cut 2)
5227         refs)
5228     (with-temp-buffer
5229       (insert references)
5230       (goto-char (point-min))
5231       ;; Cons a list of valid references.
5232       (while (re-search-forward "<[^>]+>" nil t)
5233         (push (match-string 0) refs))
5234       (setq refs (nreverse refs)
5235             count (length refs)))
5236
5237     ;; If the list has more than MAXCOUNT elements, trim it by
5238     ;; removing the CUTth element and the required number of
5239     ;; elements that follow.
5240     (when (> count maxcount)
5241       (let ((surplus (- count maxcount)))
5242         (message-shorten-1 refs cut surplus)
5243         (decf count surplus)))
5244
5245     ;; When sending via news, make sure the total folded length will
5246     ;; be less than 998 characters.  This is to cater to broken INN
5247     ;; 2.3 which counts the total number of characters in a header
5248     ;; rather than the physical line length of each line, as it shuld.
5249     ;;
5250     ;; This hack should be removed when it's believed than INN 2.3 is
5251     ;; no longer widely used.
5252     ;;
5253     ;; At this point the headers have not been generated, thus we use
5254     ;; message-this-is-news directly.
5255     (when message-this-is-news
5256       (while (< 998
5257                 (with-temp-buffer
5258                   (message-insert-header
5259                    header (mapconcat #'identity refs " "))
5260                   (buffer-size)))
5261         (message-shorten-1 refs cut 1)))
5262     ;; Finally, collect the references back into a string and insert
5263     ;; it into the buffer.
5264     (message-insert-header header (mapconcat #'identity refs " "))))
5265
5266 (defun message-position-point ()
5267   "Move point to where the user probably wants to find it."
5268   (message-narrow-to-headers)
5269   (cond
5270    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5271     (search-backward ":" )
5272     (widen)
5273     (forward-char 1)
5274     (if (eq (char-after) ? )
5275         (forward-char 1)
5276       (insert " ")))
5277    (t
5278     (goto-char (point-max))
5279     (widen)
5280     (forward-line 1)
5281     (unless (looking-at "$")
5282       (forward-line 2)))
5283    (sit-for 0)))
5284
5285 (defcustom message-beginning-of-line t
5286   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5287  goes to beginning of header values."
5288   :group 'message-buffers
5289   :link '(custom-manual "(message)Movement")
5290   :type 'boolean)
5291
5292 (defun message-beginning-of-line (&optional n)
5293   "Move point to beginning of header value or to beginning of line.
5294 The prefix argument N is passed directly to `beginning-of-line'.
5295
5296 This command is identical to `beginning-of-line' if point is
5297 outside the message header or if the option `message-beginning-of-line'
5298 is nil.
5299
5300 If point is in the message header and on a (non-continued) header
5301 line, move point to the beginning of the header value.  If point
5302 is already there, move point to beginning of line.  Therefore,
5303 repeated calls will toggle point between beginning of field and
5304 beginning of line."
5305   (interactive "p")
5306   (let ((zrs 'zmacs-region-stays))
5307     (when (and (interactive-p) (boundp zrs))
5308       (set zrs t)))
5309   (if (and message-beginning-of-line
5310            (message-point-in-header-p))
5311       (let* ((here (point))
5312              (bol (progn (beginning-of-line n) (point)))
5313              (eol (point-at-eol))
5314              (eoh (re-search-forward ": *" eol t)))
5315         (if (or (not eoh) (equal here eoh))
5316             (goto-char bol)
5317           (goto-char eoh)))
5318     (beginning-of-line n)))
5319
5320 (defun message-buffer-name (type &optional to group)
5321   "Return a new (unique) buffer name based on TYPE and TO."
5322   (cond
5323    ;; Generate a new buffer name The Message Way.
5324    ((eq message-generate-new-buffers 'unique)
5325     (generate-new-buffer-name
5326      (concat "*" type
5327              (if to
5328                  (concat " to "
5329                          (or (car (mail-extract-address-components to))
5330                              to) "")
5331                "")
5332              (if (and group (not (string= group ""))) (concat " on " group) "")
5333              "*")))
5334    ;; Check whether `message-generate-new-buffers' is a function,
5335    ;; and if so, call it.
5336    ((functionp message-generate-new-buffers)
5337     (funcall message-generate-new-buffers type to group))
5338    ((eq message-generate-new-buffers 'unsent)
5339     (generate-new-buffer-name
5340      (concat "*unsent " type
5341              (if to
5342                  (concat " to "
5343                          (or (car (mail-extract-address-components to))
5344                              to) "")
5345                "")
5346              (if (and group (not (string= group ""))) (concat " on " group) "")
5347              "*")))
5348    ;; Use standard name.
5349    (t
5350     (format "*%s message*" type))))
5351
5352 (defun message-pop-to-buffer (name)
5353   "Pop to buffer NAME, and warn if it already exists and is modified."
5354   (let ((buffer (get-buffer name)))
5355     (if (and buffer
5356              (buffer-name buffer))
5357         (progn
5358           (set-buffer (pop-to-buffer buffer))
5359           (when (and (buffer-modified-p)
5360                      (not (y-or-n-p
5361                            "Message already being composed; erase? ")))
5362             (error "Message being composed")))
5363       (set-buffer (pop-to-buffer name)))
5364     (erase-buffer)
5365     (message-mode)))
5366
5367 (defun message-do-send-housekeeping ()
5368   "Kill old message buffers."
5369   ;; We might have sent this buffer already.  Delete it from the
5370   ;; list of buffers.
5371   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5372   (while (and message-max-buffers
5373               message-buffer-list
5374               (>= (length message-buffer-list) message-max-buffers))
5375     ;; Kill the oldest buffer -- unless it has been changed.
5376     (let ((buffer (pop message-buffer-list)))
5377       (when (and (buffer-name buffer)
5378                  (not (buffer-modified-p buffer)))
5379         (kill-buffer buffer))))
5380   ;; Rename the buffer.
5381   (if message-send-rename-function
5382       (funcall message-send-rename-function)
5383     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5384     (when (string-match
5385            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5386            (buffer-name))
5387       (let ((name (match-string 2 (buffer-name)))
5388             to group)
5389         (if (not (or (null name)
5390                      (string-equal name "mail")
5391                      (string-equal name "posting")))
5392             (setq name (concat "*sent " name "*"))
5393           (message-narrow-to-headers)
5394           (setq to (message-fetch-field "to"))
5395           (setq group (message-fetch-field "newsgroups"))
5396           (widen)
5397           (setq name
5398                 (cond
5399                  (to (concat "*sent mail to "
5400                              (or (car (mail-extract-address-components to))
5401                                  to) "*"))
5402                  ((and group (not (string= group "")))
5403                   (concat "*sent posting on " group "*"))
5404                  (t "*sent mail*"))))
5405         (unless (string-equal name (buffer-name))
5406           (rename-buffer name t)))))
5407   ;; Push the current buffer onto the list.
5408   (when message-max-buffers
5409     (setq message-buffer-list
5410           (nconc message-buffer-list (list (current-buffer))))))
5411
5412 (defun message-mail-user-agent ()
5413   (let ((mua (cond
5414               ((not message-mail-user-agent) nil)
5415               ((eq message-mail-user-agent t) mail-user-agent)
5416               (t message-mail-user-agent))))
5417     (if (memq mua '(message-user-agent gnus-user-agent))
5418         nil
5419       mua)))
5420
5421 (defun message-setup (headers &optional replybuffer actions switch-function)
5422   (let ((mua (message-mail-user-agent))
5423         subject to field yank-action)
5424     (if (not (and message-this-is-mail mua))
5425         (message-setup-1 headers replybuffer actions)
5426       (if replybuffer
5427           (setq yank-action (list 'insert-buffer replybuffer)))
5428       (setq headers (copy-sequence headers))
5429       (setq field (assq 'Subject headers))
5430       (when field
5431         (setq subject (cdr field))
5432         (setq headers (delq field headers)))
5433       (setq field (assq 'To headers))
5434       (when field
5435         (setq to (cdr field))
5436         (setq headers (delq field headers)))
5437       (let ((mail-user-agent mua))
5438         (compose-mail to subject
5439                       (mapcar (lambda (item)
5440                                 (cons
5441                                  (format "%s" (car item))
5442                                  (cdr item)))
5443                               headers)
5444                       nil switch-function yank-action actions)))))
5445
5446 (defun message-headers-to-generate (headers included-headers excluded-headers)
5447   "Return a list that includes all headers from HEADERS.
5448 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5449 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5450 are not included."
5451   (let ((result nil)
5452         header-name)
5453     (dolist (header headers)
5454       (setq header-name (cond
5455                          ((and (consp header)
5456                                (eq (car header) 'optional))
5457                           ;; On the form (optional . Header)
5458                           (cdr header))
5459                          ((consp header)
5460                           ;; On the form (Header . function)
5461                           (car header))
5462                          (t
5463                           ;; Just a Header.
5464                           header)))
5465       (when (and (not (memq header-name excluded-headers))
5466                  (or (eq included-headers t)
5467                      (memq header-name included-headers)))
5468         (push header result)))
5469     (nreverse result)))
5470
5471 (defun message-setup-1 (headers &optional replybuffer actions)
5472   (dolist (action actions)
5473     (condition-case nil
5474         (add-to-list 'message-send-actions
5475                      `(apply ',(car action) ',(cdr action)))))
5476   (setq message-reply-buffer replybuffer)
5477   (goto-char (point-min))
5478   ;; Insert all the headers.
5479   (mail-header-format
5480    (let ((h headers)
5481          (alist message-header-format-alist))
5482      (while h
5483        (unless (assq (caar h) message-header-format-alist)
5484          (push (list (caar h)) alist))
5485        (pop h))
5486      alist)
5487    headers)
5488   (delete-region (point) (progn (forward-line -1) (point)))
5489   (when message-default-headers
5490     (insert message-default-headers)
5491     (or (bolp) (insert ?\n)))
5492   (insert mail-header-separator "\n")
5493   (forward-line -1)
5494   (when (message-news-p)
5495     (when message-default-news-headers
5496       (insert message-default-news-headers)
5497       (or (bolp) (insert ?\n)))
5498     (when message-generate-headers-first
5499       (message-generate-headers
5500        (message-headers-to-generate
5501         (append message-required-news-headers
5502                 message-required-headers)
5503         message-generate-headers-first
5504         '(Lines Subject)))))
5505   (when (message-mail-p)
5506     (when message-default-mail-headers
5507       (insert message-default-mail-headers)
5508       (or (bolp) (insert ?\n)))
5509     (save-restriction
5510       (message-narrow-to-headers)
5511       (if message-alternative-emails
5512           (message-use-alternative-email-as-from)))
5513     (when message-generate-headers-first
5514       (message-generate-headers
5515        (message-headers-to-generate
5516         (append message-required-mail-headers
5517                 message-required-headers)
5518         message-generate-headers-first
5519         '(Lines Subject)))))
5520   (run-hooks 'message-signature-setup-hook)
5521   (message-insert-signature)
5522   (save-restriction
5523     (message-narrow-to-headers)
5524     (run-hooks 'message-header-setup-hook))
5525   (set-buffer-modified-p nil)
5526   (setq buffer-undo-list nil)
5527   (run-hooks 'message-setup-hook)
5528   (message-position-point)
5529   (undo-boundary))
5530
5531 (defun message-set-auto-save-file-name ()
5532   "Associate the message buffer with a file in the drafts directory."
5533   (when message-auto-save-directory
5534     (unless (file-directory-p
5535              (directory-file-name message-auto-save-directory))
5536       (make-directory message-auto-save-directory t))
5537     (if (gnus-alive-p)
5538         (setq message-draft-article
5539               (nndraft-request-associate-buffer "drafts"))
5540       (setq buffer-file-name (expand-file-name
5541                               (if (memq system-type
5542                                         '(ms-dos ms-windows windows-nt
5543                                                  cygwin cygwin32 win32 w32
5544                                                  mswindows))
5545                                   "message"
5546                                 "*message*")
5547                               message-auto-save-directory))
5548       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5549     (clear-visited-file-modtime)
5550     (setq buffer-file-coding-system message-draft-coding-system)))
5551
5552 (defun message-disassociate-draft ()
5553   "Disassociate the message buffer from the drafts directory."
5554   (when message-draft-article
5555     (nndraft-request-expire-articles
5556      (list message-draft-article) "drafts" nil t)))
5557
5558 (defun message-insert-headers ()
5559   "Generate the headers for the article."
5560   (interactive)
5561   (save-excursion
5562     (save-restriction
5563       (message-narrow-to-headers)
5564       (when (message-news-p)
5565         (message-generate-headers
5566          (delq 'Lines
5567                (delq 'Subject
5568                      (copy-sequence message-required-news-headers)))))
5569       (when (message-mail-p)
5570         (message-generate-headers
5571          (delq 'Lines
5572                (delq 'Subject
5573                      (copy-sequence message-required-mail-headers))))))))
5574
5575 \f
5576
5577 ;;;
5578 ;;; Commands for interfacing with message
5579 ;;;
5580
5581 ;;;###autoload
5582 (defun message-mail (&optional to subject
5583                                other-headers continue switch-function
5584                                yank-action send-actions)
5585   "Start editing a mail message to be sent.
5586 OTHER-HEADERS is an alist of header/value pairs."
5587   (interactive)
5588   (let ((message-this-is-mail t) replybuffer)
5589     (unless (message-mail-user-agent)
5590       (message-pop-to-buffer (message-buffer-name "mail" to)))
5591     ;; FIXME: message-mail should do something if YANK-ACTION is not
5592     ;; insert-buffer.
5593     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5594          (setq replybuffer (nth 1 yank-action)))
5595     (message-setup
5596      (nconc
5597       `((To . ,(or to "")) (Subject . ,(or subject "")))
5598       (when other-headers other-headers))
5599      replybuffer send-actions)
5600     ;; FIXME: Should return nil if failure.
5601     t))
5602
5603 ;;;###autoload
5604 (defun message-news (&optional newsgroups subject)
5605   "Start editing a news article to be sent."
5606   (interactive)
5607   (let ((message-this-is-news t))
5608     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5609     (message-setup `((Newsgroups . ,(or newsgroups ""))
5610                      (Subject . ,(or subject ""))))))
5611
5612 (defun message-get-reply-headers (wide &optional to-address address-headers)
5613   (let (follow-to mct never-mct to cc author mft recipients)
5614     ;; Find all relevant headers we need.
5615     (save-restriction
5616       (message-narrow-to-headers-or-head)
5617       ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
5618       ;; message-header-synonyms.
5619       (setq to (or (message-fetch-field "to")
5620                    (and (loop for synonym in message-header-synonyms
5621                               when (memq 'Original-To synonym)
5622                               return t)
5623                         (message-fetch-field "original-to")))
5624             cc (message-fetch-field "cc")
5625             mct (message-fetch-field "mail-copies-to")
5626             author (or (message-fetch-field "mail-reply-to")
5627                        (message-fetch-field "reply-to")
5628                        (message-fetch-field "from")
5629                        "")
5630             mft (and message-use-mail-followup-to
5631                      (message-fetch-field "mail-followup-to"))))
5632
5633     ;; Handle special values of Mail-Copies-To.
5634     (when mct
5635       (cond ((or (equal (downcase mct) "never")
5636                  (equal (downcase mct) "nobody"))
5637              (setq never-mct t)
5638              (setq mct nil))
5639             ((or (equal (downcase mct) "always")
5640                  (equal (downcase mct) "poster"))
5641              (setq mct author))))
5642
5643     (save-match-data
5644       ;; Build (textual) list of new recipient addresses.
5645       (cond
5646        ((not wide)
5647         (setq recipients (concat ", " author)))
5648        (address-headers
5649         (dolist (header address-headers)
5650           (let ((value (message-fetch-field header)))
5651             (when value
5652               (setq recipients (concat recipients ", " value))))))
5653        ((and mft
5654              (string-match "[^ \t,]" mft)
5655              (or (not (eq message-use-mail-followup-to 'ask))
5656                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5657 You should normally obey the Mail-Followup-To: header.  In this
5658 article, it has the value of
5659
5660 " mft "
5661
5662 which directs your response to " (if (string-match "," mft)
5663                                      "the specified addresses"
5664                                    "that address only") ".
5665
5666 Most commonly, Mail-Followup-To is used by a mailing list poster to
5667 express that responses should be sent to just the list, and not the
5668 poster as well.
5669
5670 If a message is posted to several mailing lists, Mail-Followup-To may
5671 also be used to direct the following discussion to one list only,
5672 because discussions that are spread over several lists tend to be
5673 fragmented and very difficult to follow.
5674
5675 Also, some source/announcement lists are not intended for discussion;
5676 responses here are directed to other addresses.")))
5677         (setq recipients (concat ", " mft)))
5678        (to-address
5679         (setq recipients (concat ", " to-address))
5680         ;; If the author explicitly asked for a copy, we don't deny it to them.
5681         (if mct (setq recipients (concat recipients ", " mct))))
5682        (t
5683         (setq recipients (if never-mct "" (concat ", " author)))
5684         (if to  (setq recipients (concat recipients ", " to)))
5685         (if cc  (setq recipients (concat recipients ", " cc)))
5686         (if mct (setq recipients (concat recipients ", " mct)))))
5687       (if (>= (length recipients) 2)
5688           ;; Strip the leading ", ".
5689           (setq recipients (substring recipients 2)))
5690       ;; Squeeze whitespace.
5691       (while (string-match "[ \t][ \t]+" recipients)
5692         (setq recipients (replace-match " " t t recipients)))
5693       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5694       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5695         (setq recipients (rmail-dont-reply-to recipients)))
5696       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5697       (if (string-equal recipients "")
5698           (setq recipients author))
5699       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5700       (setq recipients
5701             (mapcar
5702              (lambda (addr)
5703                (cons (downcase (mail-strip-quoted-names addr)) addr))
5704              (message-tokenize-header recipients)))
5705       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5706       (let ((s recipients))
5707         (while s
5708           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5709
5710       ;; Remove hierarchical lists that are contained within each other,
5711       ;; if message-hierarchical-addresses is defined.
5712       (when message-hierarchical-addresses
5713         (let ((plain-addrs (mapcar 'car recipients))
5714               subaddrs recip)
5715           (while plain-addrs
5716             (setq subaddrs (assoc (car plain-addrs)
5717                                   message-hierarchical-addresses)
5718                   plain-addrs (cdr plain-addrs))
5719             (when subaddrs
5720               (setq subaddrs (cdr subaddrs))
5721               (while subaddrs
5722                 (setq recip (assoc (car subaddrs) recipients)
5723                       subaddrs (cdr subaddrs))
5724                 (if recip
5725                     (setq recipients (delq recip recipients))))))))
5726
5727       ;; Build the header alist.  Allow the user to be asked whether
5728       ;; or not to reply to all recipients in a wide reply.
5729       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5730       (when (and recipients
5731                  (or (not message-wide-reply-confirm-recipients)
5732                      (y-or-n-p "Reply to all recipients? ")))
5733         (setq recipients (mapconcat
5734                           (lambda (addr) (cdr addr)) recipients ", "))
5735         (if (string-match "^ +" recipients)
5736             (setq recipients (substring recipients (match-end 0))))
5737         (push (cons 'Cc recipients) follow-to)))
5738     follow-to))
5739
5740 ;;;###autoload
5741 (defun message-reply (&optional to-address wide)
5742   "Start editing a reply to the article in the current buffer."
5743   (interactive)
5744   (require 'gnus-sum)                   ; for gnus-list-identifiers
5745   (let ((cur (current-buffer))
5746         from subject date reply-to to cc
5747         references message-id follow-to
5748         (inhibit-point-motion-hooks t)
5749         (message-this-is-mail t)
5750         gnus-warning)
5751     (save-restriction
5752       (message-narrow-to-head-1)
5753       ;; Allow customizations to have their say.
5754       (if (not wide)
5755           ;; This is a regular reply.
5756           (when (functionp message-reply-to-function)
5757             (save-excursion
5758               (setq follow-to (funcall message-reply-to-function))))
5759         ;; This is a followup.
5760         (when (functionp message-wide-reply-to-function)
5761           (save-excursion
5762             (setq follow-to
5763                   (funcall message-wide-reply-to-function)))))
5764       (setq message-id (message-fetch-field "message-id" t)
5765             references (message-fetch-field "references")
5766             date (message-fetch-field "date")
5767             from (message-fetch-field "from")
5768             subject (or (message-fetch-field "subject") "none"))
5769       (when gnus-list-identifiers
5770         (setq subject (message-strip-list-identifiers subject)))
5771       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5772       (when message-subject-trailing-was-query
5773         (setq subject (message-strip-subject-trailing-was subject)))
5774
5775       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5776                  (string-match "<[^>]+>" gnus-warning))
5777         (setq message-id (match-string 0 gnus-warning)))
5778
5779       (unless follow-to
5780         (setq follow-to (message-get-reply-headers wide to-address))))
5781
5782     (unless (message-mail-user-agent)
5783       (message-pop-to-buffer
5784        (message-buffer-name
5785         (if wide "wide reply" "reply") from
5786         (if wide to-address nil))))
5787
5788     (setq message-reply-headers
5789           (vector 0 subject from date message-id references 0 0 ""))
5790
5791     (message-setup
5792      `((Subject . ,subject)
5793        ,@follow-to)
5794      cur)))
5795
5796 ;;;###autoload
5797 (defun message-wide-reply (&optional to-address)
5798   "Make a \"wide\" reply to the message in the current buffer."
5799   (interactive)
5800   (message-reply to-address t))
5801
5802 ;;;###autoload
5803 (defun message-followup (&optional to-newsgroups)
5804   "Follow up to the message in the current buffer.
5805 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5806   (interactive)
5807   (require 'gnus-sum)                   ; for gnus-list-identifiers
5808   (let ((cur (current-buffer))
5809         from subject date reply-to mrt mct
5810         references message-id follow-to
5811         (inhibit-point-motion-hooks t)
5812         (message-this-is-news t)
5813         followup-to distribution newsgroups gnus-warning posted-to)
5814     (save-restriction
5815       (narrow-to-region
5816        (goto-char (point-min))
5817        (if (search-forward "\n\n" nil t)
5818            (1- (point))
5819          (point-max)))
5820       (when (functionp message-followup-to-function)
5821         (setq follow-to
5822               (funcall message-followup-to-function)))
5823       (setq from (message-fetch-field "from")
5824             date (message-fetch-field "date")
5825             subject (or (message-fetch-field "subject") "none")
5826             references (message-fetch-field "references")
5827             message-id (message-fetch-field "message-id" t)
5828             followup-to (message-fetch-field "followup-to")
5829             newsgroups (message-fetch-field "newsgroups")
5830             posted-to (message-fetch-field "posted-to")
5831             reply-to (message-fetch-field "reply-to")
5832             mrt (message-fetch-field "mail-reply-to")
5833             distribution (message-fetch-field "distribution")
5834             mct (message-fetch-field "mail-copies-to"))
5835       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5836                  (string-match "<[^>]+>" gnus-warning))
5837         (setq message-id (match-string 0 gnus-warning)))
5838       ;; Remove bogus distribution.
5839       (when (and (stringp distribution)
5840                  (let ((case-fold-search t))
5841                    (string-match "world" distribution)))
5842         (setq distribution nil))
5843       (if gnus-list-identifiers
5844           (setq subject (message-strip-list-identifiers subject)))
5845       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5846       (when message-subject-trailing-was-query
5847         (setq subject (message-strip-subject-trailing-was subject)))
5848       (widen))
5849
5850     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5851
5852     (setq message-reply-headers
5853           (vector 0 subject from date message-id references 0 0 ""))
5854
5855     (message-setup
5856      `((Subject . ,subject)
5857        ,@(cond
5858           (to-newsgroups
5859            (list (cons 'Newsgroups to-newsgroups)))
5860           (follow-to follow-to)
5861           ((and followup-to message-use-followup-to)
5862            (list
5863             (cond
5864              ((equal (downcase followup-to) "poster")
5865               (if (or (eq message-use-followup-to 'use)
5866                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
5867 You should normally obey the Followup-To: header.
5868
5869 `Followup-To: poster' sends your response via e-mail instead of news.
5870
5871 A typical situation where `Followup-To: poster' is used is when the poster
5872 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5873                   (progn
5874                     (setq message-this-is-news nil)
5875                     (cons 'To (or mrt reply-to from "")))
5876                 (cons 'Newsgroups newsgroups)))
5877              (t
5878               (if (or (equal followup-to newsgroups)
5879                       (not (eq message-use-followup-to 'ask))
5880                       (message-y-or-n-p
5881                        (concat "Obey Followup-To: " followup-to "? ") t "\
5882 You should normally obey the Followup-To: header.
5883
5884         `Followup-To: " followup-to "'
5885 directs your response to " (if (string-match "," followup-to)
5886                                "the specified newsgroups"
5887                              "that newsgroup only") ".
5888
5889 If a message is posted to several newsgroups, Followup-To is often
5890 used to direct the following discussion to one newsgroup only,
5891 because discussions that are spread over several newsgroup tend to
5892 be fragmented and very difficult to follow.
5893
5894 Also, some source/announcement newsgroups are not intended for discussion;
5895 responses here are directed to other newsgroups."))
5896                   (cons 'Newsgroups followup-to)
5897                 (cons 'Newsgroups newsgroups))))))
5898           (posted-to
5899            `((Newsgroups . ,posted-to)))
5900           (t
5901            `((Newsgroups . ,newsgroups))))
5902        ,@(and distribution (list (cons 'Distribution distribution)))
5903        ,@(when (and mct
5904                     (not (or (equal (downcase mct) "never")
5905                              (equal (downcase mct) "nobody"))))
5906            (list (cons 'Cc (if (or (equal (downcase mct) "always")
5907                                    (equal (downcase mct) "poster"))
5908                                (or mrt reply-to from "")
5909                              mct)))))
5910
5911      cur)))
5912
5913 (defun message-is-yours-p ()
5914   "Non-nil means current article is yours.
5915 If you have added 'cancel-messages to 'message-shoot-gnksa-feet', all articles
5916 are yours except those that have Cancel-Lock header not belonging to you.
5917 Instead of shooting GNKSA feet, you should modify 'message-alternative-emails'
5918 regexp to match all of yours addresses."
5919   ;; Canlock-logic as suggested by Per Abrahamsen
5920   ;; <abraham@dina.kvl.dk>
5921   ;;
5922   ;; IF article has cancel-lock THEN
5923   ;;   IF we can verify it THEN
5924   ;;     issue cancel
5925   ;;   ELSE
5926   ;;     error: cancellock: article is not yours
5927   ;; ELSE
5928   ;;   Use old rules, comparing sender...
5929   (save-excursion
5930     (save-restriction
5931       (message-narrow-to-head-1)
5932       (if (message-fetch-field "Cancel-Lock")
5933           (if (null (canlock-verify))
5934               t
5935             (error "Failed to verify Cancel-lock: This article is not yours"))
5936         (let (sender from)
5937           (or
5938            (message-gnksa-enable-p 'cancel-messages)
5939            (and (setq sender (message-fetch-field "sender"))
5940                 (string-equal (downcase sender)
5941                               (downcase (message-make-sender))))
5942            ;; Email address in From field equals to our address
5943            (and (setq from (message-fetch-field "from"))
5944                 (string-equal
5945                  (downcase (cadr (mail-extract-address-components from)))
5946                  (downcase (cadr (mail-extract-address-components
5947                                   (message-make-from))))))
5948            ;; Email address in From field matches
5949            ;; 'message-alternative-emails' regexp
5950            (and from
5951                 message-alternative-emails
5952                 (string-match
5953                  message-alternative-emails
5954                  (cadr (mail-extract-address-components from))))))))))
5955
5956 ;;;###autoload
5957 (defun message-cancel-news (&optional arg)
5958   "Cancel an article you posted.
5959 If ARG, allow editing of the cancellation message."
5960   (interactive "P")
5961   (unless (message-news-p)
5962     (error "This is not a news article; canceling is impossible"))
5963   (let (from newsgroups message-id distribution buf)
5964     (save-excursion
5965       ;; Get header info from original article.
5966       (save-restriction
5967         (message-narrow-to-head-1)
5968         (setq from (message-fetch-field "from")
5969               newsgroups (message-fetch-field "newsgroups")
5970               message-id (message-fetch-field "message-id" t)
5971               distribution (message-fetch-field "distribution")))
5972       ;; Make sure that this article was written by the user.
5973       (unless (message-is-yours-p)
5974         (error "This article is not yours"))
5975       (when (yes-or-no-p "Do you really want to cancel this article? ")
5976         ;; Make control message.
5977         (if arg
5978             (message-news)
5979           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5980         (erase-buffer)
5981         (insert "Newsgroups: " newsgroups "\n"
5982                 "From: " from "\n"
5983                 "Subject: cmsg cancel " message-id "\n"
5984                 "Control: cancel " message-id "\n"
5985                 (if distribution
5986                     (concat "Distribution: " distribution "\n")
5987                   "")
5988                 mail-header-separator "\n"
5989                 message-cancel-message)
5990         (run-hooks 'message-cancel-hook)
5991         (unless arg
5992           (message "Canceling your article...")
5993           (if (let ((message-syntax-checks
5994                      'dont-check-for-anything-just-trust-me))
5995                 (funcall message-send-news-function))
5996               (message "Canceling your article...done"))
5997           (kill-buffer buf))))))
5998
5999 ;;;###autoload
6000 (defun message-supersede ()
6001   "Start composing a message to supersede the current message.
6002 This is done simply by taking the old article and adding a Supersedes
6003 header line with the old Message-ID."
6004   (interactive)
6005   (let ((cur (current-buffer)))
6006     ;; Check whether the user owns the article that is to be superseded.
6007     (unless (message-is-yours-p)
6008       (error "This article is not yours"))
6009     ;; Get a normal message buffer.
6010     (message-pop-to-buffer (message-buffer-name "supersede"))
6011     (insert-buffer-substring cur)
6012     (mime-to-mml)
6013     (message-narrow-to-head-1)
6014     ;; Remove unwanted headers.
6015     (when message-ignored-supersedes-headers
6016       (message-remove-header message-ignored-supersedes-headers t))
6017     (goto-char (point-min))
6018     (if (not (re-search-forward "^Message-ID: " nil t))
6019         (error "No Message-ID in this article")
6020       (replace-match "Supersedes: " t t))
6021     (goto-char (point-max))
6022     (insert mail-header-separator)
6023     (widen)
6024     (forward-line 1)))
6025
6026 ;;;###autoload
6027 (defun message-recover ()
6028   "Reread contents of current buffer from its last auto-save file."
6029   (interactive)
6030   (let ((file-name (make-auto-save-file-name)))
6031     (cond ((save-window-excursion
6032              (if (not (eq system-type 'vax-vms))
6033                  (with-output-to-temp-buffer "*Directory*"
6034                    (with-current-buffer standard-output
6035                      (fundamental-mode)) ; for Emacs 20.4+
6036                    (buffer-disable-undo standard-output)
6037                    (let ((default-directory "/"))
6038                      (call-process
6039                       "ls" nil standard-output nil "-l" file-name))))
6040              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6041            (let ((buffer-read-only nil))
6042              (erase-buffer)
6043              (insert-file-contents file-name nil)))
6044           (t (error "message-recover cancelled")))))
6045
6046 ;;; Washing Subject:
6047
6048 (defun message-wash-subject (subject)
6049   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6050 Previous forwarders, replyers, etc. may add it."
6051   (with-temp-buffer
6052     (insert subject)
6053     (goto-char (point-min))
6054     ;; strip Re/Fwd stuff off the beginning
6055     (while (re-search-forward
6056             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6057       (replace-match ""))
6058
6059     ;; and gnus-style forwards [foo@bar.com] subject
6060     (goto-char (point-min))
6061     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6062       (replace-match ""))
6063
6064     ;; and off the end
6065     (goto-char (point-max))
6066     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6067       (replace-match ""))
6068
6069     ;; and finally, any whitespace that was left-over
6070     (goto-char (point-min))
6071     (while (re-search-forward "^[ \t]+" nil t)
6072       (replace-match ""))
6073     (goto-char (point-max))
6074     (while (re-search-backward "[ \t]+$" nil t)
6075       (replace-match ""))
6076
6077     (buffer-string)))
6078
6079 ;;; Forwarding messages.
6080
6081 (defvar message-forward-decoded-p nil
6082   "Non-nil means the original message is decoded.")
6083
6084 (defun message-forward-subject-name-subject (subject)
6085   "Generate a SUBJECT for a forwarded message.
6086 The form is: [Source] Subject, where if the original message was mail,
6087 Source is the name of the sender, and if the original message was
6088 news, Source is the list of newsgroups is was posted to."
6089   (let* ((group (message-fetch-field "newsgroups"))
6090          (from (message-fetch-field "from"))
6091          (prefix
6092           (if group
6093               (gnus-group-decoded-name group)
6094             (or (and from (car (gnus-extract-address-components from)))
6095                 "(nowhere)"))))
6096     (concat "["
6097             (if message-forward-decoded-p
6098                 prefix
6099               (mail-decode-encoded-word-string prefix))
6100             "] " subject)))
6101
6102 (defun message-forward-subject-author-subject (subject)
6103   "Generate a SUBJECT for a forwarded message.
6104 The form is: [Source] Subject, where if the original message was mail,
6105 Source is the sender, and if the original message was news, Source is
6106 the list of newsgroups is was posted to."
6107   (let* ((group (message-fetch-field "newsgroups"))
6108          (prefix
6109           (if group
6110               (gnus-group-decoded-name group)
6111             (or (message-fetch-field "from")
6112                 "(nowhere)"))))
6113     (concat "["
6114             (if message-forward-decoded-p
6115                 prefix
6116               (mail-decode-encoded-word-string prefix))
6117             "] " subject)))
6118
6119 (defun message-forward-subject-fwd (subject)
6120   "Generate a SUBJECT for a forwarded message.
6121 The form is: Fwd: Subject, where Subject is the original subject of
6122 the message."
6123   (if (string-match "^Fwd: " subject)
6124       subject
6125     (concat "Fwd: " subject)))
6126
6127 (defun message-make-forward-subject ()
6128   "Return a Subject header suitable for the message in the current buffer."
6129   (save-excursion
6130     (save-restriction
6131       (message-narrow-to-head-1)
6132       (let ((funcs message-make-forward-subject-function)
6133             (subject (message-fetch-field "Subject")))
6134         (setq subject
6135               (if subject
6136                   (if message-forward-decoded-p
6137                       subject
6138                     (mail-decode-encoded-word-string subject))
6139                 ""))
6140         (if message-wash-forwarded-subjects
6141             (setq subject (message-wash-subject subject)))
6142         ;; Make sure funcs is a list.
6143         (and funcs
6144              (not (listp funcs))
6145              (setq funcs (list funcs)))
6146         ;; Apply funcs in order, passing subject generated by previous
6147         ;; func to the next one.
6148         (while funcs
6149           (when (functionp (car funcs))
6150             (setq subject (funcall (car funcs) subject)))
6151           (setq funcs (cdr funcs)))
6152         subject))))
6153
6154 (eval-when-compile
6155   (defvar gnus-article-decoded-p))
6156
6157
6158 ;;;###autoload
6159 (defun message-forward (&optional news digest)
6160   "Forward the current message via mail.
6161 Optional NEWS will use news to forward instead of mail.
6162 Optional DIGEST will use digest to forward."
6163   (interactive "P")
6164   (let* ((cur (current-buffer))
6165          (message-forward-decoded-p
6166           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
6167               gnus-article-decoded-p ;; In an article buffer.
6168             message-forward-decoded-p))
6169          (subject (message-make-forward-subject)))
6170     (if news
6171         (message-news nil subject)
6172       (message-mail nil subject))
6173     (message-forward-make-body cur digest)))
6174
6175 (defun message-forward-make-body-plain (forward-buffer)
6176   (insert
6177    "\n-------------------- Start of forwarded message --------------------\n")
6178   (let ((b (point)) e)
6179     (insert
6180      (with-temp-buffer
6181        (mm-disable-multibyte)
6182        (insert
6183         (with-current-buffer forward-buffer
6184           (mm-with-unibyte-current-buffer (buffer-string))))
6185        (mm-enable-multibyte)
6186        (mime-to-mml)
6187        (goto-char (point-min))
6188        (when (looking-at "From ")
6189          (replace-match "X-From-Line: "))
6190        (buffer-string)))
6191     (setq e (point))
6192     (insert
6193      "\n-------------------- End of forwarded message --------------------\n")
6194     (when (and (not current-prefix-arg)
6195                message-forward-ignored-headers)
6196       (save-restriction
6197         (narrow-to-region b e)
6198         (goto-char b)
6199         (narrow-to-region (point)
6200                           (or (search-forward "\n\n" nil t) (point)))
6201         (message-remove-header message-forward-ignored-headers t)))))
6202
6203 (defun message-forward-make-body-mime (forward-buffer)
6204   (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
6205   (let ((b (point)) e)
6206     (save-restriction
6207       (narrow-to-region (point) (point))
6208       (mml-insert-buffer forward-buffer)
6209       (goto-char (point-min))
6210       (when (looking-at "From ")
6211         (replace-match "X-From-Line: "))
6212       (goto-char (point-max)))
6213     (setq e (point))
6214     (insert "<#/part>\n")))
6215
6216 (defun message-forward-make-body-mml (forward-buffer)
6217   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
6218   (let ((b (point)) e)
6219     (if (not message-forward-decoded-p)
6220         (insert
6221          (with-temp-buffer
6222            (mm-disable-multibyte)
6223            (insert
6224             (with-current-buffer forward-buffer
6225               (mm-with-unibyte-current-buffer (buffer-string))))
6226            (mm-enable-multibyte)
6227            (mime-to-mml)
6228            (goto-char (point-min))
6229            (when (looking-at "From ")
6230              (replace-match "X-From-Line: "))
6231            (buffer-string)))
6232       (save-restriction
6233         (narrow-to-region (point) (point))
6234         (mml-insert-buffer forward-buffer)
6235         (goto-char (point-min))
6236         (when (looking-at "From ")
6237           (replace-match "X-From-Line: "))
6238         (goto-char (point-max))))
6239     (setq e (point))
6240     (insert "<#/mml>\n")
6241     (when (and (not current-prefix-arg)
6242                message-forward-ignored-headers)
6243       (save-restriction
6244         (narrow-to-region b e)
6245         (goto-char b)
6246         (narrow-to-region (point)
6247                           (or (search-forward "\n\n" nil t) (point)))
6248         (message-remove-header message-forward-ignored-headers t)))))
6249
6250 (defun message-forward-make-body-digest-plain (forward-buffer)
6251   (insert
6252    "\n-------------------- Start of forwarded message --------------------\n")
6253   (let ((b (point)) e)
6254     (mml-insert-buffer forward-buffer)
6255     (setq e (point))
6256     (insert
6257      "\n-------------------- End of forwarded message --------------------\n")))
6258
6259 (defun message-forward-make-body-digest-mime (forward-buffer)
6260   (insert "\n<#multipart type=digest>\n")
6261   (let ((b (point)) e)
6262     (insert-buffer-substring forward-buffer)
6263     (setq e (point))
6264     (insert "<#/multipart>\n")
6265     (save-restriction
6266       (narrow-to-region b e)
6267       (goto-char b)
6268       (narrow-to-region (point)
6269                         (or (search-forward "\n\n" nil t) (point)))
6270       (delete-region (point-min) (point-max)))))
6271
6272 (defun message-forward-make-body-digest (forward-buffer)
6273   (if message-forward-as-mime
6274       (message-forward-make-body-digest-mime forward-buffer)
6275     (message-forward-make-body-digest-plain forward-buffer)))
6276
6277 ;;;###autoload
6278 (defun message-forward-make-body (forward-buffer &optional digest)
6279   ;; Put point where we want it before inserting the forwarded
6280   ;; message.
6281   (if message-forward-before-signature
6282       (message-goto-body)
6283     (goto-char (point-max)))
6284   (if digest
6285       (message-forward-make-body-digest forward-buffer)
6286     (if message-forward-as-mime
6287         (if (and message-forward-show-mml
6288                  (not (and (eq message-forward-show-mml 'best)
6289                            (with-current-buffer forward-buffer
6290                              (goto-char (point-min))
6291                              (re-search-forward
6292                               "Content-Type: *multipart/\\(signed\\|encrypted\\)"
6293                               nil t)))))
6294             (message-forward-make-body-mml forward-buffer)
6295           (message-forward-make-body-mime forward-buffer))
6296       (message-forward-make-body-plain forward-buffer)))
6297   (message-position-point))
6298
6299 ;;;###autoload
6300 (defun message-forward-rmail-make-body (forward-buffer)
6301   (save-window-excursion
6302     (set-buffer forward-buffer)
6303     (if (rmail-msg-is-pruned)
6304         (rmail-msg-restore-non-pruned-header)))
6305   (message-forward-make-body forward-buffer))
6306
6307 (eval-when-compile (defvar rmail-enable-mime-composing))
6308
6309 ;; Fixme: Should have defcustom.
6310 ;;;###autoload
6311 (defun message-insinuate-rmail ()
6312   "Let RMAIL use message to forward."
6313   (interactive)
6314   (setq rmail-enable-mime-composing t)
6315   (setq rmail-insert-mime-forwarded-message-function
6316         'message-forward-rmail-make-body))
6317
6318 ;;;###autoload
6319 (defun message-resend (address)
6320   "Resend the current article to ADDRESS."
6321   (interactive
6322    (list (message-read-from-minibuffer "Resend message to: ")))
6323   (message "Resending message to %s..." address)
6324   (save-excursion
6325     (let ((cur (current-buffer))
6326           beg)
6327       ;; We first set up a normal mail buffer.
6328       (unless (message-mail-user-agent)
6329         (set-buffer (get-buffer-create " *message resend*"))
6330         (erase-buffer))
6331       (let ((message-this-is-mail t)
6332             message-setup-hook)
6333         (message-setup `((To . ,address))))
6334       ;; Insert our usual headers.
6335       (message-generate-headers '(From Date To Message-ID))
6336       (message-narrow-to-headers)
6337       ;; Remove X-Draft-From header etc.
6338       (message-remove-header message-ignored-mail-headers t)
6339       ;; Rename them all to "Resent-*".
6340       (goto-char (point-min))
6341       (while (re-search-forward "^[A-Za-z]" nil t)
6342         (forward-char -1)
6343         (insert "Resent-"))
6344       (widen)
6345       (forward-line)
6346       (delete-region (point) (point-max))
6347       (setq beg (point))
6348       ;; Insert the message to be resent.
6349       (insert-buffer-substring cur)
6350       (goto-char (point-min))
6351       (search-forward "\n\n")
6352       (forward-char -1)
6353       (save-restriction
6354         (narrow-to-region beg (point))
6355         (message-remove-header message-ignored-resent-headers t)
6356         (goto-char (point-max)))
6357       (insert mail-header-separator)
6358       ;; Rename all old ("Also-")Resent headers.
6359       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6360         (beginning-of-line)
6361         (insert "Also-"))
6362       ;; Quote any "From " lines at the beginning.
6363       (goto-char beg)
6364       (when (looking-at "From ")
6365         (replace-match "X-From-Line: "))
6366       ;; Send it.
6367       (let ((message-inhibit-body-encoding t)
6368             message-required-mail-headers
6369             rfc2047-encode-encoded-words)
6370         (message-send-mail))
6371       (kill-buffer (current-buffer)))
6372     (message "Resending message to %s...done" address)))
6373
6374 ;;;###autoload
6375 (defun message-bounce ()
6376   "Re-mail the current message.
6377 This only makes sense if the current message is a bounce message that
6378 contains some mail you have written which has been bounced back to
6379 you."
6380   (interactive)
6381   (let ((handles (mm-dissect-buffer t))
6382         boundary)
6383     (message-pop-to-buffer (message-buffer-name "bounce"))
6384     (if (stringp (car handles))
6385         ;; This is a MIME bounce.
6386         (mm-insert-part (car (last handles)))
6387       ;; This is a non-MIME bounce, so we try to remove things
6388       ;; manually.
6389       (mm-insert-part handles)
6390       (undo-boundary)
6391       (goto-char (point-min))
6392       (re-search-forward "\n\n+" nil t)
6393       (setq boundary (point))
6394       ;; We remove everything before the bounced mail.
6395       (if (or (re-search-forward message-unsent-separator nil t)
6396               (progn
6397                 (search-forward "\n\n" nil 'move)
6398                 (re-search-backward "^Return-Path:.*\n" boundary t)))
6399           (progn
6400             (forward-line 1)
6401             (delete-region (point-min)
6402                            (if (re-search-forward "^[^ \n\t]+:" nil t)
6403                                (match-beginning 0)
6404                              (point))))
6405         (goto-char boundary)
6406         (when (re-search-backward "^.?From .*\n" nil t)
6407           (delete-region (match-beginning 0) (match-end 0)))))
6408     (mm-enable-multibyte)
6409     (save-restriction
6410       (message-narrow-to-head-1)
6411       (message-remove-header message-ignored-bounced-headers t)
6412       (goto-char (point-max))
6413       (insert mail-header-separator))
6414     (message-position-point)))
6415
6416 ;;;
6417 ;;; Interactive entry points for new message buffers.
6418 ;;;
6419
6420 ;;;###autoload
6421 (defun message-mail-other-window (&optional to subject)
6422   "Like `message-mail' command, but display mail buffer in another window."
6423   (interactive)
6424   (unless (message-mail-user-agent)
6425     (let ((pop-up-windows t)
6426           (special-display-buffer-names nil)
6427           (special-display-regexps nil)
6428           (same-window-buffer-names nil)
6429           (same-window-regexps nil))
6430       (message-pop-to-buffer (message-buffer-name "mail" to))))
6431   (let ((message-this-is-mail t))
6432     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6433                    nil nil 'switch-to-buffer-other-window)))
6434
6435 ;;;###autoload
6436 (defun message-mail-other-frame (&optional to subject)
6437   "Like `message-mail' command, but display mail buffer in another frame."
6438   (interactive)
6439   (unless (message-mail-user-agent)
6440     (let ((pop-up-frames t)
6441           (special-display-buffer-names nil)
6442           (special-display-regexps nil)
6443           (same-window-buffer-names nil)
6444           (same-window-regexps nil))
6445       (message-pop-to-buffer (message-buffer-name "mail" to))))
6446   (let ((message-this-is-mail t))
6447     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6448                    nil nil 'switch-to-buffer-other-frame)))
6449
6450 ;;;###autoload
6451 (defun message-news-other-window (&optional newsgroups subject)
6452   "Start editing a news article to be sent."
6453   (interactive)
6454   (let ((pop-up-windows t)
6455         (special-display-buffer-names nil)
6456         (special-display-regexps nil)
6457         (same-window-buffer-names nil)
6458         (same-window-regexps nil))
6459     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6460   (let ((message-this-is-news t))
6461     (message-setup `((Newsgroups . ,(or newsgroups ""))
6462                      (Subject . ,(or subject ""))))))
6463
6464 ;;;###autoload
6465 (defun message-news-other-frame (&optional newsgroups subject)
6466   "Start editing a news article to be sent."
6467   (interactive)
6468   (let ((pop-up-frames t)
6469         (special-display-buffer-names nil)
6470         (special-display-regexps nil)
6471         (same-window-buffer-names nil)
6472         (same-window-regexps nil))
6473     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6474   (let ((message-this-is-news t))
6475     (message-setup `((Newsgroups . ,(or newsgroups ""))
6476                      (Subject . ,(or subject ""))))))
6477
6478 ;;; underline.el
6479
6480 ;; This code should be moved to underline.el (from which it is stolen).
6481
6482 ;;;###autoload
6483 (defun bold-region (start end)
6484   "Bold all nonblank characters in the region.
6485 Works by overstriking characters.
6486 Called from program, takes two arguments START and END
6487 which specify the range to operate on."
6488   (interactive "r")
6489   (save-excursion
6490     (let ((end1 (make-marker)))
6491       (move-marker end1 (max start end))
6492       (goto-char (min start end))
6493       (while (< (point) end1)
6494         (or (looking-at "[_\^@- ]")
6495             (insert (char-after) "\b"))
6496         (forward-char 1)))))
6497
6498 ;;;###autoload
6499 (defun unbold-region (start end)
6500   "Remove all boldness (overstruck characters) in the region.
6501 Called from program, takes two arguments START and END
6502 which specify the range to operate on."
6503   (interactive "r")
6504   (save-excursion
6505     (let ((end1 (make-marker)))
6506       (move-marker end1 (max start end))
6507       (goto-char (min start end))
6508       (while (re-search-forward "\b" end1 t)
6509         (if (eq (char-after) (char-after (- (point) 2)))
6510             (delete-char -2))))))
6511
6512 (defun message-exchange-point-and-mark ()
6513   "Exchange point and mark, but don't activate region if it was inactive."
6514   (unless (prog1
6515               (message-mark-active-p)
6516             (exchange-point-and-mark))
6517     (setq mark-active nil)))
6518
6519 (defalias 'message-make-overlay 'make-overlay)
6520 (defalias 'message-delete-overlay 'delete-overlay)
6521 (defalias 'message-overlay-put 'overlay-put)
6522 (defun message-kill-all-overlays ()
6523   (if (featurep 'xemacs)
6524       (map-extents (lambda (extent ignore) (delete-extent extent)))
6525     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
6526
6527 ;; Support for toolbar
6528 (eval-when-compile
6529   (defvar tool-bar-map)
6530   (defvar tool-bar-mode))
6531
6532 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6533   ;; We need to make tool bar entries in local keymaps with
6534   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6535   (if (fboundp 'tool-bar-local-item-from-menu)
6536       ;; This is for Emacs 21.3
6537       (tool-bar-local-item-from-menu command icon in-map from-map props)
6538     (tool-bar-add-item-from-menu command icon from-map props)))
6539
6540 (defun message-tool-bar-map ()
6541   (or message-tool-bar-map
6542       (setq message-tool-bar-map
6543             (and
6544              (condition-case nil (require 'tool-bar) (error nil))
6545              (fboundp 'tool-bar-add-item-from-menu)
6546              tool-bar-mode
6547              (let ((tool-bar-map (copy-keymap tool-bar-map))
6548                    (load-path (mm-image-load-path)))
6549                ;; Zap some items which aren't so relevant and take
6550                ;; up space.
6551                (dolist (key '(print-buffer kill-buffer save-buffer
6552                                            write-file dired open-file))
6553                  (define-key tool-bar-map (vector key) nil))
6554                (message-tool-bar-local-item-from-menu
6555                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
6556                (message-tool-bar-local-item-from-menu
6557                 'message-kill-buffer "close" tool-bar-map message-mode-map)
6558                (message-tool-bar-local-item-from-menu
6559                     'message-dont-send "cancel" tool-bar-map message-mode-map)
6560                (message-tool-bar-local-item-from-menu
6561                 'mml-attach-file "attach" tool-bar-map mml-mode-map)
6562                (message-tool-bar-local-item-from-menu
6563                 'ispell-message "spell" tool-bar-map message-mode-map)
6564                (message-tool-bar-local-item-from-menu
6565                 'mml-preview "preview"
6566                 tool-bar-map mml-mode-map)
6567                (message-tool-bar-local-item-from-menu
6568                 'message-insert-importance-high "important"
6569                 tool-bar-map message-mode-map)
6570                (message-tool-bar-local-item-from-menu
6571                 'message-insert-importance-low "unimportant"
6572                 tool-bar-map message-mode-map)
6573                (message-tool-bar-local-item-from-menu
6574                 'message-insert-disposition-notification-to "receipt"
6575                 tool-bar-map message-mode-map)
6576                tool-bar-map)))))
6577
6578 ;;; Group name completion.
6579
6580 (defcustom message-newgroups-header-regexp
6581   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6582   "Regexp that match headers that lists groups."
6583   :group 'message
6584   :type 'regexp)
6585
6586 (defcustom message-completion-alist
6587   (list (cons message-newgroups-header-regexp 'message-expand-group)
6588         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6589         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6590           . message-expand-name)
6591         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6592           . message-expand-name))
6593   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6594   :group 'message
6595   :type '(alist :key-type regexp :value-type function))
6596
6597 (defcustom message-expand-name-databases
6598   (list 'bbdb 'eudc)
6599   "List of databases to try for name completion (`message-expand-name').
6600 Each element is a symbol and can be `bbdb' or `eudc'."
6601   :group 'message
6602   :type '(set (const bbdb) (const eudc)))
6603
6604 (defcustom message-tab-body-function nil
6605   "*Function to execute when `message-tab' (TAB) is executed in the body.
6606 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6607   :group 'message
6608   :link '(custom-manual "(message)Various Commands")
6609   :type 'function)
6610
6611 (defun message-tab ()
6612   "Complete names according to `message-completion-alist'.
6613 Execute function specified by `message-tab-body-function' when not in
6614 those headers."
6615   (interactive)
6616   (let ((alist message-completion-alist))
6617     (while (and alist
6618                 (let ((mail-abbrev-mode-regexp (caar alist)))
6619                   (not (mail-abbrev-in-expansion-header-p))))
6620       (setq alist (cdr alist)))
6621     (funcall (or (cdar alist) message-tab-body-function
6622                  (lookup-key text-mode-map "\t")
6623                  (lookup-key global-map "\t")
6624                  'indent-relative))))
6625
6626 (defun message-expand-group ()
6627   "Expand the group name under point."
6628   (let* ((b (save-excursion
6629               (save-restriction
6630                 (narrow-to-region
6631                  (save-excursion
6632                    (beginning-of-line)
6633                    (skip-chars-forward "^:")
6634                    (1+ (point)))
6635                  (point))
6636                 (skip-chars-backward "^, \t\n") (point))))
6637          (completion-ignore-case t)
6638          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6639                                             (point))))
6640          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6641          (completions (all-completions string hashtb))
6642          comp)
6643     (delete-region b (point))
6644     (cond
6645      ((= (length completions) 1)
6646       (if (string= (car completions) string)
6647           (progn
6648             (insert string)
6649             (message "Only matching group"))
6650         (insert (car completions))))
6651      ((and (setq comp (try-completion string hashtb))
6652            (not (string= comp string)))
6653       (insert comp))
6654      (t
6655       (insert string)
6656       (if (not comp)
6657           (message "No matching groups")
6658         (save-selected-window
6659           (pop-to-buffer "*Completions*")
6660           (buffer-disable-undo)
6661           (let ((buffer-read-only nil))
6662             (erase-buffer)
6663             (let ((standard-output (current-buffer)))
6664               (display-completion-list (sort completions 'string<)))
6665             (goto-char (point-min))
6666             (delete-region (point) (progn (forward-line 3) (point))))))))))
6667
6668 (defun message-expand-name ()
6669   (cond ((and (memq 'eudc message-expand-name-databases)
6670                     (boundp 'eudc-protocol)
6671                     eudc-protocol)
6672          (eudc-expand-inline))
6673         ((and (memq 'bbdb message-expand-name-databases)
6674               (fboundp 'bbdb-complete-name))
6675          (bbdb-complete-name))
6676         (t
6677          (expand-abbrev))))
6678
6679 ;;; Help stuff.
6680
6681 (defun message-talkative-question (ask question show &rest text)
6682   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6683 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6684 The following arguments may contain lists of values."
6685   (if (and show
6686            (setq text (message-flatten-list text)))
6687       (save-window-excursion
6688         (save-excursion
6689           (with-output-to-temp-buffer " *MESSAGE information message*"
6690             (set-buffer " *MESSAGE information message*")
6691             (fundamental-mode)          ; for Emacs 20.4+
6692             (mapcar 'princ text)
6693             (goto-char (point-min))))
6694         (funcall ask question))
6695     (funcall ask question)))
6696
6697 (defun message-flatten-list (list)
6698   "Return a new, flat list that contains all elements of LIST.
6699
6700 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6701 => (1 2 3 4 5 6 7)"
6702   (cond ((consp list)
6703          (apply 'append (mapcar 'message-flatten-list list)))
6704         (list
6705          (list list))))
6706
6707 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6708   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
6709 Then clone the local variables and values from the old buffer to the
6710 new one, cloning only the locals having a substring matching the
6711 regexp VARSTR."
6712   (let ((oldbuf (current-buffer)))
6713     (save-excursion
6714       (set-buffer (generate-new-buffer name))
6715       (message-clone-locals oldbuf varstr)
6716       (current-buffer))))
6717
6718 (defun message-clone-locals (buffer &optional varstr)
6719   "Clone the local variables from BUFFER to the current buffer."
6720   (let ((locals (save-excursion
6721                   (set-buffer buffer)
6722                   (buffer-local-variables)))
6723         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
6724     (mapcar
6725      (lambda (local)
6726        (when (and (consp local)
6727                   (car local)
6728                   (string-match regexp (symbol-name (car local)))
6729                   (or (null varstr)
6730                       (string-match varstr (symbol-name (car local)))))
6731          (ignore-errors
6732            (set (make-local-variable (car local))
6733                 (cdr local)))))
6734      locals)))
6735
6736 ;;;
6737 ;;; MIME functions
6738 ;;;
6739
6740 (defvar message-inhibit-body-encoding nil)
6741
6742 (defun message-encode-message-body ()
6743   (unless message-inhibit-body-encoding
6744     (let ((mail-parse-charset (or mail-parse-charset
6745                                   message-default-charset))
6746           (case-fold-search t)
6747           lines content-type-p)
6748       (message-goto-body)
6749       (save-restriction
6750         (narrow-to-region (point) (point-max))
6751         (let ((new (mml-generate-mime)))
6752           (when new
6753             (delete-region (point-min) (point-max))
6754             (insert new)
6755             (goto-char (point-min))
6756             (if (eq (aref new 0) ?\n)
6757                 (delete-char 1)
6758               (search-forward "\n\n")
6759               (setq lines (buffer-substring (point-min) (1- (point))))
6760               (delete-region (point-min) (point))))))
6761       (save-restriction
6762         (message-narrow-to-headers-or-head)
6763         (message-remove-header "Mime-Version")
6764         (goto-char (point-max))
6765         (insert "MIME-Version: 1.0\n")
6766         (when lines
6767           (insert lines))
6768         (setq content-type-p
6769               (or mml-boundary
6770                   (re-search-backward "^Content-Type:" nil t))))
6771       (save-restriction
6772         (message-narrow-to-headers-or-head)
6773         (message-remove-first-header "Content-Type")
6774         (message-remove-first-header "Content-Transfer-Encoding"))
6775       ;; We always make sure that the message has a Content-Type
6776       ;; header.  This is because some broken MTAs and MUAs get
6777       ;; awfully confused when confronted with a message with a
6778       ;; MIME-Version header and without a Content-Type header.  For
6779       ;; instance, Solaris' /usr/bin/mail.
6780       (unless content-type-p
6781         (goto-char (point-min))
6782         ;; For unknown reason, MIME-Version doesn't exist.
6783         (when (re-search-forward "^MIME-Version:" nil t)
6784           (forward-line 1)
6785           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6786
6787 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6788   "Read from the minibuffer while providing abbrev expansion."
6789   (if (fboundp 'mail-abbrevs-setup)
6790       (let ((mail-abbrev-mode-regexp "")
6791             (minibuffer-setup-hook 'mail-abbrevs-setup)
6792             (minibuffer-local-map message-minibuffer-local-map))
6793         (read-from-minibuffer prompt initial-contents))
6794     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6795           (minibuffer-local-map message-minibuffer-local-map))
6796       (read-string prompt initial-contents))))
6797
6798 (defun message-use-alternative-email-as-from ()
6799   (require 'mail-utils)
6800   (let* ((fields '("To" "Cc"))
6801          (emails
6802           (split-string
6803            (mail-strip-quoted-names
6804             (mapconcat 'message-fetch-reply-field fields ","))
6805            "[ \f\t\n\r\v,]+"))
6806          email)
6807     (while emails
6808       (if (string-match message-alternative-emails (car emails))
6809           (setq email (car emails)
6810                 emails nil))
6811       (pop emails))
6812     (unless (or (not email) (equal email user-mail-address))
6813       (goto-char (point-max))
6814       (insert "From: " email "\n"))))
6815
6816 (defun message-options-get (symbol)
6817   (cdr (assq symbol message-options)))
6818
6819 (defun message-options-set (symbol value)
6820   (let ((the-cons (assq symbol message-options)))
6821     (if the-cons
6822         (if value
6823             (setcdr the-cons value)
6824           (setq message-options (delq the-cons message-options)))
6825       (and value
6826            (push (cons symbol value) message-options))))
6827   value)
6828
6829 (defun message-options-set-recipient ()
6830   (save-restriction
6831     (message-narrow-to-headers-or-head)
6832     (message-options-set 'message-sender
6833                          (mail-strip-quoted-names
6834                           (message-fetch-field "from")))
6835     (message-options-set 'message-recipients
6836                          (mail-strip-quoted-names
6837                           (let ((to (message-fetch-field "to"))
6838                                 (cc (message-fetch-field "cc"))
6839                                 (bcc (message-fetch-field "bcc")))
6840                             (concat
6841                              (or to "")
6842                              (if (and to cc) ", ")
6843                              (or cc "")
6844                              (if (and (or to cc) bcc) ", ")
6845                              (or bcc "")))))))
6846
6847 (defun message-hide-headers ()
6848   "Hide headers based on the `message-hidden-headers' variable."
6849   (let ((regexps (if (stringp message-hidden-headers)
6850                      (list message-hidden-headers)
6851                    message-hidden-headers))
6852         (inhibit-point-motion-hooks t)
6853         (after-change-functions nil))
6854     (when regexps
6855       (save-excursion
6856         (save-restriction
6857           (message-narrow-to-headers)
6858           (goto-char (point-min))
6859           (while (not (eobp))
6860             (if (not (message-hide-header-p regexps))
6861                 (message-next-header)
6862               (let ((begin (point)))
6863                 (message-next-header)
6864                 (add-text-properties
6865                  begin (point)
6866                  '(invisible t message-hidden t))))))))))
6867
6868 (defun message-hide-header-p (regexps)
6869   (let ((result nil)
6870         (reverse nil))
6871     (when (eq (car regexps) 'not)
6872       (setq reverse t)
6873       (pop regexps))
6874     (dolist (regexp regexps)
6875       (setq result (or result (looking-at regexp))))
6876     (if reverse
6877         (not result)
6878       result)))
6879
6880 (when (featurep 'xemacs)
6881   (require 'messagexmas)
6882   (message-xmas-redefine))
6883
6884 (provide 'message)
6885
6886 (run-hooks 'message-load-hook)
6887
6888 ;; Local Variables:
6889 ;; coding: iso-8859-1
6890 ;; End:
6891
6892 ;;; arch-tag: 94b32cac-4504-4b6c-8181-030ebf380ee0
6893 ;;; message.el ends here