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