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