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