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