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