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