517a0e25f64cea75c4c6e6ec213ea257966f9793
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97,98,99 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: mail, news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33
34 (require 'mailheader)
35 (require 'nnheader)
36 (require 'easymenu)
37 (require 'custom)
38 (if (string-match "XEmacs\\|Lucid" emacs-version)
39     (require 'mail-abbrevs)
40   (require 'mailabbrev))
41 (require 'mail-parse)
42 (require 'mm-bodies)
43 (require 'mm-encode)
44 (require 'mml)
45
46 (defgroup message '((user-mail-address custom-variable)
47                     (user-full-name custom-variable))
48   "Mail and news message composing."
49   :link '(custom-manual "(message)Top")
50   :group 'mail
51   :group 'news)
52
53 (put 'user-mail-address 'custom-type 'string)
54 (put 'user-full-name 'custom-type 'string)
55
56 (defgroup message-various nil
57   "Various Message Variables"
58   :link '(custom-manual "(message)Various Message Variables")
59   :group 'message)
60
61 (defgroup message-buffers nil
62   "Message Buffers"
63   :link '(custom-manual "(message)Message Buffers")
64   :group 'message)
65
66 (defgroup message-sending nil
67   "Message Sending"
68   :link '(custom-manual "(message)Sending Variables")
69   :group 'message)
70
71 (defgroup message-interface nil
72   "Message Interface"
73   :link '(custom-manual "(message)Interface")
74   :group 'message)
75
76 (defgroup message-forwarding nil
77   "Message Forwarding"
78   :link '(custom-manual "(message)Forwarding")
79   :group 'message-interface)
80
81 (defgroup message-insertion nil
82   "Message Insertion"
83   :link '(custom-manual "(message)Insertion")
84   :group 'message)
85
86 (defgroup message-headers nil
87   "Message Headers"
88   :link '(custom-manual "(message)Message Headers")
89   :group 'message)
90
91 (defgroup message-news nil
92   "Composing News Messages"
93   :group 'message)
94
95 (defgroup message-mail nil
96   "Composing Mail Messages"
97   :group 'message)
98
99 (defgroup message-faces nil
100   "Faces used for message composing."
101   :group 'message
102   :group 'faces)
103
104 (defcustom message-directory "~/Mail/"
105   "*Directory from which all other mail file variables are derived."
106   :group 'message-various
107   :type 'directory)
108
109 (defcustom message-max-buffers 10
110   "*How many buffers to keep before starting to kill them off."
111   :group 'message-buffers
112   :type 'integer)
113
114 (defcustom message-send-rename-function nil
115   "Function called to rename the buffer after sending it."
116   :group 'message-buffers
117   :type 'function)
118
119 (defcustom message-fcc-handler-function 'message-output
120   "*A function called to save outgoing articles.
121 This function will be called with the name of the file to store the
122 article in.  The default function is `message-output' which saves in Unix
123 mailbox format."
124   :type '(radio (function-item message-output)
125                 (function :tag "Other"))
126   :group 'message-sending)
127
128 (defcustom message-courtesy-message
129   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
130   "*This is inserted at the start of a mailed copy of a posted message.
131 If the string contains the format spec \"%s\", the Newsgroups
132 the article has been posted to will be inserted there.
133 If this variable is nil, no such courtesy message will be added."
134   :group 'message-sending
135   :type 'string)
136
137 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
138   "*Regexp that matches headers to be removed in resent bounced mail."
139   :group 'message-interface
140   :type 'regexp)
141
142 ;;;###autoload
143 (defcustom message-from-style 'default
144   "*Specifies how \"From\" headers look.
145
146 If `nil', they contain just the return address like:
147         king@grassland.com
148 If `parens', they look like:
149         king@grassland.com (Elvis Parsley)
150 If `angles', they look like:
151         Elvis Parsley <king@grassland.com>
152
153 Otherwise, most addresses look like `angles', but they look like
154 `parens' if `angles' would need quoting and `parens' would not."
155   :type '(choice (const :tag "simple" nil)
156                  (const parens)
157                  (const angles)
158                  (const default))
159   :group 'message-headers)
160
161 (defcustom message-syntax-checks nil
162   ; Guess this one shouldn't be easy to customize...
163   "*Controls what syntax checks should not be performed on outgoing posts.
164 To disable checking of long signatures, for instance, add
165  `(signature . disabled)' to this list.
166
167 Don't touch this variable unless you really know what you're doing.
168
169 Checks include subject-cmsg multiple-headers sendsys message-id from
170 long-lines control-chars size new-text redirected-followup signature
171 approved sender empty empty-headers message-id from subject
172 shorten-followup-to existing-newsgroups buffer-file-name unchanged."
173   :group 'message-news)
174
175 (defcustom message-required-news-headers
176   '(From Newsgroups Subject Date Message-ID
177          (optional . Organization) Lines
178          (optional . User-Agent))
179   "*Headers to be generated or prompted for when posting an article.
180 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
181 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
182 User-Agent are optional.  If don't you want message to insert some
183 header, remove it from this list."
184   :group 'message-news
185   :group 'message-headers
186   :type '(repeat sexp))
187
188 (defcustom message-required-mail-headers
189   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
190          (optional . User-Agent))
191   "*Headers to be generated or prompted for when mailing a message.
192 RFC822 required that From, Date, To, Subject and Message-ID be
193 included.  Organization, Lines and User-Agent are optional."
194   :group 'message-mail
195   :group 'message-headers
196   :type '(repeat sexp))
197
198 (defcustom message-deletable-headers '(Message-ID Date Lines)
199   "Headers to be deleted if they already exist and were generated by message previously."
200   :group 'message-headers
201   :type 'sexp)
202
203 (defcustom message-ignored-news-headers
204   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:"
205   "*Regexp of headers to be removed unconditionally before posting."
206   :group 'message-news
207   :group 'message-headers
208   :type 'regexp)
209
210 (defcustom message-ignored-mail-headers "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:"
211   "*Regexp of headers to be removed unconditionally before mailing."
212   :group 'message-mail
213   :group 'message-headers
214   :type 'regexp)
215
216 (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:"
217   "*Header lines matching this regexp will be deleted before posting.
218 It's best to delete old Path and Date headers before posting to avoid
219 any confusion."
220   :group 'message-interface
221   :type 'regexp)
222
223 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
224   "*Regexp matching \"Re: \" in the subject line."
225   :group 'message-various
226   :type 'regexp)
227
228 ;;;###autoload
229 (defcustom message-signature-separator "^-- *$"
230   "Regexp matching the signature separator."
231   :type 'regexp
232   :group 'message-various)
233
234 (defcustom message-elide-elipsis "\n[...]\n\n"
235   "*The string which is inserted for elided text."
236   :type 'string
237   :group 'message-various)
238
239 (defcustom message-interactive nil
240   "Non-nil means when sending a message wait for and display errors.
241 nil means let mailer mail back a message to report errors."
242   :group 'message-sending
243   :group 'message-mail
244   :type 'boolean)
245
246 (defcustom message-generate-new-buffers 'unique
247   "*Non-nil means that a new message buffer will be created whenever `message-setup' is called.
248 If this is a function, call that function with three parameters:  The type,
249 the to address and the group name.  (Any of these may be nil.)  The function
250 should return the new buffer name."
251   :group 'message-buffers
252   :type '(choice (const :tag "off" nil)
253                  (const :tag "unique" unique)
254                  (const :tag "unsent" unsent)
255                  (function fun)))
256
257 (defcustom message-kill-buffer-on-exit nil
258   "*Non-nil means that the message buffer will be killed after sending a message."
259   :group 'message-buffers
260   :type 'boolean)
261
262 (defvar gnus-local-organization)
263 (defcustom message-user-organization
264   (or (and (boundp 'gnus-local-organization)
265            (stringp gnus-local-organization)
266            gnus-local-organization)
267       (getenv "ORGANIZATION")
268       t)
269   "*String to be used as an Organization header.
270 If t, use `message-user-organization-file'."
271   :group 'message-headers
272   :type '(choice string
273                  (const :tag "consult file" t)))
274
275 ;;;###autoload
276 (defcustom message-user-organization-file "/usr/lib/news/organization"
277   "*Local news organization file."
278   :type 'file
279   :group 'message-headers)
280
281 (defcustom message-forward-start-separator
282   "------- Start of forwarded message -------\n"
283   "*Delimiter inserted before forwarded messages."
284   :group 'message-forwarding
285   :type 'string)
286
287 (defcustom message-forward-end-separator
288   "------- End of forwarded message -------\n"
289   "*Delimiter inserted after forwarded messages."
290   :group 'message-forwarding
291   :type 'string)
292
293 (defcustom message-signature-before-forwarded-message t
294   "*If non-nil, put the signature before any included forwarded message."
295   :group 'message-forwarding
296   :type 'boolean)
297
298 (defcustom message-included-forward-headers
299   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^Followup-To:\\|^Reply-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Mail-Copies-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:\\|^Content-Transfer-Encoding:\\|^Content-Type:\\|^Mime-Version:"
300   "*Regexp matching headers to be included in forwarded messages."
301   :group 'message-forwarding
302   :type 'regexp)
303
304 (defcustom message-make-forward-subject-function
305   'message-forward-subject-author-subject
306  "*A list of functions that are called to generate a subject header for forwarded messages.
307 The subject generated by the previous function is passed into each
308 successive function.
309
310 The provided functions are:
311
312 * message-forward-subject-author-subject (Source of article (author or
313       newsgroup)), in brackets followed by the subject
314 * message-forward-subject-fwd (Subject of article with 'Fwd:' prepended
315       to it."
316  :group 'message-forwarding
317  :type '(radio (function-item message-forward-subject-author-subject)
318                (function-item message-forward-subject-fwd)))
319
320 (defcustom message-wash-forwarded-subjects nil
321   "*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."
322   :group 'message-forwarding
323   :type 'boolean)
324
325 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
326   "*All headers that match this regexp will be deleted when resending a message."
327   :group 'message-interface
328   :type 'regexp)
329
330 (defcustom message-ignored-cited-headers "."
331   "*Delete these headers from the messages you yank."
332   :group 'message-insertion
333   :type 'regexp)
334
335 (defcustom message-cancel-message "I am canceling my own article."
336   "Message to be inserted in the cancel message."
337   :group 'message-interface
338   :type 'string)
339
340 ;; Useful to set in site-init.el
341 ;;;###autoload
342 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
343   "Function to call to send the current buffer as mail.
344 The headers should be delimited by a line whose contents match the
345 variable `mail-header-separator'.
346
347 Valid values include `message-send-mail-with-sendmail' (the default),
348 `message-send-mail-with-mh', `message-send-mail-with-qmail' and
349 `smtpmail-send-it'."
350   :type '(radio (function-item message-send-mail-with-sendmail)
351                 (function-item message-send-mail-with-mh)
352                 (function-item message-send-mail-with-qmail)
353                 (function-item smtpmail-send-it)
354                 (function :tag "Other"))
355   :group 'message-sending
356   :group 'message-mail)
357
358 (defcustom message-send-news-function 'message-send-news
359   "Function to call to send the current buffer as news.
360 The headers should be delimited by a line whose contents match the
361 variable `mail-header-separator'."
362   :group 'message-sending
363   :group 'message-news
364   :type 'function)
365
366 (defcustom message-reply-to-function nil
367   "Function that should return a list of headers.
368 This function should pick out addresses from the To, Cc, and From headers
369 and respond with new To and Cc headers."
370   :group 'message-interface
371   :type 'function)
372
373 (defcustom message-wide-reply-to-function nil
374   "Function that should return a list of headers.
375 This function should pick out addresses from the To, Cc, and From headers
376 and respond with new To and Cc headers."
377   :group 'message-interface
378   :type 'function)
379
380 (defcustom message-followup-to-function nil
381   "Function that should return a list of headers.
382 This function should pick out addresses from the To, Cc, and From headers
383 and respond with new To and Cc headers."
384   :group 'message-interface
385   :type 'function)
386
387 (defcustom message-use-followup-to 'ask
388   "*Specifies what to do with Followup-To header.
389 If nil, always ignore the header.  If it is t, use its value, but
390 query before using the \"poster\" value.  If it is the symbol `ask',
391 always query the user whether to use the value.  If it is the symbol
392 `use', always use the value."
393   :group 'message-interface
394   :type '(choice (const :tag "ignore" nil)
395                  (const use)
396                  (const ask)))
397
398 ;; stuff relating to broken sendmail in MMDF
399 (defcustom message-sendmail-f-is-evil nil
400   "*Non-nil means that \"-f username\" should not be added to the sendmail
401 command line, because it is even more evil than leaving it out."
402   :group 'message-sending
403   :type 'boolean)
404
405 ;; qmail-related stuff
406 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
407   "Location of the qmail-inject program."
408   :group 'message-sending
409   :type 'file)
410
411 (defcustom message-qmail-inject-args nil
412   "Arguments passed to qmail-inject programs.
413 This should be a list of strings, one string for each argument.
414
415 For e.g., if you wish to set the envelope sender address so that bounces
416 go to the right place or to deal with listserv's usage of that address, you
417 might set this variable to '(\"-f\" \"you@some.where\")."
418   :group 'message-sending
419   :type '(repeat string))
420
421 (defvar gnus-post-method)
422 (defvar gnus-select-method)
423 (defcustom message-post-method
424   (cond ((and (boundp 'gnus-post-method)
425               (listp gnus-post-method)
426               gnus-post-method)
427          gnus-post-method)
428         ((boundp 'gnus-select-method)
429          gnus-select-method)
430         (t '(nnspool "")))
431   "*Method used to post news.
432 Note that when posting from inside Gnus, for instance, this
433 variable isn't used."
434   :group 'message-news
435   :group 'message-sending
436   ;; This should be the `gnus-select-method' widget, but that might
437   ;; create a dependence to `gnus.el'.
438   :type 'sexp)
439
440 (defcustom message-generate-headers-first nil
441   "*If non-nil, generate all possible headers before composing."
442   :group 'message-headers
443   :type 'boolean)
444
445 (defcustom message-setup-hook nil
446   "Normal hook, run each time a new outgoing message is initialized.
447 The function `message-setup' runs this hook."
448   :group 'message-various
449   :type 'hook)
450
451 (defcustom message-cancel-hook nil
452   "Hook run when cancelling articles."
453   :group 'message-various
454   :type 'hook)
455
456 (defcustom message-signature-setup-hook nil
457   "Normal hook, run each time a new outgoing message is initialized.
458 It is run after the headers have been inserted and before
459 the signature is inserted."
460   :group 'message-various
461   :type 'hook)
462
463 (defcustom message-mode-hook nil
464   "Hook run in message mode buffers."
465   :group 'message-various
466   :type 'hook)
467
468 (defcustom message-header-hook nil
469   "Hook run in a message mode buffer narrowed to the headers."
470   :group 'message-various
471   :type 'hook)
472
473 (defcustom message-header-setup-hook nil
474   "Hook called narrowed to the headers when setting up a message buffer."
475   :group 'message-various
476   :type 'hook)
477
478 ;;;###autoload
479 (defcustom message-citation-line-function 'message-insert-citation-line
480   "*Function called to insert the \"Whomever writes:\" line."
481   :type 'function
482   :group 'message-insertion)
483
484 ;;;###autoload
485 (defcustom message-yank-prefix "> "
486   "*Prefix inserted on the lines of yanked messages."
487   :type 'string
488   :group 'message-insertion)
489
490 (defcustom message-indentation-spaces 3
491   "*Number of spaces to insert at the beginning of each cited line.
492 Used by `message-yank-original' via `message-yank-cite'."
493   :group 'message-insertion
494   :type 'integer)
495
496 ;;;###autoload
497 (defcustom message-cite-function 'message-cite-original
498   "*Function for citing an original message.
499 Predefined functions include `message-cite-original' and
500 `message-cite-original-without-signature'.
501 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
502   :type '(radio (function-item message-cite-original)
503                 (function-item sc-cite-original)
504                 (function :tag "Other"))
505   :group 'message-insertion)
506
507 ;;;###autoload
508 (defcustom message-indent-citation-function 'message-indent-citation
509   "*Function for modifying a citation just inserted in the mail buffer.
510 This can also be a list of functions.  Each function can find the
511 citation between (point) and (mark t).  And each function should leave
512 point and mark around the citation text as modified."
513   :type 'function
514   :group 'message-insertion)
515
516 (defvar message-abbrevs-loaded nil)
517
518 ;;;###autoload
519 (defcustom message-signature t
520   "*String to be inserted at the end of the message buffer.
521 If t, the `message-signature-file' file will be inserted instead.
522 If a function, the result from the function will be used instead.
523 If a form, the result from the form will be used instead."
524   :type 'sexp
525   :group 'message-insertion)
526
527 ;;;###autoload
528 (defcustom message-signature-file "~/.signature"
529   "*File containing the text inserted at end of message buffer."
530   :type 'file
531   :group 'message-insertion)
532
533 (defcustom message-distribution-function nil
534   "*Function called to return a Distribution header."
535   :group 'message-news
536   :group 'message-headers
537   :type 'function)
538
539 (defcustom message-expires 14
540   "Number of days before your article expires."
541   :group 'message-news
542   :group 'message-headers
543   :link '(custom-manual "(message)News Headers")
544   :type 'integer)
545
546 (defcustom message-user-path nil
547   "If nil, use the NNTP server name in the Path header.
548 If stringp, use this; if non-nil, use no host name (user name only)."
549   :group 'message-news
550   :group 'message-headers
551   :link '(custom-manual "(message)News Headers")
552   :type '(choice (const :tag "nntp" nil)
553                  (string :tag "name")
554                  (sexp :tag "none" :format "%t" t)))
555
556 (defvar message-reply-buffer nil)
557 (defvar message-reply-headers nil)
558 (defvar message-newsreader nil)
559 (defvar message-mailer nil)
560 (defvar message-sent-message-via nil)
561 (defvar message-checksum nil)
562 (defvar message-send-actions nil
563   "A list of actions to be performed upon successful sending of a message.")
564 (defvar message-exit-actions nil
565   "A list of actions to be performed upon exiting after sending a message.")
566 (defvar message-kill-actions nil
567   "A list of actions to be performed before killing a message buffer.")
568 (defvar message-postpone-actions nil
569   "A list of actions to be performed after postponing a message.")
570
571 (define-widget 'message-header-lines 'text
572   "All header lines must be LFD terminated."
573   :format "%t:%n%v"
574   :valid-regexp "^\\'"
575   :error "All header lines must be newline terminated")
576
577 (defcustom message-default-headers ""
578   "*A string containing header lines to be inserted in outgoing messages.
579 It is inserted before you edit the message, so you can edit or delete
580 these lines."
581   :group 'message-headers
582   :type 'message-header-lines)
583
584 (defcustom message-default-mail-headers ""
585   "*A string of header lines to be inserted in outgoing mails."
586   :group 'message-headers
587   :group 'message-mail
588   :type 'message-header-lines)
589
590 (defcustom message-default-news-headers ""
591   "*A string of header lines to be inserted in outgoing news
592 articles."
593   :group 'message-headers
594   :group 'message-news
595   :type 'message-header-lines)
596
597 ;; Note: could use /usr/ucb/mail instead of sendmail;
598 ;; options -t, and -v if not interactive.
599 (defcustom message-mailer-swallows-blank-line
600   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
601                          system-configuration)
602            (file-readable-p "/etc/sendmail.cf")
603            (let ((buffer (get-buffer-create " *temp*")))
604              (unwind-protect
605                  (save-excursion
606                    (set-buffer buffer)
607                    (insert-file-contents "/etc/sendmail.cf")
608                    (goto-char (point-min))
609                    (let ((case-fold-search nil))
610                      (re-search-forward "^OR\\>" nil t)))
611                (kill-buffer buffer))))
612       ;; According to RFC822, "The field-name must be composed of printable
613       ;; ASCII characters (i. e., characters that have decimal values between
614       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
615       ;; space, or colon.
616       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
617   "*Set this non-nil if the system's mailer runs the header and body together.
618 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
619 The value should be an expression to test whether the problem will
620 actually occur."
621   :group 'message-sending
622   :type 'sexp)
623
624 ;; Ignore errors in case this is used in Emacs 19.
625 ;; Don't use ignore-errors because this is copied into loaddefs.el.
626 ;;;###autoload
627 (condition-case nil
628     (define-mail-user-agent 'message-user-agent
629       'message-mail 'message-send-and-exit
630       'message-kill-buffer 'message-send-hook)
631   (error nil))
632
633 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
634   "If non-nil, delete the deletable headers before feeding to mh.")
635
636 (defvar message-send-method-alist
637   '((news message-news-p message-send-via-news)
638     (mail message-mail-p message-send-via-mail))
639   "Alist of ways to send outgoing messages.
640 Each element has the form
641
642   \(TYPE PREDICATE FUNCTION)
643
644 where TYPE is a symbol that names the method; PREDICATE is a function
645 called without any parameters to determine whether the message is
646 a message of type TYPE; and FUNCTION is a function to be called if
647 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
648 the prefix.")
649
650 (defvar message-mail-alias-type 'abbrev
651   "*What alias expansion type to use in Message buffers.
652 The default is `abbrev', which uses mailabbrev.  nil switches
653 mail aliases off.")
654
655 (defcustom message-auto-save-directory
656   (nnheader-concat message-directory "drafts/")
657   "*Directory where Message auto-saves buffers if Gnus isn't running.
658 If nil, Message won't auto-save."
659   :group 'message-buffers
660   :type 'directory)
661
662 (defcustom message-buffer-naming-style 'unique
663   "*The way new message buffers are named.
664 Valid valued are `unique' and `unsent'."
665   :group 'message-buffers
666   :type '(choice (const :tag "unique" unique)
667                  (const :tag "unsent" unsent)))
668
669 (defcustom message-default-charset nil
670   "Default charset used in non-MULE XEmacsen.")
671
672 ;;; Internal variables.
673 ;;; Well, not really internal.
674
675 (defvar message-mode-syntax-table
676   (let ((table (copy-syntax-table text-mode-syntax-table)))
677     (modify-syntax-entry ?% ". " table)
678     (modify-syntax-entry ?> ". " table)
679     (modify-syntax-entry ?< ". " table)
680     table)
681   "Syntax table used while in Message mode.")
682
683 (defvar message-mode-abbrev-table text-mode-abbrev-table
684   "Abbrev table used in Message mode buffers.
685 Defaults to `text-mode-abbrev-table'.")
686 (defgroup message-headers nil
687   "Message headers."
688   :link '(custom-manual "(message)Variables")
689   :group 'message)
690
691 (defface message-header-to-face
692   '((((class color)
693       (background dark))
694      (:foreground "green2" :bold t))
695     (((class color)
696       (background light))
697      (:foreground "MidnightBlue" :bold t))
698     (t
699      (:bold t :italic t)))
700   "Face used for displaying From headers."
701   :group 'message-faces)
702
703 (defface message-header-cc-face
704   '((((class color)
705       (background dark))
706      (:foreground "green4" :bold t))
707     (((class color)
708       (background light))
709      (:foreground "MidnightBlue"))
710     (t
711      (:bold t)))
712   "Face used for displaying Cc headers."
713   :group 'message-faces)
714
715 (defface message-header-subject-face
716   '((((class color)
717       (background dark))
718      (:foreground "green3"))
719     (((class color)
720       (background light))
721      (:foreground "navy blue" :bold t))
722     (t
723      (:bold t)))
724   "Face used for displaying subject headers."
725   :group 'message-faces)
726
727 (defface message-header-newsgroups-face
728   '((((class color)
729       (background dark))
730      (:foreground "yellow" :bold t :italic t))
731     (((class color)
732       (background light))
733      (:foreground "blue4" :bold t :italic t))
734     (t
735      (:bold t :italic t)))
736   "Face used for displaying newsgroups headers."
737   :group 'message-faces)
738
739 (defface message-header-other-face
740   '((((class color)
741       (background dark))
742      (:foreground "#b00000"))
743     (((class color)
744       (background light))
745      (:foreground "steel blue"))
746     (t
747      (:bold t :italic t)))
748   "Face used for displaying newsgroups headers."
749   :group 'message-faces)
750
751 (defface message-header-name-face
752   '((((class color)
753       (background dark))
754      (:foreground "DarkGreen"))
755     (((class color)
756       (background light))
757      (:foreground "cornflower blue"))
758     (t
759      (:bold t)))
760   "Face used for displaying header names."
761   :group 'message-faces)
762
763 (defface message-header-xheader-face
764   '((((class color)
765       (background dark))
766      (:foreground "blue"))
767     (((class color)
768       (background light))
769      (:foreground "blue"))
770     (t
771      (:bold t)))
772   "Face used for displaying X-Header headers."
773   :group 'message-faces)
774
775 (defface message-separator-face
776   '((((class color)
777       (background dark))
778      (:foreground "blue3"))
779     (((class color)
780       (background light))
781      (:foreground "brown"))
782     (t
783      (:bold t)))
784   "Face used for displaying the separator."
785   :group 'message-faces)
786
787 (defface message-cited-text-face
788   '((((class color)
789       (background dark))
790      (:foreground "red"))
791     (((class color)
792       (background light))
793      (:foreground "red"))
794     (t
795      (:bold t)))
796   "Face used for displaying cited text names."
797   :group 'message-faces)
798
799 (defface message-mml-face
800   '((((class color)
801       (background dark))
802      (:foreground "ForestGreen"))
803     (((class color)
804       (background light))
805      (:foreground "ForestGreen"))
806     (t
807      (:bold t)))
808   "Face used for displaying MML."
809   :group 'message-faces)
810
811 (defvar message-font-lock-keywords
812   (let* ((cite-prefix "A-Za-z")
813          (cite-suffix (concat cite-prefix "0-9_.@-"))
814          (content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)"))
815     `((,(concat "^\\([Tt]o:\\)" content)
816        (1 'message-header-name-face)
817        (2 'message-header-to-face nil t))
818       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
819        (1 'message-header-name-face)
820        (2 'message-header-cc-face nil t))
821       (,(concat "^\\([Ss]ubject:\\)" content)
822        (1 'message-header-name-face)
823        (2 'message-header-subject-face nil t))
824       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
825        (1 'message-header-name-face)
826        (2 'message-header-newsgroups-face nil t))
827       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
828        (1 'message-header-name-face)
829        (2 'message-header-other-face nil t))
830       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
831        (1 'message-header-name-face)
832        (2 'message-header-name-face))
833       ,@(if (and mail-header-separator
834                  (not (equal mail-header-separator "")))
835             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
836                1 'message-separator-face))
837           nil)
838       (,(concat "^[ \t]*"
839                 "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
840                 "[:>|}].*")
841        (0 'message-cited-text-face))
842       ("<#/?\\(multipart\\|part\\|external\\).*>"
843        (0 'message-mml-face))))
844   "Additional expressions to highlight in Message mode.")
845
846 ;; XEmacs does it like this.  For Emacs, we have to set the
847 ;; `font-lock-defaults' buffer-local variable.
848 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
849
850 (defvar message-face-alist
851   '((bold . bold-region)
852     (underline . underline-region)
853     (default . (lambda (b e)
854                  (unbold-region b e)
855                  (ununderline-region b e))))
856   "Alist of mail and news faces for facemenu.
857 The cdr of ech entry is a function for applying the face to a region.")
858
859 (defcustom message-send-hook nil
860   "Hook run before sending messages."
861   :group 'message-various
862   :options '(ispell-message)
863   :type 'hook)
864
865 (defcustom message-send-mail-hook nil
866   "Hook run before sending mail messages."
867   :group 'message-various
868   :type 'hook)
869
870 (defcustom message-send-news-hook nil
871   "Hook run before sending news messages."
872   :group 'message-various
873   :type 'hook)
874
875 (defcustom message-sent-hook nil
876   "Hook run after sending messages."
877   :group 'message-various
878   :type 'hook)
879
880 (defvar message-send-coding-system 'binary
881   "Coding system to encode outgoing mail.")
882
883 (defvar message-draft-coding-system
884   (cond
885    ((not (fboundp 'coding-system-p)) nil)
886    ((coding-system-p 'emacs-mule) 'emacs-mule)
887    ((coding-system-p 'escape-quoted) 'escape-quoted)
888    ((coding-system-p 'no-conversion) 'no-conversion)
889    (t nil))
890   "Coding system to compose mail.")
891
892 ;;; Internal variables.
893
894 (defvar message-buffer-list nil)
895 (defvar message-this-is-news nil)
896 (defvar message-this-is-mail nil)
897 (defvar message-draft-article nil)
898 (defvar message-mime-part nil)
899 (defvar message-posting-charset nil)
900
901 ;; Byte-compiler warning
902 (defvar gnus-active-hashtb)
903 (defvar gnus-read-active-file)
904
905 ;;; Regexp matching the delimiter of messages in UNIX mail format
906 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
907 ;;; of rmail.el's rmail-unix-mail-delimiter.
908 (defvar message-unix-mail-delimiter
909   (let ((time-zone-regexp
910          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
911                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
912                  "\\|"
913                  "\\) *")))
914     (concat
915      "From "
916
917      ;; Many things can happen to an RFC 822 mailbox before it is put into
918      ;; a `From' line.  The leading phrase can be stripped, e.g.
919      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
920      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
921      ;; can be removed, e.g.
922      ;;         From: joe@y.z (Joe      K
923      ;;                 User)
924      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
925      ;;         From: Joe User
926      ;;                 <joe@y.z>
927      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
928      ;; The mailbox can be removed or be replaced by white space, e.g.
929      ;;         From: "Joe User"{space}{tab}
930      ;;                 <joe@y.z>
931      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
932      ;; where {space} and {tab} represent the Ascii space and tab characters.
933      ;; We want to match the results of any of these manglings.
934      ;; The following regexp rejects names whose first characters are
935      ;; obviously bogus, but after that anything goes.
936      "\\([^\0-\b\n-\r\^?].*\\)? "
937
938      ;; The time the message was sent.
939      "\\([^\0-\r \^?]+\\) +"                            ; day of the week
940      "\\([^\0-\r \^?]+\\) +"                            ; month
941      "\\([0-3]?[0-9]\\) +"                              ; day of month
942      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"  ; time of day
943
944      ;; Perhaps a time zone, specified by an abbreviation, or by a
945      ;; numeric offset.
946      time-zone-regexp
947
948      ;; The year.
949      " \\([0-9][0-9]+\\) *"
950
951      ;; On some systems the time zone can appear after the year, too.
952      time-zone-regexp
953
954      ;; Old uucp cruft.
955      "\\(remote from .*\\)?"
956
957      "\n"))
958   "Regexp matching the delimiter of messages in UNIX mail format.")
959
960 (defvar message-unsent-separator
961   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
962           "^ *---+ +Returned message +---+ *$\\|"
963           "^Start of returned message$\\|"
964           "^ *---+ +Original message +---+ *$\\|"
965           "^ *--+ +begin message +--+ *$\\|"
966           "^ *---+ +Original message follows +---+ *$\\|"
967           "^|? *---+ +Message text follows: +---+ *|?$")
968   "A regexp that matches the separator before the text of a failed message.")
969
970 (defvar message-header-format-alist
971   `((Newsgroups)
972     (To . message-fill-address)
973     (Cc . message-fill-address)
974     (Subject)
975     (In-Reply-To)
976     (Fcc)
977     (Bcc)
978     (Date)
979     (Organization)
980     (Distribution)
981     (Lines)
982     (Expires)
983     (Message-ID)
984     (References . message-shorten-references)
985     (User-Agent))
986   "Alist used for formatting headers.")
987
988 (eval-and-compile
989   (autoload 'message-setup-toolbar "messagexmas")
990   (autoload 'mh-new-draft-name "mh-comp")
991   (autoload 'mh-send-letter "mh-comp")
992   (autoload 'gnus-point-at-eol "gnus-util")
993   (autoload 'gnus-point-at-bol "gnus-util")
994   (autoload 'gnus-output-to-mail "gnus-util")
995   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
996   (autoload 'nndraft-request-associate-buffer "nndraft")
997   (autoload 'nndraft-request-expire-articles "nndraft")
998   (autoload 'gnus-open-server "gnus-int")
999   (autoload 'gnus-request-post "gnus-int")
1000   (autoload 'gnus-alive-p "gnus-util")
1001   (autoload 'rmail-output "rmail"))
1002
1003 \f
1004
1005 ;;;
1006 ;;; Utility functions.
1007 ;;;
1008
1009 (defmacro message-y-or-n-p (question show &rest text)
1010   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1011   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1012
1013 ;; Delete the current line (and the next N lines.);
1014 (defmacro message-delete-line (&optional n)
1015   `(delete-region (progn (beginning-of-line) (point))
1016                   (progn (forward-line ,(or n 1)) (point))))
1017
1018 (defun message-tokenize-header (header &optional separator)
1019   "Split HEADER into a list of header elements.
1020 \",\" is used as the separator."
1021   (if (not header)
1022       nil
1023     (let ((regexp (format "[%s]+" (or separator ",")))
1024           (beg 1)
1025           (first t)
1026           quoted elems paren)
1027       (save-excursion
1028         (message-set-work-buffer)
1029         (insert header)
1030         (goto-char (point-min))
1031         (while (not (eobp))
1032           (if first
1033               (setq first nil)
1034             (forward-char 1))
1035           (cond ((and (> (point) beg)
1036                       (or (eobp)
1037                           (and (looking-at regexp)
1038                                (not quoted)
1039                                (not paren))))
1040                  (push (buffer-substring beg (point)) elems)
1041                  (setq beg (match-end 0)))
1042                 ((eq (char-after) ?\")
1043                  (setq quoted (not quoted)))
1044                 ((and (eq (char-after) ?\()
1045                       (not quoted))
1046                  (setq paren t))
1047                 ((and (eq (char-after) ?\))
1048                       (not quoted))
1049                  (setq paren nil))))
1050         (nreverse elems)))))
1051
1052 (defun message-mail-file-mbox-p (file)
1053   "Say whether FILE looks like a Unix mbox file."
1054   (when (and (file-exists-p file)
1055              (file-readable-p file)
1056              (file-regular-p file))
1057     (with-temp-buffer
1058       (nnheader-insert-file-contents file)
1059       (goto-char (point-min))
1060       (looking-at message-unix-mail-delimiter))))
1061
1062 (defun message-fetch-field (header &optional not-all)
1063   "The same as `mail-fetch-field', only remove all newlines."
1064   (let* ((inhibit-point-motion-hooks t)
1065          (value (mail-fetch-field header nil (not not-all))))
1066     (when value
1067       (while (string-match "\n[\t ]+" value)
1068         (setq value (replace-match " " t t value)))
1069       ;; We remove all text props.delete-region
1070       (format "%s" value))))
1071
1072 (defun message-narrow-to-field ()
1073   "Narrow the buffer to the header on the current line."
1074   (beginning-of-line)
1075   (narrow-to-region
1076    (point)
1077    (progn
1078      (forward-line 1)
1079      (if (re-search-forward "^[^ \n\t]" nil t)
1080          (progn
1081            (beginning-of-line)
1082            (point))
1083        (point-max))))
1084   (goto-char (point-min)))
1085
1086 (defun message-add-header (&rest headers)
1087   "Add the HEADERS to the message header, skipping those already present."
1088   (while headers
1089     (let (hclean)
1090       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1091         (error "Invalid header `%s'" (car headers)))
1092       (setq hclean (match-string 1 (car headers)))
1093     (save-restriction
1094       (message-narrow-to-headers)
1095       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1096         (insert (car headers) ?\n))))
1097     (setq headers (cdr headers))))
1098
1099 (defun message-fetch-reply-field (header)
1100   "Fetch FIELD from the message we're replying to."
1101   (when (and message-reply-buffer
1102              (buffer-name message-reply-buffer))
1103     (save-excursion
1104       (set-buffer message-reply-buffer)
1105       (message-fetch-field header))))
1106
1107 (defun message-set-work-buffer ()
1108   (if (get-buffer " *message work*")
1109       (progn
1110         (set-buffer " *message work*")
1111         (erase-buffer))
1112     (set-buffer (get-buffer-create " *message work*"))
1113     (kill-all-local-variables)
1114     (mm-enable-multibyte)))
1115
1116 (defun message-functionp (form)
1117   "Return non-nil if FORM is funcallable."
1118   (or (and (symbolp form) (fboundp form))
1119       (and (listp form) (eq (car form) 'lambda))
1120       (byte-code-function-p form)))
1121
1122 (defun message-strip-subject-re (subject)
1123   "Remove \"Re:\" from subject lines."
1124   (if (string-match message-subject-re-regexp subject)
1125       (substring subject (match-end 0))
1126     subject))
1127
1128 (defun message-remove-header (header &optional is-regexp first reverse)
1129   "Remove HEADER in the narrowed buffer.
1130 If REGEXP, HEADER is a regular expression.
1131 If FIRST, only remove the first instance of the header.
1132 Return the number of headers removed."
1133   (goto-char (point-min))
1134   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1135         (number 0)
1136         (case-fold-search t)
1137         last)
1138     (while (and (not (eobp))
1139                 (not last))
1140       (if (if reverse
1141               (not (looking-at regexp))
1142             (looking-at regexp))
1143           (progn
1144             (incf number)
1145             (when first
1146               (setq last t))
1147             (delete-region
1148              (point)
1149              ;; There might be a continuation header, so we have to search
1150              ;; until we find a new non-continuation line.
1151              (progn
1152                (forward-line 1)
1153                (if (re-search-forward "^[^ \t]" nil t)
1154                    (goto-char (match-beginning 0))
1155                  (point-max)))))
1156         (forward-line 1)
1157         (if (re-search-forward "^[^ \t]" nil t)
1158             (goto-char (match-beginning 0))
1159           (goto-char (point-max)))))
1160     number))
1161
1162 (defun message-remove-first-header (header)
1163   "Remove the first instance of HEADER if there is more than one."
1164   (let ((count 0)
1165         (regexp (concat "^" (regexp-quote header) ":")))
1166     (save-excursion
1167       (goto-char (point-min))
1168       (while (re-search-forward regexp nil t)
1169         (incf count)))
1170     (while (> count 1)
1171       (message-remove-header header nil t)
1172       (decf count))))
1173
1174 (defun message-narrow-to-headers ()
1175   "Narrow the buffer to the head of the message."
1176   (widen)
1177   (narrow-to-region
1178    (goto-char (point-min))
1179    (if (re-search-forward
1180         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1181        (match-beginning 0)
1182      (point-max)))
1183   (goto-char (point-min)))
1184
1185 (defun message-narrow-to-head ()
1186   "Narrow the buffer to the head of the message.
1187 Point is left at the beginning of the narrowed-to region."
1188   (widen)
1189   (narrow-to-region
1190    (goto-char (point-min))
1191    (if (search-forward "\n\n" nil 1)
1192        (1- (point))
1193      (point-max)))
1194   (goto-char (point-min)))
1195
1196 (defun message-narrow-to-headers-or-head ()
1197   "Narrow the buffer to the head of the message."
1198   (widen)
1199   (narrow-to-region
1200    (goto-char (point-min))
1201    (cond
1202     ((re-search-forward
1203       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1204      (match-beginning 0))
1205     ((search-forward "\n\n" nil t)
1206      (1- (point)))
1207     (t
1208      (point-max))))
1209   (goto-char (point-min)))
1210
1211 (defun message-news-p ()
1212   "Say whether the current buffer contains a news message."
1213   (and (not message-this-is-mail)
1214        (or message-this-is-news
1215            (save-excursion
1216              (save-restriction
1217                (message-narrow-to-headers)
1218                (and (message-fetch-field "newsgroups")
1219                     (not (message-fetch-field "posted-to"))))))))
1220
1221 (defun message-mail-p ()
1222   "Say whether the current buffer contains a mail message."
1223   (and (not message-this-is-news)
1224        (or message-this-is-mail
1225            (save-excursion
1226              (save-restriction
1227                (message-narrow-to-headers)
1228                (or (message-fetch-field "to")
1229                    (message-fetch-field "cc")
1230                    (message-fetch-field "bcc")))))))
1231
1232 (defun message-next-header ()
1233   "Go to the beginning of the next header."
1234   (beginning-of-line)
1235   (or (eobp) (forward-char 1))
1236   (not (if (re-search-forward "^[^ \t]" nil t)
1237            (beginning-of-line)
1238          (goto-char (point-max)))))
1239
1240 (defun message-sort-headers-1 ()
1241   "Sort the buffer as headers using `message-rank' text props."
1242   (goto-char (point-min))
1243   (sort-subr
1244    nil 'message-next-header
1245    (lambda ()
1246      (message-next-header)
1247      (unless (bobp)
1248        (forward-char -1)))
1249    (lambda ()
1250      (or (get-text-property (point) 'message-rank)
1251          10000))))
1252
1253 (defun message-sort-headers ()
1254   "Sort the headers of the current message according to `message-header-format-alist'."
1255   (interactive)
1256   (save-excursion
1257     (save-restriction
1258       (let ((max (1+ (length message-header-format-alist)))
1259             rank)
1260         (message-narrow-to-headers)
1261         (while (re-search-forward "^[^ \n]+:" nil t)
1262           (put-text-property
1263            (match-beginning 0) (1+ (match-beginning 0))
1264            'message-rank
1265            (if (setq rank (length (memq (assq (intern (buffer-substring
1266                                                        (match-beginning 0)
1267                                                        (1- (match-end 0))))
1268                                               message-header-format-alist)
1269                                         message-header-format-alist)))
1270                (- max rank)
1271              (1+ max)))))
1272       (message-sort-headers-1))))
1273
1274 \f
1275
1276 ;;;
1277 ;;; Message mode
1278 ;;;
1279
1280 ;;; Set up keymap.
1281
1282 (defvar message-mode-map nil)
1283
1284 (unless message-mode-map
1285   (setq message-mode-map (make-keymap))
1286   (set-keymap-parent message-mode-map text-mode-map)
1287   (define-key message-mode-map "\C-c?" 'describe-mode)
1288
1289   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1290   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1291   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1292   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1293   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1294   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1295   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1296   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1297   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1298   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1299   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1300   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1301   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1302
1303   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1304   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1305
1306   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1307   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1308   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1309   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1310   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1311   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1312   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1313
1314   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1315   (define-key message-mode-map "\C-c\C-s" 'message-send)
1316   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1317   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1318
1319   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1320   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1321   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1322   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1323
1324   (define-key message-mode-map "\C-c\C-a" 'message-mime-attach-file)
1325   (define-key message-mode-map "\C-c\C-m\C-a" 'message-mime-attach-file)
1326   (define-key message-mode-map "\C-c\C-m\C-e" 'message-mime-attach-external)
1327   (define-key message-mode-map "\C-c\C-m\C-q" 'mml-quote-region)
1328
1329   (define-key message-mode-map "\t" 'message-tab))
1330
1331 (easy-menu-define
1332  message-mode-menu message-mode-map "Message Menu."
1333  '("Message"
1334    ["Sort Headers" message-sort-headers t]
1335    ["Yank Original" message-yank-original t]
1336    ["Fill Yanked Message" message-fill-yanked-message t]
1337    ["Insert Signature" message-insert-signature t]
1338    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1339    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1340    ["Elide Region" message-elide-region (mark t)]
1341    ["Delete Outside Region" message-delete-not-region (mark t)]
1342    ["Kill To Signature" message-kill-to-signature t]
1343    ["Newline and Reformat" message-newline-and-reformat t]
1344    ["Rename buffer" message-rename-buffer t]
1345    ["Spellcheck" ispell-message t]
1346    ["Attach file as MIME" message-mime-attach-file t]
1347    "----"
1348    ["Send Message" message-send-and-exit t]
1349    ["Abort Message" message-dont-send t]
1350    ["Kill Message" message-kill-buffer t]))
1351
1352 (easy-menu-define
1353  message-mode-field-menu message-mode-map ""
1354  '("Field"
1355    ["Fetch To" message-insert-to t]
1356    ["Fetch Newsgroups" message-insert-newsgroups t]
1357    "----"
1358    ["To" message-goto-to t]
1359    ["Subject" message-goto-subject t]
1360    ["Cc" message-goto-cc t]
1361    ["Reply-To" message-goto-reply-to t]
1362    ["Summary" message-goto-summary t]
1363    ["Keywords" message-goto-keywords t]
1364    ["Newsgroups" message-goto-newsgroups t]
1365    ["Followup-To" message-goto-followup-to t]
1366    ["Distribution" message-goto-distribution t]
1367    ["Body" message-goto-body t]
1368    ["Signature" message-goto-signature t]))
1369
1370 (defvar facemenu-add-face-function)
1371 (defvar facemenu-remove-face-function)
1372
1373 ;;;###autoload
1374 (defun message-mode ()
1375   "Major mode for editing mail and news to be sent.
1376 Like Text Mode but with these additional commands:
1377 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1378 C-c C-f  move to a header field (and create it if there isn't):
1379          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1380          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1381          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1382          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1383          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1384          C-c C-f C-f  move to Followup-To
1385 C-c C-t  message-insert-to (add a To header to a news followup)
1386 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1387 C-c C-b  message-goto-body (move to beginning of message text).
1388 C-c C-i  message-goto-signature (move to the beginning of the signature).
1389 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1390 C-c C-y  message-yank-original (insert current message, if any).
1391 C-c C-q  message-fill-yanked-message (fill what was yanked).
1392 C-c C-e  message-elide-region (elide the text between point and mark).
1393 C-c C-v  message-delete-not-region (remove the text outside the region).
1394 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1395 C-c C-r  message-caesar-buffer-body (rot13 the message body).
1396 C-c C-a  message-mime-attach-file (attach a file as MIME)."
1397   (interactive)
1398   (kill-all-local-variables)
1399   (set (make-local-variable 'message-reply-buffer) nil)
1400   (make-local-variable 'message-send-actions)
1401   (make-local-variable 'message-exit-actions)
1402   (make-local-variable 'message-kill-actions)
1403   (make-local-variable 'message-postpone-actions)
1404   (make-local-variable 'message-draft-article)
1405   (make-local-hook 'kill-buffer-hook)
1406   (set-syntax-table message-mode-syntax-table)
1407   (use-local-map message-mode-map)
1408   (setq local-abbrev-table message-mode-abbrev-table)
1409   (setq major-mode 'message-mode)
1410   (setq mode-name "Message")
1411   (setq buffer-offer-save t)
1412   (make-local-variable 'facemenu-add-face-function)
1413   (make-local-variable 'facemenu-remove-face-function)
1414   (setq facemenu-add-face-function
1415         (lambda (face end)
1416           (let ((face-fun (cdr (assq face message-face-alist))))
1417             (if face-fun
1418                 (funcall face-fun (point) end)
1419               (error "Face %s not configured for %s mode" face mode-name)))
1420           "")
1421         facemenu-remove-face-function t)
1422   (make-local-variable 'paragraph-separate)
1423   (make-local-variable 'paragraph-start)
1424   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1425   ;; lines that delimit forwarded messages.
1426   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1427   ;; are also sometimes used and should be separators.
1428   (setq paragraph-start
1429         (concat (regexp-quote mail-header-separator)
1430                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1431                 "-- $\\|---+$\\|"
1432                 page-delimiter
1433                 ;;!!! Uhm... shurely this can't be right?
1434                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1435   (setq paragraph-separate paragraph-start)
1436   (make-local-variable 'message-reply-headers)
1437   (setq message-reply-headers nil)
1438   (make-local-variable 'message-newsreader)
1439   (make-local-variable 'message-mailer)
1440   (make-local-variable 'message-post-method)
1441   (set (make-local-variable 'message-sent-message-via) nil)
1442   (set (make-local-variable 'message-checksum) nil)
1443   (set (make-local-variable 'message-mime-part) 0)
1444   ;;(when (fboundp 'mail-hist-define-keys)
1445   ;;  (mail-hist-define-keys))
1446   (when (string-match "XEmacs\\|Lucid" emacs-version)
1447     (message-setup-toolbar))
1448   (easy-menu-add message-mode-menu message-mode-map)
1449   (easy-menu-add message-mode-field-menu message-mode-map)
1450   ;; Allow mail alias things.
1451   (when (eq message-mail-alias-type 'abbrev)
1452     (if (fboundp 'mail-abbrevs-setup)
1453         (mail-abbrevs-setup)
1454       (mail-aliases-setup)))
1455   (message-set-auto-save-file-name)
1456   (unless (string-match "XEmacs" emacs-version)
1457     (set (make-local-variable 'font-lock-defaults)
1458          '(message-font-lock-keywords t)))
1459   (make-local-variable 'adaptive-fill-regexp)
1460   (setq adaptive-fill-regexp
1461         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1462   (unless (boundp 'adaptive-fill-first-line-regexp)
1463     (setq adaptive-fill-first-line-regexp nil))
1464   (make-local-variable 'adaptive-fill-first-line-regexp)
1465   (setq adaptive-fill-first-line-regexp
1466         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1467                 adaptive-fill-first-line-regexp))
1468   (mm-enable-multibyte)
1469   (run-hooks 'text-mode-hook 'message-mode-hook))
1470
1471 \f
1472
1473 ;;;
1474 ;;; Message mode commands
1475 ;;;
1476
1477 ;;; Movement commands
1478
1479 (defun message-goto-to ()
1480   "Move point to the To header."
1481   (interactive)
1482   (message-position-on-field "To"))
1483
1484 (defun message-goto-subject ()
1485   "Move point to the Subject header."
1486   (interactive)
1487   (message-position-on-field "Subject"))
1488
1489 (defun message-goto-cc ()
1490   "Move point to the Cc header."
1491   (interactive)
1492   (message-position-on-field "Cc" "To"))
1493
1494 (defun message-goto-bcc ()
1495   "Move point to the Bcc  header."
1496   (interactive)
1497   (message-position-on-field "Bcc" "Cc" "To"))
1498
1499 (defun message-goto-fcc ()
1500   "Move point to the Fcc header."
1501   (interactive)
1502   (message-position-on-field "Fcc" "To" "Newsgroups"))
1503
1504 (defun message-goto-reply-to ()
1505   "Move point to the Reply-To header."
1506   (interactive)
1507   (message-position-on-field "Reply-To" "Subject"))
1508
1509 (defun message-goto-newsgroups ()
1510   "Move point to the Newsgroups header."
1511   (interactive)
1512   (message-position-on-field "Newsgroups"))
1513
1514 (defun message-goto-distribution ()
1515   "Move point to the Distribution header."
1516   (interactive)
1517   (message-position-on-field "Distribution"))
1518
1519 (defun message-goto-followup-to ()
1520   "Move point to the Followup-To header."
1521   (interactive)
1522   (message-position-on-field "Followup-To" "Newsgroups"))
1523
1524 (defun message-goto-keywords ()
1525   "Move point to the Keywords header."
1526   (interactive)
1527   (message-position-on-field "Keywords" "Subject"))
1528
1529 (defun message-goto-summary ()
1530   "Move point to the Summary header."
1531   (interactive)
1532   (message-position-on-field "Summary" "Subject"))
1533
1534 (defun message-goto-body ()
1535   "Move point to the beginning of the message body."
1536   (interactive)
1537   (if (looking-at "[ \t]*\n") (expand-abbrev))
1538   (goto-char (point-min))
1539   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1540
1541 (defun message-goto-eoh ()
1542   "Move point to the end of the headers."
1543   (interactive)
1544   (message-goto-body)
1545   (forward-line -2))
1546
1547 (defun message-goto-signature ()
1548   "Move point to the beginning of the message signature.
1549 If there is no signature in the article, go to the end and
1550 return nil."
1551   (interactive)
1552   (goto-char (point-min))
1553   (if (re-search-forward message-signature-separator nil t)
1554       (forward-line 1)
1555     (goto-char (point-max))
1556     nil))
1557
1558 \f
1559
1560 (defun message-insert-to (&optional force)
1561   "Insert a To header that points to the author of the article being replied to.
1562 If the original author requested not to be sent mail, the function signals
1563 an error.
1564 With the prefix argument FORCE, insert the header anyway."
1565   (interactive "P")
1566   (let ((co (message-fetch-reply-field "mail-copies-to")))
1567     (when (and (null force)
1568                co
1569                (or (equal (downcase co) "never")
1570                    (equal (downcase co) "nobody")))
1571       (error "The user has requested not to have copies sent via mail")))
1572   (when (and (message-position-on-field "To")
1573              (mail-fetch-field "to")
1574              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1575     (insert ", "))
1576   (insert (or (message-fetch-reply-field "reply-to")
1577               (message-fetch-reply-field "from") "")))
1578
1579 (defun message-insert-newsgroups ()
1580   "Insert the Newsgroups header from the article being replied to."
1581   (interactive)
1582   (when (and (message-position-on-field "Newsgroups")
1583              (mail-fetch-field "newsgroups")
1584              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1585     (insert ","))
1586   (insert (or (message-fetch-reply-field "newsgroups") "")))
1587
1588 \f
1589
1590 ;;; Various commands
1591
1592 (defun message-delete-not-region (beg end)
1593   "Delete everything in the body of the current message that is outside of the region."
1594   (interactive "r")
1595   (save-excursion
1596     (goto-char end)
1597     (delete-region (point) (if (not (message-goto-signature))
1598                                (point)
1599                              (forward-line -2)
1600                              (point)))
1601     (insert "\n")
1602     (goto-char beg)
1603     (delete-region beg (progn (message-goto-body)
1604                               (forward-line 2)
1605                               (point))))
1606   (when (message-goto-signature)
1607     (forward-line -2)))
1608
1609 (defun message-kill-to-signature ()
1610   "Deletes all text up to the signature."
1611   (interactive)
1612   (let ((point (point)))
1613     (message-goto-signature)
1614     (unless (eobp)
1615       (forward-line -2))
1616     (kill-region point (point))
1617     (unless (bolp)
1618       (insert "\n"))))
1619
1620 (defun message-newline-and-reformat ()
1621   "Insert four newlines, and then reformat if inside quoted text."
1622   (interactive)
1623   (let ((point (point))
1624         quoted)
1625     (save-excursion
1626       (beginning-of-line)
1627       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1628     (insert "\n\n\n\n")
1629     (when quoted
1630       (insert message-yank-prefix))
1631     (fill-paragraph nil)
1632     (goto-char point)
1633     (forward-line 2)))
1634
1635 (defun message-insert-signature (&optional force)
1636   "Insert a signature.  See documentation for the `message-signature' variable."
1637   (interactive (list 0))
1638   (let* ((signature
1639           (cond
1640            ((and (null message-signature)
1641                  (eq force 0))
1642             (save-excursion
1643               (goto-char (point-max))
1644               (not (re-search-backward message-signature-separator nil t))))
1645            ((and (null message-signature)
1646                  force)
1647             t)
1648            ((message-functionp message-signature)
1649             (funcall message-signature))
1650            ((listp message-signature)
1651             (eval message-signature))
1652            (t message-signature)))
1653          (signature
1654           (cond ((stringp signature)
1655                  signature)
1656                 ((and (eq t signature)
1657                       message-signature-file
1658                       (file-exists-p message-signature-file))
1659                  signature))))
1660     (when signature
1661       (goto-char (point-max))
1662       ;; Insert the signature.
1663       (unless (bolp)
1664         (insert "\n"))
1665       (insert "\n-- \n")
1666       (if (eq signature t)
1667           (insert-file-contents message-signature-file)
1668         (insert signature))
1669       (goto-char (point-max))
1670       (or (bolp) (insert "\n")))))
1671
1672 (defun message-elide-region (b e)
1673   "Elide the text between point and mark.
1674 An ellipsis (from `message-elide-elipsis') will be inserted where the
1675 text was killed."
1676   (interactive "r")
1677   (kill-region b e)
1678   (unless (bolp)
1679     (insert "\n"))
1680   (insert message-elide-elipsis))
1681
1682 (defvar message-caesar-translation-table nil)
1683
1684 (defun message-caesar-region (b e &optional n)
1685   "Caesar rotation of region by N, default 13, for decrypting netnews."
1686   (interactive
1687    (list
1688     (min (point) (or (mark t) (point)))
1689     (max (point) (or (mark t) (point)))
1690     (when current-prefix-arg
1691       (prefix-numeric-value current-prefix-arg))))
1692
1693   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1694   (unless (or (zerop n)                 ; no action needed for a rot of 0
1695               (= b e))                  ; no region to rotate
1696     ;; We build the table, if necessary.
1697     (when (or (not message-caesar-translation-table)
1698               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1699         (setq message-caesar-translation-table
1700               (message-make-caesar-translation-table n)))
1701     ;; Then we translate the region.  Do it this way to retain
1702     ;; text properties.
1703     (while (< b e)
1704       (when (< (char-after b) 255)
1705         (subst-char-in-region
1706          b (1+ b) (char-after b)
1707          (aref message-caesar-translation-table (char-after b))))
1708       (incf b))))
1709
1710 (defun message-make-caesar-translation-table (n)
1711   "Create a rot table with offset N."
1712   (let ((i -1)
1713         (table (make-string 256 0)))
1714     (while (< (incf i) 256)
1715       (aset table i i))
1716     (concat
1717      (substring table 0 ?A)
1718      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1719      (substring table ?A (+ ?A n))
1720      (substring table (+ ?A 26) ?a)
1721      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1722      (substring table ?a (+ ?a n))
1723      (substring table (+ ?a 26) 255))))
1724
1725 (defun message-caesar-buffer-body (&optional rotnum)
1726   "Caesar rotates all letters in the current buffer by 13 places.
1727 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1728 With prefix arg, specifies the number of places to rotate each letter forward.
1729 Mail and USENET news headers are not rotated."
1730   (interactive (if current-prefix-arg
1731                    (list (prefix-numeric-value current-prefix-arg))
1732                  (list nil)))
1733   (save-excursion
1734     (save-restriction
1735       (when (message-goto-body)
1736         (narrow-to-region (point) (point-max)))
1737       (message-caesar-region (point-min) (point-max) rotnum))))
1738
1739 (defun message-pipe-buffer-body (program)
1740   "Pipe the message body in the current buffer through PROGRAM."
1741   (save-excursion
1742     (save-restriction
1743       (when (message-goto-body)
1744         (narrow-to-region (point) (point-max)))
1745       (let ((body (buffer-substring (point-min) (point-max))))
1746         (unless (equal 0 (call-process-region
1747                            (point-min) (point-max) program t t))
1748             (insert body)
1749             (message "%s failed." program))))))
1750
1751 (defun message-rename-buffer (&optional enter-string)
1752   "Rename the *message* buffer to \"*message* RECIPIENT\".
1753 If the function is run with a prefix, it will ask for a new buffer
1754 name, rather than giving an automatic name."
1755   (interactive "Pbuffer name: ")
1756   (save-excursion
1757     (save-restriction
1758       (goto-char (point-min))
1759       (narrow-to-region (point)
1760                         (search-forward mail-header-separator nil 'end))
1761       (let* ((mail-to (or
1762                        (if (message-news-p) (message-fetch-field "Newsgroups")
1763                          (message-fetch-field "To"))
1764                        ""))
1765              (mail-trimmed-to
1766               (if (string-match "," mail-to)
1767                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1768                 mail-to))
1769              (name-default (concat "*message* " mail-trimmed-to))
1770              (name (if enter-string
1771                        (read-string "New buffer name: " name-default)
1772                      name-default)))
1773         (rename-buffer name t)))))
1774
1775 (defun message-fill-yanked-message (&optional justifyp)
1776   "Fill the paragraphs of a message yanked into this one.
1777 Numeric argument means justify as well."
1778   (interactive "P")
1779   (save-excursion
1780     (goto-char (point-min))
1781     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1782     (let ((fill-prefix message-yank-prefix))
1783       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1784
1785 (defun message-indent-citation ()
1786   "Modify text just inserted from a message to be cited.
1787 The inserted text should be the region.
1788 When this function returns, the region is again around the modified text.
1789
1790 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1791 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1792   (let ((start (point)))
1793     ;; Remove unwanted headers.
1794     (when message-ignored-cited-headers
1795       (let (all-removed)
1796         (save-restriction
1797           (narrow-to-region
1798            (goto-char start)
1799            (if (search-forward "\n\n" nil t)
1800                (1- (point))
1801              (point)))
1802           (message-remove-header message-ignored-cited-headers t)
1803           (when (= (point-min) (point-max))
1804             (setq all-removed t))
1805           (goto-char (point-max)))
1806         (if all-removed
1807             (goto-char start)
1808           (forward-line 1))))
1809     ;; Delete blank lines at the start of the buffer.
1810     (while (and (point-min)
1811                 (eolp)
1812                 (not (eobp)))
1813       (message-delete-line))
1814     ;; Delete blank lines at the end of the buffer.
1815     (goto-char (point-max))
1816     (unless (eolp)
1817       (insert "\n"))
1818     (while (and (zerop (forward-line -1))
1819                 (looking-at "$"))
1820       (message-delete-line))
1821     ;; Do the indentation.
1822     (if (null message-yank-prefix)
1823         (indent-rigidly start (mark t) message-indentation-spaces)
1824       (save-excursion
1825         (goto-char start)
1826         (while (< (point) (mark t))
1827           (insert message-yank-prefix)
1828           (forward-line 1))))
1829     (goto-char start)))
1830
1831 (defun message-yank-original (&optional arg)
1832   "Insert the message being replied to, if any.
1833 Puts point before the text and mark after.
1834 Normally indents each nonblank line ARG spaces (default 3).  However,
1835 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1836
1837 This function uses `message-cite-function' to do the actual citing.
1838
1839 Just \\[universal-argument] as argument means don't indent, insert no
1840 prefix, and don't delete any headers."
1841   (interactive "P")
1842   (let ((modified (buffer-modified-p)))
1843     (when (and message-reply-buffer
1844                message-cite-function)
1845       (delete-windows-on message-reply-buffer t)
1846       (insert-buffer message-reply-buffer)
1847       (funcall message-cite-function)
1848       (message-exchange-point-and-mark)
1849       (unless (bolp)
1850         (insert ?\n))
1851       (unless modified
1852         (setq message-checksum (message-checksum))))))
1853
1854 (defun message-cite-original-without-signature ()
1855   "Cite function in the standard Message manner."
1856   (let ((start (point))
1857         (end (mark t))
1858         (functions
1859          (when message-indent-citation-function
1860            (if (listp message-indent-citation-function)
1861                message-indent-citation-function
1862              (list message-indent-citation-function)))))
1863     (mml-quote-region start end)
1864     (goto-char end)
1865     (when (re-search-backward message-signature-separator start t)
1866       ;; Also peel off any blank lines before the signature.
1867       (forward-line -1)
1868       (while (looking-at "^[ \t]*$")
1869         (forward-line -1))
1870       (forward-line 1)
1871       (delete-region (point) end))
1872     (goto-char start)
1873     (while functions
1874       (funcall (pop functions)))
1875     (when message-citation-line-function
1876       (unless (bolp)
1877         (insert "\n"))
1878       (funcall message-citation-line-function))))
1879
1880 (defvar mail-citation-hook)             ;Compiler directive
1881 (defun message-cite-original ()
1882   "Cite function in the standard Message manner."
1883   (if (and (boundp 'mail-citation-hook)
1884            mail-citation-hook)
1885       (run-hooks 'mail-citation-hook)
1886     (let ((start (point))
1887           (end (mark t))
1888           (functions
1889            (when message-indent-citation-function
1890              (if (listp message-indent-citation-function)
1891                  message-indent-citation-function
1892                (list message-indent-citation-function)))))
1893       (mml-quote-region start end)
1894       (goto-char start)
1895       (while functions
1896         (funcall (pop functions)))
1897       (when message-citation-line-function
1898         (unless (bolp)
1899           (insert "\n"))
1900         (funcall message-citation-line-function)))))
1901
1902 (defun message-insert-citation-line ()
1903   "Function that inserts a simple citation line."
1904   (when message-reply-headers
1905     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1906
1907 (defun message-position-on-field (header &rest afters)
1908   (let ((case-fold-search t))
1909     (save-restriction
1910       (narrow-to-region
1911        (goto-char (point-min))
1912        (progn
1913          (re-search-forward
1914           (concat "^" (regexp-quote mail-header-separator) "$"))
1915          (match-beginning 0)))
1916       (goto-char (point-min))
1917       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1918           (progn
1919             (re-search-forward "^[^ \t]" nil 'move)
1920             (beginning-of-line)
1921             (skip-chars-backward "\n")
1922             t)
1923         (while (and afters
1924                     (not (re-search-forward
1925                           (concat "^" (regexp-quote (car afters)) ":")
1926                           nil t)))
1927           (pop afters))
1928         (when afters
1929           (re-search-forward "^[^ \t]" nil 'move)
1930           (beginning-of-line))
1931         (insert header ": \n")
1932         (forward-char -1)
1933         nil))))
1934
1935 (defun message-remove-signature ()
1936   "Remove the signature from the text between point and mark.
1937 The text will also be indented the normal way."
1938   (save-excursion
1939     (let ((start (point))
1940           mark)
1941       (if (not (re-search-forward message-signature-separator (mark t) t))
1942           ;; No signature here, so we just indent the cited text.
1943           (message-indent-citation)
1944         ;; Find the last non-empty line.
1945         (forward-line -1)
1946         (while (looking-at "[ \t]*$")
1947           (forward-line -1))
1948         (forward-line 1)
1949         (setq mark (set-marker (make-marker) (point)))
1950         (goto-char start)
1951         (message-indent-citation)
1952         ;; Enable undoing the deletion.
1953         (undo-boundary)
1954         (delete-region mark (mark t))
1955         (set-marker mark nil)))))
1956
1957 \f
1958
1959 ;;;
1960 ;;; Sending messages
1961 ;;;
1962
1963 (defun message-send-and-exit (&optional arg)
1964   "Send message like `message-send', then, if no errors, exit from mail buffer."
1965   (interactive "P")
1966   (let ((buf (current-buffer))
1967         (actions message-exit-actions))
1968     (when (and (message-send arg)
1969                (buffer-name buf))
1970       (if message-kill-buffer-on-exit
1971           (kill-buffer buf)
1972         (bury-buffer buf)
1973         (when (eq buf (current-buffer))
1974           (message-bury buf)))
1975       (message-do-actions actions)
1976       t)))
1977
1978 (defun message-dont-send ()
1979   "Don't send the message you have been editing."
1980   (interactive)
1981   (set-buffer-modified-p t)
1982   (save-buffer)
1983   (let ((actions message-postpone-actions))
1984     (message-bury (current-buffer))
1985     (message-do-actions actions)))
1986
1987 (defun message-kill-buffer ()
1988   "Kill the current buffer."
1989   (interactive)
1990   (when (or (not (buffer-modified-p))
1991             (yes-or-no-p "Message modified; kill anyway? "))
1992     (let ((actions message-kill-actions))
1993       (setq buffer-file-name nil)
1994       (kill-buffer (current-buffer))
1995       (message-do-actions actions))))
1996
1997 (defun message-bury (buffer)
1998   "Bury this mail buffer."
1999   (let ((newbuf (other-buffer buffer)))
2000     (bury-buffer buffer)
2001     (if (and (fboundp 'frame-parameters)
2002              (cdr (assq 'dedicated (frame-parameters)))
2003              (not (null (delq (selected-frame) (visible-frame-list)))))
2004         (delete-frame (selected-frame))
2005       (switch-to-buffer newbuf))))
2006
2007 (defun message-send (&optional arg)
2008   "Send the message in the current buffer.
2009 If `message-interactive' is non-nil, wait for success indication
2010 or error messages, and inform user.
2011 Otherwise any failure is reported in a message back to
2012 the user from the mailer."
2013   (interactive "P")
2014   ;; Make it possible to undo the coming changes.
2015   (undo-boundary)
2016   (let ((inhibit-read-only t))
2017     (put-text-property (point-min) (point-max) 'read-only nil))
2018   (message-fix-before-sending)
2019   (run-hooks 'message-send-hook)
2020   (message "Sending...")
2021   (let ((alist message-send-method-alist)
2022         (success t)
2023         elem sent)
2024     (while (and success
2025                 (setq elem (pop alist)))
2026       (when (and (or (not (funcall (cadr elem)))
2027                      (and (or (not (memq (car elem)
2028                                          message-sent-message-via))
2029                               (y-or-n-p
2030                                (format
2031                                 "Already sent message via %s; resend? "
2032                                 (car elem))))
2033                           (setq success (funcall (caddr elem) arg)))))
2034         (setq sent t)))
2035     (when (and success sent)
2036       (message-do-fcc)
2037       ;;(when (fboundp 'mail-hist-put-headers-into-history)
2038       ;; (mail-hist-put-headers-into-history))
2039       (save-excursion
2040         (run-hooks 'message-sent-hook))
2041       (message "Sending...done")
2042       ;; Mark the buffer as unmodified and delete auto-save.
2043       (set-buffer-modified-p nil)
2044       (delete-auto-save-file-if-necessary t)
2045       (message-disassociate-draft)
2046       ;; Delete other mail buffers and stuff.
2047       (message-do-send-housekeeping)
2048       (message-do-actions message-send-actions)
2049       ;; Return success.
2050       t)))
2051
2052 (defun message-send-via-mail (arg)
2053   "Send the current message via mail."
2054   (message-send-mail arg))
2055
2056 (defun message-send-via-news (arg)
2057   "Send the current message via news."
2058   (funcall message-send-news-function arg))
2059
2060 (defmacro message-check (type &rest forms)
2061   "Eval FORMS if TYPE is to be checked."
2062   `(or (message-check-element ,type)
2063        (save-excursion
2064          ,@forms)))
2065
2066 (put 'message-check 'lisp-indent-function 1)
2067 (put 'message-check 'edebug-form-spec '(form body))
2068
2069 (defun message-fix-before-sending ()
2070   "Do various things to make the message nice before sending it."
2071   ;; Make sure there's a newline at the end of the message.
2072   (goto-char (point-max))
2073   (unless (bolp)
2074     (insert "\n"))
2075   ;; Delete all invisible text.
2076   (message-check 'invisible-text
2077     (when (text-property-any (point-min) (point-max) 'invisible t)
2078       (put-text-property (point-min) (point-max) 'invisible nil)
2079       (unless (yes-or-no-p
2080                "Invisible text found and made visible; continue posting? ")
2081         (error "Invisible text found and made visible")))))
2082
2083 (defun message-add-action (action &rest types)
2084   "Add ACTION to be performed when doing an exit of type TYPES."
2085   (let (var)
2086     (while types
2087       (set (setq var (intern (format "message-%s-actions" (pop types))))
2088            (nconc (symbol-value var) (list action))))))
2089
2090 (defun message-do-actions (actions)
2091   "Perform all actions in ACTIONS."
2092   ;; Now perform actions on successful sending.
2093   (while actions
2094     (ignore-errors
2095       (cond
2096        ;; A simple function.
2097        ((message-functionp (car actions))
2098         (funcall (car actions)))
2099        ;; Something to be evaled.
2100        (t
2101         (eval (car actions)))))
2102     (pop actions)))
2103
2104 (defun message-send-mail (&optional arg)
2105   (require 'mail-utils)
2106   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2107         (case-fold-search nil)
2108         (news (message-news-p))
2109         (mailbuf (current-buffer)))
2110     (message-encode-message-body)
2111     (save-restriction
2112       (message-narrow-to-headers)
2113       ;; Insert some headers.
2114       (let ((message-deletable-headers
2115              (if news nil message-deletable-headers)))
2116         (message-generate-headers message-required-mail-headers))
2117       (let ((mail-parse-charset message-posting-charset))
2118         (mail-encode-encoded-word-buffer))
2119       ;; Let the user do all of the above.
2120       (run-hooks 'message-header-hook))
2121     (unwind-protect
2122         (save-excursion
2123           (set-buffer tembuf)
2124           (erase-buffer)
2125           ;; Avoid copying text props.
2126           (insert (format
2127                    "%s" (save-excursion
2128                           (set-buffer mailbuf)
2129                           (buffer-string))))
2130           ;; Remove some headers.
2131           (save-restriction
2132             (message-narrow-to-headers)
2133             ;; Remove some headers.
2134             (message-remove-header message-ignored-mail-headers t))
2135           (goto-char (point-max))
2136           ;; require one newline at the end.
2137           (or (= (preceding-char) ?\n)
2138               (insert ?\n))
2139           (when (and news
2140                      (or (message-fetch-field "cc")
2141                          (message-fetch-field "to")))
2142             (message-insert-courtesy-copy))
2143           (funcall message-send-mail-function))
2144       (kill-buffer tembuf))
2145     (set-buffer mailbuf)
2146     (push 'mail message-sent-message-via)))
2147
2148 (defun message-send-mail-with-sendmail ()
2149   "Send off the prepared buffer with sendmail."
2150   (let ((errbuf (if message-interactive
2151                     (generate-new-buffer " sendmail errors")
2152                   0))
2153         resend-to-addresses delimline)
2154     (let ((case-fold-search t))
2155       (save-restriction
2156         (message-narrow-to-headers)
2157         (setq resend-to-addresses (message-fetch-field "resent-to")))
2158       ;; Change header-delimiter to be what sendmail expects.
2159       (goto-char (point-min))
2160       (re-search-forward
2161        (concat "^" (regexp-quote mail-header-separator) "\n"))
2162       (replace-match "\n")
2163       (backward-char 1)
2164       (setq delimline (point-marker))
2165       (run-hooks 'message-send-mail-hook)
2166       ;; Insert an extra newline if we need it to work around
2167       ;; Sun's bug that swallows newlines.
2168       (goto-char (1+ delimline))
2169       (when (eval message-mailer-swallows-blank-line)
2170         (newline))
2171       (when message-interactive
2172         (save-excursion
2173           (set-buffer errbuf)
2174           (erase-buffer))))
2175     (let ((default-directory "/")
2176           (coding-system-for-write message-send-coding-system))
2177       (apply 'call-process-region
2178              (append (list (point-min) (point-max)
2179                            (if (boundp 'sendmail-program)
2180                                sendmail-program
2181                              "/usr/lib/sendmail")
2182                            nil errbuf nil "-oi")
2183                      ;; Always specify who from,
2184                      ;; since some systems have broken sendmails.
2185                      ;; But some systems are more broken with -f, so
2186                      ;; we'll let users override this.
2187                      (if (null message-sendmail-f-is-evil)
2188                          (list "-f" (user-login-name)))
2189                      ;; These mean "report errors by mail"
2190                      ;; and "deliver in background".
2191                      (if (null message-interactive) '("-oem" "-odb"))
2192                      ;; Get the addresses from the message
2193                      ;; unless this is a resend.
2194                      ;; We must not do that for a resend
2195                      ;; because we would find the original addresses.
2196                      ;; For a resend, include the specific addresses.
2197                      (if resend-to-addresses
2198                          (list resend-to-addresses)
2199                        '("-t")))))
2200     (when message-interactive
2201       (save-excursion
2202         (set-buffer errbuf)
2203         (goto-char (point-min))
2204         (while (re-search-forward "\n\n* *" nil t)
2205           (replace-match "; "))
2206         (if (not (zerop (buffer-size)))
2207             (error "Sending...failed to %s"
2208                    (buffer-substring (point-min) (point-max)))))
2209       (when (bufferp errbuf)
2210         (kill-buffer errbuf)))))
2211
2212 (defun message-send-mail-with-qmail ()
2213   "Pass the prepared message buffer to qmail-inject.
2214 Refer to the documentation for the variable `message-send-mail-function'
2215 to find out how to use this."
2216   ;; replace the header delimiter with a blank line
2217   (goto-char (point-min))
2218   (re-search-forward
2219    (concat "^" (regexp-quote mail-header-separator) "\n"))
2220   (replace-match "\n")
2221   (run-hooks 'message-send-mail-hook)
2222   ;; send the message
2223   (case
2224       (let ((coding-system-for-write message-send-coding-system))
2225         (apply
2226          'call-process-region 1 (point-max) message-qmail-inject-program
2227          nil nil nil
2228          ;; qmail-inject's default behaviour is to look for addresses on the
2229          ;; command line; if there're none, it scans the headers.
2230          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2231          ;;
2232          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2233          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2234          ;; message from stdin.
2235          ;;
2236          ;; qmail also has the advantage of not having been raped by
2237          ;; various vendors, so we don't have to allow for that, either --
2238          ;; compare this with message-send-mail-with-sendmail and weep
2239          ;; for sendmail's lost innocence.
2240          ;;
2241          ;; all this is way cool coz it lets us keep the arguments entirely
2242          ;; free for -inject-arguments -- a big win for the user and for us
2243          ;; since we don't have to play that double-guessing game and the user
2244          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2245          message-qmail-inject-args))
2246     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2247     ;; we have to look at the retval instead
2248     (0 nil)
2249     (1   (error "qmail-inject reported permanent failure"))
2250     (111 (error "qmail-inject reported transient failure"))
2251     ;; should never happen
2252     (t   (error "qmail-inject reported unknown failure"))))
2253
2254 (defun message-send-mail-with-mh ()
2255   "Send the prepared message buffer with mh."
2256   (let ((mh-previous-window-config nil)
2257         (name (mh-new-draft-name)))
2258     (setq buffer-file-name name)
2259     ;; MH wants to generate these headers itself.
2260     (when message-mh-deletable-headers
2261       (let ((headers message-mh-deletable-headers))
2262         (while headers
2263           (goto-char (point-min))
2264           (and (re-search-forward
2265                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2266                (message-delete-line))
2267           (pop headers))))
2268     (run-hooks 'message-send-mail-hook)
2269     ;; Pass it on to mh.
2270     (mh-send-letter)))
2271
2272 (defun message-send-news (&optional arg)
2273   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2274         (case-fold-search nil)
2275         (method (if (message-functionp message-post-method)
2276                     (funcall message-post-method arg)
2277                   message-post-method))
2278         (messbuf (current-buffer))
2279         (message-syntax-checks
2280          (if arg
2281              (cons '(existing-newsgroups . disabled)
2282                    message-syntax-checks)
2283            message-syntax-checks))
2284         result)
2285     (if (not (message-check-news-body-syntax))
2286         nil
2287       (message-encode-message-body)
2288       (save-restriction
2289         (message-narrow-to-headers)
2290         ;; Insert some headers.
2291         (message-generate-headers message-required-news-headers)
2292         (let ((mail-parse-charset message-posting-charset))
2293           (mail-encode-encoded-word-buffer))
2294         ;; Let the user do all of the above.
2295         (run-hooks 'message-header-hook))
2296       (message-cleanup-headers)
2297       (if (not (message-check-news-syntax))
2298           nil
2299         (unwind-protect
2300             (save-excursion
2301               (set-buffer tembuf)
2302               (buffer-disable-undo)
2303               (erase-buffer)
2304               ;; Avoid copying text props.
2305               (insert (format
2306                        "%s" (save-excursion
2307                               (set-buffer messbuf)
2308                               (buffer-string))))
2309               ;; Remove some headers.
2310               (save-restriction
2311                 (message-narrow-to-headers)
2312                 ;; Remove some headers.
2313                 (message-remove-header message-ignored-news-headers t))
2314               (goto-char (point-max))
2315               ;; require one newline at the end.
2316               (or (= (preceding-char) ?\n)
2317                   (insert ?\n))
2318               (let ((case-fold-search t))
2319                 ;; Remove the delimiter.
2320                 (goto-char (point-min))
2321                 (re-search-forward
2322                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2323                 (replace-match "\n")
2324                 (backward-char 1))
2325               (run-hooks 'message-send-news-hook)
2326               (gnus-open-server method)
2327             (setq result (let ((mail-header-separator ""))
2328                            (gnus-request-post method))))
2329           (kill-buffer tembuf))
2330         (set-buffer messbuf)
2331         (if result
2332             (push 'news message-sent-message-via)
2333           (message "Couldn't send message via news: %s"
2334                    (nnheader-get-report (car method)))
2335           nil)))))
2336
2337 ;;;
2338 ;;; Header generation & syntax checking.
2339 ;;;
2340
2341 (defun message-check-element (type)
2342   "Returns non-nil if this type is not to be checked."
2343   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2344       t
2345     (let ((able (assq type message-syntax-checks)))
2346       (and (consp able)
2347            (eq (cdr able) 'disabled)))))
2348
2349 (defun message-check-news-syntax ()
2350   "Check the syntax of the message."
2351   (save-excursion
2352     (save-restriction
2353       (widen)
2354       ;; We narrow to the headers and check them first.
2355       (save-excursion
2356         (save-restriction
2357           (message-narrow-to-headers)
2358           (message-check-news-header-syntax))))))
2359
2360 (defun message-check-news-header-syntax ()
2361   (and
2362    ;; Check the Subject header.
2363    (message-check 'subject
2364      (let* ((case-fold-search t)
2365             (subject (message-fetch-field "subject")))
2366        (or
2367         (and subject
2368              (not (string-match "\\`[ \t]*\\'" subject)))
2369         (ignore
2370          (message
2371           "The subject field is empty or missing.  Posting is denied.")))))
2372    ;; Check for commands in Subject.
2373    (message-check 'subject-cmsg
2374      (if (string-match "^cmsg " (message-fetch-field "subject"))
2375          (y-or-n-p
2376           "The control code \"cmsg\" is in the subject.  Really post? ")
2377        t))
2378    ;; Check for multiple identical headers.
2379    (message-check 'multiple-headers
2380      (let (found)
2381        (while (and (not found)
2382                    (re-search-forward "^[^ \t:]+: " nil t))
2383          (save-excursion
2384            (or (re-search-forward
2385                 (concat "^"
2386                         (regexp-quote
2387                          (setq found
2388                                (buffer-substring
2389                                 (match-beginning 0) (- (match-end 0) 2))))
2390                         ":")
2391                 nil t)
2392                (setq found nil))))
2393        (if found
2394            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2395          t)))
2396    ;; Check for Version and Sendsys.
2397    (message-check 'sendsys
2398      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2399          (y-or-n-p
2400           (format "The article contains a %s command.  Really post? "
2401                   (buffer-substring (match-beginning 0)
2402                                     (1- (match-end 0)))))
2403        t))
2404    ;; See whether we can shorten Followup-To.
2405    (message-check 'shorten-followup-to
2406      (let ((newsgroups (message-fetch-field "newsgroups"))
2407            (followup-to (message-fetch-field "followup-to"))
2408            to)
2409        (when (and newsgroups
2410                   (string-match "," newsgroups)
2411                   (not followup-to)
2412                   (not
2413                    (zerop
2414                     (length
2415                      (setq to (completing-read
2416                                "Followups to: (default all groups) "
2417                                (mapcar (lambda (g) (list g))
2418                                        (cons "poster"
2419                                              (message-tokenize-header
2420                                               newsgroups)))))))))
2421          (goto-char (point-min))
2422          (insert "Followup-To: " to "\n"))
2423        t))
2424    ;; Check "Shoot me".
2425    (message-check 'shoot
2426      (if (re-search-forward
2427           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2428          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2429        t))
2430    ;; Check for Approved.
2431    (message-check 'approved
2432      (if (re-search-forward "^Approved:" nil t)
2433          (y-or-n-p "The article contains an Approved header.  Really post? ")
2434        t))
2435    ;; Check the Message-ID header.
2436    (message-check 'message-id
2437      (let* ((case-fold-search t)
2438             (message-id (message-fetch-field "message-id" t)))
2439        (or (not message-id)
2440            ;; Is there an @ in the ID?
2441            (and (string-match "@" message-id)
2442                 ;; Is there a dot in the ID?
2443                 (string-match "@[^.]*\\." message-id)
2444                 ;; Does the ID end with a dot?
2445                 (not (string-match "\\.>" message-id)))
2446            (y-or-n-p
2447             (format "The Message-ID looks strange: \"%s\".  Really post? "
2448                     message-id)))))
2449    ;; Check the Newsgroups & Followup-To headers.
2450    (message-check 'existing-newsgroups
2451      (let* ((case-fold-search t)
2452             (newsgroups (message-fetch-field "newsgroups"))
2453             (followup-to (message-fetch-field "followup-to"))
2454             (groups (message-tokenize-header
2455                      (if followup-to
2456                          (concat newsgroups "," followup-to)
2457                        newsgroups)))
2458             (hashtb (and (boundp 'gnus-active-hashtb)
2459                          gnus-active-hashtb))
2460             errors)
2461        (if (or (not hashtb)
2462                (not (boundp 'gnus-read-active-file))
2463                (not gnus-read-active-file)
2464                (eq gnus-read-active-file 'some))
2465            t
2466          (while groups
2467            (when (and (not (boundp (intern (car groups) hashtb)))
2468                       (not (equal (car groups) "poster")))
2469              (push (car groups) errors))
2470            (pop groups))
2471          (if (not errors)
2472              t
2473            (y-or-n-p
2474             (format
2475              "Really post to %s unknown group%s: %s "
2476              (if (= (length errors) 1) "this" "these")
2477              (if (= (length errors) 1) "" "s")
2478              (mapconcat 'identity errors ", ")))))))
2479    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2480    (message-check 'valid-newsgroups
2481      (let ((case-fold-search t)
2482            (headers '("Newsgroups" "Followup-To"))
2483            header error)
2484        (while (and headers (not error))
2485          (when (setq header (mail-fetch-field (car headers)))
2486            (if (or
2487                 (not
2488                  (string-match
2489                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2490                   header))
2491                 (memq
2492                  nil (mapcar
2493                       (lambda (g)
2494                         (not (string-match "\\.\\'\\|\\.\\." g)))
2495                       (message-tokenize-header header ","))))
2496                (setq error t)))
2497          (unless error
2498            (pop headers)))
2499        (if (not error)
2500            t
2501          (y-or-n-p
2502           (format "The %s header looks odd: \"%s\".  Really post? "
2503                   (car headers) header)))))
2504    (message-check 'repeated-newsgroups
2505      (let ((case-fold-search t)
2506            (headers '("Newsgroups" "Followup-To"))
2507            header error groups group)
2508        (while (and headers
2509                    (not error))
2510          (when (setq header (mail-fetch-field (pop headers)))
2511            (setq groups (message-tokenize-header header ","))
2512            (while (setq group (pop groups))
2513              (when (member group groups)
2514                (setq error group
2515                      groups nil)))))
2516        (if (not error)
2517            t
2518          (y-or-n-p
2519           (format "Group %s is repeated in headers.  Really post? " error)))))
2520    ;; Check the From header.
2521    (message-check 'from
2522      (let* ((case-fold-search t)
2523             (from (message-fetch-field "from"))
2524             (ad (nth 1 (mail-extract-address-components from))))
2525        (cond
2526         ((not from)
2527          (message "There is no From line.  Posting is denied.")
2528          nil)
2529         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2530              (string-match "\\.\\." ad) ;larsi@ifi..uio
2531              (string-match "@\\." ad)   ;larsi@.ifi.uio
2532              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2533              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2534              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2535          (message
2536           "Denied posting -- the From looks strange: \"%s\"." from)
2537          nil)
2538         (t t))))))
2539
2540 (defun message-check-news-body-syntax ()
2541   (and
2542    ;; Check for long lines.
2543    (message-check 'long-lines
2544      (goto-char (point-min))
2545      (re-search-forward
2546       (concat "^" (regexp-quote mail-header-separator) "$"))
2547      (while (and
2548              (progn
2549                (end-of-line)
2550                (< (current-column) 80))
2551              (zerop (forward-line 1))))
2552      (or (bolp)
2553          (eobp)
2554          (y-or-n-p
2555           "You have lines longer than 79 characters.  Really post? ")))
2556    ;; Check whether the article is empty.
2557    (message-check 'empty
2558      (goto-char (point-min))
2559      (re-search-forward
2560       (concat "^" (regexp-quote mail-header-separator) "$"))
2561      (forward-line 1)
2562      (let ((b (point)))
2563        (goto-char (point-max))
2564        (re-search-backward message-signature-separator nil t)
2565        (beginning-of-line)
2566        (or (re-search-backward "[^ \n\t]" b t)
2567            (y-or-n-p "Empty article.  Really post? "))))
2568    ;; Check for control characters.
2569    (message-check 'control-chars
2570      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2571          (y-or-n-p
2572           "The article contains control characters.  Really post? ")
2573        t))
2574    ;; Check excessive size.
2575    (message-check 'size
2576      (if (> (buffer-size) 60000)
2577          (y-or-n-p
2578           (format "The article is %d octets long.  Really post? "
2579                   (buffer-size)))
2580        t))
2581    ;; Check whether any new text has been added.
2582    (message-check 'new-text
2583      (or
2584       (not message-checksum)
2585       (not (eq (message-checksum) message-checksum))
2586       (y-or-n-p
2587        "It looks like no new text has been added.  Really post? ")))
2588    ;; Check the length of the signature.
2589    (message-check 'signature
2590      (goto-char (point-max))
2591      (if (or (not (re-search-backward message-signature-separator nil t))
2592              (search-forward message-forward-end-separator nil t))
2593          t
2594        (if (> (count-lines (point) (point-max)) 5)
2595            (y-or-n-p
2596             (format
2597              "Your .sig is %d lines; it should be max 4.  Really post? "
2598              (1- (count-lines (point) (point-max)))))
2599          t)))))
2600
2601 (defun message-checksum ()
2602   "Return a \"checksum\" for the current buffer."
2603   (let ((sum 0))
2604     (save-excursion
2605       (goto-char (point-min))
2606       (re-search-forward
2607        (concat "^" (regexp-quote mail-header-separator) "$"))
2608       (while (not (eobp))
2609         (when (not (looking-at "[ \t\n]"))
2610           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2611                             (char-after))))
2612         (forward-char 1)))
2613     sum))
2614
2615 (defun message-do-fcc ()
2616   "Process Fcc headers in the current buffer."
2617   (let ((case-fold-search t)
2618         (buf (current-buffer))
2619         list file)
2620     (save-excursion
2621       (set-buffer (get-buffer-create " *message temp*"))
2622       (erase-buffer)
2623       (insert-buffer-substring buf)
2624       (save-restriction
2625         (message-narrow-to-headers)
2626         (while (setq file (message-fetch-field "fcc"))
2627           (push file list)
2628           (message-remove-header "fcc" nil t)))
2629       (goto-char (point-min))
2630       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2631       (replace-match "" t t)
2632       ;; Process FCC operations.
2633       (while list
2634         (setq file (pop list))
2635         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2636             ;; Pipe the article to the program in question.
2637             (call-process-region (point-min) (point-max) shell-file-name
2638                                  nil nil nil shell-command-switch
2639                                  (match-string 1 file))
2640           ;; Save the article.
2641           (setq file (expand-file-name file))
2642           (unless (file-exists-p (file-name-directory file))
2643             (make-directory (file-name-directory file) t))
2644           (if (and message-fcc-handler-function
2645                    (not (eq message-fcc-handler-function 'rmail-output)))
2646               (funcall message-fcc-handler-function file)
2647             (if (and (file-readable-p file) (mail-file-babyl-p file))
2648                 (rmail-output file 1 nil t)
2649               (let ((mail-use-rfc822 t))
2650                 (rmail-output file 1 t t))))))
2651
2652       (kill-buffer (current-buffer)))))
2653
2654 (defun message-output (filename)
2655   "Append this article to Unix/babyl mail file.."
2656   (if (and (file-readable-p filename)
2657            (mail-file-babyl-p filename))
2658       (rmail-output-to-rmail-file filename t)
2659     (gnus-output-to-mail filename t)))
2660
2661 (defun message-cleanup-headers ()
2662   "Do various automatic cleanups of the headers."
2663   ;; Remove empty lines in the header.
2664   (save-restriction
2665     (message-narrow-to-headers)
2666     ;; Remove blank lines.
2667     (while (re-search-forward "^[ \t]*\n" nil t)
2668       (replace-match "" t t))
2669
2670     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2671     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2672     ;; embedded line breaks.
2673     (goto-char (point-min))
2674     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2675       (save-restriction
2676         (narrow-to-region
2677          (point)
2678          (if (re-search-forward "^[^ \t]" nil t)
2679              (match-beginning 0)
2680            (forward-line 1)
2681            (point)))
2682         (goto-char (point-min))
2683         (while (re-search-forward "\n[ \t]+" nil t)
2684           (replace-match " " t t))      ;No line breaks (too confusing)
2685         (goto-char (point-min))
2686         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2687           (replace-match "," t t))
2688         (goto-char (point-min))
2689         ;; Remove trailing commas.
2690         (when (re-search-forward ",+$" nil t)
2691           (replace-match "" t t))))))
2692
2693 (defun message-make-date (&optional now)
2694   "Make a valid data header.
2695 If NOW, use that time instead."
2696   (let* ((now (or now (current-time)))
2697          (zone (nth 8 (decode-time now)))
2698          (sign "+"))
2699     (when (< zone 0)
2700       (setq sign "-")
2701       (setq zone (- zone)))
2702     (concat
2703      (format-time-string "%d" now)
2704      ;; The month name of the %b spec is locale-specific.  Pfff.
2705      (format " %s "
2706              (capitalize (car (rassoc (nth 4 (decode-time now))
2707                                       parse-time-months))))
2708      (format-time-string "%Y %H:%M:%S " now)
2709      ;; We do all of this because XEmacs doesn't have the %z spec.
2710      (format "%s%02d%02d" sign (/ zone 3600) (% zone 3600)))))
2711
2712 (defun message-make-message-id ()
2713   "Make a unique Message-ID."
2714   (concat "<" (message-unique-id)
2715           (let ((psubject (save-excursion (message-fetch-field "subject")))
2716                 (psupersedes
2717                  (save-excursion (message-fetch-field "supersedes"))))
2718             (if (or
2719                  (and message-reply-headers
2720                       (mail-header-references message-reply-headers)
2721                       (mail-header-subject message-reply-headers)
2722                       psubject
2723                       (mail-header-subject message-reply-headers)
2724                       (not (string=
2725                             (message-strip-subject-re
2726                              (mail-header-subject message-reply-headers))
2727                             (message-strip-subject-re psubject))))
2728                  (and psupersedes
2729                       (string-match "_-_@" psupersedes)))
2730                 "_-_" ""))
2731           "@" (message-make-fqdn) ">"))
2732
2733 (defvar message-unique-id-char nil)
2734
2735 ;; If you ever change this function, make sure the new version
2736 ;; cannot generate IDs that the old version could.
2737 ;; You might for example insert a "." somewhere (not next to another dot
2738 ;; or string boundary), or modify the "fsf" string.
2739 (defun message-unique-id ()
2740   ;; Don't use microseconds from (current-time), they may be unsupported.
2741   ;; Instead we use this randomly inited counter.
2742   (setq message-unique-id-char
2743         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2744            ;; (current-time) returns 16-bit ints,
2745            ;; and 2^16*25 just fits into 4 digits i base 36.
2746            (* 25 25)))
2747   (let ((tm (current-time)))
2748     (concat
2749      (if (memq system-type '(ms-dos emx vax-vms))
2750          (let ((user (downcase (user-login-name))))
2751            (while (string-match "[^a-z0-9_]" user)
2752              (aset user (match-beginning 0) ?_))
2753            user)
2754        (message-number-base36 (user-uid) -1))
2755      (message-number-base36 (+ (car   tm)
2756                                (lsh (% message-unique-id-char 25) 16)) 4)
2757      (message-number-base36 (+ (nth 1 tm)
2758                                (lsh (/ message-unique-id-char 25) 16)) 4)
2759      ;; Append the newsreader name, because while the generated
2760      ;; ID is unique to this newsreader, other newsreaders might
2761      ;; otherwise generate the same ID via another algorithm.
2762      ".fsf")))
2763
2764 (defun message-number-base36 (num len)
2765   (if (if (< len 0)
2766           (<= num 0)
2767         (= len 0))
2768       ""
2769     (concat (message-number-base36 (/ num 36) (1- len))
2770             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2771                                   (% num 36))))))
2772
2773 (defun message-make-organization ()
2774   "Make an Organization header."
2775   (let* ((organization
2776           (when message-user-organization
2777                 (if (message-functionp message-user-organization)
2778                     (funcall message-user-organization)
2779                   message-user-organization))))
2780     (save-excursion
2781       (message-set-work-buffer)
2782       (cond ((stringp organization)
2783              (insert organization))
2784             ((and (eq t organization)
2785                   message-user-organization-file
2786                   (file-exists-p message-user-organization-file))
2787              (insert-file-contents message-user-organization-file)))
2788       (goto-char (point-min))
2789       (while (re-search-forward "[\t\n]+" nil t)
2790         (replace-match "" t t))
2791       (unless (zerop (buffer-size))
2792         (buffer-string)))))
2793
2794 (defun message-make-lines ()
2795   "Count the number of lines and return numeric string."
2796   (save-excursion
2797     (save-restriction
2798       (widen)
2799       (goto-char (point-min))
2800       (re-search-forward
2801        (concat "^" (regexp-quote mail-header-separator) "$"))
2802       (forward-line 1)
2803       (int-to-string (count-lines (point) (point-max))))))
2804
2805 (defun message-make-in-reply-to ()
2806   "Return the In-Reply-To header for this message."
2807   (when message-reply-headers
2808     (let ((from (mail-header-from message-reply-headers))
2809           (date (mail-header-date message-reply-headers)))
2810       (when from
2811         (let ((stop-pos
2812                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2813           (concat (if (and stop-pos
2814                            (not (zerop stop-pos)))
2815                       (substring from 0 stop-pos) from)
2816                   "'s message of \""
2817                   (if (or (not date) (string= date ""))
2818                       "(unknown date)" date)
2819                   "\""))))))
2820
2821 (defun message-make-distribution ()
2822   "Make a Distribution header."
2823   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2824     (cond ((message-functionp message-distribution-function)
2825            (funcall message-distribution-function))
2826           (t orig-distribution))))
2827
2828 (defun message-make-expires ()
2829   "Return an Expires header based on `message-expires'."
2830   (let ((current (current-time))
2831         (future (* 1.0 message-expires 60 60 24)))
2832     ;; Add the future to current.
2833     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2834     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2835     (message-make-date current)))
2836
2837 (defun message-make-path ()
2838   "Return uucp path."
2839   (let ((login-name (user-login-name)))
2840     (cond ((null message-user-path)
2841            (concat (system-name) "!" login-name))
2842           ((stringp message-user-path)
2843            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2844            (concat message-user-path "!" login-name))
2845           (t login-name))))
2846
2847 (defun message-make-from ()
2848   "Make a From header."
2849   (let* ((style message-from-style)
2850          (login (message-make-address))
2851          (fullname
2852           (or (and (boundp 'user-full-name)
2853                    user-full-name)
2854               (user-full-name))))
2855     (when (string= fullname "&")
2856       (setq fullname (user-login-name)))
2857     (save-excursion
2858       (message-set-work-buffer)
2859       (cond
2860        ((or (null style)
2861             (equal fullname ""))
2862         (insert login))
2863        ((or (eq style 'angles)
2864             (and (not (eq style 'parens))
2865                  ;; Use angles if no quoting is needed, or if parens would
2866                  ;; need quoting too.
2867                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2868                      (let ((tmp (concat fullname nil)))
2869                        (while (string-match "([^()]*)" tmp)
2870                          (aset tmp (match-beginning 0) ?-)
2871                          (aset tmp (1- (match-end 0)) ?-))
2872                        (string-match "[\\()]" tmp)))))
2873         (insert fullname)
2874         (goto-char (point-min))
2875         ;; Look for a character that cannot appear unquoted
2876         ;; according to RFC 822.
2877         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2878           ;; Quote fullname, escaping specials.
2879           (goto-char (point-min))
2880           (insert "\"")
2881           (while (re-search-forward "[\"\\]" nil 1)
2882             (replace-match "\\\\\\&" t))
2883           (insert "\""))
2884         (insert " <" login ">"))
2885        (t                               ; 'parens or default
2886         (insert login " (")
2887         (let ((fullname-start (point)))
2888           (insert fullname)
2889           (goto-char fullname-start)
2890           ;; RFC 822 says \ and nonmatching parentheses
2891           ;; must be escaped in comments.
2892           ;; Escape every instance of ()\ ...
2893           (while (re-search-forward "[()\\]" nil 1)
2894             (replace-match "\\\\\\&" t))
2895           ;; ... then undo escaping of matching parentheses,
2896           ;; including matching nested parentheses.
2897           (goto-char fullname-start)
2898           (while (re-search-forward
2899                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2900                   nil 1)
2901             (replace-match "\\1(\\3)" t)
2902             (goto-char fullname-start)))
2903         (insert ")")))
2904       (buffer-string))))
2905
2906 (defun message-make-sender ()
2907   "Return the \"real\" user address.
2908 This function tries to ignore all user modifications, and
2909 give as trustworthy answer as possible."
2910   (concat (user-login-name) "@" (system-name)))
2911
2912 (defun message-make-address ()
2913   "Make the address of the user."
2914   (or (message-user-mail-address)
2915       (concat (user-login-name) "@" (message-make-domain))))
2916
2917 (defun message-user-mail-address ()
2918   "Return the pertinent part of `user-mail-address'."
2919   (when user-mail-address
2920     (if (string-match " " user-mail-address)
2921         (nth 1 (mail-extract-address-components user-mail-address))
2922       user-mail-address)))
2923
2924 (defun message-make-fqdn ()
2925   "Return user's fully qualified domain name."
2926   (let ((system-name (system-name))
2927         (user-mail (message-user-mail-address)))
2928     (cond
2929      ((string-match "[^.]\\.[^.]" system-name)
2930       ;; `system-name' returned the right result.
2931       system-name)
2932      ;; Try `mail-host-address'.
2933      ((and (boundp 'mail-host-address)
2934            (stringp mail-host-address)
2935            (string-match "\\." mail-host-address))
2936       mail-host-address)
2937      ;; We try `user-mail-address' as a backup.
2938      ((and user-mail
2939            (string-match "\\." user-mail)
2940            (string-match "@\\(.*\\)\\'" user-mail))
2941       (match-string 1 user-mail))
2942      ;; Default to this bogus thing.
2943      (t
2944       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2945
2946 (defun message-make-host-name ()
2947   "Return the name of the host."
2948   (let ((fqdn (message-make-fqdn)))
2949     (string-match "^[^.]+\\." fqdn)
2950     (substring fqdn 0 (1- (match-end 0)))))
2951
2952 (defun message-make-domain ()
2953   "Return the domain name."
2954   (or mail-host-address
2955       (message-make-fqdn)))
2956
2957 (defun message-generate-headers (headers)
2958   "Prepare article HEADERS.
2959 Headers already prepared in the buffer are not modified."
2960   (save-restriction
2961     (message-narrow-to-headers)
2962     (let* ((Date (message-make-date))
2963            (Message-ID (message-make-message-id))
2964            (Organization (message-make-organization))
2965            (From (message-make-from))
2966            (Path (message-make-path))
2967            (Subject nil)
2968            (Newsgroups nil)
2969            (In-Reply-To (message-make-in-reply-to))
2970            (To nil)
2971            (Distribution (message-make-distribution))
2972            (Lines (message-make-lines))
2973            (User-Agent message-newsreader)
2974            (Expires (message-make-expires))
2975            (case-fold-search t)
2976            header value elem)
2977       ;; First we remove any old generated headers.
2978       (let ((headers message-deletable-headers))
2979         (unless (buffer-modified-p)
2980           (setq headers (delq 'Message-ID (copy-sequence headers))))
2981         (while headers
2982           (goto-char (point-min))
2983           (and (re-search-forward
2984                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2985                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2986                (message-delete-line))
2987           (pop headers)))
2988       ;; Go through all the required headers and see if they are in the
2989       ;; articles already.  If they are not, or are empty, they are
2990       ;; inserted automatically - except for Subject, Newsgroups and
2991       ;; Distribution.
2992       (while headers
2993         (goto-char (point-min))
2994         (setq elem (pop headers))
2995         (if (consp elem)
2996             (if (eq (car elem) 'optional)
2997                 (setq header (cdr elem))
2998               (setq header (car elem)))
2999           (setq header elem))
3000         (when (or (not (re-search-forward
3001                         (concat "^"
3002                                 (regexp-quote
3003                                  (downcase
3004                                   (if (stringp header)
3005                                       header
3006                                     (symbol-name header))))
3007                                 ":")
3008                         nil t))
3009                   (progn
3010                     ;; The header was found.  We insert a space after the
3011                     ;; colon, if there is none.
3012                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3013                     ;; Find out whether the header is empty...
3014                     (looking-at "[ \t]*$")))
3015           ;; So we find out what value we should insert.
3016           (setq value
3017                 (cond
3018                  ((and (consp elem) (eq (car elem) 'optional))
3019                   ;; This is an optional header.  If the cdr of this
3020                   ;; is something that is nil, then we do not insert
3021                   ;; this header.
3022                   (setq header (cdr elem))
3023                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3024                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3025                  ((consp elem)
3026                   ;; The element is a cons.  Either the cdr is a
3027                   ;; string to be inserted verbatim, or it is a
3028                   ;; function, and we insert the value returned from
3029                   ;; this function.
3030                   (or (and (stringp (cdr elem)) (cdr elem))
3031                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3032                  ((and (boundp header) (symbol-value header))
3033                   ;; The element is a symbol.  We insert the value
3034                   ;; of this symbol, if any.
3035                   (symbol-value header))
3036                  (t
3037                   ;; We couldn't generate a value for this header,
3038                   ;; so we just ask the user.
3039                   (read-from-minibuffer
3040                    (format "Empty header for %s; enter value: " header)))))
3041           ;; Finally insert the header.
3042           (when (and value
3043                      (not (equal value "")))
3044             (save-excursion
3045               (if (bolp)
3046                   (progn
3047                     ;; This header didn't exist, so we insert it.
3048                     (goto-char (point-max))
3049                     (insert (if (stringp header) header (symbol-name header))
3050                             ": " value "\n")
3051                     (forward-line -1))
3052                 ;; The value of this header was empty, so we clear
3053                 ;; totally and insert the new value.
3054                 (delete-region (point) (gnus-point-at-eol))
3055                 (insert value))
3056               ;; Add the deletable property to the headers that require it.
3057               (and (memq header message-deletable-headers)
3058                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3059                    (add-text-properties
3060                     (point) (match-end 0)
3061                     '(message-deletable t face italic) (current-buffer)))))))
3062       ;; Insert new Sender if the From is strange.
3063       (let ((from (message-fetch-field "from"))
3064             (sender (message-fetch-field "sender"))
3065             (secure-sender (message-make-sender)))
3066         (when (and from
3067                    (not (message-check-element 'sender))
3068                    (not (string=
3069                          (downcase
3070                           (cadr (mail-extract-address-components from)))
3071                          (downcase secure-sender)))
3072                    (or (null sender)
3073                        (not
3074                         (string=
3075                          (downcase
3076                           (cadr (mail-extract-address-components sender)))
3077                          (downcase secure-sender)))))
3078           (goto-char (point-min))
3079           ;; Rename any old Sender headers to Original-Sender.
3080           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3081             (beginning-of-line)
3082             (insert "Original-")
3083             (beginning-of-line))
3084           (when (or (message-news-p)
3085                     (string-match "@.+\\.." secure-sender))
3086             (insert "Sender: " secure-sender "\n")))))))
3087
3088 (defun message-insert-courtesy-copy ()
3089   "Insert a courtesy message in mail copies of combined messages."
3090   (let (newsgroups)
3091     (save-excursion
3092       (save-restriction
3093         (message-narrow-to-headers)
3094         (when (setq newsgroups (message-fetch-field "newsgroups"))
3095           (goto-char (point-max))
3096           (insert "Posted-To: " newsgroups "\n")))
3097       (forward-line 1)
3098       (when message-courtesy-message
3099         (cond
3100          ((string-match "%s" message-courtesy-message)
3101           (insert (format message-courtesy-message newsgroups)))
3102          (t
3103           (insert message-courtesy-message)))))))
3104
3105 ;;;
3106 ;;; Setting up a message buffer
3107 ;;;
3108
3109 (defun message-fill-address (header value)
3110   (save-restriction
3111     (narrow-to-region (point) (point))
3112     (insert (capitalize (symbol-name header))
3113             ": "
3114             (if (consp value) (car value) value)
3115             "\n")
3116     (narrow-to-region (point-min) (1- (point-max)))
3117     (let (quoted last)
3118       (goto-char (point-min))
3119       (while (not (eobp))
3120         (skip-chars-forward "^,\"" (point-max))
3121         (if (or (eq (char-after) ?,)
3122                 (eobp))
3123             (when (not quoted)
3124               (if (and (> (current-column) 78)
3125                        last)
3126                   (progn
3127                     (save-excursion
3128                       (goto-char last)
3129                       (insert "\n\t"))
3130                     (setq last (1+ (point))))
3131                 (setq last (1+ (point)))))
3132           (setq quoted (not quoted)))
3133         (unless (eobp)
3134           (forward-char 1))))
3135     (goto-char (point-max))
3136     (widen)
3137     (forward-line 1)))
3138
3139 (defun message-fill-header (header value)
3140   (let ((begin (point))
3141         (fill-column 990)
3142         (fill-prefix "\t"))
3143     (insert (capitalize (symbol-name header))
3144             ": "
3145             (if (consp value) (car value) value)
3146             "\n")
3147     (save-restriction
3148       (narrow-to-region begin (point))
3149       (fill-region-as-paragraph begin (point))
3150       ;; Tapdance around looong Message-IDs.
3151       (forward-line -1)
3152       (when (looking-at "[ \t]*$")
3153         (message-delete-line))
3154       (goto-char begin)
3155       (re-search-forward ":" nil t)
3156       (when (looking-at "\n[ \t]+")
3157         (replace-match " " t t))
3158       (goto-char (point-max)))))
3159
3160 (defun message-shorten-references (header references)
3161   "Limit REFERENCES to be shorter than 988 characters."
3162   (let ((max 988)
3163         (cut 4)
3164         refs)
3165     (with-temp-buffer
3166       (insert references)
3167       (goto-char (point-min))
3168       (while (re-search-forward "<[^>]+>" nil t)
3169         (push (match-string 0) refs))
3170       (setq refs (nreverse refs))
3171       (while (> (length (mapconcat 'identity refs " ")) max)
3172         (when (< (length refs) (1+ cut))
3173           (decf cut))
3174         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3175     (insert (capitalize (symbol-name header)) ": "
3176             (mapconcat 'identity refs " ") "\n")))
3177
3178 (defun message-position-point ()
3179   "Move point to where the user probably wants to find it."
3180   (message-narrow-to-headers)
3181   (cond
3182    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3183     (search-backward ":" )
3184     (widen)
3185     (forward-char 1)
3186     (if (eq (char-after) ? )
3187         (forward-char 1)
3188       (insert " ")))
3189    (t
3190     (goto-char (point-max))
3191     (widen)
3192     (forward-line 1)
3193     (unless (looking-at "$")
3194       (forward-line 2)))
3195    (sit-for 0)))
3196
3197 (defun message-buffer-name (type &optional to group)
3198   "Return a new (unique) buffer name based on TYPE and TO."
3199   (cond
3200    ;; Generate a new buffer name The Message Way.
3201    ((eq message-generate-new-buffers 'unique)
3202     (generate-new-buffer-name
3203      (concat "*" type
3204              (if to
3205                  (concat " to "
3206                          (or (car (mail-extract-address-components to))
3207                              to) "")
3208                "")
3209              (if (and group (not (string= group ""))) (concat " on " group) "")
3210              "*")))
3211    ;; Check whether `message-generate-new-buffers' is a function,
3212    ;; and if so, call it.
3213    ((message-functionp message-generate-new-buffers)
3214     (funcall message-generate-new-buffers type to group))
3215    ((eq message-generate-new-buffers 'unsent)
3216     (generate-new-buffer-name
3217      (concat "*unsent " type
3218              (if to
3219                  (concat " to "
3220                          (or (car (mail-extract-address-components to))
3221                              to) "")
3222                "")
3223              (if (and group (not (string= group ""))) (concat " on " group) "")
3224              "*")))
3225    ;; Use standard name.
3226    (t
3227     (format "*%s message*" type))))
3228
3229 (defun message-pop-to-buffer (name)
3230   "Pop to buffer NAME, and warn if it already exists and is modified."
3231   (let ((buffer (get-buffer name)))
3232     (if (and buffer
3233              (buffer-name buffer))
3234         (progn
3235           (set-buffer (pop-to-buffer buffer))
3236           (when (and (buffer-modified-p)
3237                      (not (y-or-n-p
3238                            "Message already being composed; erase? ")))
3239             (error "Message being composed")))
3240       (set-buffer (pop-to-buffer name)))
3241     (erase-buffer)
3242     (message-mode)))
3243
3244 (defun message-do-send-housekeeping ()
3245   "Kill old message buffers."
3246   ;; We might have sent this buffer already.  Delete it from the
3247   ;; list of buffers.
3248   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3249   (while (and message-max-buffers
3250               message-buffer-list
3251               (>= (length message-buffer-list) message-max-buffers))
3252     ;; Kill the oldest buffer -- unless it has been changed.
3253     (let ((buffer (pop message-buffer-list)))
3254       (when (and (buffer-name buffer)
3255                  (not (buffer-modified-p buffer)))
3256         (kill-buffer buffer))))
3257   ;; Rename the buffer.
3258   (if message-send-rename-function
3259       (funcall message-send-rename-function)
3260     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3261       (rename-buffer
3262        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3263   ;; Push the current buffer onto the list.
3264   (when message-max-buffers
3265     (setq message-buffer-list
3266           (nconc message-buffer-list (list (current-buffer))))))
3267
3268 (defvar mc-modes-alist)
3269 (defun message-setup (headers &optional replybuffer actions)
3270   (when (and (boundp 'mc-modes-alist)
3271              (not (assq 'message-mode mc-modes-alist)))
3272     (push '(message-mode (encrypt . mc-encrypt-message)
3273                          (sign . mc-sign-message))
3274           mc-modes-alist))
3275   (when actions
3276     (setq message-send-actions actions))
3277   (setq message-reply-buffer replybuffer)
3278   (goto-char (point-min))
3279   ;; Insert all the headers.
3280   (mail-header-format
3281    (let ((h headers)
3282          (alist message-header-format-alist))
3283      (while h
3284        (unless (assq (caar h) message-header-format-alist)
3285          (push (list (caar h)) alist))
3286        (pop h))
3287      alist)
3288    headers)
3289   (delete-region (point) (progn (forward-line -1) (point)))
3290   (when message-default-headers
3291     (insert message-default-headers)
3292     (or (bolp) (insert ?\n)))
3293   (put-text-property
3294    (point)
3295    (progn
3296      (insert mail-header-separator "\n")
3297      (1- (point)))
3298    'read-only nil)
3299   (forward-line -1)
3300   (when (message-news-p)
3301     (when message-default-news-headers
3302       (insert message-default-news-headers)
3303       (or (bolp) (insert ?\n)))
3304     (when message-generate-headers-first
3305       (message-generate-headers
3306        (delq 'Lines
3307              (delq 'Subject
3308                    (copy-sequence message-required-news-headers))))))
3309   (when (message-mail-p)
3310     (when message-default-mail-headers
3311       (insert message-default-mail-headers)
3312       (or (bolp) (insert ?\n)))
3313     (when message-generate-headers-first
3314       (message-generate-headers
3315        (delq 'Lines
3316              (delq 'Subject
3317                    (copy-sequence message-required-mail-headers))))))
3318   (run-hooks 'message-signature-setup-hook)
3319   (message-insert-signature)
3320   (save-restriction
3321     (message-narrow-to-headers)
3322     (run-hooks 'message-header-setup-hook))
3323   (set-buffer-modified-p nil)
3324   (setq buffer-undo-list nil)
3325   (run-hooks 'message-setup-hook)
3326   (message-position-point)
3327   (undo-boundary))
3328
3329 (defun message-set-auto-save-file-name ()
3330   "Associate the message buffer with a file in the drafts directory."
3331   (when message-auto-save-directory
3332     (if (gnus-alive-p)
3333         (setq message-draft-article
3334               (nndraft-request-associate-buffer "drafts"))
3335       (setq buffer-file-name (expand-file-name "*message*"
3336                                                message-auto-save-directory))
3337       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3338     (clear-visited-file-modtime)
3339     (setq buffer-file-coding-system message-draft-coding-system)))
3340
3341 (defun message-disassociate-draft ()
3342   "Disassociate the message buffer from the drafts directory."
3343   (when message-draft-article
3344     (nndraft-request-expire-articles
3345      (list message-draft-article) "drafts" nil t)))
3346
3347 (defun message-insert-headers ()
3348   "Generate the headers for the article."
3349   (interactive)
3350   (save-excursion
3351     (save-restriction
3352       (message-narrow-to-headers)
3353       (when (message-news-p)
3354         (message-generate-headers
3355          (delq 'Lines
3356                (delq 'Subject
3357                      (copy-sequence message-required-news-headers)))))
3358       (when (message-mail-p)
3359         (message-generate-headers
3360          (delq 'Lines
3361                (delq 'Subject
3362                      (copy-sequence message-required-mail-headers))))))))
3363
3364 \f
3365
3366 ;;;
3367 ;;; Commands for interfacing with message
3368 ;;;
3369
3370 ;;;###autoload
3371 (defun message-mail (&optional to subject
3372                                other-headers continue switch-function
3373                                yank-action send-actions)
3374   "Start editing a mail message to be sent.
3375 OTHER-HEADERS is an alist of header/value pairs."
3376   (interactive)
3377   (let ((message-this-is-mail t))
3378     (message-pop-to-buffer (message-buffer-name "mail" to))
3379     (message-setup
3380      (nconc
3381       `((To . ,(or to "")) (Subject . ,(or subject "")))
3382       (when other-headers other-headers)))))
3383
3384 ;;;###autoload
3385 (defun message-news (&optional newsgroups subject)
3386   "Start editing a news article to be sent."
3387   (interactive)
3388   (let ((message-this-is-news t))
3389     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3390     (message-setup `((Newsgroups . ,(or newsgroups ""))
3391                      (Subject . ,(or subject ""))))))
3392
3393 ;;;###autoload
3394 (defun message-reply (&optional to-address wide)
3395   "Start editing a reply to the article in the current buffer."
3396   (interactive)
3397   (let ((cur (current-buffer))
3398         from subject date reply-to to cc
3399         references message-id follow-to
3400         (inhibit-point-motion-hooks t)
3401         mct never-mct gnus-warning)
3402     (save-restriction
3403       (message-narrow-to-head)
3404       ;; Allow customizations to have their say.
3405       (if (not wide)
3406           ;; This is a regular reply.
3407           (if (message-functionp message-reply-to-function)
3408               (setq follow-to (funcall message-reply-to-function)))
3409         ;; This is a followup.
3410         (if (message-functionp message-wide-reply-to-function)
3411             (save-excursion
3412               (setq follow-to
3413                     (funcall message-wide-reply-to-function)))))
3414       ;; Find all relevant headers we need.
3415       (setq from (message-fetch-field "from")
3416             date (message-fetch-field "date")
3417             subject (or (message-fetch-field "subject") "none")
3418             to (message-fetch-field "to")
3419             cc (message-fetch-field "cc")
3420             mct (message-fetch-field "mail-copies-to")
3421             reply-to (message-fetch-field "reply-to")
3422             references (message-fetch-field "references")
3423             message-id (message-fetch-field "message-id" t))
3424       ;; Remove any (buggy) Re:'s that are present and make a
3425       ;; proper one.
3426       (when (string-match message-subject-re-regexp subject)
3427         (setq subject (substring subject (match-end 0))))
3428       (setq subject (concat "Re: " subject))
3429
3430       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3431                  (string-match "<[^>]+>" gnus-warning))
3432         (setq message-id (match-string 0 gnus-warning)))
3433
3434       ;; Handle special values of Mail-Copies-To.
3435       (when mct
3436         (cond ((or (equal (downcase mct) "never")
3437                    (equal (downcase mct) "nobody"))
3438                (setq never-mct t)
3439                (setq mct nil))
3440               ((or (equal (downcase mct) "always")
3441                    (equal (downcase mct) "poster"))
3442                (setq mct (or reply-to from)))))
3443
3444       (unless follow-to
3445         (if (or (not wide)
3446                 to-address)
3447             (progn
3448               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3449               (when (and wide mct)
3450                 (push (cons 'Cc mct) follow-to)))
3451           (let (ccalist)
3452             (save-excursion
3453               (message-set-work-buffer)
3454               (unless never-mct
3455                 (insert (or reply-to from "")))
3456               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3457               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3458               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3459               (goto-char (point-min))
3460               (while (re-search-forward "[ \t]+" nil t)
3461                 (replace-match " " t t))
3462               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3463               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3464                         (erase-buffer)))
3465               (goto-char (point-min))
3466               ;; Perhaps Mail-Copies-To: never removed the only address?
3467               (when (eobp)
3468                 (insert (or reply-to from "")))
3469               (setq ccalist
3470                     (mapcar
3471                      (lambda (addr)
3472                        (cons (mail-strip-quoted-names addr) addr))
3473                      (message-tokenize-header (buffer-string))))
3474               (let ((s ccalist))
3475                 (while s
3476                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3477             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3478             (when ccalist
3479               (let ((ccs (cons 'Cc (mapconcat
3480                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3481                 (when (string-match "^ +" (cdr ccs))
3482                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3483                 (push ccs follow-to))))))
3484       (widen))
3485
3486     (message-pop-to-buffer (message-buffer-name
3487                             (if wide "wide reply" "reply") from
3488                             (if wide to-address nil)))
3489
3490     (setq message-reply-headers
3491           (vector 0 subject from date message-id references 0 0 ""))
3492
3493     (message-setup
3494      `((Subject . ,subject)
3495        ,@follow-to
3496        ,@(if (or references message-id)
3497              `((References . ,(concat (or references "") (and references " ")
3498                                       (or message-id ""))))
3499            nil))
3500      cur)))
3501
3502 ;;;###autoload
3503 (defun message-wide-reply (&optional to-address)
3504   "Make a \"wide\" reply to the message in the current buffer."
3505   (interactive)
3506   (message-reply to-address t))
3507
3508 ;;;###autoload
3509 (defun message-followup (&optional to-newsgroups)
3510   "Follow up to the message in the current buffer.
3511 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3512   (interactive)
3513   (let ((cur (current-buffer))
3514         from subject date reply-to mct
3515         references message-id follow-to
3516         (inhibit-point-motion-hooks t)
3517         (message-this-is-news t)
3518         followup-to distribution newsgroups gnus-warning posted-to)
3519     (save-restriction
3520       (narrow-to-region
3521        (goto-char (point-min))
3522        (if (search-forward "\n\n" nil t)
3523            (1- (point))
3524          (point-max)))
3525       (when (message-functionp message-followup-to-function)
3526         (setq follow-to
3527               (funcall message-followup-to-function)))
3528       (setq from (message-fetch-field "from")
3529             date (message-fetch-field "date")
3530             subject (or (message-fetch-field "subject") "none")
3531             references (message-fetch-field "references")
3532             message-id (message-fetch-field "message-id" t)
3533             followup-to (message-fetch-field "followup-to")
3534             newsgroups (message-fetch-field "newsgroups")
3535             posted-to (message-fetch-field "posted-to")
3536             reply-to (message-fetch-field "reply-to")
3537             distribution (message-fetch-field "distribution")
3538             mct (message-fetch-field "mail-copies-to"))
3539       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3540                  (string-match "<[^>]+>" gnus-warning))
3541         (setq message-id (match-string 0 gnus-warning)))
3542       ;; Remove bogus distribution.
3543       (when (and (stringp distribution)
3544                  (let ((case-fold-search t))
3545                    (string-match "world" distribution)))
3546         (setq distribution nil))
3547       ;; Remove any (buggy) Re:'s that are present and make a
3548       ;; proper one.
3549       (when (string-match message-subject-re-regexp subject)
3550         (setq subject (substring subject (match-end 0))))
3551       (setq subject (concat "Re: " subject))
3552       (widen))
3553
3554     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3555
3556     (message-setup
3557      `((Subject . ,subject)
3558        ,@(cond
3559           (to-newsgroups
3560            (list (cons 'Newsgroups to-newsgroups)))
3561           (follow-to follow-to)
3562           ((and followup-to message-use-followup-to)
3563            (list
3564             (cond
3565              ((equal (downcase followup-to) "poster")
3566               (if (or (eq message-use-followup-to 'use)
3567                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3568 You should normally obey the Followup-To: header.
3569
3570 `Followup-To: poster' sends your response via e-mail instead of news.
3571
3572 A typical situation where `Followup-To: poster' is used is when the poster
3573 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3574                   (progn
3575                     (setq message-this-is-news nil)
3576                     (cons 'To (or reply-to from "")))
3577                 (cons 'Newsgroups newsgroups)))
3578              (t
3579               (if (or (equal followup-to newsgroups)
3580                       (not (eq message-use-followup-to 'ask))
3581                       (message-y-or-n-p
3582                        (concat "Obey Followup-To: " followup-to "? ") t "\
3583 You should normally obey the Followup-To: header.
3584
3585         `Followup-To: " followup-to "'
3586 directs your response to " (if (string-match "," followup-to)
3587                                "the specified newsgroups"
3588                              "that newsgroup only") ".
3589
3590 If a message is posted to several newsgroups, Followup-To is often
3591 used to direct the following discussion to one newsgroup only,
3592 because discussions that are spread over several newsgroup tend to
3593 be fragmented and very difficult to follow.
3594
3595 Also, some source/announcement newsgroups are not indented for discussion;
3596 responses here are directed to other newsgroups."))
3597                   (cons 'Newsgroups followup-to)
3598                 (cons 'Newsgroups newsgroups))))))
3599           (posted-to
3600            `((Newsgroups . ,posted-to)))
3601           (t
3602            `((Newsgroups . ,newsgroups))))
3603        ,@(and distribution (list (cons 'Distribution distribution)))
3604        ,@(if (or references message-id)
3605              `((References . ,(concat (or references "") (and references " ")
3606                                       (or message-id "")))))
3607        ,@(when (and mct
3608                     (not (or (equal (downcase mct) "never")
3609                              (equal (downcase mct) "nobody"))))
3610            (list (cons 'Cc (if (or (equal (downcase mct) "always")
3611                                    (equal (downcase mct) "poster"))
3612                                (or reply-to from "")
3613                              mct)))))
3614
3615      cur)
3616
3617     (setq message-reply-headers
3618           (vector 0 subject from date message-id references 0 0 ""))))
3619
3620
3621 ;;;###autoload
3622 (defun message-cancel-news ()
3623   "Cancel an article you posted."
3624   (interactive)
3625   (unless (message-news-p)
3626     (error "This is not a news article; canceling is impossible"))
3627   (when (yes-or-no-p "Do you really want to cancel this article? ")
3628     (let (from newsgroups message-id distribution buf sender)
3629       (save-excursion
3630         ;; Get header info. from original article.
3631         (save-restriction
3632           (message-narrow-to-head)
3633           (setq from (message-fetch-field "from")
3634                 sender (message-fetch-field "sender")
3635                 newsgroups (message-fetch-field "newsgroups")
3636                 message-id (message-fetch-field "message-id" t)
3637                 distribution (message-fetch-field "distribution")))
3638         ;; Make sure that this article was written by the user.
3639         (unless (or (and sender
3640                          (string-equal
3641                           (downcase sender)
3642                           (downcase (message-make-sender))))
3643                     (string-equal
3644                      (downcase (cadr (mail-extract-address-components from)))
3645                      (downcase (cadr (mail-extract-address-components
3646                                       (message-make-from))))))
3647           (error "This article is not yours"))
3648         ;; Make control message.
3649         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3650         (erase-buffer)
3651         (insert "Newsgroups: " newsgroups "\n"
3652                 "From: " (message-make-from) "\n"
3653                 "Subject: cmsg cancel " message-id "\n"
3654                 "Control: cancel " message-id "\n"
3655                 (if distribution
3656                     (concat "Distribution: " distribution "\n")
3657                   "")
3658                 mail-header-separator "\n"
3659                 message-cancel-message)
3660         (run-hooks 'message-cancel-hook)
3661         (message "Canceling your article...")
3662         (if (let ((message-syntax-checks
3663                    'dont-check-for-anything-just-trust-me))
3664               (funcall message-send-news-function))
3665             (message "Canceling your article...done"))
3666         (kill-buffer buf)))))
3667
3668 ;;;###autoload
3669 (defun message-supersede ()
3670   "Start composing a message to supersede the current message.
3671 This is done simply by taking the old article and adding a Supersedes
3672 header line with the old Message-ID."
3673   (interactive)
3674   (let ((cur (current-buffer))
3675         (sender (message-fetch-field "sender"))
3676         (from (message-fetch-field "from")))
3677     ;; Check whether the user owns the article that is to be superseded.
3678     (unless (or (and sender
3679                      (string-equal
3680                       (downcase sender)
3681                       (downcase (message-make-sender))))
3682                 (string-equal
3683                  (downcase (cadr (mail-extract-address-components from)))
3684                  (downcase (cadr (mail-extract-address-components
3685                                   (message-make-from))))))
3686       (error "This article is not yours"))
3687     ;; Get a normal message buffer.
3688     (message-pop-to-buffer (message-buffer-name "supersede"))
3689     (insert-buffer-substring cur)
3690     (message-narrow-to-head)
3691     ;; Remove unwanted headers.
3692     (when message-ignored-supersedes-headers
3693       (message-remove-header message-ignored-supersedes-headers t))
3694     (goto-char (point-min))
3695     (if (not (re-search-forward "^Message-ID: " nil t))
3696         (error "No Message-ID in this article")
3697       (replace-match "Supersedes: " t t))
3698     (goto-char (point-max))
3699     (insert mail-header-separator)
3700     (widen)
3701     (forward-line 1)))
3702
3703 ;;;###autoload
3704 (defun message-recover ()
3705   "Reread contents of current buffer from its last auto-save file."
3706   (interactive)
3707   (let ((file-name (make-auto-save-file-name)))
3708     (cond ((save-window-excursion
3709              (if (not (eq system-type 'vax-vms))
3710                  (with-output-to-temp-buffer "*Directory*"
3711                    (buffer-disable-undo standard-output)
3712                    (let ((default-directory "/"))
3713                      (call-process
3714                       "ls" nil standard-output nil "-l" file-name))))
3715              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3716            (let ((buffer-read-only nil))
3717              (erase-buffer)
3718              (insert-file-contents file-name nil)))
3719           (t (error "message-recover cancelled")))))
3720
3721 ;;; Washing Subject:
3722
3723 (defun message-wash-subject (subject)
3724   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3725   (with-temp-buffer
3726     (insert-string subject)
3727     (goto-char (point-min))
3728     ;; strip Re/Fwd stuff off the beginning
3729     (while (re-search-forward
3730             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
3731       (replace-match ""))
3732
3733     ;; and gnus-style forwards [foo@bar.com] subject
3734     (goto-char (point-min))
3735     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
3736       (replace-match ""))
3737
3738     ;; and off the end
3739     (goto-char (point-max))
3740     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
3741       (replace-match ""))
3742
3743     ;; and finally, any whitespace that was left-over
3744     (goto-char (point-min))
3745     (while (re-search-forward "^[ \t]+" nil t)
3746       (replace-match ""))
3747     (goto-char (point-max))
3748     (while (re-search-backward "[ \t]+$" nil t)
3749       (replace-match ""))
3750
3751     (buffer-string)))
3752
3753 ;;; Forwarding messages.
3754
3755 (defun message-forward-subject-author-subject (subject)
3756   "Generate a subject for a forwarded message.
3757 The form is: [Source] Subject, where if the original message was mail,
3758 Source is the sender, and if the original message was news, Source is
3759 the list of newsgroups is was posted to."
3760   (concat "["
3761           (or (message-fetch-field
3762                (if (message-news-p) "newsgroups" "from"))
3763               "(nowhere)")
3764           "] " subject))
3765
3766 (defun message-forward-subject-fwd (subject)
3767   "Generate a subject for a forwarded message.
3768 The form is: Fwd: Subject, where Subject is the original subject of
3769 the message."
3770   (concat "Fwd: " subject))
3771
3772 (defun message-make-forward-subject ()
3773   "Return a Subject header suitable for the message in the current buffer."
3774   (save-excursion
3775     (save-restriction
3776       (current-buffer)
3777       (message-narrow-to-head)
3778       (let ((funcs message-make-forward-subject-function)
3779             (subject (if message-wash-forwarded-subjects
3780                          (message-wash-subject
3781                           (or (message-fetch-field "Subject") ""))
3782                        (or (message-fetch-field "Subject") ""))))
3783         ;; Make sure funcs is a list.
3784         (and funcs
3785              (not (listp funcs))
3786              (setq funcs (list funcs)))
3787         ;; Apply funcs in order, passing subject generated by previous
3788         ;; func to the next one.
3789         (while funcs
3790           (when (message-functionp (car funcs))
3791             (setq subject (funcall (car funcs) subject)))
3792           (setq funcs (cdr funcs)))
3793         subject))))
3794
3795 ;;;###autoload
3796 (defun message-forward (&optional news)
3797   "Forward the current message via mail.
3798 Optional NEWS will use news to forward instead of mail."
3799   (interactive "P")
3800   (let ((cur (current-buffer))
3801         (subject (message-make-forward-subject))
3802         art-beg)
3803     (if news
3804         (message-news nil subject)
3805       (message-mail nil subject))
3806     ;; Put point where we want it before inserting the forwarded
3807     ;; message.
3808     (if message-signature-before-forwarded-message
3809         (goto-char (point-max))
3810       (message-goto-body))
3811     ;; Make sure we're at the start of the line.
3812     (unless (eolp)
3813       (insert "\n"))
3814     ;; Narrow to the area we are to insert.
3815     (narrow-to-region (point) (point))
3816     ;; Insert the separators and the forwarded buffer.
3817     (insert message-forward-start-separator)
3818     (setq art-beg (point))
3819     (insert-buffer-substring cur)
3820     (goto-char (point-max))
3821     (insert message-forward-end-separator)
3822     (set-text-properties (point-min) (point-max) nil)
3823     ;; Remove all unwanted headers.
3824     (goto-char art-beg)
3825     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3826                                   (1- (point))
3827                                 (point)))
3828     (goto-char (point-min))
3829     (message-remove-header message-included-forward-headers t nil t)
3830     (widen)
3831     (message-position-point)))
3832
3833 ;;;###autoload
3834 (defun message-resend (address)
3835   "Resend the current article to ADDRESS."
3836   (interactive "sResend message to: ")
3837   (message "Resending message to %s..." address)
3838   (save-excursion
3839     (let ((cur (current-buffer))
3840           beg)
3841       ;; We first set up a normal mail buffer.
3842       (set-buffer (get-buffer-create " *message resend*"))
3843       (erase-buffer)
3844       (message-setup `((To . ,address)))
3845       ;; Insert our usual headers.
3846       (message-generate-headers '(From Date To))
3847       (message-narrow-to-headers)
3848       ;; Rename them all to "Resent-*".
3849       (while (re-search-forward "^[A-Za-z]" nil t)
3850         (forward-char -1)
3851         (insert "Resent-"))
3852       (widen)
3853       (forward-line)
3854       (delete-region (point) (point-max))
3855       (setq beg (point))
3856       ;; Insert the message to be resent.
3857       (insert-buffer-substring cur)
3858       (goto-char (point-min))
3859       (search-forward "\n\n")
3860       (forward-char -1)
3861       (save-restriction
3862         (narrow-to-region beg (point))
3863         (message-remove-header message-ignored-resent-headers t)
3864         (goto-char (point-max)))
3865       (insert mail-header-separator)
3866       ;; Rename all old ("Also-")Resent headers.
3867       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
3868         (beginning-of-line)
3869         (insert "Also-"))
3870       ;; Quote any "From " lines at the beginning.
3871       (goto-char beg)
3872       (when (looking-at "From ")
3873         (replace-match "X-From-Line: "))
3874       ;; Send it.
3875       (let (message-required-mail-headers)
3876         (message-send-mail))
3877       (kill-buffer (current-buffer)))
3878     (message "Resending message to %s...done" address)))
3879
3880 ;;;###autoload
3881 (defun message-bounce ()
3882   "Re-mail the current message.
3883 This only makes sense if the current message is a bounce message than
3884 contains some mail you have written which has been bounced back to
3885 you."
3886   (interactive)
3887   (let ((cur (current-buffer))
3888         boundary)
3889     (message-pop-to-buffer (message-buffer-name "bounce"))
3890     (insert-buffer-substring cur)
3891     (undo-boundary)
3892     (message-narrow-to-head)
3893     (if (and (message-fetch-field "Mime-Version")
3894              (setq boundary (message-fetch-field "Content-Type")))
3895         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3896             (setq boundary (concat (match-string 1 boundary) " *\n"
3897                                    "Content-Type: message/rfc822"))
3898           (setq boundary nil)))
3899     (widen)
3900     (goto-char (point-min))
3901     (search-forward "\n\n" nil t)
3902     (or (and boundary
3903              (re-search-forward boundary nil t)
3904              (forward-line 2))
3905         (and (re-search-forward message-unsent-separator nil t)
3906              (forward-line 1))
3907         (re-search-forward "^Return-Path:.*\n" nil t))
3908     ;; We remove everything before the bounced mail.
3909     (delete-region
3910      (point-min)
3911      (if (re-search-forward "^[^ \n\t]+:" nil t)
3912          (match-beginning 0)
3913        (point)))
3914     (save-restriction
3915       (message-narrow-to-head)
3916       (message-remove-header message-ignored-bounced-headers t)
3917       (goto-char (point-max))
3918       (insert mail-header-separator))
3919     (message-position-point)))
3920
3921 ;;;
3922 ;;; Interactive entry points for new message buffers.
3923 ;;;
3924
3925 ;;;###autoload
3926 (defun message-mail-other-window (&optional to subject)
3927   "Like `message-mail' command, but display mail buffer in another window."
3928   (interactive)
3929   (let ((pop-up-windows t)
3930         (special-display-buffer-names nil)
3931         (special-display-regexps nil)
3932         (same-window-buffer-names nil)
3933         (same-window-regexps nil))
3934     (message-pop-to-buffer (message-buffer-name "mail" to)))
3935   (let ((message-this-is-mail t))
3936     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3937
3938 ;;;###autoload
3939 (defun message-mail-other-frame (&optional to subject)
3940   "Like `message-mail' command, but display mail buffer in another frame."
3941   (interactive)
3942   (let ((pop-up-frames t)
3943         (special-display-buffer-names nil)
3944         (special-display-regexps nil)
3945         (same-window-buffer-names nil)
3946         (same-window-regexps nil))
3947     (message-pop-to-buffer (message-buffer-name "mail" to)))
3948   (let ((message-this-is-mail t))
3949     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3950
3951 ;;;###autoload
3952 (defun message-news-other-window (&optional newsgroups subject)
3953   "Start editing a news article to be sent."
3954   (interactive)
3955   (let ((pop-up-windows t)
3956         (special-display-buffer-names nil)
3957         (special-display-regexps nil)
3958         (same-window-buffer-names nil)
3959         (same-window-regexps nil))
3960     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3961   (let ((message-this-is-news t))
3962     (message-setup `((Newsgroups . ,(or newsgroups ""))
3963                      (Subject . ,(or subject ""))))))
3964
3965 ;;;###autoload
3966 (defun message-news-other-frame (&optional newsgroups subject)
3967   "Start editing a news article to be sent."
3968   (interactive)
3969   (let ((pop-up-frames t)
3970         (special-display-buffer-names nil)
3971         (special-display-regexps nil)
3972         (same-window-buffer-names nil)
3973         (same-window-regexps nil))
3974     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3975   (let ((message-this-is-news t))
3976     (message-setup `((Newsgroups . ,(or newsgroups ""))
3977                      (Subject . ,(or subject ""))))))
3978
3979 ;;; underline.el
3980
3981 ;; This code should be moved to underline.el (from which it is stolen).
3982
3983 ;;;###autoload
3984 (defun bold-region (start end)
3985   "Bold all nonblank characters in the region.
3986 Works by overstriking characters.
3987 Called from program, takes two arguments START and END
3988 which specify the range to operate on."
3989   (interactive "r")
3990   (save-excursion
3991     (let ((end1 (make-marker)))
3992       (move-marker end1 (max start end))
3993       (goto-char (min start end))
3994       (while (< (point) end1)
3995         (or (looking-at "[_\^@- ]")
3996             (insert (char-after) "\b"))
3997         (forward-char 1)))))
3998
3999 ;;;###autoload
4000 (defun unbold-region (start end)
4001   "Remove all boldness (overstruck characters) in the region.
4002 Called from program, takes two arguments START and END
4003 which specify the range to operate on."
4004   (interactive "r")
4005   (save-excursion
4006     (let ((end1 (make-marker)))
4007       (move-marker end1 (max start end))
4008       (goto-char (min start end))
4009       (while (re-search-forward "\b" end1 t)
4010         (if (eq (char-after) (char-after (- (point) 2)))
4011             (delete-char -2))))))
4012
4013 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4014
4015 ;; Support for toolbar
4016 (when (string-match "XEmacs\\|Lucid" emacs-version)
4017   (require 'messagexmas))
4018
4019 ;;; Group name completion.
4020
4021 (defvar message-newgroups-header-regexp
4022   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4023   "Regexp that match headers that lists groups.")
4024
4025 (defun message-tab ()
4026   "Expand group names in Newsgroups and Followup-To headers.
4027 Do a `tab-to-tab-stop' if not in those headers."
4028   (interactive)
4029   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4030         (mail-abbrev-in-expansion-header-p))
4031       (message-expand-group)
4032     (tab-to-tab-stop)))
4033
4034 (defvar gnus-active-hashtb)
4035 (defun message-expand-group ()
4036   "Expand the group name under point."
4037   (let* ((b (save-excursion
4038               (save-restriction
4039                 (narrow-to-region
4040                  (save-excursion
4041                    (beginning-of-line)
4042                    (skip-chars-forward "^:")
4043                    (1+ (point)))
4044                  (point))
4045                 (skip-chars-backward "^, \t\n") (point))))
4046          (completion-ignore-case t)
4047          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4048                                             (point))))
4049          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4050          (completions (all-completions string hashtb))
4051          comp)
4052     (delete-region b (point))
4053     (cond
4054      ((= (length completions) 1)
4055       (if (string= (car completions) string)
4056           (progn
4057             (insert string)
4058             (message "Only matching group"))
4059         (insert (car completions))))
4060      ((and (setq comp (try-completion string hashtb))
4061            (not (string= comp string)))
4062       (insert comp))
4063      (t
4064       (insert string)
4065       (if (not comp)
4066           (message "No matching groups")
4067         (save-selected-window
4068           (pop-to-buffer "*Completions*")
4069           (buffer-disable-undo)
4070           (let ((buffer-read-only nil))
4071             (erase-buffer)
4072             (let ((standard-output (current-buffer)))
4073               (display-completion-list (sort completions 'string<)))
4074             (goto-char (point-min))
4075             (delete-region (point) (progn (forward-line 3) (point))))))))))
4076
4077 ;;; Help stuff.
4078
4079 (defun message-talkative-question (ask question show &rest text)
4080   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4081 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4082 The following arguments may contain lists of values."
4083   (if (and show
4084            (setq text (message-flatten-list text)))
4085       (save-window-excursion
4086         (save-excursion
4087           (with-output-to-temp-buffer " *MESSAGE information message*"
4088             (set-buffer " *MESSAGE information message*")
4089             (mapcar 'princ text)
4090             (goto-char (point-min))))
4091         (funcall ask question))
4092     (funcall ask question)))
4093
4094 (defun message-flatten-list (list)
4095   "Return a new, flat list that contains all elements of LIST.
4096
4097 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4098 => (1 2 3 4 5 6 7)"
4099   (cond ((consp list)
4100          (apply 'append (mapcar 'message-flatten-list list)))
4101         (list
4102          (list list))))
4103
4104 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4105   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4106 Then clone the local variables and values from the old buffer to the
4107 new one, cloning only the locals having a substring matching the
4108 regexp varstr."
4109   (let ((oldbuf (current-buffer)))
4110     (save-excursion
4111       (set-buffer (generate-new-buffer name))
4112       (message-clone-locals oldbuf)
4113       (current-buffer))))
4114
4115 (defun message-clone-locals (buffer)
4116   "Clone the local variables from BUFFER to the current buffer."
4117   (let ((locals (save-excursion
4118                   (set-buffer buffer)
4119                   (buffer-local-variables)))
4120         (regexp "^gnus\\|^nn\\|^message"))
4121     (mapcar
4122      (lambda (local)
4123        (when (and (consp local)
4124                   (car local)
4125                   (string-match regexp (symbol-name (car local))))
4126          (ignore-errors
4127            (set (make-local-variable (car local))
4128                 (cdr local)))))
4129      locals)))
4130
4131 ;;; Miscellaneous functions
4132
4133 ;; stolen (and renamed) from nnheader.el
4134 (defun message-replace-chars-in-string (string from to)
4135   "Replace characters in STRING from FROM to TO."
4136   (let ((string (substring string 0))   ;Copy string.
4137         (len (length string))
4138         (idx 0))
4139     ;; Replace all occurrences of FROM with TO.
4140     (while (< idx len)
4141       (when (= (aref string idx) from)
4142         (aset string idx to))
4143       (setq idx (1+ idx)))
4144     string))
4145
4146 ;;;
4147 ;;; MIME functions
4148 ;;;
4149
4150 (defun message-mime-query-file (prompt)
4151   (let ((file (read-file-name prompt nil nil t)))
4152     ;; Prevent some common errors.  This is inspired by similar code in
4153     ;; VM.
4154     (when (file-directory-p file)
4155       (error "%s is a directory, cannot attach" file))
4156     (unless (file-exists-p file)
4157       (error "No such file: %s" file))
4158     (unless (file-readable-p file)
4159       (error "Permission denied: %s" file))
4160     file))
4161
4162 (defun message-mime-query-type (file)
4163   (let* ((default (or (mm-default-file-encoding file)
4164                       ;; Perhaps here we should check what the file
4165                       ;; looks like, and offer text/plain if it looks
4166                       ;; like text/plain.
4167                       "application/octet-stream"))
4168          (string (completing-read
4169                   (format "Content type (default %s): " default)
4170                   (delete-duplicates
4171                    (mapcar (lambda (m) (list (cdr m))) mailcap-mime-extensions)
4172                    :test 'equal))))
4173     (if (not (equal string ""))
4174         string
4175       default)))
4176
4177 (defun message-mime-query-description ()
4178   (let ((description (read-string "One line description: ")))
4179     (when (string-match "\\`[ \t]*\\'" description)
4180       (setq description nil))
4181     description))
4182
4183 (defun message-mime-attach-file (file &optional type description)
4184   "Attach a file to the outgoing MIME message.
4185 The file is not inserted or encoded until you send the message with
4186 `\\[message-send-and-exit]' or `\\[message-send]'.
4187
4188 FILE is the name of the file to attach.  TYPE is its content-type, a
4189 string of the form \"type/subtype\".  DESCRIPTION is a one-line
4190 description of the attachment."
4191   (interactive
4192    (let* ((file (message-mime-query-file "Attach file: "))
4193           (type (message-mime-query-type file))
4194           (description (message-mime-query-description)))
4195      (list file type description)))
4196   (insert (format
4197            "<#part type=%s name=%s filename=%s%s disposition=attachment><#/part>\n"
4198            type (prin1-to-string (file-name-nondirectory file))
4199            (prin1-to-string file)
4200            (if description
4201                (format " description=%s" (prin1-to-string description))
4202              ""))))
4203
4204 (defun message-mime-attach-external (file &optional type description)
4205   "Attach an external file into the buffer.
4206 FILE is an ange-ftp/efs specification of the part location.
4207 TYPE is the MIME type to use."
4208   (interactive
4209    (let* ((file (message-mime-query-file "Attach external file: "))
4210           (type (message-mime-query-type file))
4211           (description (message-mime-query-description)))
4212      (list file type description)))
4213   (insert (format
4214            "<#external type=%s name=%s disposition=attachment><#/external>\n"
4215            type (prin1-to-string file))))
4216
4217 (defun message-encode-message-body ()
4218   (let ((mail-parse-charset message-default-charset)
4219         (case-fold-search t)
4220         lines multipart-p content-type-p)
4221     (message-goto-body)
4222     (save-restriction
4223       (narrow-to-region (point) (point-max))
4224       (let ((new (mml-generate-mime)))
4225         (when new
4226           (delete-region (point-min) (point-max))
4227           (insert new)
4228           (goto-char (point-min))
4229           (if (eq (aref new 0) ?\n)
4230               (delete-char 1)
4231             (search-forward "\n\n")
4232             (setq lines (buffer-substring (point-min) (1- (point))))
4233             (delete-region (point-min)  (point))))))
4234     (save-restriction
4235       (message-narrow-to-headers-or-head)
4236       (message-remove-header "Mime-Version")
4237       (goto-char (point-max))
4238       (insert "MIME-Version: 1.0\n")
4239       (when lines
4240         (insert lines))
4241       (setq multipart-p
4242             (re-search-backward "^Content-Type: multipart/" nil t))
4243       (goto-char (point-max))
4244       (setq content-type-p
4245             (re-search-backward "^Content-Type:" nil t)))
4246     (save-restriction
4247       (message-narrow-to-headers-or-head)
4248       (message-remove-first-header "Content-Type")
4249       (message-remove-first-header "Content-Transfer-Encoding"))
4250     (when multipart-p
4251       (message-goto-body)
4252       (insert "This is a MIME multipart message.  If you are reading\n")
4253       (insert "this, you shouldn't.\n"))
4254     ;; We always make sure that the message has a Content-Type header.
4255     ;; This is because some broken MTAs and MUAs get awfully confused
4256     ;; when confronted with a message with a MIME-Version header and
4257     ;; without a Content-Type header.  For instance, Solaris'
4258     ;; /usr/bin/mail.
4259     (unless content-type-p
4260       (goto-char (point-min))
4261       (re-search-forward "^MIME-Version:")
4262       (forward-line 1)
4263       (insert "Content-Type: text/plain; charset=us-ascii\n"))))
4264
4265 (provide 'message)
4266
4267 (run-hooks 'message-load-hook)
4268
4269 ;;; message.el ends here