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