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