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