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