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