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