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