* message.el (message-mode-syntax-table): Move forward.
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: mail, news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This mode provides mail-sending facilities from within Emacs.  It
28 ;; consists mainly of large chunks of code from the sendmail.el,
29 ;; gnus-msg.el and rnewspost.el files.
30
31 ;;; Code:
32
33 (eval-when-compile
34   (require 'cl)
35   (defvar gnus-list-identifiers)) ; gnus-sum is required where necessary
36 (require 'canlock)
37 (require 'mailheader)
38 (require 'nnheader)
39 ;; This is apparently necessary even though things are autoloaded:
40 (if (featurep 'xemacs)
41     (require 'mail-abbrevs))
42 (require 'mail-parse)
43 (require 'mml)
44 (require 'rfc822)
45 (eval-and-compile
46   (autoload 'sha1 "sha1-el"))
47
48 (defgroup message '((user-mail-address custom-variable)
49                     (user-full-name custom-variable))
50   "Mail and news message composing."
51   :link '(custom-manual "(message)Top")
52   :group 'mail
53   :group 'news)
54
55 (put 'user-mail-address 'custom-type 'string)
56 (put 'user-full-name 'custom-type 'string)
57
58 (defgroup message-various nil
59   "Various Message Variables"
60   :link '(custom-manual "(message)Various Message Variables")
61   :group 'message)
62
63 (defgroup message-buffers nil
64   "Message Buffers"
65   :link '(custom-manual "(message)Message Buffers")
66   :group 'message)
67
68 (defgroup message-sending nil
69   "Message Sending"
70   :link '(custom-manual "(message)Sending Variables")
71   :group 'message)
72
73 (defgroup message-interface nil
74   "Message Interface"
75   :link '(custom-manual "(message)Interface")
76   :group 'message)
77
78 (defgroup message-forwarding nil
79   "Message Forwarding"
80   :link '(custom-manual "(message)Forwarding")
81   :group 'message-interface)
82
83 (defgroup message-insertion nil
84   "Message Insertion"
85   :link '(custom-manual "(message)Insertion")
86   :group 'message)
87
88 (defgroup message-headers nil
89   "Message Headers"
90   :link '(custom-manual "(message)Message Headers")
91   :group 'message)
92
93 (defgroup message-news nil
94   "Composing News Messages"
95   :group 'message)
96
97 (defgroup message-mail nil
98   "Composing Mail Messages"
99   :group 'message)
100
101 (defgroup message-faces nil
102   "Faces used for message composing."
103   :group 'message
104   :group 'faces)
105
106 (defcustom message-directory "~/Mail/"
107   "*Directory from which all other mail file variables are derived."
108   :group 'message-various
109   :type 'directory)
110
111 (defcustom message-max-buffers 10
112   "*How many buffers to keep before starting to kill them off."
113   :group 'message-buffers
114   :type 'integer)
115
116 (defcustom message-send-rename-function nil
117   "Function called to rename the buffer after sending it."
118   :group 'message-buffers
119   :type '(choice function (const nil)))
120
121 (defcustom message-fcc-handler-function 'message-output
122   "*A function called to save outgoing articles.
123 This function will be called with the name of the file to store the
124 article in.  The default function is `message-output' which saves in Unix
125 mailbox format."
126   :type '(radio (function-item message-output)
127                 (function :tag "Other"))
128   :group 'message-sending)
129
130 (defcustom message-fcc-externalize-attachments nil
131   "If non-nil, attachments are included as external parts in Fcc copies."
132   :type 'boolean
133   :group 'message-sending)
134
135 (defcustom message-courtesy-message
136   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
137   "*This is inserted at the start of a mailed copy of a posted message.
138 If the string contains the format spec \"%s\", the Newsgroups
139 the article has been posted to will be inserted there.
140 If this variable is nil, no such courtesy message will be added."
141   :group 'message-sending
142   :type 'string)
143
144 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
145   "*Regexp that matches headers to be removed in resent bounced mail."
146   :group 'message-interface
147   :type 'regexp)
148
149 ;;;###autoload
150 (defcustom message-from-style 'default
151   "*Specifies how \"From\" headers look.
152
153 If nil, they contain just the return address like:
154         king@grassland.com
155 If `parens', they look like:
156         king@grassland.com (Elvis Parsley)
157 If `angles', they look like:
158         Elvis Parsley <king@grassland.com>
159
160 Otherwise, most addresses look like `angles', but they look like
161 `parens' if `angles' would need quoting and `parens' would not."
162   :type '(choice (const :tag "simple" nil)
163                  (const parens)
164                  (const angles)
165                  (const default))
166   :group 'message-headers)
167
168 (defcustom message-syntax-checks nil
169   ;; Guess this one shouldn't be easy to customize...
170   "*Controls what syntax checks should not be performed on outgoing posts.
171 To disable checking of long signatures, for instance, add
172  `(signature . disabled)' to this list.
173
174 Don't touch this variable unless you really know what you're doing.
175
176 Checks include `subject-cmsg', `multiple-headers', `sendsys',
177 `message-id', `from', `long-lines', `control-chars', `size',
178 `new-text', `quoting-style', `redirected-followup', `signature',
179 `approved', `sender', `empty', `empty-headers', `message-id', `from',
180 `subject', `shorten-followup-to', `existing-newsgroups',
181 `buffer-file-name', `unchanged', `newsgroups', `reply-to'."
182   :group 'message-news
183   :type '(repeat sexp))                 ; Fixme: improve this
184
185 (defcustom message-required-news-headers
186   '(From Newsgroups Subject Date Message-ID
187          (optional . Organization) Lines
188          (optional . User-Agent))
189   "*Headers to be generated or prompted for when posting an article.
190 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
191 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
192 User-Agent are optional.  If don't you want message to insert some
193 header, remove it from this list."
194   :group 'message-news
195   :group 'message-headers
196   :type '(repeat sexp))
197
198 (defcustom message-required-mail-headers
199   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
200          (optional . User-Agent))
201   "*Headers to be generated or prompted for when mailing a message.
202 It is recommended that From, Date, To, Subject and Message-ID be
203 included.  Organization, Lines and User-Agent are optional."
204   :group 'message-mail
205   :group 'message-headers
206   :type '(repeat sexp))
207
208 (defcustom message-deletable-headers '(Message-ID Date Lines)
209   "Headers to be deleted if they already exist and were generated by message previously."
210   :group 'message-headers
211   :type 'sexp)
212
213 (defcustom message-ignored-news-headers
214   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
215   "*Regexp of headers to be removed unconditionally before posting."
216   :group 'message-news
217   :group 'message-headers
218   :type 'regexp)
219
220 (defcustom message-ignored-mail-headers
221   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
222   "*Regexp of headers to be removed unconditionally before mailing."
223   :group 'message-mail
224   :group 'message-headers
225   :type 'regexp)
226
227 (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:"
228   "*Header lines matching this regexp will be deleted before posting.
229 It's best to delete old Path and Date headers before posting to avoid
230 any confusion."
231   :group 'message-interface
232   :type 'regexp)
233
234 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
235   "*Regexp matching \"Re: \" in the subject line."
236   :group 'message-various
237   :type 'regexp)
238
239 ;;;###autoload
240 (defcustom message-signature-separator "^-- *$"
241   "Regexp matching the signature separator."
242   :type 'regexp
243   :group 'message-various)
244
245 (defcustom message-elide-ellipsis "\n[...]\n\n"
246   "*The string which is inserted for elided text."
247   :type 'string
248   :group 'message-various)
249
250 (defcustom message-interactive nil
251   "Non-nil means when sending a message wait for and display errors.
252 nil means let mailer mail back a message to report errors."
253   :group 'message-sending
254   :group 'message-mail
255   :type 'boolean)
256
257 (defcustom message-generate-new-buffers 'unique
258   "*Non-nil means create a new message buffer whenever `message-setup' is called.
259 If this is a function, call that function with three parameters:  The type,
260 the to address and the group name.  (Any of these may be nil.)  The function
261 should return the new buffer name."
262   :group 'message-buffers
263   :type '(choice (const :tag "off" nil)
264                  (const :tag "unique" unique)
265                  (const :tag "unsent" unsent)
266                  (function fun)))
267
268 (defcustom message-kill-buffer-on-exit nil
269   "*Non-nil means that the message buffer will be killed after sending a message."
270   :group 'message-buffers
271   :type 'boolean)
272
273 (eval-when-compile
274   (defvar gnus-local-organization))
275 (defcustom message-user-organization
276   (or (and (boundp 'gnus-local-organization)
277            (stringp gnus-local-organization)
278            gnus-local-organization)
279       (getenv "ORGANIZATION")
280       t)
281   "*String to be used as an Organization header.
282 If t, use `message-user-organization-file'."
283   :group 'message-headers
284   :type '(choice string
285                  (const :tag "consult file" t)))
286
287 ;;;###autoload
288 (defcustom message-user-organization-file "/usr/lib/news/organization"
289   "*Local news organization file."
290   :type 'file
291   :group 'message-headers)
292
293 (defcustom message-make-forward-subject-function
294   'message-forward-subject-author-subject
295   "*List of functions called to generate subject headers for forwarded messages.
296 The subject generated by the previous function is passed into each
297 successive function.
298
299 The provided functions are:
300
301 * `message-forward-subject-author-subject' (Source of article (author or
302       newsgroup)), in brackets followed by the subject
303 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
304       to it."
305   :group 'message-forwarding
306   :type '(radio (function-item message-forward-subject-author-subject)
307                 (function-item message-forward-subject-fwd)
308                 (repeat :tag "List of functions" function)))
309
310 (defcustom message-forward-as-mime t
311   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
312   :version "21.1"
313   :group 'message-forwarding
314   :type 'boolean)
315
316 (defcustom message-forward-show-mml t
317   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
318   :version "21.1"
319   :group 'message-forwarding
320   :type 'boolean)
321
322 (defcustom message-forward-before-signature t
323   "*If non-nil, put forwarded message before signature, else after."
324   :group 'message-forwarding
325   :type 'boolean)
326
327 (defcustom message-wash-forwarded-subjects nil
328   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
329   :group 'message-forwarding
330   :type 'boolean)
331
332 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
333   "*All headers that match this regexp will be deleted when resending a message."
334   :group 'message-interface
335   :type 'regexp)
336
337 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
338   "*All headers that match this regexp will be deleted when forwarding a message."
339   :version "21.1"
340   :group 'message-forwarding
341   :type '(choice (const :tag "None" nil)
342                  regexp))
343
344 (defcustom message-ignored-cited-headers "."
345   "*Delete these headers from the messages you yank."
346   :group 'message-insertion
347   :type 'regexp)
348
349 (defvar message-mode-syntax-table
350   (let ((table (copy-syntax-table text-mode-syntax-table)))
351     (modify-syntax-entry ?% ". " table)
352     (modify-syntax-entry ?> ". " table)
353     (modify-syntax-entry ?< ". " table)
354     table)
355   "Syntax table used while in Message mode.")
356
357 (defcustom message-cite-prefix-regexp
358   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
359       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>»|:}+]\\)+"
360     (with-syntax-table message-mode-syntax-table
361       ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
362       (let ((non-word-constituents
363              (concat
364               (if (string-match "\\w" "-")  "" "-")
365               (if (string-match "\\w" "_")  "" "_")
366               (if (string-match "\\w" ".")  "" "."))))
367         (if (equal non-word-constituents "")
368             "\\([ \t]*\\(\\w\\)+>+\\|[ \t]*[]>»|:}+]\\)+"
369           (concat "\\([ \t]*\\(\\w\\|[" 
370                   non-word-constituents
371                   "]\\)+>+\\|[ \t]*[]>»|:}+]\\)+")))))
372   "*Regexp matching the longest possible citation prefix on a line."
373   :group 'message-insertion
374   :type 'regexp)
375
376 (defcustom message-cancel-message "I am canceling my own article.\n"
377   "Message to be inserted in the cancel message."
378   :group 'message-interface
379   :type 'string)
380
381 ;; Useful to set in site-init.el
382 ;;;###autoload
383 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
384   "Function to call to send the current buffer as mail.
385 The headers should be delimited by a line whose contents match the
386 variable `mail-header-separator'.
387
388 Valid values include `message-send-mail-with-sendmail' (the default),
389 `message-send-mail-with-mh', `message-send-mail-with-qmail',
390 `smtpmail-send-it' and `feedmail-send-it'.
391
392 See also `send-mail-function'."
393   :type '(radio (function-item message-send-mail-with-sendmail)
394                 (function-item message-send-mail-with-mh)
395                 (function-item message-send-mail-with-qmail)
396                 (function-item smtpmail-send-it)
397                 (function-item feedmail-send-it)
398                 (function :tag "Other"))
399   :group 'message-sending
400   :group 'message-mail)
401
402 (defcustom message-send-news-function 'message-send-news
403   "Function to call to send the current buffer as news.
404 The headers should be delimited by a line whose contents match the
405 variable `mail-header-separator'."
406   :group 'message-sending
407   :group 'message-news
408   :type 'function)
409
410 (defcustom message-reply-to-function nil
411   "If non-nil, function that should return a list of headers.
412 This function should pick out addresses from the To, Cc, and From headers
413 and respond with new To and Cc headers."
414   :group 'message-interface
415   :type '(choice function (const nil)))
416
417 (defcustom message-wide-reply-to-function nil
418   "If non-nil, function that should return a list of headers.
419 This function should pick out addresses from the To, Cc, and From headers
420 and respond with new To and Cc headers."
421   :group 'message-interface
422   :type '(choice function (const nil)))
423
424 (defcustom message-followup-to-function nil
425   "If non-nil, function that should return a list of headers.
426 This function should pick out addresses from the To, Cc, and From headers
427 and respond with new To and Cc headers."
428   :group 'message-interface
429   :type '(choice function (const nil)))
430
431 (defcustom message-use-followup-to 'ask
432   "*Specifies what to do with Followup-To header.
433 If nil, always ignore the header.  If it is t, use its value, but
434 query before using the \"poster\" value.  If it is the symbol `ask',
435 always query the user whether to use the value.  If it is the symbol
436 `use', always use the value."
437   :group 'message-interface
438   :type '(choice (const :tag "ignore" nil)
439                  (const :tag "use & query" t)
440                  (const use)
441                  (const ask)))
442
443 (defcustom message-use-mail-followup-to 'use
444   "*Specifies what to do with Mail-Followup-To header.
445 If nil, always ignore the header.  If it is the symbol `ask', always
446 query the user whether to use the value.  If it is the symbol `use',
447 always use the value."
448   :group 'message-interface
449   :type '(choice (const :tag "ignore" nil)
450                  (const use)
451                  (const ask)))
452
453 (defcustom message-subscribed-address-functions nil
454   "*Specifies functions for determining list subscription.
455 If nil, do not attempt to determine list subscribtion with functions.
456 If non-nil, this variable contains a list of functions which return
457 regular expressions to match lists.  These functions can be used in
458 conjunction with `message-subscribed-regexps' and
459 `message-subscribed-addresses'."
460   :group 'message-interface
461   :type '(repeat sexp))
462
463 (defcustom message-subscribed-address-file nil
464   "*A file containing addresses the user is subscribed to.
465 If nil, do not look at any files to determine list subscriptions.  If
466 non-nil, each line of this file should be a mailing list address."
467   :group 'message-interface
468   :type 'string)
469
470 (defcustom message-subscribed-addresses nil
471   "*Specifies a list of addresses the user is subscribed to.
472 If nil, do not use any predefined list subscriptions.  This list of
473 addresses can be used in conjuction with
474 `message-subscribed-address-functions' and `message-subscribed-regexps'."
475   :group 'message-interface
476   :type '(repeat string))
477
478 (defcustom message-subscribed-regexps nil
479   "*Specifies a list of addresses the user is subscribed to.
480 If nil, do not use any predefined list subscriptions.  This list of
481 regular expressions can be used in conjuction with
482 `message-subscribed-address-functions' and `message-subscribed-addresses'."
483   :group 'message-interface
484   :type '(repeat regexp))
485
486 (defcustom message-allow-no-recipients 'ask
487   "Specifies what to do when there are no recipients other than Gcc/Fcc.
488 If it is the symbol `always', the posting is allowed.  If it is the
489 symbol `never', the posting is not allowed.  If it is the symbol
490 `ask', you are prompted."
491   :group 'message-interface
492   :type '(choice (const always)
493                  (const never)
494                  (const ask)))
495
496 (defcustom message-sendmail-f-is-evil nil
497   "*Non-nil means don't add \"-f username\" to the sendmail command line.
498 Doing so would be even more evil than leaving it out."
499   :group 'message-sending
500   :type 'boolean)
501
502 ;; qmail-related stuff
503 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
504   "Location of the qmail-inject program."
505   :group 'message-sending
506   :type 'file)
507
508 (defcustom message-qmail-inject-args nil
509   "Arguments passed to qmail-inject programs.
510 This should be a list of strings, one string for each argument.
511
512 For e.g., if you wish to set the envelope sender address so that bounces
513 go to the right place or to deal with listserv's usage of that address, you
514 might set this variable to '(\"-f\" \"you@some.where\")."
515   :group 'message-sending
516   :type '(repeat string))
517
518 (defvar message-cater-to-broken-inn t
519   "Non-nil means Gnus should not fold the `References' header.
520 Folding `References' makes ancient versions of INN create incorrect
521 NOV lines.")
522
523 (eval-when-compile
524   (defvar gnus-post-method)
525   (defvar gnus-select-method))
526 (defcustom message-post-method
527   (cond ((and (boundp 'gnus-post-method)
528               (listp gnus-post-method)
529               gnus-post-method)
530          gnus-post-method)
531         ((boundp 'gnus-select-method)
532          gnus-select-method)
533         (t '(nnspool "")))
534   "*Method used to post news.
535 Note that when posting from inside Gnus, for instance, this
536 variable isn't used."
537   :group 'message-news
538   :group 'message-sending
539   ;; This should be the `gnus-select-method' widget, but that might
540   ;; create a dependence to `gnus.el'.
541   :type 'sexp)
542
543 (defcustom message-generate-headers-first nil
544   "*If non-nil, generate all required headers before composing.
545 The variables `message-required-news-headers' and
546 `message-required-mail-headers' specify which headers to generate.
547
548 Note that the variable `message-deletable-headers' specifies headers which
549 are to be deleted and then re-generated before sending, so this variable
550 will not have a visible effect for those headers."
551   :group 'message-headers
552   :type 'boolean)
553
554 (defcustom message-setup-hook nil
555   "Normal hook, run each time a new outgoing message is initialized.
556 The function `message-setup' runs this hook."
557   :group 'message-various
558   :type 'hook)
559
560 (defcustom message-cancel-hook nil
561   "Hook run when cancelling articles."
562   :group 'message-various
563   :type 'hook)
564
565 (defcustom message-signature-setup-hook nil
566   "Normal hook, run each time a new outgoing message is initialized.
567 It is run after the headers have been inserted and before
568 the signature is inserted."
569   :group 'message-various
570   :type 'hook)
571
572 (defcustom message-mode-hook nil
573   "Hook run in message mode buffers."
574   :group 'message-various
575   :type 'hook)
576
577 (defcustom message-header-hook nil
578   "Hook run in a message mode buffer narrowed to the headers."
579   :group 'message-various
580   :type 'hook)
581
582 (defcustom message-header-setup-hook nil
583   "Hook called narrowed to the headers when setting up a message buffer."
584   :group 'message-various
585   :type 'hook)
586
587 (defcustom message-minibuffer-local-map
588   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
589     (set-keymap-parent map minibuffer-local-map)
590     map)
591   "Keymap for `message-read-from-minibuffer'.")
592
593 ;;;###autoload
594 (defcustom message-citation-line-function 'message-insert-citation-line
595   "*Function called to insert the \"Whomever writes:\" line.
596
597 Note that Gnus provides a feature where the reader can click on
598 `writes:' to hide the cited text.  If you change this line too much,
599 people who read your message will have to change their Gnus
600 configuration.  See the variable `gnus-cite-attribution-suffix'."
601   :type 'function
602   :group 'message-insertion)
603
604 ;;;###autoload
605 (defcustom message-yank-prefix "> "
606   "*Prefix inserted on the lines of yanked messages.
607 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
608 See also `message-yank-cited-prefix'."
609   :type 'string
610   :group 'message-insertion)
611
612 (defcustom message-yank-cited-prefix ">"
613   "*Prefix inserted on cited or empty lines of yanked messages.
614 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
615 See also `message-yank-prefix'."
616   :type 'string
617   :group 'message-insertion)
618
619 (defcustom message-indentation-spaces 3
620   "*Number of spaces to insert at the beginning of each cited line.
621 Used by `message-yank-original' via `message-yank-cite'."
622   :group 'message-insertion
623   :type 'integer)
624
625 ;;;###autoload
626 (defcustom message-cite-function 'message-cite-original
627   "*Function for citing an original message.
628 Predefined functions include `message-cite-original' and
629 `message-cite-original-without-signature'.
630 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
631   :type '(radio (function-item message-cite-original)
632                 (function-item message-cite-original-without-signature)
633                 (function-item sc-cite-original)
634                 (function :tag "Other"))
635   :group 'message-insertion)
636
637 ;;;###autoload
638 (defcustom message-indent-citation-function 'message-indent-citation
639   "*Function for modifying a citation just inserted in the mail buffer.
640 This can also be a list of functions.  Each function can find the
641 citation between (point) and (mark t).  And each function should leave
642 point and mark around the citation text as modified."
643   :type 'function
644   :group 'message-insertion)
645
646 (defvar message-abbrevs-loaded nil)
647
648 ;;;###autoload
649 (defcustom message-signature t
650   "*String to be inserted at the end of the message buffer.
651 If t, the `message-signature-file' file will be inserted instead.
652 If a function, the result from the function will be used instead.
653 If a form, the result from the form will be used instead."
654   :type 'sexp
655   :group 'message-insertion)
656
657 ;;;###autoload
658 (defcustom message-signature-file "~/.signature"
659   "*Name of file containing the text inserted at end of message buffer.
660 Ignored if the named file doesn't exist.
661 If nil, don't insert a signature."
662   :type '(choice file (const :tags "None" nil))
663   :group 'message-insertion)
664
665 (defcustom message-distribution-function nil
666   "*Function called to return a Distribution header."
667   :group 'message-news
668   :group 'message-headers
669   :type '(choice function (const nil)))
670
671 (defcustom message-expires 14
672   "Number of days before your article expires."
673   :group 'message-news
674   :group 'message-headers
675   :link '(custom-manual "(message)News Headers")
676   :type 'integer)
677
678 (defcustom message-user-path nil
679   "If nil, use the NNTP server name in the Path header.
680 If stringp, use this; if non-nil, use no host name (user name only)."
681   :group 'message-news
682   :group 'message-headers
683   :link '(custom-manual "(message)News Headers")
684   :type '(choice (const :tag "nntp" nil)
685                  (string :tag "name")
686                  (sexp :tag "none" :format "%t" t)))
687
688 (defvar message-reply-buffer nil)
689 (defvar message-reply-headers nil)
690 (defvar message-newsreader nil)
691 (defvar message-mailer nil)
692 (defvar message-sent-message-via nil)
693 (defvar message-checksum nil)
694 (defvar message-send-actions nil
695   "A list of actions to be performed upon successful sending of a message.")
696 (defvar message-exit-actions nil
697   "A list of actions to be performed upon exiting after sending a message.")
698 (defvar message-kill-actions nil
699   "A list of actions to be performed before killing a message buffer.")
700 (defvar message-postpone-actions nil
701   "A list of actions to be performed after postponing a message.")
702
703 (define-widget 'message-header-lines 'text
704   "All header lines must be LFD terminated."
705   :format "%{%t%}:%n%v"
706   :valid-regexp "^\\'"
707   :error "All header lines must be newline terminated")
708
709 (defcustom message-default-headers ""
710   "*A string containing header lines to be inserted in outgoing messages.
711 It is inserted before you edit the message, so you can edit or delete
712 these lines."
713   :group 'message-headers
714   :type 'message-header-lines)
715
716 (defcustom message-default-mail-headers ""
717   "*A string of header lines to be inserted in outgoing mails."
718   :group 'message-headers
719   :group 'message-mail
720   :type 'message-header-lines)
721
722 (defcustom message-default-news-headers ""
723   "*A string of header lines to be inserted in outgoing news articles."
724   :group 'message-headers
725   :group 'message-news
726   :type 'message-header-lines)
727
728 ;; Note: could use /usr/ucb/mail instead of sendmail;
729 ;; options -t, and -v if not interactive.
730 (defcustom message-mailer-swallows-blank-line
731   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
732                          system-configuration)
733            (file-readable-p "/etc/sendmail.cf")
734            (let ((buffer (get-buffer-create " *temp*")))
735              (unwind-protect
736                  (save-excursion
737                    (set-buffer buffer)
738                    (insert-file-contents "/etc/sendmail.cf")
739                    (goto-char (point-min))
740                    (let ((case-fold-search nil))
741                      (re-search-forward "^OR\\>" nil t)))
742                (kill-buffer buffer))))
743       ;; According to RFC822, "The field-name must be composed of printable
744       ;; ASCII characters (i. e., characters that have decimal values between
745       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
746       ;; space, or colon.
747       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
748   "*Set this non-nil if the system's mailer runs the header and body together.
749 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
750 The value should be an expression to test whether the problem will
751 actually occur."
752   :group 'message-sending
753   :type 'sexp)
754
755 ;;;###autoload
756 (define-mail-user-agent 'message-user-agent
757   'message-mail 'message-send-and-exit
758   'message-kill-buffer 'message-send-hook)
759
760 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
761   "If non-nil, delete the deletable headers before feeding to mh.")
762
763 (defvar message-send-method-alist
764   '((news message-news-p message-send-via-news)
765     (mail message-mail-p message-send-via-mail))
766   "Alist of ways to send outgoing messages.
767 Each element has the form
768
769   \(TYPE PREDICATE FUNCTION)
770
771 where TYPE is a symbol that names the method; PREDICATE is a function
772 called without any parameters to determine whether the message is
773 a message of type TYPE; and FUNCTION is a function to be called if
774 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
775 the prefix.")
776
777 (defcustom message-mail-alias-type 'abbrev
778   "*What alias expansion type to use in Message buffers.
779 The default is `abbrev', which uses mailabbrev.  nil switches
780 mail aliases off."
781   :group 'message
782   :link '(custom-manual "(message)Mail Aliases")
783   :type '(choice (const :tag "Use Mailabbrev" abbrev)
784                  (const :tag "No expansion" nil)))
785
786 (defcustom message-auto-save-directory
787   (file-name-as-directory (nnheader-concat message-directory "drafts"))
788   "*Directory where Message auto-saves buffers if Gnus isn't running.
789 If nil, Message won't auto-save."
790   :group 'message-buffers
791   :type '(choice directory (const :tag "Don't auto-save" nil)))
792
793 (defcustom message-buffer-naming-style 'unique
794   "*The way new message buffers are named.
795 Valid valued are `unique' and `unsent'."
796   :version "21.1"
797   :group 'message-buffers
798   :type '(choice (const :tag "unique" unique)
799                  (const :tag "unsent" unsent)))
800
801 (defcustom message-default-charset
802   (and (not (mm-multibyte-p)) 'iso-8859-1)
803   "Default charset used in non-MULE Emacsen.
804 If nil, you might be asked to input the charset."
805   :version "21.1"
806   :group 'message
807   :type 'symbol)
808
809 (defcustom message-dont-reply-to-names
810   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
811   "*A regexp specifying addresses to prune when doing wide replies.
812 A value of nil means exclude your own user name only."
813   :version "21.1"
814   :group 'message
815   :type '(choice (const :tag "Yourself" nil)
816                  regexp))
817
818 (defvar message-shoot-gnksa-feet nil
819   "*A list of GNKSA feet you are allowed to shoot.
820 Gnus gives you all the opportunity you could possibly want for
821 shooting yourself in the foot.  Also, Gnus allows you to shoot the
822 feet of Good Net-Keeping Seal of Approval. The following are foot
823 candidates:
824 `empty-article'     Allow you to post an empty article;
825 `quoted-text-only'  Allow you to post quoted text only;
826 `multiple-copies'   Allow you to post multiple copies.")
827 ;; `cancel-messages'   Allow you to cancel or supersede others' messages.
828
829 (defsubst message-gnksa-enable-p (feature)
830   (or (not (listp message-shoot-gnksa-feet))
831       (memq feature message-shoot-gnksa-feet)))
832
833 ;;; Internal variables.
834 ;;; Well, not really internal.
835
836 (defface message-header-to-face
837   '((((class color)
838       (background dark))
839      (:foreground "green2" :bold t))
840     (((class color)
841       (background light))
842      (:foreground "MidnightBlue" :bold t))
843     (t
844      (:bold t :italic t)))
845   "Face used for displaying From headers."
846   :group 'message-faces)
847
848 (defface message-header-cc-face
849   '((((class color)
850       (background dark))
851      (:foreground "green4" :bold t))
852     (((class color)
853       (background light))
854      (:foreground "MidnightBlue"))
855     (t
856      (:bold t)))
857   "Face used for displaying Cc headers."
858   :group 'message-faces)
859
860 (defface message-header-subject-face
861   '((((class color)
862       (background dark))
863      (:foreground "green3"))
864     (((class color)
865       (background light))
866      (:foreground "navy blue" :bold t))
867     (t
868      (:bold t)))
869   "Face used for displaying subject headers."
870   :group 'message-faces)
871
872 (defface message-header-newsgroups-face
873   '((((class color)
874       (background dark))
875      (:foreground "yellow" :bold t :italic t))
876     (((class color)
877       (background light))
878      (:foreground "blue4" :bold t :italic t))
879     (t
880      (:bold t :italic t)))
881   "Face used for displaying newsgroups headers."
882   :group 'message-faces)
883
884 (defface message-header-other-face
885   '((((class color)
886       (background dark))
887      (:foreground "#b00000"))
888     (((class color)
889       (background light))
890      (:foreground "steel blue"))
891     (t
892      (:bold t :italic t)))
893   "Face used for displaying newsgroups headers."
894   :group 'message-faces)
895
896 (defface message-header-name-face
897   '((((class color)
898       (background dark))
899      (:foreground "DarkGreen"))
900     (((class color)
901       (background light))
902      (:foreground "cornflower blue"))
903     (t
904      (:bold t)))
905   "Face used for displaying header names."
906   :group 'message-faces)
907
908 (defface message-header-xheader-face
909   '((((class color)
910       (background dark))
911      (:foreground "blue"))
912     (((class color)
913       (background light))
914      (:foreground "blue"))
915     (t
916      (:bold t)))
917   "Face used for displaying X-Header headers."
918   :group 'message-faces)
919
920 (defface message-separator-face
921   '((((class color)
922       (background dark))
923      (:foreground "blue3"))
924     (((class color)
925       (background light))
926      (:foreground "brown"))
927     (t
928      (:bold t)))
929   "Face used for displaying the separator."
930   :group 'message-faces)
931
932 (defface message-cited-text-face
933   '((((class color)
934       (background dark))
935      (:foreground "red"))
936     (((class color)
937       (background light))
938      (:foreground "red"))
939     (t
940      (:bold t)))
941   "Face used for displaying cited text names."
942   :group 'message-faces)
943
944 (defface message-mml-face
945   '((((class color)
946       (background dark))
947      (:foreground "ForestGreen"))
948     (((class color)
949       (background light))
950      (:foreground "ForestGreen"))
951     (t
952      (:bold t)))
953   "Face used for displaying MML."
954   :group 'message-faces)
955
956 (defvar message-font-lock-keywords
957   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
958     `((,(concat "^\\([Tt]o:\\)" content)
959        (1 'message-header-name-face)
960        (2 'message-header-to-face nil t))
961       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
962        (1 'message-header-name-face)
963        (2 'message-header-cc-face nil t))
964       (,(concat "^\\([Ss]ubject:\\)" content)
965        (1 'message-header-name-face)
966        (2 'message-header-subject-face nil t))
967       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
968        (1 'message-header-name-face)
969        (2 'message-header-newsgroups-face nil t))
970       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
971        (1 'message-header-name-face)
972        (2 'message-header-other-face nil t))
973       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
974        (1 'message-header-name-face)
975        (2 'message-header-name-face))
976       ,@(if (and mail-header-separator
977                  (not (equal mail-header-separator "")))
978             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
979                1 'message-separator-face))
980           nil)
981       (,(concat "^\\(" message-cite-prefix-regexp "\\).*")
982        (0 'message-cited-text-face))
983       ("<#/?\\(multipart\\|part\\|external\\|mml\\|secure\\).*>"
984        (0 'message-mml-face))))
985   "Additional expressions to highlight in Message mode.")
986
987 ;; XEmacs does it like this.  For Emacs, we have to set the
988 ;; `font-lock-defaults' buffer-local variable.
989 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
990
991 (defvar message-face-alist
992   '((bold . bold-region)
993     (underline . underline-region)
994     (default . (lambda (b e)
995                  (unbold-region b e)
996                  (ununderline-region b e))))
997   "Alist of mail and news faces for facemenu.
998 The cdr of ech entry is a function for applying the face to a region.")
999
1000 (defcustom message-send-hook nil
1001   "Hook run before sending messages."
1002   :group 'message-various
1003   :options '(ispell-message)
1004   :type 'hook)
1005
1006 (defcustom message-send-mail-hook nil
1007   "Hook run before sending mail messages."
1008   :group 'message-various
1009   :type 'hook)
1010
1011 (defcustom message-send-news-hook nil
1012   "Hook run before sending news messages."
1013   :group 'message-various
1014   :type 'hook)
1015
1016 (defcustom message-sent-hook nil
1017   "Hook run after sending messages."
1018   :group 'message-various
1019   :type 'hook)
1020
1021 (defvar message-send-coding-system 'binary
1022   "Coding system to encode outgoing mail.")
1023
1024 (defvar message-draft-coding-system
1025   mm-auto-save-coding-system
1026   "Coding system to compose mail.")
1027
1028 (defcustom message-send-mail-partially-limit 1000000
1029   "The limitation of messages sent as message/partial.
1030 The lower bound of message size in characters, beyond which the message
1031 should be sent in several parts.  If it is nil, the size is unlimited."
1032   :version "21.1"
1033   :group 'message-buffers
1034   :type '(choice (const :tag "unlimited" nil)
1035                  (integer 1000000)))
1036
1037 (defcustom message-alternative-emails nil
1038   "A regexp to match the alternative email addresses.
1039 The first matched address (not primary one) is used in the From field."
1040   :group 'message-headers
1041   :type '(choice (const :tag "Always use primary" nil)
1042                  regexp))
1043
1044 (defcustom message-mail-user-agent nil
1045   "Like `mail-user-agent'.
1046 Except if it is nil, use Gnus native MUA; if it is t, use
1047 `mail-user-agent'."
1048   :type '(radio (const :tag "Gnus native"
1049                        :format "%t\n"
1050                        nil)
1051                 (const :tag "`mail-user-agent'"
1052                        :format "%t\n"
1053                        t)
1054                 (function-item :tag "Default Emacs mail"
1055                                :format "%t\n"
1056                                sendmail-user-agent)
1057                 (function-item :tag "Emacs interface to MH"
1058                                :format "%t\n"
1059                                mh-e-user-agent)
1060                 (function :tag "Other"))
1061   :version "21.1"
1062   :group 'message)
1063
1064 (defcustom message-wide-reply-confirm-recipients nil
1065   "Whether to confirm a wide reply to multiple email recipients.
1066 If this variable is nil, don't ask whether to reply to all recipients.
1067 If this variable is non-nil, pose the question \"Reply to all
1068 recipients?\" before a wide reply to multiple recipients.  If the user
1069 answers yes, reply to all recipients as usual.  If the user answers
1070 no, only reply back to the author."
1071   :group 'message-headers
1072   :type 'boolean)
1073
1074 (defcustom message-insert-canlock t
1075   "Whether to insert a Cancel-Lock header in news postings."
1076   :group 'message-headers
1077   :type 'boolean)
1078
1079 ;;; Internal variables.
1080
1081 (defvar message-sending-message "Sending...")
1082 (defvar message-buffer-list nil)
1083 (defvar message-this-is-news nil)
1084 (defvar message-this-is-mail nil)
1085 (defvar message-draft-article nil)
1086 (defvar message-mime-part nil)
1087 (defvar message-posting-charset nil)
1088
1089 ;; Byte-compiler warning
1090 (eval-when-compile
1091   (defvar gnus-active-hashtb)
1092   (defvar gnus-read-active-file))
1093
1094 ;;; Regexp matching the delimiter of messages in UNIX mail format
1095 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1096 ;;; of rmail.el's rmail-unix-mail-delimiter.
1097 (defvar message-unix-mail-delimiter
1098   (let ((time-zone-regexp
1099          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1100                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1101                  "\\|"
1102                  "\\) *")))
1103     (concat
1104      "From "
1105
1106      ;; Many things can happen to an RFC 822 mailbox before it is put into
1107      ;; a `From' line.  The leading phrase can be stripped, e.g.
1108      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1109      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1110      ;; can be removed, e.g.
1111      ;;         From: joe@y.z (Joe      K
1112      ;;                 User)
1113      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1114      ;;         From: Joe User
1115      ;;                 <joe@y.z>
1116      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1117      ;; The mailbox can be removed or be replaced by white space, e.g.
1118      ;;         From: "Joe User"{space}{tab}
1119      ;;                 <joe@y.z>
1120      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1121      ;; where {space} and {tab} represent the Ascii space and tab characters.
1122      ;; We want to match the results of any of these manglings.
1123      ;; The following regexp rejects names whose first characters are
1124      ;; obviously bogus, but after that anything goes.
1125      "\\([^\0-\b\n-\r\^?].*\\)? "
1126
1127      ;; The time the message was sent.
1128      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1129      "\\([^\0-\r \^?]+\\) +"            ; month
1130      "\\([0-3]?[0-9]\\) +"              ; day of month
1131      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1132
1133      ;; Perhaps a time zone, specified by an abbreviation, or by a
1134      ;; numeric offset.
1135      time-zone-regexp
1136
1137      ;; The year.
1138      " \\([0-9][0-9]+\\) *"
1139
1140      ;; On some systems the time zone can appear after the year, too.
1141      time-zone-regexp
1142
1143      ;; Old uucp cruft.
1144      "\\(remote from .*\\)?"
1145
1146      "\n"))
1147   "Regexp matching the delimiter of messages in UNIX mail format.")
1148
1149 (defvar message-unsent-separator
1150   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1151           "^ *---+ +Returned message +---+ *$\\|"
1152           "^Start of returned message$\\|"
1153           "^ *---+ +Original message +---+ *$\\|"
1154           "^ *--+ +begin message +--+ *$\\|"
1155           "^ *---+ +Original message follows +---+ *$\\|"
1156           "^ *---+ +Undelivered message follows +---+ *$\\|"
1157           "^|? *---+ +Message text follows: +---+ *|?$")
1158   "A regexp that matches the separator before the text of a failed message.")
1159
1160 (defvar message-header-format-alist
1161   `((Newsgroups)
1162     (To . message-fill-address)
1163     (Cc . message-fill-address)
1164     (Subject)
1165     (In-Reply-To)
1166     (Fcc)
1167     (Bcc)
1168     (Date)
1169     (Organization)
1170     (Distribution)
1171     (Lines)
1172     (Expires)
1173     (Message-ID)
1174     (References . message-shorten-references)
1175     (User-Agent))
1176   "Alist used for formatting headers.")
1177
1178 (defvar message-options nil
1179   "Some saved answers when sending message.")
1180
1181 (defvar message-send-mail-real-function nil
1182   "Internal send mail function.")
1183
1184 (defvar message-bogus-system-names "^localhost\\."
1185   "The regexp of bogus system names.")
1186
1187 (eval-and-compile
1188   (autoload 'message-setup-toolbar "messagexmas")
1189   (autoload 'mh-new-draft-name "mh-comp")
1190   (autoload 'mh-send-letter "mh-comp")
1191   (autoload 'gnus-point-at-eol "gnus-util")
1192   (autoload 'gnus-point-at-bol "gnus-util")
1193   (autoload 'gnus-output-to-rmail "gnus-util")
1194   (autoload 'gnus-output-to-mail "gnus-util")
1195   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1196   (autoload 'nndraft-request-associate-buffer "nndraft")
1197   (autoload 'nndraft-request-expire-articles "nndraft")
1198   (autoload 'gnus-open-server "gnus-int")
1199   (autoload 'gnus-request-post "gnus-int")
1200   (autoload 'gnus-alive-p "gnus-util")
1201   (autoload 'gnus-server-string "gnus")
1202   (autoload 'gnus-group-name-charset "gnus-group")
1203   (autoload 'gnus-group-name-decode "gnus-group")
1204   (autoload 'gnus-groups-from-server "gnus")
1205   (autoload 'rmail-output "rmailout"))
1206
1207 \f
1208
1209 ;;;
1210 ;;; Utility functions.
1211 ;;;
1212
1213 (defmacro message-y-or-n-p (question show &rest text)
1214   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1215   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1216
1217 (defmacro message-delete-line (&optional n)
1218   "Delete the current line (and the next N lines)."
1219   `(delete-region (progn (beginning-of-line) (point))
1220                   (progn (forward-line ,(or n 1)) (point))))
1221
1222 (defun message-unquote-tokens (elems)
1223   "Remove double quotes (\") from strings in list ELEMS."
1224   (mapcar (lambda (item)
1225             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1226               (setq item (concat (match-string 1 item)
1227                                  (match-string 2 item))))
1228             item)
1229           elems))
1230
1231 (defun message-tokenize-header (header &optional separator)
1232   "Split HEADER into a list of header elements.
1233 SEPARATOR is a string of characters to be used as separators.  \",\"
1234 is used by default."
1235   (if (not header)
1236       nil
1237     (let ((regexp (format "[%s]+" (or separator ",")))
1238           (beg 1)
1239           (first t)
1240           quoted elems paren)
1241       (save-excursion
1242         (message-set-work-buffer)
1243         (insert header)
1244         (goto-char (point-min))
1245         (while (not (eobp))
1246           (if first
1247               (setq first nil)
1248             (forward-char 1))
1249           (cond ((and (> (point) beg)
1250                       (or (eobp)
1251                           (and (looking-at regexp)
1252                                (not quoted)
1253                                (not paren))))
1254                  (push (buffer-substring beg (point)) elems)
1255                  (setq beg (match-end 0)))
1256                 ((eq (char-after) ?\")
1257                  (setq quoted (not quoted)))
1258                 ((and (eq (char-after) ?\()
1259                       (not quoted))
1260                  (setq paren t))
1261                 ((and (eq (char-after) ?\))
1262                       (not quoted))
1263                  (setq paren nil))))
1264         (nreverse elems)))))
1265
1266 (defun message-mail-file-mbox-p (file)
1267   "Say whether FILE looks like a Unix mbox file."
1268   (when (and (file-exists-p file)
1269              (file-readable-p file)
1270              (file-regular-p file))
1271     (with-temp-buffer
1272       (nnheader-insert-file-contents file)
1273       (goto-char (point-min))
1274       (looking-at message-unix-mail-delimiter))))
1275
1276 (defun message-fetch-field (header &optional not-all)
1277   "The same as `mail-fetch-field', only remove all newlines."
1278   (let* ((inhibit-point-motion-hooks t)
1279          (case-fold-search t)
1280          (value (mail-fetch-field header nil (not not-all))))
1281     (when value
1282       (while (string-match "\n[\t ]+" value)
1283         (setq value (replace-match " " t t value)))
1284       (set-text-properties 0 (length value) nil value)
1285       value)))
1286
1287 (defun message-narrow-to-field ()
1288   "Narrow the buffer to the header on the current line."
1289   (beginning-of-line)
1290   (narrow-to-region
1291    (point)
1292    (progn
1293      (forward-line 1)
1294      (if (re-search-forward "^[^ \n\t]" nil t)
1295          (progn
1296            (beginning-of-line)
1297            (point))
1298        (point-max))))
1299   (goto-char (point-min)))
1300
1301 (defun message-add-header (&rest headers)
1302   "Add the HEADERS to the message header, skipping those already present."
1303   (while headers
1304     (let (hclean)
1305       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1306         (error "Invalid header `%s'" (car headers)))
1307       (setq hclean (match-string 1 (car headers)))
1308       (save-restriction
1309         (message-narrow-to-headers)
1310         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1311           (goto-char (point-max))
1312           (if (string-match "\n$" (car headers))
1313               (insert (car headers))
1314             (insert (car headers) ?\n)))))
1315     (setq headers (cdr headers))))
1316
1317
1318 (defun message-fetch-reply-field (header)
1319   "Fetch field HEADER from the message we're replying to."
1320   (when (and message-reply-buffer
1321              (buffer-name message-reply-buffer))
1322     (save-excursion
1323       (set-buffer message-reply-buffer)
1324       (message-fetch-field header))))
1325
1326 (defun message-set-work-buffer ()
1327   (if (get-buffer " *message work*")
1328       (progn
1329         (set-buffer " *message work*")
1330         (erase-buffer))
1331     (set-buffer (get-buffer-create " *message work*"))
1332     (kill-all-local-variables)
1333     (mm-enable-multibyte)))
1334
1335 (defun message-functionp (form)
1336   "Return non-nil if FORM is funcallable."
1337   (or (and (symbolp form) (fboundp form))
1338       (and (listp form) (eq (car form) 'lambda))
1339       (byte-code-function-p form)))
1340
1341 (defun message-strip-list-identifiers (subject)
1342   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1343   (require 'gnus-sum)                   ; for gnus-list-identifiers
1344   (let ((regexp (if (stringp gnus-list-identifiers)
1345                     gnus-list-identifiers
1346                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1347     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1348                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1349         (concat (substring subject 0 (match-beginning 1))
1350                 (or (match-string 3 subject)
1351                     (match-string 5 subject))
1352                 (substring subject
1353                            (match-end 1)))
1354       subject)))
1355
1356 (defun message-strip-subject-re (subject)
1357   "Remove \"Re:\" from subject lines in string SUBJECT."
1358   (if (string-match message-subject-re-regexp subject)
1359       (substring subject (match-end 0))
1360     subject))
1361
1362 (defun message-remove-header (header &optional is-regexp first reverse)
1363   "Remove HEADER in the narrowed buffer.
1364 If IS-REGEXP, HEADER is a regular expression.
1365 If FIRST, only remove the first instance of the header.
1366 Return the number of headers removed."
1367   (goto-char (point-min))
1368   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1369         (number 0)
1370         (case-fold-search t)
1371         last)
1372     (while (and (not (eobp))
1373                 (not last))
1374       (if (if reverse
1375               (not (looking-at regexp))
1376             (looking-at regexp))
1377           (progn
1378             (incf number)
1379             (when first
1380               (setq last t))
1381             (delete-region
1382              (point)
1383              ;; There might be a continuation header, so we have to search
1384              ;; until we find a new non-continuation line.
1385              (progn
1386                (forward-line 1)
1387                (if (re-search-forward "^[^ \t]" nil t)
1388                    (goto-char (match-beginning 0))
1389                  (point-max)))))
1390         (forward-line 1)
1391         (if (re-search-forward "^[^ \t]" nil t)
1392             (goto-char (match-beginning 0))
1393           (goto-char (point-max)))))
1394     number))
1395
1396 (defun message-remove-first-header (header)
1397   "Remove the first instance of HEADER if there is more than one."
1398   (let ((count 0)
1399         (regexp (concat "^" (regexp-quote header) ":")))
1400     (save-excursion
1401       (goto-char (point-min))
1402       (while (re-search-forward regexp nil t)
1403         (incf count)))
1404     (while (> count 1)
1405       (message-remove-header header nil t)
1406       (decf count))))
1407
1408 (defun message-narrow-to-headers ()
1409   "Narrow the buffer to the head of the message."
1410   (widen)
1411   (narrow-to-region
1412    (goto-char (point-min))
1413    (if (re-search-forward
1414         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1415        (match-beginning 0)
1416      (point-max)))
1417   (goto-char (point-min)))
1418
1419 (defun message-narrow-to-head-1 ()
1420   "Like `message-narrow-to-head'.  Don't widen."
1421   (narrow-to-region
1422    (goto-char (point-min))
1423    (if (search-forward "\n\n" nil 1)
1424        (1- (point))
1425      (point-max)))
1426   (goto-char (point-min)))
1427
1428 (defun message-narrow-to-head ()
1429   "Narrow the buffer to the head of the message.
1430 Point is left at the beginning of the narrowed-to region."
1431   (widen)
1432   (message-narrow-to-head-1))
1433
1434 (defun message-narrow-to-headers-or-head ()
1435   "Narrow the buffer to the head of the message."
1436   (widen)
1437   (narrow-to-region
1438    (goto-char (point-min))
1439    (cond
1440     ((re-search-forward
1441       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1442      (match-beginning 0))
1443     ((search-forward "\n\n" nil t)
1444      (1- (point)))
1445     (t
1446      (point-max))))
1447   (goto-char (point-min)))
1448
1449 (defun message-news-p ()
1450   "Say whether the current buffer contains a news message."
1451   (and (not message-this-is-mail)
1452        (or message-this-is-news
1453            (save-excursion
1454              (save-restriction
1455                (message-narrow-to-headers)
1456                (and (message-fetch-field "newsgroups")
1457                     (not (message-fetch-field "posted-to"))))))))
1458
1459 (defun message-mail-p ()
1460   "Say whether the current buffer contains a mail message."
1461   (and (not message-this-is-news)
1462        (or message-this-is-mail
1463            (save-excursion
1464              (save-restriction
1465                (message-narrow-to-headers)
1466                (or (message-fetch-field "to")
1467                    (message-fetch-field "cc")
1468                    (message-fetch-field "bcc")))))))
1469
1470 (defun message-next-header ()
1471   "Go to the beginning of the next header."
1472   (beginning-of-line)
1473   (or (eobp) (forward-char 1))
1474   (not (if (re-search-forward "^[^ \t]" nil t)
1475            (beginning-of-line)
1476          (goto-char (point-max)))))
1477
1478 (defun message-sort-headers-1 ()
1479   "Sort the buffer as headers using `message-rank' text props."
1480   (goto-char (point-min))
1481   (require 'sort)
1482   (sort-subr
1483    nil 'message-next-header
1484    (lambda ()
1485      (message-next-header)
1486      (unless (bobp)
1487        (forward-char -1)))
1488    (lambda ()
1489      (or (get-text-property (point) 'message-rank)
1490          10000))))
1491
1492 (defun message-sort-headers ()
1493   "Sort the headers of the current message according to `message-header-format-alist'."
1494   (interactive)
1495   (save-excursion
1496     (save-restriction
1497       (let ((max (1+ (length message-header-format-alist)))
1498             rank)
1499         (message-narrow-to-headers)
1500         (while (re-search-forward "^[^ \n]+:" nil t)
1501           (put-text-property
1502            (match-beginning 0) (1+ (match-beginning 0))
1503            'message-rank
1504            (if (setq rank (length (memq (assq (intern (buffer-substring
1505                                                        (match-beginning 0)
1506                                                        (1- (match-end 0))))
1507                                               message-header-format-alist)
1508                                         message-header-format-alist)))
1509                (- max rank)
1510              (1+ max)))))
1511       (message-sort-headers-1))))
1512
1513 \f
1514
1515 ;;;
1516 ;;; Message mode
1517 ;;;
1518
1519 ;;; Set up keymap.
1520
1521 (defvar message-mode-map nil)
1522
1523 (unless message-mode-map
1524   (setq message-mode-map (make-keymap))
1525   (set-keymap-parent message-mode-map text-mode-map)
1526   (define-key message-mode-map "\C-c?" 'describe-mode)
1527
1528   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1529   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
1530   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1531   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1532   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1533   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1534   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1535   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1536   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1537   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1538   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1539   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1540   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1541   (define-key message-mode-map "\C-c\C-f\C-i" 'message-insert-or-toggle-importance)
1542   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1543   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1544
1545   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1546   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1547
1548   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
1549   (define-key message-mode-map "\C-c\M-n" 'message-insert-disposition-notification-to)
1550
1551   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1552   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1553   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1554   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1555   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1556   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1557   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1558   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1559
1560   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1561   (define-key message-mode-map "\C-c\C-s" 'message-send)
1562   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1563   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1564   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
1565
1566   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1567   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1568   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1569   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1570   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
1571
1572   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1573   
1574   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
1575   (define-key message-mode-map "\t" 'message-tab)
1576   (define-key message-mode-map "\M-;" 'comment-region))
1577
1578 (easy-menu-define
1579   message-mode-menu message-mode-map "Message Menu."
1580   `("Message"
1581     ["Sort Headers" message-sort-headers t]
1582     ["Yank Original" message-yank-original t]
1583     ["Fill Yanked Message" message-fill-yanked-message t]
1584     ["Insert Signature" message-insert-signature t]
1585     ["Caesar (rot13) Message" message-caesar-buffer-body t]
1586     ["Caesar (rot13) Region" message-caesar-region (mark t)]
1587     ["Elide Region" message-elide-region (mark t)]
1588     ["Delete Outside Region" message-delete-not-region (mark t)]
1589     ["Kill To Signature" message-kill-to-signature t]
1590     ["Newline and Reformat" message-newline-and-reformat t]
1591     ["Rename buffer" message-rename-buffer t]
1592     ["Flag As Important" message-insert-importance-high
1593      ,@(if (featurep 'xemacs) '(t)
1594          '(:help "Mark this message as important"))]
1595     ["Flag As Unimportant" message-insert-importance-low
1596      ,@(if (featurep 'xemacs) '(t)
1597          '(:help "Mark this message as unimportant"))]
1598     ["Request Receipt" 
1599      message-insert-disposition-notification-to
1600      ,@(if (featurep 'xemacs) '(t)
1601          '(:help "Request a Disposition Notification of this article"))]
1602     ["Spellcheck" ispell-message
1603      ,@(if (featurep 'xemacs) '(t)
1604          '(:help "Spellcheck this message"))]
1605     "----"
1606     ["Send Message" message-send-and-exit
1607      ,@(if (featurep 'xemacs) '(t)
1608          '(:help "Send this message"))]
1609     ["Postpone Message" message-dont-send
1610      ,@(if (featurep 'xemacs) '(t)
1611          '(:help "File this draft message and exit"))]
1612     ["Send at Specific Time" gnus-delay-article
1613      ,@(if (featurep 'xemacs) '(t)
1614          '(:help "Ask, then arrange to send message at that time"))]
1615     ["Kill Message" message-kill-buffer
1616      ,@(if (featurep 'xemacs) '(t)
1617          '(:help "Delete this message without sending"))]))
1618
1619 (easy-menu-define
1620   message-mode-field-menu message-mode-map ""
1621   '("Field"
1622     ["Fetch To" message-insert-to t]
1623     ["Fetch Newsgroups" message-insert-newsgroups t]
1624     "----"
1625     ["To" message-goto-to t]
1626     ["From" message-goto-from t]
1627     ["Subject" message-goto-subject t]
1628     ["Cc" message-goto-cc t]
1629     ["Reply-To" message-goto-reply-to t]
1630     ["Summary" message-goto-summary t]
1631     ["Keywords" message-goto-keywords t]
1632     ["Newsgroups" message-goto-newsgroups t]
1633     ["Followup-To" message-goto-followup-to t]
1634     ["Mail-Followup-To" message-goto-mail-followup-to t]
1635     ["Distribution" message-goto-distribution t]
1636     ["Body" message-goto-body t]
1637     ["Signature" message-goto-signature t]))
1638
1639 (defvar message-tool-bar-map nil)
1640
1641 (eval-when-compile
1642   (defvar facemenu-add-face-function)
1643   (defvar facemenu-remove-face-function))
1644
1645 ;;; Forbidden properties
1646 ;;
1647 ;; We use `after-change-functions' to keep special text properties
1648 ;; that interfer with the normal function of message mode out of the
1649 ;; buffer. 
1650
1651 (defcustom message-strip-special-text-properties t
1652   "Strip special properties from the message buffer.
1653
1654 Emacs has a number of special text properties which can break message
1655 composing in various ways.  If this option is set, message will strip
1656 these properties from the message composition buffer.  However, some
1657 packages requires these properties to be present in order to work.
1658 If you use one of these packages, turn this option off, and hope the
1659 message composition doesn't break too bad."
1660   :group 'message-various
1661   :type 'boolean)
1662
1663 (defconst message-forbidden-properties 
1664   ;; No reason this should be clutter up customize.  We make it a
1665   ;; property list (rather than a list of property symbols), to be
1666   ;; directly useful for `remove-text-properties'.
1667   '(field nil read-only nil intangible nil invisible nil 
1668           mouse-face nil modification-hooks nil insert-in-front-hooks nil
1669           insert-behind-hooks nil point-entered nil point-left nil) 
1670   ;; Other special properties:
1671   ;; category, face, display: probably doesn't do any harm.
1672   ;; fontified: is used by font-lock.
1673   ;; syntax-table, local-map: I dunno.
1674   ;; We need to add XEmacs names to the list.
1675   "Property list of with properties.forbidden in message buffers.
1676 The values of the properties are ignored, only the property names are used.")
1677
1678 (defun message-tamago-not-in-use-p (pos)
1679   "Return t when tamago version 4 is not in use at the cursor position.
1680 Tamago version 4 is a popular input method for writing Japanese text.
1681 It uses the properties `intangible', `invisible', `modification-hooks'
1682 and `read-only' when translating ascii or kana text to kanji text.
1683 These properties are essential to work, so we should never strip them."
1684   (not (and (boundp 'egg-modefull-mode)
1685             (symbol-value 'egg-modefull-mode)
1686             (or (memq (get-text-property pos 'intangible)
1687                       '(its-part-1 its-part-2))
1688                 (get-text-property pos 'egg-end)
1689                 (get-text-property pos 'egg-lang)
1690                 (get-text-property pos 'egg-start)))))
1691
1692 (defun message-strip-forbidden-properties (begin end &optional old-length)
1693   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
1694 This function is intended to be called from `after-change-functions'.
1695 See also `message-forbidden-properties'."
1696   (when (and message-strip-special-text-properties
1697              (message-tamago-not-in-use-p begin))
1698     (remove-text-properties begin end message-forbidden-properties)))
1699
1700 ;;;###autoload
1701 (define-derived-mode message-mode text-mode "Message"
1702   "Major mode for editing mail and news to be sent.
1703 Like Text Mode but with these additional commands:\\<message-mode-map>
1704 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1705 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1706 C-c C-f  move to a header field (and create it if there isn't):
1707          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1708          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1709          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1710          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1711          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1712          C-c C-f C-f  move to Followup-To
1713          C-c C-f C-m  move to Mail-Followup-To
1714          C-c C-f C-i  cycle through Importance values
1715 C-c C-t  `message-insert-to' (add a To header to a news followup)
1716 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
1717 C-c C-b  `message-goto-body' (move to beginning of message text).
1718 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
1719 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
1720 C-c C-y  `message-yank-original' (insert current message, if any).
1721 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
1722 C-c C-e  `message-elide-region' (elide the text between point and mark).
1723 C-c C-v  `message-delete-not-region' (remove the text outside the region).
1724 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
1725 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
1726 C-c C-a  `mml-attach-file' (attach a file as MIME).
1727 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
1728 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
1729 M-RET    `message-newline-and-reformat' (break the line and reformat)."
1730   (set (make-local-variable 'message-reply-buffer) nil)
1731   (make-local-variable 'message-send-actions)
1732   (make-local-variable 'message-exit-actions)
1733   (make-local-variable 'message-kill-actions)
1734   (make-local-variable 'message-postpone-actions)
1735   (make-local-variable 'message-draft-article)
1736   (setq buffer-offer-save t)
1737   (set (make-local-variable 'facemenu-add-face-function)
1738        (lambda (face end)
1739          (let ((face-fun (cdr (assq face message-face-alist))))
1740            (if face-fun
1741                (funcall face-fun (point) end)
1742              (error "Face %s not configured for %s mode" face mode-name)))
1743          ""))
1744   (set (make-local-variable 'facemenu-remove-face-function) t)
1745   (set (make-local-variable 'message-reply-headers) nil)
1746   (make-local-variable 'message-newsreader)
1747   (make-local-variable 'message-mailer)
1748   (make-local-variable 'message-post-method)
1749   (set (make-local-variable 'message-sent-message-via) nil)
1750   (set (make-local-variable 'message-checksum) nil)
1751   (set (make-local-variable 'message-mime-part) 0)
1752   (message-setup-fill-variables)
1753   ;; Allow using comment commands to add/remove quoting.
1754   (set (make-local-variable 'comment-start) message-yank-prefix)
1755   (if (featurep 'xemacs)
1756       (message-setup-toolbar)
1757     (set (make-local-variable 'font-lock-defaults)
1758          '(message-font-lock-keywords t))
1759     (if (boundp 'tool-bar-map)
1760         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1761   (easy-menu-add message-mode-menu message-mode-map)
1762   (easy-menu-add message-mode-field-menu message-mode-map)
1763   ;; make-local-hook is harmless though obsolete in Emacs 21.
1764   ;; Emacs 20 and XEmacs need make-local-hook. 
1765   (make-local-hook 'after-change-functions)
1766   ;; Mmmm... Forbidden properties...
1767   (add-hook 'after-change-functions 'message-strip-forbidden-properties 
1768             nil 'local)
1769   ;; Allow mail alias things.
1770   (when (eq message-mail-alias-type 'abbrev)
1771     (if (fboundp 'mail-abbrevs-setup)
1772         (mail-abbrevs-setup)
1773       (mail-aliases-setup)))
1774   (message-set-auto-save-file-name)
1775   (mm-enable-multibyte)
1776   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
1777   (mml-mode))
1778
1779 (defun message-setup-fill-variables ()
1780   "Setup message fill variables."
1781   (set (make-local-variable 'fill-paragraph-function)
1782        'message-fill-paragraph)
1783   (make-local-variable 'paragraph-separate)
1784   (make-local-variable 'paragraph-start)
1785   (make-local-variable 'adaptive-fill-regexp)
1786   (unless (boundp 'adaptive-fill-first-line-regexp)
1787     (setq adaptive-fill-first-line-regexp nil))
1788   (make-local-variable 'adaptive-fill-first-line-regexp)
1789   (let ((quote-prefix-regexp
1790          ;; User should change message-cite-prefix-regexp if
1791          ;; message-yank-prefix is set to an abnormal value.
1792          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
1793     (setq paragraph-start
1794           (concat
1795            (regexp-quote mail-header-separator) "$\\|"
1796            "[ \t]*$\\|"                 ; blank lines
1797            "-- $\\|"                    ; signature delimiter
1798            "---+$\\|"              ; delimiters for forwarded messages
1799            page-delimiter "$\\|"        ; spoiler warnings
1800            ".*wrote:$\\|"               ; attribution lines
1801            quote-prefix-regexp "$"))    ; empty lines in quoted text
1802     (setq paragraph-separate paragraph-start)
1803     (setq adaptive-fill-regexp
1804           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1805     (setq adaptive-fill-first-line-regexp
1806           (concat quote-prefix-regexp "\\|"
1807                   adaptive-fill-first-line-regexp)))
1808   (make-local-variable 'auto-fill-inhibit-regexp)
1809   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
1810   (setq auto-fill-inhibit-regexp nil)
1811   (make-local-variable 'normal-auto-fill-function)
1812   (setq normal-auto-fill-function 'message-do-auto-fill)
1813   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
1814   ;; In that case, ensure that it uses the right function.  The real
1815   ;; solution would be not to use `define-derived-mode', and run
1816   ;; `text-mode-hook' ourself at the end of the mode.
1817   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
1818   (when auto-fill-function
1819     (setq auto-fill-function normal-auto-fill-function)))
1820
1821 \f
1822
1823 ;;;
1824 ;;; Message mode commands
1825 ;;;
1826
1827 ;;; Movement commands
1828
1829 (defun message-goto-to ()
1830   "Move point to the To header."
1831   (interactive)
1832   (message-position-on-field "To"))
1833
1834 (defun message-goto-from ()
1835   "Move point to the From header."
1836   (interactive)
1837   (message-position-on-field "From"))
1838
1839 (defun message-goto-subject ()
1840   "Move point to the Subject header."
1841   (interactive)
1842   (message-position-on-field "Subject"))
1843
1844 (defun message-goto-cc ()
1845   "Move point to the Cc header."
1846   (interactive)
1847   (message-position-on-field "Cc" "To"))
1848
1849 (defun message-goto-bcc ()
1850   "Move point to the Bcc  header."
1851   (interactive)
1852   (message-position-on-field "Bcc" "Cc" "To"))
1853
1854 (defun message-goto-fcc ()
1855   "Move point to the Fcc header."
1856   (interactive)
1857   (message-position-on-field "Fcc" "To" "Newsgroups"))
1858
1859 (defun message-goto-reply-to ()
1860   "Move point to the Reply-To header."
1861   (interactive)
1862   (message-position-on-field "Reply-To" "Subject"))
1863
1864 (defun message-goto-newsgroups ()
1865   "Move point to the Newsgroups header."
1866   (interactive)
1867   (message-position-on-field "Newsgroups"))
1868
1869 (defun message-goto-distribution ()
1870   "Move point to the Distribution header."
1871   (interactive)
1872   (message-position-on-field "Distribution"))
1873
1874 (defun message-goto-followup-to ()
1875   "Move point to the Followup-To header."
1876   (interactive)
1877   (message-position-on-field "Followup-To" "Newsgroups"))
1878
1879 (defun message-goto-mail-followup-to ()
1880   "Move point to the Mail-Followup-To header."
1881   (interactive)
1882   (message-position-on-field "Mail-Followup-To" "From"))
1883
1884 (defun message-goto-keywords ()
1885   "Move point to the Keywords header."
1886   (interactive)
1887   (message-position-on-field "Keywords" "Subject"))
1888
1889 (defun message-goto-summary ()
1890   "Move point to the Summary header."
1891   (interactive)
1892   (message-position-on-field "Summary" "Subject"))
1893
1894 (defun message-goto-body (&optional interactivep)
1895   "Move point to the beginning of the message body."
1896   (interactive (list t))
1897   (when (and interactivep
1898              (looking-at "[ \t]*\n"))
1899     (expand-abbrev))
1900   (goto-char (point-min))
1901   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1902       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
1903
1904 (defun message-goto-eoh ()
1905   "Move point to the end of the headers."
1906   (interactive)
1907   (message-goto-body)
1908   (forward-line -1))
1909
1910 (defun message-goto-signature ()
1911   "Move point to the beginning of the message signature.
1912 If there is no signature in the article, go to the end and
1913 return nil."
1914   (interactive)
1915   (goto-char (point-min))
1916   (if (re-search-forward message-signature-separator nil t)
1917       (forward-line 1)
1918     (goto-char (point-max))
1919     nil))
1920
1921 \f
1922
1923 (defun message-insert-to (&optional force)
1924   "Insert a To header that points to the author of the article being replied to.
1925 If the original author requested not to be sent mail, the function signals
1926 an error.
1927 With the prefix argument FORCE, insert the header anyway."
1928   (interactive "P")
1929   (let ((co (message-fetch-reply-field "mail-copies-to")))
1930     (when (and (null force)
1931                co
1932                (or (equal (downcase co) "never")
1933                    (equal (downcase co) "nobody")))
1934       (error "The user has requested not to have copies sent via mail")))
1935   (when (and (message-position-on-field "To")
1936              (mail-fetch-field "to")
1937              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1938     (insert ", "))
1939   (insert (or (message-fetch-reply-field "mail-reply-to")
1940               (message-fetch-reply-field "reply-to")
1941               (message-fetch-reply-field "from") "")))
1942
1943 (defun message-widen-reply ()
1944   "Widen the reply to include maximum recipients."
1945   (interactive)
1946   (let ((follow-to
1947          (and message-reply-buffer
1948               (buffer-name message-reply-buffer)
1949               (save-excursion
1950                 (set-buffer message-reply-buffer)
1951                 (message-get-reply-headers t)))))
1952     (save-excursion
1953       (save-restriction
1954         (message-narrow-to-headers)
1955         (dolist (elem follow-to)
1956           (message-remove-header (symbol-name (car elem)))
1957           (goto-char (point-min))
1958           (insert (symbol-name (car elem)) ": "
1959                   (cdr elem) "\n"))))))
1960
1961 (defun message-insert-newsgroups ()
1962   "Insert the Newsgroups header from the article being replied to."
1963   (interactive)
1964   (when (and (message-position-on-field "Newsgroups")
1965              (mail-fetch-field "newsgroups")
1966              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1967     (insert ","))
1968   (insert (or (message-fetch-reply-field "newsgroups") "")))
1969
1970 \f
1971
1972 ;;; Various commands
1973
1974 (defun message-delete-not-region (beg end)
1975   "Delete everything in the body of the current message outside of the region."
1976   (interactive "r")
1977   (let (citeprefix)
1978     (save-excursion
1979       (goto-char beg)
1980       ;; snarf citation prefix, if appropriate
1981       (unless (eq (point) (progn (beginning-of-line) (point)))
1982         (when (looking-at message-cite-prefix-regexp)
1983           (setq citeprefix (match-string 0))))
1984       (goto-char end)
1985       (delete-region (point) (if (not (message-goto-signature))
1986                                  (point)
1987                                (forward-line -2)
1988                                (point)))
1989       (insert "\n")
1990       (goto-char beg)
1991       (delete-region beg (progn (message-goto-body)
1992                                 (forward-line 2)
1993                                 (point)))
1994       (when citeprefix
1995         (insert citeprefix))))
1996   (when (message-goto-signature)
1997     (forward-line -2)))
1998
1999 (defun message-kill-to-signature ()
2000   "Deletes all text up to the signature."
2001   (interactive)
2002   (let ((point (point)))
2003     (message-goto-signature)
2004     (unless (eobp)
2005       (forward-line -2))
2006     (kill-region point (point))
2007     (unless (bolp)
2008       (insert "\n"))))
2009
2010 (defun message-newline-and-reformat (&optional arg not-break)
2011   "Insert four newlines, and then reformat if inside quoted text.
2012 Prefix arg means justify as well."
2013   (interactive (list (if current-prefix-arg 'full)))
2014   (let (quoted point beg end leading-space bolp)
2015     (setq point (point))
2016     (beginning-of-line)
2017     (setq beg (point))
2018     (setq bolp (= beg point))
2019     ;; Find first line of the paragraph.
2020     (if not-break
2021         (while (and (not (eobp))
2022                     (not (looking-at message-cite-prefix-regexp))
2023                     (looking-at paragraph-start))
2024           (forward-line 1)))
2025     ;; Find the prefix
2026     (when (looking-at message-cite-prefix-regexp)
2027       (setq quoted (match-string 0))
2028       (goto-char (match-end 0))
2029       (looking-at "[ \t]*")
2030       (setq leading-space (match-string 0)))
2031     (if (and quoted
2032              (not not-break)
2033              (not bolp)
2034              (< (- point beg) (length quoted)))
2035         ;; break inside the cite prefix.
2036         (setq quoted nil
2037               end nil))
2038     (if quoted
2039         (progn
2040           (forward-line 1)
2041           (while (and (not (eobp))
2042                       (not (looking-at paragraph-separate))
2043                       (looking-at message-cite-prefix-regexp)
2044                       (equal quoted (match-string 0)))
2045             (goto-char (match-end 0))
2046             (looking-at "[ \t]*")
2047             (if (> (length leading-space) (length (match-string 0)))
2048                 (setq leading-space (match-string 0)))
2049             (forward-line 1))
2050           (setq end (point))
2051           (goto-char beg)
2052           (while (and (if (bobp) nil (forward-line -1) t)
2053                       (not (looking-at paragraph-start))
2054                       (looking-at message-cite-prefix-regexp)
2055                       (equal quoted (match-string 0)))
2056             (setq beg (point))
2057             (goto-char (match-end 0))
2058             (looking-at "[ \t]*")
2059             (if (> (length leading-space) (length (match-string 0)))
2060                 (setq leading-space (match-string 0)))))
2061       (while (and (not (eobp))
2062                   (not (looking-at paragraph-separate))
2063                   (not (looking-at message-cite-prefix-regexp)))
2064         (forward-line 1))
2065       (setq end (point))
2066       (goto-char beg)
2067       (while (and (if (bobp) nil (forward-line -1) t)
2068                   (not (looking-at paragraph-start))
2069                   (not (looking-at message-cite-prefix-regexp)))
2070         (setq beg (point))))
2071     (goto-char point)
2072     (save-restriction
2073       (narrow-to-region beg end)
2074       (if not-break
2075           (setq point nil)
2076         (if bolp
2077             (newline)
2078           (newline)
2079           (newline))
2080         (setq point (point))
2081         ;; (newline 2) doesn't mark both newline's as hard, so call
2082         ;; newline twice. -jas
2083         (newline)
2084         (newline)
2085         (delete-region (point) (re-search-forward "[ \t]*"))
2086         (when (and quoted (not bolp))
2087           (insert quoted leading-space)))
2088       (if quoted
2089           (let* ((adaptive-fill-regexp
2090                   (regexp-quote (concat quoted leading-space)))
2091                  (adaptive-fill-first-line-regexp
2092                   adaptive-fill-regexp ))
2093             (fill-paragraph arg))
2094         (fill-paragraph arg))
2095       (if point (goto-char point)))))
2096
2097 (defun message-fill-paragraph (&optional arg)
2098   "Like `fill-paragraph'."
2099   (interactive (list (if current-prefix-arg 'full)))
2100   (if (and (boundp 'filladapt-mode) filladapt-mode)
2101       nil
2102     (message-newline-and-reformat arg t)
2103     t))
2104
2105 ;; Is it better to use `mail-header-end'?
2106 (defun message-point-in-header-p ()
2107   "Return t if point is in the header."
2108   (save-excursion
2109     (let ((p (point)))
2110       (goto-char (point-min))
2111       (not (re-search-forward
2112             (concat "^" (regexp-quote mail-header-separator) "\n")
2113             p t)))))
2114
2115 (defun message-do-auto-fill ()
2116   "Like `do-auto-fill', but don't fill in message header."
2117   (unless (message-point-in-header-p)
2118     (do-auto-fill)))
2119
2120 (defun message-insert-signature (&optional force)
2121   "Insert a signature.  See documentation for variable `message-signature'."
2122   (interactive (list 0))
2123   (let* ((signature
2124           (cond
2125            ((and (null message-signature)
2126                  (eq force 0))
2127             (save-excursion
2128               (goto-char (point-max))
2129               (not (re-search-backward message-signature-separator nil t))))
2130            ((and (null message-signature)
2131                  force)
2132             t)
2133            ((message-functionp message-signature)
2134             (funcall message-signature))
2135            ((listp message-signature)
2136             (eval message-signature))
2137            (t message-signature)))
2138          (signature
2139           (cond ((stringp signature)
2140                  signature)
2141                 ((and (eq t signature)
2142                       message-signature-file
2143                       (file-exists-p message-signature-file))
2144                  signature))))
2145     (when signature
2146       (goto-char (point-max))
2147       ;; Insert the signature.
2148       (unless (bolp)
2149         (insert "\n"))
2150       (insert "\n-- \n")
2151       (if (eq signature t)
2152           (insert-file-contents message-signature-file)
2153         (insert signature))
2154       (goto-char (point-max))
2155       (or (bolp) (insert "\n")))))
2156
2157 (defun message-insert-importance-high ()
2158   "Insert header to mark message as important."
2159   (interactive)
2160   (save-excursion
2161     (message-remove-header "Importance")
2162     (message-goto-eoh)
2163     (insert "Importance: high\n")))
2164
2165 (defun message-insert-importance-low ()
2166   "Insert header to mark message as unimportant."
2167   (interactive)
2168   (save-excursion
2169     (message-remove-header "Importance")
2170     (message-goto-eoh)
2171     (insert "Importance: low\n")))
2172
2173 (defun message-insert-or-toggle-importance ()
2174   "Insert a \"Importance: high\" header, or cycle through the header values.
2175 The three allowed values according to RFC 1327 are `high', `normal'
2176 and `low'."
2177   (interactive)
2178   (save-excursion
2179     (let ((valid '("high" "normal" "low"))
2180           (new "high")
2181           cur)
2182       (when (setq cur (message-fetch-field "Importance"))
2183         (message-remove-header "Importance")
2184         (setq new (cond ((string= cur "high")
2185                          "low")
2186                         ((string= cur "low")
2187                          "normal")
2188                         (t
2189                          "high"))))
2190       (message-goto-eoh)
2191       (insert (format "Importance: %s\n" new)))))
2192
2193 (defun message-insert-disposition-notification-to ()
2194   "Request a disposition notification (return receipt) to this message.
2195 Note that this should not be used in newsgroups."
2196   (interactive)
2197   (save-excursion
2198     (message-remove-header "Disposition-Notification-To")
2199     (message-goto-eoh)
2200     (insert (format "Disposition-Notification-To: %s\n"
2201                     (or (message-fetch-field "From") (message-make-from))))))
2202
2203 (defun message-elide-region (b e)
2204   "Elide the text in the region.
2205 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2206 text was killed."
2207   (interactive "r")
2208   (kill-region b e)
2209   (insert message-elide-ellipsis))
2210
2211 (defvar message-caesar-translation-table nil)
2212
2213 (defun message-caesar-region (b e &optional n)
2214   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2215   (interactive
2216    (list
2217     (min (point) (or (mark t) (point)))
2218     (max (point) (or (mark t) (point)))
2219     (when current-prefix-arg
2220       (prefix-numeric-value current-prefix-arg))))
2221
2222   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2223   (unless (or (zerop n)                 ; no action needed for a rot of 0
2224               (= b e))                  ; no region to rotate
2225     ;; We build the table, if necessary.
2226     (when (or (not message-caesar-translation-table)
2227               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2228       (setq message-caesar-translation-table
2229             (message-make-caesar-translation-table n)))
2230     (translate-region b e message-caesar-translation-table)))
2231
2232 (defun message-make-caesar-translation-table (n)
2233   "Create a rot table with offset N."
2234   (let ((i -1)
2235         (table (make-string 256 0)))
2236     (while (< (incf i) 256)
2237       (aset table i i))
2238     (concat
2239      (substring table 0 ?A)
2240      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2241      (substring table ?A (+ ?A n))
2242      (substring table (+ ?A 26) ?a)
2243      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2244      (substring table ?a (+ ?a n))
2245      (substring table (+ ?a 26) 255))))
2246
2247 (defun message-caesar-buffer-body (&optional rotnum)
2248   "Caesar rotate all letters in the current buffer by 13 places.
2249 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2250 With prefix arg, specifies the number of places to rotate each letter forward.
2251 Mail and USENET news headers are not rotated."
2252   (interactive (if current-prefix-arg
2253                    (list (prefix-numeric-value current-prefix-arg))
2254                  (list nil)))
2255   (save-excursion
2256     (save-restriction
2257       (when (message-goto-body)
2258         (narrow-to-region (point) (point-max)))
2259       (message-caesar-region (point-min) (point-max) rotnum))))
2260
2261 (defun message-pipe-buffer-body (program)
2262   "Pipe the message body in the current buffer through PROGRAM."
2263   (save-excursion
2264     (save-restriction
2265       (when (message-goto-body)
2266         (narrow-to-region (point) (point-max)))
2267       (shell-command-on-region
2268        (point-min) (point-max) program nil t))))
2269
2270 (defun message-rename-buffer (&optional enter-string)
2271   "Rename the *message* buffer to \"*message* RECIPIENT\".
2272 If the function is run with a prefix, it will ask for a new buffer
2273 name, rather than giving an automatic name."
2274   (interactive "Pbuffer name: ")
2275   (save-excursion
2276     (save-restriction
2277       (goto-char (point-min))
2278       (narrow-to-region (point)
2279                         (search-forward mail-header-separator nil 'end))
2280       (let* ((mail-to (or
2281                        (if (message-news-p) (message-fetch-field "Newsgroups")
2282                          (message-fetch-field "To"))
2283                        ""))
2284              (mail-trimmed-to
2285               (if (string-match "," mail-to)
2286                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2287                 mail-to))
2288              (name-default (concat "*message* " mail-trimmed-to))
2289              (name (if enter-string
2290                        (read-string "New buffer name: " name-default)
2291                      name-default)))
2292         (rename-buffer name t)))))
2293
2294 (defun message-fill-yanked-message (&optional justifyp)
2295   "Fill the paragraphs of a message yanked into this one.
2296 Numeric argument means justify as well."
2297   (interactive "P")
2298   (save-excursion
2299     (goto-char (point-min))
2300     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2301     (let ((fill-prefix message-yank-prefix))
2302       (fill-individual-paragraphs (point) (point-max) justifyp))))
2303
2304 (defun message-indent-citation ()
2305   "Modify text just inserted from a message to be cited.
2306 The inserted text should be the region.
2307 When this function returns, the region is again around the modified text.
2308
2309 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2310 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2311   (let ((start (point)))
2312     ;; Remove unwanted headers.
2313     (when message-ignored-cited-headers
2314       (let (all-removed)
2315         (save-restriction
2316           (narrow-to-region
2317            (goto-char start)
2318            (if (search-forward "\n\n" nil t)
2319                (1- (point))
2320              (point)))
2321           (message-remove-header message-ignored-cited-headers t)
2322           (when (= (point-min) (point-max))
2323             (setq all-removed t))
2324           (goto-char (point-max)))
2325         (if all-removed
2326             (goto-char start)
2327           (forward-line 1))))
2328     ;; Delete blank lines at the start of the buffer.
2329     (while (and (point-min)
2330                 (eolp)
2331                 (not (eobp)))
2332       (message-delete-line))
2333     ;; Delete blank lines at the end of the buffer.
2334     (goto-char (point-max))
2335     (unless (eolp)
2336       (insert "\n"))
2337     (while (and (zerop (forward-line -1))
2338                 (looking-at "$"))
2339       (message-delete-line))
2340     ;; Do the indentation.
2341     (if (null message-yank-prefix)
2342         (indent-rigidly start (mark t) message-indentation-spaces)
2343       (save-excursion
2344         (goto-char start)
2345         (while (< (point) (mark t))
2346           (if (or (looking-at ">") (looking-at "^$"))
2347               (insert message-yank-cited-prefix)
2348             (insert message-yank-prefix))
2349           (forward-line 1))))
2350     (goto-char start)))
2351
2352 (defun message-yank-original (&optional arg)
2353   "Insert the message being replied to, if any.
2354 Puts point before the text and mark after.
2355 Normally indents each nonblank line ARG spaces (default 3).  However,
2356 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2357
2358 This function uses `message-cite-function' to do the actual citing.
2359
2360 Just \\[universal-argument] as argument means don't indent, insert no
2361 prefix, and don't delete any headers."
2362   (interactive "P")
2363   (let ((modified (buffer-modified-p)))
2364     (when (and message-reply-buffer
2365                message-cite-function)
2366       (delete-windows-on message-reply-buffer t)
2367       (insert-buffer message-reply-buffer)
2368       (unless arg
2369         (funcall message-cite-function))
2370       (message-exchange-point-and-mark)
2371       (unless (bolp)
2372         (insert ?\n))
2373       (unless modified
2374         (setq message-checksum (message-checksum))))))
2375
2376 (defun message-yank-buffer (buffer)
2377   "Insert BUFFER into the current buffer and quote it."
2378   (interactive "bYank buffer: ")
2379   (let ((message-reply-buffer buffer))
2380     (save-window-excursion
2381       (message-yank-original))))
2382
2383 (defun message-buffers ()
2384   "Return a list of active message buffers."
2385   (let (buffers)
2386     (save-excursion
2387       (dolist (buffer (buffer-list t))
2388         (set-buffer buffer)
2389         (when (and (eq major-mode 'message-mode)
2390                    (null message-sent-message-via))
2391           (push (buffer-name buffer) buffers))))
2392     (nreverse buffers)))
2393
2394 (defun message-cite-original-without-signature ()
2395   "Cite function in the standard Message manner."
2396   (let ((start (point))
2397         (end (mark t))
2398         (functions
2399          (when message-indent-citation-function
2400            (if (listp message-indent-citation-function)
2401                message-indent-citation-function
2402              (list message-indent-citation-function)))))
2403     (mml-quote-region start end)
2404     ;; Allow undoing.
2405     (undo-boundary)
2406     (goto-char end)
2407     (when (re-search-backward message-signature-separator start t)
2408       ;; Also peel off any blank lines before the signature.
2409       (forward-line -1)
2410       (while (looking-at "^[ \t]*$")
2411         (forward-line -1))
2412       (forward-line 1)
2413       (delete-region (point) end)
2414       (unless (search-backward "\n\n" start t)
2415         ;; Insert a blank line if it is peeled off.
2416         (insert "\n")))
2417     (goto-char start)
2418     (while functions
2419       (funcall (pop functions)))
2420     (when message-citation-line-function
2421       (unless (bolp)
2422         (insert "\n"))
2423       (funcall message-citation-line-function))))
2424
2425 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
2426 (defun message-cite-original ()
2427   "Cite function in the standard Message manner."
2428   (if (and (boundp 'mail-citation-hook)
2429            mail-citation-hook)
2430       (run-hooks 'mail-citation-hook)
2431     (let ((start (point))
2432           (end (mark t))
2433           (functions
2434            (when message-indent-citation-function
2435              (if (listp message-indent-citation-function)
2436                  message-indent-citation-function
2437                (list message-indent-citation-function)))))
2438       (mml-quote-region start end)
2439       (goto-char start)
2440       (while functions
2441         (funcall (pop functions)))
2442       (when message-citation-line-function
2443         (unless (bolp)
2444           (insert "\n"))
2445         (funcall message-citation-line-function)))))
2446
2447 (defun message-insert-citation-line ()
2448   "Insert a simple citation line."
2449   (when message-reply-headers
2450     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2451
2452 (defun message-position-on-field (header &rest afters)
2453   (let ((case-fold-search t))
2454     (save-restriction
2455       (narrow-to-region
2456        (goto-char (point-min))
2457        (progn
2458          (re-search-forward
2459           (concat "^" (regexp-quote mail-header-separator) "$"))
2460          (match-beginning 0)))
2461       (goto-char (point-min))
2462       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2463           (progn
2464             (re-search-forward "^[^ \t]" nil 'move)
2465             (beginning-of-line)
2466             (skip-chars-backward "\n")
2467             t)
2468         (while (and afters
2469                     (not (re-search-forward
2470                           (concat "^" (regexp-quote (car afters)) ":")
2471                           nil t)))
2472           (pop afters))
2473         (when afters
2474           (re-search-forward "^[^ \t]" nil 'move)
2475           (beginning-of-line))
2476         (insert header ": \n")
2477         (forward-char -1)
2478         nil))))
2479
2480 (defun message-remove-signature ()
2481   "Remove the signature from the text between point and mark.
2482 The text will also be indented the normal way."
2483   (save-excursion
2484     (let ((start (point))
2485           mark)
2486       (if (not (re-search-forward message-signature-separator (mark t) t))
2487           ;; No signature here, so we just indent the cited text.
2488           (message-indent-citation)
2489         ;; Find the last non-empty line.
2490         (forward-line -1)
2491         (while (looking-at "[ \t]*$")
2492           (forward-line -1))
2493         (forward-line 1)
2494         (setq mark (set-marker (make-marker) (point)))
2495         (goto-char start)
2496         (message-indent-citation)
2497         ;; Enable undoing the deletion.
2498         (undo-boundary)
2499         (delete-region mark (mark t))
2500         (set-marker mark nil)))))
2501
2502 \f
2503
2504 ;;;
2505 ;;; Sending messages
2506 ;;;
2507
2508 (defun message-send-and-exit (&optional arg)
2509   "Send message like `message-send', then, if no errors, exit from mail buffer."
2510   (interactive "P")
2511   (let ((buf (current-buffer))
2512         (actions message-exit-actions))
2513     (when (and (message-send arg)
2514                (buffer-name buf))
2515       (if message-kill-buffer-on-exit
2516           (kill-buffer buf)
2517         (bury-buffer buf)
2518         (when (eq buf (current-buffer))
2519           (message-bury buf)))
2520       (message-do-actions actions)
2521       t)))
2522
2523 (defun message-dont-send ()
2524   "Don't send the message you have been editing.
2525 Instead, just auto-save the buffer and then bury it."
2526   (interactive)
2527   (set-buffer-modified-p t)
2528   (save-buffer)
2529   (let ((actions message-postpone-actions))
2530     (message-bury (current-buffer))
2531     (message-do-actions actions)))
2532
2533 (defun message-kill-buffer ()
2534   "Kill the current buffer."
2535   (interactive)
2536   (when (or (not (buffer-modified-p))
2537             (yes-or-no-p "Message modified; kill anyway? "))
2538     (let ((actions message-kill-actions)
2539           (draft-article message-draft-article)
2540           (auto-save-file-name buffer-auto-save-file-name)
2541           (file-name buffer-file-name)
2542           (modified (buffer-modified-p)))
2543       (setq buffer-file-name nil)
2544       (kill-buffer (current-buffer))
2545       (when (and (or (and auto-save-file-name
2546                           (file-exists-p auto-save-file-name))
2547                      (and file-name
2548                           (file-exists-p file-name)))
2549                (yes-or-no-p (format "Remove the backup file%s? "
2550                                     (if modified " too" ""))))
2551         (ignore-errors
2552           (delete-file auto-save-file-name))
2553         (let ((message-draft-article draft-article))
2554           (message-disassociate-draft)))
2555       (message-do-actions actions))))
2556
2557 (defun message-bury (buffer)
2558   "Bury this mail BUFFER."
2559   (let ((newbuf (other-buffer buffer)))
2560     (bury-buffer buffer)
2561     (if (and (fboundp 'frame-parameters)
2562              (cdr (assq 'dedicated (frame-parameters)))
2563              (not (null (delq (selected-frame) (visible-frame-list)))))
2564         (delete-frame (selected-frame))
2565       (switch-to-buffer newbuf))))
2566
2567 (defun message-send (&optional arg)
2568   "Send the message in the current buffer.
2569 If `message-interactive' is non-nil, wait for success indication or
2570 error messages, and inform user.
2571 Otherwise any failure is reported in a message back to the user from
2572 the mailer.
2573 The usage of ARG is defined by the instance that called Message.
2574 It should typically alter the sending method in some way or other."
2575   (interactive "P")
2576   ;; Make it possible to undo the coming changes.
2577   (undo-boundary)
2578   (let ((inhibit-read-only t))
2579     (put-text-property (point-min) (point-max) 'read-only nil))
2580   (message-fix-before-sending)
2581   (run-hooks 'message-send-hook)
2582   (message message-sending-message)
2583   (let ((alist message-send-method-alist)
2584         (success t)
2585         elem sent dont-barf-on-no-method
2586         (message-options message-options))
2587     (message-options-set-recipient)
2588     (while (and success
2589                 (setq elem (pop alist)))
2590       (when (funcall (cadr elem))
2591         (when (and (or (not (memq (car elem)
2592                                   message-sent-message-via))
2593                        (if (or (message-gnksa-enable-p 'multiple-copies)
2594                                (not (eq (car elem) 'news)))
2595                            (y-or-n-p
2596                             (format
2597                              "Already sent message via %s; resend? "
2598                              (car elem)))
2599                          (error "Denied posting -- multiple copies")))
2600                    (setq success (funcall (caddr elem) arg)))
2601           (setq sent t))))
2602     (unless (or sent
2603                 (not success)
2604                 (let ((fcc (message-fetch-field "Fcc"))
2605                       (gcc (message-fetch-field "Gcc")))
2606                   (when (or fcc gcc)
2607                     (or (eq message-allow-no-recipients 'always)
2608                         (and (not (eq message-allow-no-recipients 'never))
2609                              (setq dont-barf-on-no-method
2610                                    (gnus-y-or-n-p
2611                                     (format "No receiver, perform %s anyway? "
2612                                             (cond ((and fcc gcc) "Fcc and Gcc")
2613                                                   (fcc "Fcc")
2614                                                   (t "Gcc"))))))))))
2615       (error "No methods specified to send by"))
2616     (when (or dont-barf-on-no-method
2617               (and success sent))
2618       (message-do-fcc)
2619       (save-excursion
2620         (run-hooks 'message-sent-hook))
2621       (message "Sending...done")
2622       ;; Mark the buffer as unmodified and delete auto-save.
2623       (set-buffer-modified-p nil)
2624       (delete-auto-save-file-if-necessary t)
2625       (message-disassociate-draft)
2626       ;; Delete other mail buffers and stuff.
2627       (message-do-send-housekeeping)
2628       (message-do-actions message-send-actions)
2629       ;; Return success.
2630       t)))
2631
2632 (defun message-send-via-mail (arg)
2633   "Send the current message via mail."
2634   (message-send-mail arg))
2635
2636 (defun message-send-via-news (arg)
2637   "Send the current message via news."
2638   (funcall message-send-news-function arg))
2639
2640 (defmacro message-check (type &rest forms)
2641   "Eval FORMS if TYPE is to be checked."
2642   `(or (message-check-element ,type)
2643        (save-excursion
2644          ,@forms)))
2645
2646 (put 'message-check 'lisp-indent-function 1)
2647 (put 'message-check 'edebug-form-spec '(form body))
2648
2649 (defun message-text-with-property (prop)
2650   "Return a list of all points where the text has PROP."
2651   (let ((points nil)
2652         (point (point-min)))
2653     (save-excursion
2654       (while (< point (point-max))
2655         (when (get-text-property point prop)
2656           (push point points))
2657         (incf point)))
2658     (nreverse points)))
2659
2660 (defun message-fix-before-sending ()
2661   "Do various things to make the message nice before sending it."
2662   ;; Make sure there's a newline at the end of the message.
2663   (goto-char (point-max))
2664   (unless (bolp)
2665     (insert "\n"))
2666   ;; Delete all invisible text.
2667   (message-check 'invisible-text
2668     (let ((points (message-text-with-property 'invisible)))
2669       (when points
2670         (goto-char (car points))
2671         (dolist (point points)
2672           (add-text-properties point (1+ point)
2673                                '(invisible nil highlight t)))
2674         (unless (yes-or-no-p
2675                  "Invisible text found and made visible; continue posting? ")
2676           (error "Invisible text found and made visible"))))))
2677
2678 (defun message-add-action (action &rest types)
2679   "Add ACTION to be performed when doing an exit of type TYPES."
2680   (let (var)
2681     (while types
2682       (set (setq var (intern (format "message-%s-actions" (pop types))))
2683            (nconc (symbol-value var) (list action))))))
2684
2685 (defun message-do-actions (actions)
2686   "Perform all actions in ACTIONS."
2687   ;; Now perform actions on successful sending.
2688   (while actions
2689     (ignore-errors
2690       (cond
2691        ;; A simple function.
2692        ((message-functionp (car actions))
2693         (funcall (car actions)))
2694        ;; Something to be evaled.
2695        (t
2696         (eval (car actions)))))
2697     (pop actions)))
2698
2699 (defun message-send-mail-partially ()
2700   "Send mail as message/partial."
2701   ;; replace the header delimiter with a blank line
2702   (goto-char (point-min))
2703   (re-search-forward
2704    (concat "^" (regexp-quote mail-header-separator) "\n"))
2705   (replace-match "\n")
2706   (run-hooks 'message-send-mail-hook)
2707   (let ((p (goto-char (point-min)))
2708         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2709         (curbuf (current-buffer))
2710         (id (message-make-message-id)) (n 1)
2711         plist total  header required-mail-headers)
2712     (while (not (eobp))
2713       (if (< (point-max) (+ p message-send-mail-partially-limit))
2714           (goto-char (point-max))
2715         (goto-char (+ p message-send-mail-partially-limit))
2716         (beginning-of-line)
2717         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2718       (push p plist)
2719       (setq p (point)))
2720     (setq total (length plist))
2721     (push (point-max) plist)
2722     (setq plist (nreverse plist))
2723     (unwind-protect
2724         (save-excursion
2725           (setq p (pop plist))
2726           (while plist
2727             (set-buffer curbuf)
2728             (copy-to-buffer tembuf p (car plist))
2729             (set-buffer tembuf)
2730             (goto-char (point-min))
2731             (if header
2732                 (progn
2733                   (goto-char (point-min))
2734                   (narrow-to-region (point) (point))
2735                   (insert header))
2736               (message-goto-eoh)
2737               (setq header (buffer-substring (point-min) (point)))
2738               (goto-char (point-min))
2739               (narrow-to-region (point) (point))
2740               (insert header)
2741               (message-remove-header "Mime-Version")
2742               (message-remove-header "Content-Type")
2743               (message-remove-header "Content-Transfer-Encoding")
2744               (message-remove-header "Message-ID")
2745               (message-remove-header "Lines")
2746               (goto-char (point-max))
2747               (insert "Mime-Version: 1.0\n")
2748               (setq header (buffer-substring (point-min) (point-max))))
2749             (goto-char (point-max))
2750             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
2751                             id n total))
2752             (forward-char -1)
2753             (let ((mail-header-separator ""))
2754               (when (memq 'Message-ID message-required-mail-headers)
2755                 (insert "Message-ID: " (message-make-message-id) "\n"))
2756               (when (memq 'Lines message-required-mail-headers)
2757                 (insert "Lines: " (message-make-lines) "\n"))
2758               (message-goto-subject)
2759               (end-of-line)
2760               (insert (format " (%d/%d)" n total))
2761               (widen)
2762               (mm-with-unibyte-current-buffer
2763                 (funcall (or message-send-mail-real-function
2764                              message-send-mail-function))))
2765             (setq n (+ n 1))
2766             (setq p (pop plist))
2767             (erase-buffer)))
2768       (kill-buffer tembuf))))
2769
2770 (defun message-send-mail (&optional arg)
2771   (require 'mail-utils)
2772   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2773          (case-fold-search nil)
2774          (news (message-news-p))
2775          (mailbuf (current-buffer))
2776          (message-this-is-mail t)
2777          (message-posting-charset
2778           (if (fboundp 'gnus-setup-posting-charset)
2779               (gnus-setup-posting-charset nil)
2780             message-posting-charset))
2781          (headers message-required-mail-headers))
2782     (save-restriction
2783       (message-narrow-to-headers)
2784       ;; Generate the Mail-Followup-To header if the header is not there...
2785       (if (and (or message-subscribed-regexps
2786                    message-subscribed-addresses
2787                    message-subscribed-address-file
2788                    message-subscribed-address-functions)
2789                (not (mail-fetch-field "mail-followup-to")))
2790           (setq headers
2791                 (cons
2792                  (cons "Mail-Followup-To" (message-make-mft))
2793                  message-required-mail-headers))
2794         ;; otherwise, delete the MFT header if the field is empty
2795         (when (equal "" (mail-fetch-field "mail-followup-to"))
2796           (message-remove-header "^Mail-Followup-To:")))
2797       ;; Insert some headers.
2798       (let ((message-deletable-headers
2799              (if news nil message-deletable-headers)))
2800         (message-generate-headers headers))
2801       ;; Let the user do all of the above.
2802       (run-hooks 'message-header-hook))
2803     (unwind-protect
2804         (save-excursion
2805           (set-buffer tembuf)
2806           (erase-buffer)
2807           ;; Avoid copying text props (except hard newlines).
2808           (insert (with-current-buffer mailbuf
2809                     (mml-buffer-substring-no-properties-except-hard-newlines
2810                      (point-min) (point-max))))
2811           ;; Remove some headers.
2812           (message-encode-message-body)
2813           (save-restriction
2814             (message-narrow-to-headers)
2815             ;; We (re)generate the Lines header.
2816             (when (memq 'Lines message-required-mail-headers)
2817               (message-generate-headers '(Lines)))
2818             ;; Remove some headers.
2819             (message-remove-header message-ignored-mail-headers t)
2820             (let ((mail-parse-charset message-default-charset))
2821               (mail-encode-encoded-word-buffer)))
2822           (goto-char (point-max))
2823           ;; require one newline at the end.
2824           (or (= (preceding-char) ?\n)
2825               (insert ?\n))
2826           (when
2827               (save-restriction
2828                 (message-narrow-to-headers)
2829                 (and news
2830                      (or (message-fetch-field "cc")
2831                          (message-fetch-field "to"))
2832                      (let ((content-type (message-fetch-field "content-type")))
2833                        (or
2834                         (not content-type)
2835                         (string= "text/plain"
2836                                  (car
2837                                   (mail-header-parse-content-type
2838                                    content-type)))))))
2839             (message-insert-courtesy-copy))
2840           (if (or (not message-send-mail-partially-limit)
2841                   (< (point-max) message-send-mail-partially-limit)
2842                   (not (y-or-n-p "Message exceeds message-send-mail-partially-limit, send in parts? ")))
2843               (mm-with-unibyte-current-buffer
2844                 (message "Sending via mail...")
2845                 (funcall (or message-send-mail-real-function
2846                              message-send-mail-function)))
2847             (message-send-mail-partially)))
2848       (kill-buffer tembuf))
2849     (set-buffer mailbuf)
2850     (push 'mail message-sent-message-via)))
2851
2852 (defun message-send-mail-with-sendmail ()
2853   "Send off the prepared buffer with sendmail."
2854   (let ((errbuf (if message-interactive
2855                     (message-generate-new-buffer-clone-locals
2856                      " sendmail errors")
2857                   0))
2858         resend-to-addresses delimline)
2859     (let ((case-fold-search t))
2860       (save-restriction
2861         (message-narrow-to-headers)
2862         (setq resend-to-addresses (message-fetch-field "resent-to")))
2863       ;; Change header-delimiter to be what sendmail expects.
2864       (goto-char (point-min))
2865       (re-search-forward
2866        (concat "^" (regexp-quote mail-header-separator) "\n"))
2867       (replace-match "\n")
2868       (backward-char 1)
2869       (setq delimline (point-marker))
2870       (run-hooks 'message-send-mail-hook)
2871       ;; Insert an extra newline if we need it to work around
2872       ;; Sun's bug that swallows newlines.
2873       (goto-char (1+ delimline))
2874       (when (eval message-mailer-swallows-blank-line)
2875         (newline))
2876       (when message-interactive
2877         (save-excursion
2878           (set-buffer errbuf)
2879           (erase-buffer))))
2880     (let ((default-directory "/")
2881           (coding-system-for-write message-send-coding-system))
2882       (apply 'call-process-region
2883              (append (list (point-min) (point-max)
2884                            (if (boundp 'sendmail-program)
2885                                sendmail-program
2886                              "/usr/lib/sendmail")
2887                            nil errbuf nil "-oi")
2888                      ;; Always specify who from,
2889                      ;; since some systems have broken sendmails.
2890                      ;; But some systems are more broken with -f, so
2891                      ;; we'll let users override this.
2892                      (if (null message-sendmail-f-is-evil)
2893                          (list "-f" (message-make-address)))
2894                      ;; These mean "report errors by mail"
2895                      ;; and "deliver in background".
2896                      (if (null message-interactive) '("-oem" "-odb"))
2897                      ;; Get the addresses from the message
2898                      ;; unless this is a resend.
2899                      ;; We must not do that for a resend
2900                      ;; because we would find the original addresses.
2901                      ;; For a resend, include the specific addresses.
2902                      (if resend-to-addresses
2903                          (list resend-to-addresses)
2904                        '("-t")))))
2905     (when message-interactive
2906       (save-excursion
2907         (set-buffer errbuf)
2908         (goto-char (point-min))
2909         (while (re-search-forward "\n\n* *" nil t)
2910           (replace-match "; "))
2911         (if (not (zerop (buffer-size)))
2912             (error "Sending...failed to %s"
2913                    (buffer-substring (point-min) (point-max)))))
2914       (when (bufferp errbuf)
2915         (kill-buffer errbuf)))))
2916
2917 (defun message-send-mail-with-qmail ()
2918   "Pass the prepared message buffer to qmail-inject.
2919 Refer to the documentation for the variable `message-send-mail-function'
2920 to find out how to use this."
2921   ;; replace the header delimiter with a blank line
2922   (goto-char (point-min))
2923   (re-search-forward
2924    (concat "^" (regexp-quote mail-header-separator) "\n"))
2925   (replace-match "\n")
2926   (run-hooks 'message-send-mail-hook)
2927   ;; send the message
2928   (case
2929       (let ((coding-system-for-write message-send-coding-system))
2930         (apply
2931          'call-process-region 1 (point-max) message-qmail-inject-program
2932          nil nil nil
2933          ;; qmail-inject's default behaviour is to look for addresses on the
2934          ;; command line; if there're none, it scans the headers.
2935          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2936          ;;
2937          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2938          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2939          ;; message from stdin.
2940          ;;
2941          ;; qmail also has the advantage of not having been raped by
2942          ;; various vendors, so we don't have to allow for that, either --
2943          ;; compare this with message-send-mail-with-sendmail and weep
2944          ;; for sendmail's lost innocence.
2945          ;;
2946          ;; all this is way cool coz it lets us keep the arguments entirely
2947          ;; free for -inject-arguments -- a big win for the user and for us
2948          ;; since we don't have to play that double-guessing game and the user
2949          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2950          message-qmail-inject-args))
2951     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2952     ;; we have to look at the retval instead
2953     (0 nil)
2954     (100 (error "qmail-inject reported permanent failure"))
2955     (111 (error "qmail-inject reported transient failure"))
2956     ;; should never happen
2957     (t   (error "qmail-inject reported unknown failure"))))
2958
2959 (defun message-send-mail-with-mh ()
2960   "Send the prepared message buffer with mh."
2961   (let ((mh-previous-window-config nil)
2962         (name (mh-new-draft-name)))
2963     (setq buffer-file-name name)
2964     ;; MH wants to generate these headers itself.
2965     (when message-mh-deletable-headers
2966       (let ((headers message-mh-deletable-headers))
2967         (while headers
2968           (goto-char (point-min))
2969           (and (re-search-forward
2970                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2971                (message-delete-line))
2972           (pop headers))))
2973     (run-hooks 'message-send-mail-hook)
2974     ;; Pass it on to mh.
2975     (mh-send-letter)))
2976
2977 (defun message-canlock-generate ()
2978   "Return a string that is non-trival to guess.
2979 Do not use this for anything important, it is cryptographically weak."
2980   (sha1 (concat (message-unique-id)
2981                 (format "%x%x%x" (random) (random t) (random))
2982                 (prin1-to-string (recent-keys))
2983                 (prin1-to-string (garbage-collect)))))
2984
2985 (defun message-canlock-password ()
2986   "The password used by message for cancel locks.
2987 This is the value of `canlock-password', if that option is non-nil.
2988 Otherwise, generate and save a value for `canlock-password' first."
2989   (unless canlock-password
2990     (customize-save-variable 'canlock-password (message-canlock-generate)))
2991   canlock-password)
2992
2993 (defun message-insert-canlock ()
2994   (when message-insert-canlock
2995     (message-canlock-password)
2996     (canlock-insert-header)))
2997
2998 (defun message-send-news (&optional arg)
2999   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3000          (case-fold-search nil)
3001          (method (if (message-functionp message-post-method)
3002                      (funcall message-post-method arg)
3003                    message-post-method))
3004          (newsgroups-field (save-restriction
3005                             (message-narrow-to-headers-or-head)
3006                             (message-fetch-field "Newsgroups")))
3007          (followup-field (save-restriction
3008                            (message-narrow-to-headers-or-head)
3009                            (message-fetch-field "Followup-To")))
3010          ;; BUG: We really need to get the charset for each name in the
3011          ;; Newsgroups and Followup-To lines to allow crossposting
3012          ;; between group namess with incompatible character sets.
3013          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3014          (group-field-charset
3015           (gnus-group-name-charset method newsgroups-field))
3016          (followup-field-charset 
3017           (gnus-group-name-charset method (or followup-field "")))
3018          (rfc2047-header-encoding-alist
3019           (append (when group-field-charset
3020                     (list (cons "Newsgroups" group-field-charset)))
3021                   (when followup-field-charset
3022                     (list (cons "Followup-To" followup-field-charset)))
3023                   rfc2047-header-encoding-alist))
3024          (messbuf (current-buffer))
3025          (message-syntax-checks
3026           (if (and arg
3027                    (listp message-syntax-checks))
3028               (cons '(existing-newsgroups . disabled)
3029                     message-syntax-checks)
3030             message-syntax-checks))
3031          (message-this-is-news t)
3032          (message-posting-charset
3033           (gnus-setup-posting-charset newsgroups-field))
3034          result)
3035     (if (not (message-check-news-body-syntax))
3036         nil
3037       (save-restriction
3038         (message-narrow-to-headers)
3039         ;; Insert some headers.
3040         (message-generate-headers message-required-news-headers)
3041         (message-insert-canlock)
3042         ;; Let the user do all of the above.
3043         (run-hooks 'message-header-hook))
3044       ;; Note: This check will be disabled by the ".*" default value for
3045       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3046       (when (and group-field-charset
3047                  (listp message-syntax-checks))
3048         (setq message-syntax-checks
3049               (cons '(valid-newsgroups . disabled)
3050                     message-syntax-checks)))
3051       (message-cleanup-headers)
3052       (if (not (let ((message-post-method method))
3053                  (message-check-news-syntax)))
3054           nil
3055         (unwind-protect
3056             (save-excursion
3057               (set-buffer tembuf)
3058               (buffer-disable-undo)
3059               (erase-buffer)
3060               ;; Avoid copying text props (except hard newlines).
3061               (insert
3062                (with-current-buffer messbuf
3063                  (mml-buffer-substring-no-properties-except-hard-newlines
3064                   (point-min) (point-max))))
3065               (message-encode-message-body)
3066               ;; Remove some headers.
3067               (save-restriction
3068                 (message-narrow-to-headers)
3069                 ;; We (re)generate the Lines header.
3070                 (when (memq 'Lines message-required-mail-headers)
3071                   (message-generate-headers '(Lines)))
3072                 ;; Remove some headers.
3073                 (message-remove-header message-ignored-news-headers t)
3074                 (let ((mail-parse-charset message-default-charset))
3075                   (mail-encode-encoded-word-buffer)))
3076               (goto-char (point-max))
3077               ;; require one newline at the end.
3078               (or (= (preceding-char) ?\n)
3079                   (insert ?\n))
3080               (let ((case-fold-search t))
3081                 ;; Remove the delimiter.
3082                 (goto-char (point-min))
3083                 (re-search-forward
3084                  (concat "^" (regexp-quote mail-header-separator) "\n"))
3085                 (replace-match "\n")
3086                 (backward-char 1))
3087               (run-hooks 'message-send-news-hook)
3088               (gnus-open-server method)
3089               (message "Sending news with %s..." (gnus-server-string method))
3090               (setq result (let ((mail-header-separator ""))
3091                              (gnus-request-post method))))
3092           (kill-buffer tembuf))
3093         (set-buffer messbuf)
3094         (if result
3095             (push 'news message-sent-message-via)
3096           (message "Couldn't send message via news: %s"
3097                    (nnheader-get-report (car method)))
3098           nil)))))
3099
3100 ;;;
3101 ;;; Header generation & syntax checking.
3102 ;;;
3103
3104 (defun message-check-element (type)
3105   "Return non-nil if this TYPE is not to be checked."
3106   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3107       t
3108     (let ((able (assq type message-syntax-checks)))
3109       (and (consp able)
3110            (eq (cdr able) 'disabled)))))
3111
3112 (defun message-check-news-syntax ()
3113   "Check the syntax of the message."
3114   (save-excursion
3115     (save-restriction
3116       (widen)
3117       ;; We narrow to the headers and check them first.
3118       (save-excursion
3119         (save-restriction
3120           (message-narrow-to-headers)
3121           (message-check-news-header-syntax))))))
3122
3123 (defun message-check-news-header-syntax ()
3124   (and
3125    ;; Check Newsgroups header.
3126    (message-check 'newsgroups
3127      (let ((group (message-fetch-field "newsgroups")))
3128        (or
3129         (and group
3130              (not (string-match "\\`[ \t]*\\'" group)))
3131         (ignore
3132          (message
3133           "The newsgroups field is empty or missing.  Posting is denied.")))))
3134    ;; Check the Subject header.
3135    (message-check 'subject
3136      (let* ((case-fold-search t)
3137             (subject (message-fetch-field "subject")))
3138        (or
3139         (and subject
3140              (not (string-match "\\`[ \t]*\\'" subject)))
3141         (ignore
3142          (message
3143           "The subject field is empty or missing.  Posting is denied.")))))
3144    ;; Check for commands in Subject.
3145    (message-check 'subject-cmsg
3146      (if (string-match "^cmsg " (message-fetch-field "subject"))
3147          (y-or-n-p
3148           "The control code \"cmsg\" is in the subject.  Really post? ")
3149        t))
3150    ;; Check for multiple identical headers.
3151    (message-check 'multiple-headers
3152      (let (found)
3153        (while (and (not found)
3154                    (re-search-forward "^[^ \t:]+: " nil t))
3155          (save-excursion
3156            (or (re-search-forward
3157                 (concat "^"
3158                         (regexp-quote
3159                          (setq found
3160                                (buffer-substring
3161                                 (match-beginning 0) (- (match-end 0) 2))))
3162                         ":")
3163                 nil t)
3164                (setq found nil))))
3165        (if found
3166            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3167          t)))
3168    ;; Check for Version and Sendsys.
3169    (message-check 'sendsys
3170      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3171          (y-or-n-p
3172           (format "The article contains a %s command.  Really post? "
3173                   (buffer-substring (match-beginning 0)
3174                                     (1- (match-end 0)))))
3175        t))
3176    ;; See whether we can shorten Followup-To.
3177    (message-check 'shorten-followup-to
3178      (let ((newsgroups (message-fetch-field "newsgroups"))
3179            (followup-to (message-fetch-field "followup-to"))
3180            to)
3181        (when (and newsgroups
3182                   (string-match "," newsgroups)
3183                   (not followup-to)
3184                   (not
3185                    (zerop
3186                     (length
3187                      (setq to (completing-read
3188                                "Followups to (default: no Followup-To header) "
3189                                (mapcar (lambda (g) (list g))
3190                                        (cons "poster"
3191                                              (message-tokenize-header
3192                                               newsgroups)))))))))
3193          (goto-char (point-min))
3194          (insert "Followup-To: " to "\n"))
3195        t))
3196    ;; Check "Shoot me".
3197    (message-check 'shoot
3198      (if (re-search-forward
3199           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3200          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3201        t))
3202    ;; Check for Approved.
3203    (message-check 'approved
3204      (if (re-search-forward "^Approved:" nil t)
3205          (y-or-n-p "The article contains an Approved header.  Really post? ")
3206        t))
3207    ;; Check the Message-ID header.
3208    (message-check 'message-id
3209      (let* ((case-fold-search t)
3210             (message-id (message-fetch-field "message-id" t)))
3211        (or (not message-id)
3212            ;; Is there an @ in the ID?
3213            (and (string-match "@" message-id)
3214                 ;; Is there a dot in the ID?
3215                 (string-match "@[^.]*\\." message-id)
3216                 ;; Does the ID end with a dot?
3217                 (not (string-match "\\.>" message-id)))
3218            (y-or-n-p
3219             (format "The Message-ID looks strange: \"%s\".  Really post? "
3220                     message-id)))))
3221    ;; Check the Newsgroups & Followup-To headers.
3222    (message-check 'existing-newsgroups
3223      (let* ((case-fold-search t)
3224             (newsgroups (message-fetch-field "newsgroups"))
3225             (followup-to (message-fetch-field "followup-to"))
3226             (groups (message-tokenize-header
3227                      (if followup-to
3228                          (concat newsgroups "," followup-to)
3229                        newsgroups)))
3230             (post-method (if (message-functionp message-post-method)
3231                              (funcall message-post-method)
3232                            message-post-method))
3233             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3234             ;; would probably involve a new nnoo function.
3235             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3236             (method (if (and (consp post-method) 
3237                              (eq (car post-method) 'nnvirtual)
3238                              gnus-message-group-art)
3239                         (let ((group (car (nnvirtual-find-group-art
3240                                            (car gnus-message-group-art)
3241                                            (cdr gnus-message-group-art)))))
3242                           (gnus-find-method-for-group group))
3243                       post-method))
3244             (known-groups
3245              (mapcar (lambda (n)
3246                        (gnus-group-name-decode 
3247                         (gnus-group-real-name n)
3248                         (gnus-group-name-charset method n)))
3249                      (gnus-groups-from-server method)))
3250             errors)
3251        (while groups
3252          (unless (or (equal (car groups) "poster")
3253                      (member (car groups) known-groups))
3254            (push (car groups) errors))
3255          (pop groups))
3256        (cond
3257         ;; Gnus is not running.
3258         ((or (not (and (boundp 'gnus-active-hashtb)
3259                        gnus-active-hashtb))
3260              (not (boundp 'gnus-read-active-file)))
3261          t)
3262         ;; We don't have all the group names.
3263         ((and (or (not gnus-read-active-file)
3264                   (eq gnus-read-active-file 'some))
3265               errors)
3266          (y-or-n-p
3267           (format
3268            "Really post to %s possibly unknown group%s: %s? "
3269            (if (= (length errors) 1) "this" "these")
3270            (if (= (length errors) 1) "" "s")
3271            (mapconcat 'identity errors ", "))))
3272         ;; There were no errors.
3273         ((not errors)
3274          t)
3275         ;; There are unknown groups.
3276         (t
3277          (y-or-n-p
3278           (format
3279            "Really post to %s unknown group%s: %s? "
3280            (if (= (length errors) 1) "this" "these")
3281            (if (= (length errors) 1) "" "s")
3282            (mapconcat 'identity errors ", ")))))))
3283    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3284    (message-check 'valid-newsgroups
3285      (let ((case-fold-search t)
3286            (headers '("Newsgroups" "Followup-To"))
3287            header error)
3288        (while (and headers (not error))
3289          (when (setq header (mail-fetch-field (car headers)))
3290            (if (or
3291                 (not
3292                  (string-match
3293                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3294                   header))
3295                 (memq
3296                  nil (mapcar
3297                       (lambda (g)
3298                         (not (string-match "\\.\\'\\|\\.\\." g)))
3299                       (message-tokenize-header header ","))))
3300                (setq error t)))
3301          (unless error
3302            (pop headers)))
3303        (if (not error)
3304            t
3305          (y-or-n-p
3306           (format "The %s header looks odd: \"%s\".  Really post? "
3307                   (car headers) header)))))
3308    (message-check 'repeated-newsgroups
3309      (let ((case-fold-search t)
3310            (headers '("Newsgroups" "Followup-To"))
3311            header error groups group)
3312        (while (and headers
3313                    (not error))
3314          (when (setq header (mail-fetch-field (pop headers)))
3315            (setq groups (message-tokenize-header header ","))
3316            (while (setq group (pop groups))
3317              (when (member group groups)
3318                (setq error group
3319                      groups nil)))))
3320        (if (not error)
3321            t
3322          (y-or-n-p
3323           (format "Group %s is repeated in headers.  Really post? " error)))))
3324    ;; Check the From header.
3325    (message-check 'from
3326      (let* ((case-fold-search t)
3327             (from (message-fetch-field "from"))
3328             ad)
3329        (cond
3330         ((not from)
3331          (message "There is no From line.  Posting is denied.")
3332          nil)
3333         ((or (not (string-match
3334                    "@[^\\.]*\\."
3335                    (setq ad (nth 1 (mail-extract-address-components
3336                                     from))))) ;larsi@ifi
3337              (string-match "\\.\\." ad) ;larsi@ifi..uio
3338              (string-match "@\\." ad)   ;larsi@.ifi.uio
3339              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3340              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3341              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3342          (message
3343           "Denied posting -- the From looks strange: \"%s\"." from)
3344          nil)
3345         ((let ((addresses (rfc822-addresses from)))
3346            (while (and addresses
3347                        (not (eq (string-to-char (car addresses)) ?\()))
3348              (setq addresses (cdr addresses)))
3349            addresses)
3350          (message
3351           "Denied posting -- bad From address: \"%s\"." from)
3352          nil)
3353         (t t))))
3354    ;; Check the Reply-To header.
3355    (message-check 'reply-to
3356      (let* ((case-fold-search t)
3357             (reply-to (message-fetch-field "reply-to"))
3358             ad)
3359        (cond
3360         ((not reply-to)
3361          t)
3362         ((string-match "," reply-to)
3363          (y-or-n-p
3364           (format "Multiple Reply-To addresses: \"%s\". Really post? "
3365                   reply-to)))
3366         ((or (not (string-match
3367                    "@[^\\.]*\\."
3368                    (setq ad (nth 1 (mail-extract-address-components
3369                                     reply-to))))) ;larsi@ifi
3370              (string-match "\\.\\." ad) ;larsi@ifi..uio
3371              (string-match "@\\." ad)   ;larsi@.ifi.uio
3372              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3373              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3374              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
3375          (y-or-n-p
3376           (format
3377            "The Reply-To looks strange: \"%s\". Really post? "
3378            reply-to)))
3379         (t t))))))
3380
3381 (defun message-check-news-body-syntax ()
3382   (and
3383    ;; Check for long lines.
3384    (message-check 'long-lines
3385      (goto-char (point-min))
3386      (re-search-forward
3387       (concat "^" (regexp-quote mail-header-separator) "$"))
3388      (forward-line 1)
3389      (while (and
3390              (or (looking-at
3391                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
3392                  (let ((p (point)))
3393                    (end-of-line)
3394                    (< (- (point) p) 80)))
3395              (zerop (forward-line 1))))
3396      (or (bolp)
3397          (eobp)
3398          (y-or-n-p
3399           "You have lines longer than 79 characters.  Really post? ")))
3400    ;; Check whether the article is empty.
3401    (message-check 'empty
3402      (goto-char (point-min))
3403      (re-search-forward
3404       (concat "^" (regexp-quote mail-header-separator) "$"))
3405      (forward-line 1)
3406      (let ((b (point)))
3407        (goto-char (point-max))
3408        (re-search-backward message-signature-separator nil t)
3409        (beginning-of-line)
3410        (or (re-search-backward "[^ \n\t]" b t)
3411            (if (message-gnksa-enable-p 'empty-article)
3412                (y-or-n-p "Empty article.  Really post? ")
3413              (message "Denied posting -- Empty article.")
3414              nil))))
3415    ;; Check for control characters.
3416    (message-check 'control-chars
3417      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3418          (y-or-n-p
3419           "The article contains control characters.  Really post? ")
3420        t))
3421    ;; Check excessive size.
3422    (message-check 'size
3423      (if (> (buffer-size) 60000)
3424          (y-or-n-p
3425           (format "The article is %d octets long.  Really post? "
3426                   (buffer-size)))
3427        t))
3428    ;; Check whether any new text has been added.
3429    (message-check 'new-text
3430      (or
3431       (not message-checksum)
3432       (not (eq (message-checksum) message-checksum))
3433       (if (message-gnksa-enable-p 'quoted-text-only)
3434           (y-or-n-p
3435            "It looks like no new text has been added.  Really post? ")
3436         (message "Denied posting -- no new text has been added.")
3437         nil)))
3438    ;; Check the length of the signature.
3439    (message-check 'signature
3440      (goto-char (point-max))
3441      (if (> (count-lines (point) (point-max)) 5)
3442          (y-or-n-p
3443           (format
3444            "Your .sig is %d lines; it should be max 4.  Really post? "
3445            (1- (count-lines (point) (point-max)))))
3446        t))
3447    ;; Ensure that text follows last quoted portion.
3448    (message-check 'quoting-style
3449      (goto-char (point-max))
3450      (let ((no-problem t))
3451        (when (search-backward-regexp "^>[^\n]*\n" nil t)
3452          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
3453        (if no-problem
3454            t
3455          (if (message-gnksa-enable-p 'quoted-text-only)
3456              (y-or-n-p "Your text should follow quoted text.  Really post? ")
3457            ;; Ensure that
3458            (goto-char (point-min))
3459            (re-search-forward
3460             (concat "^" (regexp-quote mail-header-separator) "$"))
3461            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
3462                (y-or-n-p "Your text should follow quoted text.  Really post? ")
3463              (message "Denied posting -- only quoted text.")
3464              nil)))))))
3465
3466 (defun message-checksum ()
3467   "Return a \"checksum\" for the current buffer."
3468   (let ((sum 0))
3469     (save-excursion
3470       (goto-char (point-min))
3471       (re-search-forward
3472        (concat "^" (regexp-quote mail-header-separator) "$"))
3473       (while (not (eobp))
3474         (when (not (looking-at "[ \t\n]"))
3475           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3476                             (char-after))))
3477         (forward-char 1)))
3478     sum))
3479
3480 (defun message-do-fcc ()
3481   "Process Fcc headers in the current buffer."
3482   (let ((case-fold-search t)
3483         (buf (current-buffer))
3484         list file
3485         (mml-externalize-attachments message-fcc-externalize-attachments))
3486     (save-excursion
3487       (save-restriction
3488         (message-narrow-to-headers)
3489         (setq file (message-fetch-field "fcc" t)))
3490       (when file
3491         (set-buffer (get-buffer-create " *message temp*"))
3492         (erase-buffer)
3493         (insert-buffer-substring buf)
3494         (message-encode-message-body)
3495         (save-restriction
3496           (message-narrow-to-headers)
3497           (while (setq file (message-fetch-field "fcc" t))
3498             (push file list)
3499             (message-remove-header "fcc" nil t))
3500           (let ((mail-parse-charset message-default-charset)
3501                 (rfc2047-header-encoding-alist
3502                  (cons '("Newsgroups" . default)
3503                        rfc2047-header-encoding-alist)))
3504             (mail-encode-encoded-word-buffer)))
3505         (goto-char (point-min))
3506         (when (re-search-forward
3507                (concat "^" (regexp-quote mail-header-separator) "$")
3508                nil t)
3509           (replace-match "" t t ))
3510         ;; Process FCC operations.
3511         (while list
3512           (setq file (pop list))
3513           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3514               ;; Pipe the article to the program in question.
3515               (call-process-region (point-min) (point-max) shell-file-name
3516                                    nil nil nil shell-command-switch
3517                                    (match-string 1 file))
3518             ;; Save the article.
3519             (setq file (expand-file-name file))
3520             (unless (file-exists-p (file-name-directory file))
3521               (make-directory (file-name-directory file) t))
3522             (if (and message-fcc-handler-function
3523                      (not (eq message-fcc-handler-function 'rmail-output)))
3524                 (funcall message-fcc-handler-function file)
3525               (if (and (file-readable-p file) (mail-file-babyl-p file))
3526                   (rmail-output file 1 nil t)
3527                 (let ((mail-use-rfc822 t))
3528                   (rmail-output file 1 t t))))))
3529         (kill-buffer (current-buffer))))))
3530
3531 (defun message-output (filename)
3532   "Append this article to Unix/babyl mail file FILENAME."
3533   (if (and (file-readable-p filename)
3534            (mail-file-babyl-p filename))
3535       (gnus-output-to-rmail filename t)
3536     (gnus-output-to-mail filename t)))
3537
3538 (defun message-cleanup-headers ()
3539   "Do various automatic cleanups of the headers."
3540   ;; Remove empty lines in the header.
3541   (save-restriction
3542     (message-narrow-to-headers)
3543     ;; Remove blank lines.
3544     (while (re-search-forward "^[ \t]*\n" nil t)
3545       (replace-match "" t t))
3546
3547     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3548     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3549     ;; embedded line breaks.
3550     (goto-char (point-min))
3551     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3552       (save-restriction
3553         (narrow-to-region
3554          (point)
3555          (if (re-search-forward "^[^ \t]" nil t)
3556              (match-beginning 0)
3557            (forward-line 1)
3558            (point)))
3559         (goto-char (point-min))
3560         (while (re-search-forward "\n[ \t]+" nil t)
3561           (replace-match " " t t))     ;No line breaks (too confusing)
3562         (goto-char (point-min))
3563         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3564           (replace-match "," t t))
3565         (goto-char (point-min))
3566         ;; Remove trailing commas.
3567         (when (re-search-forward ",+$" nil t)
3568           (replace-match "" t t))))))
3569
3570 (defun message-make-date (&optional now)
3571   "Make a valid data header.
3572 If NOW, use that time instead."
3573   (let* ((now (or now (current-time)))
3574          (zone (nth 8 (decode-time now)))
3575          (sign "+"))
3576     (when (< zone 0)
3577       (setq sign "-")
3578       (setq zone (- zone)))
3579     (concat
3580      ;; The day name of the %a spec is locale-specific.  Pfff.
3581      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
3582                                              parse-time-weekdays))))
3583      (format-time-string "%d" now)
3584      ;; The month name of the %b spec is locale-specific.  Pfff.
3585      (format " %s "
3586              (capitalize (car (rassoc (nth 4 (decode-time now))
3587                                       parse-time-months))))
3588      (format-time-string "%Y %H:%M:%S " now)
3589      ;; We do all of this because XEmacs doesn't have the %z spec.
3590      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3591
3592 (defun message-make-message-id ()
3593   "Make a unique Message-ID."
3594   (concat "<" (message-unique-id)
3595           (let ((psubject (save-excursion (message-fetch-field "subject")))
3596                 (psupersedes
3597                  (save-excursion (message-fetch-field "supersedes"))))
3598             (if (or
3599                  (and message-reply-headers
3600                       (mail-header-references message-reply-headers)
3601                       (mail-header-subject message-reply-headers)
3602                       psubject
3603                       (not (string=
3604                             (message-strip-subject-re
3605                              (mail-header-subject message-reply-headers))
3606                             (message-strip-subject-re psubject))))
3607                  (and psupersedes
3608                       (string-match "_-_@" psupersedes)))
3609                 "_-_" ""))
3610           "@" (message-make-fqdn) ">"))
3611
3612 (defvar message-unique-id-char nil)
3613
3614 ;; If you ever change this function, make sure the new version
3615 ;; cannot generate IDs that the old version could.
3616 ;; You might for example insert a "." somewhere (not next to another dot
3617 ;; or string boundary), or modify the "fsf" string.
3618 (defun message-unique-id ()
3619   ;; Don't use microseconds from (current-time), they may be unsupported.
3620   ;; Instead we use this randomly inited counter.
3621   (setq message-unique-id-char
3622         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3623            ;; (current-time) returns 16-bit ints,
3624            ;; and 2^16*25 just fits into 4 digits i base 36.
3625            (* 25 25)))
3626   (let ((tm (current-time)))
3627     (concat
3628      (if (memq system-type '(ms-dos emx vax-vms))
3629          (let ((user (downcase (user-login-name))))
3630            (while (string-match "[^a-z0-9_]" user)
3631              (aset user (match-beginning 0) ?_))
3632            user)
3633        (message-number-base36 (user-uid) -1))
3634      (message-number-base36 (+ (car tm)
3635                                (lsh (% message-unique-id-char 25) 16)) 4)
3636      (message-number-base36 (+ (nth 1 tm)
3637                                (lsh (/ message-unique-id-char 25) 16)) 4)
3638      ;; Append the newsreader name, because while the generated
3639      ;; ID is unique to this newsreader, other newsreaders might
3640      ;; otherwise generate the same ID via another algorithm.
3641      ".fsf")))
3642
3643 (defun message-number-base36 (num len)
3644   (if (if (< len 0)
3645           (<= num 0)
3646         (= len 0))
3647       ""
3648     (concat (message-number-base36 (/ num 36) (1- len))
3649             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3650                                   (% num 36))))))
3651
3652 (defun message-make-organization ()
3653   "Make an Organization header."
3654   (let* ((organization
3655           (when message-user-organization
3656             (if (message-functionp message-user-organization)
3657                 (funcall message-user-organization)
3658               message-user-organization))))
3659     (save-excursion
3660       (message-set-work-buffer)
3661       (cond ((stringp organization)
3662              (insert organization))
3663             ((and (eq t organization)
3664                   message-user-organization-file
3665                   (file-exists-p message-user-organization-file))
3666              (insert-file-contents message-user-organization-file)))
3667       (goto-char (point-min))
3668       (while (re-search-forward "[\t\n]+" nil t)
3669         (replace-match "" t t))
3670       (unless (zerop (buffer-size))
3671         (buffer-string)))))
3672
3673 (defun message-make-lines ()
3674   "Count the number of lines and return numeric string."
3675   (save-excursion
3676     (save-restriction
3677       (widen)
3678       (message-goto-body)
3679       (int-to-string (count-lines (point) (point-max))))))
3680
3681 (defun message-make-in-reply-to ()
3682   "Return the In-Reply-To header for this message."
3683   (when message-reply-headers
3684     (let ((from (mail-header-from message-reply-headers))
3685           (date (mail-header-date message-reply-headers))
3686           (msg-id (mail-header-message-id message-reply-headers)))
3687       (when from
3688         (let ((stop-pos
3689                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3690           (concat msg-id (if msg-id " (")
3691                   (if (and stop-pos
3692                            (not (zerop stop-pos)))
3693                       (substring from 0 stop-pos) from)
3694                   "'s message of \""
3695                   (if (or (not date) (string= date ""))
3696                       "(unknown date)" date)
3697                   "\"" (if msg-id ")")))))))
3698
3699 (defun message-make-distribution ()
3700   "Make a Distribution header."
3701   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3702     (cond ((message-functionp message-distribution-function)
3703            (funcall message-distribution-function))
3704           (t orig-distribution))))
3705
3706 (defun message-make-expires ()
3707   "Return an Expires header based on `message-expires'."
3708   (let ((current (current-time))
3709         (future (* 1.0 message-expires 60 60 24)))
3710     ;; Add the future to current.
3711     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3712     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3713     (message-make-date current)))
3714
3715 (defun message-make-path ()
3716   "Return uucp path."
3717   (let ((login-name (user-login-name)))
3718     (cond ((null message-user-path)
3719            (concat (system-name) "!" login-name))
3720           ((stringp message-user-path)
3721            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3722            (concat message-user-path "!" login-name))
3723           (t login-name))))
3724
3725 (defun message-make-from ()
3726   "Make a From header."
3727   (let* ((style message-from-style)
3728          (login (message-make-address))
3729          (fullname
3730           (or (and (boundp 'user-full-name)
3731                    user-full-name)
3732               (user-full-name))))
3733     (when (string= fullname "&")
3734       (setq fullname (user-login-name)))
3735     (save-excursion
3736       (message-set-work-buffer)
3737       (cond
3738        ((or (null style)
3739             (equal fullname ""))
3740         (insert login))
3741        ((or (eq style 'angles)
3742             (and (not (eq style 'parens))
3743                  ;; Use angles if no quoting is needed, or if parens would
3744                  ;; need quoting too.
3745                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3746                      (let ((tmp (concat fullname nil)))
3747                        (while (string-match "([^()]*)" tmp)
3748                          (aset tmp (match-beginning 0) ?-)
3749                          (aset tmp (1- (match-end 0)) ?-))
3750                        (string-match "[\\()]" tmp)))))
3751         (insert fullname)
3752         (insert " <" login ">"))
3753        (t                               ; 'parens or default
3754         (insert login " (")
3755         (let ((fullname-start (point)))
3756           (insert fullname)
3757           (goto-char fullname-start)
3758           ;; RFC 822 says \ and nonmatching parentheses
3759           ;; must be escaped in comments.
3760           ;; Escape every instance of ()\ ...
3761           (while (re-search-forward "[()\\]" nil 1)
3762             (replace-match "\\\\\\&" t))
3763           ;; ... then undo escaping of matching parentheses,
3764           ;; including matching nested parentheses.
3765           (goto-char fullname-start)
3766           (while (re-search-forward
3767                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3768                   nil 1)
3769             (replace-match "\\1(\\3)" t)
3770             (goto-char fullname-start)))
3771         (insert ")")))
3772       (buffer-string))))
3773
3774 (defun message-make-sender ()
3775   "Return the \"real\" user address.
3776 This function tries to ignore all user modifications, and
3777 give as trustworthy answer as possible."
3778   (concat (user-login-name) "@" (system-name)))
3779
3780 (defun message-make-address ()
3781   "Make the address of the user."
3782   (or (message-user-mail-address)
3783       (concat (user-login-name) "@" (message-make-domain))))
3784
3785 (defun message-user-mail-address ()
3786   "Return the pertinent part of `user-mail-address'."
3787   (when user-mail-address
3788     (if (string-match " " user-mail-address)
3789         (nth 1 (mail-extract-address-components user-mail-address))
3790       user-mail-address)))
3791
3792 (defun message-make-fqdn ()
3793   "Return user's fully qualified domain name."
3794   (let ((system-name (system-name))
3795         (user-mail (message-user-mail-address)))
3796     (cond
3797      ((and (string-match "[^.]\\.[^.]" system-name)
3798            (not (string-match message-bogus-system-names system-name)))
3799       ;; `system-name' returned the right result.
3800       system-name)
3801      ;; Try `mail-host-address'.
3802      ((and (boundp 'mail-host-address)
3803            (stringp mail-host-address)
3804            (string-match "\\." mail-host-address))
3805       mail-host-address)
3806      ;; We try `user-mail-address' as a backup.
3807      ((and user-mail
3808            (string-match "\\." user-mail)
3809            (string-match "@\\(.*\\)\\'" user-mail))
3810       (match-string 1 user-mail))
3811      ;; Default to this bogus thing.
3812      (t
3813       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
3814
3815 (defun message-make-host-name ()
3816   "Return the name of the host."
3817   (let ((fqdn (message-make-fqdn)))
3818     (string-match "^[^.]+\\." fqdn)
3819     (substring fqdn 0 (1- (match-end 0)))))
3820
3821 (defun message-make-domain ()
3822   "Return the domain name."
3823   (or mail-host-address
3824       (message-make-fqdn)))
3825
3826 (defun message-make-mft ()
3827   "Return the Mail-Followup-To header."
3828   (let* ((msg-recipients (message-options-get 'message-recipients))
3829          (recipients
3830           (mapcar 'mail-strip-quoted-names
3831                   (message-tokenize-header msg-recipients)))
3832          (file-regexps
3833           (if message-subscribed-address-file
3834               (let (begin end item re)
3835                 (save-excursion
3836                   (with-temp-buffer
3837                     (insert-file-contents message-subscribed-address-file)
3838                     (while (not (eobp))
3839                       (setq begin (point))
3840                       (forward-line 1)
3841                       (setq end (point))
3842                       (if (bolp) (setq end (1- end)))
3843                       (setq item (regexp-quote (buffer-substring begin end)))
3844                       (if re (setq re (concat re "\\|" item))
3845                         (setq re (concat "\\`\\(" item))))
3846                     (and re (list (concat re "\\)\\'"))))))))
3847          (mft-regexps (apply 'append message-subscribed-regexps
3848                              (mapcar 'regexp-quote
3849                                      message-subscribed-addresses)
3850                              file-regexps
3851                              (mapcar 'funcall
3852                                      message-subscribed-address-functions))))
3853     (save-match-data
3854       (when (eval (apply 'append '(or)
3855                          (mapcar
3856                           (function (lambda (regexp)
3857                                       (mapcar
3858                                        (function (lambda (recipient)
3859                                                    `(string-match ,regexp
3860                                                                   ,recipient)))
3861                                        recipients)))
3862                           mft-regexps)))
3863         msg-recipients))))
3864
3865 (defun message-generate-headers (headers)
3866   "Prepare article HEADERS.
3867 Headers already prepared in the buffer are not modified."
3868   (save-restriction
3869     (message-narrow-to-headers)
3870     (let* ((Date (message-make-date))
3871            (Message-ID (message-make-message-id))
3872            (Organization (message-make-organization))
3873            (From (message-make-from))
3874            (Path (message-make-path))
3875            (Subject nil)
3876            (Newsgroups nil)
3877            (In-Reply-To (message-make-in-reply-to))
3878            (To nil)
3879            (Distribution (message-make-distribution))
3880            (Lines (message-make-lines))
3881            (User-Agent message-newsreader)
3882            (Expires (message-make-expires))
3883            (case-fold-search t)
3884            header value elem)
3885       ;; First we remove any old generated headers.
3886       (let ((headers message-deletable-headers))
3887         (unless (buffer-modified-p)
3888           (setq headers (delq 'Message-ID (copy-sequence headers))))
3889         (while headers
3890           (goto-char (point-min))
3891           (and (re-search-forward
3892                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3893                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3894                (message-delete-line))
3895           (pop headers)))
3896       ;; Go through all the required headers and see if they are in the
3897       ;; articles already.  If they are not, or are empty, they are
3898       ;; inserted automatically - except for Subject, Newsgroups and
3899       ;; Distribution.
3900       (while headers
3901         (goto-char (point-min))
3902         (setq elem (pop headers))
3903         (if (consp elem)
3904             (if (eq (car elem) 'optional)
3905                 (setq header (cdr elem))
3906               (setq header (car elem)))
3907           (setq header elem))
3908         (when (or (not (re-search-forward
3909                         (concat "^"
3910                                 (regexp-quote
3911                                  (downcase
3912                                   (if (stringp header)
3913                                       header
3914                                     (symbol-name header))))
3915                                 ":")
3916                         nil t))
3917                   (progn
3918                     ;; The header was found.  We insert a space after the
3919                     ;; colon, if there is none.
3920                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3921                     ;; Find out whether the header is empty...
3922                     (looking-at "[ \t]*\n[^ \t]")))
3923           ;; So we find out what value we should insert.
3924           (setq value
3925                 (cond
3926                  ((and (consp elem) (eq (car elem) 'optional))
3927                   ;; This is an optional header.  If the cdr of this
3928                   ;; is something that is nil, then we do not insert
3929                   ;; this header.
3930                   (setq header (cdr elem))
3931                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3932                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3933                  ((consp elem)
3934                   ;; The element is a cons.  Either the cdr is a
3935                   ;; string to be inserted verbatim, or it is a
3936                   ;; function, and we insert the value returned from
3937                   ;; this function.
3938                   (or (and (stringp (cdr elem)) (cdr elem))
3939                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3940                  ((and (boundp header) (symbol-value header))
3941                   ;; The element is a symbol.  We insert the value
3942                   ;; of this symbol, if any.
3943                   (symbol-value header))
3944                  ((not (message-check-element header))
3945                   ;; We couldn't generate a value for this header,
3946                   ;; so we just ask the user.
3947                   (read-from-minibuffer
3948                    (format "Empty header for %s; enter value: " header)))))
3949           ;; Finally insert the header.
3950           (when (and value
3951                      (not (equal value "")))
3952             (save-excursion
3953               (if (bolp)
3954                   (progn
3955                     ;; This header didn't exist, so we insert it.
3956                     (goto-char (point-max))
3957                     (insert (if (stringp header) header (symbol-name header))
3958                             ": " value)
3959                     ;; We check whether the value was ended by a
3960                     ;; newline.  If now, we insert one.
3961                     (unless (bolp)
3962                       (insert "\n"))
3963                     (forward-line -1))
3964                 ;; The value of this header was empty, so we clear
3965                 ;; totally and insert the new value.
3966                 (delete-region (point) (gnus-point-at-eol))
3967                 (insert value))
3968               ;; Add the deletable property to the headers that require it.
3969               (and (memq header message-deletable-headers)
3970                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3971                    (add-text-properties
3972                     (point) (match-end 0)
3973                     '(message-deletable t face italic) (current-buffer)))))))
3974       ;; Insert new Sender if the From is strange.
3975       (let ((from (message-fetch-field "from"))
3976             (sender (message-fetch-field "sender"))
3977             (secure-sender (message-make-sender)))
3978         (when (and from
3979                    (not (message-check-element 'sender))
3980                    (not (string=
3981                          (downcase
3982                           (cadr (mail-extract-address-components from)))
3983                          (downcase secure-sender)))
3984                    (or (null sender)
3985                        (not
3986                         (string=
3987                          (downcase
3988                           (cadr (mail-extract-address-components sender)))
3989                          (downcase secure-sender)))))
3990           (goto-char (point-min))
3991           ;; Rename any old Sender headers to Original-Sender.
3992           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3993             (beginning-of-line)
3994             (insert "Original-")
3995             (beginning-of-line))
3996           (when (or (message-news-p)
3997                     (string-match "@.+\\.." secure-sender))
3998             (insert "Sender: " secure-sender "\n")))))))
3999
4000 (defun message-insert-courtesy-copy ()
4001   "Insert a courtesy message in mail copies of combined messages."
4002   (let (newsgroups)
4003     (save-excursion
4004       (save-restriction
4005         (message-narrow-to-headers)
4006         (when (setq newsgroups (message-fetch-field "newsgroups"))
4007           (goto-char (point-max))
4008           (insert "Posted-To: " newsgroups "\n")))
4009       (forward-line 1)
4010       (when message-courtesy-message
4011         (cond
4012          ((string-match "%s" message-courtesy-message)
4013           (insert (format message-courtesy-message newsgroups)))
4014          (t
4015           (insert message-courtesy-message)))))))
4016
4017 ;;;
4018 ;;; Setting up a message buffer
4019 ;;;
4020
4021 (defun message-fill-address (header value)
4022   (save-restriction
4023     (narrow-to-region (point) (point))
4024     (insert (capitalize (symbol-name header))
4025             ": "
4026             (if (consp value) (car value) value)
4027             "\n")
4028     (narrow-to-region (point-min) (1- (point-max)))
4029     (let (quoted last)
4030       (goto-char (point-min))
4031       (while (not (eobp))
4032         (skip-chars-forward "^,\"" (point-max))
4033         (if (or (eq (char-after) ?,)
4034                 (eobp))
4035             (when (not quoted)
4036               (if (and (> (current-column) 78)
4037                        last)
4038                   (progn
4039                     (save-excursion
4040                       (goto-char last)
4041                       (insert "\n\t"))
4042                     (setq last (1+ (point))))
4043                 (setq last (1+ (point)))))
4044           (setq quoted (not quoted)))
4045         (unless (eobp)
4046           (forward-char 1))))
4047     (goto-char (point-max))
4048     (widen)
4049     (forward-line 1)))
4050
4051 (defun message-fill-header (header value)
4052   (let ((begin (point))
4053         (fill-column 78)
4054         (fill-prefix "\t"))
4055     (insert (capitalize (symbol-name header))
4056             ": "
4057             (if (consp value) (car value) value)
4058             "\n")
4059     (save-restriction
4060       (narrow-to-region begin (point))
4061       (fill-region-as-paragraph begin (point))
4062       ;; Tapdance around looong Message-IDs.
4063       (forward-line -1)
4064       (when (looking-at "[ \t]*$")
4065         (message-delete-line))
4066       (goto-char begin)
4067       (re-search-forward ":" nil t)
4068       (when (looking-at "\n[ \t]+")
4069         (replace-match " " t t))
4070       (goto-char (point-max)))))
4071
4072 (defun message-shorten-1 (list cut surplus)
4073   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4074   (setcdr (nthcdr (- cut 2) list)
4075           (nthcdr (+ (- cut 2) surplus 1) list)))
4076
4077 (defun message-shorten-references (header references)
4078   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4079 If folding is disallowed, also check that the REFERENCES are less
4080 than 988 characters long, and if they are not, trim them until they are."
4081   (let ((maxcount 21)
4082         (count 0)
4083         (cut 2)
4084         refs)
4085     (with-temp-buffer
4086       (insert references)
4087       (goto-char (point-min))
4088       ;; Cons a list of valid references.
4089       (while (re-search-forward "<[^>]+>" nil t)
4090         (push (match-string 0) refs))
4091       (setq refs (nreverse refs)
4092             count (length refs)))
4093
4094     ;; If the list has more than MAXCOUNT elements, trim it by
4095     ;; removing the CUTth element and the required number of
4096     ;; elements that follow.
4097     (when (> count maxcount)
4098       (let ((surplus (- count maxcount)))
4099         (message-shorten-1 refs cut surplus)
4100         (decf count surplus)))
4101
4102     ;; If folding is disallowed, make sure the total length (including
4103     ;; the spaces between) will be less than MAXSIZE characters.
4104     ;;
4105     ;; Only disallow folding for News messages. At this point the headers
4106     ;; have not been generated, thus we use message-this-is-news directly.
4107     (when (and message-this-is-news message-cater-to-broken-inn)
4108       (let ((maxsize 988)
4109             (totalsize (+ (apply #'+ (mapcar #'length refs))
4110                           (1- count)))
4111             (surplus 0)
4112             (ptr (nthcdr (1- cut) refs)))
4113         ;; Decide how many elements to cut off...
4114         (while (> totalsize maxsize)
4115           (decf totalsize (1+ (length (car ptr))))
4116           (incf surplus)
4117           (setq ptr (cdr ptr)))
4118         ;; ...and do it.
4119         (when (> surplus 0)
4120           (message-shorten-1 refs cut surplus))))
4121
4122     ;; Finally, collect the references back into a string and insert
4123     ;; it into the buffer.
4124     (let ((refstring (mapconcat #'identity refs " ")))
4125       (if (and message-this-is-news message-cater-to-broken-inn)
4126           (insert (capitalize (symbol-name header)) ": "
4127                   refstring "\n")
4128         (message-fill-header header refstring)))))
4129
4130 (defun message-position-point ()
4131   "Move point to where the user probably wants to find it."
4132   (message-narrow-to-headers)
4133   (cond
4134    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4135     (search-backward ":" )
4136     (widen)
4137     (forward-char 1)
4138     (if (eq (char-after) ? )
4139         (forward-char 1)
4140       (insert " ")))
4141    (t
4142     (goto-char (point-max))
4143     (widen)
4144     (forward-line 1)
4145     (unless (looking-at "$")
4146       (forward-line 2)))
4147    (sit-for 0)))
4148
4149 (defun message-beginning-of-line (&optional n)
4150   "Move point to beginning of header value or to beginning of line."
4151   (interactive "p")
4152   (if (message-point-in-header-p)
4153       (let* ((here (point))
4154              (bol (progn (beginning-of-line n) (point)))
4155              (eol (gnus-point-at-eol))
4156              (eoh (re-search-forward ": *" eol t)))
4157         (if (or (not eoh) (equal here eoh))
4158             (goto-char bol)
4159           (goto-char eoh)))
4160     (beginning-of-line n)))
4161
4162 (defun message-buffer-name (type &optional to group)
4163   "Return a new (unique) buffer name based on TYPE and TO."
4164   (cond
4165    ;; Generate a new buffer name The Message Way.
4166    ((eq message-generate-new-buffers 'unique)
4167     (generate-new-buffer-name
4168      (concat "*" type
4169              (if to
4170                  (concat " to "
4171                          (or (car (mail-extract-address-components to))
4172                              to) "")
4173                "")
4174              (if (and group (not (string= group ""))) (concat " on " group) "")
4175              "*")))
4176    ;; Check whether `message-generate-new-buffers' is a function,
4177    ;; and if so, call it.
4178    ((message-functionp message-generate-new-buffers)
4179     (funcall message-generate-new-buffers type to group))
4180    ((eq message-generate-new-buffers 'unsent)
4181     (generate-new-buffer-name
4182      (concat "*unsent " type
4183              (if to
4184                  (concat " to "
4185                          (or (car (mail-extract-address-components to))
4186                              to) "")
4187                "")
4188              (if (and group (not (string= group ""))) (concat " on " group) "")
4189              "*")))
4190    ;; Use standard name.
4191    (t
4192     (format "*%s message*" type))))
4193
4194 (defun message-pop-to-buffer (name)
4195   "Pop to buffer NAME, and warn if it already exists and is modified."
4196   (let ((buffer (get-buffer name)))
4197     (if (and buffer
4198              (buffer-name buffer))
4199         (progn
4200           (set-buffer (pop-to-buffer buffer))
4201           (when (and (buffer-modified-p)
4202                      (not (y-or-n-p
4203                            "Message already being composed; erase? ")))
4204             (error "Message being composed")))
4205       (set-buffer (pop-to-buffer name)))
4206     (erase-buffer)
4207     (message-mode)))
4208
4209 (defun message-do-send-housekeeping ()
4210   "Kill old message buffers."
4211   ;; We might have sent this buffer already.  Delete it from the
4212   ;; list of buffers.
4213   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4214   (while (and message-max-buffers
4215               message-buffer-list
4216               (>= (length message-buffer-list) message-max-buffers))
4217     ;; Kill the oldest buffer -- unless it has been changed.
4218     (let ((buffer (pop message-buffer-list)))
4219       (when (and (buffer-name buffer)
4220                  (not (buffer-modified-p buffer)))
4221         (kill-buffer buffer))))
4222   ;; Rename the buffer.
4223   (if message-send-rename-function
4224       (funcall message-send-rename-function)
4225     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
4226     (when (string-match
4227            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
4228            (buffer-name))
4229       (let ((name (match-string 2 (buffer-name)))
4230             to group)
4231         (if (not (or (null name)
4232                      (string-equal name "mail")
4233                      (string-equal name "posting")))
4234             (setq name (concat "*sent " name "*"))
4235           (message-narrow-to-headers)
4236           (setq to (message-fetch-field "to"))
4237           (setq group (message-fetch-field "newsgroups"))
4238           (widen)
4239           (setq name
4240                 (cond
4241                  (to (concat "*sent mail to "
4242                              (or (car (mail-extract-address-components to))
4243                                  to) "*"))
4244                  ((and group (not (string= group "")))
4245                   (concat "*sent posting on " group "*"))
4246                  (t "*sent mail*"))))
4247         (unless (string-equal name (buffer-name))
4248           (rename-buffer name t)))))
4249   ;; Push the current buffer onto the list.
4250   (when message-max-buffers
4251     (setq message-buffer-list
4252           (nconc message-buffer-list (list (current-buffer))))))
4253
4254 (defun message-mail-user-agent ()
4255   (let ((mua (cond
4256               ((not message-mail-user-agent) nil)
4257               ((eq message-mail-user-agent t) mail-user-agent)
4258               (t message-mail-user-agent))))
4259     (if (memq mua '(message-user-agent gnus-user-agent))
4260         nil
4261       mua)))
4262
4263 (defun message-setup (headers &optional replybuffer actions switch-function)
4264   (let ((mua (message-mail-user-agent))
4265         subject to field yank-action)
4266     (if (not (and message-this-is-mail mua))
4267         (message-setup-1 headers replybuffer actions)
4268       (if replybuffer
4269           (setq yank-action (list 'insert-buffer replybuffer)))
4270       (setq headers (copy-sequence headers))
4271       (setq field (assq 'Subject headers))
4272       (when field
4273         (setq subject (cdr field))
4274         (setq headers (delq field headers)))
4275       (setq field (assq 'To headers))
4276       (when field
4277         (setq to (cdr field))
4278         (setq headers (delq field headers)))
4279       (let ((mail-user-agent mua))
4280         (compose-mail to subject
4281                       (mapcar (lambda (item)
4282                                 (cons
4283                                  (format "%s" (car item))
4284                                  (cdr item)))
4285                               headers)
4286                       nil switch-function yank-action actions)))))
4287
4288 (defun message-setup-1 (headers &optional replybuffer actions)
4289   (dolist (action actions)
4290     (condition-case nil
4291         (add-to-list 'message-send-actions
4292                      `(apply ',(car action) ',(cdr action)))))
4293   (setq message-reply-buffer replybuffer)
4294   (goto-char (point-min))
4295   ;; Insert all the headers.
4296   (mail-header-format
4297    (let ((h headers)
4298          (alist message-header-format-alist))
4299      (while h
4300        (unless (assq (caar h) message-header-format-alist)
4301          (push (list (caar h)) alist))
4302        (pop h))
4303      alist)
4304    headers)
4305   (delete-region (point) (progn (forward-line -1) (point)))
4306   (when message-default-headers
4307     (insert message-default-headers)
4308     (or (bolp) (insert ?\n)))
4309   (put-text-property
4310    (point)
4311    (progn
4312      (insert mail-header-separator "\n")
4313      (1- (point)))
4314    'read-only nil)
4315   (forward-line -1)
4316   (when (message-news-p)
4317     (when message-default-news-headers
4318       (insert message-default-news-headers)
4319       (or (bolp) (insert ?\n)))
4320     (when message-generate-headers-first
4321       (message-generate-headers
4322        (delq 'Lines
4323              (delq 'Subject
4324                    (copy-sequence message-required-news-headers))))))
4325   (when (message-mail-p)
4326     (when message-default-mail-headers
4327       (insert message-default-mail-headers)
4328       (or (bolp) (insert ?\n)))
4329     (when message-generate-headers-first
4330       (message-generate-headers
4331        (delq 'Lines
4332              (delq 'Subject
4333                    (copy-sequence message-required-mail-headers))))))
4334   (run-hooks 'message-signature-setup-hook)
4335   (message-insert-signature)
4336   (save-restriction
4337     (message-narrow-to-headers)
4338     (if message-alternative-emails
4339         (message-use-alternative-email-as-from))
4340     (run-hooks 'message-header-setup-hook))
4341   (set-buffer-modified-p nil)
4342   (setq buffer-undo-list nil)
4343   (run-hooks 'message-setup-hook)
4344   (message-position-point)
4345   (undo-boundary))
4346
4347 (defun message-set-auto-save-file-name ()
4348   "Associate the message buffer with a file in the drafts directory."
4349   (when message-auto-save-directory
4350     (unless (file-directory-p
4351              (directory-file-name message-auto-save-directory))
4352       (gnus-make-directory message-auto-save-directory))
4353     (if (gnus-alive-p)
4354         (setq message-draft-article
4355               (nndraft-request-associate-buffer "drafts"))
4356       (setq buffer-file-name (expand-file-name
4357                               (if (memq system-type 
4358                                         '(ms-dos ms-windows windows-nt 
4359                                                  cygwin32 win32 w32 
4360                                                  mswindows))
4361                                   "message"
4362                                 "*message*")
4363                               message-auto-save-directory))
4364       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4365     (clear-visited-file-modtime)
4366     (setq buffer-file-coding-system message-draft-coding-system)))
4367
4368 (defun message-disassociate-draft ()
4369   "Disassociate the message buffer from the drafts directory."
4370   (when message-draft-article
4371     (nndraft-request-expire-articles
4372      (list message-draft-article) "drafts" nil t)))
4373
4374 (defun message-insert-headers ()
4375   "Generate the headers for the article."
4376   (interactive)
4377   (save-excursion
4378     (save-restriction
4379       (message-narrow-to-headers)
4380       (when (message-news-p)
4381         (message-generate-headers
4382          (delq 'Lines
4383                (delq 'Subject
4384                      (copy-sequence message-required-news-headers)))))
4385       (when (message-mail-p)
4386         (message-generate-headers
4387          (delq 'Lines
4388                (delq 'Subject
4389                      (copy-sequence message-required-mail-headers))))))))
4390
4391 \f
4392
4393 ;;;
4394 ;;; Commands for interfacing with message
4395 ;;;
4396
4397 ;;;###autoload
4398 (defun message-mail (&optional to subject
4399                                other-headers continue switch-function
4400                                yank-action send-actions)
4401   "Start editing a mail message to be sent.
4402 OTHER-HEADERS is an alist of header/value pairs."
4403   (interactive)
4404   (let ((message-this-is-mail t) replybuffer)
4405     (unless (message-mail-user-agent)
4406       (message-pop-to-buffer (message-buffer-name "mail" to)))
4407     ;; FIXME: message-mail should do something if YANK-ACTION is not
4408     ;; insert-buffer.
4409     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
4410          (setq replybuffer (nth 1 yank-action)))
4411     (message-setup
4412      (nconc
4413       `((To . ,(or to "")) (Subject . ,(or subject "")))
4414       (when other-headers other-headers))
4415      replybuffer send-actions)
4416     ;; FIXME: Should return nil if failure.
4417     t))
4418
4419 ;;;###autoload
4420 (defun message-news (&optional newsgroups subject)
4421   "Start editing a news article to be sent."
4422   (interactive)
4423   (let ((message-this-is-news t))
4424     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
4425     (message-setup `((Newsgroups . ,(or newsgroups ""))
4426                      (Subject . ,(or subject ""))))))
4427
4428 (defun message-get-reply-headers (wide &optional to-address)
4429   (let (follow-to mct never-mct to cc author mft recipients)
4430     ;; Find all relevant headers we need.
4431     (setq to (message-fetch-field "to")
4432           cc (message-fetch-field "cc")
4433           mct (message-fetch-field "mail-copies-to")
4434           author (or (message-fetch-field "mail-reply-to")
4435                      (message-fetch-field "reply-to")
4436                      (message-fetch-field "from")
4437                      "")
4438           mft (and message-use-mail-followup-to
4439                    (message-fetch-field "mail-followup-to")))
4440
4441     ;; Handle special values of Mail-Copies-To.
4442     (when mct
4443       (cond ((or (equal (downcase mct) "never")
4444                  (equal (downcase mct) "nobody"))
4445              (setq never-mct t)
4446              (setq mct nil))
4447             ((or (equal (downcase mct) "always")
4448                  (equal (downcase mct) "poster"))
4449              (setq mct author))))
4450
4451     (save-match-data
4452       ;; Build (textual) list of new recipient addresses.
4453       (cond
4454        ((not wide)
4455         (setq recipients (concat ", " author)))
4456        ((and mft
4457              (string-match "[^ \t,]" mft)
4458              (or (not (eq message-use-mail-followup-to 'ask))
4459                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
4460 You should normally obey the Mail-Followup-To: header.  In this
4461 article, it has the value of
4462
4463 " mft "
4464
4465 which directs your response to " (if (string-match "," mft)
4466                                      "the specified addresses"
4467                                    "that address only") ".
4468
4469 Most commonly, Mail-Followup-To is used by a mailing list poster to
4470 express that responses should be sent to just the list, and not the
4471 poster as well.
4472
4473 If a message is posted to several mailing lists, Mail-Followup-To may
4474 also be used to direct the following discussion to one list only,
4475 because discussions that are spread over several lists tend to be
4476 fragmented and very difficult to follow.
4477
4478 Also, some source/announcement lists are not intended for discussion;
4479 responses here are directed to other addresses.")))
4480         (setq recipients (concat ", " mft)))
4481        (to-address
4482         (setq recipients (concat ", " to-address))
4483         ;; If the author explicitly asked for a copy, we don't deny it to them.
4484         (if mct (setq recipients (concat recipients ", " mct))))
4485        (t
4486         (setq recipients (if never-mct "" (concat ", " author)))
4487         (if to  (setq recipients (concat recipients ", " to)))
4488         (if cc  (setq recipients (concat recipients ", " cc)))
4489         (if mct (setq recipients (concat recipients ", " mct)))))
4490       (if (>= (length recipients) 2)
4491           ;; Strip the leading ", ".
4492           (setq recipients (substring recipients 2)))
4493       ;; Squeeze whitespace.
4494       (while (string-match "[ \t][ \t]+" recipients)
4495         (setq recipients (replace-match " " t t recipients)))
4496       ;; Remove addresses that match `rmail-dont-reply-to-names'.
4497       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4498         (setq recipients (rmail-dont-reply-to recipients)))
4499       ;; Perhaps "Mail-Copies-To: never" removed the only address?
4500       (if (string-equal recipients "")
4501           (setq recipients author))
4502       ;; Convert string to a list of (("foo@bar" . "Name <foo@bar>") ...).
4503       (setq recipients
4504             (mapcar
4505              (lambda (addr)
4506                (cons (mail-strip-quoted-names addr) addr))
4507              (message-tokenize-header recipients)))
4508       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
4509       (let ((s recipients))
4510         (while s
4511           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
4512       ;; Build the header alist.  Allow the user to be asked whether
4513       ;; or not to reply to all recipients in a wide reply.
4514       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
4515       (when (and recipients
4516                  (or (not message-wide-reply-confirm-recipients)
4517                      (y-or-n-p "Reply to all recipients? ")))
4518         (setq recipients (mapconcat
4519                           (lambda (addr) (cdr addr)) recipients ", "))
4520         (if (string-match "^ +" recipients)
4521             (setq recipients (substring recipients (match-end 0))))
4522         (push (cons 'Cc recipients) follow-to)))
4523     follow-to))
4524
4525 ;;;###autoload
4526 (defun message-reply (&optional to-address wide)
4527   "Start editing a reply to the article in the current buffer."
4528   (interactive)
4529   (require 'gnus-sum)                   ; for gnus-list-identifiers
4530   (let ((cur (current-buffer))
4531         from subject date reply-to to cc
4532         references message-id follow-to
4533         (inhibit-point-motion-hooks t)
4534         (message-this-is-mail t)
4535         gnus-warning)
4536     (save-restriction
4537       (message-narrow-to-head-1)
4538       ;; Allow customizations to have their say.
4539       (if (not wide)
4540           ;; This is a regular reply.
4541           (when (message-functionp message-reply-to-function)
4542             (save-excursion
4543               (setq follow-to (funcall message-reply-to-function))))
4544         ;; This is a followup.
4545         (when (message-functionp message-wide-reply-to-function)
4546           (save-excursion
4547             (setq follow-to
4548                   (funcall message-wide-reply-to-function)))))
4549       (setq message-id (message-fetch-field "message-id" t)
4550             references (message-fetch-field "references")
4551             date (message-fetch-field "date")
4552             from (message-fetch-field "from")
4553             subject (or (message-fetch-field "subject") "none"))
4554       (when gnus-list-identifiers
4555         (setq subject (message-strip-list-identifiers subject)))
4556       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4557
4558       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4559                  (string-match "<[^>]+>" gnus-warning))
4560         (setq message-id (match-string 0 gnus-warning)))
4561
4562       (unless follow-to
4563         (setq follow-to (message-get-reply-headers wide to-address))))
4564
4565     (unless (message-mail-user-agent)
4566       (message-pop-to-buffer
4567        (message-buffer-name
4568         (if wide "wide reply" "reply") from
4569         (if wide to-address nil))))
4570
4571     (setq message-reply-headers
4572           (vector 0 subject from date message-id references 0 0 ""))
4573
4574     (message-setup
4575      `((Subject . ,subject)
4576        ,@follow-to
4577        ,@(if (or references message-id)
4578              `((References . ,(concat (or references "") (and references " ")
4579                                       (or message-id ""))))
4580            nil))
4581      cur)))
4582
4583 ;;;###autoload
4584 (defun message-wide-reply (&optional to-address)
4585   "Make a \"wide\" reply to the message in the current buffer."
4586   (interactive)
4587   (message-reply to-address t))
4588
4589 ;;;###autoload
4590 (defun message-followup (&optional to-newsgroups)
4591   "Follow up to the message in the current buffer.
4592 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4593   (interactive)
4594   (require 'gnus-sum)                   ; for gnus-list-identifiers
4595   (let ((cur (current-buffer))
4596         from subject date reply-to mrt mct
4597         references message-id follow-to
4598         (inhibit-point-motion-hooks t)
4599         (message-this-is-news t)
4600         followup-to distribution newsgroups gnus-warning posted-to)
4601     (save-restriction
4602       (narrow-to-region
4603        (goto-char (point-min))
4604        (if (search-forward "\n\n" nil t)
4605            (1- (point))
4606          (point-max)))
4607       (when (message-functionp message-followup-to-function)
4608         (setq follow-to
4609               (funcall message-followup-to-function)))
4610       (setq from (message-fetch-field "from")
4611             date (message-fetch-field "date")
4612             subject (or (message-fetch-field "subject") "none")
4613             references (message-fetch-field "references")
4614             message-id (message-fetch-field "message-id" t)
4615             followup-to (message-fetch-field "followup-to")
4616             newsgroups (message-fetch-field "newsgroups")
4617             posted-to (message-fetch-field "posted-to")
4618             reply-to (message-fetch-field "reply-to")
4619             mrt (message-fetch-field "mail-reply-to")
4620             distribution (message-fetch-field "distribution")
4621             mct (message-fetch-field "mail-copies-to"))
4622       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4623                  (string-match "<[^>]+>" gnus-warning))
4624         (setq message-id (match-string 0 gnus-warning)))
4625       ;; Remove bogus distribution.
4626       (when (and (stringp distribution)
4627                  (let ((case-fold-search t))
4628                    (string-match "world" distribution)))
4629         (setq distribution nil))
4630       (if gnus-list-identifiers
4631           (setq subject (message-strip-list-identifiers subject)))
4632       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4633       (widen))
4634
4635     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4636
4637     (message-setup
4638      `((Subject . ,subject)
4639        ,@(cond
4640           (to-newsgroups
4641            (list (cons 'Newsgroups to-newsgroups)))
4642           (follow-to follow-to)
4643           ((and followup-to message-use-followup-to)
4644            (list
4645             (cond
4646              ((equal (downcase followup-to) "poster")
4647               (if (or (eq message-use-followup-to 'use)
4648                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
4649 You should normally obey the Followup-To: header.
4650
4651 `Followup-To: poster' sends your response via e-mail instead of news.
4652
4653 A typical situation where `Followup-To: poster' is used is when the poster
4654 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4655                   (progn
4656                     (setq message-this-is-news nil)
4657                     (cons 'To (or mrt reply-to from "")))
4658                 (cons 'Newsgroups newsgroups)))
4659              (t
4660               (if (or (equal followup-to newsgroups)
4661                       (not (eq message-use-followup-to 'ask))
4662                       (message-y-or-n-p
4663                        (concat "Obey Followup-To: " followup-to "? ") t "\
4664 You should normally obey the Followup-To: header.
4665
4666         `Followup-To: " followup-to "'
4667 directs your response to " (if (string-match "," followup-to)
4668                                "the specified newsgroups"
4669                              "that newsgroup only") ".
4670
4671 If a message is posted to several newsgroups, Followup-To is often
4672 used to direct the following discussion to one newsgroup only,
4673 because discussions that are spread over several newsgroup tend to
4674 be fragmented and very difficult to follow.
4675
4676 Also, some source/announcement newsgroups are not intended for discussion;
4677 responses here are directed to other newsgroups."))
4678                   (cons 'Newsgroups followup-to)
4679                 (cons 'Newsgroups newsgroups))))))
4680           (posted-to
4681            `((Newsgroups . ,posted-to)))
4682           (t
4683            `((Newsgroups . ,newsgroups))))
4684        ,@(and distribution (list (cons 'Distribution distribution)))
4685        ,@(if (or references message-id)
4686              `((References . ,(concat (or references "") (and references " ")
4687                                       (or message-id "")))))
4688        ,@(when (and mct
4689                     (not (or (equal (downcase mct) "never")
4690                              (equal (downcase mct) "nobody"))))
4691            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4692                                    (equal (downcase mct) "poster"))
4693                                (or mrt reply-to from "")
4694                              mct)))))
4695
4696      cur)
4697
4698     (setq message-reply-headers
4699           (vector 0 subject from date message-id references 0 0 ""))))
4700
4701
4702 ;;;###autoload
4703 (defun message-cancel-news (&optional arg)
4704   "Cancel an article you posted.
4705 If ARG, allow editing of the cancellation message."
4706   (interactive "P")
4707   (unless (message-news-p)
4708     (error "This is not a news article; canceling is impossible"))
4709   (let (from newsgroups message-id distribution buf sender)
4710     (save-excursion
4711       ;; Get header info from original article.
4712       (save-restriction
4713         (message-narrow-to-head-1)
4714         (setq from (message-fetch-field "from")
4715               sender (message-fetch-field "sender")
4716               newsgroups (message-fetch-field "newsgroups")
4717               message-id (message-fetch-field "message-id" t)
4718               distribution (message-fetch-field "distribution")))
4719       ;; Make sure that this article was written by the user.
4720       (unless (or
4721                ;; Canlock-logic as suggested by Per Abrahamsen
4722                ;; <abraham@dina.kvl.dk>
4723                ;;
4724                ;; IF article has cancel-lock THEN
4725                ;;   IF we can verify it THEN
4726                ;;     issue cancel
4727                ;;   ELSE
4728                ;;     error: cancellock: article is not yours
4729                ;; ELSE
4730                ;;   Use old rules, comparing sender...
4731                (if (message-fetch-field "Cancel-Lock")
4732                    (if (null (canlock-verify))
4733                        t
4734                      (error "Failed to verify Cancel-lock: This article is not yours"))
4735                  nil)
4736                (message-gnksa-enable-p 'cancel-messages)
4737                (and sender
4738                     (string-equal
4739                      (downcase sender)
4740                      (downcase (message-make-sender))))
4741                (string-equal
4742                 (downcase (cadr (mail-extract-address-components from)))
4743                 (downcase (cadr (mail-extract-address-components
4744                                  (message-make-from))))))
4745         (error "This article is not yours"))
4746       (when (yes-or-no-p "Do you really want to cancel this article? ")
4747         ;; Make control message.
4748         (if arg
4749             (message-news)
4750           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4751         (erase-buffer)
4752         (insert "Newsgroups: " newsgroups "\n"
4753                 "From: " from "\n"
4754                 "Subject: cmsg cancel " message-id "\n"
4755                 "Control: cancel " message-id "\n"
4756                 (if distribution
4757                     (concat "Distribution: " distribution "\n")
4758                   "")
4759                 mail-header-separator "\n"
4760                 message-cancel-message)
4761         (run-hooks 'message-cancel-hook)
4762         (unless arg
4763           (message "Canceling your article...")
4764           (if (let ((message-syntax-checks
4765                      'dont-check-for-anything-just-trust-me))
4766                 (funcall message-send-news-function))
4767               (message "Canceling your article...done"))
4768           (kill-buffer buf))))))
4769
4770 ;;;###autoload
4771 (defun message-supersede ()
4772   "Start composing a message to supersede the current message.
4773 This is done simply by taking the old article and adding a Supersedes
4774 header line with the old Message-ID."
4775   (interactive)
4776   (let ((cur (current-buffer))
4777         (sender (message-fetch-field "sender"))
4778         (from (message-fetch-field "from")))
4779     ;; Check whether the user owns the article that is to be superseded.
4780     (unless (or
4781              ;; Canlock-logic as suggested by Per Abrahamsen
4782              ;; <abraham@dina.kvl.dk>
4783              ;;
4784              ;; IF article has cancel-lock THEN
4785              ;;   IF we can verify it THEN
4786              ;;     issue cancel
4787              ;;   ELSE
4788              ;;     error: cancellock: article is not yours
4789              ;; ELSE
4790              ;;   Use old rules, comparing sender...
4791              (if (message-fetch-field "Cancel-Lock")
4792                  (if (null (canlock-verify))
4793                      t
4794                    (error "Failed to verify Cancel-lock: This article is not yours"))
4795                nil)
4796              (message-gnksa-enable-p 'cancel-messages)
4797                 (and sender
4798                      (string-equal
4799                       (downcase sender)
4800                       (downcase (message-make-sender))))
4801                 (string-equal
4802                  (downcase (cadr (mail-extract-address-components from)))
4803                  (downcase (cadr (mail-extract-address-components
4804                                   (message-make-from))))))
4805       (error "This article is not yours"))
4806     ;; Get a normal message buffer.
4807     (message-pop-to-buffer (message-buffer-name "supersede"))
4808     (insert-buffer-substring cur)
4809     (mime-to-mml)
4810     (message-narrow-to-head-1)
4811     ;; Remove unwanted headers.
4812     (when message-ignored-supersedes-headers
4813       (message-remove-header message-ignored-supersedes-headers t))
4814     (goto-char (point-min))
4815     (if (not (re-search-forward "^Message-ID: " nil t))
4816         (error "No Message-ID in this article")
4817       (replace-match "Supersedes: " t t))
4818     (goto-char (point-max))
4819     (insert mail-header-separator)
4820     (widen)
4821     (forward-line 1)))
4822
4823 ;;;###autoload
4824 (defun message-recover ()
4825   "Reread contents of current buffer from its last auto-save file."
4826   (interactive)
4827   (let ((file-name (make-auto-save-file-name)))
4828     (cond ((save-window-excursion
4829              (if (not (eq system-type 'vax-vms))
4830                  (with-output-to-temp-buffer "*Directory*"
4831                    (with-current-buffer standard-output
4832                      (fundamental-mode)) ; for Emacs 20.4+
4833                    (buffer-disable-undo standard-output)
4834                    (let ((default-directory "/"))
4835                      (call-process
4836                       "ls" nil standard-output nil "-l" file-name))))
4837              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4838            (let ((buffer-read-only nil))
4839              (erase-buffer)
4840              (insert-file-contents file-name nil)))
4841           (t (error "message-recover cancelled")))))
4842
4843 ;;; Washing Subject:
4844
4845 (defun message-wash-subject (subject)
4846   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
4847 Previous forwarders, replyers, etc. may add it."
4848   (with-temp-buffer
4849     (insert subject)
4850     (goto-char (point-min))
4851     ;; strip Re/Fwd stuff off the beginning
4852     (while (re-search-forward
4853             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4854       (replace-match ""))
4855
4856     ;; and gnus-style forwards [foo@bar.com] subject
4857     (goto-char (point-min))
4858     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4859       (replace-match ""))
4860
4861     ;; and off the end
4862     (goto-char (point-max))
4863     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4864       (replace-match ""))
4865
4866     ;; and finally, any whitespace that was left-over
4867     (goto-char (point-min))
4868     (while (re-search-forward "^[ \t]+" nil t)
4869       (replace-match ""))
4870     (goto-char (point-max))
4871     (while (re-search-backward "[ \t]+$" nil t)
4872       (replace-match ""))
4873
4874     (buffer-string)))
4875
4876 ;;; Forwarding messages.
4877
4878 (defvar message-forward-decoded-p nil
4879   "Non-nil means the original message is decoded.")
4880
4881 (defun message-forward-subject-author-subject (subject)
4882   "Generate a SUBJECT for a forwarded message.
4883 The form is: [Source] Subject, where if the original message was mail,
4884 Source is the sender, and if the original message was news, Source is
4885 the list of newsgroups is was posted to."
4886   (concat "["
4887           (let ((prefix
4888                  (or (message-fetch-field "newsgroups")
4889                      (message-fetch-field "from")
4890                      "(nowhere)")))
4891             (if message-forward-decoded-p
4892                 prefix
4893               (mail-decode-encoded-word-string prefix)))
4894           "] " subject))
4895
4896 (defun message-forward-subject-fwd (subject)
4897   "Generate a SUBJECT for a forwarded message.
4898 The form is: Fwd: Subject, where Subject is the original subject of
4899 the message."
4900   (concat "Fwd: " subject))
4901
4902 (defun message-make-forward-subject ()
4903   "Return a Subject header suitable for the message in the current buffer."
4904   (save-excursion
4905     (save-restriction
4906       (message-narrow-to-head-1)
4907       (let ((funcs message-make-forward-subject-function)
4908             (subject (message-fetch-field "Subject")))
4909         (setq subject
4910               (if subject
4911                   (if message-forward-decoded-p
4912                       subject
4913                     (mail-decode-encoded-word-string subject))
4914                 ""))
4915         (if message-wash-forwarded-subjects
4916             (setq subject (message-wash-subject subject)))
4917         ;; Make sure funcs is a list.
4918         (and funcs
4919              (not (listp funcs))
4920              (setq funcs (list funcs)))
4921         ;; Apply funcs in order, passing subject generated by previous
4922         ;; func to the next one.
4923         (while funcs
4924           (when (message-functionp (car funcs))
4925             (setq subject (funcall (car funcs) subject)))
4926           (setq funcs (cdr funcs)))
4927         subject))))
4928
4929 (eval-when-compile
4930   (defvar gnus-article-decoded-p))
4931
4932
4933 ;;;###autoload
4934 (defun message-forward (&optional news digest)
4935   "Forward the current message via mail.
4936 Optional NEWS will use news to forward instead of mail.
4937 Optional DIGEST will use digest to forward."
4938   (interactive "P")
4939   (let* ((cur (current-buffer))
4940          (message-forward-decoded-p
4941           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
4942               gnus-article-decoded-p ;; In an article buffer.
4943             message-forward-decoded-p))
4944          (subject (message-make-forward-subject)))
4945     (if news
4946         (message-news nil subject)
4947       (message-mail nil subject))
4948     (message-forward-make-body cur digest)))
4949
4950 ;;;###autoload
4951 (defun message-forward-make-body (forward-buffer &optional digest)
4952   ;; Put point where we want it before inserting the forwarded
4953   ;; message.
4954   (if message-forward-before-signature
4955       (message-goto-body)
4956     (goto-char (point-max)))
4957   (if message-forward-as-mime
4958       (if digest
4959           (insert "\n<#multipart type=digest>\n")
4960         (if message-forward-show-mml
4961             (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4962           (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4963     (insert "\n-------------------- Start of forwarded message --------------------\n"))
4964   (let ((b (point)) e)
4965     (if digest
4966         (if message-forward-as-mime
4967             (insert-buffer-substring forward-buffer)
4968           (mml-insert-buffer forward-buffer))
4969       (if (and message-forward-show-mml
4970                (not message-forward-decoded-p))
4971           (insert
4972            (with-temp-buffer
4973              (mm-disable-multibyte-mule4) ;; Must copy buffer in unibyte mode
4974                (insert
4975                 (with-current-buffer forward-buffer
4976                   (mm-string-as-unibyte (buffer-string))))
4977                (mm-enable-multibyte-mule4)
4978                (mime-to-mml)
4979                (goto-char (point-min))
4980                (when (looking-at "From ")
4981                  (replace-match "X-From-Line: "))
4982                (buffer-string)))
4983         (save-restriction
4984           (narrow-to-region (point) (point))
4985           (mml-insert-buffer forward-buffer)
4986           (goto-char (point-min))
4987           (when (looking-at "From ")
4988             (replace-match "X-From-Line: "))
4989           (goto-char (point-max)))))
4990     (setq e (point))
4991     (if message-forward-as-mime
4992         (if digest
4993             (insert "<#/multipart>\n")
4994           (if message-forward-show-mml
4995               (insert "<#/mml>\n")
4996             (insert "<#/part>\n")))
4997       (insert "\n-------------------- End of forwarded message --------------------\n"))
4998     (if (and digest message-forward-as-mime)
4999         (save-restriction
5000           (narrow-to-region b e)
5001           (goto-char b)
5002           (narrow-to-region (point)
5003                             (or (search-forward "\n\n" nil t) (point)))
5004           (delete-region (point-min) (point-max)))
5005       (when (and (not current-prefix-arg)
5006                  message-forward-ignored-headers)
5007         (save-restriction
5008           (narrow-to-region b e)
5009           (goto-char b)
5010           (narrow-to-region (point)
5011                             (or (search-forward "\n\n" nil t) (point)))
5012           (message-remove-header message-forward-ignored-headers t)))))
5013   (message-position-point))
5014
5015 ;;;###autoload
5016 (defun message-forward-rmail-make-body (forward-buffer)
5017   (save-window-excursion
5018     (set-buffer forward-buffer)
5019     (let (rmail-enable-mime)
5020       (rmail-toggle-header 0)))
5021   (message-forward-make-body forward-buffer))
5022
5023 ;;;###autoload
5024 (defun message-insinuate-rmail ()
5025   "Let RMAIL uses message to forward."
5026   (interactive)
5027   (setq rmail-enable-mime-composing t)
5028   (setq rmail-insert-mime-forwarded-message-function 
5029         'message-forward-rmail-make-body))
5030
5031 ;;;###autoload
5032 (defun message-resend (address)
5033   "Resend the current article to ADDRESS."
5034   (interactive
5035    (list (message-read-from-minibuffer "Resend message to: ")))
5036   (message "Resending message to %s..." address)
5037   (save-excursion
5038     (let ((cur (current-buffer))
5039           beg)
5040       ;; We first set up a normal mail buffer.
5041       (unless (message-mail-user-agent)
5042         (set-buffer (get-buffer-create " *message resend*"))
5043         (erase-buffer))
5044       (let ((message-this-is-mail t))
5045         (message-setup `((To . ,address))))
5046       ;; Insert our usual headers.
5047       (message-generate-headers '(From Date To))
5048       (message-narrow-to-headers)
5049       ;; Rename them all to "Resent-*".
5050       (while (re-search-forward "^[A-Za-z]" nil t)
5051         (forward-char -1)
5052         (insert "Resent-"))
5053       (widen)
5054       (forward-line)
5055       (delete-region (point) (point-max))
5056       (setq beg (point))
5057       ;; Insert the message to be resent.
5058       (insert-buffer-substring cur)
5059       (goto-char (point-min))
5060       (search-forward "\n\n")
5061       (forward-char -1)
5062       (save-restriction
5063         (narrow-to-region beg (point))
5064         (message-remove-header message-ignored-resent-headers t)
5065         (goto-char (point-max)))
5066       (insert mail-header-separator)
5067       ;; Rename all old ("Also-")Resent headers.
5068       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5069         (beginning-of-line)
5070         (insert "Also-"))
5071       ;; Quote any "From " lines at the beginning.
5072       (goto-char beg)
5073       (when (looking-at "From ")
5074         (replace-match "X-From-Line: "))
5075       ;; Send it.
5076       (let ((message-inhibit-body-encoding t)
5077             message-required-mail-headers)
5078         (message-send-mail))
5079       (kill-buffer (current-buffer)))
5080     (message "Resending message to %s...done" address)))
5081
5082 ;;;###autoload
5083 (defun message-bounce ()
5084   "Re-mail the current message.
5085 This only makes sense if the current message is a bounce message that
5086 contains some mail you have written which has been bounced back to
5087 you."
5088   (interactive)
5089   (let ((handles (mm-dissect-buffer t))
5090         boundary)
5091     (message-pop-to-buffer (message-buffer-name "bounce"))
5092     (if (stringp (car handles))
5093         ;; This is a MIME bounce.
5094         (mm-insert-part (car (last handles)))
5095       ;; This is a non-MIME bounce, so we try to remove things
5096       ;; manually.
5097       (mm-insert-part handles)
5098       (undo-boundary)
5099       (goto-char (point-min))
5100       (search-forward "\n\n" nil t)
5101       (if (or (and (re-search-forward message-unsent-separator nil t)
5102                    (forward-line 1))
5103               (re-search-forward "^Return-Path:.*\n" nil t))
5104           ;; We remove everything before the bounced mail.
5105           (delete-region
5106            (point-min)
5107            (if (re-search-forward "^[^ \n\t]+:" nil t)
5108                (match-beginning 0)
5109              (point)))
5110         (when (re-search-backward "^.?From .*\n" nil t)
5111           (delete-region (match-beginning 0) (match-end 0)))))
5112     (mm-enable-multibyte)
5113     (mime-to-mml)
5114     (save-restriction
5115       (message-narrow-to-head-1)
5116       (message-remove-header message-ignored-bounced-headers t)
5117       (goto-char (point-max))
5118       (insert mail-header-separator))
5119     (message-position-point)))
5120
5121 ;;;
5122 ;;; Interactive entry points for new message buffers.
5123 ;;;
5124
5125 ;;;###autoload
5126 (defun message-mail-other-window (&optional to subject)
5127   "Like `message-mail' command, but display mail buffer in another window."
5128   (interactive)
5129   (unless (message-mail-user-agent)
5130     (let ((pop-up-windows t)
5131           (special-display-buffer-names nil)
5132           (special-display-regexps nil)
5133           (same-window-buffer-names nil)
5134           (same-window-regexps nil))
5135       (message-pop-to-buffer (message-buffer-name "mail" to))))
5136   (let ((message-this-is-mail t))
5137     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5138                    nil nil 'switch-to-buffer-other-window)))
5139
5140 ;;;###autoload
5141 (defun message-mail-other-frame (&optional to subject)
5142   "Like `message-mail' command, but display mail buffer in another frame."
5143   (interactive)
5144   (unless (message-mail-user-agent)
5145     (let ((pop-up-frames t)
5146           (special-display-buffer-names nil)
5147           (special-display-regexps nil)
5148           (same-window-buffer-names nil)
5149           (same-window-regexps nil))
5150       (message-pop-to-buffer (message-buffer-name "mail" to))))
5151   (let ((message-this-is-mail t))
5152     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5153                    nil nil 'switch-to-buffer-other-frame)))
5154
5155 ;;;###autoload
5156 (defun message-news-other-window (&optional newsgroups subject)
5157   "Start editing a news article to be sent."
5158   (interactive)
5159   (let ((pop-up-windows t)
5160         (special-display-buffer-names nil)
5161         (special-display-regexps nil)
5162         (same-window-buffer-names nil)
5163         (same-window-regexps nil))
5164     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
5165   (let ((message-this-is-news t))
5166     (message-setup `((Newsgroups . ,(or newsgroups ""))
5167                      (Subject . ,(or subject ""))))))
5168
5169 ;;;###autoload
5170 (defun message-news-other-frame (&optional newsgroups subject)
5171   "Start editing a news article to be sent."
5172   (interactive)
5173   (let ((pop-up-frames t)
5174         (special-display-buffer-names nil)
5175         (special-display-regexps nil)
5176         (same-window-buffer-names nil)
5177         (same-window-regexps nil))
5178     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
5179   (let ((message-this-is-news t))
5180     (message-setup `((Newsgroups . ,(or newsgroups ""))
5181                      (Subject . ,(or subject ""))))))
5182
5183 ;;; underline.el
5184
5185 ;; This code should be moved to underline.el (from which it is stolen).
5186
5187 ;;;###autoload
5188 (defun bold-region (start end)
5189   "Bold all nonblank characters in the region.
5190 Works by overstriking characters.
5191 Called from program, takes two arguments START and END
5192 which specify the range to operate on."
5193   (interactive "r")
5194   (save-excursion
5195     (let ((end1 (make-marker)))
5196       (move-marker end1 (max start end))
5197       (goto-char (min start end))
5198       (while (< (point) end1)
5199         (or (looking-at "[_\^@- ]")
5200             (insert (char-after) "\b"))
5201         (forward-char 1)))))
5202
5203 ;;;###autoload
5204 (defun unbold-region (start end)
5205   "Remove all boldness (overstruck characters) in the region.
5206 Called from program, takes two arguments START and END
5207 which specify the range to operate on."
5208   (interactive "r")
5209   (save-excursion
5210     (let ((end1 (make-marker)))
5211       (move-marker end1 (max start end))
5212       (goto-char (min start end))
5213       (while (re-search-forward "\b" end1 t)
5214         (if (eq (char-after) (char-after (- (point) 2)))
5215             (delete-char -2))))))
5216
5217 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5218
5219 ;; Support for toolbar
5220 (eval-when-compile
5221   (defvar tool-bar-map)
5222   (defvar tool-bar-mode))
5223
5224 (defun message-tool-bar-map ()
5225   (or message-tool-bar-map
5226       (setq message-tool-bar-map
5227             (and (fboundp 'tool-bar-add-item-from-menu)
5228                  tool-bar-mode
5229                  (let ((tool-bar-map (copy-keymap tool-bar-map))
5230                        (load-path (mm-image-load-path)))
5231                    ;; Zap some items which aren't so relevant and take
5232                    ;; up space.
5233                    (dolist (key '(print-buffer kill-buffer save-buffer
5234                                                write-file dired open-file))
5235                      (define-key tool-bar-map (vector key) nil))
5236                    (tool-bar-add-item-from-menu
5237                     'message-send-and-exit "mail_send" message-mode-map)
5238                    (tool-bar-add-item-from-menu
5239                     'message-kill-buffer "close" message-mode-map)
5240                    (tool-bar-add-item-from-menu
5241                     'message-dont-send "cancel" message-mode-map)
5242                    (tool-bar-add-item-from-menu
5243                     'mml-attach-file "attach" mml-mode-map)
5244                    (tool-bar-add-item-from-menu
5245                     'ispell-message "spell" message-mode-map)
5246                    (tool-bar-add-item-from-menu
5247                     'message-insert-importance-high "important"
5248                     message-mode-map)
5249                    (tool-bar-add-item-from-menu
5250                     'message-insert-importance-low "unimportant"
5251                     message-mode-map)
5252                    (tool-bar-add-item-from-menu
5253                     'message-insert-disposition-notification-to "receipt"
5254                     message-mode-map)
5255                    tool-bar-map)))))
5256
5257 ;;; Group name completion.
5258
5259 (defcustom message-newgroups-header-regexp
5260   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5261   "Regexp that match headers that lists groups."
5262   :group 'message
5263   :type 'regexp)
5264
5265 (defcustom message-completion-alist
5266   (list (cons message-newgroups-header-regexp 'message-expand-group)
5267         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name))
5268   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
5269   :group 'message
5270   :type '(alist :key-type regexp :value-type function))
5271
5272 (defcustom message-tab-body-function nil
5273   "*Function to execute when `message-tab' (TAB) is executed in the body.
5274 If nil, the function bound in `text-mode-map' or `global-map' is executed."
5275   :group 'message
5276   :type 'function)
5277
5278 (defun message-tab ()
5279   "Complete names according to `message-completion-alist'.
5280 Execute function specified by `message-tab-body-function' when not in
5281 those headers."
5282   (interactive)
5283   (let ((alist message-completion-alist))
5284     (while (and alist
5285                 (let ((mail-abbrev-mode-regexp (caar alist)))
5286                   (not (mail-abbrev-in-expansion-header-p))))
5287       (setq alist (cdr alist)))
5288     (funcall (or (cdar alist) message-tab-body-function
5289                  (lookup-key text-mode-map "\t")
5290                  (lookup-key global-map "\t")
5291                  'indent-relative))))
5292
5293 (defun message-expand-group ()
5294   "Expand the group name under point."
5295   (let* ((b (save-excursion
5296               (save-restriction
5297                 (narrow-to-region
5298                  (save-excursion
5299                    (beginning-of-line)
5300                    (skip-chars-forward "^:")
5301                    (1+ (point)))
5302                  (point))
5303                 (skip-chars-backward "^, \t\n") (point))))
5304          (completion-ignore-case t)
5305          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5306                                             (point))))
5307          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5308          (completions (all-completions string hashtb))
5309          comp)
5310     (delete-region b (point))
5311     (cond
5312      ((= (length completions) 1)
5313       (if (string= (car completions) string)
5314           (progn
5315             (insert string)
5316             (message "Only matching group"))
5317         (insert (car completions))))
5318      ((and (setq comp (try-completion string hashtb))
5319            (not (string= comp string)))
5320       (insert comp))
5321      (t
5322       (insert string)
5323       (if (not comp)
5324           (message "No matching groups")
5325         (save-selected-window
5326           (pop-to-buffer "*Completions*")
5327           (buffer-disable-undo)
5328           (let ((buffer-read-only nil))
5329             (erase-buffer)
5330             (let ((standard-output (current-buffer)))
5331               (display-completion-list (sort completions 'string<)))
5332             (goto-char (point-min))
5333             (delete-region (point) (progn (forward-line 3) (point))))))))))
5334
5335 (defun message-expand-name ()
5336   (if (fboundp 'bbdb-complete-name)
5337       (bbdb-complete-name)
5338     (expand-abbrev)))
5339
5340 ;;; Help stuff.
5341
5342 (defun message-talkative-question (ask question show &rest text)
5343   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
5344 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
5345 The following arguments may contain lists of values."
5346   (if (and show
5347            (setq text (message-flatten-list text)))
5348       (save-window-excursion
5349         (save-excursion
5350           (with-output-to-temp-buffer " *MESSAGE information message*"
5351             (set-buffer " *MESSAGE information message*")
5352             (fundamental-mode)          ; for Emacs 20.4+
5353             (mapcar 'princ text)
5354             (goto-char (point-min))))
5355         (funcall ask question))
5356     (funcall ask question)))
5357
5358 (defun message-flatten-list (list)
5359   "Return a new, flat list that contains all elements of LIST.
5360
5361 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
5362 => (1 2 3 4 5 6 7)"
5363   (cond ((consp list)
5364          (apply 'append (mapcar 'message-flatten-list list)))
5365         (list
5366          (list list))))
5367
5368 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
5369   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
5370 Then clone the local variables and values from the old buffer to the
5371 new one, cloning only the locals having a substring matching the
5372 regexp varstr."
5373   (let ((oldbuf (current-buffer)))
5374     (save-excursion
5375       (set-buffer (generate-new-buffer name))
5376       (message-clone-locals oldbuf varstr)
5377       (current-buffer))))
5378
5379 (defun message-clone-locals (buffer &optional varstr)
5380   "Clone the local variables from BUFFER to the current buffer."
5381   (let ((locals (save-excursion
5382                   (set-buffer buffer)
5383                   (buffer-local-variables)))
5384         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
5385     (mapcar
5386      (lambda (local)
5387        (when (and (consp local)
5388                   (car local)
5389                   (string-match regexp (symbol-name (car local)))
5390                   (or (null varstr)
5391                       (string-match varstr (symbol-name (car local)))))
5392          (ignore-errors
5393            (set (make-local-variable (car local))
5394                 (cdr local)))))
5395      locals)))
5396
5397 ;;; Miscellaneous functions
5398
5399 (defsubst message-replace-chars-in-string (string from to)
5400   (mm-subst-char-in-string from to string))
5401
5402 ;;;
5403 ;;; MIME functions
5404 ;;;
5405
5406 (defvar message-inhibit-body-encoding nil)
5407
5408 (defun message-encode-message-body ()
5409   (unless message-inhibit-body-encoding
5410     (let ((mail-parse-charset (or mail-parse-charset
5411                                   message-default-charset))
5412           (case-fold-search t)
5413           lines content-type-p)
5414       (message-goto-body)
5415       (save-restriction
5416         (narrow-to-region (point) (point-max))
5417         (let ((new (mml-generate-mime)))
5418           (when new
5419             (delete-region (point-min) (point-max))
5420             (insert new)
5421             (goto-char (point-min))
5422             (if (eq (aref new 0) ?\n)
5423                 (delete-char 1)
5424               (search-forward "\n\n")
5425               (setq lines (buffer-substring (point-min) (1- (point))))
5426               (delete-region (point-min) (point))))))
5427       (save-restriction
5428         (message-narrow-to-headers-or-head)
5429         (message-remove-header "Mime-Version")
5430         (goto-char (point-max))
5431         (insert "MIME-Version: 1.0\n")
5432         (when lines
5433           (insert lines))
5434         (setq content-type-p
5435               (or mml-boundary
5436                   (re-search-backward "^Content-Type:" nil t))))
5437       (save-restriction
5438         (message-narrow-to-headers-or-head)
5439         (message-remove-first-header "Content-Type")
5440         (message-remove-first-header "Content-Transfer-Encoding"))
5441       ;; We always make sure that the message has a Content-Type
5442       ;; header.  This is because some broken MTAs and MUAs get
5443       ;; awfully confused when confronted with a message with a
5444       ;; MIME-Version header and without a Content-Type header.  For
5445       ;; instance, Solaris' /usr/bin/mail.
5446       (unless content-type-p
5447         (goto-char (point-min))
5448         ;; For unknown reason, MIME-Version doesn't exist.
5449         (when (re-search-forward "^MIME-Version:" nil t)
5450           (forward-line 1)
5451           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
5452
5453 (defun message-read-from-minibuffer (prompt &optional initial-contents)
5454   "Read from the minibuffer while providing abbrev expansion."
5455   (if (fboundp 'mail-abbrevs-setup)
5456       (let ((mail-abbrev-mode-regexp "")
5457             (minibuffer-setup-hook 'mail-abbrevs-setup)
5458             (minibuffer-local-map message-minibuffer-local-map))
5459         (read-from-minibuffer prompt initial-contents))
5460     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
5461           (minibuffer-local-map message-minibuffer-local-map))
5462       (read-string prompt initial-contents))))
5463
5464 (defun message-use-alternative-email-as-from ()
5465   (require 'mail-utils)
5466   (let* ((fields '("To" "Cc"))
5467          (emails
5468           (split-string
5469            (mail-strip-quoted-names
5470             (mapconcat 'message-fetch-reply-field fields ","))
5471            "[ \f\t\n\r\v,]+"))
5472          email)
5473     (while emails
5474       (if (string-match message-alternative-emails (car emails))
5475           (setq email (car emails)
5476                 emails nil))
5477       (pop emails))
5478     (unless (or (not email) (equal email user-mail-address))
5479       (goto-char (point-max))
5480       (insert "From: " email "\n"))))
5481
5482 (defun message-options-get (symbol)
5483   (cdr (assq symbol message-options)))
5484
5485 (defun message-options-set (symbol value)
5486   (let ((the-cons (assq symbol message-options)))
5487     (if the-cons
5488         (if value
5489             (setcdr the-cons value)
5490           (setq message-options (delq the-cons message-options)))
5491       (and value
5492            (push (cons symbol value) message-options))))
5493   value)
5494
5495 (defun message-options-set-recipient ()
5496   (save-restriction
5497     (message-narrow-to-headers-or-head)
5498     (message-options-set 'message-sender
5499                          (mail-strip-quoted-names
5500                           (message-fetch-field "from")))
5501     (message-options-set 'message-recipients
5502                          (mail-strip-quoted-names
5503                           (let ((to (message-fetch-field "to"))
5504                                 (cc (message-fetch-field "cc"))
5505                                 (bcc (message-fetch-field "bcc")))
5506                             (concat
5507                              (or to "")
5508                              (if (and to cc) ", ")
5509                              (or cc "")
5510                              (if (and (or to cc) bcc) ", ")
5511                              (or bcc "")))))))
5512
5513 (when (featurep 'xemacs)
5514   (require 'messagexmas)
5515   (message-xmas-redefine))
5516
5517 (provide 'message)
5518
5519 (run-hooks 'message-load-hook)
5520
5521 ;; Local Variables:
5522 ;; coding: iso-8859-1
5523 ;; End:
5524
5525 ;;; message.el ends here