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