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