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