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