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