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