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