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