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