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