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