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