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