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