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