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