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