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