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