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