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