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