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