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