* deuglify.el (gnus-outlook-rearrange-article): Add missing citation
[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 (&optional start end yank-only)
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   (unless start (setq start (point)))
3311   (unless yank-only
3312     ;; Remove unwanted headers.
3313     (when message-ignored-cited-headers
3314       (let (all-removed)
3315         (save-restriction
3316           (narrow-to-region
3317            (goto-char start)
3318            (if (search-forward "\n\n" nil t)
3319                (1- (point))
3320              (point)))
3321           (message-remove-header message-ignored-cited-headers t)
3322           (when (= (point-min) (point-max))
3323             (setq all-removed t))
3324           (goto-char (point-max)))
3325         (if all-removed
3326             (goto-char start)
3327           (forward-line 1))))
3328     ;; Delete blank lines at the start of the buffer.
3329     (while (and (point-min)
3330                 (eolp)
3331                 (not (eobp)))
3332       (message-delete-line))
3333     ;; Delete blank lines at the end of the buffer.
3334     (goto-char (point-max))
3335     (unless (eolp)
3336       (insert "\n"))
3337     (while (and (zerop (forward-line -1))
3338                 (looking-at "$"))
3339       (message-delete-line)))
3340   ;; Do the indentation.
3341   (if (null message-yank-prefix)
3342       (indent-rigidly start (or end (mark t)) message-indentation-spaces)
3343     (save-excursion
3344       (goto-char start)
3345       (while (< (point) (or end (mark t)))
3346         (cond ((looking-at ">")
3347                (insert message-yank-cited-prefix))
3348               ((looking-at "^$")
3349                (insert message-yank-empty-prefix))
3350               (t
3351                (insert message-yank-prefix)))
3352         (forward-line 1))))
3353   (goto-char start))
3354
3355 (defun message-yank-original (&optional arg)
3356   "Insert the message being replied to, if any.
3357 Puts point before the text and mark after.
3358 Normally indents each nonblank line ARG spaces (default 3).  However,
3359 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3360
3361 This function uses `message-cite-function' to do the actual citing.
3362
3363 Just \\[universal-argument] as argument means don't indent, insert no
3364 prefix, and don't delete any headers."
3365   (interactive "P")
3366   (let ((modified (buffer-modified-p)))
3367     (when (and message-reply-buffer
3368                message-cite-function)
3369       (delete-windows-on message-reply-buffer t)
3370       (push-mark (save-excursion
3371                    (insert-buffer-substring message-reply-buffer)
3372                    (point)))
3373       (unless arg
3374         (funcall message-cite-function))
3375       (message-exchange-point-and-mark)
3376       (unless (bolp)
3377         (insert ?\n))
3378       (unless modified
3379         (setq message-checksum (message-checksum))))))
3380
3381 (defun message-yank-buffer (buffer)
3382   "Insert BUFFER into the current buffer and quote it."
3383   (interactive "bYank buffer: ")
3384   (let ((message-reply-buffer (get-buffer buffer)))
3385     (save-window-excursion
3386       (message-yank-original))))
3387
3388 (defun message-buffers ()
3389   "Return a list of active message buffers."
3390   (let (buffers)
3391     (save-excursion
3392       (dolist (buffer (buffer-list t))
3393         (set-buffer buffer)
3394         (when (and (eq major-mode 'message-mode)
3395                    (null message-sent-message-via))
3396           (push (buffer-name buffer) buffers))))
3397     (nreverse buffers)))
3398
3399 (eval-when-compile (defvar mail-citation-hook)) ; Compiler directive
3400
3401 (defun message-cite-original-1 (strip-signature)
3402   "Cite an original message.
3403 If STRIP-SIGNATURE is non-nil, strips off the signature from the
3404 original message.
3405
3406 This function uses `mail-citation-hook' if that is non-nil."
3407   (if (and (boundp 'mail-citation-hook)
3408            mail-citation-hook)
3409       (run-hooks 'mail-citation-hook)
3410     (let* ((start (point))
3411            (end (mark t))
3412            (x-no-archive nil)
3413            (functions
3414             (when message-indent-citation-function
3415               (if (listp message-indent-citation-function)
3416                   message-indent-citation-function
3417                 (list message-indent-citation-function))))
3418            ;; This function may be called by `gnus-summary-yank-message' and
3419            ;; may insert a different article from the original.  So, we will
3420            ;; modify the value of `message-reply-headers' with that article.
3421            (message-reply-headers
3422             (save-restriction
3423               (narrow-to-region start end)
3424               (message-narrow-to-head-1)
3425               (setq x-no-archive (message-fetch-field "x-no-archive"))
3426               (vector 0
3427                       (or (message-fetch-field "subject") "none")
3428                       (message-fetch-field "from")
3429                       (message-fetch-field "date")
3430                       (message-fetch-field "message-id" t)
3431                       (message-fetch-field "references")
3432                       0 0 ""))))
3433       (mml-quote-region start end)
3434       (when strip-signature
3435         ;; Allow undoing.
3436         (undo-boundary)
3437         (goto-char end)
3438         (when (re-search-backward message-signature-separator start t)
3439           ;; Also peel off any blank lines before the signature.
3440           (forward-line -1)
3441           (while (looking-at "^[ \t]*$")
3442             (forward-line -1))
3443           (forward-line 1)
3444           (delete-region (point) end)
3445           (unless (search-backward "\n\n" start t)
3446             ;; Insert a blank line if it is peeled off.
3447             (insert "\n"))))
3448       (goto-char start)
3449       (mapc 'funcall functions)
3450       (when message-citation-line-function
3451         (unless (bolp)
3452           (insert "\n"))
3453         (funcall message-citation-line-function))
3454       (when (and x-no-archive
3455                  (not message-cite-articles-with-x-no-archive)
3456                  (string-match "yes" x-no-archive))
3457         (undo-boundary)
3458         (delete-region (point) (mark t))
3459         (insert "> [Quoted text removed due to X-No-Archive]\n")
3460         (forward-line -1)))))
3461
3462 (defun message-cite-original ()
3463   "Cite function in the standard Message manner."
3464   (message-cite-original-1 nil))
3465
3466 (defun message-insert-formated-citation-line (&optional from date)
3467   "Function that inserts a formated citation line.
3468
3469 See `message-citation-line-format'."
3470   ;; The optional args are for testing/debugging.  They will disappear later.
3471   ;; Example:
3472   ;; (with-temp-buffer
3473   ;;   (message-insert-formated-citation-line
3474   ;;    "John Doe <john.doe@example.invalid>"
3475   ;;    (current-time))
3476   ;;   (buffer-string))
3477   (when (or message-reply-headers (and from date))
3478     (unless from
3479       (setq from (mail-header-from message-reply-headers)))
3480     (let* ((data (condition-case ()
3481                      (funcall (if (boundp gnus-extract-address-components)
3482                                   gnus-extract-address-components
3483                                 'mail-extract-address-components)
3484                               from)
3485                    (error nil)))
3486            (name (car data))
3487            (fname name)
3488            (lname name)
3489            (net (car (cdr data)))
3490            (name-or-net (or (car data)
3491                             (car (cdr data)) from))
3492            (replydate
3493             (or
3494              date
3495              ;; We need Gnus functionality if the user wants date or time from
3496              ;; the original article:
3497              (when (string-match "%[^EFLn]" message-citation-line-format)
3498                (autoload 'gnus-date-get-time "gnus-util")
3499                (gnus-date-get-time (mail-header-date message-reply-headers)))))
3500            (flist
3501             (let ((i ?A) lst)
3502               (when (stringp name)
3503                 ;; Guess first name and last name:
3504                 (cond ((string-match
3505                         "\\`\\(\\w\\|[-.]\\)+ \\(\\w\\|[-.]\\)+\\'" name)
3506                        (setq fname (nth 0 (split-string name "[ \t]+"))
3507                              lname (nth 1 (split-string name "[ \t]+"))))
3508                       ((string-match
3509                         "\\`\\(\\w\\|[-.]\\)+, \\(\\w\\|[-.]\\)+\\'" name)
3510                        (setq fname (nth 1 (split-string name "[ \t,]+"))
3511                              lname (nth 0 (split-string name "[ \t,]+"))))
3512                       ((string-match
3513                         "\\`\\(\\w\\|[-.]\\)+\\'" name)
3514                        (setq fname name
3515                              lname ""))))
3516               ;; The following letters are not used in `format-time-string':
3517               (push ?E lst) (push net lst)
3518               (push ?F lst) (push fname lst)
3519               ;; We might want to use "" instead of "<X>" later.
3520               (push ?J lst) (push "<J>" lst)
3521               (push ?K lst) (push "<K>" lst)
3522               (push ?L lst) (push lname lst)
3523               (push ?N lst) (push "<N>" lst)
3524               (push ?O lst) (push "<O>" lst)
3525               (push ?P lst) (push "<P>" lst)
3526               (push ?Q lst) (push "<Q>" lst)
3527               (push ?f lst) (push "<f>" lst)
3528               (push ?i lst) (push "<i>" lst)
3529               (push ?n lst) (push name-or-net lst)
3530               (push ?o lst) (push "<o>" lst)
3531               (push ?q lst) (push "<q>" lst)
3532               (push ?t lst) (push "<t>" lst)
3533               (push ?v lst) (push "<v>" lst)
3534               ;; Delegate the rest to `format-time-string':
3535               (while (<= i ?z)
3536                 (when (and (not (memq i lst))
3537                            ;; Skip (Z,a)
3538                            (or (<= i ?Z)
3539                                (>= i ?a)))
3540                   (push i lst)
3541                   (push (condition-case nil
3542                             (progn (format-time-string (format "%%%c" i)
3543                                                        replydate))
3544                           (format ">%c<" i))
3545                         lst))
3546                 (setq i (1+ i)))
3547               (reverse lst)))
3548            (spec (apply 'format-spec-make flist)))
3549       (insert (format-spec message-citation-line-format spec)))
3550     (newline)
3551     (newline)))
3552
3553 (defun message-cite-original-without-signature ()
3554   "Cite function in the standard Message manner.
3555 This function strips off the signature from the original message."
3556   (message-cite-original-1 t))
3557
3558 (defun message-insert-citation-line ()
3559   "Insert a simple citation line."
3560   (when message-reply-headers
3561     (insert (mail-header-from message-reply-headers) " writes:")
3562     (newline)
3563     (newline)))
3564
3565 (defun message-position-on-field (header &rest afters)
3566   (let ((case-fold-search t))
3567     (save-restriction
3568       (narrow-to-region
3569        (goto-char (point-min))
3570        (progn
3571          (re-search-forward
3572           (concat "^" (regexp-quote mail-header-separator) "$"))
3573          (match-beginning 0)))
3574       (goto-char (point-min))
3575       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3576           (progn
3577             (re-search-forward "^[^ \t]" nil 'move)
3578             (beginning-of-line)
3579             (skip-chars-backward "\n")
3580             t)
3581         (while (and afters
3582                     (not (re-search-forward
3583                           (concat "^" (regexp-quote (car afters)) ":")
3584                           nil t)))
3585           (pop afters))
3586         (when afters
3587           (re-search-forward "^[^ \t]" nil 'move)
3588           (beginning-of-line))
3589         (insert header ": \n")
3590         (forward-char -1)
3591         nil))))
3592
3593 (defun message-remove-signature ()
3594   "Remove the signature from the text between point and mark.
3595 The text will also be indented the normal way."
3596   (save-excursion
3597     (let ((start (point))
3598           mark)
3599       (if (not (re-search-forward message-signature-separator (mark t) t))
3600           ;; No signature here, so we just indent the cited text.
3601           (message-indent-citation)
3602         ;; Find the last non-empty line.
3603         (forward-line -1)
3604         (while (looking-at "[ \t]*$")
3605           (forward-line -1))
3606         (forward-line 1)
3607         (setq mark (set-marker (make-marker) (point)))
3608         (goto-char start)
3609         (message-indent-citation)
3610         ;; Enable undoing the deletion.
3611         (undo-boundary)
3612         (delete-region mark (mark t))
3613         (set-marker mark nil)))))
3614
3615 \f
3616
3617 ;;;
3618 ;;; Sending messages
3619 ;;;
3620
3621 (defun message-send-and-exit (&optional arg)
3622   "Send message like `message-send', then, if no errors, exit from mail buffer."
3623   (interactive "P")
3624   (let ((buf (current-buffer))
3625         (actions message-exit-actions))
3626     (when (and (message-send arg)
3627                (buffer-name buf))
3628       (if message-kill-buffer-on-exit
3629           (kill-buffer buf)
3630         (bury-buffer buf)
3631         (when (eq buf (current-buffer))
3632           (message-bury buf)))
3633       (message-do-actions actions)
3634       t)))
3635
3636 (defun message-dont-send ()
3637   "Don't send the message you have been editing.
3638 Instead, just auto-save the buffer and then bury it."
3639   (interactive)
3640   (set-buffer-modified-p t)
3641   (save-buffer)
3642   (let ((actions message-postpone-actions))
3643     (message-bury (current-buffer))
3644     (message-do-actions actions)))
3645
3646 (defun message-kill-buffer ()
3647   "Kill the current buffer."
3648   (interactive)
3649   (when (or (not (buffer-modified-p))
3650             (not message-kill-buffer-query)
3651             (yes-or-no-p "Message modified; kill anyway? "))
3652     (let ((actions message-kill-actions)
3653           (draft-article message-draft-article)
3654           (auto-save-file-name buffer-auto-save-file-name)
3655           (file-name buffer-file-name)
3656           (modified (buffer-modified-p)))
3657       (setq buffer-file-name nil)
3658       (kill-buffer (current-buffer))
3659       (when (and (or (and auto-save-file-name
3660                           (file-exists-p auto-save-file-name))
3661                      (and file-name
3662                           (file-exists-p file-name)))
3663                  (progn
3664                    ;; If the message buffer has lived in a dedicated window,
3665                    ;; `kill-buffer' has killed the frame.  Thus the
3666                    ;; `yes-or-no-p' may show up in a lowered frame.  Make sure
3667                    ;; that the user can see the question by raising the
3668                    ;; current frame:
3669                    (raise-frame)
3670                    (yes-or-no-p (format "Remove the backup file%s? "
3671                                         (if modified " too" "")))))
3672         (ignore-errors
3673           (delete-file auto-save-file-name))
3674         (let ((message-draft-article draft-article))
3675           (message-disassociate-draft)))
3676       (message-do-actions actions))))
3677
3678 (defun message-bury (buffer)
3679   "Bury this mail BUFFER."
3680   (let ((newbuf (other-buffer buffer)))
3681     (bury-buffer buffer)
3682     (if (and (window-dedicated-p (selected-window))
3683              (not (null (delq (selected-frame) (visible-frame-list)))))
3684         (delete-frame (selected-frame))
3685       (switch-to-buffer newbuf))))
3686
3687 (defun message-send (&optional arg)
3688   "Send the message in the current buffer.
3689 If `message-interactive' is non-nil, wait for success indication or
3690 error messages, and inform user.
3691 Otherwise any failure is reported in a message back to the user from
3692 the mailer.
3693 The usage of ARG is defined by the instance that called Message.
3694 It should typically alter the sending method in some way or other."
3695   (interactive "P")
3696   ;; Make it possible to undo the coming changes.
3697   (undo-boundary)
3698   (let ((inhibit-read-only t))
3699     (put-text-property (point-min) (point-max) 'read-only nil))
3700   (message-fix-before-sending)
3701   (run-hooks 'message-send-hook)
3702   (message message-sending-message)
3703   (let ((alist message-send-method-alist)
3704         (success t)
3705         elem sent dont-barf-on-no-method
3706         (message-options message-options))
3707     (message-options-set-recipient)
3708     (while (and success
3709                 (setq elem (pop alist)))
3710       (when (funcall (cadr elem))
3711         (when (and (or (not (memq (car elem)
3712                                   message-sent-message-via))
3713                        (message-fetch-field "supersedes")
3714                        (if (or (message-gnksa-enable-p 'multiple-copies)
3715                                (not (eq (car elem) 'news)))
3716                            (y-or-n-p
3717                             (format
3718                              "Already sent message via %s; resend? "
3719                              (car elem)))
3720                          (error "Denied posting -- multiple copies")))
3721                    (setq success (funcall (caddr elem) arg)))
3722           (setq sent t))))
3723     (unless (or sent
3724                 (not success)
3725                 (let ((fcc (message-fetch-field "Fcc"))
3726                       (gcc (message-fetch-field "Gcc")))
3727                   (when (or fcc gcc)
3728                     (or (eq message-allow-no-recipients 'always)
3729                         (and (not (eq message-allow-no-recipients 'never))
3730                              (setq dont-barf-on-no-method
3731                                    (gnus-y-or-n-p
3732                                     (format "No receiver, perform %s anyway? "
3733                                             (cond ((and fcc gcc) "Fcc and Gcc")
3734                                                   (fcc "Fcc")
3735                                                   (t "Gcc"))))))))))
3736       (error "No methods specified to send by"))
3737     (when (or dont-barf-on-no-method
3738               (and success sent))
3739       (message-do-fcc)
3740       (save-excursion
3741         (run-hooks 'message-sent-hook))
3742       (message "Sending...done")
3743       ;; Do ecomplete address snarfing.
3744       (when (message-mail-alias-type-p 'ecomplete)
3745         (message-put-addresses-in-ecomplete))
3746       ;; Mark the buffer as unmodified and delete auto-save.
3747       (set-buffer-modified-p nil)
3748       (delete-auto-save-file-if-necessary t)
3749       (message-disassociate-draft)
3750       ;; Delete other mail buffers and stuff.
3751       (message-do-send-housekeeping)
3752       (message-do-actions message-send-actions)
3753       ;; Return success.
3754       t)))
3755
3756 (defun message-send-via-mail (arg)
3757   "Send the current message via mail."
3758   (message-send-mail arg))
3759
3760 (defun message-send-via-news (arg)
3761   "Send the current message via news."
3762   (funcall message-send-news-function arg))
3763
3764 (defmacro message-check (type &rest forms)
3765   "Eval FORMS if TYPE is to be checked."
3766   `(or (message-check-element ,type)
3767        (save-excursion
3768          ,@forms)))
3769
3770 (put 'message-check 'lisp-indent-function 1)
3771 (put 'message-check 'edebug-form-spec '(form body))
3772
3773 (defun message-text-with-property (prop &optional start end reverse)
3774   "Return a list of start and end positions where the text has PROP.
3775 START and END bound the search, they default to `point-min' and
3776 `point-max' respectively.  If REVERSE is non-nil, find text which does
3777 not have PROP."
3778   (unless start
3779     (setq start (point-min)))
3780   (unless end
3781     (setq end (point-max)))
3782   (let (next regions)
3783     (if reverse
3784         (while (and start
3785                     (setq start (text-property-any start end prop nil)))
3786           (setq next (next-single-property-change start prop nil end))
3787           (push (cons start (or next end)) regions)
3788           (setq start next))
3789       (while (and start
3790                   (or (get-text-property start prop)
3791                       (and (setq start (next-single-property-change
3792                                         start prop nil end))
3793                            (get-text-property start prop))))
3794         (setq next (text-property-any start end prop nil))
3795         (push (cons start (or next end)) regions)
3796         (setq start next)))
3797     (nreverse regions)))
3798
3799 (defun message-fix-before-sending ()
3800   "Do various things to make the message nice before sending it."
3801   ;; Make sure there's a newline at the end of the message.
3802   (goto-char (point-max))
3803   (unless (bolp)
3804     (insert "\n"))
3805   ;; Make the hidden headers visible.
3806   (widen)
3807   ;; Sort headers before sending the message.
3808   (message-sort-headers)
3809   ;; Make invisible text visible.
3810   ;; It doesn't seem as if this is useful, since the invisible property
3811   ;; is clobbered by an after-change hook anyhow.
3812   (message-check 'invisible-text
3813     (let ((regions (message-text-with-property 'invisible))
3814           from to)
3815       (when regions
3816         (while regions
3817           (setq from (caar regions)
3818                 to (cdar regions)
3819                 regions (cdr regions))
3820           (put-text-property from to 'invisible nil)
3821           (message-overlay-put (message-make-overlay from to)
3822                                'face 'highlight))
3823         (unless (yes-or-no-p
3824                  "Invisible text found and made visible; continue sending? ")
3825           (error "Invisible text found and made visible")))))
3826   (message-check 'illegible-text
3827     (let (found choice)
3828       (message-goto-body)
3829       (skip-chars-forward mm-7bit-chars)
3830       (while (not (eobp))
3831         (when (let ((char (char-after)))
3832                 (or (< (mm-char-int char) 128)
3833                     (and (mm-multibyte-p)
3834                          (memq (char-charset char)
3835                                '(eight-bit-control eight-bit-graphic
3836                                                    control-1))
3837                          (not (get-text-property
3838                                (point) 'untranslated-utf-8)))))
3839           (message-overlay-put (message-make-overlay (point) (1+ (point)))
3840                                'face 'highlight)
3841           (setq found t))
3842         (forward-char)
3843         (skip-chars-forward mm-7bit-chars))
3844       (when found
3845         (setq choice
3846               (gnus-multiple-choice
3847                "Non-printable characters found.  Continue sending?"
3848                '((?d "Remove non-printable characters and send")
3849                  (?r "Replace non-printable characters with dots and send")
3850                  (?i "Ignore non-printable characters and send")
3851                  (?e "Continue editing"))))
3852         (if (eq choice ?e)
3853           (error "Non-printable characters"))
3854         (message-goto-body)
3855         (skip-chars-forward mm-7bit-chars)
3856         (while (not (eobp))
3857           (when (let ((char (char-after)))
3858                   (or (< (mm-char-int char) 128)
3859                       (and (mm-multibyte-p)
3860                            ;; FIXME: Wrong for Emacs 23 (unicode) and for
3861                            ;; things like undecable utf-8.  Should at least
3862                            ;; use find-coding-systems-region.
3863                            (memq (char-charset char)
3864                                  '(eight-bit-control eight-bit-graphic
3865                                                      control-1))
3866                            (not (get-text-property
3867                                  (point) 'untranslated-utf-8)))))
3868             (if (eq choice ?i)
3869                 (message-kill-all-overlays)
3870               (delete-char 1)
3871               (when (eq choice ?r)
3872                 (insert "."))))
3873           (forward-char)
3874           (skip-chars-forward mm-7bit-chars))))))
3875
3876 (defun message-add-action (action &rest types)
3877   "Add ACTION to be performed when doing an exit of type TYPES."
3878   (while types
3879     (add-to-list (intern (format "message-%s-actions" (pop types)))
3880                  action)))
3881
3882 (defun message-delete-action (action &rest types)
3883   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3884   (let (var)
3885     (while types
3886       (set (setq var (intern (format "message-%s-actions" (pop types))))
3887            (delq action (symbol-value var))))))
3888
3889 (defun message-do-actions (actions)
3890   "Perform all actions in ACTIONS."
3891   ;; Now perform actions on successful sending.
3892   (dolist (action actions)
3893     (ignore-errors
3894       (cond
3895        ;; A simple function.
3896        ((functionp action)
3897         (funcall action))
3898        ;; Something to be evaled.
3899        (t
3900         (eval action))))))
3901
3902 (defun message-send-mail-partially ()
3903   "Send mail as message/partial."
3904   ;; replace the header delimiter with a blank line
3905   (goto-char (point-min))
3906   (re-search-forward
3907    (concat "^" (regexp-quote mail-header-separator) "\n"))
3908   (replace-match "\n")
3909   (run-hooks 'message-send-mail-hook)
3910   (let ((p (goto-char (point-min)))
3911         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3912         (curbuf (current-buffer))
3913         (id (message-make-message-id)) (n 1)
3914         plist total  header required-mail-headers)
3915     (while (not (eobp))
3916       (if (< (point-max) (+ p message-send-mail-partially-limit))
3917           (goto-char (point-max))
3918         (goto-char (+ p message-send-mail-partially-limit))
3919         (beginning-of-line)
3920         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3921       (push p plist)
3922       (setq p (point)))
3923     (setq total (length plist))
3924     (push (point-max) plist)
3925     (setq plist (nreverse plist))
3926     (unwind-protect
3927         (save-excursion
3928           (setq p (pop plist))
3929           (while plist
3930             (set-buffer curbuf)
3931             (copy-to-buffer tembuf p (car plist))
3932             (set-buffer tembuf)
3933             (goto-char (point-min))
3934             (if header
3935                 (progn
3936                   (goto-char (point-min))
3937                   (narrow-to-region (point) (point))
3938                   (insert header))
3939               (message-goto-eoh)
3940               (setq header (buffer-substring (point-min) (point)))
3941               (goto-char (point-min))
3942               (narrow-to-region (point) (point))
3943               (insert header)
3944               (message-remove-header "Mime-Version")
3945               (message-remove-header "Content-Type")
3946               (message-remove-header "Content-Transfer-Encoding")
3947               (message-remove-header "Message-ID")
3948               (message-remove-header "Lines")
3949               (goto-char (point-max))
3950               (insert "Mime-Version: 1.0\n")
3951               (setq header (buffer-string)))
3952             (goto-char (point-max))
3953             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3954                             id n total))
3955             (forward-char -1)
3956             (let ((mail-header-separator ""))
3957               (when (memq 'Message-ID message-required-mail-headers)
3958                 (insert "Message-ID: " (message-make-message-id) "\n"))
3959               (when (memq 'Lines message-required-mail-headers)
3960                 (insert "Lines: " (message-make-lines) "\n"))
3961               (message-goto-subject)
3962               (end-of-line)
3963               (insert (format " (%d/%d)" n total))
3964               (widen)
3965               (mm-with-unibyte-current-buffer
3966                 (funcall (or message-send-mail-real-function
3967                              message-send-mail-function))))
3968             (setq n (+ n 1))
3969             (setq p (pop plist))
3970             (erase-buffer)))
3971       (kill-buffer tembuf))))
3972
3973 (defun message-send-mail (&optional arg)
3974   (require 'mail-utils)
3975   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3976          (case-fold-search nil)
3977          (news (message-news-p))
3978          (mailbuf (current-buffer))
3979          (message-this-is-mail t)
3980          (message-posting-charset
3981           (if (fboundp 'gnus-setup-posting-charset)
3982               (gnus-setup-posting-charset nil)
3983             message-posting-charset))
3984          (headers message-required-mail-headers))
3985     (when message-generate-hashcash
3986       (message "Generating hashcash...")
3987       ;; Wait for calculations already started to finish...
3988       (hashcash-wait-async)
3989       ;; ...and do calculations not already done.  mail-add-payment
3990       ;; will leave existing X-Hashcash headers alone.
3991       (mail-add-payment)
3992       (message "Generating hashcash...done"))
3993     (save-restriction
3994       (message-narrow-to-headers)
3995       ;; Generate the Mail-Followup-To header if the header is not there...
3996       (if (and (message-subscribed-p)
3997                (not (mail-fetch-field "mail-followup-to")))
3998           (setq headers
3999                 (cons
4000                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4001                  message-required-mail-headers))
4002         ;; otherwise, delete the MFT header if the field is empty
4003         (when (equal "" (mail-fetch-field "mail-followup-to"))
4004           (message-remove-header "^Mail-Followup-To:")))
4005       ;; Insert some headers.
4006       (let ((message-deletable-headers
4007              (if news nil message-deletable-headers)))
4008         (message-generate-headers headers))
4009       ;; Let the user do all of the above.
4010       (run-hooks 'message-header-hook))
4011     (unwind-protect
4012         (save-excursion
4013           (set-buffer tembuf)
4014           (erase-buffer)
4015           ;; Avoid copying text props (except hard newlines).
4016           (insert (with-current-buffer mailbuf
4017                     (mml-buffer-substring-no-properties-except-hard-newlines
4018                      (point-min) (point-max))))
4019           ;; Remove some headers.
4020           (message-encode-message-body)
4021           (save-restriction
4022             (message-narrow-to-headers)
4023             ;; We (re)generate the Lines header.
4024             (when (memq 'Lines message-required-mail-headers)
4025               (message-generate-headers '(Lines)))
4026             ;; Remove some headers.
4027             (message-remove-header message-ignored-mail-headers t)
4028             (let ((mail-parse-charset message-default-charset))
4029               (mail-encode-encoded-word-buffer)))
4030           (goto-char (point-max))
4031           ;; require one newline at the end.
4032           (or (= (preceding-char) ?\n)
4033               (insert ?\n))
4034           (message-cleanup-headers)
4035           ;; FIXME: we're inserting the courtesy copy after encoding.
4036           ;; This is wrong if the courtesy copy string contains
4037           ;; non-ASCII characters. -- jh
4038           (when
4039               (save-restriction
4040                 (message-narrow-to-headers)
4041                 (and news
4042                      (or (message-fetch-field "cc")
4043                          (message-fetch-field "bcc")
4044                          (message-fetch-field "to"))
4045                      (let ((content-type (message-fetch-field
4046                                           "content-type")))
4047                        (and
4048                         (or
4049                          (not content-type)
4050                          (string= "text/plain"
4051                                   (car
4052                                    (mail-header-parse-content-type
4053                                     content-type))))
4054                         (not
4055                          (string= "base64"
4056                                   (message-fetch-field
4057                                    "content-transfer-encoding")))))))
4058             (message-insert-courtesy-copy))
4059           (if (or (not message-send-mail-partially-limit)
4060                   (< (buffer-size) message-send-mail-partially-limit)
4061                   (not (message-y-or-n-p
4062                         "The message size is too large, split? "
4063                         t
4064                         "\
4065 The message size, "
4066                         (/ (buffer-size) 1000) "KB, is too large.
4067
4068 Some mail gateways (MTA's) bounce large messages.  To avoid the
4069 problem, answer `y', and the message will be split into several
4070 smaller pieces, the size of each is about "
4071                         (/ message-send-mail-partially-limit 1000)
4072                         "KB except the last
4073 one.
4074
4075 However, some mail readers (MUA's) can't read split messages, i.e.,
4076 mails in message/partially format. Answer `n', and the message will be
4077 sent in one piece.
4078
4079 The size limit is controlled by `message-send-mail-partially-limit'.
4080 If you always want Gnus to send messages in one piece, set
4081 `message-send-mail-partially-limit' to nil.
4082 ")))
4083               (mm-with-unibyte-current-buffer
4084                 (message "Sending via mail...")
4085                 (funcall (or message-send-mail-real-function
4086                              message-send-mail-function)))
4087             (message-send-mail-partially)))
4088       (kill-buffer tembuf))
4089     (set-buffer mailbuf)
4090     (push 'mail message-sent-message-via)))
4091
4092 (defun message-send-mail-with-sendmail ()
4093   "Send off the prepared buffer with sendmail."
4094   (let ((errbuf (if message-interactive
4095                     (message-generate-new-buffer-clone-locals
4096                      " sendmail errors")
4097                   0))
4098         resend-to-addresses delimline)
4099     (unwind-protect
4100         (progn
4101           (let ((case-fold-search t))
4102             (save-restriction
4103               (message-narrow-to-headers)
4104               (setq resend-to-addresses (message-fetch-field "resent-to")))
4105             ;; Change header-delimiter to be what sendmail expects.
4106             (goto-char (point-min))
4107             (re-search-forward
4108              (concat "^" (regexp-quote mail-header-separator) "\n"))
4109             (replace-match "\n")
4110             (backward-char 1)
4111             (setq delimline (point-marker))
4112             (run-hooks 'message-send-mail-hook)
4113             ;; Insert an extra newline if we need it to work around
4114             ;; Sun's bug that swallows newlines.
4115             (goto-char (1+ delimline))
4116             (when (eval message-mailer-swallows-blank-line)
4117               (newline))
4118             (when message-interactive
4119               (with-current-buffer errbuf
4120                 (erase-buffer))))
4121           (let* ((default-directory "/")
4122                  (coding-system-for-write message-send-coding-system)
4123                  (cpr (apply
4124                        'call-process-region
4125                        (append
4126                         (list (point-min) (point-max)
4127                               (if (boundp 'sendmail-program)
4128                                   sendmail-program
4129                                 "/usr/lib/sendmail")
4130                               nil errbuf nil "-oi")
4131                         ;; Always specify who from,
4132                         ;; since some systems have broken sendmails.
4133                         ;; But some systems are more broken with -f, so
4134                         ;; we'll let users override this.
4135                         (if (null message-sendmail-f-is-evil)
4136                             (list "-f" (message-sendmail-envelope-from)))
4137                         ;; These mean "report errors by mail"
4138                         ;; and "deliver in background".
4139                         (if (null message-interactive) '("-oem" "-odb"))
4140                         ;; Get the addresses from the message
4141                         ;; unless this is a resend.
4142                         ;; We must not do that for a resend
4143                         ;; because we would find the original addresses.
4144                         ;; For a resend, include the specific addresses.
4145                         (if resend-to-addresses
4146                             (list resend-to-addresses)
4147                           '("-t"))))))
4148             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
4149               (error "Sending...failed with exit value %d" cpr)))
4150           (when message-interactive
4151             (save-excursion
4152               (set-buffer errbuf)
4153               (goto-char (point-min))
4154               (while (re-search-forward "\n+ *" nil t)
4155                 (replace-match "; "))
4156               (if (not (zerop (buffer-size)))
4157                   (error "Sending...failed to %s"
4158                          (buffer-string))))))
4159       (when (bufferp errbuf)
4160         (kill-buffer errbuf)))))
4161
4162 (defun message-send-mail-with-qmail ()
4163   "Pass the prepared message buffer to qmail-inject.
4164 Refer to the documentation for the variable `message-send-mail-function'
4165 to find out how to use this."
4166   ;; replace the header delimiter with a blank line
4167   (goto-char (point-min))
4168   (re-search-forward
4169    (concat "^" (regexp-quote mail-header-separator) "\n"))
4170   (replace-match "\n")
4171   (run-hooks 'message-send-mail-hook)
4172   ;; send the message
4173   (case
4174       (let ((coding-system-for-write message-send-coding-system))
4175         (apply
4176          'call-process-region (point-min) (point-max)
4177          message-qmail-inject-program nil nil nil
4178          ;; qmail-inject's default behaviour is to look for addresses on the
4179          ;; command line; if there're none, it scans the headers.
4180          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4181          ;;
4182          ;; in general, ALL of qmail-inject's defaults are perfect for simply
4183          ;; reading a formatted (i. e., at least a To: or Resent-To header)
4184          ;; message from stdin.
4185          ;;
4186          ;; qmail also has the advantage of not having been raped by
4187          ;; various vendors, so we don't have to allow for that, either --
4188          ;; compare this with message-send-mail-with-sendmail and weep
4189          ;; for sendmail's lost innocence.
4190          ;;
4191          ;; all this is way cool coz it lets us keep the arguments entirely
4192          ;; free for -inject-arguments -- a big win for the user and for us
4193          ;; since we don't have to play that double-guessing game and the user
4194          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4195          (if (functionp message-qmail-inject-args)
4196              (funcall message-qmail-inject-args)
4197            message-qmail-inject-args)))
4198     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4199     ;; we have to look at the retval instead
4200     (0 nil)
4201     (100 (error "qmail-inject reported permanent failure"))
4202     (111 (error "qmail-inject reported transient failure"))
4203     ;; should never happen
4204     (t   (error "qmail-inject reported unknown failure"))))
4205
4206 (defun message-send-mail-with-mh ()
4207   "Send the prepared message buffer with mh."
4208   (let ((mh-previous-window-config nil)
4209         (name (mh-new-draft-name)))
4210     (setq buffer-file-name name)
4211     ;; MH wants to generate these headers itself.
4212     (when message-mh-deletable-headers
4213       (let ((headers message-mh-deletable-headers))
4214         (while headers
4215           (goto-char (point-min))
4216           (and (re-search-forward
4217                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4218                (message-delete-line))
4219           (pop headers))))
4220     (run-hooks 'message-send-mail-hook)
4221     ;; Pass it on to mh.
4222     (mh-send-letter)))
4223
4224 (defun message-smtpmail-send-it ()
4225   "Send the prepared message buffer with `smtpmail-send-it'.
4226 This only differs from `smtpmail-send-it' that this command evaluates
4227 `message-send-mail-hook' just before sending a message.  It is useful
4228 if your ISP requires the POP-before-SMTP authentication.  See the Gnus
4229 manual for details."
4230   (run-hooks 'message-send-mail-hook)
4231   (smtpmail-send-it))
4232
4233 (defun message-canlock-generate ()
4234   "Return a string that is non-trivial to guess.
4235 Do not use this for anything important, it is cryptographically weak."
4236   (require 'sha1)
4237   (let (sha1-maximum-internal-length)
4238     (sha1 (concat (message-unique-id)
4239                   (format "%x%x%x" (random) (random t) (random))
4240                   (prin1-to-string (recent-keys))
4241                   (prin1-to-string (garbage-collect))))))
4242
4243 (defun message-canlock-password ()
4244   "The password used by message for cancel locks.
4245 This is the value of `canlock-password', if that option is non-nil.
4246 Otherwise, generate and save a value for `canlock-password' first."
4247   (unless canlock-password
4248     (customize-save-variable 'canlock-password (message-canlock-generate))
4249     (setq canlock-password-for-verify canlock-password))
4250   canlock-password)
4251
4252 (defun message-insert-canlock ()
4253   (when message-insert-canlock
4254     (message-canlock-password)
4255     (canlock-insert-header)))
4256
4257 (defun message-send-news (&optional arg)
4258   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4259          (case-fold-search nil)
4260          (method (if (functionp message-post-method)
4261                      (funcall message-post-method arg)
4262                    message-post-method))
4263          (newsgroups-field (save-restriction
4264                             (message-narrow-to-headers-or-head)
4265                             (message-fetch-field "Newsgroups")))
4266          (followup-field (save-restriction
4267                            (message-narrow-to-headers-or-head)
4268                            (message-fetch-field "Followup-To")))
4269          ;; BUG: We really need to get the charset for each name in the
4270          ;; Newsgroups and Followup-To lines to allow crossposting
4271          ;; between group namess with incompatible character sets.
4272          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4273          (group-field-charset
4274           (gnus-group-name-charset method newsgroups-field))
4275          (followup-field-charset
4276           (gnus-group-name-charset method (or followup-field "")))
4277          (rfc2047-header-encoding-alist
4278           (append (when group-field-charset
4279                     (list (cons "Newsgroups" group-field-charset)))
4280                   (when followup-field-charset
4281                     (list (cons "Followup-To" followup-field-charset)))
4282                   rfc2047-header-encoding-alist))
4283          (messbuf (current-buffer))
4284          (message-syntax-checks
4285           (if (and arg
4286                    (listp message-syntax-checks))
4287               (cons '(existing-newsgroups . disabled)
4288                     message-syntax-checks)
4289             message-syntax-checks))
4290          (message-this-is-news t)
4291          (message-posting-charset
4292           (gnus-setup-posting-charset newsgroups-field))
4293          result)
4294     (if (not (message-check-news-body-syntax))
4295         nil
4296       (save-restriction
4297         (message-narrow-to-headers)
4298         ;; Insert some headers.
4299         (message-generate-headers message-required-news-headers)
4300         (message-insert-canlock)
4301         ;; Let the user do all of the above.
4302         (run-hooks 'message-header-hook))
4303       ;; Note: This check will be disabled by the ".*" default value for
4304       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4305       (when (and group-field-charset
4306                  (listp message-syntax-checks))
4307         (setq message-syntax-checks
4308               (cons '(valid-newsgroups . disabled)
4309                     message-syntax-checks)))
4310       (message-cleanup-headers)
4311       (if (not (let ((message-post-method method))
4312                  (message-check-news-syntax)))
4313           nil
4314         (unwind-protect
4315             (save-excursion
4316               (set-buffer tembuf)
4317               (buffer-disable-undo)
4318               (erase-buffer)
4319               ;; Avoid copying text props (except hard newlines).
4320               (insert
4321                (with-current-buffer messbuf
4322                  (mml-buffer-substring-no-properties-except-hard-newlines
4323                   (point-min) (point-max))))
4324               (message-encode-message-body)
4325               ;; Remove some headers.
4326               (save-restriction
4327                 (message-narrow-to-headers)
4328                 ;; We (re)generate the Lines header.
4329                 (when (memq 'Lines message-required-mail-headers)
4330                   (message-generate-headers '(Lines)))
4331                 ;; Remove some headers.
4332                 (message-remove-header message-ignored-news-headers t)
4333                 (let ((mail-parse-charset message-default-charset))
4334                   (mail-encode-encoded-word-buffer)))
4335               (goto-char (point-max))
4336               ;; require one newline at the end.
4337               (or (= (preceding-char) ?\n)
4338                   (insert ?\n))
4339               (let ((case-fold-search t))
4340                 ;; Remove the delimiter.
4341                 (goto-char (point-min))
4342                 (re-search-forward
4343                  (concat "^" (regexp-quote mail-header-separator) "\n"))
4344                 (replace-match "\n")
4345                 (backward-char 1))
4346               (run-hooks 'message-send-news-hook)
4347               (gnus-open-server method)
4348               (message "Sending news via %s..." (gnus-server-string method))
4349               (setq result (let ((mail-header-separator ""))
4350                              (gnus-request-post method))))
4351           (kill-buffer tembuf))
4352         (set-buffer messbuf)
4353         (if result
4354             (push 'news message-sent-message-via)
4355           (message "Couldn't send message via news: %s"
4356                    (nnheader-get-report (car method)))
4357           nil)))))
4358
4359 ;;;
4360 ;;; Header generation & syntax checking.
4361 ;;;
4362
4363 (defun message-check-element (type)
4364   "Return non-nil if this TYPE is not to be checked."
4365   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4366       t
4367     (let ((able (assq type message-syntax-checks)))
4368       (and (consp able)
4369            (eq (cdr able) 'disabled)))))
4370
4371 (defun message-check-news-syntax ()
4372   "Check the syntax of the message."
4373   (save-excursion
4374     (save-restriction
4375       (widen)
4376       ;; We narrow to the headers and check them first.
4377       (save-excursion
4378         (save-restriction
4379           (message-narrow-to-headers)
4380           (message-check-news-header-syntax))))))
4381
4382 (defun message-check-news-header-syntax ()
4383   (and
4384    ;; Check Newsgroups header.
4385    (message-check 'newsgroups
4386      (let ((group (message-fetch-field "newsgroups")))
4387        (or
4388         (and group
4389              (not (string-match "\\`[ \t]*\\'" group)))
4390         (ignore
4391          (message
4392           "The newsgroups field is empty or missing.  Posting is denied.")))))
4393    ;; Check the Subject header.
4394    (message-check 'subject
4395      (let* ((case-fold-search t)
4396             (subject (message-fetch-field "subject")))
4397        (or
4398         (and subject
4399              (not (string-match "\\`[ \t]*\\'" subject)))
4400         (ignore
4401          (message
4402           "The subject field is empty or missing.  Posting is denied.")))))
4403    ;; Check for commands in Subject.
4404    (message-check 'subject-cmsg
4405      (if (string-match "^cmsg " (message-fetch-field "subject"))
4406          (y-or-n-p
4407           "The control code \"cmsg\" is in the subject.  Really post? ")
4408        t))
4409    ;; Check long header lines.
4410    (message-check 'long-header-lines
4411      (let ((start (point))
4412            (header nil)
4413            (length 0)
4414            found)
4415        (while (and (not found)
4416                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4417          (if (> (- (point) (match-beginning 0)) 998)
4418              (setq found t
4419                    length (- (point) (match-beginning 0)))
4420            (setq header (match-string-no-properties 1)))
4421          (setq start (match-beginning 0))
4422          (forward-line 1))
4423        (if found
4424            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4425                              header length))
4426          t)))
4427    ;; Check for multiple identical headers.
4428    (message-check 'multiple-headers
4429      (let (found)
4430        (while (and (not found)
4431                    (re-search-forward "^[^ \t:]+: " nil t))
4432          (save-excursion
4433            (or (re-search-forward
4434                 (concat "^"
4435                         (regexp-quote
4436                          (setq found
4437                                (buffer-substring
4438                                 (match-beginning 0) (- (match-end 0) 2))))
4439                         ":")
4440                 nil t)
4441                (setq found nil))))
4442        (if found
4443            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4444          t)))
4445    ;; Check for Version and Sendsys.
4446    (message-check 'sendsys
4447      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4448          (y-or-n-p
4449           (format "The article contains a %s command.  Really post? "
4450                   (buffer-substring (match-beginning 0)
4451                                     (1- (match-end 0)))))
4452        t))
4453    ;; See whether we can shorten Followup-To.
4454    (message-check 'shorten-followup-to
4455      (let ((newsgroups (message-fetch-field "newsgroups"))
4456            (followup-to (message-fetch-field "followup-to"))
4457            to)
4458        (when (and newsgroups
4459                   (string-match "," newsgroups)
4460                   (not followup-to)
4461                   (not
4462                    (zerop
4463                     (length
4464                      (setq to (completing-read
4465                                "Followups to (default no Followup-To header): "
4466                                (mapcar #'list
4467                                        (cons "poster"
4468                                              (message-tokenize-header
4469                                               newsgroups)))))))))
4470          (goto-char (point-min))
4471          (insert "Followup-To: " to "\n"))
4472        t))
4473    ;; Check "Shoot me".
4474    (message-check 'shoot
4475      (if (re-search-forward
4476           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4477          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4478        t))
4479    ;; Check for Approved.
4480    (message-check 'approved
4481      (if (re-search-forward "^Approved:" nil t)
4482          (y-or-n-p "The article contains an Approved header.  Really post? ")
4483        t))
4484    ;; Check the Message-ID header.
4485    (message-check 'message-id
4486      (let* ((case-fold-search t)
4487             (message-id (message-fetch-field "message-id" t)))
4488        (or (not message-id)
4489            ;; Is there an @ in the ID?
4490            (and (string-match "@" message-id)
4491                 ;; Is there a dot in the ID?
4492                 (string-match "@[^.]*\\." message-id)
4493                 ;; Does the ID end with a dot?
4494                 (not (string-match "\\.>" message-id)))
4495            (y-or-n-p
4496             (format "The Message-ID looks strange: \"%s\".  Really post? "
4497                     message-id)))))
4498    ;; Check the Newsgroups & Followup-To headers.
4499    (message-check 'existing-newsgroups
4500      (let* ((case-fold-search t)
4501             (newsgroups (message-fetch-field "newsgroups"))
4502             (followup-to (message-fetch-field "followup-to"))
4503             (groups (message-tokenize-header
4504                      (if followup-to
4505                          (concat newsgroups "," followup-to)
4506                        newsgroups)))
4507             (post-method (if (functionp message-post-method)
4508                              (funcall message-post-method)
4509                            message-post-method))
4510             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4511             ;; would probably involve a new nnoo function.
4512             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4513             (method (if (and (consp post-method)
4514                              (eq (car post-method) 'nnvirtual)
4515                              gnus-message-group-art)
4516                         (let ((group (car (nnvirtual-find-group-art
4517                                            (car gnus-message-group-art)
4518                                            (cdr gnus-message-group-art)))))
4519                           (gnus-find-method-for-group group))
4520                       post-method))
4521             (known-groups
4522              (mapcar (lambda (n)
4523                        (gnus-group-name-decode
4524                         (gnus-group-real-name n)
4525                         (gnus-group-name-charset method n)))
4526                      (gnus-groups-from-server method)))
4527             errors)
4528        (while groups
4529          (when (and (not (equal (car groups) "poster"))
4530                     (not (member (car groups) known-groups))
4531                     (not (member (car groups) errors)))
4532            (push (car groups) errors))
4533          (pop groups))
4534        (cond
4535         ;; Gnus is not running.
4536         ((or (not (and (boundp 'gnus-active-hashtb)
4537                        gnus-active-hashtb))
4538              (not (boundp 'gnus-read-active-file)))
4539          t)
4540         ;; We don't have all the group names.
4541         ((and (or (not gnus-read-active-file)
4542                   (eq gnus-read-active-file 'some))
4543               errors)
4544          (y-or-n-p
4545           (format
4546            "Really use %s possibly unknown group%s: %s? "
4547            (if (= (length errors) 1) "this" "these")
4548            (if (= (length errors) 1) "" "s")
4549            (mapconcat 'identity errors ", "))))
4550         ;; There were no errors.
4551         ((not errors)
4552          t)
4553         ;; There are unknown groups.
4554         (t
4555          (y-or-n-p
4556           (format
4557            "Really post to %s unknown group%s: %s? "
4558            (if (= (length errors) 1) "this" "these")
4559            (if (= (length errors) 1) "" "s")
4560            (mapconcat 'identity errors ", ")))))))
4561    ;; Check continuation headers.
4562    (message-check 'continuation-headers
4563      (goto-char (point-min))
4564      (let ((do-posting t))
4565        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4566          (if (y-or-n-p "Fix continuation lines? ")
4567              (progn
4568                (goto-char (match-beginning 0))
4569                (insert " "))
4570            (unless (y-or-n-p "Send anyway? ")
4571              (setq do-posting nil))))
4572        do-posting))
4573    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4574    (message-check 'valid-newsgroups
4575      (let ((case-fold-search t)
4576            (headers '("Newsgroups" "Followup-To"))
4577            header error)
4578        (while (and headers (not error))
4579          (when (setq header (mail-fetch-field (car headers)))
4580            (if (or
4581                 (not
4582                  (string-match
4583                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4584                   header))
4585                 (memq
4586                  nil (mapcar
4587                       (lambda (g)
4588                         (not (string-match "\\.\\'\\|\\.\\." g)))
4589                       (message-tokenize-header header ","))))
4590                (setq error t)))
4591          (unless error
4592            (pop headers)))
4593        (if (not error)
4594            t
4595          (y-or-n-p
4596           (format "The %s header looks odd: \"%s\".  Really post? "
4597                   (car headers) header)))))
4598    (message-check 'repeated-newsgroups
4599      (let ((case-fold-search t)
4600            (headers '("Newsgroups" "Followup-To"))
4601            header error groups group)
4602        (while (and headers
4603                    (not error))
4604          (when (setq header (mail-fetch-field (pop headers)))
4605            (setq groups (message-tokenize-header header ","))
4606            (while (setq group (pop groups))
4607              (when (member group groups)
4608                (setq error group
4609                      groups nil)))))
4610        (if (not error)
4611            t
4612          (y-or-n-p
4613           (format "Group %s is repeated in headers.  Really post? " error)))))
4614    ;; Check the From header.
4615    (message-check 'from
4616      (let* ((case-fold-search t)
4617             (from (message-fetch-field "from"))
4618             ad)
4619        (cond
4620         ((not from)
4621          (message "There is no From line.  Posting is denied.")
4622          nil)
4623         ((or (not (string-match
4624                    "@[^\\.]*\\."
4625                    (setq ad (nth 1 (mail-extract-address-components
4626                                     from))))) ;larsi@ifi
4627              (string-match "\\.\\." ad) ;larsi@ifi..uio
4628              (string-match "@\\." ad)   ;larsi@.ifi.uio
4629              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4630              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4631              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4632          (message
4633           "Denied posting -- the From looks strange: \"%s\"." from)
4634          nil)
4635         ((let ((addresses (rfc822-addresses from)))
4636            (while (and addresses
4637                        (not (eq (string-to-char (car addresses)) ?\()))
4638              (setq addresses (cdr addresses)))
4639            addresses)
4640          (message
4641           "Denied posting -- bad From address: \"%s\"." from)
4642          nil)
4643         (t t))))
4644    ;; Check the Reply-To header.
4645    (message-check 'reply-to
4646      (let* ((case-fold-search t)
4647             (reply-to (message-fetch-field "reply-to"))
4648             ad)
4649        (cond
4650         ((not reply-to)
4651          t)
4652         ((string-match "," reply-to)
4653          (y-or-n-p
4654           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4655                   reply-to)))
4656         ((or (not (string-match
4657                    "@[^\\.]*\\."
4658                    (setq ad (nth 1 (mail-extract-address-components
4659                                     reply-to))))) ;larsi@ifi
4660              (string-match "\\.\\." ad) ;larsi@ifi..uio
4661              (string-match "@\\." ad)   ;larsi@.ifi.uio
4662              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4663              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4664              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4665          (y-or-n-p
4666           (format
4667            "The Reply-To looks strange: \"%s\". Really post? "
4668            reply-to)))
4669         (t t))))))
4670
4671 (defun message-check-news-body-syntax ()
4672   (and
4673    ;; Check for long lines.
4674    (message-check 'long-lines
4675      (goto-char (point-min))
4676      (re-search-forward
4677       (concat "^" (regexp-quote mail-header-separator) "$"))
4678      (forward-line 1)
4679      (while (and
4680              (or (looking-at
4681                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
4682                  (let ((p (point)))
4683                    (end-of-line)
4684                    (< (- (point) p) 80)))
4685              (zerop (forward-line 1))))
4686      (or (bolp)
4687          (eobp)
4688          (y-or-n-p
4689           "You have lines longer than 79 characters.  Really post? ")))
4690    ;; Check whether the article is empty.
4691    (message-check 'empty
4692      (goto-char (point-min))
4693      (re-search-forward
4694       (concat "^" (regexp-quote mail-header-separator) "$"))
4695      (forward-line 1)
4696      (let ((b (point)))
4697        (goto-char (point-max))
4698        (re-search-backward message-signature-separator nil t)
4699        (beginning-of-line)
4700        (or (re-search-backward "[^ \n\t]" b t)
4701            (if (message-gnksa-enable-p 'empty-article)
4702                (y-or-n-p "Empty article.  Really post? ")
4703              (message "Denied posting -- Empty article.")
4704              nil))))
4705    ;; Check for control characters.
4706    (message-check 'control-chars
4707      (if (re-search-forward
4708           (mm-string-as-multibyte "[\000-\007\013\015-\032\034-\037\200-\237]")
4709           nil t)
4710          (y-or-n-p
4711           "The article contains control characters.  Really post? ")
4712        t))
4713    ;; Check excessive size.
4714    (message-check 'size
4715      (if (> (buffer-size) 60000)
4716          (y-or-n-p
4717           (format "The article is %d octets long.  Really post? "
4718                   (buffer-size)))
4719        t))
4720    ;; Check whether any new text has been added.
4721    (message-check 'new-text
4722      (or
4723       (not message-checksum)
4724       (not (eq (message-checksum) message-checksum))
4725       (if (message-gnksa-enable-p 'quoted-text-only)
4726           (y-or-n-p
4727            "It looks like no new text has been added.  Really post? ")
4728         (message "Denied posting -- no new text has been added.")
4729         nil)))
4730    ;; Check the length of the signature.
4731    (message-check 'signature
4732      (goto-char (point-max))
4733      (if (> (count-lines (point) (point-max)) 5)
4734          (y-or-n-p
4735           (format
4736            "Your .sig is %d lines; it should be max 4.  Really post? "
4737            (1- (count-lines (point) (point-max)))))
4738        t))
4739    ;; Ensure that text follows last quoted portion.
4740    (message-check 'quoting-style
4741      (goto-char (point-max))
4742      (let ((no-problem t))
4743        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4744          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4745        (if no-problem
4746            t
4747          (if (message-gnksa-enable-p 'quoted-text-only)
4748              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4749            ;; Ensure that
4750            (goto-char (point-min))
4751            (re-search-forward
4752             (concat "^" (regexp-quote mail-header-separator) "$"))
4753            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4754                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4755              (message "Denied posting -- only quoted text.")
4756              nil)))))))
4757
4758 (defun message-checksum ()
4759   "Return a \"checksum\" for the current buffer."
4760   (let ((sum 0))
4761     (save-excursion
4762       (goto-char (point-min))
4763       (re-search-forward
4764        (concat "^" (regexp-quote mail-header-separator) "$"))
4765       (while (not (eobp))
4766         (when (not (looking-at "[ \t\n]"))
4767           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4768                             (char-after))))
4769         (forward-char 1)))
4770     sum))
4771
4772 (defun message-do-fcc ()
4773   "Process Fcc headers in the current buffer."
4774   (let ((case-fold-search t)
4775         (buf (current-buffer))
4776         list file
4777         (mml-externalize-attachments message-fcc-externalize-attachments))
4778     (save-excursion
4779       (save-restriction
4780         (message-narrow-to-headers)
4781         (setq file (message-fetch-field "fcc" t)))
4782       (when file
4783         (set-buffer (get-buffer-create " *message temp*"))
4784         (erase-buffer)
4785         (insert-buffer-substring buf)
4786         (message-encode-message-body)
4787         (save-restriction
4788           (message-narrow-to-headers)
4789           (while (setq file (message-fetch-field "fcc" t))
4790             (push file list)
4791             (message-remove-header "fcc" nil t))
4792           (let ((mail-parse-charset message-default-charset)
4793                 (rfc2047-header-encoding-alist
4794                  (cons '("Newsgroups" . default)
4795                        rfc2047-header-encoding-alist)))
4796             (mail-encode-encoded-word-buffer)))
4797         (goto-char (point-min))
4798         (when (re-search-forward
4799                (concat "^" (regexp-quote mail-header-separator) "$")
4800                nil t)
4801           (replace-match "" t t ))
4802         ;; Process FCC operations.
4803         (while list
4804           (setq file (pop list))
4805           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4806               ;; Pipe the article to the program in question.
4807               (call-process-region (point-min) (point-max) shell-file-name
4808                                    nil nil nil shell-command-switch
4809                                    (match-string 1 file))
4810             ;; Save the article.
4811             (setq file (expand-file-name file))
4812             (unless (file-exists-p (file-name-directory file))
4813               (make-directory (file-name-directory file) t))
4814             (if (and message-fcc-handler-function
4815                      (not (eq message-fcc-handler-function 'rmail-output)))
4816                 (funcall message-fcc-handler-function file)
4817               (if (and (file-readable-p file) (mail-file-babyl-p file))
4818                   (rmail-output file 1 nil t)
4819                 (let ((mail-use-rfc822 t))
4820                   (rmail-output file 1 t t))))))
4821         (kill-buffer (current-buffer))))))
4822
4823 (defun message-output (filename)
4824   "Append this article to Unix/babyl mail file FILENAME."
4825   (if (and (file-readable-p filename)
4826            (mail-file-babyl-p filename))
4827       (gnus-output-to-rmail filename t)
4828     (gnus-output-to-mail filename t)))
4829
4830 (defun message-cleanup-headers ()
4831   "Do various automatic cleanups of the headers."
4832   ;; Remove empty lines in the header.
4833   (save-restriction
4834     (message-narrow-to-headers)
4835     ;; Remove blank lines.
4836     (while (re-search-forward "^[ \t]*\n" nil t)
4837       (replace-match "" t t))
4838
4839     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4840     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4841     ;; embedded line breaks.
4842     (goto-char (point-min))
4843     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4844       (save-restriction
4845         (narrow-to-region
4846          (point)
4847          (if (re-search-forward "^[^ \t]" nil t)
4848              (match-beginning 0)
4849            (forward-line 1)
4850            (point)))
4851         (goto-char (point-min))
4852         (while (re-search-forward "\n[ \t]+" nil t)
4853           (replace-match " " t t))     ;No line breaks (too confusing)
4854         (goto-char (point-min))
4855         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4856           (replace-match "," t t))
4857         (goto-char (point-min))
4858         ;; Remove trailing commas.
4859         (when (re-search-forward ",+$" nil t)
4860           (replace-match "" t t))))))
4861
4862 (defun message-make-date (&optional now)
4863   "Make a valid data header.
4864 If NOW, use that time instead."
4865   (let ((system-time-locale "C"))
4866     (format-time-string "%a, %d %b %Y %T %z" now)))
4867
4868 (defun message-insert-expires (days)
4869   "Insert the Expires header.  Expiry in DAYS days."
4870   (interactive "NExpire article in how many days? ")
4871   (save-excursion
4872     (message-position-on-field "Expires" "X-Draft-From")
4873     (insert (message-make-expires-date days))))
4874
4875 (defun message-make-expires-date (days)
4876   "Make date string for the Expires header.  Expiry in DAYS days.
4877
4878 In posting styles use `(\"Expires\" (make-expires-date 30))'."
4879   (let* ((cur (decode-time (current-time)))
4880          (nday (+ days (nth 3 cur))))
4881     (setf (nth 3 cur) nday)
4882     (message-make-date (apply 'encode-time cur))))
4883
4884 (defun message-make-message-id ()
4885   "Make a unique Message-ID."
4886   (concat "<" (message-unique-id)
4887           (let ((psubject (save-excursion (message-fetch-field "subject")))
4888                 (psupersedes
4889                  (save-excursion (message-fetch-field "supersedes"))))
4890             (if (or
4891                  (and message-reply-headers
4892                       (mail-header-references message-reply-headers)
4893                       (mail-header-subject message-reply-headers)
4894                       psubject
4895                       (not (string=
4896                             (message-strip-subject-re
4897                              (mail-header-subject message-reply-headers))
4898                             (message-strip-subject-re psubject))))
4899                  (and psupersedes
4900                       (string-match "_-_@" psupersedes)))
4901                 "_-_" ""))
4902           "@" (message-make-fqdn) ">"))
4903
4904 (defvar message-unique-id-char nil)
4905
4906 ;; If you ever change this function, make sure the new version
4907 ;; cannot generate IDs that the old version could.
4908 ;; You might for example insert a "." somewhere (not next to another dot
4909 ;; or string boundary), or modify the "fsf" string.
4910 (defun message-unique-id ()
4911   ;; Don't use microseconds from (current-time), they may be unsupported.
4912   ;; Instead we use this randomly inited counter.
4913   (setq message-unique-id-char
4914         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4915            ;; (current-time) returns 16-bit ints,
4916            ;; and 2^16*25 just fits into 4 digits i base 36.
4917            (* 25 25)))
4918   (let ((tm (current-time)))
4919     (concat
4920      (if (or (memq system-type '(ms-dos emx vax-vms))
4921              ;; message-number-base36 doesn't handle bigints.
4922              (floatp (user-uid)))
4923          (let ((user (downcase (user-login-name))))
4924            (while (string-match "[^a-z0-9_]" user)
4925              (aset user (match-beginning 0) ?_))
4926            user)
4927        (message-number-base36 (user-uid) -1))
4928      (message-number-base36 (+ (car tm)
4929                                (lsh (% message-unique-id-char 25) 16)) 4)
4930      (message-number-base36 (+ (nth 1 tm)
4931                                (lsh (/ message-unique-id-char 25) 16)) 4)
4932      ;; Append a given name, because while the generated ID is unique
4933      ;; to this newsreader, other newsreaders might otherwise generate
4934      ;; the same ID via another algorithm.
4935      ".fsf")))
4936
4937 (defun message-number-base36 (num len)
4938   (if (if (< len 0)
4939           (<= num 0)
4940         (= len 0))
4941       ""
4942     (concat (message-number-base36 (/ num 36) (1- len))
4943             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4944                                   (% num 36))))))
4945
4946 (defun message-make-organization ()
4947   "Make an Organization header."
4948   (let* ((organization
4949           (when message-user-organization
4950             (if (functionp message-user-organization)
4951                 (funcall message-user-organization)
4952               message-user-organization))))
4953     (with-temp-buffer
4954       (mm-enable-multibyte)
4955       (cond ((stringp organization)
4956              (insert organization))
4957             ((and (eq t organization)
4958                   message-user-organization-file
4959                   (file-exists-p message-user-organization-file))
4960              (insert-file-contents message-user-organization-file)))
4961       (goto-char (point-min))
4962       (while (re-search-forward "[\t\n]+" nil t)
4963         (replace-match "" t t))
4964       (unless (zerop (buffer-size))
4965         (buffer-string)))))
4966
4967 (defun message-make-lines ()
4968   "Count the number of lines and return numeric string."
4969   (save-excursion
4970     (save-restriction
4971       (widen)
4972       (message-goto-body)
4973       (int-to-string (count-lines (point) (point-max))))))
4974
4975 (defun message-make-references ()
4976   "Return the References header for this message."
4977   (when message-reply-headers
4978     (let ((message-id (mail-header-message-id message-reply-headers))
4979           (references (mail-header-references message-reply-headers))
4980           new-references)
4981       (if (or references message-id)
4982           (concat (or references "") (and references " ")
4983                   (or message-id ""))
4984         nil))))
4985
4986 (defun message-make-in-reply-to ()
4987   "Return the In-Reply-To header for this message."
4988   (when message-reply-headers
4989     (let ((from (mail-header-from message-reply-headers))
4990           (date (mail-header-date message-reply-headers))
4991           (msg-id (mail-header-message-id message-reply-headers)))
4992       (when from
4993         (let ((name (mail-extract-address-components from)))
4994           (concat msg-id (if msg-id " (")
4995                   (or (car name)
4996                       (nth 1 name))
4997                   "'s message of \""
4998                   (if (or (not date) (string= date ""))
4999                       "(unknown date)" date)
5000                   "\"" (if msg-id ")")))))))
5001
5002 (defun message-make-distribution ()
5003   "Make a Distribution header."
5004   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5005     (cond ((functionp message-distribution-function)
5006            (funcall message-distribution-function))
5007           (t orig-distribution))))
5008
5009 (defun message-make-expires ()
5010   "Return an Expires header based on `message-expires'."
5011   (let ((current (current-time))
5012         (future (* 1.0 message-expires 60 60 24)))
5013     ;; Add the future to current.
5014     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5015     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5016     (message-make-date current)))
5017
5018 (defun message-make-path ()
5019   "Return uucp path."
5020   (let ((login-name (user-login-name)))
5021     (cond ((null message-user-path)
5022            (concat (system-name) "!" login-name))
5023           ((stringp message-user-path)
5024            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5025            (concat message-user-path "!" login-name))
5026           (t login-name))))
5027
5028 (defun message-make-from ()
5029   "Make a From header."
5030   (let* ((style message-from-style)
5031          (login (message-make-address))
5032          (fullname
5033           (or (and (boundp 'user-full-name)
5034                    user-full-name)
5035               (user-full-name))))
5036     (when (string= fullname "&")
5037       (setq fullname (user-login-name)))
5038     (with-temp-buffer
5039       (mm-enable-multibyte)
5040       (cond
5041        ((or (null style)
5042             (equal fullname ""))
5043         (insert login))
5044        ((or (eq style 'angles)
5045             (and (not (eq style 'parens))
5046                  ;; Use angles if no quoting is needed, or if parens would
5047                  ;; need quoting too.
5048                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5049                      (let ((tmp (concat fullname nil)))
5050                        (while (string-match "([^()]*)" tmp)
5051                          (aset tmp (match-beginning 0) ?-)
5052                          (aset tmp (1- (match-end 0)) ?-))
5053                        (string-match "[\\()]" tmp)))))
5054         (insert fullname)
5055         (goto-char (point-min))
5056         ;; Look for a character that cannot appear unquoted
5057         ;; according to RFC 822.
5058         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5059           ;; Quote fullname, escaping specials.
5060           (goto-char (point-min))
5061           (insert "\"")
5062           (while (re-search-forward "[\"\\]" nil 1)
5063             (replace-match "\\\\\\&" t))
5064           (insert "\""))
5065         (insert " <" login ">"))
5066        (t                               ; 'parens or default
5067         (insert login " (")
5068         (let ((fullname-start (point)))
5069           (insert fullname)
5070           (goto-char fullname-start)
5071           ;; RFC 822 says \ and nonmatching parentheses
5072           ;; must be escaped in comments.
5073           ;; Escape every instance of ()\ ...
5074           (while (re-search-forward "[()\\]" nil 1)
5075             (replace-match "\\\\\\&" t))
5076           ;; ... then undo escaping of matching parentheses,
5077           ;; including matching nested parentheses.
5078           (goto-char fullname-start)
5079           (while (re-search-forward
5080                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5081                   nil 1)
5082             (replace-match "\\1(\\3)" t)
5083             (goto-char fullname-start)))
5084         (insert ")")))
5085       (buffer-string))))
5086
5087 (defun message-make-sender ()
5088   "Return the \"real\" user address.
5089 This function tries to ignore all user modifications, and
5090 give as trustworthy answer as possible."
5091   (concat (user-login-name) "@" (system-name)))
5092
5093 (defun message-make-address ()
5094   "Make the address of the user."
5095   (or (message-user-mail-address)
5096       (concat (user-login-name) "@" (message-make-domain))))
5097
5098 (defun message-user-mail-address ()
5099   "Return the pertinent part of `user-mail-address'."
5100   (when (and user-mail-address
5101              (string-match "@.*\\." user-mail-address))
5102     (if (string-match " " user-mail-address)
5103         (nth 1 (mail-extract-address-components user-mail-address))
5104       user-mail-address)))
5105
5106 (defun message-sendmail-envelope-from ()
5107   "Return the envelope from."
5108   (cond ((eq message-sendmail-envelope-from 'header)
5109          (nth 1 (mail-extract-address-components
5110                  (message-fetch-field "from"))))
5111         ((stringp message-sendmail-envelope-from)
5112          message-sendmail-envelope-from)
5113         (t
5114          (message-make-address))))
5115
5116 (defun message-make-fqdn ()
5117   "Return user's fully qualified domain name."
5118   (let* ((system-name (system-name))
5119          (user-mail (message-user-mail-address))
5120          (user-domain
5121           (if (and user-mail
5122                    (string-match "@\\(.*\\)\\'" user-mail))
5123               (match-string 1 user-mail)))
5124          (case-fold-search t))
5125     (cond
5126      ((and message-user-fqdn
5127            (stringp message-user-fqdn)
5128            (string-match message-valid-fqdn-regexp message-user-fqdn)
5129            (not (string-match message-bogus-system-names message-user-fqdn)))
5130       message-user-fqdn)
5131      ;; `message-user-fqdn' seems to be valid
5132      ((and (string-match message-valid-fqdn-regexp system-name)
5133            (not (string-match message-bogus-system-names system-name)))
5134       ;; `system-name' returned the right result.
5135       system-name)
5136      ;; Try `mail-host-address'.
5137      ((and (boundp 'mail-host-address)
5138            (stringp mail-host-address)
5139            (string-match message-valid-fqdn-regexp mail-host-address)
5140            (not (string-match message-bogus-system-names mail-host-address)))
5141       mail-host-address)
5142      ;; We try `user-mail-address' as a backup.
5143      ((and user-domain
5144            (stringp user-domain)
5145            (string-match message-valid-fqdn-regexp user-domain)
5146            (not (string-match message-bogus-system-names user-domain)))
5147       user-domain)
5148      ;; Default to this bogus thing.
5149      (t
5150       (concat system-name
5151               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5152
5153 (defun message-make-host-name ()
5154   "Return the name of the host."
5155   (let ((fqdn (message-make-fqdn)))
5156     (string-match "^[^.]+\\." fqdn)
5157     (substring fqdn 0 (1- (match-end 0)))))
5158
5159 (defun message-make-domain ()
5160   "Return the domain name."
5161   (or mail-host-address
5162       (message-make-fqdn)))
5163
5164 (defun message-to-list-only ()
5165   "Send a message to the list only.
5166 Remove all addresses but the list address from To and Cc headers."
5167   (interactive)
5168   (let ((listaddr (message-make-mail-followup-to t)))
5169     (when listaddr
5170       (save-excursion
5171         (message-remove-header "to")
5172         (message-remove-header "cc")
5173         (message-position-on-field "To" "X-Draft-From")
5174         (insert listaddr)))))
5175
5176 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5177   "Return the Mail-Followup-To header.
5178 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5179 subscribed address (and not the additional To and Cc header contents)."
5180   (let* ((case-fold-search t)
5181          (to (message-fetch-field "To"))
5182          (cc (message-fetch-field "cc"))
5183          (msg-recipients (concat to (and to cc ", ") cc))
5184          (recipients
5185           (mapcar 'mail-strip-quoted-names
5186                   (message-tokenize-header msg-recipients)))
5187          (file-regexps
5188           (if message-subscribed-address-file
5189               (let (begin end item re)
5190                 (save-excursion
5191                   (with-temp-buffer
5192                     (insert-file-contents message-subscribed-address-file)
5193                     (while (not (eobp))
5194                       (setq begin (point))
5195                       (forward-line 1)
5196                       (setq end (point))
5197                       (if (bolp) (setq end (1- end)))
5198                       (setq item (regexp-quote (buffer-substring begin end)))
5199                       (if re (setq re (concat re "\\|" item))
5200                         (setq re (concat "\\`\\(" item))))
5201                     (and re (list (concat re "\\)\\'"))))))))
5202          (mft-regexps (apply 'append message-subscribed-regexps
5203                              (mapcar 'regexp-quote
5204                                      message-subscribed-addresses)
5205                              file-regexps
5206                              (mapcar 'funcall
5207                                      message-subscribed-address-functions))))
5208     (save-match-data
5209       (let ((subscribed-lists nil)
5210             (list
5211              (loop for recipient in recipients
5212                when (loop for regexp in mft-regexps
5213                       when (string-match regexp recipient) return t)
5214                return recipient)))
5215         (when list
5216           (if only-show-subscribed
5217               list
5218             msg-recipients))))))
5219
5220 (defun message-idna-to-ascii-rhs-1 (header)
5221   "Interactively potentially IDNA encode domain names in HEADER."
5222   (let ((field (message-fetch-field header))
5223         rhs ace  address)
5224     (when field
5225       (dolist (rhs
5226                (mm-delete-duplicates
5227                 (mapcar (lambda (rhs) (or (cadr (split-string rhs "@")) ""))
5228                         (mapcar 'downcase
5229                                 (mapcar
5230                                  'car (mail-header-parse-addresses field))))))
5231         (setq ace (downcase (idna-to-ascii rhs)))
5232         (when (and (not (equal rhs ace))
5233                    (or (not (eq message-use-idna 'ask))
5234                        (y-or-n-p (format "Replace %s with %s in %s:? "
5235                                          rhs ace header))))
5236           (goto-char (point-min))
5237           (while (re-search-forward (concat "^" header ":") nil t)
5238             (message-narrow-to-field)
5239             (while (search-forward (concat "@" rhs) nil t)
5240               (replace-match (concat "@" ace) t t))
5241             (goto-char (point-max))
5242             (widen)))))))
5243
5244 (defun message-idna-to-ascii-rhs ()
5245   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5246 See `message-idna-encode'."
5247   (interactive)
5248   (when message-use-idna
5249     (save-excursion
5250       (save-restriction
5251         (message-narrow-to-head)
5252         (message-idna-to-ascii-rhs-1 "From")
5253         (message-idna-to-ascii-rhs-1 "To")
5254         (message-idna-to-ascii-rhs-1 "Reply-To")
5255         (message-idna-to-ascii-rhs-1 "Mail-Reply-To")
5256         (message-idna-to-ascii-rhs-1 "Mail-Followup-To")
5257         (message-idna-to-ascii-rhs-1 "Cc")))))
5258
5259 (defun message-generate-headers (headers)
5260   "Prepare article HEADERS.
5261 Headers already prepared in the buffer are not modified."
5262   (setq headers (append headers message-required-headers))
5263   (save-restriction
5264     (message-narrow-to-headers)
5265     (let* ((Date (message-make-date))
5266            (Message-ID (message-make-message-id))
5267            (Organization (message-make-organization))
5268            (From (message-make-from))
5269            (Path (message-make-path))
5270            (Subject nil)
5271            (Newsgroups nil)
5272            (In-Reply-To (message-make-in-reply-to))
5273            (References (message-make-references))
5274            (To nil)
5275            (Distribution (message-make-distribution))
5276            (Lines (message-make-lines))
5277            (User-Agent message-newsreader)
5278            (Expires (message-make-expires))
5279            (case-fold-search t)
5280            (optionalp nil)
5281            header value elem header-string)
5282       ;; First we remove any old generated headers.
5283       (let ((headers message-deletable-headers))
5284         (unless (buffer-modified-p)
5285           (setq headers (delq 'Message-ID (copy-sequence headers))))
5286         (while headers
5287           (goto-char (point-min))
5288           (and (re-search-forward
5289                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5290                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5291                (message-delete-line))
5292           (pop headers)))
5293       ;; Go through all the required headers and see if they are in the
5294       ;; articles already.  If they are not, or are empty, they are
5295       ;; inserted automatically - except for Subject, Newsgroups and
5296       ;; Distribution.
5297       (while headers
5298         (goto-char (point-min))
5299         (setq elem (pop headers))
5300         (if (consp elem)
5301             (if (eq (car elem) 'optional)
5302                 (setq header (cdr elem)
5303                       optionalp t)
5304               (setq header (car elem)))
5305           (setq header elem))
5306         (setq header-string  (if (stringp header)
5307                                  header
5308                                (symbol-name header)))
5309         (when (or (not (re-search-forward
5310                         (concat "^"
5311                                 (regexp-quote (downcase header-string))
5312                                 ":")
5313                         nil t))
5314                   (progn
5315                     ;; The header was found.  We insert a space after the
5316                     ;; colon, if there is none.
5317                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5318                     ;; Find out whether the header is empty.
5319                     (looking-at "[ \t]*\n[^ \t]")))
5320           ;; So we find out what value we should insert.
5321           (setq value
5322                 (cond
5323                  ((and (consp elem)
5324                        (eq (car elem) 'optional)
5325                        (not (member header-string message-inserted-headers)))
5326                   ;; This is an optional header.  If the cdr of this
5327                   ;; is something that is nil, then we do not insert
5328                   ;; this header.
5329                   (setq header (cdr elem))
5330                   (or (and (functionp (cdr elem))
5331                            (funcall (cdr elem)))
5332                       (and (boundp (cdr elem))
5333                            (symbol-value (cdr elem)))))
5334                  ((consp elem)
5335                   ;; The element is a cons.  Either the cdr is a
5336                   ;; string to be inserted verbatim, or it is a
5337                   ;; function, and we insert the value returned from
5338                   ;; this function.
5339                   (or (and (stringp (cdr elem))
5340                            (cdr elem))
5341                       (and (functionp (cdr elem))
5342                            (funcall (cdr elem)))))
5343                  ((and (boundp header)
5344                        (symbol-value header))
5345                   ;; The element is a symbol.  We insert the value
5346                   ;; of this symbol, if any.
5347                   (symbol-value header))
5348                  ((not (message-check-element
5349                         (intern (downcase (symbol-name header)))))
5350                   ;; We couldn't generate a value for this header,
5351                   ;; so we just ask the user.
5352                   (read-from-minibuffer
5353                    (format "Empty header for %s; enter value: " header)))))
5354           ;; Finally insert the header.
5355           (when (and value
5356                      (not (equal value "")))
5357             (save-excursion
5358               (if (bolp)
5359                   (progn
5360                     ;; This header didn't exist, so we insert it.
5361                     (goto-char (point-max))
5362                     (let ((formatter
5363                            (cdr (assq header message-header-format-alist))))
5364                       (if formatter
5365                           (funcall formatter header value)
5366                         (insert header-string ": " value))
5367                       (goto-char (message-fill-field))
5368                       ;; We check whether the value was ended by a
5369                       ;; newline.  If not, we insert one.
5370                       (unless (bolp)
5371                         (insert "\n"))
5372                       (forward-line -1)))
5373                 ;; The value of this header was empty, so we clear
5374                 ;; totally and insert the new value.
5375                 (delete-region (point) (point-at-eol))
5376                 ;; If the header is optional, and the header was
5377                 ;; empty, we can't insert it anyway.
5378                 (unless optionalp
5379                   (push header-string message-inserted-headers)
5380                   (insert value)
5381                   (message-fill-field)))
5382               ;; Add the deletable property to the headers that require it.
5383               (and (memq header message-deletable-headers)
5384                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5385                    (add-text-properties
5386                     (point) (match-end 0)
5387                     '(message-deletable t face italic) (current-buffer)))))))
5388       ;; Insert new Sender if the From is strange.
5389       (let ((from (message-fetch-field "from"))
5390             (sender (message-fetch-field "sender"))
5391             (secure-sender (message-make-sender)))
5392         (when (and from
5393                    (not (message-check-element 'sender))
5394                    (not (string=
5395                          (downcase
5396                           (cadr (mail-extract-address-components from)))
5397                          (downcase secure-sender)))
5398                    (or (null sender)
5399                        (not
5400                         (string=
5401                          (downcase
5402                           (cadr (mail-extract-address-components sender)))
5403                          (downcase secure-sender)))))
5404           (goto-char (point-min))
5405           ;; Rename any old Sender headers to Original-Sender.
5406           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5407             (beginning-of-line)
5408             (insert "Original-")
5409             (beginning-of-line))
5410           (when (or (message-news-p)
5411                     (string-match "@.+\\.." secure-sender))
5412             (insert "Sender: " secure-sender "\n"))))
5413       ;; Check for IDNA
5414       (message-idna-to-ascii-rhs))))
5415
5416 (defun message-insert-courtesy-copy ()
5417   "Insert a courtesy message in mail copies of combined messages."
5418   (let (newsgroups)
5419     (save-excursion
5420       (save-restriction
5421         (message-narrow-to-headers)
5422         (when (setq newsgroups (message-fetch-field "newsgroups"))
5423           (goto-char (point-max))
5424           (insert "Posted-To: " newsgroups "\n")))
5425       (forward-line 1)
5426       (when message-courtesy-message
5427         (cond
5428          ((string-match "%s" message-courtesy-message)
5429           (insert (format message-courtesy-message newsgroups)))
5430          (t
5431           (insert message-courtesy-message)))))))
5432
5433 ;;;
5434 ;;; Setting up a message buffer
5435 ;;;
5436
5437 (defun message-skip-to-next-address ()
5438   (let ((end (save-excursion
5439                (message-next-header)
5440                (point)))
5441         quoted char)
5442     (when (looking-at ",")
5443       (forward-char 1))
5444     (while (and (not (= (point) end))
5445                 (or (not (eq char ?,))
5446                     quoted))
5447       (skip-chars-forward "^,\"" (point-max))
5448       (when (eq (setq char (following-char)) ?\")
5449         (setq quoted (not quoted)))
5450       (unless (= (point) end)
5451         (forward-char 1)))
5452     (skip-chars-forward " \t\n")))
5453
5454 (defun message-fill-address (header value)
5455   (insert (capitalize (symbol-name header))
5456           ": "
5457           (if (consp value) (car value) value)
5458           "\n")
5459   (message-fill-field-address))
5460
5461 (defun message-split-line ()
5462   "Split current line, moving portion beyond point vertically down.
5463 If the current line has `message-yank-prefix', insert it on the new line."
5464   (interactive "*")
5465   (condition-case nil
5466       (split-line message-yank-prefix) ;; Emacs 22.1+ supports arg.
5467     (error
5468      (split-line))))
5469
5470 (defun message-insert-header (header value)
5471   (insert (capitalize (symbol-name header))
5472           ": "
5473           (if (consp value) (car value) value)))
5474
5475 (defun message-field-name ()
5476   (save-excursion
5477     (goto-char (point-min))
5478     (when (looking-at "\\([^:]+\\):")
5479       (intern (capitalize (match-string 1))))))
5480
5481 (defun message-fill-field ()
5482   (save-excursion
5483     (save-restriction
5484       (message-narrow-to-field)
5485       (let ((field-name (message-field-name)))
5486         (funcall (or (cadr (assq field-name message-field-fillers))
5487                      'message-fill-field-general)))
5488       (point-max))))
5489
5490 (defun message-fill-field-address ()
5491   (while (not (eobp))
5492     (message-skip-to-next-address)
5493     (let (last)
5494       (if (and (> (current-column) 78)
5495                last)
5496           (progn
5497             (save-excursion
5498               (goto-char last)
5499               (insert "\n\t"))
5500             (setq last (1+ (point))))
5501         (setq last (1+ (point)))))))
5502
5503 (defun message-fill-field-general ()
5504   (let ((begin (point))
5505         (fill-column 78)
5506         (fill-prefix "\t"))
5507     (while (and (search-forward "\n" nil t)
5508                 (not (eobp)))
5509       (replace-match " " t t))
5510     (fill-region-as-paragraph begin (point-max))
5511     ;; Tapdance around looong Message-IDs.
5512     (forward-line -1)
5513     (when (looking-at "[ \t]*$")
5514       (message-delete-line))
5515     (goto-char begin)
5516     (search-forward ":" nil t)
5517     (when (looking-at "\n[ \t]+")
5518       (replace-match " " t t))
5519     (goto-char (point-max))))
5520
5521 (defun message-shorten-1 (list cut surplus)
5522   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5523   (setcdr (nthcdr (- cut 2) list)
5524           (nthcdr (+ (- cut 2) surplus 1) list)))
5525
5526 (defun message-shorten-references (header references)
5527   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5528 When sending via news, also check that the REFERENCES are less
5529 than 988 characters long, and if they are not, trim them until
5530 they are."
5531   (let ((maxcount 21)
5532         (count 0)
5533         (cut 2)
5534         refs)
5535     (with-temp-buffer
5536       (insert references)
5537       (goto-char (point-min))
5538       ;; Cons a list of valid references.
5539       (while (re-search-forward "<[^>]+>" nil t)
5540         (push (match-string 0) refs))
5541       (setq refs (nreverse refs)
5542             count (length refs)))
5543
5544     ;; If the list has more than MAXCOUNT elements, trim it by
5545     ;; removing the CUTth element and the required number of
5546     ;; elements that follow.
5547     (when (> count maxcount)
5548       (let ((surplus (- count maxcount)))
5549         (message-shorten-1 refs cut surplus)
5550         (decf count surplus)))
5551
5552     ;; When sending via news, make sure the total folded length will
5553     ;; be less than 998 characters.  This is to cater to broken INN
5554     ;; 2.3 which counts the total number of characters in a header
5555     ;; rather than the physical line length of each line, as it should.
5556     ;;
5557     ;; This hack should be removed when it's believed than INN 2.3 is
5558     ;; no longer widely used.
5559     ;;
5560     ;; At this point the headers have not been generated, thus we use
5561     ;; message-this-is-news directly.
5562     (when message-this-is-news
5563       (while (< 998
5564                 (with-temp-buffer
5565                   (message-insert-header
5566                    header (mapconcat #'identity refs " "))
5567                   (buffer-size)))
5568         (message-shorten-1 refs cut 1)))
5569     ;; Finally, collect the references back into a string and insert
5570     ;; it into the buffer.
5571     (message-insert-header header (mapconcat #'identity refs " "))))
5572
5573 (defun message-position-point ()
5574   "Move point to where the user probably wants to find it."
5575   (message-narrow-to-headers)
5576   (cond
5577    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5578     (search-backward ":" )
5579     (widen)
5580     (forward-char 1)
5581     (if (eq (char-after) ? )
5582         (forward-char 1)
5583       (insert " ")))
5584    (t
5585     (goto-char (point-max))
5586     (widen)
5587     (forward-line 1)
5588     (unless (looking-at "$")
5589       (forward-line 2)))
5590    (sit-for 0)))
5591
5592 (defcustom message-beginning-of-line t
5593   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5594  goes to beginning of header values."
5595   :version "22.1"
5596   :group 'message-buffers
5597   :link '(custom-manual "(message)Movement")
5598   :type 'boolean)
5599
5600 (defun message-beginning-of-line (&optional n)
5601   "Move point to beginning of header value or to beginning of line.
5602 The prefix argument N is passed directly to `beginning-of-line'.
5603
5604 This command is identical to `beginning-of-line' if point is
5605 outside the message header or if the option `message-beginning-of-line'
5606 is nil.
5607
5608 If point is in the message header and on a (non-continued) header
5609 line, move point to the beginning of the header value or the beginning of line,
5610 whichever is closer.  If point is already at beginning of line, move point to
5611 beginning of header value.  Therefore, repeated calls will toggle point
5612 between beginning of field and beginning of line."
5613   (interactive "p")
5614   (let ((zrs 'zmacs-region-stays))
5615     (when (and (interactive-p) (boundp zrs))
5616       (set zrs t)))
5617   (if (and message-beginning-of-line
5618            (message-point-in-header-p))
5619       (let* ((here (point))
5620              (bol (progn (beginning-of-line n) (point)))
5621              (eol (point-at-eol))
5622              (eoh (re-search-forward ": *" eol t)))
5623         (goto-char
5624          (if (and eoh (or (< eoh here) (= bol here)))
5625              eoh bol)))
5626     (beginning-of-line n)))
5627
5628 (defun message-buffer-name (type &optional to group)
5629   "Return a new (unique) buffer name based on TYPE and TO."
5630   (cond
5631    ;; Generate a new buffer name The Message Way.
5632    ((eq message-generate-new-buffers 'unique)
5633     (generate-new-buffer-name
5634      (concat "*" type
5635              (if to
5636                  (concat " to "
5637                          (or (car (mail-extract-address-components to))
5638                              to) "")
5639                "")
5640              (if (and group (not (string= group ""))) (concat " on " group) "")
5641              "*")))
5642    ;; Check whether `message-generate-new-buffers' is a function,
5643    ;; and if so, call it.
5644    ((functionp message-generate-new-buffers)
5645     (funcall message-generate-new-buffers type to group))
5646    ((eq message-generate-new-buffers 'unsent)
5647     (generate-new-buffer-name
5648      (concat "*unsent " type
5649              (if to
5650                  (concat " to "
5651                          (or (car (mail-extract-address-components to))
5652                              to) "")
5653                "")
5654              (if (and group (not (string= group ""))) (concat " on " group) "")
5655              "*")))
5656    ;; Use standard name.
5657    (t
5658     (format "*%s message*" type))))
5659
5660 (defun message-pop-to-buffer (name)
5661   "Pop to buffer NAME, and warn if it already exists and is modified."
5662   (let ((buffer (get-buffer name)))
5663     (if (and buffer
5664              (buffer-name buffer))
5665         (progn
5666           (set-buffer (pop-to-buffer buffer))
5667           (when (and (buffer-modified-p)
5668                      (not (y-or-n-p
5669                            "Message already being composed; erase? ")))
5670             (error "Message being composed")))
5671       (set-buffer (pop-to-buffer name)))
5672     (erase-buffer)
5673     (message-mode)))
5674
5675 (defun message-do-send-housekeeping ()
5676   "Kill old message buffers."
5677   ;; We might have sent this buffer already.  Delete it from the
5678   ;; list of buffers.
5679   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5680   (while (and message-max-buffers
5681               message-buffer-list
5682               (>= (length message-buffer-list) message-max-buffers))
5683     ;; Kill the oldest buffer -- unless it has been changed.
5684     (let ((buffer (pop message-buffer-list)))
5685       (when (and (buffer-name buffer)
5686                  (not (buffer-modified-p buffer)))
5687         (kill-buffer buffer))))
5688   ;; Rename the buffer.
5689   (if message-send-rename-function
5690       (funcall message-send-rename-function)
5691     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5692     (when (string-match
5693            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5694            (buffer-name))
5695       (let ((name (match-string 2 (buffer-name)))
5696             to group)
5697         (if (not (or (null name)
5698                      (string-equal name "mail")
5699                      (string-equal name "posting")))
5700             (setq name (concat "*sent " name "*"))
5701           (message-narrow-to-headers)
5702           (setq to (message-fetch-field "to"))
5703           (setq group (message-fetch-field "newsgroups"))
5704           (widen)
5705           (setq name
5706                 (cond
5707                  (to (concat "*sent mail to "
5708                              (or (car (mail-extract-address-components to))
5709                                  to) "*"))
5710                  ((and group (not (string= group "")))
5711                   (concat "*sent posting on " group "*"))
5712                  (t "*sent mail*"))))
5713         (unless (string-equal name (buffer-name))
5714           (rename-buffer name t)))))
5715   ;; Push the current buffer onto the list.
5716   (when message-max-buffers
5717     (setq message-buffer-list
5718           (nconc message-buffer-list (list (current-buffer))))))
5719
5720 (defun message-mail-user-agent ()
5721   (let ((mua (cond
5722               ((not message-mail-user-agent) nil)
5723               ((eq message-mail-user-agent t) mail-user-agent)
5724               (t message-mail-user-agent))))
5725     (if (memq mua '(message-user-agent gnus-user-agent))
5726         nil
5727       mua)))
5728
5729 (defun message-setup (headers &optional replybuffer actions switch-function)
5730   (let ((mua (message-mail-user-agent))
5731         subject to field yank-action)
5732     (if (not (and message-this-is-mail mua))
5733         (message-setup-1 headers replybuffer actions)
5734       (if replybuffer
5735           (setq yank-action (list 'insert-buffer replybuffer)))
5736       (setq headers (copy-sequence headers))
5737       (setq field (assq 'Subject headers))
5738       (when field
5739         (setq subject (cdr field))
5740         (setq headers (delq field headers)))
5741       (setq field (assq 'To headers))
5742       (when field
5743         (setq to (cdr field))
5744         (setq headers (delq field headers)))
5745       (let ((mail-user-agent mua))
5746         (compose-mail to subject
5747                       (mapcar (lambda (item)
5748                                 (cons
5749                                  (format "%s" (car item))
5750                                  (cdr item)))
5751                               headers)
5752                       nil switch-function yank-action actions)))))
5753
5754 (defun message-headers-to-generate (headers included-headers excluded-headers)
5755   "Return a list that includes all headers from HEADERS.
5756 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5757 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5758 are not included."
5759   (let ((result nil)
5760         header-name)
5761     (dolist (header headers)
5762       (setq header-name (cond
5763                          ((and (consp header)
5764                                (eq (car header) 'optional))
5765                           ;; On the form (optional . Header)
5766                           (cdr header))
5767                          ((consp header)
5768                           ;; On the form (Header . function)
5769                           (car header))
5770                          (t
5771                           ;; Just a Header.
5772                           header)))
5773       (when (and (not (memq header-name excluded-headers))
5774                  (or (eq included-headers t)
5775                      (memq header-name included-headers)))
5776         (push header result)))
5777     (nreverse result)))
5778
5779 (defun message-setup-1 (headers &optional replybuffer actions)
5780   (dolist (action actions)
5781     (condition-case nil
5782         (add-to-list 'message-send-actions
5783                      `(apply ',(car action) ',(cdr action)))))
5784   (setq message-reply-buffer replybuffer)
5785   (goto-char (point-min))
5786   ;; Insert all the headers.
5787   (mail-header-format
5788    (let ((h headers)
5789          (alist message-header-format-alist))
5790      (while h
5791        (unless (assq (caar h) message-header-format-alist)
5792          (push (list (caar h)) alist))
5793        (pop h))
5794      alist)
5795    headers)
5796   (delete-region (point) (progn (forward-line -1) (point)))
5797   (when message-default-headers
5798     (insert message-default-headers)
5799     (or (bolp) (insert ?\n)))
5800   (insert mail-header-separator "\n")
5801   (forward-line -1)
5802   (when (message-news-p)
5803     (when message-default-news-headers
5804       (insert message-default-news-headers)
5805       (or (bolp) (insert ?\n)))
5806     (when message-generate-headers-first
5807       (message-generate-headers
5808        (message-headers-to-generate
5809         (append message-required-news-headers
5810                 message-required-headers)
5811         message-generate-headers-first
5812         '(Lines Subject)))))
5813   (when (message-mail-p)
5814     (when message-default-mail-headers
5815       (insert message-default-mail-headers)
5816       (or (bolp) (insert ?\n)))
5817     (when message-generate-headers-first
5818       (message-generate-headers
5819        (message-headers-to-generate
5820         (append message-required-mail-headers
5821                 message-required-headers)
5822         message-generate-headers-first
5823         '(Lines Subject)))))
5824   (run-hooks 'message-signature-setup-hook)
5825   (message-insert-signature)
5826   (save-restriction
5827     (message-narrow-to-headers)
5828     (run-hooks 'message-header-setup-hook))
5829   (set-buffer-modified-p nil)
5830   (setq buffer-undo-list nil)
5831   (when message-generate-hashcash
5832     ;; Generate hashcash headers for recipients already known
5833     (mail-add-payment-async))
5834   (run-hooks 'message-setup-hook)
5835   ;; Do this last to give it precedence over posting styles, etc.
5836   (when (message-mail-p)
5837     (save-restriction
5838       (message-narrow-to-headers)
5839       (if message-alternative-emails
5840           (message-use-alternative-email-as-from))))
5841   (message-position-point)
5842   (undo-boundary))
5843
5844 (defun message-set-auto-save-file-name ()
5845   "Associate the message buffer with a file in the drafts directory."
5846   (when message-auto-save-directory
5847     (unless (file-directory-p
5848              (directory-file-name message-auto-save-directory))
5849       (make-directory message-auto-save-directory t))
5850     (if (gnus-alive-p)
5851         (setq message-draft-article
5852               (nndraft-request-associate-buffer "drafts"))
5853       (setq buffer-file-name (expand-file-name
5854                               (if (memq system-type
5855                                         '(ms-dos ms-windows windows-nt
5856                                                  cygwin cygwin32 win32 w32
5857                                                  mswindows))
5858                                   "message"
5859                                 "*message*")
5860                               message-auto-save-directory))
5861       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5862     (clear-visited-file-modtime)
5863     (setq buffer-file-coding-system message-draft-coding-system)))
5864
5865 (defun message-disassociate-draft ()
5866   "Disassociate the message buffer from the drafts directory."
5867   (when message-draft-article
5868     (nndraft-request-expire-articles
5869      (list message-draft-article) "drafts" nil t)))
5870
5871 (defun message-insert-headers ()
5872   "Generate the headers for the article."
5873   (interactive)
5874   (save-excursion
5875     (save-restriction
5876       (message-narrow-to-headers)
5877       (when (message-news-p)
5878         (message-generate-headers
5879          (delq 'Lines
5880                (delq 'Subject
5881                      (copy-sequence message-required-news-headers)))))
5882       (when (message-mail-p)
5883         (message-generate-headers
5884          (delq 'Lines
5885                (delq 'Subject
5886                      (copy-sequence message-required-mail-headers))))))))
5887
5888 \f
5889
5890 ;;;
5891 ;;; Commands for interfacing with message
5892 ;;;
5893
5894 ;;;###autoload
5895 (defun message-mail (&optional to subject
5896                                other-headers continue switch-function
5897                                yank-action send-actions)
5898   "Start editing a mail message to be sent.
5899 OTHER-HEADERS is an alist of header/value pairs."
5900   (interactive)
5901   (let ((message-this-is-mail t) replybuffer)
5902     (unless (message-mail-user-agent)
5903       (message-pop-to-buffer (message-buffer-name "mail" to)))
5904     ;; FIXME: message-mail should do something if YANK-ACTION is not
5905     ;; insert-buffer.
5906     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5907          (setq replybuffer (nth 1 yank-action)))
5908     (message-setup
5909      (nconc
5910       `((To . ,(or to "")) (Subject . ,(or subject "")))
5911       (when other-headers other-headers))
5912      replybuffer send-actions)
5913     ;; FIXME: Should return nil if failure.
5914     t))
5915
5916 ;;;###autoload
5917 (defun message-news (&optional newsgroups subject)
5918   "Start editing a news article to be sent."
5919   (interactive)
5920   (let ((message-this-is-news t))
5921     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5922     (message-setup `((Newsgroups . ,(or newsgroups ""))
5923                      (Subject . ,(or subject ""))))))
5924
5925 (defun message-get-reply-headers (wide &optional to-address address-headers)
5926   (let (follow-to mct never-mct to cc author mft recipients extra)
5927     ;; Find all relevant headers we need.
5928     (save-restriction
5929       (message-narrow-to-headers-or-head)
5930       ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
5931       ;; message-header-synonyms.
5932       (setq to (or (message-fetch-field "to")
5933                    (and (loop for synonym in message-header-synonyms
5934                               when (memq 'Original-To synonym)
5935                               return t)
5936                         (message-fetch-field "original-to")))
5937             cc (message-fetch-field "cc")
5938             extra (when message-extra-wide-headers
5939                     (mapconcat 'identity
5940                                (mapcar 'message-fetch-field
5941                                        message-extra-wide-headers)
5942                                ", "))
5943             mct (message-fetch-field "mail-copies-to")
5944             author (or (message-fetch-field "mail-reply-to")
5945                        (message-fetch-field "reply-to")
5946                        (message-fetch-field "from")
5947                        "")
5948             mft (and message-use-mail-followup-to
5949                      (message-fetch-field "mail-followup-to"))))
5950
5951     ;; Handle special values of Mail-Copies-To.
5952     (when mct
5953       (cond ((or (equal (downcase mct) "never")
5954                  (equal (downcase mct) "nobody"))
5955              (setq never-mct t)
5956              (setq mct nil))
5957             ((or (equal (downcase mct) "always")
5958                  (equal (downcase mct) "poster"))
5959              (setq mct author))))
5960
5961     (save-match-data
5962       ;; Build (textual) list of new recipient addresses.
5963       (cond
5964        ((not wide)
5965         (setq recipients (concat ", " author)))
5966        (address-headers
5967         (dolist (header address-headers)
5968           (let ((value (message-fetch-field header)))
5969             (when value
5970               (setq recipients (concat recipients ", " value))))))
5971        ((and mft
5972              (string-match "[^ \t,]" mft)
5973              (or (not (eq message-use-mail-followup-to 'ask))
5974                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5975 You should normally obey the Mail-Followup-To: header.  In this
5976 article, it has the value of
5977
5978 " mft "
5979
5980 which directs your response to " (if (string-match "," mft)
5981                                      "the specified addresses"
5982                                    "that address only") ".
5983
5984 Most commonly, Mail-Followup-To is used by a mailing list poster to
5985 express that responses should be sent to just the list, and not the
5986 poster as well.
5987
5988 If a message is posted to several mailing lists, Mail-Followup-To may
5989 also be used to direct the following discussion to one list only,
5990 because discussions that are spread over several lists tend to be
5991 fragmented and very difficult to follow.
5992
5993 Also, some source/announcement lists are not intended for discussion;
5994 responses here are directed to other addresses.
5995
5996 You may customize the variable `message-use-mail-followup-to', if you
5997 want to get rid of this query permanently.")))
5998         (setq recipients (concat ", " mft)))
5999        (to-address
6000         (setq recipients (concat ", " to-address))
6001         ;; If the author explicitly asked for a copy, we don't deny it to them.
6002         (if mct (setq recipients (concat recipients ", " mct))))
6003        (t
6004         (setq recipients (if never-mct "" (concat ", " author)))
6005         (if to (setq recipients (concat recipients ", " to)))
6006         (if cc (setq recipients (concat recipients ", " cc)))
6007         (if extra (setq recipients (concat recipients ", " extra)))
6008         (if mct (setq recipients (concat recipients ", " mct)))))
6009       (if (>= (length recipients) 2)
6010           ;; Strip the leading ", ".
6011           (setq recipients (substring recipients 2)))
6012       ;; Squeeze whitespace.
6013       (while (string-match "[ \t][ \t]+" recipients)
6014         (setq recipients (replace-match " " t t recipients)))
6015       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6016       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
6017         (setq recipients (rmail-dont-reply-to recipients)))
6018       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6019       (if (string-equal recipients "")
6020           (setq recipients author))
6021       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6022       (setq recipients
6023             (mapcar
6024              (lambda (addr)
6025                (cons (downcase (mail-strip-quoted-names addr)) addr))
6026              (message-tokenize-header recipients)))
6027       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6028       (let ((s recipients))
6029         (while s
6030           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6031
6032       ;; Remove hierarchical lists that are contained within each other,
6033       ;; if message-hierarchical-addresses is defined.
6034       (when message-hierarchical-addresses
6035         (let ((plain-addrs (mapcar 'car recipients))
6036               subaddrs recip)
6037           (while plain-addrs
6038             (setq subaddrs (assoc (car plain-addrs)
6039                                   message-hierarchical-addresses)
6040                   plain-addrs (cdr plain-addrs))
6041             (when subaddrs
6042               (setq subaddrs (cdr subaddrs))
6043               (while subaddrs
6044                 (setq recip (assoc (car subaddrs) recipients)
6045                       subaddrs (cdr subaddrs))
6046                 (if recip
6047                     (setq recipients (delq recip recipients))))))))
6048
6049       ;; Build the header alist.  Allow the user to be asked whether
6050       ;; or not to reply to all recipients in a wide reply.
6051       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6052       (when (and recipients
6053                  (or (not message-wide-reply-confirm-recipients)
6054                      (y-or-n-p "Reply to all recipients? ")))
6055         (setq recipients (mapconcat
6056                           (lambda (addr) (cdr addr)) recipients ", "))
6057         (if (string-match "^ +" recipients)
6058             (setq recipients (substring recipients (match-end 0))))
6059         (push (cons 'Cc recipients) follow-to)))
6060     follow-to))
6061
6062 ;;;###autoload
6063 (defun message-reply (&optional to-address wide)
6064   "Start editing a reply to the article in the current buffer."
6065   (interactive)
6066   (require 'gnus-sum)                   ; for gnus-list-identifiers
6067   (let ((cur (current-buffer))
6068         from subject date reply-to to cc
6069         references message-id follow-to
6070         (inhibit-point-motion-hooks t)
6071         (message-this-is-mail t)
6072         gnus-warning)
6073     (save-restriction
6074       (message-narrow-to-head-1)
6075       ;; Allow customizations to have their say.
6076       (if (not wide)
6077           ;; This is a regular reply.
6078           (when (functionp message-reply-to-function)
6079             (save-excursion
6080               (setq follow-to (funcall message-reply-to-function))))
6081         ;; This is a followup.
6082         (when (functionp message-wide-reply-to-function)
6083           (save-excursion
6084             (setq follow-to
6085                   (funcall message-wide-reply-to-function)))))
6086       (setq message-id (message-fetch-field "message-id" t)
6087             references (message-fetch-field "references")
6088             date (message-fetch-field "date")
6089             from (message-fetch-field "from")
6090             subject (or (message-fetch-field "subject") "none"))
6091       (when gnus-list-identifiers
6092         (setq subject (message-strip-list-identifiers subject)))
6093       (setq subject (concat "Re: " (message-strip-subject-re subject)))
6094       (when message-subject-trailing-was-query
6095         (setq subject (message-strip-subject-trailing-was subject)))
6096
6097       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6098                  (string-match "<[^>]+>" gnus-warning))
6099         (setq message-id (match-string 0 gnus-warning)))
6100
6101       (unless follow-to
6102         (setq follow-to (message-get-reply-headers wide to-address))))
6103
6104     (unless (message-mail-user-agent)
6105       (message-pop-to-buffer
6106        (message-buffer-name
6107         (if wide "wide reply" "reply") from
6108         (if wide to-address nil))))
6109
6110     (setq message-reply-headers
6111           (vector 0 subject from date message-id references 0 0 ""))
6112
6113     (message-setup
6114      `((Subject . ,subject)
6115        ,@follow-to)
6116      cur)))
6117
6118 ;;;###autoload
6119 (defun message-wide-reply (&optional to-address)
6120   "Make a \"wide\" reply to the message in the current buffer."
6121   (interactive)
6122   (message-reply to-address t))
6123
6124 ;;;###autoload
6125 (defun message-followup (&optional to-newsgroups)
6126   "Follow up to the message in the current buffer.
6127 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6128   (interactive)
6129   (require 'gnus-sum)                   ; for gnus-list-identifiers
6130   (let ((cur (current-buffer))
6131         from subject date reply-to mrt mct
6132         references message-id follow-to
6133         (inhibit-point-motion-hooks t)
6134         (message-this-is-news t)
6135         followup-to distribution newsgroups gnus-warning posted-to)
6136     (save-restriction
6137       (narrow-to-region
6138        (goto-char (point-min))
6139        (if (search-forward "\n\n" nil t)
6140            (1- (point))
6141          (point-max)))
6142       (when (functionp message-followup-to-function)
6143         (setq follow-to
6144               (funcall message-followup-to-function)))
6145       (setq from (message-fetch-field "from")
6146             date (message-fetch-field "date")
6147             subject (or (message-fetch-field "subject") "none")
6148             references (message-fetch-field "references")
6149             message-id (message-fetch-field "message-id" t)
6150             followup-to (message-fetch-field "followup-to")
6151             newsgroups (message-fetch-field "newsgroups")
6152             posted-to (message-fetch-field "posted-to")
6153             reply-to (message-fetch-field "reply-to")
6154             mrt (message-fetch-field "mail-reply-to")
6155             distribution (message-fetch-field "distribution")
6156             mct (message-fetch-field "mail-copies-to"))
6157       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6158                  (string-match "<[^>]+>" gnus-warning))
6159         (setq message-id (match-string 0 gnus-warning)))
6160       ;; Remove bogus distribution.
6161       (when (and (stringp distribution)
6162                  (let ((case-fold-search t))
6163                    (string-match "world" distribution)))
6164         (setq distribution nil))
6165       (if gnus-list-identifiers
6166           (setq subject (message-strip-list-identifiers subject)))
6167       (setq subject (concat "Re: " (message-strip-subject-re subject)))
6168       (when message-subject-trailing-was-query
6169         (setq subject (message-strip-subject-trailing-was subject)))
6170       (widen))
6171
6172     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6173
6174     (setq message-reply-headers
6175           (vector 0 subject from date message-id references 0 0 ""))
6176
6177     (message-setup
6178      `((Subject . ,subject)
6179        ,@(cond
6180           (to-newsgroups
6181            (list (cons 'Newsgroups to-newsgroups)))
6182           (follow-to follow-to)
6183           ((and followup-to message-use-followup-to)
6184            (list
6185             (cond
6186              ((equal (downcase followup-to) "poster")
6187               (if (or (eq message-use-followup-to 'use)
6188                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
6189 You should normally obey the Followup-To: header.
6190
6191 `Followup-To: poster' sends your response via e-mail instead of news.
6192
6193 A typical situation where `Followup-To: poster' is used is when the poster
6194 does not read the newsgroup, so he wouldn't see any replies sent to it.
6195
6196 You may customize the variable `message-use-followup-to', if you
6197 want to get rid of this query permanently."))
6198                   (progn
6199                     (setq message-this-is-news nil)
6200                     (cons 'To (or mrt reply-to from "")))
6201                 (cons 'Newsgroups newsgroups)))
6202              (t
6203               (if (or (equal followup-to newsgroups)
6204                       (not (eq message-use-followup-to 'ask))
6205                       (message-y-or-n-p
6206                        (concat "Obey Followup-To: " followup-to "? ") t "\
6207 You should normally obey the Followup-To: header.
6208
6209         `Followup-To: " followup-to "'
6210 directs your response to " (if (string-match "," followup-to)
6211                                "the specified newsgroups"
6212                              "that newsgroup only") ".
6213
6214 If a message is posted to several newsgroups, Followup-To is often
6215 used to direct the following discussion to one newsgroup only,
6216 because discussions that are spread over several newsgroup tend to
6217 be fragmented and very difficult to follow.
6218
6219 Also, some source/announcement newsgroups are not intended for discussion;
6220 responses here are directed to other newsgroups.
6221
6222 You may customize the variable `message-use-followup-to', if you
6223 want to get rid of this query permanently."))
6224                   (cons 'Newsgroups followup-to)
6225                 (cons 'Newsgroups newsgroups))))))
6226           (posted-to
6227            `((Newsgroups . ,posted-to)))
6228           (t
6229            `((Newsgroups . ,newsgroups))))
6230        ,@(and distribution (list (cons 'Distribution distribution)))
6231        ,@(when (and mct
6232                     (not (or (equal (downcase mct) "never")
6233                              (equal (downcase mct) "nobody"))))
6234            (list (cons 'Cc (if (or (equal (downcase mct) "always")
6235                                    (equal (downcase mct) "poster"))
6236                                (or mrt reply-to from "")
6237                              mct)))))
6238
6239      cur)))
6240
6241 (defun message-is-yours-p ()
6242   "Non-nil means current article is yours.
6243 If you have added 'cancel-messages to `message-shoot-gnksa-feet', all articles
6244 are yours except those that have Cancel-Lock header not belonging to you.
6245 Instead of shooting GNKSA feet, you should modify `message-alternative-emails'
6246 regexp to match all of yours addresses."
6247   ;; Canlock-logic as suggested by Per Abrahamsen
6248   ;; <abraham@dina.kvl.dk>
6249   ;;
6250   ;; IF article has cancel-lock THEN
6251   ;;   IF we can verify it THEN
6252   ;;     issue cancel
6253   ;;   ELSE
6254   ;;     error: cancellock: article is not yours
6255   ;; ELSE
6256   ;;   Use old rules, comparing sender...
6257   (save-excursion
6258     (save-restriction
6259       (message-narrow-to-head-1)
6260       (if (message-fetch-field "Cancel-Lock")
6261           (if (null (canlock-verify))
6262               t
6263             (error "Failed to verify Cancel-lock: This article is not yours"))
6264         (let (sender from)
6265           (or
6266            (message-gnksa-enable-p 'cancel-messages)
6267            (and (setq sender (message-fetch-field "sender"))
6268                 (string-equal (downcase sender)
6269                               (downcase (message-make-sender))))
6270            ;; Email address in From field equals to our address
6271            (and (setq from (message-fetch-field "from"))
6272                 (string-equal
6273                  (downcase (car (mail-header-parse-address from)))
6274                  (downcase (car (mail-header-parse-address
6275                                  (message-make-from))))))
6276            ;; Email address in From field matches
6277            ;; 'message-alternative-emails' regexp
6278            (and from
6279                 message-alternative-emails
6280                 (string-match
6281                  message-alternative-emails
6282                  (car (mail-header-parse-address from))))))))))
6283
6284 ;;;###autoload
6285 (defun message-cancel-news (&optional arg)
6286   "Cancel an article you posted.
6287 If ARG, allow editing of the cancellation message."
6288   (interactive "P")
6289   (unless (message-news-p)
6290     (error "This is not a news article; canceling is impossible"))
6291   (let (from newsgroups message-id distribution buf)
6292     (save-excursion
6293       ;; Get header info from original article.
6294       (save-restriction
6295         (message-narrow-to-head-1)
6296         (setq from (message-fetch-field "from")
6297               newsgroups (message-fetch-field "newsgroups")
6298               message-id (message-fetch-field "message-id" t)
6299               distribution (message-fetch-field "distribution")))
6300       ;; Make sure that this article was written by the user.
6301       (unless (message-is-yours-p)
6302         (error "This article is not yours"))
6303       (when (yes-or-no-p "Do you really want to cancel this article? ")
6304         ;; Make control message.
6305         (if arg
6306             (message-news)
6307           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6308         (erase-buffer)
6309         (insert "Newsgroups: " newsgroups "\n"
6310                 "From: " from "\n"
6311                 "Subject: cmsg cancel " message-id "\n"
6312                 "Control: cancel " message-id "\n"
6313                 (if distribution
6314                     (concat "Distribution: " distribution "\n")
6315                   "")
6316                 mail-header-separator "\n"
6317                 message-cancel-message)
6318         (run-hooks 'message-cancel-hook)
6319         (unless arg
6320           (message "Canceling your article...")
6321           (if (let ((message-syntax-checks
6322                      'dont-check-for-anything-just-trust-me))
6323                 (funcall message-send-news-function))
6324               (message "Canceling your article...done"))
6325           (kill-buffer buf))))))
6326
6327 ;;;###autoload
6328 (defun message-supersede ()
6329   "Start composing a message to supersede the current message.
6330 This is done simply by taking the old article and adding a Supersedes
6331 header line with the old Message-ID."
6332   (interactive)
6333   (let ((cur (current-buffer)))
6334     ;; Check whether the user owns the article that is to be superseded.
6335     (unless (message-is-yours-p)
6336       (error "This article is not yours"))
6337     ;; Get a normal message buffer.
6338     (message-pop-to-buffer (message-buffer-name "supersede"))
6339     (insert-buffer-substring cur)
6340     (mime-to-mml)
6341     (message-narrow-to-head-1)
6342     ;; Remove unwanted headers.
6343     (when message-ignored-supersedes-headers
6344       (message-remove-header message-ignored-supersedes-headers t))
6345     (goto-char (point-min))
6346     (if (not (re-search-forward "^Message-ID: " nil t))
6347         (error "No Message-ID in this article")
6348       (replace-match "Supersedes: " t t))
6349     (goto-char (point-max))
6350     (insert mail-header-separator)
6351     (widen)
6352     (forward-line 1)))
6353
6354 ;;;###autoload
6355 (defun message-recover ()
6356   "Reread contents of current buffer from its last auto-save file."
6357   (interactive)
6358   (let ((file-name (make-auto-save-file-name)))
6359     (cond ((save-window-excursion
6360              (if (not (eq system-type 'vax-vms))
6361                  (with-output-to-temp-buffer "*Directory*"
6362                    (with-current-buffer standard-output
6363                      (fundamental-mode)) ; for Emacs 20.4+
6364                    (buffer-disable-undo standard-output)
6365                    (let ((default-directory "/"))
6366                      (call-process
6367                       "ls" nil standard-output nil "-l" file-name))))
6368              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6369            (let ((buffer-read-only nil))
6370              (erase-buffer)
6371              (insert-file-contents file-name nil)))
6372           (t (error "message-recover cancelled")))))
6373
6374 ;;; Washing Subject:
6375
6376 (defun message-wash-subject (subject)
6377   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6378 Previous forwarders, replyers, etc. may add it."
6379   (with-temp-buffer
6380     (insert subject)
6381     (goto-char (point-min))
6382     ;; strip Re/Fwd stuff off the beginning
6383     (while (re-search-forward
6384             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6385       (replace-match ""))
6386
6387     ;; and gnus-style forwards [foo@bar.com] subject
6388     (goto-char (point-min))
6389     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6390       (replace-match ""))
6391
6392     ;; and off the end
6393     (goto-char (point-max))
6394     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6395       (replace-match ""))
6396
6397     ;; and finally, any whitespace that was left-over
6398     (goto-char (point-min))
6399     (while (re-search-forward "^[ \t]+" nil t)
6400       (replace-match ""))
6401     (goto-char (point-max))
6402     (while (re-search-backward "[ \t]+$" nil t)
6403       (replace-match ""))
6404
6405     (buffer-string)))
6406
6407 ;;; Forwarding messages.
6408
6409 (defvar message-forward-decoded-p nil
6410   "Non-nil means the original message is decoded.")
6411
6412 (defun message-forward-subject-name-subject (subject)
6413   "Generate a SUBJECT for a forwarded message.
6414 The form is: [Source] Subject, where if the original message was mail,
6415 Source is the name of the sender, and if the original message was
6416 news, Source is the list of newsgroups is was posted to."
6417   (let* ((group (message-fetch-field "newsgroups"))
6418          (from (message-fetch-field "from"))
6419          (prefix
6420           (if group
6421               (gnus-group-decoded-name group)
6422             (or (and from (or
6423                            (car (gnus-extract-address-components from))
6424                            (cadr (gnus-extract-address-components from))))
6425                 "(nowhere)"))))
6426     (concat "["
6427             (if message-forward-decoded-p
6428                 prefix
6429               (mail-decode-encoded-word-string prefix))
6430             "] " subject)))
6431
6432 (defun message-forward-subject-author-subject (subject)
6433   "Generate a SUBJECT for a forwarded message.
6434 The form is: [Source] Subject, where if the original message was mail,
6435 Source is the sender, and if the original message was news, Source is
6436 the list of newsgroups is was posted to."
6437   (let* ((group (message-fetch-field "newsgroups"))
6438          (prefix
6439           (if group
6440               (gnus-group-decoded-name group)
6441             (or (message-fetch-field "from")
6442                 "(nowhere)"))))
6443     (concat "["
6444             (if message-forward-decoded-p
6445                 prefix
6446               (mail-decode-encoded-word-string prefix))
6447             "] " subject)))
6448
6449 (defun message-forward-subject-fwd (subject)
6450   "Generate a SUBJECT for a forwarded message.
6451 The form is: Fwd: Subject, where Subject is the original subject of
6452 the message."
6453   (if (string-match "^Fwd: " subject)
6454       subject
6455     (concat "Fwd: " subject)))
6456
6457 (defun message-make-forward-subject ()
6458   "Return a Subject header suitable for the message in the current buffer."
6459   (save-excursion
6460     (save-restriction
6461       (message-narrow-to-head-1)
6462       (let ((funcs message-make-forward-subject-function)
6463             (subject (message-fetch-field "Subject")))
6464         (setq subject
6465               (if subject
6466                   (if message-forward-decoded-p
6467                       subject
6468                     (mail-decode-encoded-word-string subject))
6469                 ""))
6470         (when message-wash-forwarded-subjects
6471           (setq subject (message-wash-subject subject)))
6472         ;; Make sure funcs is a list.
6473         (and funcs
6474              (not (listp funcs))
6475              (setq funcs (list funcs)))
6476         ;; Apply funcs in order, passing subject generated by previous
6477         ;; func to the next one.
6478         (dolist (func funcs)
6479           (when (functionp func)
6480             (setq subject (funcall func subject))))
6481         subject))))
6482
6483 (eval-when-compile
6484   (defvar gnus-article-decoded-p))
6485
6486
6487 ;;;###autoload
6488 (defun message-forward (&optional news digest)
6489   "Forward the current message via mail.
6490 Optional NEWS will use news to forward instead of mail.
6491 Optional DIGEST will use digest to forward."
6492   (interactive "P")
6493   (let* ((cur (current-buffer))
6494          (message-forward-decoded-p
6495           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
6496               gnus-article-decoded-p ;; In an article buffer.
6497             message-forward-decoded-p))
6498          (subject (message-make-forward-subject)))
6499     (if news
6500         (message-news nil subject)
6501       (message-mail nil subject))
6502     (message-forward-make-body cur digest)))
6503
6504 (defun message-forward-make-body-plain (forward-buffer)
6505   (insert
6506    "\n-------------------- Start of forwarded message --------------------\n")
6507   (let ((b (point)) e)
6508     (insert
6509      (with-temp-buffer
6510        (mm-disable-multibyte)
6511        (insert
6512         (with-current-buffer forward-buffer
6513           (mm-with-unibyte-current-buffer (buffer-string))))
6514        (mm-enable-multibyte)
6515        (mime-to-mml)
6516        (goto-char (point-min))
6517        (when (looking-at "From ")
6518          (replace-match "X-From-Line: "))
6519        (buffer-string)))
6520     (setq e (point))
6521     (insert
6522      "\n-------------------- End of forwarded message --------------------\n")
6523     (message-remove-ignored-headers b e)))
6524
6525 (defun message-remove-ignored-headers (b e)
6526   (when message-forward-ignored-headers
6527     (save-restriction
6528       (narrow-to-region b e)
6529       (goto-char b)
6530       (narrow-to-region (point)
6531                         (or (search-forward "\n\n" nil t) (point)))
6532       (let ((ignored (if (stringp message-forward-ignored-headers)
6533                          (list message-forward-ignored-headers)
6534                        message-forward-ignored-headers)))
6535         (dolist (elem ignored)
6536           (message-remove-header elem t))))))
6537
6538 (defun message-forward-make-body-mime (forward-buffer)
6539   (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
6540   (let ((b (point)) e)
6541     (save-restriction
6542       (narrow-to-region (point) (point))
6543       (mml-insert-buffer forward-buffer)
6544       (goto-char (point-min))
6545       (when (looking-at "From ")
6546         (replace-match "X-From-Line: "))
6547       (goto-char (point-max)))
6548     (setq e (point))
6549     (insert "<#/part>\n")))
6550
6551 (defun message-forward-make-body-mml (forward-buffer)
6552   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
6553   (let ((b (point)) e)
6554     (if (not message-forward-decoded-p)
6555         (insert
6556          (with-temp-buffer
6557            (mm-disable-multibyte)
6558            (insert
6559             (with-current-buffer forward-buffer
6560               (mm-with-unibyte-current-buffer (buffer-string))))
6561            (mm-enable-multibyte)
6562            (mime-to-mml)
6563            (goto-char (point-min))
6564            (when (looking-at "From ")
6565              (replace-match "X-From-Line: "))
6566            (buffer-string)))
6567       (save-restriction
6568         (narrow-to-region (point) (point))
6569         (mml-insert-buffer forward-buffer)
6570         (goto-char (point-min))
6571         (when (looking-at "From ")
6572           (replace-match "X-From-Line: "))
6573         (goto-char (point-max))))
6574     (setq e (point))
6575     (insert "<#/mml>\n")
6576     (when (and (not message-forward-decoded-p)
6577                message-forward-ignored-headers)
6578       (message-remove-ignored-headers b e))))
6579
6580 (defun message-forward-make-body-digest-plain (forward-buffer)
6581   (insert
6582    "\n-------------------- Start of forwarded message --------------------\n")
6583   (let ((b (point)) e)
6584     (mml-insert-buffer forward-buffer)
6585     (setq e (point))
6586     (insert
6587      "\n-------------------- End of forwarded message --------------------\n")))
6588
6589 (defun message-forward-make-body-digest-mime (forward-buffer)
6590   (insert "\n<#multipart type=digest>\n")
6591   (let ((b (point)) e)
6592     (insert-buffer-substring forward-buffer)
6593     (setq e (point))
6594     (insert "<#/multipart>\n")
6595     (save-restriction
6596       (narrow-to-region b e)
6597       (goto-char b)
6598       (narrow-to-region (point)
6599                         (or (search-forward "\n\n" nil t) (point)))
6600       (delete-region (point-min) (point-max)))))
6601
6602 (defun message-forward-make-body-digest (forward-buffer)
6603   (if message-forward-as-mime
6604       (message-forward-make-body-digest-mime forward-buffer)
6605     (message-forward-make-body-digest-plain forward-buffer)))
6606
6607 ;;;###autoload
6608 (defun message-forward-make-body (forward-buffer &optional digest)
6609   ;; Put point where we want it before inserting the forwarded
6610   ;; message.
6611   (if message-forward-before-signature
6612       (message-goto-body)
6613     (goto-char (point-max)))
6614   (if digest
6615       (message-forward-make-body-digest forward-buffer)
6616     (if message-forward-as-mime
6617         (if (and message-forward-show-mml
6618                  (not (and (eq message-forward-show-mml 'best)
6619                            (with-current-buffer forward-buffer
6620                              (goto-char (point-min))
6621                              (re-search-forward
6622                               "Content-Type: *multipart/\\(signed\\|encrypted\\)"
6623                               nil t)))))
6624             (message-forward-make-body-mml forward-buffer)
6625           (message-forward-make-body-mime forward-buffer))
6626       (message-forward-make-body-plain forward-buffer)))
6627   (message-position-point))
6628
6629 ;;;###autoload
6630 (defun message-forward-rmail-make-body (forward-buffer)
6631   (save-window-excursion
6632     (set-buffer forward-buffer)
6633     (if (rmail-msg-is-pruned)
6634         (rmail-msg-restore-non-pruned-header)))
6635   (message-forward-make-body forward-buffer))
6636
6637 (eval-when-compile (defvar rmail-enable-mime-composing))
6638
6639 ;; Fixme: Should have defcustom.
6640 ;;;###autoload
6641 (defun message-insinuate-rmail ()
6642   "Let RMAIL use message to forward."
6643   (interactive)
6644   (setq rmail-enable-mime-composing t)
6645   (setq rmail-insert-mime-forwarded-message-function
6646         'message-forward-rmail-make-body))
6647
6648 ;;;###autoload
6649 (defun message-resend (address)
6650   "Resend the current article to ADDRESS."
6651   (interactive
6652    (list (message-read-from-minibuffer "Resend message to: ")))
6653   (message "Resending message to %s..." address)
6654   (save-excursion
6655     (let ((cur (current-buffer))
6656           beg)
6657       ;; We first set up a normal mail buffer.
6658       (unless (message-mail-user-agent)
6659         (set-buffer (get-buffer-create " *message resend*"))
6660         (erase-buffer))
6661       (let ((message-this-is-mail t)
6662             message-generate-hashcash
6663             message-setup-hook)
6664         (message-setup `((To . ,address))))
6665       ;; Insert our usual headers.
6666       (message-generate-headers '(From Date To Message-ID))
6667       (message-narrow-to-headers)
6668       ;; Remove X-Draft-From header etc.
6669       (message-remove-header message-ignored-mail-headers t)
6670       ;; Rename them all to "Resent-*".
6671       (goto-char (point-min))
6672       (while (re-search-forward "^[A-Za-z]" nil t)
6673         (forward-char -1)
6674         (insert "Resent-"))
6675       (widen)
6676       (forward-line)
6677       (delete-region (point) (point-max))
6678       (setq beg (point))
6679       ;; Insert the message to be resent.
6680       (insert-buffer-substring cur)
6681       (goto-char (point-min))
6682       (search-forward "\n\n")
6683       (forward-char -1)
6684       (save-restriction
6685         (narrow-to-region beg (point))
6686         (message-remove-header message-ignored-resent-headers t)
6687         (goto-char (point-max)))
6688       (insert mail-header-separator)
6689       ;; Rename all old ("Also-")Resent headers.
6690       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6691         (beginning-of-line)
6692         (insert "Also-"))
6693       ;; Quote any "From " lines at the beginning.
6694       (goto-char beg)
6695       (when (looking-at "From ")
6696         (replace-match "X-From-Line: "))
6697       ;; Send it.
6698       (let ((message-inhibit-body-encoding t)
6699             message-required-mail-headers
6700             message-generate-hashcash
6701             rfc2047-encode-encoded-words)
6702         (message-send-mail))
6703       (kill-buffer (current-buffer)))
6704     (message "Resending message to %s...done" address)))
6705
6706 ;;;###autoload
6707 (defun message-bounce ()
6708   "Re-mail the current message.
6709 This only makes sense if the current message is a bounce message that
6710 contains some mail you have written which has been bounced back to
6711 you."
6712   (interactive)
6713   (let ((handles (mm-dissect-buffer t))
6714         boundary)
6715     (message-pop-to-buffer (message-buffer-name "bounce"))
6716     (if (stringp (car handles))
6717         ;; This is a MIME bounce.
6718         (mm-insert-part (car (last handles)))
6719       ;; This is a non-MIME bounce, so we try to remove things
6720       ;; manually.
6721       (mm-insert-part handles)
6722       (undo-boundary)
6723       (goto-char (point-min))
6724       (re-search-forward "\n\n+" nil t)
6725       (setq boundary (point))
6726       ;; We remove everything before the bounced mail.
6727       (if (or (re-search-forward message-unsent-separator nil t)
6728               (progn
6729                 (search-forward "\n\n" nil 'move)
6730                 (re-search-backward "^Return-Path:.*\n" boundary t)))
6731           (progn
6732             (forward-line 1)
6733             (delete-region (point-min)
6734                            (if (re-search-forward "^[^ \n\t]+:" nil t)
6735                                (match-beginning 0)
6736                              (point))))
6737         (goto-char boundary)
6738         (when (re-search-backward "^.?From .*\n" nil t)
6739           (delete-region (match-beginning 0) (match-end 0)))))
6740     (mm-enable-multibyte)
6741     (save-restriction
6742       (message-narrow-to-head-1)
6743       (message-remove-header message-ignored-bounced-headers t)
6744       (goto-char (point-max))
6745       (insert mail-header-separator))
6746     (message-position-point)))
6747
6748 ;;;
6749 ;;; Interactive entry points for new message buffers.
6750 ;;;
6751
6752 ;;;###autoload
6753 (defun message-mail-other-window (&optional to subject)
6754   "Like `message-mail' command, but display mail buffer in another window."
6755   (interactive)
6756   (unless (message-mail-user-agent)
6757     (let ((pop-up-windows t)
6758           (special-display-buffer-names nil)
6759           (special-display-regexps nil)
6760           (same-window-buffer-names nil)
6761           (same-window-regexps nil))
6762       (message-pop-to-buffer (message-buffer-name "mail" to))))
6763   (let ((message-this-is-mail t))
6764     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6765                    nil nil 'switch-to-buffer-other-window)))
6766
6767 ;;;###autoload
6768 (defun message-mail-other-frame (&optional to subject)
6769   "Like `message-mail' command, but display mail buffer in another frame."
6770   (interactive)
6771   (unless (message-mail-user-agent)
6772     (let ((pop-up-frames t)
6773           (special-display-buffer-names nil)
6774           (special-display-regexps nil)
6775           (same-window-buffer-names nil)
6776           (same-window-regexps nil))
6777       (message-pop-to-buffer (message-buffer-name "mail" to))))
6778   (let ((message-this-is-mail t))
6779     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6780                    nil nil 'switch-to-buffer-other-frame)))
6781
6782 ;;;###autoload
6783 (defun message-news-other-window (&optional newsgroups subject)
6784   "Start editing a news article to be sent."
6785   (interactive)
6786   (let ((pop-up-windows t)
6787         (special-display-buffer-names nil)
6788         (special-display-regexps nil)
6789         (same-window-buffer-names nil)
6790         (same-window-regexps nil))
6791     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6792   (let ((message-this-is-news t))
6793     (message-setup `((Newsgroups . ,(or newsgroups ""))
6794                      (Subject . ,(or subject ""))))))
6795
6796 ;;;###autoload
6797 (defun message-news-other-frame (&optional newsgroups subject)
6798   "Start editing a news article to be sent."
6799   (interactive)
6800   (let ((pop-up-frames t)
6801         (special-display-buffer-names nil)
6802         (special-display-regexps nil)
6803         (same-window-buffer-names nil)
6804         (same-window-regexps nil))
6805     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6806   (let ((message-this-is-news t))
6807     (message-setup `((Newsgroups . ,(or newsgroups ""))
6808                      (Subject . ,(or subject ""))))))
6809
6810 ;;; underline.el
6811
6812 ;; This code should be moved to underline.el (from which it is stolen).
6813
6814 ;;;###autoload
6815 (defun message-bold-region (start end)
6816   "Bold all nonblank characters in the region.
6817 Works by overstriking characters.
6818 Called from program, takes two arguments START and END
6819 which specify the range to operate on."
6820   (interactive "r")
6821   (save-excursion
6822     (let ((end1 (make-marker)))
6823       (move-marker end1 (max start end))
6824       (goto-char (min start end))
6825       (while (< (point) end1)
6826         (or (looking-at "[_\^@- ]")
6827             (insert (char-after) "\b"))
6828         (forward-char 1)))))
6829
6830 ;;;###autoload
6831 (defun message-unbold-region (start end)
6832   "Remove all boldness (overstruck characters) in the region.
6833 Called from program, takes two arguments START and END
6834 which specify the range to operate on."
6835   (interactive "r")
6836   (save-excursion
6837     (let ((end1 (make-marker)))
6838       (move-marker end1 (max start end))
6839       (goto-char (min start end))
6840       (while (search-forward "\b" end1 t)
6841         (if (eq (char-after) (char-after (- (point) 2)))
6842             (delete-char -2))))))
6843
6844 (defun message-exchange-point-and-mark ()
6845   "Exchange point and mark, but don't activate region if it was inactive."
6846   (unless (prog1
6847               (message-mark-active-p)
6848             (exchange-point-and-mark))
6849     (setq mark-active nil)))
6850
6851 (defalias 'message-make-overlay 'make-overlay)
6852 (defalias 'message-delete-overlay 'delete-overlay)
6853 (defalias 'message-overlay-put 'overlay-put)
6854 (defun message-kill-all-overlays ()
6855   (if (featurep 'xemacs)
6856       (map-extents (lambda (extent ignore) (delete-extent extent)))
6857     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
6858
6859 ;; Support for toolbar
6860 (eval-when-compile
6861   (defvar tool-bar-mode))
6862
6863 ;; Note: The :set function in the `message-tool-bar*' variables will only
6864 ;; affect _new_ message buffers.  We might add a function that walks thru all
6865 ;; message-mode buffers and force the update.
6866 (defun message-tool-bar-update (&optional symbol value)
6867   "Update message mode toolbar.
6868 Setter function for custom variables."
6869   (setq-default message-tool-bar-map nil)
6870   (when symbol
6871     ;; When used as ":set" function:
6872     (set-default symbol value)))
6873
6874 (defcustom message-tool-bar (if (eq gmm-tool-bar-style 'gnome)
6875                                 'message-tool-bar-gnome
6876                               'message-tool-bar-retro)
6877   "Specifies the message mode tool bar.
6878
6879 It can be either a list or a symbol refering to a list.  See
6880 `gmm-tool-bar-from-list' for the format of the list.  The
6881 default key map is `message-mode-map'.
6882
6883 Pre-defined symbols include `message-tool-bar-gnome' and
6884 `message-tool-bar-retro'."
6885   :type '(repeat gmm-tool-bar-list-item)
6886   :type '(choice (const :tag "GNOME style" message-tool-bar-gnome)
6887                  (const :tag "Retro look"  message-tool-bar-retro)
6888                  (repeat :tag "User defined list" gmm-tool-bar-item)
6889                  (symbol))
6890   :version "23.0" ;; No Gnus
6891   :initialize 'custom-initialize-default
6892   :set 'message-tool-bar-update
6893   :group 'message)
6894
6895 (defcustom message-tool-bar-gnome
6896   '((ispell-message "spell" nil
6897                     :visible (or (not (boundp 'flyspell-mode))
6898                                  (not flyspell-mode)))
6899     (flyspell-buffer "spell" t
6900                      :visible (and (boundp 'flyspell-mode)
6901                                    flyspell-mode)
6902                      :help "Flyspell whole buffer")
6903     (gmm-ignore "separator")
6904     (message-send-and-exit "mail/send")
6905     (message-dont-send "mail/save-draft")
6906     (message-kill-buffer "close") ;; stock_cancel
6907     (mml-attach-file "attach" mml-mode-map)
6908     (mml-preview "mail/preview" mml-mode-map)
6909     (mml-secure-message-sign-encrypt "lock" mml-mode-map :visible nil)
6910     (message-insert-importance-high "important" nil :visible nil)
6911     (message-insert-importance-low "unimportant" nil :visible nil)
6912     (message-insert-disposition-notification-to "receipt" nil :visible nil)
6913     (gmm-customize-mode "preferences" t :help "Edit mode preferences")
6914     (message-info "help" t :help "Message manual"))
6915   "List of items for the message tool bar (GNOME style).
6916
6917 See `gmm-tool-bar-from-list' for details on the format of the list."
6918   :type '(repeat gmm-tool-bar-item)
6919   :version "23.0" ;; No Gnus
6920   :initialize 'custom-initialize-default
6921   :set 'message-tool-bar-update
6922   :group 'message)
6923
6924 (defcustom message-tool-bar-retro
6925   '(;; Old Emacs 21 icon for consistency.
6926     (message-send-and-exit "gnus/mail_send")
6927     (message-kill-buffer "close")
6928     (message-dont-send "cancel")
6929     (mml-attach-file "attach" mml-mode-map)
6930     (ispell-message "spell")
6931     (mml-preview "preview" mml-mode-map)
6932     (message-insert-importance-high "gnus/important")
6933     (message-insert-importance-low "gnus/unimportant")
6934     (message-insert-disposition-notification-to "gnus/receipt"))
6935   "List of items for the message tool bar (retro style).
6936
6937 See `gmm-tool-bar-from-list' for details on the format of the list."
6938   :type '(repeat gmm-tool-bar-item)
6939   :version "23.0" ;; No Gnus
6940   :initialize 'custom-initialize-default
6941   :set 'message-tool-bar-update
6942   :group 'message)
6943
6944 (defcustom message-tool-bar-zap-list
6945   '(new-file open-file dired kill-buffer write-file
6946              print-buffer customize help)
6947   "List of icon items from the global tool bar.
6948 These items are not displayed on the message mode tool bar.
6949
6950 See `gmm-tool-bar-from-list' for the format of the list."
6951   :type 'gmm-tool-bar-zap-list
6952   :version "23.0" ;; No Gnus
6953   :initialize 'custom-initialize-default
6954   :set 'message-tool-bar-update
6955   :group 'message)
6956
6957 (defvar image-load-path)
6958
6959 (defun message-make-tool-bar (&optional force)
6960   "Make a message mode tool bar from `message-tool-bar-list'.
6961 When FORCE, rebuild the tool bar."
6962   (when (and (not (featurep 'xemacs))
6963              (boundp 'tool-bar-mode)
6964              tool-bar-mode
6965              (or (not message-tool-bar-map) force))
6966     (setq message-tool-bar-map
6967           (let* ((load-path
6968                   (gmm-image-load-path-for-library "message"
6969                                                    "mail/save-draft.xpm"
6970                                                    nil t))
6971                  (image-load-path (cons (car load-path)
6972                                         (when (boundp 'image-load-path)
6973                                           image-load-path))))
6974             (gmm-tool-bar-from-list message-tool-bar
6975                                     message-tool-bar-zap-list
6976                                     'message-mode-map))))
6977   message-tool-bar-map)
6978
6979 ;;; Group name completion.
6980
6981 (defcustom message-newgroups-header-regexp
6982   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6983   "Regexp that match headers that lists groups."
6984   :group 'message
6985   :type 'regexp)
6986
6987 (defcustom message-completion-alist
6988   (list (cons message-newgroups-header-regexp 'message-expand-group)
6989         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6990         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6991           . message-expand-name)
6992         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6993           . message-expand-name))
6994   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6995   :version "22.1"
6996   :group 'message
6997   :type '(alist :key-type regexp :value-type function))
6998
6999 (defcustom message-expand-name-databases
7000   (list 'bbdb 'eudc)
7001   "List of databases to try for name completion (`message-expand-name').
7002 Each element is a symbol and can be `bbdb' or `eudc'."
7003   :group 'message
7004   :type '(set (const bbdb) (const eudc)))
7005
7006 (defcustom message-tab-body-function nil
7007   "*Function to execute when `message-tab' (TAB) is executed in the body.
7008 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7009   :version "22.1"
7010   :group 'message
7011   :link '(custom-manual "(message)Various Commands")
7012   :type '(choice (const nil)
7013                  function))
7014
7015 (defun message-tab ()
7016   "Complete names according to `message-completion-alist'.
7017 Execute function specified by `message-tab-body-function' when not in
7018 those headers."
7019   (interactive)
7020   (let ((alist message-completion-alist))
7021     (while (and alist
7022                 (let ((mail-abbrev-mode-regexp (caar alist)))
7023                   (not (mail-abbrev-in-expansion-header-p))))
7024       (setq alist (cdr alist)))
7025     (funcall (or (cdar alist) message-tab-body-function
7026                  (lookup-key text-mode-map "\t")
7027                  (lookup-key global-map "\t")
7028                  'indent-relative))))
7029
7030 (eval-and-compile
7031   (condition-case nil
7032       (with-temp-buffer
7033         (let ((standard-output (current-buffer)))
7034           (eval '(display-completion-list nil "")))
7035         (defalias 'message-display-completion-list 'display-completion-list))
7036     (error ;; Don't use `wrong-number-of-arguments' here because of XEmacs.
7037      (defun message-display-completion-list (completions &optional ignore)
7038        "Display the list of completions, COMPLETIONS, using `standard-output'."
7039        (display-completion-list completions)))))
7040
7041 (defun message-expand-group ()
7042   "Expand the group name under point."
7043   (let* ((b (save-excursion
7044               (save-restriction
7045                 (narrow-to-region
7046                  (save-excursion
7047                    (beginning-of-line)
7048                    (skip-chars-forward "^:")
7049                    (1+ (point)))
7050                  (point))
7051                 (skip-chars-backward "^, \t\n") (point))))
7052          (completion-ignore-case t)
7053          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
7054                                             (point))))
7055          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
7056          (completions (all-completions string hashtb))
7057          comp)
7058     (delete-region b (point))
7059     (cond
7060      ((= (length completions) 1)
7061       (if (string= (car completions) string)
7062           (progn
7063             (insert string)
7064             (message "Only matching group"))
7065         (insert (car completions))))
7066      ((and (setq comp (try-completion string hashtb))
7067            (not (string= comp string)))
7068       (insert comp))
7069      (t
7070       (insert string)
7071       (if (not comp)
7072           (message "No matching groups")
7073         (save-selected-window
7074           (pop-to-buffer "*Completions*")
7075           (buffer-disable-undo)
7076           (let ((buffer-read-only nil))
7077             (erase-buffer)
7078             (let ((standard-output (current-buffer)))
7079               (message-display-completion-list (sort completions 'string<)
7080                                                string))
7081             (setq buffer-read-only nil)
7082             (goto-char (point-min))
7083             (delete-region (point) (progn (forward-line 3) (point))))))))))
7084
7085 (defun message-expand-name ()
7086   (cond ((and (memq 'eudc message-expand-name-databases)
7087                     (boundp 'eudc-protocol)
7088                     eudc-protocol)
7089          (eudc-expand-inline))
7090         ((and (memq 'bbdb message-expand-name-databases)
7091               (fboundp 'bbdb-complete-name))
7092          (bbdb-complete-name))
7093         (t
7094          (expand-abbrev))))
7095
7096 ;;; Help stuff.
7097
7098 (defun message-talkative-question (ask question show &rest text)
7099   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7100 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7101 The following arguments may contain lists of values."
7102   (if (and show
7103            (setq text (message-flatten-list text)))
7104       (save-window-excursion
7105         (save-excursion
7106           (with-output-to-temp-buffer " *MESSAGE information message*"
7107             (set-buffer " *MESSAGE information message*")
7108             (fundamental-mode)          ; for Emacs 20.4+
7109             (mapcar 'princ text)
7110             (goto-char (point-min))))
7111         (funcall ask question))
7112     (funcall ask question)))
7113
7114 (defun message-flatten-list (list)
7115   "Return a new, flat list that contains all elements of LIST.
7116
7117 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7118 => (1 2 3 4 5 6 7)"
7119   (cond ((consp list)
7120          (apply 'append (mapcar 'message-flatten-list list)))
7121         (list
7122          (list list))))
7123
7124 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7125   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
7126 Then clone the local variables and values from the old buffer to the
7127 new one, cloning only the locals having a substring matching the
7128 regexp VARSTR."
7129   (let ((oldbuf (current-buffer)))
7130     (save-excursion
7131       (set-buffer (generate-new-buffer name))
7132       (message-clone-locals oldbuf varstr)
7133       (current-buffer))))
7134
7135 (defun message-clone-locals (buffer &optional varstr)
7136   "Clone the local variables from BUFFER to the current buffer."
7137   (let ((locals (save-excursion
7138                   (set-buffer buffer)
7139                   (buffer-local-variables)))
7140         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address"))
7141     (mapcar
7142      (lambda (local)
7143        (when (and (consp local)
7144                   (car local)
7145                   (string-match regexp (symbol-name (car local)))
7146                   (or (null varstr)
7147                       (string-match varstr (symbol-name (car local)))))
7148          (ignore-errors
7149            (set (make-local-variable (car local))
7150                 (cdr local)))))
7151      locals)))
7152
7153 ;;;
7154 ;;; MIME functions
7155 ;;;
7156
7157 (defvar message-inhibit-body-encoding nil)
7158
7159 (defun message-encode-message-body ()
7160   (unless message-inhibit-body-encoding
7161     (let ((mail-parse-charset (or mail-parse-charset
7162                                   message-default-charset))
7163           (case-fold-search t)
7164           lines content-type-p)
7165       (message-goto-body)
7166       (save-restriction
7167         (narrow-to-region (point) (point-max))
7168         (let ((new (mml-generate-mime)))
7169           (when new
7170             (delete-region (point-min) (point-max))
7171             (insert new)
7172             (goto-char (point-min))
7173             (if (eq (aref new 0) ?\n)
7174                 (delete-char 1)
7175               (search-forward "\n\n")
7176               (setq lines (buffer-substring (point-min) (1- (point))))
7177               (delete-region (point-min) (point))))))
7178       (save-restriction
7179         (message-narrow-to-headers-or-head)
7180         (message-remove-header "Mime-Version")
7181         (goto-char (point-max))
7182         (insert "MIME-Version: 1.0\n")
7183         (when lines
7184           (insert lines))
7185         (setq content-type-p
7186               (or mml-boundary
7187                   (re-search-backward "^Content-Type:" nil t))))
7188       (save-restriction
7189         (message-narrow-to-headers-or-head)
7190         (message-remove-first-header "Content-Type")
7191         (message-remove-first-header "Content-Transfer-Encoding"))
7192       ;; We always make sure that the message has a Content-Type
7193       ;; header.  This is because some broken MTAs and MUAs get
7194       ;; awfully confused when confronted with a message with a
7195       ;; MIME-Version header and without a Content-Type header.  For
7196       ;; instance, Solaris' /usr/bin/mail.
7197       (unless content-type-p
7198         (goto-char (point-min))
7199         ;; For unknown reason, MIME-Version doesn't exist.
7200         (when (re-search-forward "^MIME-Version:" nil t)
7201           (forward-line 1)
7202           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7203
7204 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7205   "Read from the minibuffer while providing abbrev expansion."
7206   (if (fboundp 'mail-abbrevs-setup)
7207       (let ((mail-abbrev-mode-regexp "")
7208             (minibuffer-setup-hook 'mail-abbrevs-setup)
7209             (minibuffer-local-map message-minibuffer-local-map))
7210         (read-from-minibuffer prompt initial-contents))
7211     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7212           (minibuffer-local-map message-minibuffer-local-map))
7213       (read-string prompt initial-contents))))
7214
7215 (defun message-use-alternative-email-as-from ()
7216   "Set From field of the outgoing message to the first matching
7217 address in `message-alternative-emails', looking at To, Cc and
7218 From headers in the original article."
7219   (require 'mail-utils)
7220   (let* ((fields '("To" "Cc" "From"))
7221          (emails
7222           (split-string
7223            (mail-strip-quoted-names
7224             (mapconcat 'message-fetch-reply-field fields ","))
7225            "[ \f\t\n\r\v,]+"))
7226          email)
7227     (while emails
7228       (if (string-match message-alternative-emails (car emails))
7229           (setq email (car emails)
7230                 emails nil))
7231       (pop emails))
7232     (unless (or (not email) (equal email user-mail-address))
7233       (message-remove-header "From")
7234       (goto-char (point-max))
7235       (insert "From: " (let ((user-mail-address email)) (message-make-from))
7236               "\n"))))
7237
7238 (defun message-options-get (symbol)
7239   (cdr (assq symbol message-options)))
7240
7241 (defun message-options-set (symbol value)
7242   (let ((the-cons (assq symbol message-options)))
7243     (if the-cons
7244         (if value
7245             (setcdr the-cons value)
7246           (setq message-options (delq the-cons message-options)))
7247       (and value
7248            (push (cons symbol value) message-options))))
7249   value)
7250
7251 (defun message-options-set-recipient ()
7252   (save-restriction
7253     (message-narrow-to-headers-or-head)
7254     (message-options-set 'message-sender
7255                          (mail-strip-quoted-names
7256                           (message-fetch-field "from")))
7257     (message-options-set 'message-recipients
7258                          (mail-strip-quoted-names
7259                           (let ((to (message-fetch-field "to"))
7260                                 (cc (message-fetch-field "cc"))
7261                                 (bcc (message-fetch-field "bcc")))
7262                             (concat
7263                              (or to "")
7264                              (if (and to cc) ", ")
7265                              (or cc "")
7266                              (if (and (or to cc) bcc) ", ")
7267                              (or bcc "")))))))
7268
7269 (defun message-hide-headers ()
7270   "Hide headers based on the `message-hidden-headers' variable."
7271   (let ((regexps (if (stringp message-hidden-headers)
7272                      (list message-hidden-headers)
7273                    message-hidden-headers))
7274         (inhibit-point-motion-hooks t)
7275         (after-change-functions nil)
7276         (end-of-headers 0))
7277     (when regexps
7278       (save-excursion
7279         (save-restriction
7280           (message-narrow-to-headers)
7281           (goto-char (point-min))
7282           (while (not (eobp))
7283             (if (not (message-hide-header-p regexps))
7284                 (message-next-header)
7285               (let ((begin (point))
7286                     header header-len)
7287                 (message-next-header)
7288                 (setq header (buffer-substring begin (point))
7289                       header-len (- (point) begin))
7290                 (delete-region begin (point))
7291                 (goto-char (1+ end-of-headers))
7292                 (insert header)
7293                 (setq end-of-headers
7294                       (+ end-of-headers header-len))))))))
7295     (narrow-to-region (1+ end-of-headers) (point-max))))
7296
7297 (defun message-hide-header-p (regexps)
7298   (let ((result nil)
7299         (reverse nil))
7300     (when (eq (car regexps) 'not)
7301       (setq reverse t)
7302       (pop regexps))
7303     (dolist (regexp regexps)
7304       (setq result (or result (looking-at regexp))))
7305     (if reverse
7306         (not result)
7307       result)))
7308
7309 (defun message-put-addresses-in-ecomplete ()
7310   (dolist (header '("to" "cc" "from" "reply-to"))
7311     (let ((value (message-fetch-field header)))
7312       (dolist (string (mail-header-parse-addresses value 'raw))
7313         (setq string
7314               (gnus-replace-in-string
7315                (gnus-replace-in-string string "^ +\\| +$" "") "\n" ""))
7316         (ecomplete-add-item 'mail (car (mail-header-parse-address string))
7317                             string))))
7318   (ecomplete-save))
7319
7320 (defun message-display-abbrev (&optional choose)
7321   "Display the next possible abbrev for the text before point."
7322   (interactive (list t))
7323   (when (and (member (char-after (point-at-bol)) '(?C ?T ? ))
7324              (message-point-in-header-p)
7325              (save-excursion
7326                (save-restriction
7327                  (message-narrow-to-field)
7328                  (goto-char (point-min))
7329                  (looking-at "To\\|Cc"))))
7330     (let* ((end (point))
7331            (start (save-excursion
7332                     (and (re-search-backward "[\n\t ]" nil t)
7333                          (1+ (point)))))
7334            (word (when start (buffer-substring start end)))
7335            (match (when (and word
7336                              (not (zerop (length word))))
7337                     (ecomplete-display-matches 'mail word choose))))
7338       (when (and choose match)
7339         (delete-region start end)
7340         (insert match)))))
7341
7342 (when (featurep 'xemacs)
7343   (require 'messagexmas)
7344   (message-xmas-redefine))
7345
7346 (provide 'message)
7347
7348 (run-hooks 'message-load-hook)
7349
7350 ;; Local Variables:
7351 ;; coding: iso-8859-1
7352 ;; End:
7353
7354 ;; arch-tag: 94b32cac-4504-4b6c-8181-030ebf380ee0
7355 ;;; message.el ends here