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