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