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