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