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