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