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