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