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