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