(message-strip-forbidden-properties): Bind
[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   (let ((buffer-read-only nil)
2444         (inhibit-read-only t))
2445     (when (and message-strip-special-text-properties
2446                (message-tamago-not-in-use-p begin))
2447       (dolist (from-to (message-text-with-property 'message-hidden
2448                                                    begin end t))
2449         (remove-text-properties (car from-to) (cdr from-to)
2450                                 message-forbidden-properties)))))
2451
2452 ;;;###autoload
2453 (define-derived-mode message-mode text-mode "Message"
2454   "Major mode for editing mail and news to be sent.
2455 Like Text Mode but with these additional commands:\\<message-mode-map>
2456 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2457 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2458 C-c C-f  move to a header field (and create it if there isn't):
2459          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2460          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2461          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2462          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2463          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2464          C-c C-f C-o  move to From (\"Originator\")
2465          C-c C-f C-f  move to Followup-To
2466          C-c C-f C-m  move to Mail-Followup-To
2467          C-c C-f C-i  cycle through Importance values
2468          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2469          C-c C-f x    crossposting with FollowUp-To header and note in body
2470          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2471          C-c C-f a    Insert X-No-Archive: header and a note in the body
2472 C-c C-t  `message-insert-to' (add a To header to a news followup)
2473 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2474 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2475 C-c C-b  `message-goto-body' (move to beginning of message text).
2476 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2477 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2478 C-c C-y  `message-yank-original' (insert current message, if any).
2479 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2480 C-c C-e  `message-elide-region' (elide the text between point and mark).
2481 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2482 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2483 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2484 C-c C-a  `mml-attach-file' (attach a file as MIME).
2485 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2486 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2487 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2488 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2489 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2490   (setq local-abbrev-table text-mode-abbrev-table)
2491   (set (make-local-variable 'message-reply-buffer) nil)
2492   (set (make-local-variable 'message-inserted-headers) nil)
2493   (set (make-local-variable 'message-send-actions) nil)
2494   (set (make-local-variable 'message-exit-actions) nil)
2495   (set (make-local-variable 'message-kill-actions) nil)
2496   (set (make-local-variable 'message-postpone-actions) nil)
2497   (set (make-local-variable 'message-draft-article) nil)
2498   (setq buffer-offer-save t)
2499   (set (make-local-variable 'facemenu-add-face-function)
2500        (lambda (face end)
2501          (let ((face-fun (cdr (assq face message-face-alist))))
2502            (if face-fun
2503                (funcall face-fun (point) end)
2504              (error "Face %s not configured for %s mode" face mode-name)))
2505          ""))
2506   (set (make-local-variable 'facemenu-remove-face-function) t)
2507   (set (make-local-variable 'message-reply-headers) nil)
2508   (make-local-variable 'message-newsreader)
2509   (make-local-variable 'message-mailer)
2510   (make-local-variable 'message-post-method)
2511   (set (make-local-variable 'message-sent-message-via) nil)
2512   (set (make-local-variable 'message-checksum) nil)
2513   (set (make-local-variable 'message-mime-part) 0)
2514   (message-setup-fill-variables)
2515   ;; Allow using comment commands to add/remove quoting.
2516   ;; (set (make-local-variable 'comment-start) message-yank-prefix)
2517   (when message-yank-prefix
2518     (set (make-local-variable 'comment-start) message-yank-prefix)
2519     (set (make-local-variable 'comment-start-skip)
2520          (concat "^" (regexp-quote message-yank-prefix) "[ \t]*")))
2521   (if (featurep 'xemacs)
2522       (message-setup-toolbar)
2523     (set (make-local-variable 'font-lock-defaults)
2524          '(message-font-lock-keywords t))
2525     (if (boundp 'tool-bar-map)
2526         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2527   (easy-menu-add message-mode-menu message-mode-map)
2528   (easy-menu-add message-mode-field-menu message-mode-map)
2529   (gnus-make-local-hook 'after-change-functions)
2530   ;; Mmmm... Forbidden properties...
2531   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2532             nil 'local)
2533   ;; Allow mail alias things.
2534   (when (eq message-mail-alias-type 'abbrev)
2535     (if (fboundp 'mail-abbrevs-setup)
2536         (mail-abbrevs-setup)
2537       (if (fboundp 'mail-aliases-setup) ; warning avoidance
2538           (mail-aliases-setup))))
2539   (unless buffer-file-name
2540     (message-set-auto-save-file-name))
2541   (unless (buffer-base-buffer)
2542     ;; Don't enable multibyte on an indirect buffer.  Maybe enabling
2543     ;; multibyte is not necessary at all. -- zsh
2544     (mm-enable-multibyte))
2545   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
2546   (mml-mode))
2547
2548 (defun message-setup-fill-variables ()
2549   "Setup message fill variables."
2550   (set (make-local-variable 'fill-paragraph-function)
2551        'message-fill-paragraph)
2552   (make-local-variable 'paragraph-separate)
2553   (make-local-variable 'paragraph-start)
2554   (make-local-variable 'adaptive-fill-regexp)
2555   (unless (boundp 'adaptive-fill-first-line-regexp)
2556     (setq adaptive-fill-first-line-regexp nil))
2557   (make-local-variable 'adaptive-fill-first-line-regexp)
2558   (let ((quote-prefix-regexp
2559          ;; User should change message-cite-prefix-regexp if
2560          ;; message-yank-prefix is set to an abnormal value.
2561          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2562     (setq paragraph-start
2563           (concat
2564            (regexp-quote mail-header-separator) "$\\|"
2565            "[ \t]*$\\|"                 ; blank lines
2566            "-- $\\|"                    ; signature delimiter
2567            "---+$\\|"              ; delimiters for forwarded messages
2568            page-delimiter "$\\|"        ; spoiler warnings
2569            ".*wrote:$\\|"               ; attribution lines
2570            quote-prefix-regexp "$\\|"   ; empty lines in quoted text
2571                                         ; mml tags
2572            "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)"))
2573     (setq paragraph-separate paragraph-start)
2574     (setq adaptive-fill-regexp
2575           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2576     (setq adaptive-fill-first-line-regexp
2577           (concat quote-prefix-regexp "\\|"
2578                   adaptive-fill-first-line-regexp)))
2579   (make-local-variable 'auto-fill-inhibit-regexp)
2580   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2581   (setq auto-fill-inhibit-regexp nil)
2582   (make-local-variable 'normal-auto-fill-function)
2583   (setq normal-auto-fill-function 'message-do-auto-fill)
2584   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2585   ;; In that case, ensure that it uses the right function.  The real
2586   ;; solution would be not to use `define-derived-mode', and run
2587   ;; `text-mode-hook' ourself at the end of the mode.
2588   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2589   (when auto-fill-function
2590     (setq auto-fill-function normal-auto-fill-function)))
2591
2592 \f
2593
2594 ;;;
2595 ;;; Message mode commands
2596 ;;;
2597
2598 ;;; Movement commands
2599
2600 (defun message-goto-to ()
2601   "Move point to the To header."
2602   (interactive)
2603   (message-position-on-field "To"))
2604
2605 (defun message-goto-from ()
2606   "Move point to the From header."
2607   (interactive)
2608   (message-position-on-field "From"))
2609
2610 (defun message-goto-subject ()
2611   "Move point to the Subject header."
2612   (interactive)
2613   (message-position-on-field "Subject"))
2614
2615 (defun message-goto-cc ()
2616   "Move point to the Cc header."
2617   (interactive)
2618   (message-position-on-field "Cc" "To"))
2619
2620 (defun message-goto-bcc ()
2621   "Move point to the Bcc  header."
2622   (interactive)
2623   (message-position-on-field "Bcc" "Cc" "To"))
2624
2625 (defun message-goto-fcc ()
2626   "Move point to the Fcc header."
2627   (interactive)
2628   (message-position-on-field "Fcc" "To" "Newsgroups"))
2629
2630 (defun message-goto-reply-to ()
2631   "Move point to the Reply-To header."
2632   (interactive)
2633   (message-position-on-field "Reply-To" "Subject"))
2634
2635 (defun message-goto-newsgroups ()
2636   "Move point to the Newsgroups header."
2637   (interactive)
2638   (message-position-on-field "Newsgroups"))
2639
2640 (defun message-goto-distribution ()
2641   "Move point to the Distribution header."
2642   (interactive)
2643   (message-position-on-field "Distribution"))
2644
2645 (defun message-goto-followup-to ()
2646   "Move point to the Followup-To header."
2647   (interactive)
2648   (message-position-on-field "Followup-To" "Newsgroups"))
2649
2650 (defun message-goto-mail-followup-to ()
2651   "Move point to the Mail-Followup-To header."
2652   (interactive)
2653   (message-position-on-field "Mail-Followup-To" "To"))
2654
2655 (defun message-goto-keywords ()
2656   "Move point to the Keywords header."
2657   (interactive)
2658   (message-position-on-field "Keywords" "Subject"))
2659
2660 (defun message-goto-summary ()
2661   "Move point to the Summary header."
2662   (interactive)
2663   (message-position-on-field "Summary" "Subject"))
2664
2665 (defun message-goto-body (&optional interactivep)
2666   "Move point to the beginning of the message body."
2667   (interactive (list t))
2668   (when (and interactivep
2669              (looking-at "[ \t]*\n"))
2670     (expand-abbrev))
2671   (goto-char (point-min))
2672   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2673       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2674
2675 (defun message-goto-eoh ()
2676   "Move point to the end of the headers."
2677   (interactive)
2678   (message-goto-body)
2679   (forward-line -1))
2680
2681 (defun message-goto-signature ()
2682   "Move point to the beginning of the message signature.
2683 If there is no signature in the article, go to the end and
2684 return nil."
2685   (interactive)
2686   (goto-char (point-min))
2687   (if (re-search-forward message-signature-separator nil t)
2688       (forward-line 1)
2689     (goto-char (point-max))
2690     nil))
2691
2692 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
2693   "Insert a reasonable MFT header in a post to an unsubscribed list.
2694 When making original posts to a mailing list you are not subscribed to,
2695 you have to type in a MFT header by hand.  The contents, usually, are
2696 the addresses of the list and your own address.  This function inserts
2697 such a header automatically.  It fetches the contents of the To: header
2698 in the current mail buffer, and appends the current `user-mail-address'.
2699
2700 If the optional argument INCLUDE-CC is non-nil, the addresses in the
2701 Cc: header are also put into the MFT."
2702
2703   (interactive "P")
2704   (let* (cc tos)
2705     (save-restriction
2706       (message-narrow-to-headers)
2707       (message-remove-header "Mail-Followup-To")
2708       (setq cc (and include-cc (message-fetch-field "Cc")))
2709       (setq tos (if cc
2710                     (concat (message-fetch-field "To") "," cc)
2711                   (message-fetch-field "To"))))
2712     (message-goto-mail-followup-to)
2713     (insert (concat tos ", " user-mail-address))))
2714
2715 \f
2716
2717 (defun message-insert-to (&optional force)
2718   "Insert a To header that points to the author of the article being replied to.
2719 If the original author requested not to be sent mail, don't insert unless the
2720 prefix FORCE is given."
2721   (interactive "P")
2722   (let* ((mct (message-fetch-reply-field "mail-copies-to"))
2723          (dont (and mct (or (equal (downcase mct) "never")
2724                             (equal (downcase mct) "nobody"))))
2725          (to (or (message-fetch-reply-field "mail-reply-to")
2726                  (message-fetch-reply-field "reply-to")
2727                  (message-fetch-reply-field "from"))))
2728     (when (and dont to)
2729       (message
2730        (if force
2731            "Ignoring the user request not to have copies sent via mail"
2732          "Complying with the user request not to have copies sent via mail")))
2733     (when (and force (not to))
2734       (error "No mail address in the article"))
2735     (when (and to (or force (not dont)))
2736       (message-carefully-insert-headers (list (cons 'To to))))))
2737
2738 (defun message-insert-wide-reply ()
2739   "Insert To and Cc headers as if you were doing a wide reply."
2740   (interactive)
2741   (let ((headers (message-with-reply-buffer
2742                    (message-get-reply-headers t))))
2743     (message-carefully-insert-headers headers)))
2744
2745 (defcustom message-header-synonyms
2746   '((To Cc Bcc))
2747   "List of lists of header synonyms.
2748 E.g., if this list contains a member list with elements `Cc' and `To',
2749 then `message-carefully-insert-headers' will not insert a `To' header
2750 when the message is already `Cc'ed to the recipient."
2751   :version "21.4"
2752   :group 'message-headers
2753   :link '(custom-manual "(message)Message Headers")
2754   :type '(repeat sexp))
2755
2756 (defun message-carefully-insert-headers (headers)
2757   "Insert the HEADERS, an alist, into the message buffer.
2758 Does not insert the headers when they are already present there
2759 or in the synonym headers, defined by `message-header-synonyms'."
2760   ;; FIXME: Should compare only the address and not the full name.  Comparison
2761   ;; should be done case-folded (and with `string=' rather than
2762   ;; `string-match').
2763   ;; (mail-strip-quoted-names "Foo Bar <foo@bar>, bla@fasel (Bla Fasel)")
2764   (dolist (header headers)
2765     (let* ((header-name (symbol-name (car header)))
2766            (new-header (cdr header))
2767            (synonyms (loop for synonym in message-header-synonyms
2768                            when (memq (car header) synonym) return synonym))
2769            (old-header
2770             (loop for synonym in synonyms
2771                   for old-header = (mail-fetch-field (symbol-name synonym))
2772                   when (and old-header (string-match new-header old-header))
2773                   return synonym)))
2774       (if old-header
2775           (message "already have `%s' in `%s'" new-header old-header)
2776         (when (and (message-position-on-field header-name)
2777                    (setq old-header (mail-fetch-field header-name))
2778                    (not (string-match "\\` *\\'" old-header)))
2779           (insert ", "))
2780         (insert new-header)))))
2781
2782 (defun message-widen-reply ()
2783   "Widen the reply to include maximum recipients."
2784   (interactive)
2785   (let ((follow-to
2786          (and message-reply-buffer
2787               (buffer-name message-reply-buffer)
2788               (save-excursion
2789                 (set-buffer message-reply-buffer)
2790                 (message-get-reply-headers t)))))
2791     (save-excursion
2792       (save-restriction
2793         (message-narrow-to-headers)
2794         (dolist (elem follow-to)
2795           (message-remove-header (symbol-name (car elem)))
2796           (goto-char (point-min))
2797           (insert (symbol-name (car elem)) ": "
2798                   (cdr elem) "\n"))))))
2799
2800 (defun message-insert-newsgroups ()
2801   "Insert the Newsgroups header from the article being replied to."
2802   (interactive)
2803   (when (and (message-position-on-field "Newsgroups")
2804              (mail-fetch-field "newsgroups")
2805              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2806     (insert ","))
2807   (insert (or (message-fetch-reply-field "newsgroups") "")))
2808
2809 \f
2810
2811 ;;; Various commands
2812
2813 (defun message-delete-not-region (beg end)
2814   "Delete everything in the body of the current message outside of the region."
2815   (interactive "r")
2816   (let (citeprefix)
2817     (save-excursion
2818       (goto-char beg)
2819       ;; snarf citation prefix, if appropriate
2820       (unless (eq (point) (progn (beginning-of-line) (point)))
2821         (when (looking-at message-cite-prefix-regexp)
2822           (setq citeprefix (match-string 0))))
2823       (goto-char end)
2824       (delete-region (point) (if (not (message-goto-signature))
2825                                  (point)
2826                                (forward-line -2)
2827                                (point)))
2828       (insert "\n")
2829       (goto-char beg)
2830       (delete-region beg (progn (message-goto-body)
2831                                 (forward-line 2)
2832                                 (point)))
2833       (when citeprefix
2834         (insert citeprefix))))
2835   (when (message-goto-signature)
2836     (forward-line -2)))
2837
2838 (defun message-kill-to-signature (&optional arg)
2839   "Kill all text up to the signature.
2840 If a numberic argument or prefix arg is given, leave that number
2841 of lines before the signature intact."
2842   (interactive "p")
2843   (save-excursion
2844     (save-restriction
2845       (let ((point (point)))
2846         (narrow-to-region point (point-max))
2847         (message-goto-signature)
2848         (unless (eobp)
2849           (if (and arg (numberp arg))
2850               (forward-line (- -1 arg))
2851             (end-of-line -1)))
2852         (unless (= point (point))
2853           (kill-region point (point))
2854           (insert "\n"))))))
2855
2856 (defun message-newline-and-reformat (&optional arg not-break)
2857   "Insert four newlines, and then reformat if inside quoted text.
2858 Prefix arg means justify as well."
2859   (interactive (list (if current-prefix-arg 'full)))
2860   (let (quoted point beg end leading-space bolp)
2861     (setq point (point))
2862     (beginning-of-line)
2863     (setq beg (point))
2864     (setq bolp (= beg point))
2865     ;; Find first line of the paragraph.
2866     (if not-break
2867         (while (and (not (eobp))
2868                     (not (looking-at message-cite-prefix-regexp))
2869                     (looking-at paragraph-start))
2870           (forward-line 1)))
2871     ;; Find the prefix
2872     (when (looking-at message-cite-prefix-regexp)
2873       (setq quoted (match-string 0))
2874       (goto-char (match-end 0))
2875       (looking-at "[ \t]*")
2876       (setq leading-space (match-string 0)))
2877     (if (and quoted
2878              (not not-break)
2879              (not bolp)
2880              (< (- point beg) (length quoted)))
2881         ;; break inside the cite prefix.
2882         (setq quoted nil
2883               end nil))
2884     (if quoted
2885         (progn
2886           (forward-line 1)
2887           (while (and (not (eobp))
2888                       (not (looking-at paragraph-separate))
2889                       (looking-at message-cite-prefix-regexp)
2890                       (equal quoted (match-string 0)))
2891             (goto-char (match-end 0))
2892             (looking-at "[ \t]*")
2893             (if (> (length leading-space) (length (match-string 0)))
2894                 (setq leading-space (match-string 0)))
2895             (forward-line 1))
2896           (setq end (point))
2897           (goto-char beg)
2898           (while (and (if (bobp) nil (forward-line -1) t)
2899                       (not (looking-at paragraph-start))
2900                       (looking-at message-cite-prefix-regexp)
2901                       (equal quoted (match-string 0)))
2902             (setq beg (point))
2903             (goto-char (match-end 0))
2904             (looking-at "[ \t]*")
2905             (if (> (length leading-space) (length (match-string 0)))
2906                 (setq leading-space (match-string 0)))))
2907       (while (and (not (eobp))
2908                   (not (looking-at paragraph-separate))
2909                   (not (looking-at message-cite-prefix-regexp)))
2910         (forward-line 1))
2911       (setq end (point))
2912       (goto-char beg)
2913       (while (and (if (bobp) nil (forward-line -1) t)
2914                   (not (looking-at paragraph-start))
2915                   (not (looking-at message-cite-prefix-regexp)))
2916         (setq beg (point))))
2917     (goto-char point)
2918     (save-restriction
2919       (narrow-to-region beg end)
2920       (if not-break
2921           (setq point nil)
2922         (if bolp
2923             (newline)
2924           (newline)
2925           (newline))
2926         (setq point (point))
2927         ;; (newline 2) doesn't mark both newline's as hard, so call
2928         ;; newline twice. -jas
2929         (newline)
2930         (newline)
2931         (delete-region (point) (re-search-forward "[ \t]*"))
2932         (when (and quoted (not bolp))
2933           (insert quoted leading-space)))
2934       (undo-boundary)
2935       (if quoted
2936           (let* ((adaptive-fill-regexp
2937                   (regexp-quote (concat quoted leading-space)))
2938                  (adaptive-fill-first-line-regexp
2939                   adaptive-fill-regexp ))
2940             (fill-paragraph arg))
2941         (fill-paragraph arg))
2942       (if point (goto-char point)))))
2943
2944 (defun message-fill-paragraph (&optional arg)
2945   "Like `fill-paragraph'."
2946   (interactive (list (if current-prefix-arg 'full)))
2947   (if (if (boundp 'filladapt-mode) filladapt-mode)
2948       nil
2949     (if (message-point-in-header-p)
2950         (message-fill-field)
2951       (message-newline-and-reformat arg t))
2952     t))
2953
2954 ;; Is it better to use `mail-header-end'?
2955 (defun message-point-in-header-p ()
2956   "Return t if point is in the header."
2957   (save-excursion
2958     (let ((p (point)))
2959       (goto-char (point-min))
2960       (not (re-search-forward
2961             (concat "^" (regexp-quote mail-header-separator) "\n")
2962             p t)))))
2963
2964 (defun message-do-auto-fill ()
2965   "Like `do-auto-fill', but don't fill in message header."
2966   (unless (message-point-in-header-p)
2967     (do-auto-fill)))
2968
2969 (defun message-insert-signature (&optional force)
2970   "Insert a signature.  See documentation for variable `message-signature'."
2971   (interactive (list 0))
2972   (let* ((signature
2973           (cond
2974            ((and (null message-signature)
2975                  (eq force 0))
2976             (save-excursion
2977               (goto-char (point-max))
2978               (not (re-search-backward message-signature-separator nil t))))
2979            ((and (null message-signature)
2980                  force)
2981             t)
2982            ((functionp message-signature)
2983             (funcall message-signature))
2984            ((listp message-signature)
2985             (eval message-signature))
2986            (t message-signature)))
2987          (signature
2988           (cond ((stringp signature)
2989                  signature)
2990                 ((and (eq t signature)
2991                       message-signature-file
2992                       (file-exists-p message-signature-file))
2993                  signature))))
2994     (when signature
2995       (goto-char (point-max))
2996       ;; Insert the signature.
2997       (unless (bolp)
2998         (insert "\n"))
2999       (when message-signature-insert-empty-line
3000         (insert "\n"))
3001       (insert "-- \n")
3002       (if (eq signature t)
3003           (insert-file-contents message-signature-file)
3004         (insert signature))
3005       (goto-char (point-max))
3006       (or (bolp) (insert "\n")))))
3007
3008 (defun message-insert-importance-high ()
3009   "Insert header to mark message as important."
3010   (interactive)
3011   (save-excursion
3012     (save-restriction
3013       (message-narrow-to-headers)
3014       (message-remove-header "Importance"))
3015     (message-goto-eoh)
3016     (insert "Importance: high\n")))
3017
3018 (defun message-insert-importance-low ()
3019   "Insert header to mark message as unimportant."
3020   (interactive)
3021   (save-excursion
3022     (save-restriction
3023       (message-narrow-to-headers)
3024       (message-remove-header "Importance"))
3025     (message-goto-eoh)
3026     (insert "Importance: low\n")))
3027
3028 (defun message-insert-or-toggle-importance ()
3029   "Insert a \"Importance: high\" header, or cycle through the header values.
3030 The three allowed values according to RFC 1327 are `high', `normal'
3031 and `low'."
3032   (interactive)
3033   (save-excursion
3034     (let ((valid '("high" "normal" "low"))
3035           (new "high")
3036           cur)
3037       (save-restriction
3038         (message-narrow-to-headers)
3039         (when (setq cur (message-fetch-field "Importance"))
3040           (message-remove-header "Importance")
3041           (setq new (cond ((string= cur "high")
3042                            "low")
3043                           ((string= cur "low")
3044                            "normal")
3045                           (t
3046                            "high")))))
3047       (message-goto-eoh)
3048       (insert (format "Importance: %s\n" new)))))
3049
3050 (defun message-insert-disposition-notification-to ()
3051   "Request a disposition notification (return receipt) to this message.
3052 Note that this should not be used in newsgroups."
3053   (interactive)
3054   (save-excursion
3055     (save-restriction
3056       (message-narrow-to-headers)
3057       (message-remove-header "Disposition-Notification-To"))
3058     (message-goto-eoh)
3059     (insert (format "Disposition-Notification-To: %s\n"
3060                     (or (message-field-value "Reply-to")
3061                         (message-field-value "From")
3062                         (message-make-from))))))
3063
3064 (defun message-elide-region (b e)
3065   "Elide the text in the region.
3066 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3067 text was killed."
3068   (interactive "r")
3069   (kill-region b e)
3070   (insert message-elide-ellipsis))
3071
3072 (defvar message-caesar-translation-table nil)
3073
3074 (defun message-caesar-region (b e &optional n)
3075   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3076   (interactive
3077    (list
3078     (min (point) (or (mark t) (point)))
3079     (max (point) (or (mark t) (point)))
3080     (when current-prefix-arg
3081       (prefix-numeric-value current-prefix-arg))))
3082
3083   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3084   (unless (or (zerop n)                 ; no action needed for a rot of 0
3085               (= b e))                  ; no region to rotate
3086     ;; We build the table, if necessary.
3087     (when (or (not message-caesar-translation-table)
3088               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3089       (setq message-caesar-translation-table
3090             (message-make-caesar-translation-table n)))
3091     (translate-region b e message-caesar-translation-table)))
3092
3093 (defun message-make-caesar-translation-table (n)
3094   "Create a rot table with offset N."
3095   (let ((i -1)
3096         (table (make-string 256 0)))
3097     (while (< (incf i) 256)
3098       (aset table i i))
3099     (concat
3100      (substring table 0 ?A)
3101      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3102      (substring table ?A (+ ?A n))
3103      (substring table (+ ?A 26) ?a)
3104      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3105      (substring table ?a (+ ?a n))
3106      (substring table (+ ?a 26) 255))))
3107
3108 (defun message-caesar-buffer-body (&optional rotnum)
3109   "Caesar rotate all letters in the current buffer by 13 places.
3110 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3111 With prefix arg, specifies the number of places to rotate each letter forward.
3112 Mail and USENET news headers are not rotated."
3113   (interactive (if current-prefix-arg
3114                    (list (prefix-numeric-value current-prefix-arg))
3115                  (list nil)))
3116   (save-excursion
3117     (save-restriction
3118       (when (message-goto-body)
3119         (narrow-to-region (point) (point-max)))
3120       (message-caesar-region (point-min) (point-max) rotnum))))
3121
3122 (defun message-pipe-buffer-body (program)
3123   "Pipe the message body in the current buffer through PROGRAM."
3124   (save-excursion
3125     (save-restriction
3126       (when (message-goto-body)
3127         (narrow-to-region (point) (point-max)))
3128       (shell-command-on-region
3129        (point-min) (point-max) program nil t))))
3130
3131 (defun message-rename-buffer (&optional enter-string)
3132   "Rename the *message* buffer to \"*message* RECIPIENT\".
3133 If the function is run with a prefix, it will ask for a new buffer
3134 name, rather than giving an automatic name."
3135   (interactive "Pbuffer name: ")
3136   (save-excursion
3137     (save-restriction
3138       (goto-char (point-min))
3139       (narrow-to-region (point)
3140                         (search-forward mail-header-separator nil 'end))
3141       (let* ((mail-to (or
3142                        (if (message-news-p) (message-fetch-field "Newsgroups")
3143                          (message-fetch-field "To"))
3144                        ""))
3145              (mail-trimmed-to
3146               (if (string-match "," mail-to)
3147                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3148                 mail-to))
3149              (name-default (concat "*message* " mail-trimmed-to))
3150              (name (if enter-string
3151                        (read-string "New buffer name: " name-default)
3152                      name-default)))
3153         (rename-buffer name t)))))
3154
3155 (defun message-fill-yanked-message (&optional justifyp)
3156   "Fill the paragraphs of a message yanked into this one.
3157 Numeric argument means justify as well."
3158   (interactive "P")
3159   (save-excursion
3160     (goto-char (point-min))
3161     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3162     (let ((fill-prefix message-yank-prefix))
3163       (fill-individual-paragraphs (point) (point-max) justifyp))))
3164
3165 (defun message-indent-citation ()
3166   "Modify text just inserted from a message to be cited.
3167 The inserted text should be the region.
3168 When this function returns, the region is again around the modified text.
3169
3170 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3171 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3172   (let ((start (point)))
3173     ;; Remove unwanted headers.
3174     (when message-ignored-cited-headers
3175       (let (all-removed)
3176         (save-restriction
3177           (narrow-to-region
3178            (goto-char start)
3179            (if (search-forward "\n\n" nil t)
3180                (1- (point))
3181              (point)))
3182           (message-remove-header message-ignored-cited-headers t)
3183           (when (= (point-min) (point-max))
3184             (setq all-removed t))
3185           (goto-char (point-max)))
3186         (if all-removed
3187             (goto-char start)
3188           (forward-line 1))))
3189     ;; Delete blank lines at the start of the buffer.
3190     (while (and (point-min)
3191                 (eolp)
3192                 (not (eobp)))
3193       (message-delete-line))
3194     ;; Delete blank lines at the end of the buffer.
3195     (goto-char (point-max))
3196     (unless (eolp)
3197       (insert "\n"))
3198     (while (and (zerop (forward-line -1))
3199                 (looking-at "$"))
3200       (message-delete-line))
3201     ;; Do the indentation.
3202     (if (null message-yank-prefix)
3203         (indent-rigidly start (mark t) message-indentation-spaces)
3204       (save-excursion
3205         (goto-char start)
3206         (while (< (point) (mark t))
3207           (if (or (looking-at ">") (looking-at "^$"))
3208               (insert message-yank-cited-prefix)
3209             (insert message-yank-prefix))
3210           (forward-line 1))))
3211     (goto-char start)))
3212
3213 (defun message-yank-original (&optional arg)
3214   "Insert the message being replied to, if any.
3215 Puts point before the text and mark after.
3216 Normally indents each nonblank line ARG spaces (default 3).  However,
3217 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3218
3219 This function uses `message-cite-function' to do the actual citing.
3220
3221 Just \\[universal-argument] as argument means don't indent, insert no
3222 prefix, and don't delete any headers."
3223   (interactive "P")
3224   (let ((modified (buffer-modified-p)))
3225     (when (and message-reply-buffer
3226                message-cite-function)
3227       (delete-windows-on message-reply-buffer t)
3228       (insert-buffer message-reply-buffer)
3229       (unless arg
3230         (funcall message-cite-function))
3231       (message-exchange-point-and-mark)
3232       (unless (bolp)
3233         (insert ?\n))
3234       (unless modified
3235         (setq message-checksum (message-checksum))))))
3236
3237 (defun message-yank-buffer (buffer)
3238   "Insert BUFFER into the current buffer and quote it."
3239   (interactive "bYank buffer: ")
3240   (let ((message-reply-buffer (get-buffer buffer)))
3241     (save-window-excursion
3242       (message-yank-original))))
3243
3244 (defun message-buffers ()
3245   "Return a list of active message buffers."
3246   (let (buffers)
3247     (save-excursion
3248       (dolist (buffer (buffer-list t))
3249         (set-buffer buffer)
3250         (when (and (eq major-mode 'message-mode)
3251                    (null message-sent-message-via))
3252           (push (buffer-name buffer) buffers))))
3253     (nreverse buffers)))
3254
3255 (defun message-cite-original-without-signature ()
3256   "Cite function in the standard Message manner."
3257   (let* ((start (point))
3258          (end (mark t))
3259          (functions
3260           (when message-indent-citation-function
3261             (if (listp message-indent-citation-function)
3262                 message-indent-citation-function
3263               (list message-indent-citation-function))))
3264          ;; This function may be called by `gnus-summary-yank-message' and
3265          ;; may insert a different article from the original.  So, we will
3266          ;; modify the value of `message-reply-headers' with that article.
3267          (message-reply-headers
3268           (save-restriction
3269             (narrow-to-region start end)
3270             (message-narrow-to-head-1)
3271             (vector 0
3272                     (or (message-fetch-field "subject") "none")
3273                     (message-fetch-field "from")
3274                     (message-fetch-field "date")
3275                     (message-fetch-field "message-id" t)
3276                     (message-fetch-field "references")
3277                     0 0 ""))))
3278     (mml-quote-region start end)
3279     ;; Allow undoing.
3280     (undo-boundary)
3281     (goto-char end)
3282     (when (re-search-backward message-signature-separator start t)
3283       ;; Also peel off any blank lines before the signature.
3284       (forward-line -1)
3285       (while (looking-at "^[ \t]*$")
3286         (forward-line -1))
3287       (forward-line 1)
3288       (delete-region (point) end)
3289       (unless (search-backward "\n\n" start t)
3290         ;; Insert a blank line if it is peeled off.
3291         (insert "\n")))
3292     (goto-char start)
3293     (mapc 'funcall functions)
3294     (when message-citation-line-function
3295       (unless (bolp)
3296         (insert "\n"))
3297       (funcall message-citation-line-function))))
3298
3299 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
3300 (defun message-cite-original ()
3301   "Cite function in the standard Message manner."
3302   (if (and (boundp 'mail-citation-hook)
3303            mail-citation-hook)
3304       (run-hooks 'mail-citation-hook)
3305     (let* ((start (point))
3306            (end (mark t))
3307            (x-no-archive nil)
3308            (functions
3309             (when message-indent-citation-function
3310               (if (listp message-indent-citation-function)
3311                   message-indent-citation-function
3312                 (list message-indent-citation-function))))
3313            ;; This function may be called by `gnus-summary-yank-message' and
3314            ;; may insert a different article from the original.  So, we will
3315            ;; modify the value of `message-reply-headers' with that article.
3316            (message-reply-headers
3317             (save-restriction
3318               (narrow-to-region start end)
3319               (message-narrow-to-head-1)
3320               (setq x-no-archive (message-fetch-field "x-no-archive"))
3321               (vector 0
3322                       (or (message-fetch-field "subject") "none")
3323                       (message-fetch-field "from")
3324                       (message-fetch-field "date")
3325                       (message-fetch-field "message-id" t)
3326                       (message-fetch-field "references")
3327                       0 0 ""))))
3328       (mml-quote-region start end)
3329       (goto-char start)
3330       (mapc 'funcall functions)
3331       (when message-citation-line-function
3332         (unless (bolp)
3333           (insert "\n"))
3334         (funcall message-citation-line-function))
3335       (when (and x-no-archive
3336                  (not message-cite-articles-with-x-no-archive)
3337                  (string-match "yes" x-no-archive))
3338         (undo-boundary)
3339         (delete-region (point) (mark t))
3340         (insert "> [Quoted text removed due to X-No-Archive]\n")
3341         (forward-line -1)))))
3342
3343 (defun message-insert-citation-line ()
3344   "Insert a simple citation line."
3345   (when message-reply-headers
3346     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3347
3348 (defun message-position-on-field (header &rest afters)
3349   (let ((case-fold-search t))
3350     (save-restriction
3351       (narrow-to-region
3352        (goto-char (point-min))
3353        (progn
3354          (re-search-forward
3355           (concat "^" (regexp-quote mail-header-separator) "$"))
3356          (match-beginning 0)))
3357       (goto-char (point-min))
3358       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3359           (progn
3360             (re-search-forward "^[^ \t]" nil 'move)
3361             (beginning-of-line)
3362             (skip-chars-backward "\n")
3363             t)
3364         (while (and afters
3365                     (not (re-search-forward
3366                           (concat "^" (regexp-quote (car afters)) ":")
3367                           nil t)))
3368           (pop afters))
3369         (when afters
3370           (re-search-forward "^[^ \t]" nil 'move)
3371           (beginning-of-line))
3372         (insert header ": \n")
3373         (forward-char -1)
3374         nil))))
3375
3376 (defun message-remove-signature ()
3377   "Remove the signature from the text between point and mark.
3378 The text will also be indented the normal way."
3379   (save-excursion
3380     (let ((start (point))
3381           mark)
3382       (if (not (re-search-forward message-signature-separator (mark t) t))
3383           ;; No signature here, so we just indent the cited text.
3384           (message-indent-citation)
3385         ;; Find the last non-empty line.
3386         (forward-line -1)
3387         (while (looking-at "[ \t]*$")
3388           (forward-line -1))
3389         (forward-line 1)
3390         (setq mark (set-marker (make-marker) (point)))
3391         (goto-char start)
3392         (message-indent-citation)
3393         ;; Enable undoing the deletion.
3394         (undo-boundary)
3395         (delete-region mark (mark t))
3396         (set-marker mark nil)))))
3397
3398 \f
3399
3400 ;;;
3401 ;;; Sending messages
3402 ;;;
3403
3404 (defun message-send-and-exit (&optional arg)
3405   "Send message like `message-send', then, if no errors, exit from mail buffer."
3406   (interactive "P")
3407   (let ((buf (current-buffer))
3408         (actions message-exit-actions))
3409     (when (and (message-send arg)
3410                (buffer-name buf))
3411       (if message-kill-buffer-on-exit
3412           (kill-buffer buf)
3413         (bury-buffer buf)
3414         (when (eq buf (current-buffer))
3415           (message-bury buf)))
3416       (message-do-actions actions)
3417       t)))
3418
3419 (defun message-dont-send ()
3420   "Don't send the message you have been editing.
3421 Instead, just auto-save the buffer and then bury it."
3422   (interactive)
3423   (set-buffer-modified-p t)
3424   (save-buffer)
3425   (let ((actions message-postpone-actions))
3426     (message-bury (current-buffer))
3427     (message-do-actions actions)))
3428
3429 (defun message-kill-buffer ()
3430   "Kill the current buffer."
3431   (interactive)
3432   (when (or (not (buffer-modified-p))
3433             (yes-or-no-p "Message modified; kill anyway? "))
3434     (let ((actions message-kill-actions)
3435           (draft-article message-draft-article)
3436           (auto-save-file-name buffer-auto-save-file-name)
3437           (file-name buffer-file-name)
3438           (modified (buffer-modified-p)))
3439       (setq buffer-file-name nil)
3440       (kill-buffer (current-buffer))
3441       (when (and (or (and auto-save-file-name
3442                           (file-exists-p auto-save-file-name))
3443                      (and file-name
3444                           (file-exists-p file-name)))
3445                  (progn
3446                    ;; If the message buffer has lived in a dedicated window,
3447                    ;; `kill-buffer' has killed the frame.  Thus the
3448                    ;; `yes-or-no-p' may show up in a lowered frame.  Make sure
3449                    ;; that the user can see the question by raising the
3450                    ;; current frame:
3451                    (raise-frame)
3452                    (yes-or-no-p (format "Remove the backup file%s? "
3453                                         (if modified " too" "")))))
3454         (ignore-errors
3455           (delete-file auto-save-file-name))
3456         (let ((message-draft-article draft-article))
3457           (message-disassociate-draft)))
3458       (message-do-actions actions))))
3459
3460 (defun message-bury (buffer)
3461   "Bury this mail BUFFER."
3462   (let ((newbuf (other-buffer buffer)))
3463     (bury-buffer buffer)
3464     (if (and (window-dedicated-p (selected-window))
3465              (not (null (delq (selected-frame) (visible-frame-list)))))
3466         (delete-frame (selected-frame))
3467       (switch-to-buffer newbuf))))
3468
3469 (defun message-send (&optional arg)
3470   "Send the message in the current buffer.
3471 If `message-interactive' is non-nil, wait for success indication or
3472 error messages, and inform user.
3473 Otherwise any failure is reported in a message back to the user from
3474 the mailer.
3475 The usage of ARG is defined by the instance that called Message.
3476 It should typically alter the sending method in some way or other."
3477   (interactive "P")
3478   ;; Make it possible to undo the coming changes.
3479   (undo-boundary)
3480   (let ((inhibit-read-only t))
3481     (put-text-property (point-min) (point-max) 'read-only nil))
3482   (message-fix-before-sending)
3483   (run-hooks 'message-send-hook)
3484   (message message-sending-message)
3485   (let ((alist message-send-method-alist)
3486         (success t)
3487         elem sent dont-barf-on-no-method
3488         (message-options message-options))
3489     (message-options-set-recipient)
3490     (while (and success
3491                 (setq elem (pop alist)))
3492       (when (funcall (cadr elem))
3493         (when (and (or (not (memq (car elem)
3494                                   message-sent-message-via))
3495                        (message-fetch-field "supersedes")
3496                        (if (or (message-gnksa-enable-p 'multiple-copies)
3497                                (not (eq (car elem) 'news)))
3498                            (y-or-n-p
3499                             (format
3500                              "Already sent message via %s; resend? "
3501                              (car elem)))
3502                          (error "Denied posting -- multiple copies")))
3503                    (setq success (funcall (caddr elem) arg)))
3504           (setq sent t))))
3505     (unless (or sent
3506                 (not success)
3507                 (let ((fcc (message-fetch-field "Fcc"))
3508                       (gcc (message-fetch-field "Gcc")))
3509                   (when (or fcc gcc)
3510                     (or (eq message-allow-no-recipients 'always)
3511                         (and (not (eq message-allow-no-recipients 'never))
3512                              (setq dont-barf-on-no-method
3513                                    (gnus-y-or-n-p
3514                                     (format "No receiver, perform %s anyway? "
3515                                             (cond ((and fcc gcc) "Fcc and Gcc")
3516                                                   (fcc "Fcc")
3517                                                   (t "Gcc"))))))))))
3518       (error "No methods specified to send by"))
3519     (when (or dont-barf-on-no-method
3520               (and success sent))
3521       (message-do-fcc)
3522       (save-excursion
3523         (run-hooks 'message-sent-hook))
3524       (message "Sending...done")
3525       ;; Mark the buffer as unmodified and delete auto-save.
3526       (set-buffer-modified-p nil)
3527       (delete-auto-save-file-if-necessary t)
3528       (message-disassociate-draft)
3529       ;; Delete other mail buffers and stuff.
3530       (message-do-send-housekeeping)
3531       (message-do-actions message-send-actions)
3532       ;; Return success.
3533       t)))
3534
3535 (defun message-send-via-mail (arg)
3536   "Send the current message via mail."
3537   (message-send-mail arg))
3538
3539 (defun message-send-via-news (arg)
3540   "Send the current message via news."
3541   (funcall message-send-news-function arg))
3542
3543 (defmacro message-check (type &rest forms)
3544   "Eval FORMS if TYPE is to be checked."
3545   `(or (message-check-element ,type)
3546        (save-excursion
3547          ,@forms)))
3548
3549 (put 'message-check 'lisp-indent-function 1)
3550 (put 'message-check 'edebug-form-spec '(form body))
3551
3552 (defun message-text-with-property (prop &optional start end reverse)
3553   "Return a list of start and end positions where the text has PROP.
3554 START and END bound the search, they default to `point-min' and
3555 `point-max' respectively.  If REVERSE is non-nil, find text which does
3556 not have PROP."
3557   (unless start
3558     (setq start (point-min)))
3559   (unless end
3560     (setq end (point-max)))
3561   (let (next regions)
3562     (if reverse
3563         (while (and start
3564                     (setq start (text-property-any start end prop nil)))
3565           (setq next (next-single-property-change start prop nil end))
3566           (push (cons start (or next end)) regions)
3567           (setq start next))
3568       (while (and start
3569                   (or (get-text-property start prop)
3570                       (and (setq start (next-single-property-change
3571                                         start prop nil end))
3572                            (get-text-property start prop))))
3573         (setq next (text-property-any start end prop nil))
3574         (push (cons start (or next end)) regions)
3575         (setq start next)))
3576     (nreverse regions)))
3577
3578 (defun message-fix-before-sending ()
3579   "Do various things to make the message nice before sending it."
3580   ;; Make sure there's a newline at the end of the message.
3581   (goto-char (point-max))
3582   (unless (bolp)
3583     (insert "\n"))
3584   ;; Make the hidden headers visible.
3585   (dolist (from-to (message-text-with-property 'message-hidden))
3586     (add-text-properties (car from-to) (cdr from-to)
3587                          '(invisible nil intangible nil)))
3588   ;; Make invisible text visible.
3589   ;; It doesn't seem as if this is useful, since the invisible property
3590   ;; is clobbered by an after-change hook anyhow.
3591   (message-check 'invisible-text
3592     (let ((regions (message-text-with-property 'invisible))
3593           from to)
3594       (when regions
3595         (while regions
3596           (setq from (caar regions)
3597                 to (cdar regions)
3598                 regions (cdr regions))
3599           (put-text-property from to 'invisible nil)
3600           (message-overlay-put (message-make-overlay from to)
3601                                'face 'highlight))
3602         (unless (yes-or-no-p
3603                  "Invisible text found and made visible; continue sending? ")
3604           (error "Invisible text found and made visible")))))
3605   (message-check 'illegible-text
3606     (let (found choice)
3607       (message-goto-body)
3608       (skip-chars-forward mm-7bit-chars)
3609       (while (not (eobp))
3610         (when (let ((char (char-after)))
3611                 (or (< (mm-char-int char) 128)
3612                     (and (mm-multibyte-p)
3613                          (memq (char-charset char)
3614                                '(eight-bit-control eight-bit-graphic
3615                                                    control-1))
3616                          (not (get-text-property
3617                                (point) 'untranslated-utf-8)))))
3618           (message-overlay-put (message-make-overlay (point) (1+ (point)))
3619                                'face 'highlight)
3620           (setq found t))
3621         (forward-char)
3622         (skip-chars-forward mm-7bit-chars))
3623       (when found
3624         (setq choice
3625               (gnus-multiple-choice
3626                "Non-printable characters found.  Continue sending?"
3627                '((?d "Remove non-printable characters and send")
3628                  (?r "Replace non-printable characters with dots and send")
3629                  (?i "Ignore non-printable characters and send")
3630                  (?e "Continue editing"))))
3631         (if (eq choice ?e)
3632           (error "Non-printable characters"))
3633         (message-goto-body)
3634         (skip-chars-forward mm-7bit-chars)
3635         (while (not (eobp))
3636           (when (let ((char (char-after)))
3637                   (or (< (mm-char-int char) 128)
3638                       (and (mm-multibyte-p)
3639                            ;; Fixme: Wrong for Emacs 22 and for things
3640                            ;; like undecable utf-8.  Should at least
3641                            ;; use find-coding-systems-region.
3642                            (memq (char-charset char)
3643                                  '(eight-bit-control eight-bit-graphic
3644                                                      control-1))
3645                            (not (get-text-property
3646                                  (point) 'untranslated-utf-8)))))
3647             (if (eq choice ?i)
3648                 (message-kill-all-overlays)
3649               (delete-char 1)
3650               (when (eq choice ?r)
3651                 (insert "."))))
3652           (forward-char)
3653           (skip-chars-forward mm-7bit-chars))))))
3654
3655 (defun message-add-action (action &rest types)
3656   "Add ACTION to be performed when doing an exit of type TYPES."
3657   (while types
3658     (add-to-list (intern (format "message-%s-actions" (pop types)))
3659                  action)))
3660
3661 (defun message-delete-action (action &rest types)
3662   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3663   (let (var)
3664     (while types
3665       (set (setq var (intern (format "message-%s-actions" (pop types))))
3666            (delq action (symbol-value var))))))
3667
3668 (defun message-do-actions (actions)
3669   "Perform all actions in ACTIONS."
3670   ;; Now perform actions on successful sending.
3671   (dolist (action actions)
3672     (ignore-errors
3673       (cond
3674        ;; A simple function.
3675        ((functionp action)
3676         (funcall action))
3677        ;; Something to be evaled.
3678        (t
3679         (eval action))))))
3680
3681 (defun message-send-mail-partially ()
3682   "Send mail as message/partial."
3683   ;; replace the header delimiter with a blank line
3684   (goto-char (point-min))
3685   (re-search-forward
3686    (concat "^" (regexp-quote mail-header-separator) "\n"))
3687   (replace-match "\n")
3688   (run-hooks 'message-send-mail-hook)
3689   (let ((p (goto-char (point-min)))
3690         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3691         (curbuf (current-buffer))
3692         (id (message-make-message-id)) (n 1)
3693         plist total  header required-mail-headers)
3694     (while (not (eobp))
3695       (if (< (point-max) (+ p message-send-mail-partially-limit))
3696           (goto-char (point-max))
3697         (goto-char (+ p message-send-mail-partially-limit))
3698         (beginning-of-line)
3699         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3700       (push p plist)
3701       (setq p (point)))
3702     (setq total (length plist))
3703     (push (point-max) plist)
3704     (setq plist (nreverse plist))
3705     (unwind-protect
3706         (save-excursion
3707           (setq p (pop plist))
3708           (while plist
3709             (set-buffer curbuf)
3710             (copy-to-buffer tembuf p (car plist))
3711             (set-buffer tembuf)
3712             (goto-char (point-min))
3713             (if header
3714                 (progn
3715                   (goto-char (point-min))
3716                   (narrow-to-region (point) (point))
3717                   (insert header))
3718               (message-goto-eoh)
3719               (setq header (buffer-substring (point-min) (point)))
3720               (goto-char (point-min))
3721               (narrow-to-region (point) (point))
3722               (insert header)
3723               (message-remove-header "Mime-Version")
3724               (message-remove-header "Content-Type")
3725               (message-remove-header "Content-Transfer-Encoding")
3726               (message-remove-header "Message-ID")
3727               (message-remove-header "Lines")
3728               (goto-char (point-max))
3729               (insert "Mime-Version: 1.0\n")
3730               (setq header (buffer-string)))
3731             (goto-char (point-max))
3732             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3733                             id n total))
3734             (forward-char -1)
3735             (let ((mail-header-separator ""))
3736               (when (memq 'Message-ID message-required-mail-headers)
3737                 (insert "Message-ID: " (message-make-message-id) "\n"))
3738               (when (memq 'Lines message-required-mail-headers)
3739                 (insert "Lines: " (message-make-lines) "\n"))
3740               (message-goto-subject)
3741               (end-of-line)
3742               (insert (format " (%d/%d)" n total))
3743               (widen)
3744               (mm-with-unibyte-current-buffer
3745                 (funcall (or message-send-mail-real-function
3746                              message-send-mail-function))))
3747             (setq n (+ n 1))
3748             (setq p (pop plist))
3749             (erase-buffer)))
3750       (kill-buffer tembuf))))
3751
3752 (defun message-send-mail (&optional arg)
3753   (require 'mail-utils)
3754   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3755          (case-fold-search nil)
3756          (news (message-news-p))
3757          (mailbuf (current-buffer))
3758          (message-this-is-mail t)
3759          (message-posting-charset
3760           (if (fboundp 'gnus-setup-posting-charset)
3761               (gnus-setup-posting-charset nil)
3762             message-posting-charset))
3763          (headers message-required-mail-headers))
3764     (when message-generate-hashcash
3765       (message "Generating hashcash...")
3766       ;; Wait for calculations already started to finish...
3767       (hashcash-wait-async)
3768       ;; ...and do calculations not already done.  mail-add-payment
3769       ;; will leave existing X-Hashcash headers alone.
3770       (mail-add-payment)
3771       (message "Generating hashcash...done"))
3772     (save-restriction
3773       (message-narrow-to-headers)
3774       ;; Generate the Mail-Followup-To header if the header is not there...
3775       (if (and (message-subscribed-p)
3776                (not (mail-fetch-field "mail-followup-to")))
3777           (setq headers
3778                 (cons
3779                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
3780                  message-required-mail-headers))
3781         ;; otherwise, delete the MFT header if the field is empty
3782         (when (equal "" (mail-fetch-field "mail-followup-to"))
3783           (message-remove-header "^Mail-Followup-To:")))
3784       ;; Insert some headers.
3785       (let ((message-deletable-headers
3786              (if news nil message-deletable-headers)))
3787         (message-generate-headers headers))
3788       ;; Let the user do all of the above.
3789       (run-hooks 'message-header-hook))
3790     (unwind-protect
3791         (save-excursion
3792           (set-buffer tembuf)
3793           (erase-buffer)
3794           ;; Avoid copying text props (except hard newlines).
3795           (insert (with-current-buffer mailbuf
3796                     (mml-buffer-substring-no-properties-except-hard-newlines
3797                      (point-min) (point-max))))
3798           ;; Remove some headers.
3799           (message-encode-message-body)
3800           (save-restriction
3801             (message-narrow-to-headers)
3802             ;; We (re)generate the Lines header.
3803             (when (memq 'Lines message-required-mail-headers)
3804               (message-generate-headers '(Lines)))
3805             ;; Remove some headers.
3806             (message-remove-header message-ignored-mail-headers t)
3807             (let ((mail-parse-charset message-default-charset))
3808               (mail-encode-encoded-word-buffer)))
3809           (goto-char (point-max))
3810           ;; require one newline at the end.
3811           (or (= (preceding-char) ?\n)
3812               (insert ?\n))
3813           (message-cleanup-headers)
3814           ;; FIXME: we're inserting the courtesy copy after encoding.
3815           ;; This is wrong if the courtesy copy string contains
3816           ;; non-ASCII characters. -- jh
3817           (when
3818               (save-restriction
3819                 (message-narrow-to-headers)
3820                 (and news
3821                      (or (message-fetch-field "cc")
3822                          (message-fetch-field "bcc")
3823                          (message-fetch-field "to"))
3824                      (let ((content-type (message-fetch-field
3825                                           "content-type")))
3826                        (and
3827                         (or
3828                          (not content-type)
3829                          (string= "text/plain"
3830                                   (car
3831                                    (mail-header-parse-content-type
3832                                     content-type))))
3833                         (not
3834                          (string= "base64"
3835                                   (message-fetch-field
3836                                    "content-transfer-encoding")))))))
3837             (message-insert-courtesy-copy))
3838           (if (or (not message-send-mail-partially-limit)
3839                   (< (buffer-size) message-send-mail-partially-limit)
3840                   (not (message-y-or-n-p
3841                         "The message size is too large, split? "
3842                         t
3843                         "\
3844 The message size, "
3845                         (/ (buffer-size) 1000) "KB, is too large.
3846
3847 Some mail gateways (MTA's) bounce large messages.  To avoid the
3848 problem, answer `y', and the message will be split into several
3849 smaller pieces, the size of each is about "
3850                         (/ message-send-mail-partially-limit 1000)
3851                         "KB except the last
3852 one.
3853
3854 However, some mail readers (MUA's) can't read split messages, i.e.,
3855 mails in message/partially format. Answer `n', and the message will be
3856 sent in one piece.
3857
3858 The size limit is controlled by `message-send-mail-partially-limit'.
3859 If you always want Gnus to send messages in one piece, set
3860 `message-send-mail-partially-limit' to nil.
3861 ")))
3862               (mm-with-unibyte-current-buffer
3863                 (message "Sending via mail...")
3864                 (funcall (or message-send-mail-real-function
3865                              message-send-mail-function)))
3866             (message-send-mail-partially)))
3867       (kill-buffer tembuf))
3868     (set-buffer mailbuf)
3869     (push 'mail message-sent-message-via)))
3870
3871 (defun message-send-mail-with-sendmail ()
3872   "Send off the prepared buffer with sendmail."
3873   (let ((errbuf (if message-interactive
3874                     (message-generate-new-buffer-clone-locals
3875                      " sendmail errors")
3876                   0))
3877         resend-to-addresses delimline)
3878     (unwind-protect
3879         (progn
3880           (let ((case-fold-search t))
3881             (save-restriction
3882               (message-narrow-to-headers)
3883               (setq resend-to-addresses (message-fetch-field "resent-to")))
3884             ;; Change header-delimiter to be what sendmail expects.
3885             (goto-char (point-min))
3886             (re-search-forward
3887              (concat "^" (regexp-quote mail-header-separator) "\n"))
3888             (replace-match "\n")
3889             (backward-char 1)
3890             (setq delimline (point-marker))
3891             (run-hooks 'message-send-mail-hook)
3892             ;; Insert an extra newline if we need it to work around
3893             ;; Sun's bug that swallows newlines.
3894             (goto-char (1+ delimline))
3895             (when (eval message-mailer-swallows-blank-line)
3896               (newline))
3897             (when message-interactive
3898               (with-current-buffer errbuf
3899                 (erase-buffer))))
3900           (let* ((default-directory "/")
3901                  (coding-system-for-write message-send-coding-system)
3902                  (cpr (apply
3903                        'call-process-region
3904                        (append
3905                         (list (point-min) (point-max)
3906                               (if (boundp 'sendmail-program)
3907                                   sendmail-program
3908                                 "/usr/lib/sendmail")
3909                               nil errbuf nil "-oi")
3910                         ;; Always specify who from,
3911                         ;; since some systems have broken sendmails.
3912                         ;; But some systems are more broken with -f, so
3913                         ;; we'll let users override this.
3914                         (if (null message-sendmail-f-is-evil)
3915                             (list "-f" (message-sendmail-envelope-from)))
3916                         ;; These mean "report errors by mail"
3917                         ;; and "deliver in background".
3918                         (if (null message-interactive) '("-oem" "-odb"))
3919                         ;; Get the addresses from the message
3920                         ;; unless this is a resend.
3921                         ;; We must not do that for a resend
3922                         ;; because we would find the original addresses.
3923                         ;; For a resend, include the specific addresses.
3924                         (if resend-to-addresses
3925                             (list resend-to-addresses)
3926                           '("-t"))))))
3927             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
3928               (error "Sending...failed with exit value %d" cpr)))
3929           (when message-interactive
3930             (save-excursion
3931               (set-buffer errbuf)
3932               (goto-char (point-min))
3933               (while (re-search-forward "\n+ *" nil t)
3934                 (replace-match "; "))
3935               (if (not (zerop (buffer-size)))
3936                   (error "Sending...failed to %s"
3937                          (buffer-string))))))
3938       (when (bufferp errbuf)
3939         (kill-buffer errbuf)))))
3940
3941 (defun message-send-mail-with-qmail ()
3942   "Pass the prepared message buffer to qmail-inject.
3943 Refer to the documentation for the variable `message-send-mail-function'
3944 to find out how to use this."
3945   ;; replace the header delimiter with a blank line
3946   (goto-char (point-min))
3947   (re-search-forward
3948    (concat "^" (regexp-quote mail-header-separator) "\n"))
3949   (replace-match "\n")
3950   (run-hooks 'message-send-mail-hook)
3951   ;; send the message
3952   (case
3953       (let ((coding-system-for-write message-send-coding-system))
3954         (apply
3955          'call-process-region (point-min) (point-max)
3956          message-qmail-inject-program nil nil nil
3957          ;; qmail-inject's default behaviour is to look for addresses on the
3958          ;; command line; if there're none, it scans the headers.
3959          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3960          ;;
3961          ;; in general, ALL of qmail-inject's defaults are perfect for simply
3962          ;; reading a formatted (i. e., at least a To: or Resent-To header)
3963          ;; message from stdin.
3964          ;;
3965          ;; qmail also has the advantage of not having been raped by
3966          ;; various vendors, so we don't have to allow for that, either --
3967          ;; compare this with message-send-mail-with-sendmail and weep
3968          ;; for sendmail's lost innocence.
3969          ;;
3970          ;; all this is way cool coz it lets us keep the arguments entirely
3971          ;; free for -inject-arguments -- a big win for the user and for us
3972          ;; since we don't have to play that double-guessing game and the user
3973          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3974          (if (functionp message-qmail-inject-args)
3975              (funcall message-qmail-inject-args)
3976            message-qmail-inject-args)))
3977     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3978     ;; we have to look at the retval instead
3979     (0 nil)
3980     (100 (error "qmail-inject reported permanent failure"))
3981     (111 (error "qmail-inject reported transient failure"))
3982     ;; should never happen
3983     (t   (error "qmail-inject reported unknown failure"))))
3984
3985 (defun message-send-mail-with-mh ()
3986   "Send the prepared message buffer with mh."
3987   (let ((mh-previous-window-config nil)
3988         (name (mh-new-draft-name)))
3989     (setq buffer-file-name name)
3990     ;; MH wants to generate these headers itself.
3991     (when message-mh-deletable-headers
3992       (let ((headers message-mh-deletable-headers))
3993         (while headers
3994           (goto-char (point-min))
3995           (and (re-search-forward
3996                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3997                (message-delete-line))
3998           (pop headers))))
3999     (run-hooks 'message-send-mail-hook)
4000     ;; Pass it on to mh.
4001     (mh-send-letter)))
4002
4003 (defun message-smtpmail-send-it ()
4004   "Send the prepared message buffer with `smtpmail-send-it'.
4005 This only differs from `smtpmail-send-it' that this command evaluates
4006 `message-send-mail-hook' just before sending a message.  It is useful
4007 if your ISP requires the POP-before-SMTP authentication.  See the Gnus
4008 manual for details."
4009   (run-hooks 'message-send-mail-hook)
4010   (smtpmail-send-it))
4011
4012 (defun message-canlock-generate ()
4013   "Return a string that is non-trivial to guess.
4014 Do not use this for anything important, it is cryptographically weak."
4015   (require 'sha1)
4016   (let (sha1-maximum-internal-length)
4017     (sha1 (concat (message-unique-id)
4018                   (format "%x%x%x" (random) (random t) (random))
4019                   (prin1-to-string (recent-keys))
4020                   (prin1-to-string (garbage-collect))))))
4021
4022 (defun message-canlock-password ()
4023   "The password used by message for cancel locks.
4024 This is the value of `canlock-password', if that option is non-nil.
4025 Otherwise, generate and save a value for `canlock-password' first."
4026   (unless canlock-password
4027     (customize-save-variable 'canlock-password (message-canlock-generate))
4028     (setq canlock-password-for-verify canlock-password))
4029   canlock-password)
4030
4031 (defun message-insert-canlock ()
4032   (when message-insert-canlock
4033     (message-canlock-password)
4034     (canlock-insert-header)))
4035
4036 (defun message-send-news (&optional arg)
4037   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4038          (case-fold-search nil)
4039          (method (if (functionp message-post-method)
4040                      (funcall message-post-method arg)
4041                    message-post-method))
4042          (newsgroups-field (save-restriction
4043                             (message-narrow-to-headers-or-head)
4044                             (message-fetch-field "Newsgroups")))
4045          (followup-field (save-restriction
4046                            (message-narrow-to-headers-or-head)
4047                            (message-fetch-field "Followup-To")))
4048          ;; BUG: We really need to get the charset for each name in the
4049          ;; Newsgroups and Followup-To lines to allow crossposting
4050          ;; between group namess with incompatible character sets.
4051          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4052          (group-field-charset
4053           (gnus-group-name-charset method newsgroups-field))
4054          (followup-field-charset
4055           (gnus-group-name-charset method (or followup-field "")))
4056          (rfc2047-header-encoding-alist
4057           (append (when group-field-charset
4058                     (list (cons "Newsgroups" group-field-charset)))
4059                   (when followup-field-charset
4060                     (list (cons "Followup-To" followup-field-charset)))
4061                   rfc2047-header-encoding-alist))
4062          (messbuf (current-buffer))
4063          (message-syntax-checks
4064           (if (and arg
4065                    (listp message-syntax-checks))
4066               (cons '(existing-newsgroups . disabled)
4067                     message-syntax-checks)
4068             message-syntax-checks))
4069          (message-this-is-news t)
4070          (message-posting-charset
4071           (gnus-setup-posting-charset newsgroups-field))
4072          result)
4073     (if (not (message-check-news-body-syntax))
4074         nil
4075       (save-restriction
4076         (message-narrow-to-headers)
4077         ;; Insert some headers.
4078         (message-generate-headers message-required-news-headers)
4079         (message-insert-canlock)
4080         ;; Let the user do all of the above.
4081         (run-hooks 'message-header-hook))
4082       ;; Note: This check will be disabled by the ".*" default value for
4083       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4084       (when (and group-field-charset
4085                  (listp message-syntax-checks))
4086         (setq message-syntax-checks
4087               (cons '(valid-newsgroups . disabled)
4088                     message-syntax-checks)))
4089       (message-cleanup-headers)
4090       (if (not (let ((message-post-method method))
4091                  (message-check-news-syntax)))
4092           nil
4093         (unwind-protect
4094             (save-excursion
4095               (set-buffer tembuf)
4096               (buffer-disable-undo)
4097               (erase-buffer)
4098               ;; Avoid copying text props (except hard newlines).
4099               (insert
4100                (with-current-buffer messbuf
4101                  (mml-buffer-substring-no-properties-except-hard-newlines
4102                   (point-min) (point-max))))
4103               (message-encode-message-body)
4104               ;; Remove some headers.
4105               (save-restriction
4106                 (message-narrow-to-headers)
4107                 ;; We (re)generate the Lines header.
4108                 (when (memq 'Lines message-required-mail-headers)
4109                   (message-generate-headers '(Lines)))
4110                 ;; Remove some headers.
4111                 (message-remove-header message-ignored-news-headers t)
4112                 (let ((mail-parse-charset message-default-charset))
4113                   (mail-encode-encoded-word-buffer)))
4114               (goto-char (point-max))
4115               ;; require one newline at the end.
4116               (or (= (preceding-char) ?\n)
4117                   (insert ?\n))
4118               (let ((case-fold-search t))
4119                 ;; Remove the delimiter.
4120                 (goto-char (point-min))
4121                 (re-search-forward
4122                  (concat "^" (regexp-quote mail-header-separator) "\n"))
4123                 (replace-match "\n")
4124                 (backward-char 1))
4125               (run-hooks 'message-send-news-hook)
4126               (gnus-open-server method)
4127               (message "Sending news via %s..." (gnus-server-string method))
4128               (setq result (let ((mail-header-separator ""))
4129                              (gnus-request-post method))))
4130           (kill-buffer tembuf))
4131         (set-buffer messbuf)
4132         (if result
4133             (push 'news message-sent-message-via)
4134           (message "Couldn't send message via news: %s"
4135                    (nnheader-get-report (car method)))
4136           nil)))))
4137
4138 ;;;
4139 ;;; Header generation & syntax checking.
4140 ;;;
4141
4142 (defun message-check-element (type)
4143   "Return non-nil if this TYPE is not to be checked."
4144   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4145       t
4146     (let ((able (assq type message-syntax-checks)))
4147       (and (consp able)
4148            (eq (cdr able) 'disabled)))))
4149
4150 (defun message-check-news-syntax ()
4151   "Check the syntax of the message."
4152   (save-excursion
4153     (save-restriction
4154       (widen)
4155       ;; We narrow to the headers and check them first.
4156       (save-excursion
4157         (save-restriction
4158           (message-narrow-to-headers)
4159           (message-check-news-header-syntax))))))
4160
4161 (defun message-check-news-header-syntax ()
4162   (and
4163    ;; Check Newsgroups header.
4164    (message-check 'newsgroups
4165      (let ((group (message-fetch-field "newsgroups")))
4166        (or
4167         (and group
4168              (not (string-match "\\`[ \t]*\\'" group)))
4169         (ignore
4170          (message
4171           "The newsgroups field is empty or missing.  Posting is denied.")))))
4172    ;; Check the Subject header.
4173    (message-check 'subject
4174      (let* ((case-fold-search t)
4175             (subject (message-fetch-field "subject")))
4176        (or
4177         (and subject
4178              (not (string-match "\\`[ \t]*\\'" subject)))
4179         (ignore
4180          (message
4181           "The subject field is empty or missing.  Posting is denied.")))))
4182    ;; Check for commands in Subject.
4183    (message-check 'subject-cmsg
4184      (if (string-match "^cmsg " (message-fetch-field "subject"))
4185          (y-or-n-p
4186           "The control code \"cmsg\" is in the subject.  Really post? ")
4187        t))
4188    ;; Check long header lines.
4189    (message-check 'long-header-lines
4190      (let ((start (point))
4191            (header nil)
4192            (length 0)
4193            found)
4194        (while (and (not found)
4195                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4196          (if (> (- (point) (match-beginning 0)) 998)
4197              (setq found t
4198                    length (- (point) (match-beginning 0)))
4199            (setq header (match-string-no-properties 1)))
4200          (setq start (match-beginning 0))
4201          (forward-line 1))
4202        (if found
4203            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4204                              header length))
4205          t)))
4206    ;; Check for multiple identical headers.
4207    (message-check 'multiple-headers
4208      (let (found)
4209        (while (and (not found)
4210                    (re-search-forward "^[^ \t:]+: " nil t))
4211          (save-excursion
4212            (or (re-search-forward
4213                 (concat "^"
4214                         (regexp-quote
4215                          (setq found
4216                                (buffer-substring
4217                                 (match-beginning 0) (- (match-end 0) 2))))
4218                         ":")
4219                 nil t)
4220                (setq found nil))))
4221        (if found
4222            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4223          t)))
4224    ;; Check for Version and Sendsys.
4225    (message-check 'sendsys
4226      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4227          (y-or-n-p
4228           (format "The article contains a %s command.  Really post? "
4229                   (buffer-substring (match-beginning 0)
4230                                     (1- (match-end 0)))))
4231        t))
4232    ;; See whether we can shorten Followup-To.
4233    (message-check 'shorten-followup-to
4234      (let ((newsgroups (message-fetch-field "newsgroups"))
4235            (followup-to (message-fetch-field "followup-to"))
4236            to)
4237        (when (and newsgroups
4238                   (string-match "," newsgroups)
4239                   (not followup-to)
4240                   (not
4241                    (zerop
4242                     (length
4243                      (setq to (completing-read
4244                                "Followups to (default: no Followup-To header) "
4245                                (mapcar #'list
4246                                        (cons "poster"
4247                                              (message-tokenize-header
4248                                               newsgroups)))))))))
4249          (goto-char (point-min))
4250          (insert "Followup-To: " to "\n"))
4251        t))
4252    ;; Check "Shoot me".
4253    (message-check 'shoot
4254      (if (re-search-forward
4255           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4256          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4257        t))
4258    ;; Check for Approved.
4259    (message-check 'approved
4260      (if (re-search-forward "^Approved:" nil t)
4261          (y-or-n-p "The article contains an Approved header.  Really post? ")
4262        t))
4263    ;; Check the Message-ID header.
4264    (message-check 'message-id
4265      (let* ((case-fold-search t)
4266             (message-id (message-fetch-field "message-id" t)))
4267        (or (not message-id)
4268            ;; Is there an @ in the ID?
4269            (and (string-match "@" message-id)
4270                 ;; Is there a dot in the ID?
4271                 (string-match "@[^.]*\\." message-id)
4272                 ;; Does the ID end with a dot?
4273                 (not (string-match "\\.>" message-id)))
4274            (y-or-n-p
4275             (format "The Message-ID looks strange: \"%s\".  Really post? "
4276                     message-id)))))
4277    ;; Check the Newsgroups & Followup-To headers.
4278    (message-check 'existing-newsgroups
4279      (let* ((case-fold-search t)
4280             (newsgroups (message-fetch-field "newsgroups"))
4281             (followup-to (message-fetch-field "followup-to"))
4282             (groups (message-tokenize-header
4283                      (if followup-to
4284                          (concat newsgroups "," followup-to)
4285                        newsgroups)))
4286             (post-method (if (functionp message-post-method)
4287                              (funcall message-post-method)
4288                            message-post-method))
4289             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4290             ;; would probably involve a new nnoo function.
4291             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4292             (method (if (and (consp post-method)
4293                              (eq (car post-method) 'nnvirtual)
4294                              gnus-message-group-art)
4295                         (let ((group (car (nnvirtual-find-group-art
4296                                            (car gnus-message-group-art)
4297                                            (cdr gnus-message-group-art)))))
4298                           (gnus-find-method-for-group group))
4299                       post-method))
4300             (known-groups
4301              (mapcar (lambda (n)
4302                        (gnus-group-name-decode
4303                         (gnus-group-real-name n)
4304                         (gnus-group-name-charset method n)))
4305                      (gnus-groups-from-server method)))
4306             errors)
4307        (while groups
4308          (when (and (not (equal (car groups) "poster"))
4309                     (not (member (car groups) known-groups))
4310                     (not (member (car groups) errors)))
4311            (push (car groups) errors))
4312          (pop groups))
4313        (cond
4314         ;; Gnus is not running.
4315         ((or (not (and (boundp 'gnus-active-hashtb)
4316                        gnus-active-hashtb))
4317              (not (boundp 'gnus-read-active-file)))
4318          t)
4319         ;; We don't have all the group names.
4320         ((and (or (not gnus-read-active-file)
4321                   (eq gnus-read-active-file 'some))
4322               errors)
4323          (y-or-n-p
4324           (format
4325            "Really use %s possibly unknown group%s: %s? "
4326            (if (= (length errors) 1) "this" "these")
4327            (if (= (length errors) 1) "" "s")
4328            (mapconcat 'identity errors ", "))))
4329         ;; There were no errors.
4330         ((not errors)
4331          t)
4332         ;; There are unknown groups.
4333         (t
4334          (y-or-n-p
4335           (format
4336            "Really post to %s unknown group%s: %s? "
4337            (if (= (length errors) 1) "this" "these")
4338            (if (= (length errors) 1) "" "s")
4339            (mapconcat 'identity errors ", ")))))))
4340    ;; Check continuation headers.
4341    (message-check 'continuation-headers
4342      (goto-char (point-min))
4343      (let ((do-posting t))
4344        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4345          (if (y-or-n-p "Fix continuation lines? ")
4346              (progn
4347                (goto-char (match-beginning 0))
4348                (insert " "))
4349            (unless (y-or-n-p "Send anyway? ")
4350              (setq do-posting nil))))
4351        do-posting))
4352    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4353    (message-check 'valid-newsgroups
4354      (let ((case-fold-search t)
4355            (headers '("Newsgroups" "Followup-To"))
4356            header error)
4357        (while (and headers (not error))
4358          (when (setq header (mail-fetch-field (car headers)))
4359            (if (or
4360                 (not
4361                  (string-match
4362                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4363                   header))
4364                 (memq
4365                  nil (mapcar
4366                       (lambda (g)
4367                         (not (string-match "\\.\\'\\|\\.\\." g)))
4368                       (message-tokenize-header header ","))))
4369                (setq error t)))
4370          (unless error
4371            (pop headers)))
4372        (if (not error)
4373            t
4374          (y-or-n-p
4375           (format "The %s header looks odd: \"%s\".  Really post? "
4376                   (car headers) header)))))
4377    (message-check 'repeated-newsgroups
4378      (let ((case-fold-search t)
4379            (headers '("Newsgroups" "Followup-To"))
4380            header error groups group)
4381        (while (and headers
4382                    (not error))
4383          (when (setq header (mail-fetch-field (pop headers)))
4384            (setq groups (message-tokenize-header header ","))
4385            (while (setq group (pop groups))
4386              (when (member group groups)
4387                (setq error group
4388                      groups nil)))))
4389        (if (not error)
4390            t
4391          (y-or-n-p
4392           (format "Group %s is repeated in headers.  Really post? " error)))))
4393    ;; Check the From header.
4394    (message-check 'from
4395      (let* ((case-fold-search t)
4396             (from (message-fetch-field "from"))
4397             ad)
4398        (cond
4399         ((not from)
4400          (message "There is no From line.  Posting is denied.")
4401          nil)
4402         ((or (not (string-match
4403                    "@[^\\.]*\\."
4404                    (setq ad (nth 1 (mail-extract-address-components
4405                                     from))))) ;larsi@ifi
4406              (string-match "\\.\\." ad) ;larsi@ifi..uio
4407              (string-match "@\\." ad)   ;larsi@.ifi.uio
4408              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4409              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4410              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4411          (message
4412           "Denied posting -- the From looks strange: \"%s\"." from)
4413          nil)
4414         ((let ((addresses (rfc822-addresses from)))
4415            (while (and addresses
4416                        (not (eq (string-to-char (car addresses)) ?\()))
4417              (setq addresses (cdr addresses)))
4418            addresses)
4419          (message
4420           "Denied posting -- bad From address: \"%s\"." from)
4421          nil)
4422         (t t))))
4423    ;; Check the Reply-To header.
4424    (message-check 'reply-to
4425      (let* ((case-fold-search t)
4426             (reply-to (message-fetch-field "reply-to"))
4427             ad)
4428        (cond
4429         ((not reply-to)
4430          t)
4431         ((string-match "," reply-to)
4432          (y-or-n-p
4433           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4434                   reply-to)))
4435         ((or (not (string-match
4436                    "@[^\\.]*\\."
4437                    (setq ad (nth 1 (mail-extract-address-components
4438                                     reply-to))))) ;larsi@ifi
4439              (string-match "\\.\\." ad) ;larsi@ifi..uio
4440              (string-match "@\\." ad)   ;larsi@.ifi.uio
4441              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4442              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4443              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4444          (y-or-n-p
4445           (format
4446            "The Reply-To looks strange: \"%s\". Really post? "
4447            reply-to)))
4448         (t t))))))
4449
4450 (defun message-check-news-body-syntax ()
4451   (and
4452    ;; Check for long lines.
4453    (message-check 'long-lines
4454      (goto-char (point-min))
4455      (re-search-forward
4456       (concat "^" (regexp-quote mail-header-separator) "$"))
4457      (forward-line 1)
4458      (while (and
4459              (or (looking-at
4460                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
4461                  (let ((p (point)))
4462                    (end-of-line)
4463                    (< (- (point) p) 80)))
4464              (zerop (forward-line 1))))
4465      (or (bolp)
4466          (eobp)
4467          (y-or-n-p
4468           "You have lines longer than 79 characters.  Really post? ")))
4469    ;; Check whether the article is empty.
4470    (message-check 'empty
4471      (goto-char (point-min))
4472      (re-search-forward
4473       (concat "^" (regexp-quote mail-header-separator) "$"))
4474      (forward-line 1)
4475      (let ((b (point)))
4476        (goto-char (point-max))
4477        (re-search-backward message-signature-separator nil t)
4478        (beginning-of-line)
4479        (or (re-search-backward "[^ \n\t]" b t)
4480            (if (message-gnksa-enable-p 'empty-article)
4481                (y-or-n-p "Empty article.  Really post? ")
4482              (message "Denied posting -- Empty article.")
4483              nil))))
4484    ;; Check for control characters.
4485    (message-check 'control-chars
4486      (if (re-search-forward
4487           (mm-string-as-multibyte "[\000-\007\013\015-\032\034-\037\200-\237]")
4488           nil t)
4489          (y-or-n-p
4490           "The article contains control characters.  Really post? ")
4491        t))
4492    ;; Check excessive size.
4493    (message-check 'size
4494      (if (> (buffer-size) 60000)
4495          (y-or-n-p
4496           (format "The article is %d octets long.  Really post? "
4497                   (buffer-size)))
4498        t))
4499    ;; Check whether any new text has been added.
4500    (message-check 'new-text
4501      (or
4502       (not message-checksum)
4503       (not (eq (message-checksum) message-checksum))
4504       (if (message-gnksa-enable-p 'quoted-text-only)
4505           (y-or-n-p
4506            "It looks like no new text has been added.  Really post? ")
4507         (message "Denied posting -- no new text has been added.")
4508         nil)))
4509    ;; Check the length of the signature.
4510    (message-check 'signature
4511      (goto-char (point-max))
4512      (if (> (count-lines (point) (point-max)) 5)
4513          (y-or-n-p
4514           (format
4515            "Your .sig is %d lines; it should be max 4.  Really post? "
4516            (1- (count-lines (point) (point-max)))))
4517        t))
4518    ;; Ensure that text follows last quoted portion.
4519    (message-check 'quoting-style
4520      (goto-char (point-max))
4521      (let ((no-problem t))
4522        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4523          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4524        (if no-problem
4525            t
4526          (if (message-gnksa-enable-p 'quoted-text-only)
4527              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4528            ;; Ensure that
4529            (goto-char (point-min))
4530            (re-search-forward
4531             (concat "^" (regexp-quote mail-header-separator) "$"))
4532            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4533                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4534              (message "Denied posting -- only quoted text.")
4535              nil)))))))
4536
4537 (defun message-checksum ()
4538   "Return a \"checksum\" for the current buffer."
4539   (let ((sum 0))
4540     (save-excursion
4541       (goto-char (point-min))
4542       (re-search-forward
4543        (concat "^" (regexp-quote mail-header-separator) "$"))
4544       (while (not (eobp))
4545         (when (not (looking-at "[ \t\n]"))
4546           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4547                             (char-after))))
4548         (forward-char 1)))
4549     sum))
4550
4551 (defun message-do-fcc ()
4552   "Process Fcc headers in the current buffer."
4553   (let ((case-fold-search t)
4554         (buf (current-buffer))
4555         list file
4556         (mml-externalize-attachments message-fcc-externalize-attachments))
4557     (save-excursion
4558       (save-restriction
4559         (message-narrow-to-headers)
4560         (setq file (message-fetch-field "fcc" t)))
4561       (when file
4562         (set-buffer (get-buffer-create " *message temp*"))
4563         (erase-buffer)
4564         (insert-buffer-substring buf)
4565         (message-encode-message-body)
4566         (save-restriction
4567           (message-narrow-to-headers)
4568           (while (setq file (message-fetch-field "fcc" t))
4569             (push file list)
4570             (message-remove-header "fcc" nil t))
4571           (let ((mail-parse-charset message-default-charset)
4572                 (rfc2047-header-encoding-alist
4573                  (cons '("Newsgroups" . default)
4574                        rfc2047-header-encoding-alist)))
4575             (mail-encode-encoded-word-buffer)))
4576         (goto-char (point-min))
4577         (when (re-search-forward
4578                (concat "^" (regexp-quote mail-header-separator) "$")
4579                nil t)
4580           (replace-match "" t t ))
4581         ;; Process FCC operations.
4582         (while list
4583           (setq file (pop list))
4584           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4585               ;; Pipe the article to the program in question.
4586               (call-process-region (point-min) (point-max) shell-file-name
4587                                    nil nil nil shell-command-switch
4588                                    (match-string 1 file))
4589             ;; Save the article.
4590             (setq file (expand-file-name file))
4591             (unless (file-exists-p (file-name-directory file))
4592               (make-directory (file-name-directory file) t))
4593             (if (and message-fcc-handler-function
4594                      (not (eq message-fcc-handler-function 'rmail-output)))
4595                 (funcall message-fcc-handler-function file)
4596               (if (and (file-readable-p file) (mail-file-babyl-p file))
4597                   (rmail-output file 1 nil t)
4598                 (let ((mail-use-rfc822 t))
4599                   (rmail-output file 1 t t))))))
4600         (kill-buffer (current-buffer))))))
4601
4602 (defun message-output (filename)
4603   "Append this article to Unix/babyl mail file FILENAME."
4604   (if (and (file-readable-p filename)
4605            (mail-file-babyl-p filename))
4606       (gnus-output-to-rmail filename t)
4607     (gnus-output-to-mail filename t)))
4608
4609 (defun message-cleanup-headers ()
4610   "Do various automatic cleanups of the headers."
4611   ;; Remove empty lines in the header.
4612   (save-restriction
4613     (message-narrow-to-headers)
4614     ;; Remove blank lines.
4615     (while (re-search-forward "^[ \t]*\n" nil t)
4616       (replace-match "" t t))
4617
4618     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4619     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4620     ;; embedded line breaks.
4621     (goto-char (point-min))
4622     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4623       (save-restriction
4624         (narrow-to-region
4625          (point)
4626          (if (re-search-forward "^[^ \t]" nil t)
4627              (match-beginning 0)
4628            (forward-line 1)
4629            (point)))
4630         (goto-char (point-min))
4631         (while (re-search-forward "\n[ \t]+" nil t)
4632           (replace-match " " t t))     ;No line breaks (too confusing)
4633         (goto-char (point-min))
4634         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4635           (replace-match "," t t))
4636         (goto-char (point-min))
4637         ;; Remove trailing commas.
4638         (when (re-search-forward ",+$" nil t)
4639           (replace-match "" t t))))))
4640
4641 (defun message-make-date (&optional now)
4642   "Make a valid data header.
4643 If NOW, use that time instead."
4644   (let ((system-time-locale "C"))
4645     (format-time-string "%a, %d %b %Y %T %z" now)))
4646
4647 (defun message-make-message-id ()
4648   "Make a unique Message-ID."
4649   (concat "<" (message-unique-id)
4650           (let ((psubject (save-excursion (message-fetch-field "subject")))
4651                 (psupersedes
4652                  (save-excursion (message-fetch-field "supersedes"))))
4653             (if (or
4654                  (and message-reply-headers
4655                       (mail-header-references message-reply-headers)
4656                       (mail-header-subject message-reply-headers)
4657                       psubject
4658                       (not (string=
4659                             (message-strip-subject-re
4660                              (mail-header-subject message-reply-headers))
4661                             (message-strip-subject-re psubject))))
4662                  (and psupersedes
4663                       (string-match "_-_@" psupersedes)))
4664                 "_-_" ""))
4665           "@" (message-make-fqdn) ">"))
4666
4667 (defvar message-unique-id-char nil)
4668
4669 ;; If you ever change this function, make sure the new version
4670 ;; cannot generate IDs that the old version could.
4671 ;; You might for example insert a "." somewhere (not next to another dot
4672 ;; or string boundary), or modify the "fsf" string.
4673 (defun message-unique-id ()
4674   ;; Don't use microseconds from (current-time), they may be unsupported.
4675   ;; Instead we use this randomly inited counter.
4676   (setq message-unique-id-char
4677         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4678            ;; (current-time) returns 16-bit ints,
4679            ;; and 2^16*25 just fits into 4 digits i base 36.
4680            (* 25 25)))
4681   (let ((tm (current-time)))
4682     (concat
4683      (if (memq system-type '(ms-dos emx vax-vms))
4684          (let ((user (downcase (user-login-name))))
4685            (while (string-match "[^a-z0-9_]" user)
4686              (aset user (match-beginning 0) ?_))
4687            user)
4688        (message-number-base36 (user-uid) -1))
4689      (message-number-base36 (+ (car tm)
4690                                (lsh (% message-unique-id-char 25) 16)) 4)
4691      (message-number-base36 (+ (nth 1 tm)
4692                                (lsh (/ message-unique-id-char 25) 16)) 4)
4693      ;; Append a given name, because while the generated ID is unique
4694      ;; to this newsreader, other newsreaders might otherwise generate
4695      ;; the same ID via another algorithm.
4696      ".fsf")))
4697
4698 (defun message-number-base36 (num len)
4699   (if (if (< len 0)
4700           (<= num 0)
4701         (= len 0))
4702       ""
4703     (concat (message-number-base36 (/ num 36) (1- len))
4704             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4705                                   (% num 36))))))
4706
4707 (defun message-make-organization ()
4708   "Make an Organization header."
4709   (let* ((organization
4710           (when message-user-organization
4711             (if (functionp message-user-organization)
4712                 (funcall message-user-organization)
4713               message-user-organization))))
4714     (with-temp-buffer
4715       (mm-enable-multibyte)
4716       (cond ((stringp organization)
4717              (insert organization))
4718             ((and (eq t organization)
4719                   message-user-organization-file
4720                   (file-exists-p message-user-organization-file))
4721              (insert-file-contents message-user-organization-file)))
4722       (goto-char (point-min))
4723       (while (re-search-forward "[\t\n]+" nil t)
4724         (replace-match "" t t))
4725       (unless (zerop (buffer-size))
4726         (buffer-string)))))
4727
4728 (defun message-make-lines ()
4729   "Count the number of lines and return numeric string."
4730   (save-excursion
4731     (save-restriction
4732       (widen)
4733       (message-goto-body)
4734       (int-to-string (count-lines (point) (point-max))))))
4735
4736 (defun message-make-references ()
4737   "Return the References header for this message."
4738   (when message-reply-headers
4739     (let ((message-id (mail-header-message-id message-reply-headers))
4740           (references (mail-header-references message-reply-headers))
4741           new-references)
4742       (if (or references message-id)
4743           (concat (or references "") (and references " ")
4744                   (or message-id ""))
4745         nil))))
4746
4747 (defun message-make-in-reply-to ()
4748   "Return the In-Reply-To header for this message."
4749   (when message-reply-headers
4750     (let ((from (mail-header-from message-reply-headers))
4751           (date (mail-header-date message-reply-headers))
4752           (msg-id (mail-header-message-id message-reply-headers)))
4753       (when from
4754         (let ((name (mail-extract-address-components from)))
4755           (concat msg-id (if msg-id " (")
4756                   (or (car name)
4757                       (nth 1 name))
4758                   "'s message of \""
4759                   (if (or (not date) (string= date ""))
4760                       "(unknown date)" date)
4761                   "\"" (if msg-id ")")))))))
4762
4763 (defun message-make-distribution ()
4764   "Make a Distribution header."
4765   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4766     (cond ((functionp message-distribution-function)
4767            (funcall message-distribution-function))
4768           (t orig-distribution))))
4769
4770 (defun message-make-expires ()
4771   "Return an Expires header based on `message-expires'."
4772   (let ((current (current-time))
4773         (future (* 1.0 message-expires 60 60 24)))
4774     ;; Add the future to current.
4775     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4776     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4777     (message-make-date current)))
4778
4779 (defun message-make-path ()
4780   "Return uucp path."
4781   (let ((login-name (user-login-name)))
4782     (cond ((null message-user-path)
4783            (concat (system-name) "!" login-name))
4784           ((stringp message-user-path)
4785            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4786            (concat message-user-path "!" login-name))
4787           (t login-name))))
4788
4789 (defun message-make-from ()
4790   "Make a From header."
4791   (let* ((style message-from-style)
4792          (login (message-make-address))
4793          (fullname
4794           (or (and (boundp 'user-full-name)
4795                    user-full-name)
4796               (user-full-name))))
4797     (when (string= fullname "&")
4798       (setq fullname (user-login-name)))
4799     (with-temp-buffer
4800       (mm-enable-multibyte)
4801       (cond
4802        ((or (null style)
4803             (equal fullname ""))
4804         (insert login))
4805        ((or (eq style 'angles)
4806             (and (not (eq style 'parens))
4807                  ;; Use angles if no quoting is needed, or if parens would
4808                  ;; need quoting too.
4809                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4810                      (let ((tmp (concat fullname nil)))
4811                        (while (string-match "([^()]*)" tmp)
4812                          (aset tmp (match-beginning 0) ?-)
4813                          (aset tmp (1- (match-end 0)) ?-))
4814                        (string-match "[\\()]" tmp)))))
4815         (insert fullname)
4816         (goto-char (point-min))
4817         ;; Look for a character that cannot appear unquoted
4818         ;; according to RFC 822.
4819         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
4820           ;; Quote fullname, escaping specials.
4821           (goto-char (point-min))
4822           (insert "\"")
4823           (while (re-search-forward "[\"\\]" nil 1)
4824             (replace-match "\\\\\\&" t))
4825           (insert "\""))
4826         (insert " <" login ">"))
4827        (t                               ; 'parens or default
4828         (insert login " (")
4829         (let ((fullname-start (point)))
4830           (insert fullname)
4831           (goto-char fullname-start)
4832           ;; RFC 822 says \ and nonmatching parentheses
4833           ;; must be escaped in comments.
4834           ;; Escape every instance of ()\ ...
4835           (while (re-search-forward "[()\\]" nil 1)
4836             (replace-match "\\\\\\&" t))
4837           ;; ... then undo escaping of matching parentheses,
4838           ;; including matching nested parentheses.
4839           (goto-char fullname-start)
4840           (while (re-search-forward
4841                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4842                   nil 1)
4843             (replace-match "\\1(\\3)" t)
4844             (goto-char fullname-start)))
4845         (insert ")")))
4846       (buffer-string))))
4847
4848 (defun message-make-sender ()
4849   "Return the \"real\" user address.
4850 This function tries to ignore all user modifications, and
4851 give as trustworthy answer as possible."
4852   (concat (user-login-name) "@" (system-name)))
4853
4854 (defun message-make-address ()
4855   "Make the address of the user."
4856   (or (message-user-mail-address)
4857       (concat (user-login-name) "@" (message-make-domain))))
4858
4859 (defun message-user-mail-address ()
4860   "Return the pertinent part of `user-mail-address'."
4861   (when (and user-mail-address
4862              (string-match "@.*\\." user-mail-address))
4863     (if (string-match " " user-mail-address)
4864         (nth 1 (mail-extract-address-components user-mail-address))
4865       user-mail-address)))
4866
4867 (defun message-sendmail-envelope-from ()
4868   "Return the envelope from."
4869   (cond ((eq message-sendmail-envelope-from 'header)
4870          (nth 1 (mail-extract-address-components
4871                  (message-fetch-field "from"))))
4872         ((stringp message-sendmail-envelope-from)
4873          message-sendmail-envelope-from)
4874         (t
4875          (message-make-address))))
4876
4877 (defun message-make-fqdn ()
4878   "Return user's fully qualified domain name."
4879   (let* ((system-name (system-name))
4880          (user-mail (message-user-mail-address))
4881          (user-domain
4882           (if (and user-mail
4883                    (string-match "@\\(.*\\)\\'" user-mail))
4884               (match-string 1 user-mail)))
4885          (case-fold-search t))
4886     (cond
4887      ((and message-user-fqdn
4888            (stringp message-user-fqdn)
4889            (string-match message-valid-fqdn-regexp message-user-fqdn)
4890            (not (string-match message-bogus-system-names message-user-fqdn)))
4891       message-user-fqdn)
4892      ;; `message-user-fqdn' seems to be valid
4893      ((and (string-match message-valid-fqdn-regexp system-name)
4894            (not (string-match message-bogus-system-names system-name)))
4895       ;; `system-name' returned the right result.
4896       system-name)
4897      ;; Try `mail-host-address'.
4898      ((and (boundp 'mail-host-address)
4899            (stringp mail-host-address)
4900            (string-match message-valid-fqdn-regexp mail-host-address)
4901            (not (string-match message-bogus-system-names mail-host-address)))
4902       mail-host-address)
4903      ;; We try `user-mail-address' as a backup.
4904      ((and user-domain
4905            (stringp user-domain)
4906            (string-match message-valid-fqdn-regexp user-domain)
4907            (not (string-match message-bogus-system-names user-domain)))
4908       user-domain)
4909      ;; Default to this bogus thing.
4910      (t
4911       (concat system-name
4912               ".i-did-not-set--mail-host-address--so-tickle-me")))))
4913
4914 (defun message-make-host-name ()
4915   "Return the name of the host."
4916   (let ((fqdn (message-make-fqdn)))
4917     (string-match "^[^.]+\\." fqdn)
4918     (substring fqdn 0 (1- (match-end 0)))))
4919
4920 (defun message-make-domain ()
4921   "Return the domain name."
4922   (or mail-host-address
4923       (message-make-fqdn)))
4924
4925 (defun message-to-list-only ()
4926   "Send a message to the list only.
4927 Remove all addresses but the list address from To and Cc headers."
4928   (interactive)
4929   (let ((listaddr (message-make-mail-followup-to t)))
4930     (when listaddr
4931       (save-excursion
4932         (message-remove-header "to")
4933         (message-remove-header "cc")
4934         (message-position-on-field "To" "X-Draft-From")
4935         (insert listaddr)))))
4936
4937 (defun message-make-mail-followup-to (&optional only-show-subscribed)
4938   "Return the Mail-Followup-To header.
4939 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
4940 subscribed address (and not the additional To and Cc header contents)."
4941   (let* ((case-fold-search t)
4942          (to (message-fetch-field "To"))
4943          (cc (message-fetch-field "cc"))
4944          (msg-recipients (concat to (and to cc ", ") cc))
4945          (recipients
4946           (mapcar 'mail-strip-quoted-names
4947                   (message-tokenize-header msg-recipients)))
4948          (file-regexps
4949           (if message-subscribed-address-file
4950               (let (begin end item re)
4951                 (save-excursion
4952                   (with-temp-buffer
4953                     (insert-file-contents message-subscribed-address-file)
4954                     (while (not (eobp))
4955                       (setq begin (point))
4956                       (forward-line 1)
4957                       (setq end (point))
4958                       (if (bolp) (setq end (1- end)))
4959                       (setq item (regexp-quote (buffer-substring begin end)))
4960                       (if re (setq re (concat re "\\|" item))
4961                         (setq re (concat "\\`\\(" item))))
4962                     (and re (list (concat re "\\)\\'"))))))))
4963          (mft-regexps (apply 'append message-subscribed-regexps
4964                              (mapcar 'regexp-quote
4965                                      message-subscribed-addresses)
4966                              file-regexps
4967                              (mapcar 'funcall
4968                                      message-subscribed-address-functions))))
4969     (save-match-data
4970       (let ((subscribed-lists nil)
4971             (list
4972              (loop for recipient in recipients
4973                when (loop for regexp in mft-regexps
4974                       when (string-match regexp recipient) return t)
4975                return recipient)))
4976         (when list
4977           (if only-show-subscribed
4978               list
4979             msg-recipients))))))
4980
4981 (defun message-idna-to-ascii-rhs-1 (header)
4982   "Interactively potentially IDNA encode domain names in HEADER."
4983   (let ((field (message-fetch-field header))
4984         rhs ace  address)
4985     (when field
4986       (dolist (address (mail-header-parse-addresses field))
4987         (setq address (car address)
4988               rhs (downcase (or (cadr (split-string address "@")) ""))
4989               ace (downcase (idna-to-ascii rhs)))
4990         (when (and (not (equal rhs ace))
4991                    (or (not (eq message-use-idna 'ask))
4992                        (y-or-n-p (format "Replace %s with %s? " rhs ace))))
4993           (goto-char (point-min))
4994           (while (re-search-forward (concat "^" header ":") nil t)
4995             (message-narrow-to-field)
4996             (while (search-forward (concat "@" rhs) nil t)
4997               (replace-match (concat "@" ace) t t))
4998             (goto-char (point-max))
4999             (widen)))))))
5000
5001 (defun message-idna-to-ascii-rhs ()
5002   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5003 See `message-idna-encode'."
5004   (interactive)
5005   (when message-use-idna
5006     (save-excursion
5007       (save-restriction
5008         (message-narrow-to-head)
5009         (message-idna-to-ascii-rhs-1 "From")
5010         (message-idna-to-ascii-rhs-1 "To")
5011         (message-idna-to-ascii-rhs-1 "Cc")))))
5012
5013 (defun message-generate-headers (headers)
5014   "Prepare article HEADERS.
5015 Headers already prepared in the buffer are not modified."
5016   (setq headers (append headers message-required-headers))
5017   (save-restriction
5018     (message-narrow-to-headers)
5019     (let* ((Date (message-make-date))
5020            (Message-ID (message-make-message-id))
5021            (Organization (message-make-organization))
5022            (From (message-make-from))
5023            (Path (message-make-path))
5024            (Subject nil)
5025            (Newsgroups nil)
5026            (In-Reply-To (message-make-in-reply-to))
5027            (References (message-make-references))
5028            (To nil)
5029            (Distribution (message-make-distribution))
5030            (Lines (message-make-lines))
5031            (User-Agent message-newsreader)
5032            (Expires (message-make-expires))
5033            (case-fold-search t)
5034            (optionalp nil)
5035            header value elem header-string)
5036       ;; First we remove any old generated headers.
5037       (let ((headers message-deletable-headers))
5038         (unless (buffer-modified-p)
5039           (setq headers (delq 'Message-ID (copy-sequence headers))))
5040         (while headers
5041           (goto-char (point-min))
5042           (and (re-search-forward
5043                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5044                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5045                (message-delete-line))
5046           (pop headers)))
5047       ;; Go through all the required headers and see if they are in the
5048       ;; articles already.  If they are not, or are empty, they are
5049       ;; inserted automatically - except for Subject, Newsgroups and
5050       ;; Distribution.
5051       (while headers
5052         (goto-char (point-min))
5053         (setq elem (pop headers))
5054         (if (consp elem)
5055             (if (eq (car elem) 'optional)
5056                 (setq header (cdr elem)
5057                       optionalp t)
5058               (setq header (car elem)))
5059           (setq header elem))
5060         (setq header-string  (if (stringp header)
5061                                  header
5062                                (symbol-name header)))
5063         (when (or (not (re-search-forward
5064                         (concat "^"
5065                                 (regexp-quote (downcase header-string))
5066                                 ":")
5067                         nil t))
5068                   (progn
5069                     ;; The header was found.  We insert a space after the
5070                     ;; colon, if there is none.
5071                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5072                     ;; Find out whether the header is empty.
5073                     (looking-at "[ \t]*\n[^ \t]")))
5074           ;; So we find out what value we should insert.
5075           (setq value
5076                 (cond
5077                  ((and (consp elem)
5078                        (eq (car elem) 'optional)
5079                        (not (member header-string message-inserted-headers)))
5080                   ;; This is an optional header.  If the cdr of this
5081                   ;; is something that is nil, then we do not insert
5082                   ;; this header.
5083                   (setq header (cdr elem))
5084                   (or (and (functionp (cdr elem))
5085                            (funcall (cdr elem)))
5086                       (and (boundp (cdr elem))
5087                            (symbol-value (cdr elem)))))
5088                  ((consp elem)
5089                   ;; The element is a cons.  Either the cdr is a
5090                   ;; string to be inserted verbatim, or it is a
5091                   ;; function, and we insert the value returned from
5092                   ;; this function.
5093                   (or (and (stringp (cdr elem))
5094                            (cdr elem))
5095                       (and (functionp (cdr elem))
5096                            (funcall (cdr elem)))))
5097                  ((and (boundp header)
5098                        (symbol-value header))
5099                   ;; The element is a symbol.  We insert the value
5100                   ;; of this symbol, if any.
5101                   (symbol-value header))
5102                  ((not (message-check-element header))
5103                   ;; We couldn't generate a value for this header,
5104                   ;; so we just ask the user.
5105                   (read-from-minibuffer
5106                    (format "Empty header for %s; enter value: " header)))))
5107           ;; Finally insert the header.
5108           (when (and value
5109                      (not (equal value "")))
5110             (save-excursion
5111               (if (bolp)
5112                   (progn
5113                     ;; This header didn't exist, so we insert it.
5114                     (goto-char (point-max))
5115                     (let ((formatter
5116                            (cdr (assq header message-header-format-alist))))
5117                       (if formatter
5118                           (funcall formatter header value)
5119                         (insert header-string ": " value))
5120                       (goto-char (message-fill-field))
5121                       ;; We check whether the value was ended by a
5122                       ;; newline.  If not, we insert one.
5123                       (unless (bolp)
5124                         (insert "\n"))
5125                       (forward-line -1)))
5126                 ;; The value of this header was empty, so we clear
5127                 ;; totally and insert the new value.
5128                 (delete-region (point) (point-at-eol))
5129                 ;; If the header is optional, and the header was
5130                 ;; empty, we con't insert it anyway.
5131                 (unless optionalp
5132                   (push header-string message-inserted-headers)
5133                   (insert value)
5134                   (message-fill-field)))
5135               ;; Add the deletable property to the headers that require it.
5136               (and (memq header message-deletable-headers)
5137                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5138                    (add-text-properties
5139                     (point) (match-end 0)
5140                     '(message-deletable t face italic) (current-buffer)))))))
5141       ;; Insert new Sender if the From is strange.
5142       (let ((from (message-fetch-field "from"))
5143             (sender (message-fetch-field "sender"))
5144             (secure-sender (message-make-sender)))
5145         (when (and from
5146                    (not (message-check-element 'sender))
5147                    (not (string=
5148                          (downcase
5149                           (cadr (mail-extract-address-components from)))
5150                          (downcase secure-sender)))
5151                    (or (null sender)
5152                        (not
5153                         (string=
5154                          (downcase
5155                           (cadr (mail-extract-address-components sender)))
5156                          (downcase secure-sender)))))
5157           (goto-char (point-min))
5158           ;; Rename any old Sender headers to Original-Sender.
5159           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5160             (beginning-of-line)
5161             (insert "Original-")
5162             (beginning-of-line))
5163           (when (or (message-news-p)
5164                     (string-match "@.+\\.." secure-sender))
5165             (insert "Sender: " secure-sender "\n"))))
5166       ;; Check for IDNA
5167       (message-idna-to-ascii-rhs))))
5168
5169 (defun message-insert-courtesy-copy ()
5170   "Insert a courtesy message in mail copies of combined messages."
5171   (let (newsgroups)
5172     (save-excursion
5173       (save-restriction
5174         (message-narrow-to-headers)
5175         (when (setq newsgroups (message-fetch-field "newsgroups"))
5176           (goto-char (point-max))
5177           (insert "Posted-To: " newsgroups "\n")))
5178       (forward-line 1)
5179       (when message-courtesy-message
5180         (cond
5181          ((string-match "%s" message-courtesy-message)
5182           (insert (format message-courtesy-message newsgroups)))
5183          (t
5184           (insert message-courtesy-message)))))))
5185
5186 ;;;
5187 ;;; Setting up a message buffer
5188 ;;;
5189
5190 (defun message-skip-to-next-address ()
5191   (let ((end (save-excursion
5192                (message-next-header)
5193                (point)))
5194         quoted char)
5195     (when (looking-at ",")
5196       (forward-char 1))
5197     (while (and (not (= (point) end))
5198                 (or (not (eq char ?,))
5199                     quoted))
5200       (skip-chars-forward "^,\"" (point-max))
5201       (when (eq (setq char (following-char)) ?\")
5202         (setq quoted (not quoted)))
5203       (unless (= (point) end)
5204         (forward-char 1)))
5205     (skip-chars-forward " \t\n")))
5206
5207 (defun message-fill-address (header value)
5208   (insert (capitalize (symbol-name header))
5209           ": "
5210           (if (consp value) (car value) value)
5211           "\n")
5212   (message-fill-field-address))
5213
5214 (defun message-split-line ()
5215   "Split current line, moving portion beyond point vertically down.
5216 If the current line has `message-yank-prefix', insert it on the new line."
5217   (interactive "*")
5218   (condition-case nil
5219       (split-line message-yank-prefix) ;; Emacs 21.3.50+ supports arg.
5220     (error
5221      (split-line))))
5222
5223 (defun message-insert-header (header value)
5224   (insert (capitalize (symbol-name header))
5225           ": "
5226           (if (consp value) (car value) value)))
5227
5228 (defun message-field-name ()
5229   (save-excursion
5230     (goto-char (point-min))
5231     (when (looking-at "\\([^:]+\\):")
5232       (intern (capitalize (match-string 1))))))
5233
5234 (defun message-fill-field ()
5235   (save-excursion
5236     (save-restriction
5237       (message-narrow-to-field)
5238       (let ((field-name (message-field-name)))
5239         (funcall (or (cadr (assq field-name message-field-fillers))
5240                      'message-fill-field-general)))
5241       (point-max))))
5242
5243 (defun message-fill-field-address ()
5244   (while (not (eobp))
5245     (message-skip-to-next-address)
5246     (let (last)
5247       (if (and (> (current-column) 78)
5248                last)
5249           (progn
5250             (save-excursion
5251               (goto-char last)
5252               (insert "\n\t"))
5253             (setq last (1+ (point))))
5254         (setq last (1+ (point)))))))
5255   
5256 (defun message-fill-field-general ()
5257   (let ((begin (point))
5258         (fill-column 78)
5259         (fill-prefix "\t"))
5260     (while (and (search-forward "\n" nil t)
5261                 (not (eobp)))
5262       (replace-match " " t t))
5263     (fill-region-as-paragraph begin (point-max))
5264     ;; Tapdance around looong Message-IDs.
5265     (forward-line -1)
5266     (when (looking-at "[ \t]*$")
5267       (message-delete-line))
5268     (goto-char begin)
5269     (search-forward ":" nil t)
5270     (when (looking-at "\n[ \t]+")
5271       (replace-match " " t t))
5272     (goto-char (point-max))))
5273
5274 (defun message-shorten-1 (list cut surplus)
5275   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5276   (setcdr (nthcdr (- cut 2) list)
5277           (nthcdr (+ (- cut 2) surplus 1) list)))
5278
5279 (defun message-shorten-references (header references)
5280   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5281 When sending via news, also check that the REFERENCES are less
5282 than 988 characters long, and if they are not, trim them until
5283 they are."
5284   (let ((maxcount 21)
5285         (count 0)
5286         (cut 2)
5287         refs)
5288     (with-temp-buffer
5289       (insert references)
5290       (goto-char (point-min))
5291       ;; Cons a list of valid references.
5292       (while (re-search-forward "<[^>]+>" nil t)
5293         (push (match-string 0) refs))
5294       (setq refs (nreverse refs)
5295             count (length refs)))
5296
5297     ;; If the list has more than MAXCOUNT elements, trim it by
5298     ;; removing the CUTth element and the required number of
5299     ;; elements that follow.
5300     (when (> count maxcount)
5301       (let ((surplus (- count maxcount)))
5302         (message-shorten-1 refs cut surplus)
5303         (decf count surplus)))
5304
5305     ;; When sending via news, make sure the total folded length will
5306     ;; be less than 998 characters.  This is to cater to broken INN
5307     ;; 2.3 which counts the total number of characters in a header
5308     ;; rather than the physical line length of each line, as it should.
5309     ;;
5310     ;; This hack should be removed when it's believed than INN 2.3 is
5311     ;; no longer widely used.
5312     ;;
5313     ;; At this point the headers have not been generated, thus we use
5314     ;; message-this-is-news directly.
5315     (when message-this-is-news
5316       (while (< 998
5317                 (with-temp-buffer
5318                   (message-insert-header
5319                    header (mapconcat #'identity refs " "))
5320                   (buffer-size)))
5321         (message-shorten-1 refs cut 1)))
5322     ;; Finally, collect the references back into a string and insert
5323     ;; it into the buffer.
5324     (message-insert-header header (mapconcat #'identity refs " "))))
5325
5326 (defun message-position-point ()
5327   "Move point to where the user probably wants to find it."
5328   (message-narrow-to-headers)
5329   (cond
5330    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5331     (search-backward ":" )
5332     (widen)
5333     (forward-char 1)
5334     (if (eq (char-after) ? )
5335         (forward-char 1)
5336       (insert " ")))
5337    (t
5338     (goto-char (point-max))
5339     (widen)
5340     (forward-line 1)
5341     (unless (looking-at "$")
5342       (forward-line 2)))
5343    (sit-for 0)))
5344
5345 (defcustom message-beginning-of-line t
5346   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5347  goes to beginning of header values."
5348   :version "21.4"
5349   :group 'message-buffers
5350   :link '(custom-manual "(message)Movement")
5351   :type 'boolean)
5352
5353 (defun message-beginning-of-line (&optional n)
5354   "Move point to beginning of header value or to beginning of line.
5355 The prefix argument N is passed directly to `beginning-of-line'.
5356
5357 This command is identical to `beginning-of-line' if point is
5358 outside the message header or if the option `message-beginning-of-line'
5359 is nil.
5360
5361 If point is in the message header and on a (non-continued) header
5362 line, move point to the beginning of the header value.  If point
5363 is already there, move point to beginning of line.  Therefore,
5364 repeated calls will toggle point between beginning of field and
5365 beginning of line."
5366   (interactive "p")
5367   (let ((zrs 'zmacs-region-stays))
5368     (when (and (interactive-p) (boundp zrs))
5369       (set zrs t)))
5370   (if (and message-beginning-of-line
5371            (message-point-in-header-p))
5372       (let* ((here (point))
5373              (bol (progn (beginning-of-line n) (point)))
5374              (eol (point-at-eol))
5375              (eoh (re-search-forward ": *" eol t)))
5376         (if (or (not eoh) (equal here eoh))
5377             (goto-char bol)
5378           (goto-char eoh)))
5379     (beginning-of-line n)))
5380
5381 (defun message-buffer-name (type &optional to group)
5382   "Return a new (unique) buffer name based on TYPE and TO."
5383   (cond
5384    ;; Generate a new buffer name The Message Way.
5385    ((eq message-generate-new-buffers 'unique)
5386     (generate-new-buffer-name
5387      (concat "*" type
5388              (if to
5389                  (concat " to "
5390                          (or (car (mail-extract-address-components to))
5391                              to) "")
5392                "")
5393              (if (and group (not (string= group ""))) (concat " on " group) "")
5394              "*")))
5395    ;; Check whether `message-generate-new-buffers' is a function,
5396    ;; and if so, call it.
5397    ((functionp message-generate-new-buffers)
5398     (funcall message-generate-new-buffers type to group))
5399    ((eq message-generate-new-buffers 'unsent)
5400     (generate-new-buffer-name
5401      (concat "*unsent " type
5402              (if to
5403                  (concat " to "
5404                          (or (car (mail-extract-address-components to))
5405                              to) "")
5406                "")
5407              (if (and group (not (string= group ""))) (concat " on " group) "")
5408              "*")))
5409    ;; Use standard name.
5410    (t
5411     (format "*%s message*" type))))
5412
5413 (defun message-pop-to-buffer (name)
5414   "Pop to buffer NAME, and warn if it already exists and is modified."
5415   (let ((buffer (get-buffer name)))
5416     (if (and buffer
5417              (buffer-name buffer))
5418         (progn
5419           (set-buffer (pop-to-buffer buffer))
5420           (when (and (buffer-modified-p)
5421                      (not (y-or-n-p
5422                            "Message already being composed; erase? ")))
5423             (error "Message being composed")))
5424       (set-buffer (pop-to-buffer name)))
5425     (erase-buffer)
5426     (message-mode)))
5427
5428 (defun message-do-send-housekeeping ()
5429   "Kill old message buffers."
5430   ;; We might have sent this buffer already.  Delete it from the
5431   ;; list of buffers.
5432   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5433   (while (and message-max-buffers
5434               message-buffer-list
5435               (>= (length message-buffer-list) message-max-buffers))
5436     ;; Kill the oldest buffer -- unless it has been changed.
5437     (let ((buffer (pop message-buffer-list)))
5438       (when (and (buffer-name buffer)
5439                  (not (buffer-modified-p buffer)))
5440         (kill-buffer buffer))))
5441   ;; Rename the buffer.
5442   (if message-send-rename-function
5443       (funcall message-send-rename-function)
5444     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5445     (when (string-match
5446            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5447            (buffer-name))
5448       (let ((name (match-string 2 (buffer-name)))
5449             to group)
5450         (if (not (or (null name)
5451                      (string-equal name "mail")
5452                      (string-equal name "posting")))
5453             (setq name (concat "*sent " name "*"))
5454           (message-narrow-to-headers)
5455           (setq to (message-fetch-field "to"))
5456           (setq group (message-fetch-field "newsgroups"))
5457           (widen)
5458           (setq name
5459                 (cond
5460                  (to (concat "*sent mail to "
5461                              (or (car (mail-extract-address-components to))
5462                                  to) "*"))
5463                  ((and group (not (string= group "")))
5464                   (concat "*sent posting on " group "*"))
5465                  (t "*sent mail*"))))
5466         (unless (string-equal name (buffer-name))
5467           (rename-buffer name t)))))
5468   ;; Push the current buffer onto the list.
5469   (when message-max-buffers
5470     (setq message-buffer-list
5471           (nconc message-buffer-list (list (current-buffer))))))
5472
5473 (defun message-mail-user-agent ()
5474   (let ((mua (cond
5475               ((not message-mail-user-agent) nil)
5476               ((eq message-mail-user-agent t) mail-user-agent)
5477               (t message-mail-user-agent))))
5478     (if (memq mua '(message-user-agent gnus-user-agent))
5479         nil
5480       mua)))
5481
5482 (defun message-setup (headers &optional replybuffer actions switch-function)
5483   (let ((mua (message-mail-user-agent))
5484         subject to field yank-action)
5485     (if (not (and message-this-is-mail mua))
5486         (message-setup-1 headers replybuffer actions)
5487       (if replybuffer
5488           (setq yank-action (list 'insert-buffer replybuffer)))
5489       (setq headers (copy-sequence headers))
5490       (setq field (assq 'Subject headers))
5491       (when field
5492         (setq subject (cdr field))
5493         (setq headers (delq field headers)))
5494       (setq field (assq 'To headers))
5495       (when field
5496         (setq to (cdr field))
5497         (setq headers (delq field headers)))
5498       (let ((mail-user-agent mua))
5499         (compose-mail to subject
5500                       (mapcar (lambda (item)
5501                                 (cons
5502                                  (format "%s" (car item))
5503                                  (cdr item)))
5504                               headers)
5505                       nil switch-function yank-action actions)))))
5506
5507 (defun message-headers-to-generate (headers included-headers excluded-headers)
5508   "Return a list that includes all headers from HEADERS.
5509 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5510 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5511 are not included."
5512   (let ((result nil)
5513         header-name)
5514     (dolist (header headers)
5515       (setq header-name (cond
5516                          ((and (consp header)
5517                                (eq (car header) 'optional))
5518                           ;; On the form (optional . Header)
5519                           (cdr header))
5520                          ((consp header)
5521                           ;; On the form (Header . function)
5522                           (car header))
5523                          (t
5524                           ;; Just a Header.
5525                           header)))
5526       (when (and (not (memq header-name excluded-headers))
5527                  (or (eq included-headers t)
5528                      (memq header-name included-headers)))
5529         (push header result)))
5530     (nreverse result)))
5531
5532 (defun message-setup-1 (headers &optional replybuffer actions)
5533   (dolist (action actions)
5534     (condition-case nil
5535         (add-to-list 'message-send-actions
5536                      `(apply ',(car action) ',(cdr action)))))
5537   (setq message-reply-buffer replybuffer)
5538   (goto-char (point-min))
5539   ;; Insert all the headers.
5540   (mail-header-format
5541    (let ((h headers)
5542          (alist message-header-format-alist))
5543      (while h
5544        (unless (assq (caar h) message-header-format-alist)
5545          (push (list (caar h)) alist))
5546        (pop h))
5547      alist)
5548    headers)
5549   (delete-region (point) (progn (forward-line -1) (point)))
5550   (when message-default-headers
5551     (insert message-default-headers)
5552     (or (bolp) (insert ?\n)))
5553   (insert mail-header-separator "\n")
5554   (forward-line -1)
5555   (when (message-news-p)
5556     (when message-default-news-headers
5557       (insert message-default-news-headers)
5558       (or (bolp) (insert ?\n)))
5559     (when message-generate-headers-first
5560       (message-generate-headers
5561        (message-headers-to-generate
5562         (append message-required-news-headers
5563                 message-required-headers)
5564         message-generate-headers-first
5565         '(Lines Subject)))))
5566   (when (message-mail-p)
5567     (when message-default-mail-headers
5568       (insert message-default-mail-headers)
5569       (or (bolp) (insert ?\n)))
5570     (save-restriction
5571       (message-narrow-to-headers)
5572       (if message-alternative-emails
5573           (message-use-alternative-email-as-from)))
5574     (when message-generate-headers-first
5575       (message-generate-headers
5576        (message-headers-to-generate
5577         (append message-required-mail-headers
5578                 message-required-headers)
5579         message-generate-headers-first
5580         '(Lines Subject)))))
5581   (run-hooks 'message-signature-setup-hook)
5582   (message-insert-signature)
5583   (save-restriction
5584     (message-narrow-to-headers)
5585     (run-hooks 'message-header-setup-hook))
5586   (set-buffer-modified-p nil)
5587   (setq buffer-undo-list nil)
5588   (when message-generate-hashcash
5589     ;; Generate hashcash headers for recipients already known
5590     (mail-add-payment-async))
5591   (run-hooks 'message-setup-hook)
5592   (message-position-point)
5593   (undo-boundary))
5594
5595 (defun message-set-auto-save-file-name ()
5596   "Associate the message buffer with a file in the drafts directory."
5597   (when message-auto-save-directory
5598     (unless (file-directory-p
5599              (directory-file-name message-auto-save-directory))
5600       (make-directory message-auto-save-directory t))
5601     (if (gnus-alive-p)
5602         (setq message-draft-article
5603               (nndraft-request-associate-buffer "drafts"))
5604       (setq buffer-file-name (expand-file-name
5605                               (if (memq system-type
5606                                         '(ms-dos ms-windows windows-nt
5607                                                  cygwin cygwin32 win32 w32
5608                                                  mswindows))
5609                                   "message"
5610                                 "*message*")
5611                               message-auto-save-directory))
5612       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5613     (clear-visited-file-modtime)
5614     (setq buffer-file-coding-system message-draft-coding-system)))
5615
5616 (defun message-disassociate-draft ()
5617   "Disassociate the message buffer from the drafts directory."
5618   (when message-draft-article
5619     (nndraft-request-expire-articles
5620      (list message-draft-article) "drafts" nil t)))
5621
5622 (defun message-insert-headers ()
5623   "Generate the headers for the article."
5624   (interactive)
5625   (save-excursion
5626     (save-restriction
5627       (message-narrow-to-headers)
5628       (when (message-news-p)
5629         (message-generate-headers
5630          (delq 'Lines
5631                (delq 'Subject
5632                      (copy-sequence message-required-news-headers)))))
5633       (when (message-mail-p)
5634         (message-generate-headers
5635          (delq 'Lines
5636                (delq 'Subject
5637                      (copy-sequence message-required-mail-headers))))))))
5638
5639 \f
5640
5641 ;;;
5642 ;;; Commands for interfacing with message
5643 ;;;
5644
5645 ;;;###autoload
5646 (defun message-mail (&optional to subject
5647                                other-headers continue switch-function
5648                                yank-action send-actions)
5649   "Start editing a mail message to be sent.
5650 OTHER-HEADERS is an alist of header/value pairs."
5651   (interactive)
5652   (let ((message-this-is-mail t) replybuffer)
5653     (unless (message-mail-user-agent)
5654       (message-pop-to-buffer (message-buffer-name "mail" to)))
5655     ;; FIXME: message-mail should do something if YANK-ACTION is not
5656     ;; insert-buffer.
5657     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5658          (setq replybuffer (nth 1 yank-action)))
5659     (message-setup
5660      (nconc
5661       `((To . ,(or to "")) (Subject . ,(or subject "")))
5662       (when other-headers other-headers))
5663      replybuffer send-actions)
5664     ;; FIXME: Should return nil if failure.
5665     t))
5666
5667 ;;;###autoload
5668 (defun message-news (&optional newsgroups subject)
5669   "Start editing a news article to be sent."
5670   (interactive)
5671   (let ((message-this-is-news t))
5672     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5673     (message-setup `((Newsgroups . ,(or newsgroups ""))
5674                      (Subject . ,(or subject ""))))))
5675
5676 (defun message-get-reply-headers (wide &optional to-address address-headers)
5677   (let (follow-to mct never-mct to cc author mft recipients)
5678     ;; Find all relevant headers we need.
5679     (save-restriction
5680       (message-narrow-to-headers-or-head)
5681       ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
5682       ;; message-header-synonyms.
5683       (setq to (or (message-fetch-field "to")
5684                    (and (loop for synonym in message-header-synonyms
5685                               when (memq 'Original-To synonym)
5686                               return t)
5687                         (message-fetch-field "original-to")))
5688             cc (message-fetch-field "cc")
5689             mct (message-fetch-field "mail-copies-to")
5690             author (or (message-fetch-field "mail-reply-to")
5691                        (message-fetch-field "reply-to")
5692                        (message-fetch-field "from")
5693                        "")
5694             mft (and message-use-mail-followup-to
5695                      (message-fetch-field "mail-followup-to"))))
5696
5697     ;; Handle special values of Mail-Copies-To.
5698     (when mct
5699       (cond ((or (equal (downcase mct) "never")
5700                  (equal (downcase mct) "nobody"))
5701              (setq never-mct t)
5702              (setq mct nil))
5703             ((or (equal (downcase mct) "always")
5704                  (equal (downcase mct) "poster"))
5705              (setq mct author))))
5706
5707     (save-match-data
5708       ;; Build (textual) list of new recipient addresses.
5709       (cond
5710        ((not wide)
5711         (setq recipients (concat ", " author)))
5712        (address-headers
5713         (dolist (header address-headers)
5714           (let ((value (message-fetch-field header)))
5715             (when value
5716               (setq recipients (concat recipients ", " value))))))
5717        ((and mft
5718              (string-match "[^ \t,]" mft)
5719              (or (not (eq message-use-mail-followup-to 'ask))
5720                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5721 You should normally obey the Mail-Followup-To: header.  In this
5722 article, it has the value of
5723
5724 " mft "
5725
5726 which directs your response to " (if (string-match "," mft)
5727                                      "the specified addresses"
5728                                    "that address only") ".
5729
5730 Most commonly, Mail-Followup-To is used by a mailing list poster to
5731 express that responses should be sent to just the list, and not the
5732 poster as well.
5733
5734 If a message is posted to several mailing lists, Mail-Followup-To may
5735 also be used to direct the following discussion to one list only,
5736 because discussions that are spread over several lists tend to be
5737 fragmented and very difficult to follow.
5738
5739 Also, some source/announcement lists are not intended for discussion;
5740 responses here are directed to other addresses.")))
5741         (setq recipients (concat ", " mft)))
5742        (to-address
5743         (setq recipients (concat ", " to-address))
5744         ;; If the author explicitly asked for a copy, we don't deny it to them.
5745         (if mct (setq recipients (concat recipients ", " mct))))
5746        (t
5747         (setq recipients (if never-mct "" (concat ", " author)))
5748         (if to  (setq recipients (concat recipients ", " to)))
5749         (if cc  (setq recipients (concat recipients ", " cc)))
5750         (if mct (setq recipients (concat recipients ", " mct)))))
5751       (if (>= (length recipients) 2)
5752           ;; Strip the leading ", ".
5753           (setq recipients (substring recipients 2)))
5754       ;; Squeeze whitespace.
5755       (while (string-match "[ \t][ \t]+" recipients)
5756         (setq recipients (replace-match " " t t recipients)))
5757       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5758       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5759         (setq recipients (rmail-dont-reply-to recipients)))
5760       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5761       (if (string-equal recipients "")
5762           (setq recipients author))
5763       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5764       (setq recipients
5765             (mapcar
5766              (lambda (addr)
5767                (cons (downcase (mail-strip-quoted-names addr)) addr))
5768              (message-tokenize-header recipients)))
5769       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5770       (let ((s recipients))
5771         (while s
5772           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5773
5774       ;; Remove hierarchical lists that are contained within each other,
5775       ;; if message-hierarchical-addresses is defined.
5776       (when message-hierarchical-addresses
5777         (let ((plain-addrs (mapcar 'car recipients))
5778               subaddrs recip)
5779           (while plain-addrs
5780             (setq subaddrs (assoc (car plain-addrs)
5781                                   message-hierarchical-addresses)
5782                   plain-addrs (cdr plain-addrs))
5783             (when subaddrs
5784               (setq subaddrs (cdr subaddrs))
5785               (while subaddrs
5786                 (setq recip (assoc (car subaddrs) recipients)
5787                       subaddrs (cdr subaddrs))
5788                 (if recip
5789                     (setq recipients (delq recip recipients))))))))
5790
5791       ;; Build the header alist.  Allow the user to be asked whether
5792       ;; or not to reply to all recipients in a wide reply.
5793       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5794       (when (and recipients
5795                  (or (not message-wide-reply-confirm-recipients)
5796                      (y-or-n-p "Reply to all recipients? ")))
5797         (setq recipients (mapconcat
5798                           (lambda (addr) (cdr addr)) recipients ", "))
5799         (if (string-match "^ +" recipients)
5800             (setq recipients (substring recipients (match-end 0))))
5801         (push (cons 'Cc recipients) follow-to)))
5802     follow-to))
5803
5804 ;;;###autoload
5805 (defun message-reply (&optional to-address wide)
5806   "Start editing a reply to the article in the current buffer."
5807   (interactive)
5808   (require 'gnus-sum)                   ; for gnus-list-identifiers
5809   (let ((cur (current-buffer))
5810         from subject date reply-to to cc
5811         references message-id follow-to
5812         (inhibit-point-motion-hooks t)
5813         (message-this-is-mail t)
5814         gnus-warning)
5815     (save-restriction
5816       (message-narrow-to-head-1)
5817       ;; Allow customizations to have their say.
5818       (if (not wide)
5819           ;; This is a regular reply.
5820           (when (functionp message-reply-to-function)
5821             (save-excursion
5822               (setq follow-to (funcall message-reply-to-function))))
5823         ;; This is a followup.
5824         (when (functionp message-wide-reply-to-function)
5825           (save-excursion
5826             (setq follow-to
5827                   (funcall message-wide-reply-to-function)))))
5828       (setq message-id (message-fetch-field "message-id" t)
5829             references (message-fetch-field "references")
5830             date (message-fetch-field "date")
5831             from (message-fetch-field "from")
5832             subject (or (message-fetch-field "subject") "none"))
5833       (when gnus-list-identifiers
5834         (setq subject (message-strip-list-identifiers subject)))
5835       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5836       (when message-subject-trailing-was-query
5837         (setq subject (message-strip-subject-trailing-was subject)))
5838
5839       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5840                  (string-match "<[^>]+>" gnus-warning))
5841         (setq message-id (match-string 0 gnus-warning)))
5842
5843       (unless follow-to
5844         (setq follow-to (message-get-reply-headers wide to-address))))
5845
5846     (unless (message-mail-user-agent)
5847       (message-pop-to-buffer
5848        (message-buffer-name
5849         (if wide "wide reply" "reply") from
5850         (if wide to-address nil))))
5851
5852     (setq message-reply-headers
5853           (vector 0 subject from date message-id references 0 0 ""))
5854
5855     (message-setup
5856      `((Subject . ,subject)
5857        ,@follow-to)
5858      cur)))
5859
5860 ;;;###autoload
5861 (defun message-wide-reply (&optional to-address)
5862   "Make a \"wide\" reply to the message in the current buffer."
5863   (interactive)
5864   (message-reply to-address t))
5865
5866 ;;;###autoload
5867 (defun message-followup (&optional to-newsgroups)
5868   "Follow up to the message in the current buffer.
5869 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5870   (interactive)
5871   (require 'gnus-sum)                   ; for gnus-list-identifiers
5872   (let ((cur (current-buffer))
5873         from subject date reply-to mrt mct
5874         references message-id follow-to
5875         (inhibit-point-motion-hooks t)
5876         (message-this-is-news t)
5877         followup-to distribution newsgroups gnus-warning posted-to)
5878     (save-restriction
5879       (narrow-to-region
5880        (goto-char (point-min))
5881        (if (search-forward "\n\n" nil t)
5882            (1- (point))
5883          (point-max)))
5884       (when (functionp message-followup-to-function)
5885         (setq follow-to
5886               (funcall message-followup-to-function)))
5887       (setq from (message-fetch-field "from")
5888             date (message-fetch-field "date")
5889             subject (or (message-fetch-field "subject") "none")
5890             references (message-fetch-field "references")
5891             message-id (message-fetch-field "message-id" t)
5892             followup-to (message-fetch-field "followup-to")
5893             newsgroups (message-fetch-field "newsgroups")
5894             posted-to (message-fetch-field "posted-to")
5895             reply-to (message-fetch-field "reply-to")
5896             mrt (message-fetch-field "mail-reply-to")
5897             distribution (message-fetch-field "distribution")
5898             mct (message-fetch-field "mail-copies-to"))
5899       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5900                  (string-match "<[^>]+>" gnus-warning))
5901         (setq message-id (match-string 0 gnus-warning)))
5902       ;; Remove bogus distribution.
5903       (when (and (stringp distribution)
5904                  (let ((case-fold-search t))
5905                    (string-match "world" distribution)))
5906         (setq distribution nil))
5907       (if gnus-list-identifiers
5908           (setq subject (message-strip-list-identifiers subject)))
5909       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5910       (when message-subject-trailing-was-query
5911         (setq subject (message-strip-subject-trailing-was subject)))
5912       (widen))
5913
5914     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5915
5916     (setq message-reply-headers
5917           (vector 0 subject from date message-id references 0 0 ""))
5918
5919     (message-setup
5920      `((Subject . ,subject)
5921        ,@(cond
5922           (to-newsgroups
5923            (list (cons 'Newsgroups to-newsgroups)))
5924           (follow-to follow-to)
5925           ((and followup-to message-use-followup-to)
5926            (list
5927             (cond
5928              ((equal (downcase followup-to) "poster")
5929               (if (or (eq message-use-followup-to 'use)
5930                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
5931 You should normally obey the Followup-To: header.
5932
5933 `Followup-To: poster' sends your response via e-mail instead of news.
5934
5935 A typical situation where `Followup-To: poster' is used is when the poster
5936 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5937                   (progn
5938                     (setq message-this-is-news nil)
5939                     (cons 'To (or mrt reply-to from "")))
5940                 (cons 'Newsgroups newsgroups)))
5941              (t
5942               (if (or (equal followup-to newsgroups)
5943                       (not (eq message-use-followup-to 'ask))
5944                       (message-y-or-n-p
5945                        (concat "Obey Followup-To: " followup-to "? ") t "\
5946 You should normally obey the Followup-To: header.
5947
5948         `Followup-To: " followup-to "'
5949 directs your response to " (if (string-match "," followup-to)
5950                                "the specified newsgroups"
5951                              "that newsgroup only") ".
5952
5953 If a message is posted to several newsgroups, Followup-To is often
5954 used to direct the following discussion to one newsgroup only,
5955 because discussions that are spread over several newsgroup tend to
5956 be fragmented and very difficult to follow.
5957
5958 Also, some source/announcement newsgroups are not intended for discussion;
5959 responses here are directed to other newsgroups."))
5960                   (cons 'Newsgroups followup-to)
5961                 (cons 'Newsgroups newsgroups))))))
5962           (posted-to
5963            `((Newsgroups . ,posted-to)))
5964           (t
5965            `((Newsgroups . ,newsgroups))))
5966        ,@(and distribution (list (cons 'Distribution distribution)))
5967        ,@(when (and mct
5968                     (not (or (equal (downcase mct) "never")
5969                              (equal (downcase mct) "nobody"))))
5970            (list (cons 'Cc (if (or (equal (downcase mct) "always")
5971                                    (equal (downcase mct) "poster"))
5972                                (or mrt reply-to from "")
5973                              mct)))))
5974
5975      cur)))
5976
5977 (defun message-is-yours-p ()
5978   "Non-nil means current article is yours.
5979 If you have added 'cancel-messages to 'message-shoot-gnksa-feet', all articles
5980 are yours except those that have Cancel-Lock header not belonging to you.
5981 Instead of shooting GNKSA feet, you should modify 'message-alternative-emails'
5982 regexp to match all of yours addresses."
5983   ;; Canlock-logic as suggested by Per Abrahamsen
5984   ;; <abraham@dina.kvl.dk>
5985   ;;
5986   ;; IF article has cancel-lock THEN
5987   ;;   IF we can verify it THEN
5988   ;;     issue cancel
5989   ;;   ELSE
5990   ;;     error: cancellock: article is not yours
5991   ;; ELSE
5992   ;;   Use old rules, comparing sender...
5993   (save-excursion
5994     (save-restriction
5995       (message-narrow-to-head-1)
5996       (if (message-fetch-field "Cancel-Lock")
5997           (if (null (canlock-verify))
5998               t
5999             (error "Failed to verify Cancel-lock: This article is not yours"))
6000         (let (sender from)
6001           (or
6002            (message-gnksa-enable-p 'cancel-messages)
6003            (and (setq sender (message-fetch-field "sender"))
6004                 (string-equal (downcase sender)
6005                               (downcase (message-make-sender))))
6006            ;; Email address in From field equals to our address
6007            (and (setq from (message-fetch-field "from"))
6008                 (string-equal
6009                  (downcase (cadr (mail-extract-address-components from)))
6010                  (downcase (cadr (mail-extract-address-components
6011                                   (message-make-from))))))
6012            ;; Email address in From field matches
6013            ;; 'message-alternative-emails' regexp
6014            (and from
6015                 message-alternative-emails
6016                 (string-match
6017                  message-alternative-emails
6018                  (cadr (mail-extract-address-components from))))))))))
6019
6020 ;;;###autoload
6021 (defun message-cancel-news (&optional arg)
6022   "Cancel an article you posted.
6023 If ARG, allow editing of the cancellation message."
6024   (interactive "P")
6025   (unless (message-news-p)
6026     (error "This is not a news article; canceling is impossible"))
6027   (let (from newsgroups message-id distribution buf)
6028     (save-excursion
6029       ;; Get header info from original article.
6030       (save-restriction
6031         (message-narrow-to-head-1)
6032         (setq from (message-fetch-field "from")
6033               newsgroups (message-fetch-field "newsgroups")
6034               message-id (message-fetch-field "message-id" t)
6035               distribution (message-fetch-field "distribution")))
6036       ;; Make sure that this article was written by the user.
6037       (unless (message-is-yours-p)
6038         (error "This article is not yours"))
6039       (when (yes-or-no-p "Do you really want to cancel this article? ")
6040         ;; Make control message.
6041         (if arg
6042             (message-news)
6043           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6044         (erase-buffer)
6045         (insert "Newsgroups: " newsgroups "\n"
6046                 "From: " from "\n"
6047                 "Subject: cmsg cancel " message-id "\n"
6048                 "Control: cancel " message-id "\n"
6049                 (if distribution
6050                     (concat "Distribution: " distribution "\n")
6051                   "")
6052                 mail-header-separator "\n"
6053                 message-cancel-message)
6054         (run-hooks 'message-cancel-hook)
6055         (unless arg
6056           (message "Canceling your article...")
6057           (if (let ((message-syntax-checks
6058                      'dont-check-for-anything-just-trust-me))
6059                 (funcall message-send-news-function))
6060               (message "Canceling your article...done"))
6061           (kill-buffer buf))))))
6062
6063 ;;;###autoload
6064 (defun message-supersede ()
6065   "Start composing a message to supersede the current message.
6066 This is done simply by taking the old article and adding a Supersedes
6067 header line with the old Message-ID."
6068   (interactive)
6069   (let ((cur (current-buffer)))
6070     ;; Check whether the user owns the article that is to be superseded.
6071     (unless (message-is-yours-p)
6072       (error "This article is not yours"))
6073     ;; Get a normal message buffer.
6074     (message-pop-to-buffer (message-buffer-name "supersede"))
6075     (insert-buffer-substring cur)
6076     (mime-to-mml)
6077     (message-narrow-to-head-1)
6078     ;; Remove unwanted headers.
6079     (when message-ignored-supersedes-headers
6080       (message-remove-header message-ignored-supersedes-headers t))
6081     (goto-char (point-min))
6082     (if (not (re-search-forward "^Message-ID: " nil t))
6083         (error "No Message-ID in this article")
6084       (replace-match "Supersedes: " t t))
6085     (goto-char (point-max))
6086     (insert mail-header-separator)
6087     (widen)
6088     (forward-line 1)))
6089
6090 ;;;###autoload
6091 (defun message-recover ()
6092   "Reread contents of current buffer from its last auto-save file."
6093   (interactive)
6094   (let ((file-name (make-auto-save-file-name)))
6095     (cond ((save-window-excursion
6096              (if (not (eq system-type 'vax-vms))
6097                  (with-output-to-temp-buffer "*Directory*"
6098                    (with-current-buffer standard-output
6099                      (fundamental-mode)) ; for Emacs 20.4+
6100                    (buffer-disable-undo standard-output)
6101                    (let ((default-directory "/"))
6102                      (call-process
6103                       "ls" nil standard-output nil "-l" file-name))))
6104              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6105            (let ((buffer-read-only nil))
6106              (erase-buffer)
6107              (insert-file-contents file-name nil)))
6108           (t (error "message-recover cancelled")))))
6109
6110 ;;; Washing Subject:
6111
6112 (defun message-wash-subject (subject)
6113   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6114 Previous forwarders, replyers, etc. may add it."
6115   (with-temp-buffer
6116     (insert subject)
6117     (goto-char (point-min))
6118     ;; strip Re/Fwd stuff off the beginning
6119     (while (re-search-forward
6120             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6121       (replace-match ""))
6122
6123     ;; and gnus-style forwards [foo@bar.com] subject
6124     (goto-char (point-min))
6125     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6126       (replace-match ""))
6127
6128     ;; and off the end
6129     (goto-char (point-max))
6130     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6131       (replace-match ""))
6132
6133     ;; and finally, any whitespace that was left-over
6134     (goto-char (point-min))
6135     (while (re-search-forward "^[ \t]+" nil t)
6136       (replace-match ""))
6137     (goto-char (point-max))
6138     (while (re-search-backward "[ \t]+$" nil t)
6139       (replace-match ""))
6140
6141     (buffer-string)))
6142
6143 ;;; Forwarding messages.
6144
6145 (defvar message-forward-decoded-p nil
6146   "Non-nil means the original message is decoded.")
6147
6148 (defun message-forward-subject-name-subject (subject)
6149   "Generate a SUBJECT for a forwarded message.
6150 The form is: [Source] Subject, where if the original message was mail,
6151 Source is the name of the sender, and if the original message was
6152 news, Source is the list of newsgroups is was posted to."
6153   (let* ((group (message-fetch-field "newsgroups"))
6154          (from (message-fetch-field "from"))
6155          (prefix
6156           (if group
6157               (gnus-group-decoded-name group)
6158             (or (and from (car (gnus-extract-address-components from)))
6159                 "(nowhere)"))))
6160     (concat "["
6161             (if message-forward-decoded-p
6162                 prefix
6163               (mail-decode-encoded-word-string prefix))
6164             "] " subject)))
6165
6166 (defun message-forward-subject-author-subject (subject)
6167   "Generate a SUBJECT for a forwarded message.
6168 The form is: [Source] Subject, where if the original message was mail,
6169 Source is the sender, and if the original message was news, Source is
6170 the list of newsgroups is was posted to."
6171   (let* ((group (message-fetch-field "newsgroups"))
6172          (prefix
6173           (if group
6174               (gnus-group-decoded-name group)
6175             (or (message-fetch-field "from")
6176                 "(nowhere)"))))
6177     (concat "["
6178             (if message-forward-decoded-p
6179                 prefix
6180               (mail-decode-encoded-word-string prefix))
6181             "] " subject)))
6182
6183 (defun message-forward-subject-fwd (subject)
6184   "Generate a SUBJECT for a forwarded message.
6185 The form is: Fwd: Subject, where Subject is the original subject of
6186 the message."
6187   (if (string-match "^Fwd: " subject)
6188       subject
6189     (concat "Fwd: " subject)))
6190
6191 (defun message-make-forward-subject ()
6192   "Return a Subject header suitable for the message in the current buffer."
6193   (save-excursion
6194     (save-restriction
6195       (message-narrow-to-head-1)
6196       (let ((funcs message-make-forward-subject-function)
6197             (subject (message-fetch-field "Subject")))
6198         (setq subject
6199               (if subject
6200                   (if message-forward-decoded-p
6201                       subject
6202                     (mail-decode-encoded-word-string subject))
6203                 ""))
6204         (when message-wash-forwarded-subjects
6205           (setq subject (message-wash-subject subject)))
6206         ;; Make sure funcs is a list.
6207         (and funcs
6208              (not (listp funcs))
6209              (setq funcs (list funcs)))
6210         ;; Apply funcs in order, passing subject generated by previous
6211         ;; func to the next one.
6212         (dolist (func funcs)
6213           (when (functionp func)
6214             (setq subject (funcall func subject))))
6215         subject))))
6216
6217 (eval-when-compile
6218   (defvar gnus-article-decoded-p))
6219
6220
6221 ;;;###autoload
6222 (defun message-forward (&optional news digest)
6223   "Forward the current message via mail.
6224 Optional NEWS will use news to forward instead of mail.
6225 Optional DIGEST will use digest to forward."
6226   (interactive "P")
6227   (let* ((cur (current-buffer))
6228          (message-forward-decoded-p
6229           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
6230               gnus-article-decoded-p ;; In an article buffer.
6231             message-forward-decoded-p))
6232          (subject (message-make-forward-subject)))
6233     (if news
6234         (message-news nil subject)
6235       (message-mail nil subject))
6236     (message-forward-make-body cur digest)))
6237
6238 (defun message-forward-make-body-plain (forward-buffer)
6239   (insert
6240    "\n-------------------- Start of forwarded message --------------------\n")
6241   (let ((b (point)) e)
6242     (insert
6243      (with-temp-buffer
6244        (mm-disable-multibyte)
6245        (insert
6246         (with-current-buffer forward-buffer
6247           (mm-with-unibyte-current-buffer (buffer-string))))
6248        (mm-enable-multibyte)
6249        (mime-to-mml)
6250        (goto-char (point-min))
6251        (when (looking-at "From ")
6252          (replace-match "X-From-Line: "))
6253        (buffer-string)))
6254     (setq e (point))
6255     (insert
6256      "\n-------------------- End of forwarded message --------------------\n")
6257     (when (and (not current-prefix-arg)
6258                message-forward-ignored-headers)
6259       (save-restriction
6260         (narrow-to-region b e)
6261         (goto-char b)
6262         (narrow-to-region (point)
6263                           (or (search-forward "\n\n" nil t) (point)))
6264         (message-remove-header message-forward-ignored-headers t)))))
6265
6266 (defun message-forward-make-body-mime (forward-buffer)
6267   (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
6268   (let ((b (point)) e)
6269     (save-restriction
6270       (narrow-to-region (point) (point))
6271       (mml-insert-buffer forward-buffer)
6272       (goto-char (point-min))
6273       (when (looking-at "From ")
6274         (replace-match "X-From-Line: "))
6275       (goto-char (point-max)))
6276     (setq e (point))
6277     (insert "<#/part>\n")))
6278
6279 (defun message-forward-make-body-mml (forward-buffer)
6280   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
6281   (let ((b (point)) e)
6282     (if (not message-forward-decoded-p)
6283         (insert
6284          (with-temp-buffer
6285            (mm-disable-multibyte)
6286            (insert
6287             (with-current-buffer forward-buffer
6288               (mm-with-unibyte-current-buffer (buffer-string))))
6289            (mm-enable-multibyte)
6290            (mime-to-mml)
6291            (goto-char (point-min))
6292            (when (looking-at "From ")
6293              (replace-match "X-From-Line: "))
6294            (buffer-string)))
6295       (save-restriction
6296         (narrow-to-region (point) (point))
6297         (mml-insert-buffer forward-buffer)
6298         (goto-char (point-min))
6299         (when (looking-at "From ")
6300           (replace-match "X-From-Line: "))
6301         (goto-char (point-max))))
6302     (setq e (point))
6303     (insert "<#/mml>\n")
6304     (when (and (not current-prefix-arg)
6305                message-forward-ignored-headers)
6306       (save-restriction
6307         (narrow-to-region b e)
6308         (goto-char b)
6309         (narrow-to-region (point)
6310                           (or (search-forward "\n\n" nil t) (point)))
6311         (message-remove-header message-forward-ignored-headers t)))))
6312
6313 (defun message-forward-make-body-digest-plain (forward-buffer)
6314   (insert
6315    "\n-------------------- Start of forwarded message --------------------\n")
6316   (let ((b (point)) e)
6317     (mml-insert-buffer forward-buffer)
6318     (setq e (point))
6319     (insert
6320      "\n-------------------- End of forwarded message --------------------\n")))
6321
6322 (defun message-forward-make-body-digest-mime (forward-buffer)
6323   (insert "\n<#multipart type=digest>\n")
6324   (let ((b (point)) e)
6325     (insert-buffer-substring forward-buffer)
6326     (setq e (point))
6327     (insert "<#/multipart>\n")
6328     (save-restriction
6329       (narrow-to-region b e)
6330       (goto-char b)
6331       (narrow-to-region (point)
6332                         (or (search-forward "\n\n" nil t) (point)))
6333       (delete-region (point-min) (point-max)))))
6334
6335 (defun message-forward-make-body-digest (forward-buffer)
6336   (if message-forward-as-mime
6337       (message-forward-make-body-digest-mime forward-buffer)
6338     (message-forward-make-body-digest-plain forward-buffer)))
6339
6340 ;;;###autoload
6341 (defun message-forward-make-body (forward-buffer &optional digest)
6342   ;; Put point where we want it before inserting the forwarded
6343   ;; message.
6344   (if message-forward-before-signature
6345       (message-goto-body)
6346     (goto-char (point-max)))
6347   (if digest
6348       (message-forward-make-body-digest forward-buffer)
6349     (if message-forward-as-mime
6350         (if (and message-forward-show-mml
6351                  (not (and (eq message-forward-show-mml 'best)
6352                            (with-current-buffer forward-buffer
6353                              (goto-char (point-min))
6354                              (re-search-forward
6355                               "Content-Type: *multipart/\\(signed\\|encrypted\\)"
6356                               nil t)))))
6357             (message-forward-make-body-mml forward-buffer)
6358           (message-forward-make-body-mime forward-buffer))
6359       (message-forward-make-body-plain forward-buffer)))
6360   (message-position-point))
6361
6362 ;;;###autoload
6363 (defun message-forward-rmail-make-body (forward-buffer)
6364   (save-window-excursion
6365     (set-buffer forward-buffer)
6366     (if (rmail-msg-is-pruned)
6367         (rmail-msg-restore-non-pruned-header)))
6368   (message-forward-make-body forward-buffer))
6369
6370 (eval-when-compile (defvar rmail-enable-mime-composing))
6371
6372 ;; Fixme: Should have defcustom.
6373 ;;;###autoload
6374 (defun message-insinuate-rmail ()
6375   "Let RMAIL use message to forward."
6376   (interactive)
6377   (setq rmail-enable-mime-composing t)
6378   (setq rmail-insert-mime-forwarded-message-function
6379         'message-forward-rmail-make-body))
6380
6381 ;;;###autoload
6382 (defun message-resend (address)
6383   "Resend the current article to ADDRESS."
6384   (interactive
6385    (list (message-read-from-minibuffer "Resend message to: ")))
6386   (message "Resending message to %s..." address)
6387   (save-excursion
6388     (let ((cur (current-buffer))
6389           beg)
6390       ;; We first set up a normal mail buffer.
6391       (unless (message-mail-user-agent)
6392         (set-buffer (get-buffer-create " *message resend*"))
6393         (erase-buffer))
6394       (let ((message-this-is-mail t)
6395             message-setup-hook)
6396         (message-setup `((To . ,address))))
6397       ;; Insert our usual headers.
6398       (message-generate-headers '(From Date To Message-ID))
6399       (message-narrow-to-headers)
6400       ;; Remove X-Draft-From header etc.
6401       (message-remove-header message-ignored-mail-headers t)
6402       ;; Rename them all to "Resent-*".
6403       (goto-char (point-min))
6404       (while (re-search-forward "^[A-Za-z]" nil t)
6405         (forward-char -1)
6406         (insert "Resent-"))
6407       (widen)
6408       (forward-line)
6409       (delete-region (point) (point-max))
6410       (setq beg (point))
6411       ;; Insert the message to be resent.
6412       (insert-buffer-substring cur)
6413       (goto-char (point-min))
6414       (search-forward "\n\n")
6415       (forward-char -1)
6416       (save-restriction
6417         (narrow-to-region beg (point))
6418         (message-remove-header message-ignored-resent-headers t)
6419         (goto-char (point-max)))
6420       (insert mail-header-separator)
6421       ;; Rename all old ("Also-")Resent headers.
6422       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6423         (beginning-of-line)
6424         (insert "Also-"))
6425       ;; Quote any "From " lines at the beginning.
6426       (goto-char beg)
6427       (when (looking-at "From ")
6428         (replace-match "X-From-Line: "))
6429       ;; Send it.
6430       (let ((message-inhibit-body-encoding t)
6431             message-required-mail-headers
6432             rfc2047-encode-encoded-words)
6433         (message-send-mail))
6434       (kill-buffer (current-buffer)))
6435     (message "Resending message to %s...done" address)))
6436
6437 ;;;###autoload
6438 (defun message-bounce ()
6439   "Re-mail the current message.
6440 This only makes sense if the current message is a bounce message that
6441 contains some mail you have written which has been bounced back to
6442 you."
6443   (interactive)
6444   (let ((handles (mm-dissect-buffer t))
6445         boundary)
6446     (message-pop-to-buffer (message-buffer-name "bounce"))
6447     (if (stringp (car handles))
6448         ;; This is a MIME bounce.
6449         (mm-insert-part (car (last handles)))
6450       ;; This is a non-MIME bounce, so we try to remove things
6451       ;; manually.
6452       (mm-insert-part handles)
6453       (undo-boundary)
6454       (goto-char (point-min))
6455       (re-search-forward "\n\n+" nil t)
6456       (setq boundary (point))
6457       ;; We remove everything before the bounced mail.
6458       (if (or (re-search-forward message-unsent-separator nil t)
6459               (progn
6460                 (search-forward "\n\n" nil 'move)
6461                 (re-search-backward "^Return-Path:.*\n" boundary t)))
6462           (progn
6463             (forward-line 1)
6464             (delete-region (point-min)
6465                            (if (re-search-forward "^[^ \n\t]+:" nil t)
6466                                (match-beginning 0)
6467                              (point))))
6468         (goto-char boundary)
6469         (when (re-search-backward "^.?From .*\n" nil t)
6470           (delete-region (match-beginning 0) (match-end 0)))))
6471     (mm-enable-multibyte)
6472     (save-restriction
6473       (message-narrow-to-head-1)
6474       (message-remove-header message-ignored-bounced-headers t)
6475       (goto-char (point-max))
6476       (insert mail-header-separator))
6477     (message-position-point)))
6478
6479 ;;;
6480 ;;; Interactive entry points for new message buffers.
6481 ;;;
6482
6483 ;;;###autoload
6484 (defun message-mail-other-window (&optional to subject)
6485   "Like `message-mail' command, but display mail buffer in another window."
6486   (interactive)
6487   (unless (message-mail-user-agent)
6488     (let ((pop-up-windows t)
6489           (special-display-buffer-names nil)
6490           (special-display-regexps nil)
6491           (same-window-buffer-names nil)
6492           (same-window-regexps nil))
6493       (message-pop-to-buffer (message-buffer-name "mail" to))))
6494   (let ((message-this-is-mail t))
6495     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6496                    nil nil 'switch-to-buffer-other-window)))
6497
6498 ;;;###autoload
6499 (defun message-mail-other-frame (&optional to subject)
6500   "Like `message-mail' command, but display mail buffer in another frame."
6501   (interactive)
6502   (unless (message-mail-user-agent)
6503     (let ((pop-up-frames t)
6504           (special-display-buffer-names nil)
6505           (special-display-regexps nil)
6506           (same-window-buffer-names nil)
6507           (same-window-regexps nil))
6508       (message-pop-to-buffer (message-buffer-name "mail" to))))
6509   (let ((message-this-is-mail t))
6510     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6511                    nil nil 'switch-to-buffer-other-frame)))
6512
6513 ;;;###autoload
6514 (defun message-news-other-window (&optional newsgroups subject)
6515   "Start editing a news article to be sent."
6516   (interactive)
6517   (let ((pop-up-windows t)
6518         (special-display-buffer-names nil)
6519         (special-display-regexps nil)
6520         (same-window-buffer-names nil)
6521         (same-window-regexps nil))
6522     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6523   (let ((message-this-is-news t))
6524     (message-setup `((Newsgroups . ,(or newsgroups ""))
6525                      (Subject . ,(or subject ""))))))
6526
6527 ;;;###autoload
6528 (defun message-news-other-frame (&optional newsgroups subject)
6529   "Start editing a news article to be sent."
6530   (interactive)
6531   (let ((pop-up-frames t)
6532         (special-display-buffer-names nil)
6533         (special-display-regexps nil)
6534         (same-window-buffer-names nil)
6535         (same-window-regexps nil))
6536     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6537   (let ((message-this-is-news t))
6538     (message-setup `((Newsgroups . ,(or newsgroups ""))
6539                      (Subject . ,(or subject ""))))))
6540
6541 ;;; underline.el
6542
6543 ;; This code should be moved to underline.el (from which it is stolen).
6544
6545 ;;;###autoload
6546 (defun bold-region (start end)
6547   "Bold all nonblank characters in the region.
6548 Works by overstriking characters.
6549 Called from program, takes two arguments START and END
6550 which specify the range to operate on."
6551   (interactive "r")
6552   (save-excursion
6553     (let ((end1 (make-marker)))
6554       (move-marker end1 (max start end))
6555       (goto-char (min start end))
6556       (while (< (point) end1)
6557         (or (looking-at "[_\^@- ]")
6558             (insert (char-after) "\b"))
6559         (forward-char 1)))))
6560
6561 ;;;###autoload
6562 (defun unbold-region (start end)
6563   "Remove all boldness (overstruck characters) in the region.
6564 Called from program, takes two arguments START and END
6565 which specify the range to operate on."
6566   (interactive "r")
6567   (save-excursion
6568     (let ((end1 (make-marker)))
6569       (move-marker end1 (max start end))
6570       (goto-char (min start end))
6571       (while (search-forward "\b" end1 t)
6572         (if (eq (char-after) (char-after (- (point) 2)))
6573             (delete-char -2))))))
6574
6575 (defun message-exchange-point-and-mark ()
6576   "Exchange point and mark, but don't activate region if it was inactive."
6577   (unless (prog1
6578               (message-mark-active-p)
6579             (exchange-point-and-mark))
6580     (setq mark-active nil)))
6581
6582 (defalias 'message-make-overlay 'make-overlay)
6583 (defalias 'message-delete-overlay 'delete-overlay)
6584 (defalias 'message-overlay-put 'overlay-put)
6585 (defun message-kill-all-overlays ()
6586   (if (featurep 'xemacs)
6587       (map-extents (lambda (extent ignore) (delete-extent extent)))
6588     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
6589
6590 ;; Support for toolbar
6591 (eval-when-compile
6592   (defvar tool-bar-map)
6593   (defvar tool-bar-mode))
6594
6595 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6596   ;; We need to make tool bar entries in local keymaps with
6597   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6598   (if (fboundp 'tool-bar-local-item-from-menu)
6599       ;; This is for Emacs 21.3
6600       (tool-bar-local-item-from-menu command icon in-map from-map props)
6601     (tool-bar-add-item-from-menu command icon from-map props)))
6602
6603 (defun message-tool-bar-map ()
6604   (or message-tool-bar-map
6605       (setq message-tool-bar-map
6606             (and
6607              (condition-case nil (require 'tool-bar) (error nil))
6608              (fboundp 'tool-bar-add-item-from-menu)
6609              tool-bar-mode
6610              (let ((tool-bar-map (copy-keymap tool-bar-map))
6611                    (load-path (mm-image-load-path)))
6612                ;; Zap some items which aren't so relevant and take
6613                ;; up space.
6614                (dolist (key '(print-buffer kill-buffer save-buffer
6615                                            write-file dired open-file))
6616                  (define-key tool-bar-map (vector key) nil))
6617                (message-tool-bar-local-item-from-menu
6618                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
6619                (message-tool-bar-local-item-from-menu
6620                 'message-kill-buffer "close" tool-bar-map message-mode-map)
6621                (message-tool-bar-local-item-from-menu
6622                     'message-dont-send "cancel" tool-bar-map message-mode-map)
6623                (message-tool-bar-local-item-from-menu
6624                 'mml-attach-file "attach" tool-bar-map mml-mode-map)
6625                (message-tool-bar-local-item-from-menu
6626                 'ispell-message "spell" tool-bar-map message-mode-map)
6627                (message-tool-bar-local-item-from-menu
6628                 'mml-preview "preview"
6629                 tool-bar-map mml-mode-map)
6630                (message-tool-bar-local-item-from-menu
6631                 'message-insert-importance-high "important"
6632                 tool-bar-map message-mode-map)
6633                (message-tool-bar-local-item-from-menu
6634                 'message-insert-importance-low "unimportant"
6635                 tool-bar-map message-mode-map)
6636                (message-tool-bar-local-item-from-menu
6637                 'message-insert-disposition-notification-to "receipt"
6638                 tool-bar-map message-mode-map)
6639                tool-bar-map)))))
6640
6641 ;;; Group name completion.
6642
6643 (defcustom message-newgroups-header-regexp
6644   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6645   "Regexp that match headers that lists groups."
6646   :group 'message
6647   :type 'regexp)
6648
6649 (defcustom message-completion-alist
6650   (list (cons message-newgroups-header-regexp 'message-expand-group)
6651         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6652         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6653           . message-expand-name)
6654         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6655           . message-expand-name))
6656   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6657   :version "21.4"
6658   :group 'message
6659   :type '(alist :key-type regexp :value-type function))
6660
6661 (defcustom message-expand-name-databases
6662   (list 'bbdb 'eudc)
6663   "List of databases to try for name completion (`message-expand-name').
6664 Each element is a symbol and can be `bbdb' or `eudc'."
6665   :group 'message
6666   :type '(set (const bbdb) (const eudc)))
6667
6668 (defcustom message-tab-body-function nil
6669   "*Function to execute when `message-tab' (TAB) is executed in the body.
6670 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6671   :version "21.4"
6672   :group 'message
6673   :link '(custom-manual "(message)Various Commands")
6674   :type 'function)
6675
6676 (defun message-tab ()
6677   "Complete names according to `message-completion-alist'.
6678 Execute function specified by `message-tab-body-function' when not in
6679 those headers."
6680   (interactive)
6681   (let ((alist message-completion-alist))
6682     (while (and alist
6683                 (let ((mail-abbrev-mode-regexp (caar alist)))
6684                   (not (mail-abbrev-in-expansion-header-p))))
6685       (setq alist (cdr alist)))
6686     (funcall (or (cdar alist) message-tab-body-function
6687                  (lookup-key text-mode-map "\t")
6688                  (lookup-key global-map "\t")
6689                  'indent-relative))))
6690
6691 (defun message-expand-group ()
6692   "Expand the group name under point."
6693   (let* ((b (save-excursion
6694               (save-restriction
6695                 (narrow-to-region
6696                  (save-excursion
6697                    (beginning-of-line)
6698                    (skip-chars-forward "^:")
6699                    (1+ (point)))
6700                  (point))
6701                 (skip-chars-backward "^, \t\n") (point))))
6702          (completion-ignore-case t)
6703          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6704                                             (point))))
6705          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6706          (completions (all-completions string hashtb))
6707          comp)
6708     (delete-region b (point))
6709     (cond
6710      ((= (length completions) 1)
6711       (if (string= (car completions) string)
6712           (progn
6713             (insert string)
6714             (message "Only matching group"))
6715         (insert (car completions))))
6716      ((and (setq comp (try-completion string hashtb))
6717            (not (string= comp string)))
6718       (insert comp))
6719      (t
6720       (insert string)
6721       (if (not comp)
6722           (message "No matching groups")
6723         (save-selected-window
6724           (pop-to-buffer "*Completions*")
6725           (buffer-disable-undo)
6726           (let ((buffer-read-only nil))
6727             (erase-buffer)
6728             (let ((standard-output (current-buffer)))
6729               (display-completion-list (sort completions 'string<)))
6730             (goto-char (point-min))
6731             (delete-region (point) (progn (forward-line 3) (point))))))))))
6732
6733 (defun message-expand-name ()
6734   (cond ((and (memq 'eudc message-expand-name-databases)
6735                     (boundp 'eudc-protocol)
6736                     eudc-protocol)
6737          (eudc-expand-inline))
6738         ((and (memq 'bbdb message-expand-name-databases)
6739               (fboundp 'bbdb-complete-name))
6740          (bbdb-complete-name))
6741         (t
6742          (expand-abbrev))))
6743
6744 ;;; Help stuff.
6745
6746 (defun message-talkative-question (ask question show &rest text)
6747   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6748 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6749 The following arguments may contain lists of values."
6750   (if (and show
6751            (setq text (message-flatten-list text)))
6752       (save-window-excursion
6753         (save-excursion
6754           (with-output-to-temp-buffer " *MESSAGE information message*"
6755             (set-buffer " *MESSAGE information message*")
6756             (fundamental-mode)          ; for Emacs 20.4+
6757             (mapcar 'princ text)
6758             (goto-char (point-min))))
6759         (funcall ask question))
6760     (funcall ask question)))
6761
6762 (defun message-flatten-list (list)
6763   "Return a new, flat list that contains all elements of LIST.
6764
6765 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6766 => (1 2 3 4 5 6 7)"
6767   (cond ((consp list)
6768          (apply 'append (mapcar 'message-flatten-list list)))
6769         (list
6770          (list list))))
6771
6772 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6773   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
6774 Then clone the local variables and values from the old buffer to the
6775 new one, cloning only the locals having a substring matching the
6776 regexp VARSTR."
6777   (let ((oldbuf (current-buffer)))
6778     (save-excursion
6779       (set-buffer (generate-new-buffer name))
6780       (message-clone-locals oldbuf varstr)
6781       (current-buffer))))
6782
6783 (defun message-clone-locals (buffer &optional varstr)
6784   "Clone the local variables from BUFFER to the current buffer."
6785   (let ((locals (save-excursion
6786                   (set-buffer buffer)
6787                   (buffer-local-variables)))
6788         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address"))
6789     (mapcar
6790      (lambda (local)
6791        (when (and (consp local)
6792                   (car local)
6793                   (string-match regexp (symbol-name (car local)))
6794                   (or (null varstr)
6795                       (string-match varstr (symbol-name (car local)))))
6796          (ignore-errors
6797            (set (make-local-variable (car local))
6798                 (cdr local)))))
6799      locals)))
6800
6801 ;;;
6802 ;;; MIME functions
6803 ;;;
6804
6805 (defvar message-inhibit-body-encoding nil)
6806
6807 (defun message-encode-message-body ()
6808   (unless message-inhibit-body-encoding
6809     (let ((mail-parse-charset (or mail-parse-charset
6810                                   message-default-charset))
6811           (case-fold-search t)
6812           lines content-type-p)
6813       (message-goto-body)
6814       (save-restriction
6815         (narrow-to-region (point) (point-max))
6816         (let ((new (mml-generate-mime)))
6817           (when new
6818             (delete-region (point-min) (point-max))
6819             (insert new)
6820             (goto-char (point-min))
6821             (if (eq (aref new 0) ?\n)
6822                 (delete-char 1)
6823               (search-forward "\n\n")
6824               (setq lines (buffer-substring (point-min) (1- (point))))
6825               (delete-region (point-min) (point))))))
6826       (save-restriction
6827         (message-narrow-to-headers-or-head)
6828         (message-remove-header "Mime-Version")
6829         (goto-char (point-max))
6830         (insert "MIME-Version: 1.0\n")
6831         (when lines
6832           (insert lines))
6833         (setq content-type-p
6834               (or mml-boundary
6835                   (re-search-backward "^Content-Type:" nil t))))
6836       (save-restriction
6837         (message-narrow-to-headers-or-head)
6838         (message-remove-first-header "Content-Type")
6839         (message-remove-first-header "Content-Transfer-Encoding"))
6840       ;; We always make sure that the message has a Content-Type
6841       ;; header.  This is because some broken MTAs and MUAs get
6842       ;; awfully confused when confronted with a message with a
6843       ;; MIME-Version header and without a Content-Type header.  For
6844       ;; instance, Solaris' /usr/bin/mail.
6845       (unless content-type-p
6846         (goto-char (point-min))
6847         ;; For unknown reason, MIME-Version doesn't exist.
6848         (when (re-search-forward "^MIME-Version:" nil t)
6849           (forward-line 1)
6850           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6851
6852 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6853   "Read from the minibuffer while providing abbrev expansion."
6854   (if (fboundp 'mail-abbrevs-setup)
6855       (let ((mail-abbrev-mode-regexp "")
6856             (minibuffer-setup-hook 'mail-abbrevs-setup)
6857             (minibuffer-local-map message-minibuffer-local-map))
6858         (read-from-minibuffer prompt initial-contents))
6859     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6860           (minibuffer-local-map message-minibuffer-local-map))
6861       (read-string prompt initial-contents))))
6862
6863 (defun message-use-alternative-email-as-from ()
6864   (require 'mail-utils)
6865   (let* ((fields '("To" "Cc" "From"))
6866          (emails
6867           (split-string
6868            (mail-strip-quoted-names
6869             (mapconcat 'message-fetch-reply-field fields ","))
6870            "[ \f\t\n\r\v,]+"))
6871          email)
6872     (while emails
6873       (if (string-match message-alternative-emails (car emails))
6874           (setq email (car emails)
6875                 emails nil))
6876       (pop emails))
6877     (unless (or (not email) (equal email user-mail-address))
6878       (goto-char (point-max))
6879       (insert "From: " (let ((user-mail-address email)) (message-make-from))
6880               "\n"))))
6881
6882 (defun message-options-get (symbol)
6883   (cdr (assq symbol message-options)))
6884
6885 (defun message-options-set (symbol value)
6886   (let ((the-cons (assq symbol message-options)))
6887     (if the-cons
6888         (if value
6889             (setcdr the-cons value)
6890           (setq message-options (delq the-cons message-options)))
6891       (and value
6892            (push (cons symbol value) message-options))))
6893   value)
6894
6895 (defun message-options-set-recipient ()
6896   (save-restriction
6897     (message-narrow-to-headers-or-head)
6898     (message-options-set 'message-sender
6899                          (mail-strip-quoted-names
6900                           (message-fetch-field "from")))
6901     (message-options-set 'message-recipients
6902                          (mail-strip-quoted-names
6903                           (let ((to (message-fetch-field "to"))
6904                                 (cc (message-fetch-field "cc"))
6905                                 (bcc (message-fetch-field "bcc")))
6906                             (concat
6907                              (or to "")
6908                              (if (and to cc) ", ")
6909                              (or cc "")
6910                              (if (and (or to cc) bcc) ", ")
6911                              (or bcc "")))))))
6912
6913 (defun message-hide-headers ()
6914   "Hide headers based on the `message-hidden-headers' variable."
6915   (let ((regexps (if (stringp message-hidden-headers)
6916                      (list message-hidden-headers)
6917                    message-hidden-headers))
6918         (inhibit-point-motion-hooks t)
6919         (after-change-functions nil))
6920     (when regexps
6921       (save-excursion
6922         (save-restriction
6923           (message-narrow-to-headers)
6924           (goto-char (point-min))
6925           (while (not (eobp))
6926             (if (not (message-hide-header-p regexps))
6927                 (message-next-header)
6928               (let ((begin (point)))
6929                 (message-next-header)
6930                 (add-text-properties
6931                  begin (point)
6932                  '(invisible t message-hidden t))))))))))
6933
6934 (defun message-hide-header-p (regexps)
6935   (let ((result nil)
6936         (reverse nil))
6937     (when (eq (car regexps) 'not)
6938       (setq reverse t)
6939       (pop regexps))
6940     (dolist (regexp regexps)
6941       (setq result (or result (looking-at regexp))))
6942     (if reverse
6943         (not result)
6944       result)))
6945
6946 (when (featurep 'xemacs)
6947   (require 'messagexmas)
6948   (message-xmas-redefine))
6949
6950 (provide 'message)
6951
6952 (run-hooks 'message-load-hook)
6953
6954 ;; Local Variables:
6955 ;; coding: iso-8859-1
6956 ;; End:
6957
6958 ;;; arch-tag: 94b32cac-4504-4b6c-8181-030ebf380ee0
6959 ;;; message.el ends here