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