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