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