(gnus-setup-message): Setup `message-startup-parameter-alist'.
[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 (defvar mail-citation-hook) ;Compiler directive
1816 (defun message-cite-original ()
1817   "Cite function in the standard Message manner."
1818   (if (and (boundp 'mail-citation-hook)
1819            mail-citation-hook)
1820       (run-hooks 'mail-citation-hook)
1821     (let ((start (point))
1822           (functions
1823            (when message-indent-citation-function
1824              (if (listp message-indent-citation-function)
1825                  message-indent-citation-function
1826                (list message-indent-citation-function)))))
1827       (goto-char start)
1828       (while functions
1829         (funcall (pop functions)))
1830       (when message-citation-line-function
1831         (unless (bolp)
1832           (insert "\n"))
1833         (funcall message-citation-line-function)))))
1834
1835 (defun message-insert-citation-line ()
1836   "Function that inserts a simple citation line."
1837   (when message-reply-headers
1838     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1839
1840 (defun message-position-on-field (header &rest afters)
1841   (let ((case-fold-search t))
1842     (save-restriction
1843       (narrow-to-region
1844        (goto-char (point-min))
1845        (progn
1846          (re-search-forward
1847           (concat "^" (regexp-quote mail-header-separator) "$"))
1848          (match-beginning 0)))
1849       (goto-char (point-min))
1850       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1851           (progn
1852             (re-search-forward "^[^ \t]" nil 'move)
1853             (beginning-of-line)
1854             (skip-chars-backward "\n")
1855             t)
1856         (while (and afters
1857                     (not (re-search-forward
1858                           (concat "^" (regexp-quote (car afters)) ":")
1859                           nil t)))
1860           (pop afters))
1861         (when afters
1862           (re-search-forward "^[^ \t]" nil 'move)
1863           (beginning-of-line))
1864         (insert header ": \n")
1865         (forward-char -1)
1866         nil))))
1867
1868 (defun message-remove-signature ()
1869   "Remove the signature from the text between point and mark.
1870 The text will also be indented the normal way."
1871   (save-excursion
1872     (let ((start (point))
1873           mark)
1874       (if (not (re-search-forward message-signature-separator (mark t) t))
1875           ;; No signature here, so we just indent the cited text.
1876           (message-indent-citation)
1877         ;; Find the last non-empty line.
1878         (forward-line -1)
1879         (while (looking-at "[ \t]*$")
1880           (forward-line -1))
1881         (forward-line 1)
1882         (setq mark (set-marker (make-marker) (point)))
1883         (goto-char start)
1884         (message-indent-citation)
1885         ;; Enable undoing the deletion.
1886         (undo-boundary)
1887         (delete-region mark (mark t))
1888         (set-marker mark nil)))))
1889
1890 \f
1891
1892 ;;;
1893 ;;; Sending messages
1894 ;;;
1895
1896 ;; Avoid byte-compile warning.
1897 (defvar message-encoding-buffer nil)
1898 (defvar message-edit-buffer nil)
1899 (defvar message-mime-mode nil)
1900
1901 (defun message-send-and-exit (&optional arg)
1902   "Send message like `message-send', then, if no errors, exit from mail buffer."
1903   (interactive "P")
1904   (let ((buf (current-buffer))
1905         (actions message-exit-actions)
1906         (frame (selected-frame))
1907         (org-frame message-original-frame))
1908     (when (and (message-send arg)
1909                (buffer-name buf))
1910       (if message-kill-buffer-on-exit
1911           (kill-buffer buf)
1912         (bury-buffer buf)
1913         (when (eq buf (current-buffer))
1914           (message-bury buf)))
1915       (message-do-actions actions)
1916       (message-delete-frame frame org-frame)
1917       t)))
1918
1919 (defun message-dont-send ()
1920   "Don't send the message you have been editing."
1921   (interactive)
1922   (set-buffer-modified-p t)
1923   (save-buffer)
1924   (let ((actions message-postpone-actions))
1925     (message-bury (current-buffer))
1926     (message-do-actions actions)))
1927
1928 (defun message-kill-buffer ()
1929   "Kill the current buffer."
1930   (interactive)
1931   (when (or (not (buffer-modified-p))
1932             (yes-or-no-p "Message modified; kill anyway? "))
1933     (let ((actions message-kill-actions)
1934           (frame (selected-frame))
1935           (org-frame message-original-frame))
1936       (setq buffer-file-name nil)
1937       (kill-buffer (current-buffer))
1938       (message-do-actions actions)
1939       (message-delete-frame frame org-frame))))
1940
1941 (defun message-delete-frame (frame org-frame)
1942   "Delete frame for editing message."
1943   (when (and (or (and (featurep 'xemacs)
1944                       (not (eq 'tty (device-type))))
1945                  window-system
1946                  (>= emacs-major-version 20))
1947              (or (and (eq message-delete-frame-on-exit t)
1948                       (select-frame frame)
1949                       (or (eq frame org-frame)
1950                           (prog1
1951                               (y-or-n-p "Delete this frame?")
1952                             (message ""))))
1953                  (and (eq message-delete-frame-on-exit 'ask)
1954                       (select-frame frame)
1955                       (prog1
1956                           (y-or-n-p "Delete this frame?")
1957                         (message "")))))
1958     (delete-frame frame)))
1959
1960 (defun message-bury (buffer)
1961   "Bury this mail buffer."
1962   (let ((newbuf (other-buffer buffer)))
1963     (bury-buffer buffer)
1964     (if (and (fboundp 'frame-parameters)
1965              (cdr (assq 'dedicated (frame-parameters)))
1966              (not (null (delq (selected-frame) (visible-frame-list)))))
1967         (delete-frame (selected-frame))
1968       (switch-to-buffer newbuf))))
1969
1970 (defun message-send (&optional arg)
1971   "Send the message in the current buffer.
1972 If `message-interactive' is non-nil, wait for success indication
1973 or error messages, and inform user.
1974 Otherwise any failure is reported in a message back to
1975 the user from the mailer."
1976   (interactive "P")
1977   ;; Disabled test.
1978   (when (or (buffer-modified-p)
1979             (message-check-element 'unchanged)
1980             (y-or-n-p "No changes in the buffer; really send? "))
1981     ;; Make it possible to undo the coming changes.
1982     (undo-boundary)
1983     (let ((inhibit-read-only t))
1984       (put-text-property (point-min) (point-max) 'read-only nil))
1985     (run-hooks 'message-send-hook)
1986     (message "Sending...")
1987     (let ((message-encoding-buffer
1988            (message-generate-new-buffer-clone-locals " message encoding"))
1989           (message-edit-buffer (current-buffer))
1990           (message-mime-mode mime-edit-mode-flag)
1991           (alist message-send-method-alist)
1992           (success t)
1993           elem sent)
1994       (save-excursion
1995         (set-buffer message-encoding-buffer)
1996         (erase-buffer)
1997         (insert-buffer message-edit-buffer)
1998         (funcall message-encode-function)
1999         (message-fix-before-sending)
2000         (while (and success
2001                     (setq elem (pop alist)))
2002           (when (and (or (not (funcall (cadr elem)))
2003                          (and (or (not (memq (car elem)
2004                                              message-sent-message-via))
2005                                   (y-or-n-p
2006                                    (format
2007                                     "Already sent message via %s; resend? "
2008                                     (car elem))))
2009                               (setq success (funcall (caddr elem) arg)))))
2010             (setq sent t))))
2011       (when (and success sent)
2012         (message-do-fcc)
2013         ;;(when (fboundp 'mail-hist-put-headers-into-history)
2014         ;; (mail-hist-put-headers-into-history))
2015         (run-hooks 'message-sent-hook)
2016         (message "Sending...done")
2017         ;; Mark the buffer as unmodified and delete autosave.
2018         (set-buffer-modified-p nil)
2019         (delete-auto-save-file-if-necessary t)
2020         (message-disassociate-draft)
2021         ;; Delete other mail buffers and stuff.
2022         (message-do-send-housekeeping)
2023         (message-do-actions message-send-actions)
2024         ;; Return success.
2025         t))))
2026
2027 (defun message-send-via-mail (arg)
2028   "Send the current message via mail."
2029   (message-send-mail arg))
2030
2031 (defun message-send-via-news (arg)
2032   "Send the current message via news."
2033   (message-send-news arg))
2034
2035 (defun message-fix-before-sending ()
2036   "Do various things to make the message nice before sending it."
2037   ;; Make sure there's a newline at the end of the message.
2038   (goto-char (point-max))
2039   (unless (bolp)
2040     (insert "\n"))
2041   ;; Make all invisible text visible.
2042   ;;(when (text-property-any (point-min) (point-max) 'invisible t)
2043   ;;  (put-text-property (point-min) (point-max) 'invisible nil)
2044   ;;  (unless (yes-or-no-p "Invisible text found and made visible; continue posting?")
2045   ;;    (error "Invisible text found and made visible")))
2046   )
2047
2048 (defun message-add-action (action &rest types)
2049   "Add ACTION to be performed when doing an exit of type TYPES."
2050   (let (var)
2051     (while types
2052       (set (setq var (intern (format "message-%s-actions" (pop types))))
2053            (nconc (symbol-value var) (list action))))))
2054
2055 (defun message-do-actions (actions)
2056   "Perform all actions in ACTIONS."
2057   ;; Now perform actions on successful sending.
2058   (while actions
2059     (ignore-errors
2060       (cond
2061        ;; A simple function.
2062        ((message-functionp (car actions))
2063         (funcall (car actions)))
2064        ;; Something to be evaled.
2065        (t
2066         (eval (car actions)))))
2067     (pop actions)))
2068
2069 (defun message-send-mail (&optional arg)
2070   (require 'mail-utils)
2071   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2072         (case-fold-search nil)
2073         (news (message-news-p)))
2074     (save-restriction
2075       (message-narrow-to-headers)
2076       ;; Insert some headers.
2077       (let ((message-deletable-headers
2078              (if news nil message-deletable-headers)))
2079         (message-generate-headers message-required-mail-headers))
2080       ;; Let the user do all of the above.
2081       (run-hooks 'message-header-hook))
2082     (unwind-protect
2083         (save-excursion
2084           (set-buffer tembuf)
2085           (erase-buffer)
2086           (insert-buffer message-encoding-buffer)
2087           ;; Remove some headers.
2088           (save-restriction
2089             (message-narrow-to-headers)
2090             ;; Remove some headers.
2091             (message-remove-header message-ignored-mail-headers t))
2092           (goto-char (point-max))
2093           ;; require one newline at the end.
2094           (or (= (preceding-char) ?\n)
2095               (insert ?\n))
2096           (when (and news
2097                      (or (message-fetch-field "cc")
2098                          (message-fetch-field "to")))
2099             (message-insert-courtesy-copy))
2100           (mime-edit-maybe-split-and-send
2101            (function
2102             (lambda ()
2103               (interactive)
2104               (funcall message-send-mail-function)
2105               )))
2106           (funcall message-send-mail-function))
2107       (kill-buffer tembuf))
2108     (set-buffer message-edit-buffer)
2109     (push 'mail message-sent-message-via)))
2110
2111 (defun message-send-mail-with-sendmail ()
2112   "Send off the prepared buffer with sendmail."
2113   (let ((errbuf (if message-interactive
2114                     (generate-new-buffer " sendmail errors")
2115                   0))
2116         resend-to-addresses delimline)
2117     (let ((case-fold-search t))
2118       (save-restriction
2119         (message-narrow-to-headers)
2120         (setq resend-to-addresses (message-fetch-field "resent-to")))
2121       ;; Change header-delimiter to be what sendmail expects.
2122       (goto-char (point-min))
2123       (re-search-forward
2124        (concat "^" (regexp-quote mail-header-separator) "\n"))
2125       (replace-match "\n")
2126       (backward-char 1)
2127       (setq delimline (point-marker))
2128       (run-hooks 'message-send-mail-hook)
2129       ;; Insert an extra newline if we need it to work around
2130       ;; Sun's bug that swallows newlines.
2131       (goto-char (1+ delimline))
2132       (when (eval message-mailer-swallows-blank-line)
2133         (newline))
2134       (when message-interactive
2135         (save-excursion
2136           (set-buffer errbuf)
2137           (erase-buffer))))
2138     (let ((default-directory "/")
2139           (coding-system-for-write message-send-coding-system))
2140       (apply 'call-process-region
2141              (append (list (point-min) (point-max)
2142                            (if (boundp 'sendmail-program)
2143                                sendmail-program
2144                              "/usr/lib/sendmail")
2145                            nil errbuf nil "-oi")
2146                      ;; Always specify who from,
2147                      ;; since some systems have broken sendmails.
2148                      ;; But some systems are more broken with -f, so
2149                      ;; we'll let users override this.
2150                      (if (null message-sendmail-f-is-evil)
2151                          (list "-f" (user-login-name)))
2152                      ;; These mean "report errors by mail"
2153                      ;; and "deliver in background".
2154                      (if (null message-interactive) '("-oem" "-odb"))
2155                      ;; Get the addresses from the message
2156                      ;; unless this is a resend.
2157                      ;; We must not do that for a resend
2158                      ;; because we would find the original addresses.
2159                      ;; For a resend, include the specific addresses.
2160                      (if resend-to-addresses
2161                          (list resend-to-addresses)
2162                        '("-t")))))
2163     (when message-interactive
2164       (save-excursion
2165         (set-buffer errbuf)
2166         (goto-char (point-min))
2167         (while (re-search-forward "\n\n* *" nil t)
2168           (replace-match "; "))
2169         (if (not (zerop (buffer-size)))
2170             (error "Sending...failed to %s"
2171                    (buffer-substring (point-min) (point-max)))))
2172       (when (bufferp errbuf)
2173         (kill-buffer errbuf)))))
2174
2175 (defun message-send-mail-with-qmail ()
2176   "Pass the prepared message buffer to qmail-inject.
2177 Refer to the documentation for the variable `message-send-mail-function'
2178 to find out how to use this."
2179   ;; replace the header delimiter with a blank line
2180   (goto-char (point-min))
2181   (re-search-forward
2182    (concat "^" (regexp-quote mail-header-separator) "\n"))
2183   (replace-match "\n")
2184   (run-hooks 'message-send-mail-hook)
2185   ;; send the message
2186   (case
2187       (let ((coding-system-for-write message-send-coding-system))
2188         (apply
2189          'call-process-region 1 (point-max) message-qmail-inject-program
2190          nil nil nil
2191          ;; qmail-inject's default behaviour is to look for addresses on the
2192          ;; command line; if there're none, it scans the headers.
2193          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2194          ;;
2195          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2196          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2197          ;; message from stdin.
2198          ;;
2199          ;; qmail also has the advantage of not having been raped by
2200          ;; various vendors, so we don't have to allow for that, either --
2201          ;; compare this with message-send-mail-with-sendmail and weep
2202          ;; for sendmail's lost innocence.
2203          ;;
2204          ;; all this is way cool coz it lets us keep the arguments entirely
2205          ;; free for -inject-arguments -- a big win for the user and for us
2206          ;; since we don't have to play that double-guessing game and the user
2207          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2208          message-qmail-inject-args))
2209     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2210     ;; we have to look at the retval instead
2211     (0 nil)
2212     (1   (error "qmail-inject reported permanent failure"))
2213     (111 (error "qmail-inject reported transient failure"))
2214     ;; should never happen
2215     (t   (error "qmail-inject reported unknown failure"))))
2216
2217 (defun message-send-mail-with-mh ()
2218   "Send the prepared message buffer with mh."
2219   (let ((mh-previous-window-config nil)
2220         (name (mh-new-draft-name)))
2221     (setq buffer-file-name name)
2222     ;; MH wants to generate these headers itself.
2223     (when message-mh-deletable-headers
2224       (let ((headers message-mh-deletable-headers))
2225         (while headers
2226           (goto-char (point-min))
2227           (and (re-search-forward
2228                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2229                (message-delete-line))
2230           (pop headers))))
2231     (run-hooks 'message-send-mail-hook)
2232     ;; Pass it on to mh.
2233     (mh-send-letter)))
2234
2235 (defun message-send-mail-with-smtp ()
2236   "Send the prepared message buffer with SMTP."
2237   (require 'smtp)
2238   (let ((errbuf (if mail-interactive
2239                     (generate-new-buffer " smtp errors")
2240                   0))
2241         (case-fold-search nil)
2242         resend-to-addresses
2243         delimline)
2244     (unwind-protect
2245         (save-excursion
2246           (goto-char (point-max))
2247           ;; require one newline at the end.
2248           (or (= (preceding-char) ?\n)
2249               (insert ?\n))
2250           ;; Change header-delimiter to be what sendmail expects.
2251           (goto-char (point-min))
2252           (re-search-forward
2253            (concat "^" (regexp-quote mail-header-separator) "\n"))
2254           (replace-match "\n")
2255           (backward-char 1)
2256           (setq delimline (point-marker))
2257           (run-hooks 'message-send-mail-hook)
2258           ;; (sendmail-synch-aliases)
2259           ;; (if mail-aliases
2260           ;;     (expand-mail-aliases (point-min) delimline))
2261           (goto-char (point-min))
2262           ;; ignore any blank lines in the header
2263           (while (and (re-search-forward "\n\n\n*" delimline t)
2264                       (< (point) delimline))
2265             (replace-match "\n"))
2266           (let ((case-fold-search t))
2267             (goto-char (point-min))
2268             (goto-char (point-min))
2269             (while (re-search-forward "^Resent-to:" delimline t)
2270               (setq resend-to-addresses
2271                     (save-restriction
2272                       (narrow-to-region (point)
2273                                         (save-excursion
2274                                           (end-of-line)
2275                                           (point)))
2276                       (append (mail-parse-comma-list)
2277                               resend-to-addresses))))
2278 ;;; Apparently this causes a duplicate Sender.
2279 ;;;         ;; If the From is different than current user, insert Sender.
2280 ;;;         (goto-char (point-min))
2281 ;;;         (and (re-search-forward "^From:"  delimline t)
2282 ;;;              (progn
2283 ;;;                (require 'mail-utils)
2284 ;;;                (not (string-equal
2285 ;;;                      (mail-strip-quoted-names
2286 ;;;                       (save-restriction
2287 ;;;                         (narrow-to-region (point-min) delimline)
2288 ;;;                         (mail-fetch-field "From")))
2289 ;;;                      (user-login-name))))
2290 ;;;              (progn
2291 ;;;                (forward-line 1)
2292 ;;;                (insert "Sender: " (user-login-name) "\n")))
2293             ;; Don't send out a blank subject line
2294             (goto-char (point-min))
2295             (if (re-search-forward "^Subject:[ \t]*\n" delimline t)
2296                 (replace-match ""))
2297             ;; Put the "From:" field in unless for some odd reason
2298             ;; they put one in themselves.
2299             (goto-char (point-min))
2300             (if (not (re-search-forward "^From:" delimline t))
2301                 (let* ((login user-mail-address)
2302                        (fullname (user-full-name)))
2303                   (cond ((eq mail-from-style 'angles)
2304                          (insert "From: " fullname)
2305                          (let ((fullname-start (+ (point-min) 6))
2306                                (fullname-end (point-marker)))
2307                            (goto-char fullname-start)
2308                            ;; Look for a character that cannot appear unquoted
2309                            ;; according to RFC 822.
2310                            (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
2311                                                   fullname-end 1)
2312                                (progn
2313                                  ;; Quote fullname, escaping specials.
2314                                  (goto-char fullname-start)
2315                                  (insert "\"")
2316                                  (while (re-search-forward "[\"\\]"
2317                                                            fullname-end 1)
2318                                    (replace-match "\\\\\\&" t))
2319                                  (insert "\""))))
2320                          (insert " <" login ">\n"))
2321                         ((eq mail-from-style 'parens)
2322                          (insert "From: " login " (")
2323                          (let ((fullname-start (point)))
2324                            (insert fullname)
2325                            (let ((fullname-end (point-marker)))
2326                              (goto-char fullname-start)
2327                              ;; RFC 822 says \ and nonmatching parentheses
2328                              ;; must be escaped in comments.
2329                              ;; Escape every instance of ()\ ...
2330                              (while (re-search-forward "[()\\]" fullname-end 1)
2331                                (replace-match "\\\\\\&" t))
2332                              ;; ... then undo escaping of matching parentheses,
2333                              ;; including matching nested parentheses.
2334                              (goto-char fullname-start)
2335                              (while (re-search-forward 
2336                                      "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2337                                      fullname-end 1)
2338                                (replace-match "\\1(\\3)" t)
2339                                (goto-char fullname-start))))
2340                          (insert ")\n"))
2341                         ((null mail-from-style)
2342                          (insert "From: " login "\n")))))
2343             ;; Insert an extra newline if we need it to work around
2344             ;; Sun's bug that swallows newlines.
2345             (goto-char (1+ delimline))
2346             (if (eval mail-mailer-swallows-blank-line)
2347                 (newline))
2348             ;; Find and handle any FCC fields.
2349             (goto-char (point-min))
2350             (if (re-search-forward "^FCC:" delimline t)
2351                 (mail-do-fcc delimline))
2352             (if mail-interactive
2353                 (save-excursion
2354                   (set-buffer errbuf)
2355                   (erase-buffer))))
2356           ;;
2357           ;;
2358           ;;
2359           (let ((recipient-address-list
2360                  (or resend-to-addresses
2361                      (smtp-deduce-address-list (current-buffer)
2362                                                (point-min) delimline))))
2363             (smtp-do-bcc delimline)
2364             
2365             (if recipient-address-list
2366                 (if (not (smtp-via-smtp recipient-address-list
2367                                         (current-buffer)))
2368                     (error "Sending failed; SMTP protocol error"))
2369               (error "Sending failed; no recipients"))
2370             ))
2371       (if (bufferp errbuf)
2372           (kill-buffer errbuf)))))
2373
2374 (defun message-send-news (&optional arg)
2375   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2376         (case-fold-search nil)
2377         (method (if (message-functionp message-post-method)
2378                     (funcall message-post-method arg)
2379                   message-post-method))
2380         (message-syntax-checks
2381          (if arg
2382              (cons '(existing-newsgroups . disabled)
2383                    message-syntax-checks)
2384            message-syntax-checks))
2385         result)
2386     (save-restriction
2387       (message-narrow-to-headers)
2388       ;; Insert some headers.
2389       (message-generate-headers message-required-news-headers)
2390       ;; Let the user do all of the above.
2391       (run-hooks 'message-header-hook))
2392     (message-cleanup-headers)
2393     (if (not (message-check-news-syntax))
2394         (progn
2395           ;;(message "Posting not performed")
2396           nil)
2397       (unwind-protect
2398           (save-excursion
2399             (set-buffer tembuf)
2400             (buffer-disable-undo (current-buffer))
2401             (erase-buffer)
2402             (insert-buffer message-encoding-buffer)
2403             ;; Remove some headers.
2404             (save-restriction
2405               (message-narrow-to-headers)
2406               ;; Remove some headers.
2407               (message-remove-header message-ignored-news-headers t))
2408             (goto-char (point-max))
2409             ;; require one newline at the end.
2410             (or (= (preceding-char) ?\n)
2411                 (insert ?\n))
2412             (mime-edit-maybe-split-and-send
2413              (function
2414               (lambda ()
2415                 (interactive)
2416                 (save-restriction
2417                   (std11-narrow-to-header mail-header-separator)
2418                   (goto-char (point-min))
2419                   (when (re-search-forward "^Message-Id:" nil t)
2420                     (delete-region (match-end 0)(std11-field-end))
2421                     (insert (concat " " (message-make-message-id)))
2422                     ))
2423                 (funcall message-send-news-function method)
2424                 )))
2425             (setq result (funcall message-send-news-function method)))
2426         (kill-buffer tembuf))
2427       (set-buffer message-edit-buffer)
2428       (if result
2429           (push 'news message-sent-message-via)
2430         (message "Couldn't send message via news: %s"
2431                  (nnheader-get-report (car method)))
2432         nil))))
2433
2434 ;; 1997-09-29 by MORIOKA Tomohiko
2435 (defun message-send-news-with-gnus (method)
2436   (let ((case-fold-search t))
2437     ;; Remove the delimiter.
2438     (goto-char (point-min))
2439     (re-search-forward
2440      (concat "^" (regexp-quote mail-header-separator) "\n"))
2441     (replace-match "\n")
2442     (backward-char 1)
2443     (run-hooks 'message-send-news-hook)
2444     ;;(require (car method))
2445     ;;(funcall (intern (format "%s-open-server" (car method)))
2446     ;;(cadr method) (cddr method))
2447     ;;(setq result
2448     ;;    (funcall (intern (format "%s-request-post" (car method)))
2449     ;;             (cadr method)))
2450     (gnus-open-server method)
2451     (gnus-request-post method)
2452     ))
2453
2454 ;;;
2455 ;;; Header generation & syntax checking.
2456 ;;;
2457
2458 (defmacro message-check (type &rest forms)
2459   "Eval FORMS if TYPE is to be checked."
2460   `(or (message-check-element ,type)
2461        (save-excursion
2462          ,@forms)))
2463
2464 (put 'message-check 'lisp-indent-function 1)
2465 (put 'message-check 'edebug-form-spec '(form body))
2466
2467 (defun message-check-element (type)
2468   "Returns non-nil if this type is not to be checked."
2469   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2470       t
2471     (let ((able (assq type message-syntax-checks)))
2472       (and (consp able)
2473            (eq (cdr able) 'disabled)))))
2474
2475 (defun message-check-news-syntax ()
2476   "Check the syntax of the message."
2477   (save-excursion
2478     (save-restriction
2479       (widen)
2480       (and
2481        ;; We narrow to the headers and check them first.
2482        (save-excursion
2483          (save-restriction
2484            (message-narrow-to-headers)
2485            (message-check-news-header-syntax)))
2486        ;; Check the body.
2487        (save-excursion
2488          (set-buffer message-edit-buffer)
2489          (message-check-news-body-syntax))))))
2490
2491 (defun message-check-news-header-syntax ()
2492   (and
2493    ;; Check the Subject header.
2494    (message-check 'subject
2495      (let* ((case-fold-search t)
2496             (subject (message-fetch-field "subject")))
2497        (or
2498         (and subject
2499              (not (string-match "\\`[ \t]*\\'" subject)))
2500         (ignore
2501          (message
2502           "The subject field is empty or missing.  Posting is denied.")))))
2503    ;; Check for commands in Subject.
2504    (message-check 'subject-cmsg
2505      (if (string-match "^cmsg " (message-fetch-field "subject"))
2506          (y-or-n-p
2507           "The control code \"cmsg\" is in the subject.  Really post? ")
2508        t))
2509    ;; Check for multiple identical headers.
2510    (message-check 'multiple-headers
2511      (let (found)
2512        (while (and (not found)
2513                    (re-search-forward "^[^ \t:]+: " nil t))
2514          (save-excursion
2515            (or (re-search-forward
2516                 (concat "^"
2517                         (regexp-quote
2518                          (setq found
2519                                (buffer-substring
2520                                 (match-beginning 0) (- (match-end 0) 2))))
2521                         ":")
2522                 nil t)
2523                (setq found nil))))
2524        (if found
2525            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2526          t)))
2527    ;; Check for Version and Sendsys.
2528    (message-check 'sendsys
2529      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2530          (y-or-n-p
2531           (format "The article contains a %s command.  Really post? "
2532                   (buffer-substring (match-beginning 0)
2533                                     (1- (match-end 0)))))
2534        t))
2535    ;; See whether we can shorten Followup-To.
2536    (message-check 'shorten-followup-to
2537      (let ((newsgroups (message-fetch-field "newsgroups"))
2538            (followup-to (message-fetch-field "followup-to"))
2539            to)
2540        (when (and newsgroups
2541                   (string-match "," newsgroups)
2542                   (not followup-to)
2543                   (not
2544                    (zerop
2545                     (length
2546                      (setq to (completing-read
2547                                "Followups to: (default all groups) "
2548                                (mapcar (lambda (g) (list g))
2549                                        (cons "poster"
2550                                              (message-tokenize-header
2551                                               newsgroups)))))))))
2552          (goto-char (point-min))
2553          (insert "Followup-To: " to "\n"))
2554        t))
2555    ;; Check "Shoot me".
2556    (message-check 'shoot
2557      (if (re-search-forward
2558           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2559          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2560        t))
2561    ;; Check for Approved.
2562    (message-check 'approved
2563      (if (re-search-forward "^Approved:" nil t)
2564          (y-or-n-p "The article contains an Approved header.  Really post? ")
2565        t))
2566    ;; Check the Message-ID header.
2567    (message-check 'message-id
2568      (let* ((case-fold-search t)
2569             (message-id (message-fetch-field "message-id" t)))
2570        (or (not message-id)
2571            ;; Is there an @ in the ID?
2572            (and (string-match "@" message-id)
2573                 ;; Is there a dot in the ID?
2574                 (string-match "@[^.]*\\." message-id)
2575                 ;; Does the ID end with a dot?
2576                 (not (string-match "\\.>" message-id)))
2577            (y-or-n-p
2578             (format "The Message-ID looks strange: \"%s\".  Really post? "
2579                     message-id)))))
2580    ;; Check the Newsgroups & Followup-To headers.
2581    (message-check 'existing-newsgroups
2582      (let* ((case-fold-search t)
2583             (newsgroups (message-fetch-field "newsgroups"))
2584             (followup-to (message-fetch-field "followup-to"))
2585             (groups (message-tokenize-header
2586                      (if followup-to
2587                          (concat newsgroups "," followup-to)
2588                        newsgroups)))
2589             (hashtb (and (boundp 'gnus-active-hashtb)
2590                          gnus-active-hashtb))
2591             errors)
2592        (if (or (not hashtb)
2593                (not (boundp 'gnus-read-active-file))
2594                (not gnus-read-active-file)
2595                (eq gnus-read-active-file 'some))
2596            t
2597          (while groups
2598            (when (and (not (boundp (intern (car groups) hashtb)))
2599                       (not (equal (car groups) "poster")))
2600              (push (car groups) errors))
2601            (pop groups))
2602          (if (not errors)
2603              t
2604            (y-or-n-p
2605             (format
2606              "Really post to %s unknown group%s: %s "
2607              (if (= (length errors) 1) "this" "these")
2608              (if (= (length errors) 1) "" "s")
2609              (mapconcat 'identity errors ", ")))))))
2610    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2611    (message-check 'valid-newsgroups
2612      (let ((case-fold-search t)
2613            (headers '("Newsgroups" "Followup-To"))
2614            header error)
2615        (while (and headers (not error))
2616          (when (setq header (mail-fetch-field (car headers)))
2617            (if (or
2618                 (not
2619                  (string-match
2620                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2621                   header))
2622                 (memq
2623                  nil (mapcar
2624                       (lambda (g)
2625                         (not (string-match "\\.\\'\\|\\.\\." g)))
2626                       (message-tokenize-header header ","))))
2627                (setq error t)))
2628          (unless error
2629            (pop headers)))
2630        (if (not error)
2631            t
2632          (y-or-n-p
2633           (format "The %s header looks odd: \"%s\".  Really post? "
2634                   (car headers) header)))))
2635    (message-check 'repeated-newsgroups
2636      (let ((case-fold-search t)
2637            (headers '("Newsgroups" "Followup-To"))
2638            header error groups group)
2639        (while (and headers
2640                    (not error))
2641          (when (setq header (mail-fetch-field (pop headers)))
2642            (setq groups (message-tokenize-header header ","))
2643            (while (setq group (pop groups))
2644              (when (member group groups)
2645                (setq error group
2646                      groups nil)))))
2647        (if (not error)
2648            t
2649          (y-or-n-p
2650           (format "Group %s is repeated in headers.  Really post? " error)))))
2651    ;; Check the From header.
2652    (message-check 'from
2653      (let* ((case-fold-search t)
2654             (from (message-fetch-field "from"))
2655             (ad (nth 1 (mail-extract-address-components from))))
2656        (cond
2657         ((not from)
2658          (message "There is no From line.  Posting is denied.")
2659          nil)
2660         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2661              (string-match "\\.\\." ad) ;larsi@ifi..uio
2662              (string-match "@\\." ad)   ;larsi@.ifi.uio
2663              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2664              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2665              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2666          (message
2667           "Denied posting -- the From looks strange: \"%s\"." from)
2668          nil)
2669         (t t))))))
2670
2671 (defun message-check-news-body-syntax ()
2672   (and
2673    ;; Check for long lines.
2674    (message-check 'long-lines
2675      (goto-char (point-min))
2676      (re-search-forward
2677       (concat "^" (regexp-quote mail-header-separator) "$"))
2678      (while (and
2679              (progn
2680                (end-of-line)
2681                (< (current-column) 80))
2682              (zerop (forward-line 1))))
2683      (or (bolp)
2684          (eobp)
2685          (y-or-n-p
2686           "You have lines longer than 79 characters.  Really post? ")))
2687    ;; Check whether the article is empty.
2688    (message-check 'empty
2689      (goto-char (point-min))
2690      (re-search-forward
2691       (concat "^" (regexp-quote mail-header-separator) "$"))
2692      (forward-line 1)
2693      (let ((b (point)))
2694        (goto-char (point-max))
2695        (re-search-backward message-signature-separator nil t)
2696        (beginning-of-line)
2697        (or (re-search-backward "[^ \n\t]" b t)
2698            (y-or-n-p "Empty article.  Really post? "))))
2699    ;; Check for control characters.
2700    (message-check 'control-chars
2701      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2702          (y-or-n-p
2703           "The article contains control characters.  Really post? ")
2704        t))
2705    ;; Check excessive size.
2706    (message-check 'size
2707      (if (> (buffer-size) 60000)
2708          (y-or-n-p
2709           (format "The article is %d octets long.  Really post? "
2710                   (buffer-size)))
2711        t))
2712    ;; Check whether any new text has been added.
2713    (message-check 'new-text
2714      (or
2715       (not message-checksum)
2716       (not (eq (message-checksum) message-checksum))
2717       (y-or-n-p
2718        "It looks like no new text has been added.  Really post? ")))
2719    ;; Check the length of the signature.
2720    (message-check 'signature
2721      (goto-char (point-max))
2722      (if (or (not (re-search-backward message-signature-separator nil t))
2723              (search-forward message-forward-end-separator nil t))
2724          t
2725        (if (> (count-lines (point) (point-max)) 5)
2726            (y-or-n-p
2727             (format
2728              "Your .sig is %d lines; it should be max 4.  Really post? "
2729              (1- (count-lines (point) (point-max)))))
2730          t)))))
2731
2732 (defun message-checksum ()
2733   "Return a \"checksum\" for the current buffer."
2734   (let ((sum 0))
2735     (save-excursion
2736       (goto-char (point-min))
2737       (re-search-forward
2738        (concat "^" (regexp-quote mail-header-separator) "$"))
2739       (while (not (eobp))
2740         (when (not (looking-at "[ \t\n]"))
2741           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2742                             (following-char))))
2743         (forward-char 1)))
2744     sum))
2745
2746 (defun message-do-fcc ()
2747   "Process Fcc headers in the current buffer."
2748   (let ((case-fold-search t)
2749         (coding-system-for-write 'raw-text)
2750         list file)
2751     (save-excursion
2752       (set-buffer (get-buffer-create " *message temp*"))
2753       (buffer-disable-undo (current-buffer))
2754       (erase-buffer)
2755       (insert-buffer-substring message-encoding-buffer)
2756       (save-restriction
2757         (message-narrow-to-headers)
2758         (while (setq file (message-fetch-field "fcc"))
2759           (push file list)
2760           (message-remove-header "fcc" nil t)))
2761       (run-hooks 'message-header-hook 'message-before-do-fcc-hook)
2762       (goto-char (point-min))
2763       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2764       (replace-match "" t t)
2765       ;; Process FCC operations.
2766       (while list
2767         (setq file (pop list))
2768         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2769             ;; Pipe the article to the program in question.
2770             (call-process-region (point-min) (point-max) shell-file-name
2771                                  nil nil nil shell-command-switch
2772                                  (match-string 1 file))
2773           ;; Save the article.
2774           (setq file (expand-file-name file))
2775           (unless (file-exists-p (file-name-directory file))
2776             (make-directory (file-name-directory file) t))
2777           (if (and message-fcc-handler-function
2778                    (not (eq message-fcc-handler-function 'rmail-output)))
2779               (funcall message-fcc-handler-function file)
2780             (if (and (file-readable-p file) (mail-file-babyl-p file))
2781                 (rmail-output file 1 nil t)
2782               (let ((mail-use-rfc822 t))
2783                 (rmail-output file 1 t t))))))
2784
2785       (kill-buffer (current-buffer)))))
2786
2787 (defun message-output (filename)
2788   "Append this article to Unix/babyl mail file.."
2789   (if (and (file-readable-p filename)
2790            (mail-file-babyl-p filename))
2791       (gnus-output-to-rmail filename t)
2792     (gnus-output-to-mail filename t)))
2793
2794 (defun message-cleanup-headers ()
2795   "Do various automatic cleanups of the headers."
2796   ;; Remove empty lines in the header.
2797   (save-restriction
2798     (message-narrow-to-headers)
2799     ;; Remove blank lines.
2800     (while (re-search-forward "^[ \t]*\n" nil t)
2801       (replace-match "" t t))
2802
2803     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2804     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2805     ;; embedded line breaks.
2806     (goto-char (point-min))
2807     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2808       (save-restriction
2809         (narrow-to-region
2810          (point)
2811          (if (re-search-forward "^[^ \t]" nil t)
2812              (match-beginning 0)
2813            (forward-line 1)
2814            (point)))
2815         (goto-char (point-min))
2816         (while (re-search-forward "\n[ \t]+" nil t)
2817           (replace-match " " t t))      ;No line breaks (too confusing)
2818         (goto-char (point-min))
2819         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2820           (replace-match "," t t))
2821         (goto-char (point-min))
2822         ;; Remove trailing commas.
2823         (when (re-search-forward ",+$" nil t)
2824           (replace-match "" t t))))))
2825
2826 (defun message-make-date ()
2827   "Make a valid data header."
2828   (let ((now (current-time)))
2829     (timezone-make-date-arpa-standard
2830      (current-time-string now) (current-time-zone now))))
2831
2832 (defun message-make-message-id ()
2833   "Make a unique Message-ID."
2834   (concat "<" (message-unique-id)
2835           (let ((psubject (save-excursion (message-fetch-field "subject")))
2836                 (psupersedes
2837                  (save-excursion (message-fetch-field "supersedes"))))
2838             (if (or
2839                  (and message-reply-headers
2840                       (mail-header-references message-reply-headers)
2841                       (mail-header-subject message-reply-headers)
2842                       psubject
2843                       (mail-header-subject message-reply-headers)
2844                       (not (string=
2845                             (message-strip-subject-re
2846                              (mail-header-subject message-reply-headers))
2847                             (message-strip-subject-re psubject))))
2848                  (and psupersedes
2849                       (string-match "_-_@" psupersedes)))
2850                 "_-_" ""))
2851           "@" (message-make-fqdn) ">"))
2852
2853 (defvar message-unique-id-char nil)
2854
2855 ;; If you ever change this function, make sure the new version
2856 ;; cannot generate IDs that the old version could.
2857 ;; You might for example insert a "." somewhere (not next to another dot
2858 ;; or string boundary), or modify the "fsf" string.
2859 (defun message-unique-id ()
2860   ;; Don't use microseconds from (current-time), they may be unsupported.
2861   ;; Instead we use this randomly inited counter.
2862   (setq message-unique-id-char
2863         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2864            ;; (current-time) returns 16-bit ints,
2865            ;; and 2^16*25 just fits into 4 digits i base 36.
2866            (* 25 25)))
2867   (let ((tm (current-time)))
2868     (concat
2869      (if (memq system-type '(ms-dos emx vax-vms))
2870          (let ((user (downcase (user-login-name))))
2871            (while (string-match "[^a-z0-9_]" user)
2872              (aset user (match-beginning 0) ?_))
2873            user)
2874        (message-number-base36 (user-uid) -1))
2875      (message-number-base36 (+ (car   tm)
2876                                (lsh (% message-unique-id-char 25) 16)) 4)
2877      (message-number-base36 (+ (nth 1 tm)
2878                                (lsh (/ message-unique-id-char 25) 16)) 4)
2879      ;; Append the newsreader name, because while the generated
2880      ;; ID is unique to this newsreader, other newsreaders might
2881      ;; otherwise generate the same ID via another algorithm.
2882      ".fsf")))
2883
2884 (defun message-number-base36 (num len)
2885   (if (if (< len 0)
2886           (<= num 0)
2887         (= len 0))
2888       ""
2889     (concat (message-number-base36 (/ num 36) (1- len))
2890             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2891                                   (% num 36))))))
2892
2893 (defun message-make-organization ()
2894   "Make an Organization header."
2895   (let* ((organization
2896           (when message-user-organization
2897                 (if (message-functionp message-user-organization)
2898                     (funcall message-user-organization)
2899                   message-user-organization))))
2900     (save-excursion
2901       (message-set-work-buffer)
2902       (cond ((stringp organization)
2903              (insert organization))
2904             ((and (eq t organization)
2905                   message-user-organization-file
2906                   (file-exists-p message-user-organization-file))
2907              (insert-file-contents message-user-organization-file)))
2908       (goto-char (point-min))
2909       (while (re-search-forward "[\t\n]+" nil t)
2910         (replace-match "" t t))
2911       (unless (zerop (buffer-size))
2912         (buffer-string)))))
2913
2914 (defun message-make-lines ()
2915   "Count the number of lines and return numeric string."
2916   (save-excursion
2917     (save-restriction
2918       (widen)
2919       (goto-char (point-min))
2920       (re-search-forward
2921        (concat "^" (regexp-quote mail-header-separator) "$"))
2922       (forward-line 1)
2923       (int-to-string (count-lines (point) (point-max))))))
2924
2925 (defun message-make-in-reply-to ()
2926   "Return the In-Reply-To header for this message."
2927   (when message-reply-headers
2928     (let ((from (mail-header-from message-reply-headers))
2929           (date (mail-header-date message-reply-headers)))
2930       (when from
2931         (let ((stop-pos
2932                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2933           (concat (if (and stop-pos
2934                            (not (zerop stop-pos)))
2935                       (substring from 0 stop-pos) from)
2936                   "'s message of \""
2937                   (if (or (not date) (string= date ""))
2938                       "(unknown date)" date)
2939                   "\""))))))
2940
2941 (defun message-make-distribution ()
2942   "Make a Distribution header."
2943   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2944     (cond ((message-functionp message-distribution-function)
2945            (funcall message-distribution-function))
2946           (t orig-distribution))))
2947
2948 (defun message-make-expires ()
2949   "Return an Expires header based on `message-expires'."
2950   (let ((current (current-time))
2951         (future (* 1.0 message-expires 60 60 24)))
2952     ;; Add the future to current.
2953     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2954     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2955     ;; Return the date in the future in UT.
2956     (timezone-make-date-arpa-standard
2957      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2958
2959 (defun message-make-path ()
2960   "Return uucp path."
2961   (let ((login-name (user-login-name)))
2962     (cond ((null message-user-path)
2963            (concat (system-name) "!" login-name))
2964           ((stringp message-user-path)
2965            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2966            (concat message-user-path "!" login-name))
2967           (t login-name))))
2968
2969 (defun message-make-from ()
2970   "Make a From header."
2971   (let* ((style message-from-style)
2972          (login (message-make-address))
2973          (fullname
2974           (or (and (boundp 'user-full-name)
2975                    user-full-name)
2976               (user-full-name))))
2977     (when (string= fullname "&")
2978       (setq fullname (user-login-name)))
2979     (save-excursion
2980       (message-set-work-buffer)
2981       (cond
2982        ((or (null style)
2983             (equal fullname ""))
2984         (insert login))
2985        ((or (eq style 'angles)
2986             (and (not (eq style 'parens))
2987                  ;; Use angles if no quoting is needed, or if parens would
2988                  ;; need quoting too.
2989                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2990                      (let ((tmp (concat fullname nil)))
2991                        (while (string-match "([^()]*)" tmp)
2992                          (aset tmp (match-beginning 0) ?-)
2993                          (aset tmp (1- (match-end 0)) ?-))
2994                        (string-match "[\\()]" tmp)))))
2995         (insert fullname)
2996         (goto-char (point-min))
2997         ;; Look for a character that cannot appear unquoted
2998         ;; according to RFC 822.
2999         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3000           ;; Quote fullname, escaping specials.
3001           (goto-char (point-min))
3002           (insert "\"")
3003           (while (re-search-forward "[\"\\]" nil 1)
3004             (replace-match "\\\\\\&" t))
3005           (insert "\""))
3006         (insert " <" login ">"))
3007        (t                               ; 'parens or default
3008         (insert login " (")
3009         (let ((fullname-start (point)))
3010           (insert fullname)
3011           (goto-char fullname-start)
3012           ;; RFC 822 says \ and nonmatching parentheses
3013           ;; must be escaped in comments.
3014           ;; Escape every instance of ()\ ...
3015           (while (re-search-forward "[()\\]" nil 1)
3016             (replace-match "\\\\\\&" t))
3017           ;; ... then undo escaping of matching parentheses,
3018           ;; including matching nested parentheses.
3019           (goto-char fullname-start)
3020           (while (re-search-forward
3021                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3022                   nil 1)
3023             (replace-match "\\1(\\3)" t)
3024             (goto-char fullname-start)))
3025         (insert ")")))
3026       (buffer-string))))
3027
3028 (defun message-make-sender ()
3029   "Return the \"real\" user address.
3030 This function tries to ignore all user modifications, and
3031 give as trustworthy answer as possible."
3032   (concat (user-login-name) "@" (system-name)))
3033
3034 (defun message-make-address ()
3035   "Make the address of the user."
3036   (or (message-user-mail-address)
3037       (concat (user-login-name) "@" (message-make-domain))))
3038
3039 (defun message-user-mail-address ()
3040   "Return the pertinent part of `user-mail-address'."
3041   (when user-mail-address
3042     (if (string-match " " user-mail-address)
3043         (nth 1 (mail-extract-address-components user-mail-address))
3044       user-mail-address)))
3045
3046 (defun message-make-fqdn ()
3047   "Return user's fully qualified domain name."
3048   (let ((system-name (system-name))
3049         (user-mail (message-user-mail-address)))
3050     (cond
3051      ((string-match "[^.]\\.[^.]" system-name)
3052       ;; `system-name' returned the right result.
3053       system-name)
3054      ;; Try `mail-host-address'.
3055      ((and (boundp 'mail-host-address)
3056            (stringp mail-host-address)
3057            (string-match "\\." mail-host-address))
3058       mail-host-address)
3059      ;; We try `user-mail-address' as a backup.
3060      ((and user-mail
3061            (string-match "\\." user-mail)
3062            (string-match "@\\(.*\\)\\'" user-mail))
3063       (match-string 1 user-mail))
3064      ;; Default to this bogus thing.
3065      (t
3066       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3067
3068 (defun message-make-host-name ()
3069   "Return the name of the host."
3070   (let ((fqdn (message-make-fqdn)))
3071     (string-match "^[^.]+\\." fqdn)
3072     (substring fqdn 0 (1- (match-end 0)))))
3073
3074 (defun message-make-domain ()
3075   "Return the domain name."
3076   (or mail-host-address
3077       (message-make-fqdn)))
3078
3079 (defun message-generate-headers (headers)
3080   "Prepare article HEADERS.
3081 Headers already prepared in the buffer are not modified."
3082   (save-restriction
3083     (message-narrow-to-headers)
3084     (let* ((Date (message-make-date))
3085            (Message-ID (message-make-message-id))
3086            (Organization (message-make-organization))
3087            (From (message-make-from))
3088            (Path (message-make-path))
3089            (Subject nil)
3090            (Newsgroups nil)
3091            (In-Reply-To (message-make-in-reply-to))
3092            (To nil)
3093            (Distribution (message-make-distribution))
3094            (Lines (message-make-lines))
3095            (X-Newsreader message-newsreader)
3096            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
3097                           message-mailer))
3098            (Expires (message-make-expires))
3099            (case-fold-search t)
3100            header value elem)
3101       ;; First we remove any old generated headers.
3102       (let ((headers message-deletable-headers))
3103         (unless (buffer-modified-p)
3104           (setq headers (delq 'Message-ID (copy-sequence headers))))
3105         (while headers
3106           (goto-char (point-min))
3107           (and (re-search-forward
3108                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3109                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3110                (message-delete-line))
3111           (pop headers)))
3112       ;; Go through all the required headers and see if they are in the
3113       ;; articles already.  If they are not, or are empty, they are
3114       ;; inserted automatically - except for Subject, Newsgroups and
3115       ;; Distribution.
3116       (while headers
3117         (goto-char (point-min))
3118         (setq elem (pop headers))
3119         (if (consp elem)
3120             (if (eq (car elem) 'optional)
3121                 (setq header (cdr elem))
3122               (setq header (car elem)))
3123           (setq header elem))
3124         (when (or (not (re-search-forward
3125                         (concat "^"
3126                                 (regexp-quote
3127                                  (downcase
3128                                   (if (stringp header)
3129                                       header
3130                                     (symbol-name header))))
3131                                 ":")
3132                         nil t))
3133                   (progn
3134                     ;; The header was found.  We insert a space after the
3135                     ;; colon, if there is none.
3136                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
3137                     ;; Find out whether the header is empty...
3138                     (looking-at "[ \t]*$")))
3139           ;; So we find out what value we should insert.
3140           (setq value
3141                 (cond
3142                  ((and (consp elem) (eq (car elem) 'optional))
3143                   ;; This is an optional header.  If the cdr of this
3144                   ;; is something that is nil, then we do not insert
3145                   ;; this header.
3146                   (setq header (cdr elem))
3147                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3148                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3149                  ((consp elem)
3150                   ;; The element is a cons.  Either the cdr is a
3151                   ;; string to be inserted verbatim, or it is a
3152                   ;; function, and we insert the value returned from
3153                   ;; this function.
3154                   (or (and (stringp (cdr elem)) (cdr elem))
3155                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3156                  ((and (boundp header) (symbol-value header))
3157                   ;; The element is a symbol.  We insert the value
3158                   ;; of this symbol, if any.
3159                   (symbol-value header))
3160                  (t
3161                   ;; We couldn't generate a value for this header,
3162                   ;; so we just ask the user.
3163                   (read-from-minibuffer
3164                    (format "Empty header for %s; enter value: " header)))))
3165           ;; Finally insert the header.
3166           (when (and value
3167                      (not (equal value "")))
3168             (save-excursion
3169               (if (bolp)
3170                   (progn
3171                     ;; This header didn't exist, so we insert it.
3172                     (goto-char (point-max))
3173                     (insert (if (stringp header) header (symbol-name header))
3174                             ": " value "\n")
3175                     (forward-line -1))
3176                 ;; The value of this header was empty, so we clear
3177                 ;; totally and insert the new value.
3178                 (delete-region (point) (gnus-point-at-eol))
3179                 (insert value))
3180               ;; Add the deletable property to the headers that require it.
3181               (and (memq header message-deletable-headers)
3182                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3183                    (add-text-properties
3184                     (point) (match-end 0)
3185                     '(message-deletable t face italic) (current-buffer)))))))
3186       ;; Insert new Sender if the From is strange.
3187       (let ((from (message-fetch-field "from"))
3188             (sender (message-fetch-field "sender"))
3189             (secure-sender (message-make-sender)))
3190         (when (and from
3191                    (not (message-check-element 'sender))
3192                    (not (string=
3193                          (downcase
3194                           (cadr (mail-extract-address-components from)))
3195                          (downcase secure-sender)))
3196                    (or (null sender)
3197                        (not
3198                         (string=
3199                          (downcase
3200                           (cadr (mail-extract-address-components sender)))
3201                          (downcase secure-sender)))))
3202           (goto-char (point-min))
3203           ;; Rename any old Sender headers to Original-Sender.
3204           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3205             (beginning-of-line)
3206             (insert "Original-")
3207             (beginning-of-line))
3208           (when (or (message-news-p)
3209                     (string-match "@.+\\.." secure-sender))
3210             (insert "Sender: " secure-sender "\n")))))))
3211
3212 (defun message-insert-courtesy-copy ()
3213   "Insert a courtesy message in mail copies of combined messages."
3214   (let (newsgroups)
3215     (save-excursion
3216       (save-restriction
3217         (message-narrow-to-headers)
3218         (when (setq newsgroups (message-fetch-field "newsgroups"))
3219           (goto-char (point-max))
3220           (insert "Posted-To: " newsgroups "\n")))
3221       (forward-line 1)
3222       (when message-courtesy-message
3223         (cond
3224          ((string-match "%s" message-courtesy-message)
3225           (insert (format message-courtesy-message newsgroups)))
3226          (t
3227           (insert message-courtesy-message)))))))
3228
3229 ;;;
3230 ;;; Setting up a message buffer
3231 ;;;
3232
3233 (defun message-fill-address (header value)
3234   (save-restriction
3235     (narrow-to-region (point) (point))
3236     (insert (capitalize (symbol-name header))
3237             ": "
3238             (if (consp value) (car value) value)
3239             "\n")
3240     (narrow-to-region (point-min) (1- (point-max)))
3241     (let (quoted last)
3242       (goto-char (point-min))
3243       (while (not (eobp))
3244         (skip-chars-forward "^,\"" (point-max))
3245         (if (or (= (following-char) ?,)
3246                 (eobp))
3247             (when (not quoted)
3248               (if (and (> (current-column) 78)
3249                        last)
3250                   (progn
3251                     (save-excursion
3252                       (goto-char last)
3253                       (insert "\n\t"))
3254                     (setq last (1+ (point))))
3255                 (setq last (1+ (point)))))
3256           (setq quoted (not quoted)))
3257         (unless (eobp)
3258           (forward-char 1))))
3259     (goto-char (point-max))
3260     (widen)
3261     (forward-line 1)))
3262
3263 (defun message-fill-references (header value)
3264   (insert (capitalize (symbol-name header))
3265           ": "
3266           (std11-fill-msg-id-list-string
3267            (if (consp value) (car value) value))
3268           "\n"))
3269
3270 (defun message-fill-header (header value)
3271   (let ((begin (point))
3272         (fill-column 990)
3273         (fill-prefix "\t"))
3274     (insert (capitalize (symbol-name header))
3275             ": "
3276             (if (consp value) (car value) value)
3277             "\n")
3278     (save-restriction
3279       (narrow-to-region begin (point))
3280       (fill-region-as-paragraph begin (point))
3281       ;; Tapdance around looong Message-IDs.
3282       (forward-line -1)
3283       (when (looking-at "[ \t]*$")
3284         (message-delete-line))
3285       (goto-char begin)
3286       (re-search-forward ":" nil t)
3287       (when (looking-at "\n[ \t]+")
3288         (replace-match " " t t))
3289       (goto-char (point-max)))))
3290
3291 (defun message-shorten-references (header references)
3292   "Limit REFERENCES to be shorter than 988 characters."
3293   (let ((max 988)
3294         (cut 4)
3295         refs)
3296     (nnheader-temp-write nil
3297       (insert references)
3298       (goto-char (point-min))
3299       (while (re-search-forward "<[^>]+>" nil t)
3300         (push (match-string 0) refs))
3301       (setq refs (nreverse refs))
3302       (while (> (length (mapconcat 'identity refs " ")) max)
3303         (when (< (length refs) (1+ cut))
3304           (decf cut))
3305         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3306     (insert (capitalize (symbol-name header)) ": "
3307             (mapconcat 'identity refs " ") "\n")))
3308
3309 (defun message-position-point ()
3310   "Move point to where the user probably wants to find it."
3311   (message-narrow-to-headers)
3312   (cond
3313    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3314     (search-backward ":" )
3315     (widen)
3316     (forward-char 1)
3317     (if (= (following-char) ? )
3318         (forward-char 1)
3319       (insert " ")))
3320    (t
3321     (goto-char (point-max))
3322     (widen)
3323     (forward-line 1)
3324     (unless (looking-at "$")
3325       (forward-line 2)))
3326    (sit-for 0)))
3327
3328 (defun message-buffer-name (type &optional to group)
3329   "Return a new (unique) buffer name based on TYPE and TO."
3330   (cond
3331    ;; Check whether `message-generate-new-buffers' is a function,
3332    ;; and if so, call it.
3333    ((message-functionp message-generate-new-buffers)
3334     (funcall message-generate-new-buffers type to group))
3335    ;; Generate a new buffer name The Message Way.
3336    (message-generate-new-buffers
3337     (generate-new-buffer-name
3338      (concat "*" type
3339              (if to
3340                  (concat " to "
3341                          (or (car (mail-extract-address-components to))
3342                              to) "")
3343                "")
3344              (if (and group (not (string= group ""))) (concat " on " group) "")
3345              "*")))
3346    ;; Use standard name.
3347    (t
3348     (format "*%s message*" type))))
3349
3350 (defun message-pop-to-buffer (name)
3351   "Pop to buffer NAME, and warn if it already exists and is modified."
3352   (let ((pop-up-frames pop-up-frames)
3353         (special-display-buffer-names special-display-buffer-names)
3354         (special-display-regexps special-display-regexps)
3355         (same-window-buffer-names same-window-buffer-names)
3356         (same-window-regexps same-window-regexps)
3357         (buffer (get-buffer name))
3358         (cur (current-buffer)))
3359     (if (or (and (featurep 'xemacs)
3360                  (not (eq 'tty (device-type))))
3361             window-system
3362             (>= emacs-major-version 20))
3363         (when message-use-multi-frames
3364           (setq pop-up-frames t
3365                 special-display-buffer-names nil
3366                 special-display-regexps nil
3367                 same-window-buffer-names nil
3368                 same-window-regexps nil))
3369       (setq pop-up-frames nil))
3370     (if (and buffer
3371              (buffer-name buffer))
3372         (progn
3373           (set-buffer (pop-to-buffer buffer))
3374           (when (and (buffer-modified-p)
3375                      (not (y-or-n-p
3376                            "Message already being composed; erase? ")))
3377             (error "Message being composed")))
3378       (set-buffer (pop-to-buffer name)))
3379     (erase-buffer)
3380     (message-mode)
3381     (when pop-up-frames
3382       (make-local-variable 'message-original-frame)
3383       (setq message-original-frame (selected-frame)))))
3384
3385 (defun message-do-send-housekeeping ()
3386   "Kill old message buffers."
3387   ;; We might have sent this buffer already.  Delete it from the
3388   ;; list of buffers.
3389   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3390   (while (and message-max-buffers
3391               message-buffer-list
3392               (>= (length message-buffer-list) message-max-buffers))
3393     ;; Kill the oldest buffer -- unless it has been changed.
3394     (let ((buffer (pop message-buffer-list)))
3395       (when (and (buffer-name buffer)
3396                  (not (buffer-modified-p buffer)))
3397         (kill-buffer buffer))))
3398   ;; Rename the buffer.
3399   (if message-send-rename-function
3400       (funcall message-send-rename-function)
3401     (when (string-match "\\`\\*" (buffer-name))
3402       (rename-buffer
3403        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3404   ;; Push the current buffer onto the list.
3405   (when message-max-buffers
3406     (setq message-buffer-list
3407           (nconc message-buffer-list (list (current-buffer))))))
3408
3409 (defvar mc-modes-alist)
3410 (defun message-setup (headers &optional replybuffer actions)
3411   (when (and (boundp 'mc-modes-alist)
3412              (not (assq 'message-mode mc-modes-alist)))
3413     (push '(message-mode (encrypt . mc-encrypt-message)
3414                          (sign . mc-sign-message))
3415           mc-modes-alist))
3416   (when actions
3417     (setq message-send-actions actions))
3418   (setq message-reply-buffer replybuffer)
3419   (goto-char (point-min))
3420   ;; Insert all the headers.
3421   (mail-header-format
3422    (let ((h headers)
3423          (alist message-header-format-alist))
3424      (while h
3425        (unless (assq (caar h) message-header-format-alist)
3426          (push (list (caar h)) alist))
3427        (pop h))
3428      alist)
3429    headers)
3430   (delete-region (point) (progn (forward-line -1) (point)))
3431   (when message-default-headers
3432     (insert message-default-headers)
3433     (or (bolp) (insert ?\n)))
3434   (put-text-property
3435    (point)
3436    (progn
3437      (insert mail-header-separator "\n")
3438      (1- (point)))
3439    'read-only nil)
3440   (forward-line -1)
3441   (when (message-news-p)
3442     (when message-default-news-headers
3443       (insert message-default-news-headers)
3444       (or (bolp) (insert ?\n)))
3445     (when message-generate-headers-first
3446       (message-generate-headers
3447        (delq 'Lines
3448              (delq 'Subject
3449                    (copy-sequence message-required-news-headers))))))
3450   (when (message-mail-p)
3451     (when message-default-mail-headers
3452       (insert message-default-mail-headers)
3453       (or (bolp) (insert ?\n)))
3454     (when message-generate-headers-first
3455       (message-generate-headers
3456        (delq 'Lines
3457              (delq 'Subject
3458                    (copy-sequence message-required-mail-headers))))))
3459   (run-hooks 'message-signature-setup-hook)
3460   (message-insert-signature)
3461   (save-restriction
3462     (message-narrow-to-headers)
3463     (run-hooks 'message-header-setup-hook))
3464   (set-buffer-modified-p nil)
3465   (setq buffer-undo-list nil)
3466   (run-hooks 'message-setup-hook)
3467   (message-position-point)
3468   (undo-boundary))
3469
3470 (defun message-set-auto-save-file-name ()
3471   "Associate the message buffer with a file in the drafts directory."
3472   (when message-autosave-directory
3473     (if (gnus-alive-p)
3474         (setq message-draft-article
3475               (nndraft-request-associate-buffer "drafts"))
3476       (setq buffer-file-name (expand-file-name "*message*"
3477                                                message-autosave-directory))
3478       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3479     (clear-visited-file-modtime)))
3480
3481 (defun message-disassociate-draft ()
3482   "Disassociate the message buffer from the drafts directory."
3483   (when message-draft-article
3484     (nndraft-request-expire-articles
3485      (list message-draft-article) "drafts" nil t)))
3486
3487 \f
3488
3489 ;;;
3490 ;;; Commands for interfacing with message
3491 ;;;
3492
3493 ;;;###autoload
3494 (defun message-mail (&optional to subject
3495                                other-headers continue switch-function
3496                                yank-action send-actions)
3497   "Start editing a mail message to be sent.
3498 OTHER-HEADERS is an alist of header/value pairs."
3499   (interactive)
3500   (let ((message-this-is-mail t))
3501     (message-pop-to-buffer (message-buffer-name "mail" to))
3502     (message-setup
3503      (nconc
3504       `((To . ,(or to "")) (Subject . ,(or subject "")))
3505       (when other-headers other-headers)))))
3506
3507 ;;;###autoload
3508 (defun message-news (&optional newsgroups subject)
3509   "Start editing a news article to be sent."
3510   (interactive)
3511   (let ((message-this-is-news t))
3512     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3513     (message-setup `((Newsgroups . ,(or newsgroups ""))
3514                      (Subject . ,(or subject ""))))))
3515
3516 ;;;###autoload
3517 (defun message-reply (&optional to-address wide)
3518   "Start editing a reply to the article in the current buffer."
3519   (interactive)
3520   (let ((cur (current-buffer))
3521         from subject date reply-to to cc
3522         references message-id follow-to
3523         (inhibit-point-motion-hooks t)
3524         mct never-mct gnus-warning)
3525     (save-restriction
3526       (message-narrow-to-head)
3527       ;; Allow customizations to have their say.
3528       (if (not wide)
3529           ;; This is a regular reply.
3530           (if (message-functionp message-reply-to-function)
3531               (setq follow-to (funcall message-reply-to-function)))
3532         ;; This is a followup.
3533         (if (message-functionp message-wide-reply-to-function)
3534             (save-excursion
3535               (setq follow-to
3536                     (funcall message-wide-reply-to-function)))))
3537       ;; Find all relevant headers we need.
3538       (setq from (message-fetch-field "from")
3539             date (message-fetch-field "date")
3540             subject (or (message-fetch-field "subject") "none")
3541             to (message-fetch-field "to")
3542             cc (message-fetch-field "cc")
3543             mct (message-fetch-field "mail-copies-to")
3544             reply-to (message-fetch-field "reply-to")
3545             references (message-fetch-field "references")
3546             message-id (message-fetch-field "message-id" t))
3547       ;; Remove any (buggy) Re:'s that are present and make a
3548       ;; proper one.
3549       (when (string-match message-subject-re-regexp subject)
3550         (setq subject (substring subject (match-end 0))))
3551       (setq subject (concat "Re: " subject))
3552
3553       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3554                  (string-match "<[^>]+>" gnus-warning))
3555         (setq message-id (match-string 0 gnus-warning)))
3556
3557       ;; Handle special values of Mail-Copies-To.
3558       (when mct
3559         (cond ((equal (downcase mct) "never")
3560                (setq never-mct t)
3561                (setq mct nil))
3562               ((equal (downcase mct) "always")
3563                (setq mct (or reply-to from)))))
3564
3565       (unless follow-to
3566         (if (or (not wide)
3567                 to-address)
3568             (progn
3569               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3570               (when (and wide mct)
3571                 (push (cons 'Cc mct) follow-to)))
3572           (let (ccalist)
3573             (save-excursion
3574               (message-set-work-buffer)
3575               (unless never-mct
3576                 (insert (or reply-to from "")))
3577               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3578               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3579               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3580               (goto-char (point-min))
3581               (while (re-search-forward "[ \t]+" nil t)
3582                 (replace-match " " t t))
3583               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3584               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3585                         (erase-buffer)))
3586               (goto-char (point-min))
3587               ;; Perhaps Mail-Copies-To: never removed the only address?
3588               (when (eobp)
3589                 (insert (or reply-to from "")))
3590               (setq ccalist
3591                     (mapcar
3592                      (lambda (addr)
3593                        (cons (mail-strip-quoted-names addr) addr))
3594                      (message-tokenize-header (buffer-string))))
3595               (let ((s ccalist))
3596                 (while s
3597                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3598             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3599             (when ccalist
3600               (let ((ccs (cons 'Cc (mapconcat
3601                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3602                 (when (string-match "^ +" (cdr ccs))
3603                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3604                 (push ccs follow-to))))))
3605       (widen))
3606
3607     (message-pop-to-buffer (message-buffer-name
3608                             (if wide "wide reply" "reply") from
3609                             (if wide to-address nil)))
3610
3611     (setq message-reply-headers
3612           (vector 0 subject from date message-id references 0 0 ""))
3613
3614     (message-setup
3615      `((Subject . ,subject)
3616        ,@follow-to
3617        ,@(if (or references message-id)
3618              `((References . ,(concat (or references "") (and references " ")
3619                                       (or message-id ""))))
3620            nil))
3621      cur)))
3622
3623 ;;;###autoload
3624 (defun message-wide-reply (&optional to-address)
3625   "Make a \"wide\" reply to the message in the current buffer."
3626   (interactive)
3627   (message-reply to-address t))
3628
3629 ;;;###autoload
3630 (defun message-followup (&optional to-newsgroups)
3631   "Follow up to the message in the current buffer.
3632 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3633   (interactive)
3634   (let ((cur (current-buffer))
3635         from subject date reply-to mct
3636         references message-id follow-to
3637         (inhibit-point-motion-hooks t)
3638         (message-this-is-news t)
3639         followup-to distribution newsgroups gnus-warning posted-to)
3640     (save-restriction
3641       (narrow-to-region
3642        (goto-char (point-min))
3643        (if (search-forward "\n\n" nil t)
3644            (1- (point))
3645          (point-max)))
3646       (when (message-functionp message-followup-to-function)
3647         (setq follow-to
3648               (funcall message-followup-to-function)))
3649       (setq from (message-fetch-field "from")
3650             date (message-fetch-field "date")
3651             subject (or (message-fetch-field "subject") "none")
3652             references (message-fetch-field "references")
3653             message-id (message-fetch-field "message-id" t)
3654             followup-to (message-fetch-field "followup-to")
3655             newsgroups (message-fetch-field "newsgroups")
3656             posted-to (message-fetch-field "posted-to")
3657             reply-to (message-fetch-field "reply-to")
3658             distribution (message-fetch-field "distribution")
3659             mct (message-fetch-field "mail-copies-to"))
3660       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3661                  (string-match "<[^>]+>" gnus-warning))
3662         (setq message-id (match-string 0 gnus-warning)))
3663       ;; Remove bogus distribution.
3664       (when (and (stringp distribution)
3665                  (let ((case-fold-search t))
3666                    (string-match "world" distribution)))
3667         (setq distribution nil))
3668       ;; Remove any (buggy) Re:'s that are present and make a
3669       ;; proper one.
3670       (when (string-match message-subject-re-regexp subject)
3671         (setq subject (substring subject (match-end 0))))
3672       (setq subject (concat "Re: " subject))
3673       (widen))
3674
3675     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3676
3677     (message-setup
3678      `((Subject . ,subject)
3679        ,@(cond
3680           (to-newsgroups
3681            (list (cons 'Newsgroups to-newsgroups)))
3682           (follow-to follow-to)
3683           ((and followup-to message-use-followup-to)
3684            (list
3685             (cond
3686              ((equal (downcase followup-to) "poster")
3687               (if (or (eq message-use-followup-to 'use)
3688                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3689 You should normally obey the Followup-To: header.
3690
3691 `Followup-To: poster' sends your response via e-mail instead of news.
3692
3693 A typical situation where `Followup-To: poster' is used is when the poster
3694 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3695                   (progn
3696                     (setq message-this-is-news nil)
3697                     (cons 'To (or reply-to from "")))
3698                 (cons 'Newsgroups newsgroups)))
3699              (t
3700               (if (or (equal followup-to newsgroups)
3701                       (not (eq message-use-followup-to 'ask))
3702                       (message-y-or-n-p
3703                        (concat "Obey Followup-To: " followup-to "? ") t "\
3704 You should normally obey the Followup-To: header.
3705
3706         `Followup-To: " followup-to "'
3707 directs your response to " (if (string-match "," followup-to)
3708                                "the specified newsgroups"
3709                              "that newsgroup only") ".
3710
3711 If a message is posted to several newsgroups, Followup-To is often
3712 used to direct the following discussion to one newsgroup only,
3713 because discussions that are spread over several newsgroup tend to
3714 be fragmented and very difficult to follow.
3715
3716 Also, some source/announcement newsgroups are not indented for discussion;
3717 responses here are directed to other newsgroups."))
3718                   (cons 'Newsgroups followup-to)
3719                 (cons 'Newsgroups newsgroups))))))
3720           (posted-to
3721            `((Newsgroups . ,posted-to)))
3722           (t
3723            `((Newsgroups . ,newsgroups))))
3724        ,@(and distribution (list (cons 'Distribution distribution)))
3725        ,@(if (or references message-id)
3726              `((References . ,(concat (or references "") (and references " ")
3727                                       (or message-id "")))))
3728        ,@(when (and mct
3729                     (not (equal (downcase mct) "never")))
3730            (list (cons 'Cc (if (equal (downcase mct) "always")
3731                                (or reply-to from "")
3732                              mct)))))
3733
3734      cur)
3735
3736     (setq message-reply-headers
3737           (vector 0 subject from date message-id references 0 0 ""))))
3738
3739
3740 ;;;###autoload
3741 (defun message-cancel-news ()
3742   "Cancel an article you posted."
3743   (interactive)
3744   (unless (message-news-p)
3745     (error "This is not a news article; canceling is impossible"))
3746   (when (yes-or-no-p "Do you really want to cancel this article? ")
3747     (let (from newsgroups message-id distribution buf sender)
3748       (save-excursion
3749         ;; Get header info. from original article.
3750         (save-restriction
3751           (message-narrow-to-head)
3752           (setq from (message-fetch-field "from")
3753                 sender (message-fetch-field "sender")
3754                 newsgroups (message-fetch-field "newsgroups")
3755                 message-id (message-fetch-field "message-id" t)
3756                 distribution (message-fetch-field "distribution")))
3757         ;; Make sure that this article was written by the user.
3758         (unless (or (and sender
3759                          (string-equal
3760                           (downcase sender)
3761                           (downcase (message-make-sender))))
3762                     (string-equal
3763                      (downcase (cadr (mail-extract-address-components from)))
3764                      (downcase (cadr (mail-extract-address-components
3765                                       (message-make-from))))))
3766           (error "This article is not yours"))
3767         ;; Make control message.
3768         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3769         (buffer-disable-undo (current-buffer))
3770         (erase-buffer)
3771         (insert "Newsgroups: " newsgroups "\n"
3772                 "From: " (message-make-from) "\n"
3773                 "Subject: cmsg cancel " message-id "\n"
3774                 "Control: cancel " message-id "\n"
3775                 (if distribution
3776                     (concat "Distribution: " distribution "\n")
3777                   "")
3778                 mail-header-separator "\n"
3779                 message-cancel-message)
3780         (message "Canceling your article...")
3781         (if (let ((message-syntax-checks
3782                    'dont-check-for-anything-just-trust-me)
3783                   (message-encoding-buffer (current-buffer))
3784                   (message-edit-buffer (current-buffer)))
3785               (message-send-news))
3786             (message "Canceling your article...done"))
3787         (kill-buffer buf)))))
3788
3789 ;;;###autoload
3790 (defun message-supersede ()
3791   "Start composing a message to supersede the current message.
3792 This is done simply by taking the old article and adding a Supersedes
3793 header line with the old Message-ID."
3794   (interactive)
3795   (let ((cur (current-buffer))
3796         (sender (message-fetch-field "sender"))
3797         (from (message-fetch-field "from")))
3798     ;; Check whether the user owns the article that is to be superseded.
3799     (unless (or (and sender
3800                      (string-equal
3801                       (downcase sender)
3802                       (downcase (message-make-sender))))
3803                 (string-equal
3804                  (downcase (cadr (mail-extract-address-components from)))
3805                  (downcase (cadr (mail-extract-address-components
3806                                   (message-make-from))))))
3807       (error "This article is not yours"))
3808     ;; Get a normal message buffer.
3809     (message-pop-to-buffer (message-buffer-name "supersede"))
3810     (insert-buffer-substring cur)
3811     (message-narrow-to-head)
3812     ;; Remove unwanted headers.
3813     (when message-ignored-supersedes-headers
3814       (message-remove-header message-ignored-supersedes-headers t))
3815     (goto-char (point-min))
3816     (if (not (re-search-forward "^Message-ID: " nil t))
3817         (error "No Message-ID in this article")
3818       (replace-match "Supersedes: " t t))
3819     (goto-char (point-max))
3820     (insert mail-header-separator)
3821     (widen)
3822     (forward-line 1)))
3823
3824 ;;;###autoload
3825 (defun message-recover ()
3826   "Reread contents of current buffer from its last auto-save file."
3827   (interactive)
3828   (let ((file-name (make-auto-save-file-name)))
3829     (cond ((save-window-excursion
3830              (if (not (eq system-type 'vax-vms))
3831                  (with-output-to-temp-buffer "*Directory*"
3832                    (buffer-disable-undo standard-output)
3833                    (let ((default-directory "/"))
3834                      (call-process
3835                       "ls" nil standard-output nil "-l" file-name))))
3836              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3837            (let ((buffer-read-only nil))
3838              (erase-buffer)
3839              (insert-file-contents file-name nil)))
3840           (t (error "message-recover cancelled")))))
3841
3842 ;;; Washing Subject:
3843
3844 (defun message-wash-subject (subject)
3845   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3846   (nnheader-temp-write nil
3847     (insert-string subject)
3848     (goto-char (point-min))
3849     ;; strip Re/Fwd stuff off the beginning
3850     (while (re-search-forward
3851             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
3852       (replace-match ""))
3853
3854     ;; and gnus-style forwards [foo@bar.com] subject
3855     (goto-char (point-min))
3856     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
3857       (replace-match ""))
3858
3859     ;; and off the end
3860     (goto-char (point-max))
3861     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
3862       (replace-match ""))
3863
3864     ;; and finally, any whitespace that was left-over
3865     (goto-char (point-min))
3866     (while (re-search-forward "^[ \t]+" nil t)
3867       (replace-match ""))
3868     (goto-char (point-max))
3869     (while (re-search-backward "[ \t]+$" nil t)
3870       (replace-match ""))
3871
3872     (buffer-string)))
3873     
3874 ;;; Forwarding messages.
3875
3876 (defun message-forward-subject-author-subject (subject)
3877   "Generate a subject for a forwarded message.
3878 The form is: [Source] Subject, where if the original message was mail,
3879 Source is the sender, and if the original message was news, Source is
3880 the list of newsgroups is was posted to."
3881   (concat "["
3882           (or (message-fetch-field
3883                (if (message-news-p) "newsgroups" "from"))
3884               "(nowhere)")
3885           "] " subject))
3886
3887 (defun message-forward-subject-fwd (subject)
3888   "Generate a subject for a forwarded message.
3889 The form is: Fwd: Subject, where Subject is the original subject of
3890 the message."
3891   (concat "Fwd: " subject))
3892
3893 (defun message-make-forward-subject ()
3894   "Return a Subject header suitable for the message in the current buffer."
3895   (save-excursion
3896     (save-restriction
3897       (current-buffer)
3898       (message-narrow-to-head)
3899       (let ((funcs message-make-forward-subject-function)
3900             (subject (if message-wash-forwarded-subjects
3901                          (message-wash-subject
3902                           (or (eword-decode-unstructured-field-body
3903                                (message-fetch-field "Subject")) ""))
3904                        (or (eword-decode-unstructured-field-body
3905                             (message-fetch-field "Subject")) ""))))
3906         ;; Make sure funcs is a list.
3907         (and funcs
3908              (not (listp funcs))
3909              (setq funcs (list funcs)))
3910         ;; Apply funcs in order, passing subject generated by previous
3911         ;; func to the next one.
3912         (while funcs
3913           (when (message-functionp (car funcs))
3914             (setq subject (funcall (car funcs) subject)))
3915           (setq funcs (cdr funcs)))
3916         subject))))
3917
3918 ;;;###autoload
3919 (defun message-forward (&optional news)
3920   "Forward the current message via mail.
3921 Optional NEWS will use news to forward instead of mail."
3922   (interactive "P")
3923   (let ((cur (current-buffer))
3924         (subject (message-make-forward-subject))
3925         art-beg)
3926     (if news (message-news nil subject) (message-mail nil subject))
3927     ;; Put point where we want it before inserting the forwarded
3928     ;; message.
3929     (if message-signature-before-forwarded-message
3930         (goto-char (point-max))
3931       (message-goto-body))
3932     ;; Make sure we're at the start of the line.
3933     (unless (eolp)
3934       (insert "\n"))
3935     ;; Narrow to the area we are to insert.
3936     (narrow-to-region (point) (point))
3937     ;; Insert the separators and the forwarded buffer.
3938     (insert message-forward-start-separator)
3939     (setq art-beg (point))
3940     (insert-buffer-substring cur)
3941     (goto-char (point-max))
3942     (insert message-forward-end-separator)
3943     (set-text-properties (point-min) (point-max) nil)
3944     ;; Remove all unwanted headers.
3945     (goto-char art-beg)
3946     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3947                                   (1- (point))
3948                                 (point)))
3949     (goto-char (point-min))
3950     (message-remove-header message-included-forward-headers t nil t)
3951     (widen)
3952     (message-position-point)))
3953
3954 ;;;###autoload
3955 (defun message-resend (address)
3956   "Resend the current article to ADDRESS."
3957   (interactive "sResend message to: ")
3958   (message "Resending message to %s..." address)
3959   (save-excursion
3960     (let ((cur (current-buffer))
3961           beg)
3962       ;; We first set up a normal mail buffer.
3963       (set-buffer (get-buffer-create " *message resend*"))
3964       (buffer-disable-undo (current-buffer))
3965       (erase-buffer)
3966       ;; avoid to turn-on-mime-edit
3967       (let (message-setup-hook)
3968         (message-setup `((To . ,address)))
3969         )
3970       ;; Insert our usual headers.
3971       (message-generate-headers '(From Date To))
3972       (message-narrow-to-headers)
3973       ;; Rename them all to "Resent-*".
3974       (while (re-search-forward "^[A-Za-z]" nil t)
3975         (forward-char -1)
3976         (insert "Resent-"))
3977       (widen)
3978       (forward-line)
3979       (delete-region (point) (point-max))
3980       (setq beg (point))
3981       ;; Insert the message to be resent.
3982       (insert-buffer-substring cur)
3983       (goto-char (point-min))
3984       (search-forward "\n\n")
3985       (forward-char -1)
3986       (save-restriction
3987         (narrow-to-region beg (point))
3988         (message-remove-header message-ignored-resent-headers t)
3989         (goto-char (point-max)))
3990       (insert mail-header-separator)
3991       ;; Rename all old ("Also-")Resent headers.
3992       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
3993         (beginning-of-line)
3994         (insert "Also-"))
3995       ;; Quote any "From " lines at the beginning.
3996       (goto-char beg)
3997       (when (looking-at "From ")
3998         (replace-match "X-From-Line: "))
3999       ;; Send it.
4000       (let ((message-encoding-buffer (current-buffer))
4001             (message-edit-buffer (current-buffer)))
4002         (message-send-mail))
4003       (kill-buffer (current-buffer)))
4004     (message "Resending message to %s...done" address)))
4005
4006 ;;;###autoload
4007 (defun message-bounce ()
4008   "Re-mail the current message.
4009 This only makes sense if the current message is a bounce message than
4010 contains some mail you have written which has been bounced back to
4011 you."
4012   (interactive)
4013   (let ((cur (current-buffer))
4014         boundary)
4015     (message-pop-to-buffer (message-buffer-name "bounce"))
4016     (insert-buffer-substring cur)
4017     (undo-boundary)
4018     (message-narrow-to-head)
4019     (if (and (message-fetch-field "MIME-Version")
4020              (setq boundary (message-fetch-field "Content-Type")))
4021         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4022             (setq boundary (concat (match-string 1 boundary) " *\n"
4023                                    "Content-Type: message/rfc822"))
4024           (setq boundary nil)))
4025     (widen)
4026     (goto-char (point-min))
4027     (search-forward "\n\n" nil t)
4028     (or (and boundary
4029              (re-search-forward boundary nil t)
4030              (forward-line 2))
4031         (and (re-search-forward message-unsent-separator nil t)
4032              (forward-line 1))
4033         (re-search-forward "^Return-Path:.*\n" nil t))
4034     ;; We remove everything before the bounced mail.
4035     (delete-region
4036      (point-min)
4037      (if (re-search-forward "^[^ \n\t]+:" nil t)
4038          (match-beginning 0)
4039        (point)))
4040     (save-restriction
4041       (message-narrow-to-head)
4042       (message-remove-header message-ignored-bounced-headers t)
4043       (goto-char (point-max))
4044       (insert mail-header-separator))
4045     (message-position-point)))
4046
4047 ;;;
4048 ;;; Interactive entry points for new message buffers.
4049 ;;;
4050
4051 ;;;###autoload
4052 (defun message-mail-other-window (&optional to subject)
4053   "Like `message-mail' command, but display mail buffer in another window."
4054   (interactive)
4055   (let ((pop-up-windows t)
4056         (special-display-buffer-names nil)
4057         (special-display-regexps nil)
4058         (same-window-buffer-names nil)
4059         (same-window-regexps nil))
4060     (message-pop-to-buffer (message-buffer-name "mail" to)))
4061   (let ((message-this-is-mail t))
4062     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4063
4064 ;;;###autoload
4065 (defun message-mail-other-frame (&optional to subject)
4066   "Like `message-mail' command, but display mail buffer in another frame."
4067   (interactive)
4068   (let ((pop-up-frames t)
4069         (special-display-buffer-names nil)
4070         (special-display-regexps nil)
4071         (same-window-buffer-names nil)
4072         (same-window-regexps nil))
4073     (message-pop-to-buffer (message-buffer-name "mail" to)))
4074   (let ((message-this-is-mail t))
4075     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4076
4077 ;;;###autoload
4078 (defun message-news-other-window (&optional newsgroups subject)
4079   "Start editing a news article to be sent."
4080   (interactive)
4081   (let ((pop-up-windows t)
4082         (special-display-buffer-names nil)
4083         (special-display-regexps nil)
4084         (same-window-buffer-names nil)
4085         (same-window-regexps nil))
4086     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4087   (let ((message-this-is-news t))
4088     (message-setup `((Newsgroups . ,(or newsgroups ""))
4089                      (Subject . ,(or subject ""))))))
4090
4091 ;;;###autoload
4092 (defun message-news-other-frame (&optional newsgroups subject)
4093   "Start editing a news article to be sent."
4094   (interactive)
4095   (let ((pop-up-frames t)
4096         (special-display-buffer-names nil)
4097         (special-display-regexps nil)
4098         (same-window-buffer-names nil)
4099         (same-window-regexps nil))
4100     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4101   (let ((message-this-is-news t))
4102     (message-setup `((Newsgroups . ,(or newsgroups ""))
4103                      (Subject . ,(or subject ""))))))
4104
4105 ;;; underline.el
4106
4107 ;; This code should be moved to underline.el (from which it is stolen).
4108
4109 ;;;###autoload
4110 (defun bold-region (start end)
4111   "Bold all nonblank characters in the region.
4112 Works by overstriking characters.
4113 Called from program, takes two arguments START and END
4114 which specify the range to operate on."
4115   (interactive "r")
4116   (save-excursion
4117     (let ((end1 (make-marker)))
4118       (move-marker end1 (max start end))
4119       (goto-char (min start end))
4120       (while (< (point) end1)
4121         (or (looking-at "[_\^@- ]")
4122             (insert (following-char) "\b"))
4123         (forward-char 1)))))
4124
4125 ;;;###autoload
4126 (defun unbold-region (start end)
4127   "Remove all boldness (overstruck characters) in the region.
4128 Called from program, takes two arguments START and END
4129 which specify the range to operate on."
4130   (interactive "r")
4131   (save-excursion
4132     (let ((end1 (make-marker)))
4133       (move-marker end1 (max start end))
4134       (goto-char (min start end))
4135       (while (re-search-forward "\b" end1 t)
4136         (if (eq (following-char) (char-after (- (point) 2)))
4137             (delete-char -2))))))
4138
4139 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4140
4141 ;; Support for toolbar
4142 (when (string-match "XEmacs\\|Lucid" emacs-version)
4143   (require 'messagexmas))
4144
4145 ;;; Group name completion.
4146
4147 (defvar message-newgroups-header-regexp
4148   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4149   "Regexp that match headers that lists groups.")
4150
4151 (defun message-tab ()
4152   "Expand group names in Newsgroups and Followup-To headers.
4153 Do a `tab-to-tab-stop' if not in those headers."
4154   (interactive)
4155   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4156         (mail-abbrev-in-expansion-header-p))
4157       (message-expand-group)
4158     (tab-to-tab-stop)))
4159
4160 (defvar gnus-active-hashtb)
4161 (defun message-expand-group ()
4162   "Expand the group name under point."
4163   (let* ((b (save-excursion
4164               (save-restriction
4165                 (narrow-to-region
4166                  (save-excursion
4167                    (beginning-of-line)
4168                    (skip-chars-forward "^:")
4169                    (1+ (point)))
4170                  (point))
4171                 (skip-chars-backward "^, \t\n") (point))))
4172          (completion-ignore-case t)
4173          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4174                                             (point))))
4175          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4176          (completions (all-completions string hashtb))
4177          comp)
4178     (delete-region b (point))
4179     (cond
4180      ((= (length completions) 1)
4181       (if (string= (car completions) string)
4182           (progn
4183             (insert string)
4184             (message "Only matching group"))
4185         (insert (car completions))))
4186      ((and (setq comp (try-completion string hashtb))
4187            (not (string= comp string)))
4188       (insert comp))
4189      (t
4190       (insert string)
4191       (if (not comp)
4192           (message "No matching groups")
4193         (save-selected-window
4194           (pop-to-buffer "*Completions*")
4195           (buffer-disable-undo (current-buffer))
4196           (let ((buffer-read-only nil))
4197             (erase-buffer)
4198             (let ((standard-output (current-buffer)))
4199               (display-completion-list (sort completions 'string<)))
4200             (goto-char (point-min))
4201             (delete-region (point) (progn (forward-line 3) (point))))))))))
4202
4203 ;;; Help stuff.
4204
4205 (defun message-talkative-question (ask question show &rest text)
4206   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4207 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4208 The following arguments may contain lists of values."
4209   (if (and show
4210            (setq text (message-flatten-list text)))
4211       (save-window-excursion
4212         (save-excursion
4213           (with-output-to-temp-buffer " *MESSAGE information message*"
4214             (set-buffer " *MESSAGE information message*")
4215             (mapcar 'princ text)
4216             (goto-char (point-min))))
4217         (funcall ask question))
4218     (funcall ask question)))
4219
4220 (defun message-flatten-list (list)
4221   "Return a new, flat list that contains all elements of LIST.
4222
4223 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4224 => (1 2 3 4 5 6 7)"
4225   (cond ((consp list)
4226          (apply 'append (mapcar 'message-flatten-list list)))
4227         (list
4228          (list list))))
4229
4230 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4231   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4232 Then clone the local variables and values from the old buffer to the
4233 new one, cloning only the locals having a substring matching the
4234 regexp varstr."
4235   (let ((oldbuf (current-buffer)))
4236     (save-excursion
4237       (set-buffer (generate-new-buffer name))
4238       (message-clone-locals oldbuf)
4239       (current-buffer))))
4240
4241 (defun message-clone-locals (buffer)
4242   "Clone the local variables from BUFFER to the current buffer."
4243   (let ((locals (save-excursion
4244                   (set-buffer buffer)
4245                   (buffer-local-variables)))
4246         (regexp "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
4247     (mapcar
4248      (lambda (local)
4249        (when (and (consp local)
4250                   (car local)
4251                   (string-match regexp (symbol-name (car local))))
4252          (ignore-errors
4253            (set (make-local-variable (car local))
4254                 (cdr local)))))
4255      locals)))
4256
4257
4258 ;;; @ for MIME Edit mode
4259 ;;;
4260
4261 (defun message-maybe-setup-default-charset ()
4262   (let ((charset
4263          (and (boundp 'gnus-summary-buffer)
4264               (buffer-live-p gnus-summary-buffer)
4265               (save-excursion
4266                 (set-buffer gnus-summary-buffer)
4267                 default-mime-charset))))
4268     (if charset
4269         (progn
4270           (make-local-variable 'default-mime-charset)
4271           (setq default-mime-charset charset)
4272           ))))
4273
4274 (defun message-maybe-encode ()
4275   (when message-mime-mode
4276     (run-hooks 'mime-edit-translate-hook)
4277     (if (catch 'mime-edit-error
4278           (save-excursion
4279             (mime-edit-translate-body)
4280             ))
4281         (error "Translation error!")
4282       )
4283     (end-of-invisible)
4284     (run-hooks 'mime-edit-exit-hook)
4285     ))
4286
4287 (defun message-mime-insert-article (&optional message)
4288   (interactive)
4289   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4290         (message-reply-buffer gnus-original-article-buffer)
4291         )
4292     (message-yank-original nil)
4293     ))
4294
4295 (set-alist 'mime-edit-message-inserter-alist
4296            'message-mode (function message-mime-insert-article))
4297
4298 ;;; Miscellaneous functions
4299
4300 ;; stolen (and renamed) from nnheader.el
4301 (defun message-replace-chars-in-string (string from to)
4302   "Replace characters in STRING from FROM to TO."
4303   (let ((string (substring string 0))   ;Copy string.
4304         (len (length string))
4305         (idx 0))
4306     ;; Replace all occurrences of FROM with TO.
4307     (while (< idx len)
4308       (when (= (aref string idx) from)
4309         (aset string idx to))
4310       (setq idx (1+ idx)))
4311     string))
4312
4313 (run-hooks 'message-load-hook)
4314
4315 (provide 'message)
4316
4317 ;;; message.el ends here