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