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