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