eeba47e9a93f02f9ed33d0499d39385981f9983b
[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, instead of
988 regexps, the elements can be on the form `(not REGEXP)'."
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 intangible nil invisible 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     (remove-text-properties begin end message-forbidden-properties)))
2258
2259 ;;;###autoload
2260 (define-derived-mode message-mode text-mode "Message"
2261   "Major mode for editing mail and news to be sent.
2262 Like Text Mode but with these additional commands:\\<message-mode-map>
2263 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2264 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2265 C-c C-f  move to a header field (and create it if there isn't):
2266          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2267          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2268          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2269          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2270          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2271          C-c C-f C-o  move to From (\"Originator\")
2272          C-c C-f C-f  move to Followup-To
2273          C-c C-f C-m  move to Mail-Followup-To
2274          C-c C-f C-i  cycle through Importance values
2275          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2276          C-c C-f x    crossposting with FollowUp-To header and note in body
2277          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2278          C-c C-f a    Insert X-No-Archive: header and a note in the body
2279 C-c C-t  `message-insert-to' (add a To header to a news followup)
2280 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2281 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2282 C-c C-b  `message-goto-body' (move to beginning of message text).
2283 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2284 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2285 C-c C-y  `message-yank-original' (insert current message, if any).
2286 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2287 C-c C-e  `message-elide-region' (elide the text between point and mark).
2288 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2289 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2290 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2291 C-c C-a  `mml-attach-file' (attach a file as MIME).
2292 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2293 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2294 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2295 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2296 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2297   (setq local-abbrev-table text-mode-abbrev-table)
2298   (set (make-local-variable 'message-reply-buffer) nil)
2299   (make-local-variable 'message-send-actions)
2300   (make-local-variable 'message-exit-actions)
2301   (make-local-variable 'message-kill-actions)
2302   (make-local-variable 'message-postpone-actions)
2303   (make-local-variable 'message-draft-article)
2304   (setq buffer-offer-save t)
2305   (set (make-local-variable 'facemenu-add-face-function)
2306        (lambda (face end)
2307          (let ((face-fun (cdr (assq face message-face-alist))))
2308            (if face-fun
2309                (funcall face-fun (point) end)
2310              (error "Face %s not configured for %s mode" face mode-name)))
2311          ""))
2312   (set (make-local-variable 'facemenu-remove-face-function) t)
2313   (set (make-local-variable 'message-reply-headers) nil)
2314   (make-local-variable 'message-newsreader)
2315   (make-local-variable 'message-mailer)
2316   (make-local-variable 'message-post-method)
2317   (set (make-local-variable 'message-sent-message-via) nil)
2318   (set (make-local-variable 'message-checksum) nil)
2319   (set (make-local-variable 'message-mime-part) 0)
2320   (message-setup-fill-variables)
2321   (set
2322    (make-local-variable 'paragraph-separate)
2323    (format "\\(%s\\)\\|\\(%s\\)"
2324            paragraph-separate
2325            "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)"))
2326   ;; Allow using comment commands to add/remove quoting.
2327   (set (make-local-variable 'comment-start) message-yank-prefix)
2328   (if (featurep 'xemacs)
2329       (message-setup-toolbar)
2330     (set (make-local-variable 'font-lock-defaults)
2331          '(message-font-lock-keywords t))
2332     (if (boundp 'tool-bar-map)
2333         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2334   (easy-menu-add message-mode-menu message-mode-map)
2335   (easy-menu-add message-mode-field-menu message-mode-map)
2336   ;; make-local-hook is harmless though obsolete in Emacs 21.
2337   ;; Emacs 20 and XEmacs need make-local-hook.
2338   (make-local-hook 'after-change-functions)
2339   ;; Mmmm... Forbidden properties...
2340   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2341             nil 'local)
2342   ;; Allow mail alias things.
2343   (when (eq message-mail-alias-type 'abbrev)
2344     (if (fboundp 'mail-abbrevs-setup)
2345         (mail-abbrevs-setup)
2346       (mail-aliases-setup)))
2347   (unless buffer-file-name
2348     (message-set-auto-save-file-name))
2349   (unless (buffer-base-buffer)
2350     ;; Don't enable multibyte on an indirect buffer.  Maybe enabling
2351     ;; multibyte is not necessary at all. -- zsh
2352     (mm-enable-multibyte))
2353   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
2354   (mml-mode))
2355
2356 (defun message-setup-fill-variables ()
2357   "Setup message fill variables."
2358   (set (make-local-variable 'fill-paragraph-function)
2359        'message-fill-paragraph)
2360   (make-local-variable 'paragraph-separate)
2361   (make-local-variable 'paragraph-start)
2362   (make-local-variable 'adaptive-fill-regexp)
2363   (unless (boundp 'adaptive-fill-first-line-regexp)
2364     (setq adaptive-fill-first-line-regexp nil))
2365   (make-local-variable 'adaptive-fill-first-line-regexp)
2366   (let ((quote-prefix-regexp
2367          ;; User should change message-cite-prefix-regexp if
2368          ;; message-yank-prefix is set to an abnormal value.
2369          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2370     (setq paragraph-start
2371           (concat
2372            (regexp-quote mail-header-separator) "$\\|"
2373            "[ \t]*$\\|"                 ; blank lines
2374            "-- $\\|"                    ; signature delimiter
2375            "---+$\\|"              ; delimiters for forwarded messages
2376            page-delimiter "$\\|"        ; spoiler warnings
2377            ".*wrote:$\\|"               ; attribution lines
2378            quote-prefix-regexp "$"))    ; empty lines in quoted text
2379     (setq paragraph-separate paragraph-start)
2380     (setq adaptive-fill-regexp
2381           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2382     (setq adaptive-fill-first-line-regexp
2383           (concat quote-prefix-regexp "\\|"
2384                   adaptive-fill-first-line-regexp)))
2385   (make-local-variable 'auto-fill-inhibit-regexp)
2386   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2387   (setq auto-fill-inhibit-regexp nil)
2388   (make-local-variable 'normal-auto-fill-function)
2389   (setq normal-auto-fill-function 'message-do-auto-fill)
2390   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2391   ;; In that case, ensure that it uses the right function.  The real
2392   ;; solution would be not to use `define-derived-mode', and run
2393   ;; `text-mode-hook' ourself at the end of the mode.
2394   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2395   (when auto-fill-function
2396     (setq auto-fill-function normal-auto-fill-function)))
2397
2398 \f
2399
2400 ;;;
2401 ;;; Message mode commands
2402 ;;;
2403
2404 ;;; Movement commands
2405
2406 (defun message-goto-to ()
2407   "Move point to the To header."
2408   (interactive)
2409   (message-position-on-field "To"))
2410
2411 (defun message-goto-from ()
2412   "Move point to the From header."
2413   (interactive)
2414   (message-position-on-field "From"))
2415
2416 (defun message-goto-subject ()
2417   "Move point to the Subject header."
2418   (interactive)
2419   (message-position-on-field "Subject"))
2420
2421 (defun message-goto-cc ()
2422   "Move point to the Cc header."
2423   (interactive)
2424   (message-position-on-field "Cc" "To"))
2425
2426 (defun message-goto-bcc ()
2427   "Move point to the Bcc  header."
2428   (interactive)
2429   (message-position-on-field "Bcc" "Cc" "To"))
2430
2431 (defun message-goto-fcc ()
2432   "Move point to the Fcc header."
2433   (interactive)
2434   (message-position-on-field "Fcc" "To" "Newsgroups"))
2435
2436 (defun message-goto-reply-to ()
2437   "Move point to the Reply-To header."
2438   (interactive)
2439   (message-position-on-field "Reply-To" "Subject"))
2440
2441 (defun message-goto-newsgroups ()
2442   "Move point to the Newsgroups header."
2443   (interactive)
2444   (message-position-on-field "Newsgroups"))
2445
2446 (defun message-goto-distribution ()
2447   "Move point to the Distribution header."
2448   (interactive)
2449   (message-position-on-field "Distribution"))
2450
2451 (defun message-goto-followup-to ()
2452   "Move point to the Followup-To header."
2453   (interactive)
2454   (message-position-on-field "Followup-To" "Newsgroups"))
2455
2456 (defun message-goto-mail-followup-to ()
2457   "Move point to the Mail-Followup-To header."
2458   (interactive)
2459   (message-position-on-field "Mail-Followup-To" "From"))
2460
2461 (defun message-goto-keywords ()
2462   "Move point to the Keywords header."
2463   (interactive)
2464   (message-position-on-field "Keywords" "Subject"))
2465
2466 (defun message-goto-summary ()
2467   "Move point to the Summary header."
2468   (interactive)
2469   (message-position-on-field "Summary" "Subject"))
2470
2471 (defun message-goto-body (&optional interactivep)
2472   "Move point to the beginning of the message body."
2473   (interactive (list t))
2474   (when (and interactivep
2475              (looking-at "[ \t]*\n"))
2476     (expand-abbrev))
2477   (goto-char (point-min))
2478   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2479       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2480
2481 (defun message-goto-eoh ()
2482   "Move point to the end of the headers."
2483   (interactive)
2484   (message-goto-body)
2485   (forward-line -1))
2486
2487 (defun message-goto-signature ()
2488   "Move point to the beginning of the message signature.
2489 If there is no signature in the article, go to the end and
2490 return nil."
2491   (interactive)
2492   (goto-char (point-min))
2493   (if (re-search-forward message-signature-separator nil t)
2494       (forward-line 1)
2495     (goto-char (point-max))
2496     nil))
2497
2498 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
2499   "Insert a reasonable MFT header in a post to an unsubscribed list.
2500 When making original posts to a mailing list you are not subscribed to,
2501 you have to type in a MFT header by hand.  The contents, usually, are
2502 the addresses of the list and your own address.  This function inserts
2503 such a header automatically.  It fetches the contents of the To: header
2504 in the current mail buffer, and appends the current `user-mail-address'.
2505
2506 If the optional argument INCLUDE-CC is non-nil, the addresses in the
2507 Cc: header are also put into the MFT."
2508
2509   (interactive "P")
2510   (message-remove-header "Mail-Followup-To")
2511   (let* ((cc (and include-cc (message-fetch-field "Cc")))
2512          (tos (if cc
2513                   (concat (message-fetch-field "To") "," cc)
2514                 (message-fetch-field "To"))))
2515     (message-goto-mail-followup-to)
2516     (insert (concat tos ", " user-mail-address))))
2517
2518 \f
2519
2520 (defun message-insert-to (&optional force)
2521   "Insert a To header that points to the author of the article being replied to.
2522 If the original author requested not to be sent mail, the function signals
2523 an error.
2524 With the prefix argument FORCE, insert the header anyway."
2525   (interactive "P")
2526   (let ((co (message-fetch-reply-field "mail-copies-to")))
2527     (when (and (null force)
2528                co
2529                (or (equal (downcase co) "never")
2530                    (equal (downcase co) "nobody")))
2531       (error "The user has requested not to have copies sent via mail")))
2532   (message-carefully-insert-headers
2533    (list (cons 'To
2534                (or (message-fetch-reply-field "mail-reply-to")
2535                    (message-fetch-reply-field "reply-to")
2536                    (message-fetch-reply-field "from")
2537                    "")))))
2538
2539 (defun message-insert-wide-reply ()
2540   "Insert To and Cc headers as if you were doing a wide reply."
2541   (interactive)
2542   (let ((headers (message-with-reply-buffer
2543                    (message-get-reply-headers t))))
2544     (message-carefully-insert-headers headers)))
2545
2546 (defun message-carefully-insert-headers (headers)
2547   (dolist (header headers)
2548     (let ((header-name (symbol-name (car header))))
2549       (when (and (message-position-on-field header-name)
2550                  (mail-fetch-field header-name)
2551                  (not (string-match "\\` *\\'"
2552                                     (mail-fetch-field header-name))))
2553         (insert ", "))
2554       (insert (cdr header)))))
2555
2556 (defun message-widen-reply ()
2557   "Widen the reply to include maximum recipients."
2558   (interactive)
2559   (let ((follow-to
2560          (and message-reply-buffer
2561               (buffer-name message-reply-buffer)
2562               (save-excursion
2563                 (set-buffer message-reply-buffer)
2564                 (message-get-reply-headers t)))))
2565     (save-excursion
2566       (save-restriction
2567         (message-narrow-to-headers)
2568         (dolist (elem follow-to)
2569           (message-remove-header (symbol-name (car elem)))
2570           (goto-char (point-min))
2571           (insert (symbol-name (car elem)) ": "
2572                   (cdr elem) "\n"))))))
2573
2574 (defun message-insert-newsgroups ()
2575   "Insert the Newsgroups header from the article being replied to."
2576   (interactive)
2577   (when (and (message-position-on-field "Newsgroups")
2578              (mail-fetch-field "newsgroups")
2579              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2580     (insert ","))
2581   (insert (or (message-fetch-reply-field "newsgroups") "")))
2582
2583 \f
2584
2585 ;;; Various commands
2586
2587 (defun message-delete-not-region (beg end)
2588   "Delete everything in the body of the current message outside of the region."
2589   (interactive "r")
2590   (let (citeprefix)
2591     (save-excursion
2592       (goto-char beg)
2593       ;; snarf citation prefix, if appropriate
2594       (unless (eq (point) (progn (beginning-of-line) (point)))
2595         (when (looking-at message-cite-prefix-regexp)
2596           (setq citeprefix (match-string 0))))
2597       (goto-char end)
2598       (delete-region (point) (if (not (message-goto-signature))
2599                                  (point)
2600                                (forward-line -2)
2601                                (point)))
2602       (insert "\n")
2603       (goto-char beg)
2604       (delete-region beg (progn (message-goto-body)
2605                                 (forward-line 2)
2606                                 (point)))
2607       (when citeprefix
2608         (insert citeprefix))))
2609   (when (message-goto-signature)
2610     (forward-line -2)))
2611
2612 (defun message-kill-to-signature ()
2613   "Deletes all text up to the signature."
2614   (interactive)
2615   (let ((point (point)))
2616     (message-goto-signature)
2617     (unless (eobp)
2618       (forward-line -2))
2619     (kill-region point (point))
2620     (unless (bolp)
2621       (insert "\n"))))
2622
2623 (defun message-newline-and-reformat (&optional arg not-break)
2624   "Insert four newlines, and then reformat if inside quoted text.
2625 Prefix arg means justify as well."
2626   (interactive (list (if current-prefix-arg 'full)))
2627   (let (quoted point beg end leading-space bolp)
2628     (setq point (point))
2629     (beginning-of-line)
2630     (setq beg (point))
2631     (setq bolp (= beg point))
2632     ;; Find first line of the paragraph.
2633     (if not-break
2634         (while (and (not (eobp))
2635                     (not (looking-at message-cite-prefix-regexp))
2636                     (looking-at paragraph-start))
2637           (forward-line 1)))
2638     ;; Find the prefix
2639     (when (looking-at message-cite-prefix-regexp)
2640       (setq quoted (match-string 0))
2641       (goto-char (match-end 0))
2642       (looking-at "[ \t]*")
2643       (setq leading-space (match-string 0)))
2644     (if (and quoted
2645              (not not-break)
2646              (not bolp)
2647              (< (- point beg) (length quoted)))
2648         ;; break inside the cite prefix.
2649         (setq quoted nil
2650               end nil))
2651     (if quoted
2652         (progn
2653           (forward-line 1)
2654           (while (and (not (eobp))
2655                       (not (looking-at paragraph-separate))
2656                       (looking-at message-cite-prefix-regexp)
2657                       (equal quoted (match-string 0)))
2658             (goto-char (match-end 0))
2659             (looking-at "[ \t]*")
2660             (if (> (length leading-space) (length (match-string 0)))
2661                 (setq leading-space (match-string 0)))
2662             (forward-line 1))
2663           (setq end (point))
2664           (goto-char beg)
2665           (while (and (if (bobp) nil (forward-line -1) t)
2666                       (not (looking-at paragraph-start))
2667                       (looking-at message-cite-prefix-regexp)
2668                       (equal quoted (match-string 0)))
2669             (setq beg (point))
2670             (goto-char (match-end 0))
2671             (looking-at "[ \t]*")
2672             (if (> (length leading-space) (length (match-string 0)))
2673                 (setq leading-space (match-string 0)))))
2674       (while (and (not (eobp))
2675                   (not (looking-at paragraph-separate))
2676                   (not (looking-at message-cite-prefix-regexp)))
2677         (forward-line 1))
2678       (setq end (point))
2679       (goto-char beg)
2680       (while (and (if (bobp) nil (forward-line -1) t)
2681                   (not (looking-at paragraph-start))
2682                   (not (looking-at message-cite-prefix-regexp)))
2683         (setq beg (point))))
2684     (goto-char point)
2685     (save-restriction
2686       (narrow-to-region beg end)
2687       (if not-break
2688           (setq point nil)
2689         (if bolp
2690             (newline)
2691           (newline)
2692           (newline))
2693         (setq point (point))
2694         ;; (newline 2) doesn't mark both newline's as hard, so call
2695         ;; newline twice. -jas
2696         (newline)
2697         (newline)
2698         (delete-region (point) (re-search-forward "[ \t]*"))
2699         (when (and quoted (not bolp))
2700           (insert quoted leading-space)))
2701       (if quoted
2702           (let* ((adaptive-fill-regexp
2703                   (regexp-quote (concat quoted leading-space)))
2704                  (adaptive-fill-first-line-regexp
2705                   adaptive-fill-regexp ))
2706             (fill-paragraph arg))
2707         (fill-paragraph arg))
2708       (if point (goto-char point)))))
2709
2710 (defun message-fill-paragraph (&optional arg)
2711   "Like `fill-paragraph'."
2712   (interactive (list (if current-prefix-arg 'full)))
2713   (if (and (boundp 'filladapt-mode) filladapt-mode)
2714       nil
2715     (message-newline-and-reformat arg t)
2716     t))
2717
2718 ;; Is it better to use `mail-header-end'?
2719 (defun message-point-in-header-p ()
2720   "Return t if point is in the header."
2721   (save-excursion
2722     (let ((p (point)))
2723       (goto-char (point-min))
2724       (not (re-search-forward
2725             (concat "^" (regexp-quote mail-header-separator) "\n")
2726             p t)))))
2727
2728 (defun message-do-auto-fill ()
2729   "Like `do-auto-fill', but don't fill in message header."
2730   (unless (message-point-in-header-p)
2731     (do-auto-fill)))
2732
2733 (defun message-insert-signature (&optional force)
2734   "Insert a signature.  See documentation for variable `message-signature'."
2735   (interactive (list 0))
2736   (let* ((signature
2737           (cond
2738            ((and (null message-signature)
2739                  (eq force 0))
2740             (save-excursion
2741               (goto-char (point-max))
2742               (not (re-search-backward message-signature-separator nil t))))
2743            ((and (null message-signature)
2744                  force)
2745             t)
2746            ((message-functionp message-signature)
2747             (funcall message-signature))
2748            ((listp message-signature)
2749             (eval message-signature))
2750            (t message-signature)))
2751          (signature
2752           (cond ((stringp signature)
2753                  signature)
2754                 ((and (eq t signature)
2755                       message-signature-file
2756                       (file-exists-p message-signature-file))
2757                  signature))))
2758     (when signature
2759       (goto-char (point-max))
2760       ;; Insert the signature.
2761       (unless (bolp)
2762         (insert "\n"))
2763       (when message-signature-insert-empty-line
2764         (insert "\n"))
2765       (insert "-- \n")
2766       (if (eq signature t)
2767           (insert-file-contents message-signature-file)
2768         (insert signature))
2769       (goto-char (point-max))
2770       (or (bolp) (insert "\n")))))
2771
2772 (defun message-insert-importance-high ()
2773   "Insert header to mark message as important."
2774   (interactive)
2775   (save-excursion
2776     (message-remove-header "Importance")
2777     (message-goto-eoh)
2778     (insert "Importance: high\n")))
2779
2780 (defun message-insert-importance-low ()
2781   "Insert header to mark message as unimportant."
2782   (interactive)
2783   (save-excursion
2784     (message-remove-header "Importance")
2785     (message-goto-eoh)
2786     (insert "Importance: low\n")))
2787
2788 (defun message-insert-or-toggle-importance ()
2789   "Insert a \"Importance: high\" header, or cycle through the header values.
2790 The three allowed values according to RFC 1327 are `high', `normal'
2791 and `low'."
2792   (interactive)
2793   (save-excursion
2794     (let ((valid '("high" "normal" "low"))
2795           (new "high")
2796           cur)
2797       (when (setq cur (message-fetch-field "Importance"))
2798         (message-remove-header "Importance")
2799         (setq new (cond ((string= cur "high")
2800                          "low")
2801                         ((string= cur "low")
2802                          "normal")
2803                         (t
2804                          "high"))))
2805       (message-goto-eoh)
2806       (insert (format "Importance: %s\n" new)))))
2807
2808 (defun message-insert-disposition-notification-to ()
2809   "Request a disposition notification (return receipt) to this message.
2810 Note that this should not be used in newsgroups."
2811   (interactive)
2812   (save-excursion
2813     (message-remove-header "Disposition-Notification-To")
2814     (message-goto-eoh)
2815     (insert (format "Disposition-Notification-To: %s\n"
2816                     (or (message-fetch-field "From") (message-make-from))))))
2817
2818 (defun message-elide-region (b e)
2819   "Elide the text in the region.
2820 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2821 text was killed."
2822   (interactive "r")
2823   (kill-region b e)
2824   (insert message-elide-ellipsis))
2825
2826 (defvar message-caesar-translation-table nil)
2827
2828 (defun message-caesar-region (b e &optional n)
2829   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2830   (interactive
2831    (list
2832     (min (point) (or (mark t) (point)))
2833     (max (point) (or (mark t) (point)))
2834     (when current-prefix-arg
2835       (prefix-numeric-value current-prefix-arg))))
2836
2837   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2838   (unless (or (zerop n)                 ; no action needed for a rot of 0
2839               (= b e))                  ; no region to rotate
2840     ;; We build the table, if necessary.
2841     (when (or (not message-caesar-translation-table)
2842               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2843       (setq message-caesar-translation-table
2844             (message-make-caesar-translation-table n)))
2845     (translate-region b e message-caesar-translation-table)))
2846
2847 (defun message-make-caesar-translation-table (n)
2848   "Create a rot table with offset N."
2849   (let ((i -1)
2850         (table (make-string 256 0)))
2851     (while (< (incf i) 256)
2852       (aset table i i))
2853     (concat
2854      (substring table 0 ?A)
2855      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2856      (substring table ?A (+ ?A n))
2857      (substring table (+ ?A 26) ?a)
2858      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2859      (substring table ?a (+ ?a n))
2860      (substring table (+ ?a 26) 255))))
2861
2862 (defun message-caesar-buffer-body (&optional rotnum)
2863   "Caesar rotate all letters in the current buffer by 13 places.
2864 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2865 With prefix arg, specifies the number of places to rotate each letter forward.
2866 Mail and USENET news headers are not rotated."
2867   (interactive (if current-prefix-arg
2868                    (list (prefix-numeric-value current-prefix-arg))
2869                  (list nil)))
2870   (save-excursion
2871     (save-restriction
2872       (when (message-goto-body)
2873         (narrow-to-region (point) (point-max)))
2874       (message-caesar-region (point-min) (point-max) rotnum))))
2875
2876 (defun message-pipe-buffer-body (program)
2877   "Pipe the message body in the current buffer through PROGRAM."
2878   (save-excursion
2879     (save-restriction
2880       (when (message-goto-body)
2881         (narrow-to-region (point) (point-max)))
2882       (shell-command-on-region
2883        (point-min) (point-max) program nil t))))
2884
2885 (defun message-rename-buffer (&optional enter-string)
2886   "Rename the *message* buffer to \"*message* RECIPIENT\".
2887 If the function is run with a prefix, it will ask for a new buffer
2888 name, rather than giving an automatic name."
2889   (interactive "Pbuffer name: ")
2890   (save-excursion
2891     (save-restriction
2892       (goto-char (point-min))
2893       (narrow-to-region (point)
2894                         (search-forward mail-header-separator nil 'end))
2895       (let* ((mail-to (or
2896                        (if (message-news-p) (message-fetch-field "Newsgroups")
2897                          (message-fetch-field "To"))
2898                        ""))
2899              (mail-trimmed-to
2900               (if (string-match "," mail-to)
2901                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2902                 mail-to))
2903              (name-default (concat "*message* " mail-trimmed-to))
2904              (name (if enter-string
2905                        (read-string "New buffer name: " name-default)
2906                      name-default)))
2907         (rename-buffer name t)))))
2908
2909 (defun message-fill-yanked-message (&optional justifyp)
2910   "Fill the paragraphs of a message yanked into this one.
2911 Numeric argument means justify as well."
2912   (interactive "P")
2913   (save-excursion
2914     (goto-char (point-min))
2915     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2916     (let ((fill-prefix message-yank-prefix))
2917       (fill-individual-paragraphs (point) (point-max) justifyp))))
2918
2919 (defun message-indent-citation ()
2920   "Modify text just inserted from a message to be cited.
2921 The inserted text should be the region.
2922 When this function returns, the region is again around the modified text.
2923
2924 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2925 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2926   (let ((start (point)))
2927     ;; Remove unwanted headers.
2928     (when message-ignored-cited-headers
2929       (let (all-removed)
2930         (save-restriction
2931           (narrow-to-region
2932            (goto-char start)
2933            (if (search-forward "\n\n" nil t)
2934                (1- (point))
2935              (point)))
2936           (message-remove-header message-ignored-cited-headers t)
2937           (when (= (point-min) (point-max))
2938             (setq all-removed t))
2939           (goto-char (point-max)))
2940         (if all-removed
2941             (goto-char start)
2942           (forward-line 1))))
2943     ;; Delete blank lines at the start of the buffer.
2944     (while (and (point-min)
2945                 (eolp)
2946                 (not (eobp)))
2947       (message-delete-line))
2948     ;; Delete blank lines at the end of the buffer.
2949     (goto-char (point-max))
2950     (unless (eolp)
2951       (insert "\n"))
2952     (while (and (zerop (forward-line -1))
2953                 (looking-at "$"))
2954       (message-delete-line))
2955     ;; Do the indentation.
2956     (if (null message-yank-prefix)
2957         (indent-rigidly start (mark t) message-indentation-spaces)
2958       (save-excursion
2959         (goto-char start)
2960         (while (< (point) (mark t))
2961           (if (or (looking-at ">") (looking-at "^$"))
2962               (insert message-yank-cited-prefix)
2963             (insert message-yank-prefix))
2964           (forward-line 1))))
2965     (goto-char start)))
2966
2967 (defun message-yank-original (&optional arg)
2968   "Insert the message being replied to, if any.
2969 Puts point before the text and mark after.
2970 Normally indents each nonblank line ARG spaces (default 3).  However,
2971 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2972
2973 This function uses `message-cite-function' to do the actual citing.
2974
2975 Just \\[universal-argument] as argument means don't indent, insert no
2976 prefix, and don't delete any headers."
2977   (interactive "P")
2978   (let ((modified (buffer-modified-p)))
2979     (when (and message-reply-buffer
2980                message-cite-function)
2981       (delete-windows-on message-reply-buffer t)
2982       (insert-buffer message-reply-buffer)
2983       (unless arg
2984         (funcall message-cite-function))
2985       (message-exchange-point-and-mark)
2986       (unless (bolp)
2987         (insert ?\n))
2988       (unless modified
2989         (setq message-checksum (message-checksum))))))
2990
2991 (defun message-yank-buffer (buffer)
2992   "Insert BUFFER into the current buffer and quote it."
2993   (interactive "bYank buffer: ")
2994   (let ((message-reply-buffer buffer))
2995     (save-window-excursion
2996       (message-yank-original))))
2997
2998 (defun message-buffers ()
2999   "Return a list of active message buffers."
3000   (let (buffers)
3001     (save-excursion
3002       (dolist (buffer (buffer-list t))
3003         (set-buffer buffer)
3004         (when (and (eq major-mode 'message-mode)
3005                    (null message-sent-message-via))
3006           (push (buffer-name buffer) buffers))))
3007     (nreverse buffers)))
3008
3009 (defun message-cite-original-without-signature ()
3010   "Cite function in the standard Message manner."
3011   (let ((start (point))
3012         (end (mark t))
3013         (functions
3014          (when message-indent-citation-function
3015            (if (listp message-indent-citation-function)
3016                message-indent-citation-function
3017              (list message-indent-citation-function)))))
3018     (mml-quote-region start end)
3019     ;; Allow undoing.
3020     (undo-boundary)
3021     (goto-char end)
3022     (when (re-search-backward message-signature-separator start t)
3023       ;; Also peel off any blank lines before the signature.
3024       (forward-line -1)
3025       (while (looking-at "^[ \t]*$")
3026         (forward-line -1))
3027       (forward-line 1)
3028       (delete-region (point) end)
3029       (unless (search-backward "\n\n" start t)
3030         ;; Insert a blank line if it is peeled off.
3031         (insert "\n")))
3032     (goto-char start)
3033     (while functions
3034       (funcall (pop functions)))
3035     (when message-citation-line-function
3036       (unless (bolp)
3037         (insert "\n"))
3038       (funcall message-citation-line-function))))
3039
3040 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
3041 (defun message-cite-original ()
3042   "Cite function in the standard Message manner."
3043   (if (and (boundp 'mail-citation-hook)
3044            mail-citation-hook)
3045       (run-hooks 'mail-citation-hook)
3046     (let ((start (point))
3047           (end (mark t))
3048           (functions
3049            (when message-indent-citation-function
3050              (if (listp message-indent-citation-function)
3051                  message-indent-citation-function
3052                (list message-indent-citation-function)))))
3053       (mml-quote-region start end)
3054       (goto-char start)
3055       (while functions
3056         (funcall (pop functions)))
3057       (when message-citation-line-function
3058         (unless (bolp)
3059           (insert "\n"))
3060         (funcall message-citation-line-function)))))
3061
3062 (defun message-insert-citation-line ()
3063   "Insert a simple citation line."
3064   (when message-reply-headers
3065     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3066
3067 (defun message-position-on-field (header &rest afters)
3068   (let ((case-fold-search t))
3069     (save-restriction
3070       (narrow-to-region
3071        (goto-char (point-min))
3072        (progn
3073          (re-search-forward
3074           (concat "^" (regexp-quote mail-header-separator) "$"))
3075          (match-beginning 0)))
3076       (goto-char (point-min))
3077       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3078           (progn
3079             (re-search-forward "^[^ \t]" nil 'move)
3080             (beginning-of-line)
3081             (skip-chars-backward "\n")
3082             t)
3083         (while (and afters
3084                     (not (re-search-forward
3085                           (concat "^" (regexp-quote (car afters)) ":")
3086                           nil t)))
3087           (pop afters))
3088         (when afters
3089           (re-search-forward "^[^ \t]" nil 'move)
3090           (beginning-of-line))
3091         (insert header ": \n")
3092         (forward-char -1)
3093         nil))))
3094
3095 (defun message-remove-signature ()
3096   "Remove the signature from the text between point and mark.
3097 The text will also be indented the normal way."
3098   (save-excursion
3099     (let ((start (point))
3100           mark)
3101       (if (not (re-search-forward message-signature-separator (mark t) t))
3102           ;; No signature here, so we just indent the cited text.
3103           (message-indent-citation)
3104         ;; Find the last non-empty line.
3105         (forward-line -1)
3106         (while (looking-at "[ \t]*$")
3107           (forward-line -1))
3108         (forward-line 1)
3109         (setq mark (set-marker (make-marker) (point)))
3110         (goto-char start)
3111         (message-indent-citation)
3112         ;; Enable undoing the deletion.
3113         (undo-boundary)
3114         (delete-region mark (mark t))
3115         (set-marker mark nil)))))
3116
3117 \f
3118
3119 ;;;
3120 ;;; Sending messages
3121 ;;;
3122
3123 (defun message-send-and-exit (&optional arg)
3124   "Send message like `message-send', then, if no errors, exit from mail buffer."
3125   (interactive "P")
3126   (let ((buf (current-buffer))
3127         (actions message-exit-actions))
3128     (when (and (message-send arg)
3129                (buffer-name buf))
3130       (if message-kill-buffer-on-exit
3131           (kill-buffer buf)
3132         (bury-buffer buf)
3133         (when (eq buf (current-buffer))
3134           (message-bury buf)))
3135       (message-do-actions actions)
3136       t)))
3137
3138 (defun message-dont-send ()
3139   "Don't send the message you have been editing.
3140 Instead, just auto-save the buffer and then bury it."
3141   (interactive)
3142   (set-buffer-modified-p t)
3143   (save-buffer)
3144   (let ((actions message-postpone-actions))
3145     (message-bury (current-buffer))
3146     (message-do-actions actions)))
3147
3148 (defun message-kill-buffer ()
3149   "Kill the current buffer."
3150   (interactive)
3151   (when (or (not (buffer-modified-p))
3152             (yes-or-no-p "Message modified; kill anyway? "))
3153     (let ((actions message-kill-actions)
3154           (draft-article message-draft-article)
3155           (auto-save-file-name buffer-auto-save-file-name)
3156           (file-name buffer-file-name)
3157           (modified (buffer-modified-p)))
3158       (setq buffer-file-name nil)
3159       (kill-buffer (current-buffer))
3160       (when (and (or (and auto-save-file-name
3161                           (file-exists-p auto-save-file-name))
3162                      (and file-name
3163                           (file-exists-p file-name)))
3164                (yes-or-no-p (format "Remove the backup file%s? "
3165                                     (if modified " too" ""))))
3166         (ignore-errors
3167           (delete-file auto-save-file-name))
3168         (let ((message-draft-article draft-article))
3169           (message-disassociate-draft)))
3170       (message-do-actions actions))))
3171
3172 (defun message-bury (buffer)
3173   "Bury this mail BUFFER."
3174   (let ((newbuf (other-buffer buffer)))
3175     (bury-buffer buffer)
3176     (if (and (fboundp 'frame-parameters)
3177              (cdr (assq 'dedicated (frame-parameters)))
3178              (not (null (delq (selected-frame) (visible-frame-list)))))
3179         (delete-frame (selected-frame))
3180       (switch-to-buffer newbuf))))
3181
3182 (defun message-send (&optional arg)
3183   "Send the message in the current buffer.
3184 If `message-interactive' is non-nil, wait for success indication or
3185 error messages, and inform user.
3186 Otherwise any failure is reported in a message back to the user from
3187 the mailer.
3188 The usage of ARG is defined by the instance that called Message.
3189 It should typically alter the sending method in some way or other."
3190   (interactive "P")
3191   ;; Make it possible to undo the coming changes.
3192   (undo-boundary)
3193   (let ((inhibit-read-only t))
3194     (put-text-property (point-min) (point-max) 'read-only nil))
3195   (message-fix-before-sending)
3196   (run-hooks 'message-send-hook)
3197   (message message-sending-message)
3198   (let ((alist message-send-method-alist)
3199         (success t)
3200         elem sent dont-barf-on-no-method
3201         (message-options message-options))
3202     (message-options-set-recipient)
3203     (while (and success
3204                 (setq elem (pop alist)))
3205       (when (funcall (cadr elem))
3206         (when (and (or (not (memq (car elem)
3207                                   message-sent-message-via))
3208                        (not (message-fetch-field "supersedes"))
3209                        (if (or (message-gnksa-enable-p 'multiple-copies)
3210                                (not (eq (car elem) 'news)))
3211                            (y-or-n-p
3212                             (format
3213                              "Already sent message via %s; resend? "
3214                              (car elem)))
3215                          (error "Denied posting -- multiple copies")))
3216                    (setq success (funcall (caddr elem) arg)))
3217           (setq sent t))))
3218     (unless (or sent
3219                 (not success)
3220                 (let ((fcc (message-fetch-field "Fcc"))
3221                       (gcc (message-fetch-field "Gcc")))
3222                   (when (or fcc gcc)
3223                     (or (eq message-allow-no-recipients 'always)
3224                         (and (not (eq message-allow-no-recipients 'never))
3225                              (setq dont-barf-on-no-method
3226                                    (gnus-y-or-n-p
3227                                     (format "No receiver, perform %s anyway? "
3228                                             (cond ((and fcc gcc) "Fcc and Gcc")
3229                                                   (fcc "Fcc")
3230                                                   (t "Gcc"))))))))))
3231       (error "No methods specified to send by"))
3232     (when (or dont-barf-on-no-method
3233               (and success sent))
3234       (message-do-fcc)
3235       (save-excursion
3236         (run-hooks 'message-sent-hook))
3237       (message "Sending...done")
3238       ;; Mark the buffer as unmodified and delete auto-save.
3239       (set-buffer-modified-p nil)
3240       (delete-auto-save-file-if-necessary t)
3241       (message-disassociate-draft)
3242       ;; Delete other mail buffers and stuff.
3243       (message-do-send-housekeeping)
3244       (message-do-actions message-send-actions)
3245       ;; Return success.
3246       t)))
3247
3248 (defun message-send-via-mail (arg)
3249   "Send the current message via mail."
3250   (message-send-mail arg))
3251
3252 (defun message-send-via-news (arg)
3253   "Send the current message via news."
3254   (funcall message-send-news-function arg))
3255
3256 (defmacro message-check (type &rest forms)
3257   "Eval FORMS if TYPE is to be checked."
3258   `(or (message-check-element ,type)
3259        (save-excursion
3260          ,@forms)))
3261
3262 (put 'message-check 'lisp-indent-function 1)
3263 (put 'message-check 'edebug-form-spec '(form body))
3264
3265 (defun message-text-with-property (prop)
3266   "Return a list of all points where the text has PROP."
3267   (let ((points nil)
3268         (point (point-min)))
3269     (save-excursion
3270       (while (< point (point-max))
3271         (when (get-text-property point prop)
3272           (push point points))
3273         (incf point)))
3274     (nreverse points)))
3275
3276 (defun message-fix-before-sending ()
3277   "Do various things to make the message nice before sending it."
3278   ;; Make sure there's a newline at the end of the message.
3279   (goto-char (point-max))
3280   (unless (bolp)
3281     (insert "\n"))
3282   ;; Delete all invisible text.
3283   (message-check 'invisible-text
3284     (let ((points (message-text-with-property 'invisible)))
3285       (when points
3286         (goto-char (car points))
3287         (dolist (point points)
3288           (add-text-properties point (1+ point)
3289                                '(invisible nil face highlight
3290                                            font-lock-face highlight)))
3291         (unless (yes-or-no-p
3292                  "Invisible text found and made visible; continue posting? ")
3293           (error "Invisible text found and made visible")))))
3294   (message-check 'illegible-text
3295     (let (found choice)
3296       (message-goto-body)
3297       (skip-chars-forward mm-7bit-chars)
3298       (while (not (eobp))
3299         (when (let ((char (char-after)))
3300                 (or (< (mm-char-int char) 128)
3301                     (and (mm-multibyte-p)
3302                          (memq (char-charset char)
3303                                '(eight-bit-control eight-bit-graphic
3304                                                    control-1)))))
3305           (add-text-properties (point) (1+ (point))
3306                                '(font-lock-face highlight face highlight))
3307           (setq found t))
3308         (forward-char)
3309         (skip-chars-forward mm-7bit-chars))
3310       (when found
3311         (setq choice
3312               (gnus-multiple-choice
3313                "Illegible text found.  Continue posting?"
3314                '((?d "Remove and continue posting")
3315                  (?r "Replace with dots and continue posting")
3316                  (?i "Ignore and continue posting")
3317                  (?e "Continue editing"))))
3318         (if (eq choice ?e)
3319           (error "Illegible text found"))
3320         (message-goto-body)
3321         (skip-chars-forward mm-7bit-chars)
3322         (while (not (eobp))
3323           (when (let ((char (char-after)))
3324                   (or (< (mm-char-int char) 128)
3325                       (and (mm-multibyte-p)
3326                            (memq (char-charset char)
3327                                  '(eight-bit-control eight-bit-graphic
3328                                                      control-1)))))
3329             (if (eq choice ?i)
3330                 (remove-text-properties (point) (1+ (point))
3331                                         '(font-lock-face highlight face highlight))
3332               (delete-char 1)
3333               (when (eq choice ?r)
3334                 (insert "."))))
3335           (forward-char)
3336           (skip-chars-forward mm-7bit-chars))))))
3337
3338 (defun message-add-action (action &rest types)
3339   "Add ACTION to be performed when doing an exit of type TYPES."
3340   (while types
3341     (add-to-list (intern (format "message-%s-actions" (pop types)))
3342                  action)))
3343
3344 (defun message-delete-action (action &rest types)
3345   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3346   (let (var)
3347     (while types
3348       (set (setq var (intern (format "message-%s-actions" (pop types))))
3349            (delq action (symbol-value var))))))
3350
3351 (defun message-do-actions (actions)
3352   "Perform all actions in ACTIONS."
3353   ;; Now perform actions on successful sending.
3354   (while actions
3355     (ignore-errors
3356       (cond
3357        ;; A simple function.
3358        ((message-functionp (car actions))
3359         (funcall (car actions)))
3360        ;; Something to be evaled.
3361        (t
3362         (eval (car actions)))))
3363     (pop actions)))
3364
3365 (defun message-send-mail-partially ()
3366   "Send mail as message/partial."
3367   ;; replace the header delimiter with a blank line
3368   (goto-char (point-min))
3369   (re-search-forward
3370    (concat "^" (regexp-quote mail-header-separator) "\n"))
3371   (replace-match "\n")
3372   (run-hooks 'message-send-mail-hook)
3373   (let ((p (goto-char (point-min)))
3374         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3375         (curbuf (current-buffer))
3376         (id (message-make-message-id)) (n 1)
3377         plist total  header required-mail-headers)
3378     (while (not (eobp))
3379       (if (< (point-max) (+ p message-send-mail-partially-limit))
3380           (goto-char (point-max))
3381         (goto-char (+ p message-send-mail-partially-limit))
3382         (beginning-of-line)
3383         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3384       (push p plist)
3385       (setq p (point)))
3386     (setq total (length plist))
3387     (push (point-max) plist)
3388     (setq plist (nreverse plist))
3389     (unwind-protect
3390         (save-excursion
3391           (setq p (pop plist))
3392           (while plist
3393             (set-buffer curbuf)
3394             (copy-to-buffer tembuf p (car plist))
3395             (set-buffer tembuf)
3396             (goto-char (point-min))
3397             (if header
3398                 (progn
3399                   (goto-char (point-min))
3400                   (narrow-to-region (point) (point))
3401                   (insert header))
3402               (message-goto-eoh)
3403               (setq header (buffer-substring (point-min) (point)))
3404               (goto-char (point-min))
3405               (narrow-to-region (point) (point))
3406               (insert header)
3407               (message-remove-header "Mime-Version")
3408               (message-remove-header "Content-Type")
3409               (message-remove-header "Content-Transfer-Encoding")
3410               (message-remove-header "Message-ID")
3411               (message-remove-header "Lines")
3412               (goto-char (point-max))
3413               (insert "Mime-Version: 1.0\n")
3414               (setq header (buffer-string)))
3415             (goto-char (point-max))
3416             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3417                             id n total))
3418             (forward-char -1)
3419             (let ((mail-header-separator ""))
3420               (when (memq 'Message-ID message-required-mail-headers)
3421                 (insert "Message-ID: " (message-make-message-id) "\n"))
3422               (when (memq 'Lines message-required-mail-headers)
3423                 (insert "Lines: " (message-make-lines) "\n"))
3424               (message-goto-subject)
3425               (end-of-line)
3426               (insert (format " (%d/%d)" n total))
3427               (widen)
3428               (mm-with-unibyte-current-buffer
3429                 (funcall (or message-send-mail-real-function
3430                              message-send-mail-function))))
3431             (setq n (+ n 1))
3432             (setq p (pop plist))
3433             (erase-buffer)))
3434       (kill-buffer tembuf))))
3435
3436 (defun message-send-mail (&optional arg)
3437   (require 'mail-utils)
3438   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3439          (case-fold-search nil)
3440          (news (message-news-p))
3441          (mailbuf (current-buffer))
3442          (message-this-is-mail t)
3443          (message-posting-charset
3444           (if (fboundp 'gnus-setup-posting-charset)
3445               (gnus-setup-posting-charset nil)
3446             message-posting-charset))
3447          (headers message-required-mail-headers))
3448     (save-restriction
3449       (message-narrow-to-headers)
3450       ;; Generate the Mail-Followup-To header if the header is not there...
3451       (if (and (message-subscribed-p)
3452                (not (mail-fetch-field "mail-followup-to")))
3453           (setq headers
3454                 (cons
3455                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
3456                  message-required-mail-headers))
3457         ;; otherwise, delete the MFT header if the field is empty
3458         (when (equal "" (mail-fetch-field "mail-followup-to"))
3459           (message-remove-header "^Mail-Followup-To:")))
3460       ;; Insert some headers.
3461       (let ((message-deletable-headers
3462              (if news nil message-deletable-headers)))
3463         (message-generate-headers headers))
3464       ;; Let the user do all of the above.
3465       (run-hooks 'message-header-hook))
3466     (unwind-protect
3467         (save-excursion
3468           (set-buffer tembuf)
3469           (erase-buffer)
3470           ;; Avoid copying text props (except hard newlines).
3471           (insert (with-current-buffer mailbuf
3472                     (mml-buffer-substring-no-properties-except-hard-newlines
3473                      (point-min) (point-max))))
3474           ;; Remove some headers.
3475           (message-encode-message-body)
3476           (save-restriction
3477             (message-narrow-to-headers)
3478             ;; We (re)generate the Lines header.
3479             (when (memq 'Lines message-required-mail-headers)
3480               (message-generate-headers '(Lines)))
3481             ;; Remove some headers.
3482             (message-remove-header message-ignored-mail-headers t)
3483             (let ((mail-parse-charset message-default-charset))
3484               (mail-encode-encoded-word-buffer)))
3485           (goto-char (point-max))
3486           ;; require one newline at the end.
3487           (or (= (preceding-char) ?\n)
3488               (insert ?\n))
3489           (message-cleanup-headers)
3490           (when
3491               (save-restriction
3492                 (message-narrow-to-headers)
3493                 (and news
3494                      (or (message-fetch-field "cc")
3495                          (message-fetch-field "bcc")
3496                          (message-fetch-field "to"))
3497                      (let ((content-type (message-fetch-field "content-type")))
3498                        (or
3499                         (not content-type)
3500                         (string= "text/plain"
3501                                  (car
3502                                   (mail-header-parse-content-type
3503                                    content-type)))))))
3504             (message-insert-courtesy-copy))
3505           (if (or (not message-send-mail-partially-limit)
3506                   (< (point-max) message-send-mail-partially-limit)
3507                   (not (message-y-or-n-p
3508                         "The message size is too large, split? "
3509                         t
3510                         "\
3511 The message size, "
3512                         (/ (point-max) 1000) "KB, is too large.
3513
3514 Some mail gateways (MTA's) bounce large messages.  To avoid the
3515 problem, answer `y', and the message will be split into several
3516 smaller pieces, the size of each is about "
3517                         (/ message-send-mail-partially-limit 1000)
3518                         "KB except the last
3519 one.
3520
3521 However, some mail readers (MUA's) can't read split messages, i.e.,
3522 mails in message/partially format. Answer `n', and the message will be
3523 sent in one piece.
3524
3525 The size limit is controlled by `message-send-mail-partially-limit'.
3526 If you always want Gnus to send messages in one piece, set
3527 `message-send-mail-partially-limit' to nil.
3528 ")))
3529               (mm-with-unibyte-current-buffer
3530                 (message "Sending via mail...")
3531                 (funcall (or message-send-mail-real-function
3532                              message-send-mail-function)))
3533             (message-send-mail-partially)))
3534       (kill-buffer tembuf))
3535     (set-buffer mailbuf)
3536     (push 'mail message-sent-message-via)))
3537
3538 (defun message-send-mail-with-sendmail ()
3539   "Send off the prepared buffer with sendmail."
3540   (let ((errbuf (if message-interactive
3541                     (message-generate-new-buffer-clone-locals
3542                      " sendmail errors")
3543                   0))
3544         resend-to-addresses delimline)
3545     (unwind-protect
3546         (progn
3547           (let ((case-fold-search t))
3548             (save-restriction
3549               (message-narrow-to-headers)
3550               (setq resend-to-addresses (message-fetch-field "resent-to")))
3551             ;; Change header-delimiter to be what sendmail expects.
3552             (goto-char (point-min))
3553             (re-search-forward
3554              (concat "^" (regexp-quote mail-header-separator) "\n"))
3555             (replace-match "\n")
3556             (backward-char 1)
3557             (setq delimline (point-marker))
3558             (run-hooks 'message-send-mail-hook)
3559             ;; Insert an extra newline if we need it to work around
3560             ;; Sun's bug that swallows newlines.
3561             (goto-char (1+ delimline))
3562             (when (eval message-mailer-swallows-blank-line)
3563               (newline))
3564             (when message-interactive
3565               (save-excursion
3566                 (set-buffer errbuf)
3567                 (erase-buffer))))
3568           (let* ((default-directory "/")
3569                  (coding-system-for-write message-send-coding-system)
3570                  (cpr (apply
3571                        'call-process-region
3572                        (append
3573                         (list (point-min) (point-max)
3574                               (if (boundp 'sendmail-program)
3575                                   sendmail-program
3576                                 "/usr/lib/sendmail")
3577                               nil errbuf nil "-oi")
3578                         ;; Always specify who from,
3579                         ;; since some systems have broken sendmails.
3580                         ;; But some systems are more broken with -f, so
3581                         ;; we'll let users override this.
3582                         (if (null message-sendmail-f-is-evil)
3583                             (list "-f" (message-sendmail-envelope-from)))
3584                         ;; These mean "report errors by mail"
3585                         ;; and "deliver in background".
3586                         (if (null message-interactive) '("-oem" "-odb"))
3587                         ;; Get the addresses from the message
3588                         ;; unless this is a resend.
3589                         ;; We must not do that for a resend
3590                         ;; because we would find the original addresses.
3591                         ;; For a resend, include the specific addresses.
3592                         (if resend-to-addresses
3593                             (list resend-to-addresses)
3594                           '("-t"))))))
3595             (unless (or (null cpr) (zerop cpr))
3596               (error "Sending...failed with exit value %d" cpr)))
3597           (when message-interactive
3598             (save-excursion
3599               (set-buffer errbuf)
3600               (goto-char (point-min))
3601               (while (re-search-forward "\n\n* *" nil t)
3602                 (replace-match "; "))
3603               (if (not (zerop (buffer-size)))
3604                   (error "Sending...failed to %s"
3605                          (buffer-string))))))
3606       (when (bufferp errbuf)
3607         (kill-buffer errbuf)))))
3608
3609 (defun message-send-mail-with-qmail ()
3610   "Pass the prepared message buffer to qmail-inject.
3611 Refer to the documentation for the variable `message-send-mail-function'
3612 to find out how to use this."
3613   ;; replace the header delimiter with a blank line
3614   (goto-char (point-min))
3615   (re-search-forward
3616    (concat "^" (regexp-quote mail-header-separator) "\n"))
3617   (replace-match "\n")
3618   (run-hooks 'message-send-mail-hook)
3619   ;; send the message
3620   (case
3621       (let ((coding-system-for-write message-send-coding-system))
3622         (apply
3623          'call-process-region 1 (point-max) message-qmail-inject-program
3624          nil nil nil
3625          ;; qmail-inject's default behaviour is to look for addresses on the
3626          ;; command line; if there're none, it scans the headers.
3627          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3628          ;;
3629          ;; in general, ALL of qmail-inject's defaults are perfect for simply
3630          ;; reading a formatted (i. e., at least a To: or Resent-To header)
3631          ;; message from stdin.
3632          ;;
3633          ;; qmail also has the advantage of not having been raped by
3634          ;; various vendors, so we don't have to allow for that, either --
3635          ;; compare this with message-send-mail-with-sendmail and weep
3636          ;; for sendmail's lost innocence.
3637          ;;
3638          ;; all this is way cool coz it lets us keep the arguments entirely
3639          ;; free for -inject-arguments -- a big win for the user and for us
3640          ;; since we don't have to play that double-guessing game and the user
3641          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3642          (if (message-functionp message-qmail-inject-args)
3643              (funcall message-qmail-inject-args)
3644            message-qmail-inject-args)))
3645     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3646     ;; we have to look at the retval instead
3647     (0 nil)
3648     (100 (error "qmail-inject reported permanent failure"))
3649     (111 (error "qmail-inject reported transient failure"))
3650     ;; should never happen
3651     (t   (error "qmail-inject reported unknown failure"))))
3652
3653 (defun message-send-mail-with-mh ()
3654   "Send the prepared message buffer with mh."
3655   (let ((mh-previous-window-config nil)
3656         (name (mh-new-draft-name)))
3657     (setq buffer-file-name name)
3658     ;; MH wants to generate these headers itself.
3659     (when message-mh-deletable-headers
3660       (let ((headers message-mh-deletable-headers))
3661         (while headers
3662           (goto-char (point-min))
3663           (and (re-search-forward
3664                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3665                (message-delete-line))
3666           (pop headers))))
3667     (run-hooks 'message-send-mail-hook)
3668     ;; Pass it on to mh.
3669     (mh-send-letter)))
3670
3671 (defun message-smtpmail-send-it ()
3672   "Send the prepared message buffer with `smtpmail-send-it'.
3673 This only differs from `smtpmail-send-it' that this command evaluates
3674 `message-send-mail-hook' just before sending a message.  It is useful
3675 if your ISP requires the POP-before-SMTP authentication.  See the
3676 documentation for the function `mail-source-touch-pop'."
3677   (run-hooks 'message-send-mail-hook)
3678   (smtpmail-send-it))
3679
3680 (defun message-canlock-generate ()
3681   "Return a string that is non-trival to guess.
3682 Do not use this for anything important, it is cryptographically weak."
3683   (let (sha1-maximum-internal-length)
3684     (sha1 (concat (message-unique-id)
3685                   (format "%x%x%x" (random) (random t) (random))
3686                   (prin1-to-string (recent-keys))
3687                   (prin1-to-string (garbage-collect))))))
3688
3689 (defun message-canlock-password ()
3690   "The password used by message for cancel locks.
3691 This is the value of `canlock-password', if that option is non-nil.
3692 Otherwise, generate and save a value for `canlock-password' first."
3693   (unless canlock-password
3694     (customize-save-variable 'canlock-password (message-canlock-generate))
3695     (setq canlock-password-for-verify canlock-password))
3696   canlock-password)
3697
3698 (defun message-insert-canlock ()
3699   (when message-insert-canlock
3700     (message-canlock-password)
3701     (canlock-insert-header)))
3702
3703 (defun message-send-news (&optional arg)
3704   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3705          (case-fold-search nil)
3706          (method (if (message-functionp message-post-method)
3707                      (funcall message-post-method arg)
3708                    message-post-method))
3709          (newsgroups-field (save-restriction
3710                             (message-narrow-to-headers-or-head)
3711                             (message-fetch-field "Newsgroups")))
3712          (followup-field (save-restriction
3713                            (message-narrow-to-headers-or-head)
3714                            (message-fetch-field "Followup-To")))
3715          ;; BUG: We really need to get the charset for each name in the
3716          ;; Newsgroups and Followup-To lines to allow crossposting
3717          ;; between group namess with incompatible character sets.
3718          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3719          (group-field-charset
3720           (gnus-group-name-charset method newsgroups-field))
3721          (followup-field-charset
3722           (gnus-group-name-charset method (or followup-field "")))
3723          (rfc2047-header-encoding-alist
3724           (append (when group-field-charset
3725                     (list (cons "Newsgroups" group-field-charset)))
3726                   (when followup-field-charset
3727                     (list (cons "Followup-To" followup-field-charset)))
3728                   rfc2047-header-encoding-alist))
3729          (messbuf (current-buffer))
3730          (message-syntax-checks
3731           (if (and arg
3732                    (listp message-syntax-checks))
3733               (cons '(existing-newsgroups . disabled)
3734                     message-syntax-checks)
3735             message-syntax-checks))
3736          (message-this-is-news t)
3737          (message-posting-charset
3738           (gnus-setup-posting-charset newsgroups-field))
3739          result)
3740     (if (not (message-check-news-body-syntax))
3741         nil
3742       (save-restriction
3743         (message-narrow-to-headers)
3744         ;; Insert some headers.
3745         (message-generate-headers message-required-news-headers)
3746         (message-insert-canlock)
3747         ;; Let the user do all of the above.
3748         (run-hooks 'message-header-hook))
3749       ;; Note: This check will be disabled by the ".*" default value for
3750       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3751       (when (and group-field-charset
3752                  (listp message-syntax-checks))
3753         (setq message-syntax-checks
3754               (cons '(valid-newsgroups . disabled)
3755                     message-syntax-checks)))
3756       (message-cleanup-headers)
3757       (if (not (let ((message-post-method method))
3758                  (message-check-news-syntax)))
3759           nil
3760         (unwind-protect
3761             (save-excursion
3762               (set-buffer tembuf)
3763               (buffer-disable-undo)
3764               (erase-buffer)
3765               ;; Avoid copying text props (except hard newlines).
3766               (insert
3767                (with-current-buffer messbuf
3768                  (mml-buffer-substring-no-properties-except-hard-newlines
3769                   (point-min) (point-max))))
3770               (message-encode-message-body)
3771               ;; Remove some headers.
3772               (save-restriction
3773                 (message-narrow-to-headers)
3774                 ;; We (re)generate the Lines header.
3775                 (when (memq 'Lines message-required-mail-headers)
3776                   (message-generate-headers '(Lines)))
3777                 ;; Remove some headers.
3778                 (message-remove-header message-ignored-news-headers t)
3779                 (let ((mail-parse-charset message-default-charset))
3780                   (mail-encode-encoded-word-buffer)))
3781               (goto-char (point-max))
3782               ;; require one newline at the end.
3783               (or (= (preceding-char) ?\n)
3784                   (insert ?\n))
3785               (let ((case-fold-search t))
3786                 ;; Remove the delimiter.
3787                 (goto-char (point-min))
3788                 (re-search-forward
3789                  (concat "^" (regexp-quote mail-header-separator) "\n"))
3790                 (replace-match "\n")
3791                 (backward-char 1))
3792               (run-hooks 'message-send-news-hook)
3793               (gnus-open-server method)
3794               (message "Sending news via %s..." (gnus-server-string method))
3795               (setq result (let ((mail-header-separator ""))
3796                              (gnus-request-post method))))
3797           (kill-buffer tembuf))
3798         (set-buffer messbuf)
3799         (if result
3800             (push 'news message-sent-message-via)
3801           (message "Couldn't send message via news: %s"
3802                    (nnheader-get-report (car method)))
3803           nil)))))
3804
3805 ;;;
3806 ;;; Header generation & syntax checking.
3807 ;;;
3808
3809 (defun message-check-element (type)
3810   "Return non-nil if this TYPE is not to be checked."
3811   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3812       t
3813     (let ((able (assq type message-syntax-checks)))
3814       (and (consp able)
3815            (eq (cdr able) 'disabled)))))
3816
3817 (defun message-check-news-syntax ()
3818   "Check the syntax of the message."
3819   (save-excursion
3820     (save-restriction
3821       (widen)
3822       ;; We narrow to the headers and check them first.
3823       (save-excursion
3824         (save-restriction
3825           (message-narrow-to-headers)
3826           (message-check-news-header-syntax))))))
3827
3828 (defun message-check-news-header-syntax ()
3829   (and
3830    ;; Check Newsgroups header.
3831    (message-check 'newsgroups
3832      (let ((group (message-fetch-field "newsgroups")))
3833        (or
3834         (and group
3835              (not (string-match "\\`[ \t]*\\'" group)))
3836         (ignore
3837          (message
3838           "The newsgroups field is empty or missing.  Posting is denied.")))))
3839    ;; Check the Subject header.
3840    (message-check 'subject
3841      (let* ((case-fold-search t)
3842             (subject (message-fetch-field "subject")))
3843        (or
3844         (and subject
3845              (not (string-match "\\`[ \t]*\\'" subject)))
3846         (ignore
3847          (message
3848           "The subject field is empty or missing.  Posting is denied.")))))
3849    ;; Check for commands in Subject.
3850    (message-check 'subject-cmsg
3851      (if (string-match "^cmsg " (message-fetch-field "subject"))
3852          (y-or-n-p
3853           "The control code \"cmsg\" is in the subject.  Really post? ")
3854        t))
3855    ;; Check long header lines.
3856    (message-check 'long-header-lines
3857      (let ((start (point))
3858            (header nil)
3859            (length 0)
3860            found)
3861        (while (and (not found)
3862                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
3863          (if (> (- (point) (match-beginning 0)) 998)
3864              (setq found t
3865                    length (- (point) (match-beginning 0)))
3866            (setq header (match-string-no-properties 1)))
3867          (setq start (match-beginning 0))
3868          (forward-line 1))
3869        (if found
3870            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
3871                              header length))
3872          t)))
3873    ;; Check for multiple identical headers.
3874    (message-check 'multiple-headers
3875      (let (found)
3876        (while (and (not found)
3877                    (re-search-forward "^[^ \t:]+: " nil t))
3878          (save-excursion
3879            (or (re-search-forward
3880                 (concat "^"
3881                         (regexp-quote
3882                          (setq found
3883                                (buffer-substring
3884                                 (match-beginning 0) (- (match-end 0) 2))))
3885                         ":")
3886                 nil t)
3887                (setq found nil))))
3888        (if found
3889            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3890          t)))
3891    ;; Check for Version and Sendsys.
3892    (message-check 'sendsys
3893      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3894          (y-or-n-p
3895           (format "The article contains a %s command.  Really post? "
3896                   (buffer-substring (match-beginning 0)
3897                                     (1- (match-end 0)))))
3898        t))
3899    ;; See whether we can shorten Followup-To.
3900    (message-check 'shorten-followup-to
3901      (let ((newsgroups (message-fetch-field "newsgroups"))
3902            (followup-to (message-fetch-field "followup-to"))
3903            to)
3904        (when (and newsgroups
3905                   (string-match "," newsgroups)
3906                   (not followup-to)
3907                   (not
3908                    (zerop
3909                     (length
3910                      (setq to (completing-read
3911                                "Followups to (default: no Followup-To header) "
3912                                (mapcar (lambda (g) (list g))
3913                                        (cons "poster"
3914                                              (message-tokenize-header
3915                                               newsgroups)))))))))
3916          (goto-char (point-min))
3917          (insert "Followup-To: " to "\n"))
3918        t))
3919    ;; Check "Shoot me".
3920    (message-check 'shoot
3921      (if (re-search-forward
3922           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
3923          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3924        t))
3925    ;; Check for Approved.
3926    (message-check 'approved
3927      (if (re-search-forward "^Approved:" nil t)
3928          (y-or-n-p "The article contains an Approved header.  Really post? ")
3929        t))
3930    ;; Check the Message-ID header.
3931    (message-check 'message-id
3932      (let* ((case-fold-search t)
3933             (message-id (message-fetch-field "message-id" t)))
3934        (or (not message-id)
3935            ;; Is there an @ in the ID?
3936            (and (string-match "@" message-id)
3937                 ;; Is there a dot in the ID?
3938                 (string-match "@[^.]*\\." message-id)
3939                 ;; Does the ID end with a dot?
3940                 (not (string-match "\\.>" message-id)))
3941            (y-or-n-p
3942             (format "The Message-ID looks strange: \"%s\".  Really post? "
3943                     message-id)))))
3944    ;; Check the Newsgroups & Followup-To headers.
3945    (message-check 'existing-newsgroups
3946      (let* ((case-fold-search t)
3947             (newsgroups (message-fetch-field "newsgroups"))
3948             (followup-to (message-fetch-field "followup-to"))
3949             (groups (message-tokenize-header
3950                      (if followup-to
3951                          (concat newsgroups "," followup-to)
3952                        newsgroups)))
3953             (post-method (if (message-functionp message-post-method)
3954                              (funcall message-post-method)
3955                            message-post-method))
3956             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3957             ;; would probably involve a new nnoo function.
3958             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3959             (method (if (and (consp post-method)
3960                              (eq (car post-method) 'nnvirtual)
3961                              gnus-message-group-art)
3962                         (let ((group (car (nnvirtual-find-group-art
3963                                            (car gnus-message-group-art)
3964                                            (cdr gnus-message-group-art)))))
3965                           (gnus-find-method-for-group group))
3966                       post-method))
3967             (known-groups
3968              (mapcar (lambda (n)
3969                        (gnus-group-name-decode
3970                         (gnus-group-real-name n)
3971                         (gnus-group-name-charset method n)))
3972                      (gnus-groups-from-server method)))
3973             errors)
3974        (while groups
3975          (when (and (not (equal (car groups) "poster"))
3976                     (not (member (car groups) known-groups))
3977                     (not (member (car groups) errors)))
3978            (push (car groups) errors))
3979          (pop groups))
3980        (cond
3981         ;; Gnus is not running.
3982         ((or (not (and (boundp 'gnus-active-hashtb)
3983                        gnus-active-hashtb))
3984              (not (boundp 'gnus-read-active-file)))
3985          t)
3986         ;; We don't have all the group names.
3987         ((and (or (not gnus-read-active-file)
3988                   (eq gnus-read-active-file 'some))
3989               errors)
3990          (y-or-n-p
3991           (format
3992            "Really post to %s possibly unknown group%s: %s? "
3993            (if (= (length errors) 1) "this" "these")
3994            (if (= (length errors) 1) "" "s")
3995            (mapconcat 'identity errors ", "))))
3996         ;; There were no errors.
3997         ((not errors)
3998          t)
3999         ;; There are unknown groups.
4000         (t
4001          (y-or-n-p
4002           (format
4003            "Really post to %s unknown group%s: %s? "
4004            (if (= (length errors) 1) "this" "these")
4005            (if (= (length errors) 1) "" "s")
4006            (mapconcat 'identity errors ", ")))))))
4007    ;; Check continuation headers.
4008    (message-check 'continuation-headers
4009      (goto-char (point-min))
4010      (let ((do-posting t))
4011        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4012          (if (y-or-n-p "Fix continuation lines? ")
4013              (progn
4014                (goto-char (match-beginning 0))
4015                (insert " "))
4016            (unless (y-or-n-p "Send anyway? ")
4017              (setq do-posting nil))))
4018        do-posting))
4019    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4020    (message-check 'valid-newsgroups
4021      (let ((case-fold-search t)
4022            (headers '("Newsgroups" "Followup-To"))
4023            header error)
4024        (while (and headers (not error))
4025          (when (setq header (mail-fetch-field (car headers)))
4026            (if (or
4027                 (not
4028                  (string-match
4029                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4030                   header))
4031                 (memq
4032                  nil (mapcar
4033                       (lambda (g)
4034                         (not (string-match "\\.\\'\\|\\.\\." g)))
4035                       (message-tokenize-header header ","))))
4036                (setq error t)))
4037          (unless error
4038            (pop headers)))
4039        (if (not error)
4040            t
4041          (y-or-n-p
4042           (format "The %s header looks odd: \"%s\".  Really post? "
4043                   (car headers) header)))))
4044    (message-check 'repeated-newsgroups
4045      (let ((case-fold-search t)
4046            (headers '("Newsgroups" "Followup-To"))
4047            header error groups group)
4048        (while (and headers
4049                    (not error))
4050          (when (setq header (mail-fetch-field (pop headers)))
4051            (setq groups (message-tokenize-header header ","))
4052            (while (setq group (pop groups))
4053              (when (member group groups)
4054                (setq error group
4055                      groups nil)))))
4056        (if (not error)
4057            t
4058          (y-or-n-p
4059           (format "Group %s is repeated in headers.  Really post? " error)))))
4060    ;; Check the From header.
4061    (message-check 'from
4062      (let* ((case-fold-search t)
4063             (from (message-fetch-field "from"))
4064             ad)
4065        (cond
4066         ((not from)
4067          (message "There is no From line.  Posting is denied.")
4068          nil)
4069         ((or (not (string-match
4070                    "@[^\\.]*\\."
4071                    (setq ad (nth 1 (mail-extract-address-components
4072                                     from))))) ;larsi@ifi
4073              (string-match "\\.\\." ad) ;larsi@ifi..uio
4074              (string-match "@\\." ad)   ;larsi@.ifi.uio
4075              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4076              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4077              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4078          (message
4079           "Denied posting -- the From looks strange: \"%s\"." from)
4080          nil)
4081         ((let ((addresses (rfc822-addresses from)))
4082            (while (and addresses
4083                        (not (eq (string-to-char (car addresses)) ?\()))
4084              (setq addresses (cdr addresses)))
4085            addresses)
4086          (message
4087           "Denied posting -- bad From address: \"%s\"." from)
4088          nil)
4089         (t t))))
4090    ;; Check the Reply-To header.
4091    (message-check 'reply-to
4092      (let* ((case-fold-search t)
4093             (reply-to (message-fetch-field "reply-to"))
4094             ad)
4095        (cond
4096         ((not reply-to)
4097          t)
4098         ((string-match "," reply-to)
4099          (y-or-n-p
4100           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4101                   reply-to)))
4102         ((or (not (string-match
4103                    "@[^\\.]*\\."
4104                    (setq ad (nth 1 (mail-extract-address-components
4105                                     reply-to))))) ;larsi@ifi
4106              (string-match "\\.\\." ad) ;larsi@ifi..uio
4107              (string-match "@\\." ad)   ;larsi@.ifi.uio
4108              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4109              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4110              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4111          (y-or-n-p
4112           (format
4113            "The Reply-To looks strange: \"%s\". Really post? "
4114            reply-to)))
4115         (t t))))))
4116
4117 (defun message-check-news-body-syntax ()
4118   (and
4119    ;; Check for long lines.
4120    (message-check 'long-lines
4121      (goto-char (point-min))
4122      (re-search-forward
4123       (concat "^" (regexp-quote mail-header-separator) "$"))
4124      (forward-line 1)
4125      (while (and
4126              (or (looking-at
4127                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
4128                  (let ((p (point)))
4129                    (end-of-line)
4130                    (< (- (point) p) 80)))
4131              (zerop (forward-line 1))))
4132      (or (bolp)
4133          (eobp)
4134          (y-or-n-p
4135           "You have lines longer than 79 characters.  Really post? ")))
4136    ;; Check whether the article is empty.
4137    (message-check 'empty
4138      (goto-char (point-min))
4139      (re-search-forward
4140       (concat "^" (regexp-quote mail-header-separator) "$"))
4141      (forward-line 1)
4142      (let ((b (point)))
4143        (goto-char (point-max))
4144        (re-search-backward message-signature-separator nil t)
4145        (beginning-of-line)
4146        (or (re-search-backward "[^ \n\t]" b t)
4147            (if (message-gnksa-enable-p 'empty-article)
4148                (y-or-n-p "Empty article.  Really post? ")
4149              (message "Denied posting -- Empty article.")
4150              nil))))
4151    ;; Check for control characters.
4152    (message-check 'control-chars
4153      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4154          (y-or-n-p
4155           "The article contains control characters.  Really post? ")
4156        t))
4157    ;; Check excessive size.
4158    (message-check 'size
4159      (if (> (buffer-size) 60000)
4160          (y-or-n-p
4161           (format "The article is %d octets long.  Really post? "
4162                   (buffer-size)))
4163        t))
4164    ;; Check whether any new text has been added.
4165    (message-check 'new-text
4166      (or
4167       (not message-checksum)
4168       (not (eq (message-checksum) message-checksum))
4169       (if (message-gnksa-enable-p 'quoted-text-only)
4170           (y-or-n-p
4171            "It looks like no new text has been added.  Really post? ")
4172         (message "Denied posting -- no new text has been added.")
4173         nil)))
4174    ;; Check the length of the signature.
4175    (message-check 'signature
4176      (goto-char (point-max))
4177      (if (> (count-lines (point) (point-max)) 5)
4178          (y-or-n-p
4179           (format
4180            "Your .sig is %d lines; it should be max 4.  Really post? "
4181            (1- (count-lines (point) (point-max)))))
4182        t))
4183    ;; Ensure that text follows last quoted portion.
4184    (message-check 'quoting-style
4185      (goto-char (point-max))
4186      (let ((no-problem t))
4187        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4188          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4189        (if no-problem
4190            t
4191          (if (message-gnksa-enable-p 'quoted-text-only)
4192              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4193            ;; Ensure that
4194            (goto-char (point-min))
4195            (re-search-forward
4196             (concat "^" (regexp-quote mail-header-separator) "$"))
4197            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4198                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4199              (message "Denied posting -- only quoted text.")
4200              nil)))))))
4201
4202 (defun message-checksum ()
4203   "Return a \"checksum\" for the current buffer."
4204   (let ((sum 0))
4205     (save-excursion
4206       (goto-char (point-min))
4207       (re-search-forward
4208        (concat "^" (regexp-quote mail-header-separator) "$"))
4209       (while (not (eobp))
4210         (when (not (looking-at "[ \t\n]"))
4211           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4212                             (char-after))))
4213         (forward-char 1)))
4214     sum))
4215
4216 (defun message-do-fcc ()
4217   "Process Fcc headers in the current buffer."
4218   (let ((case-fold-search t)
4219         (buf (current-buffer))
4220         list file
4221         (mml-externalize-attachments message-fcc-externalize-attachments))
4222     (save-excursion
4223       (save-restriction
4224         (message-narrow-to-headers)
4225         (setq file (message-fetch-field "fcc" t)))
4226       (when file
4227         (set-buffer (get-buffer-create " *message temp*"))
4228         (erase-buffer)
4229         (insert-buffer-substring buf)
4230         (message-encode-message-body)
4231         (save-restriction
4232           (message-narrow-to-headers)
4233           (while (setq file (message-fetch-field "fcc" t))
4234             (push file list)
4235             (message-remove-header "fcc" nil t))
4236           (let ((mail-parse-charset message-default-charset)
4237                 (rfc2047-header-encoding-alist
4238                  (cons '("Newsgroups" . default)
4239                        rfc2047-header-encoding-alist)))
4240             (mail-encode-encoded-word-buffer)))
4241         (goto-char (point-min))
4242         (when (re-search-forward
4243                (concat "^" (regexp-quote mail-header-separator) "$")
4244                nil t)
4245           (replace-match "" t t ))
4246         ;; Process FCC operations.
4247         (while list
4248           (setq file (pop list))
4249           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4250               ;; Pipe the article to the program in question.
4251               (call-process-region (point-min) (point-max) shell-file-name
4252                                    nil nil nil shell-command-switch
4253                                    (match-string 1 file))
4254             ;; Save the article.
4255             (setq file (expand-file-name file))
4256             (unless (file-exists-p (file-name-directory file))
4257               (make-directory (file-name-directory file) t))
4258             (if (and message-fcc-handler-function
4259                      (not (eq message-fcc-handler-function 'rmail-output)))
4260                 (funcall message-fcc-handler-function file)
4261               (if (and (file-readable-p file) (mail-file-babyl-p file))
4262                   (rmail-output file 1 nil t)
4263                 (let ((mail-use-rfc822 t))
4264                   (rmail-output file 1 t t))))))
4265         (kill-buffer (current-buffer))))))
4266
4267 (defun message-output (filename)
4268   "Append this article to Unix/babyl mail file FILENAME."
4269   (if (and (file-readable-p filename)
4270            (mail-file-babyl-p filename))
4271       (gnus-output-to-rmail filename t)
4272     (gnus-output-to-mail filename t)))
4273
4274 (defun message-cleanup-headers ()
4275   "Do various automatic cleanups of the headers."
4276   ;; Remove empty lines in the header.
4277   (save-restriction
4278     (message-narrow-to-headers)
4279     ;; Remove blank lines.
4280     (while (re-search-forward "^[ \t]*\n" nil t)
4281       (replace-match "" t t))
4282
4283     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4284     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4285     ;; embedded line breaks.
4286     (goto-char (point-min))
4287     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4288       (save-restriction
4289         (narrow-to-region
4290          (point)
4291          (if (re-search-forward "^[^ \t]" nil t)
4292              (match-beginning 0)
4293            (forward-line 1)
4294            (point)))
4295         (goto-char (point-min))
4296         (while (re-search-forward "\n[ \t]+" nil t)
4297           (replace-match " " t t))     ;No line breaks (too confusing)
4298         (goto-char (point-min))
4299         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4300           (replace-match "," t t))
4301         (goto-char (point-min))
4302         ;; Remove trailing commas.
4303         (when (re-search-forward ",+$" nil t)
4304           (replace-match "" t t))))))
4305
4306 (defun message-make-date (&optional now)
4307   "Make a valid data header.
4308 If NOW, use that time instead."
4309   (let* ((now (or now (current-time)))
4310          (zone (nth 8 (decode-time now)))
4311          (sign "+"))
4312     (when (< zone 0)
4313       (setq sign "-")
4314       (setq zone (- zone)))
4315     (concat
4316      ;; The day name of the %a spec is locale-specific.  Pfff.
4317      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4318                                              parse-time-weekdays))))
4319      (format-time-string "%d" now)
4320      ;; The month name of the %b spec is locale-specific.  Pfff.
4321      (format " %s "
4322              (capitalize (car (rassoc (nth 4 (decode-time now))
4323                                       parse-time-months))))
4324      (format-time-string "%Y %H:%M:%S " now)
4325      ;; We do all of this because XEmacs doesn't have the %z spec.
4326      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4327
4328 (defun message-make-message-id ()
4329   "Make a unique Message-ID."
4330   (concat "<" (message-unique-id)
4331           (let ((psubject (save-excursion (message-fetch-field "subject")))
4332                 (psupersedes
4333                  (save-excursion (message-fetch-field "supersedes"))))
4334             (if (or
4335                  (and message-reply-headers
4336                       (mail-header-references message-reply-headers)
4337                       (mail-header-subject message-reply-headers)
4338                       psubject
4339                       (not (string=
4340                             (message-strip-subject-re
4341                              (mail-header-subject message-reply-headers))
4342                             (message-strip-subject-re psubject))))
4343                  (and psupersedes
4344                       (string-match "_-_@" psupersedes)))
4345                 "_-_" ""))
4346           "@" (message-make-fqdn) ">"))
4347
4348 (defvar message-unique-id-char nil)
4349
4350 ;; If you ever change this function, make sure the new version
4351 ;; cannot generate IDs that the old version could.
4352 ;; You might for example insert a "." somewhere (not next to another dot
4353 ;; or string boundary), or modify the "fsf" string.
4354 (defun message-unique-id ()
4355   ;; Don't use microseconds from (current-time), they may be unsupported.
4356   ;; Instead we use this randomly inited counter.
4357   (setq message-unique-id-char
4358         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4359            ;; (current-time) returns 16-bit ints,
4360            ;; and 2^16*25 just fits into 4 digits i base 36.
4361            (* 25 25)))
4362   (let ((tm (current-time)))
4363     (concat
4364      (if (memq system-type '(ms-dos emx vax-vms))
4365          (let ((user (downcase (user-login-name))))
4366            (while (string-match "[^a-z0-9_]" user)
4367              (aset user (match-beginning 0) ?_))
4368            user)
4369        (message-number-base36 (user-uid) -1))
4370      (message-number-base36 (+ (car tm)
4371                                (lsh (% message-unique-id-char 25) 16)) 4)
4372      (message-number-base36 (+ (nth 1 tm)
4373                                (lsh (/ message-unique-id-char 25) 16)) 4)
4374      ;; Append the newsreader name, because while the generated
4375      ;; ID is unique to this newsreader, other newsreaders might
4376      ;; otherwise generate the same ID via another algorithm.
4377      ".fsf")))
4378
4379 (defun message-number-base36 (num len)
4380   (if (if (< len 0)
4381           (<= num 0)
4382         (= len 0))
4383       ""
4384     (concat (message-number-base36 (/ num 36) (1- len))
4385             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4386                                   (% num 36))))))
4387
4388 (defun message-make-organization ()
4389   "Make an Organization header."
4390   (let* ((organization
4391           (when message-user-organization
4392             (if (message-functionp message-user-organization)
4393                 (funcall message-user-organization)
4394               message-user-organization))))
4395     (save-excursion
4396       (message-set-work-buffer)
4397       (cond ((stringp organization)
4398              (insert organization))
4399             ((and (eq t organization)
4400                   message-user-organization-file
4401                   (file-exists-p message-user-organization-file))
4402              (insert-file-contents message-user-organization-file)))
4403       (goto-char (point-min))
4404       (while (re-search-forward "[\t\n]+" nil t)
4405         (replace-match "" t t))
4406       (unless (zerop (buffer-size))
4407         (buffer-string)))))
4408
4409 (defun message-make-lines ()
4410   "Count the number of lines and return numeric string."
4411   (save-excursion
4412     (save-restriction
4413       (widen)
4414       (message-goto-body)
4415       (int-to-string (count-lines (point) (point-max))))))
4416
4417 (defun message-make-references ()
4418   "Return the References header for this message."
4419   (when message-reply-headers
4420     (let ((message-id (mail-header-message-id message-reply-headers))
4421           (references (mail-header-references message-reply-headers))
4422           new-references)
4423       (if (or references message-id)
4424           (concat (or references "") (and references " ")
4425                   (or message-id ""))
4426         nil))))
4427
4428 (defun message-make-in-reply-to ()
4429   "Return the In-Reply-To header for this message."
4430   (when message-reply-headers
4431     (let ((from (mail-header-from message-reply-headers))
4432           (date (mail-header-date message-reply-headers))
4433           (msg-id (mail-header-message-id message-reply-headers)))
4434       (when from
4435         (let ((name (mail-extract-address-components from)))
4436           (concat msg-id (if msg-id " (")
4437                   (or (car name)
4438                       (nth 1 name))
4439                   "'s message of \""
4440                   (if (or (not date) (string= date ""))
4441                       "(unknown date)" date)
4442                   "\"" (if msg-id ")")))))))
4443
4444 (defun message-make-distribution ()
4445   "Make a Distribution header."
4446   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4447     (cond ((message-functionp message-distribution-function)
4448            (funcall message-distribution-function))
4449           (t orig-distribution))))
4450
4451 (defun message-make-expires ()
4452   "Return an Expires header based on `message-expires'."
4453   (let ((current (current-time))
4454         (future (* 1.0 message-expires 60 60 24)))
4455     ;; Add the future to current.
4456     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4457     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4458     (message-make-date current)))
4459
4460 (defun message-make-path ()
4461   "Return uucp path."
4462   (let ((login-name (user-login-name)))
4463     (cond ((null message-user-path)
4464            (concat (system-name) "!" login-name))
4465           ((stringp message-user-path)
4466            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4467            (concat message-user-path "!" login-name))
4468           (t login-name))))
4469
4470 (defun message-make-from ()
4471   "Make a From header."
4472   (let* ((style message-from-style)
4473          (login (message-make-address))
4474          (fullname
4475           (or (and (boundp 'user-full-name)
4476                    user-full-name)
4477               (user-full-name))))
4478     (when (string= fullname "&")
4479       (setq fullname (user-login-name)))
4480     (save-excursion
4481       (message-set-work-buffer)
4482       (cond
4483        ((or (null style)
4484             (equal fullname ""))
4485         (insert login))
4486        ((or (eq style 'angles)
4487             (and (not (eq style 'parens))
4488                  ;; Use angles if no quoting is needed, or if parens would
4489                  ;; need quoting too.
4490                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4491                      (let ((tmp (concat fullname nil)))
4492                        (while (string-match "([^()]*)" tmp)
4493                          (aset tmp (match-beginning 0) ?-)
4494                          (aset tmp (1- (match-end 0)) ?-))
4495                        (string-match "[\\()]" tmp)))))
4496         (insert fullname)
4497         (insert " <" login ">"))
4498        (t                               ; 'parens or default
4499         (insert login " (")
4500         (let ((fullname-start (point)))
4501           (insert fullname)
4502           (goto-char fullname-start)
4503           ;; RFC 822 says \ and nonmatching parentheses
4504           ;; must be escaped in comments.
4505           ;; Escape every instance of ()\ ...
4506           (while (re-search-forward "[()\\]" nil 1)
4507             (replace-match "\\\\\\&" t))
4508           ;; ... then undo escaping of matching parentheses,
4509           ;; including matching nested parentheses.
4510           (goto-char fullname-start)
4511           (while (re-search-forward
4512                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4513                   nil 1)
4514             (replace-match "\\1(\\3)" t)
4515             (goto-char fullname-start)))
4516         (insert ")")))
4517       (buffer-string))))
4518
4519 (defun message-make-sender ()
4520   "Return the \"real\" user address.
4521 This function tries to ignore all user modifications, and
4522 give as trustworthy answer as possible."
4523   (concat (user-login-name) "@" (system-name)))
4524
4525 (defun message-make-address ()
4526   "Make the address of the user."
4527   (or (message-user-mail-address)
4528       (concat (user-login-name) "@" (message-make-domain))))
4529
4530 (defun message-user-mail-address ()
4531   "Return the pertinent part of `user-mail-address'."
4532   (when (and user-mail-address
4533              (string-match "@.*\\." user-mail-address))
4534     (if (string-match " " user-mail-address)
4535         (nth 1 (mail-extract-address-components user-mail-address))
4536       user-mail-address)))
4537
4538 (defun message-sendmail-envelope-from ()
4539   "Return the envelope from."
4540   (cond ((eq message-sendmail-envelope-from 'header)
4541          (nth 1 (mail-extract-address-components
4542                  (message-fetch-field "from"))))
4543         ((stringp message-sendmail-envelope-from)
4544          message-sendmail-envelope-from)
4545         (t
4546          (message-make-address))))
4547
4548 (defun message-make-fqdn ()
4549   "Return user's fully qualified domain name."
4550   (let* ((system-name (system-name))
4551          (user-mail (message-user-mail-address))
4552          (user-domain
4553           (if (and user-mail
4554                    (string-match "@\\(.*\\)\\'" user-mail))
4555               (match-string 1 user-mail))))
4556     (cond
4557      ((and message-user-fqdn
4558            (stringp message-user-fqdn)
4559            (string-match message-valid-fqdn-regexp message-user-fqdn)
4560            (not (string-match message-bogus-system-names message-user-fqdn)))
4561       message-user-fqdn)
4562      ;; `message-user-fqdn' seems to be valid
4563      ((and (string-match message-valid-fqdn-regexp system-name)
4564            (not (string-match message-bogus-system-names system-name)))
4565       ;; `system-name' returned the right result.
4566       system-name)
4567      ;; Try `mail-host-address'.
4568      ((and (boundp 'mail-host-address)
4569            (stringp mail-host-address)
4570            (string-match message-valid-fqdn-regexp mail-host-address)
4571            (not (string-match message-bogus-system-names mail-host-address)))
4572       mail-host-address)
4573      ;; We try `user-mail-address' as a backup.
4574      ((and user-domain
4575            (stringp user-domain)
4576            (string-match message-valid-fqdn-regexp user-domain)
4577            (not (string-match message-bogus-system-names user-domain)))
4578       user-domain)
4579      ;; Default to this bogus thing.
4580      (t
4581       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
4582
4583 (defun message-make-host-name ()
4584   "Return the name of the host."
4585   (let ((fqdn (message-make-fqdn)))
4586     (string-match "^[^.]+\\." fqdn)
4587     (substring fqdn 0 (1- (match-end 0)))))
4588
4589 (defun message-make-domain ()
4590   "Return the domain name."
4591   (or mail-host-address
4592       (message-make-fqdn)))
4593
4594 (defun message-to-list-only ()
4595   "Send a message to the list only.
4596 Remove all addresses but the list address from To and Cc headers."
4597   (interactive)
4598   (let ((listaddr (message-make-mail-followup-to t)))
4599     (when listaddr
4600       (save-excursion
4601         (message-remove-header "to")
4602         (message-remove-header "cc")
4603         (message-position-on-field "To" "X-Draft-From")
4604         (insert listaddr)))))
4605
4606 (defun message-make-mail-followup-to (&optional only-show-subscribed)
4607   "Return the Mail-Followup-To header.
4608 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
4609 subscribed address (and not the additional To and Cc header contents)."
4610   (let* ((case-fold-search t)
4611          (to (message-fetch-field "To"))
4612          (cc (message-fetch-field "cc"))
4613          (msg-recipients (concat to (and to cc ", ") cc))
4614          (recipients
4615           (mapcar 'mail-strip-quoted-names
4616                   (message-tokenize-header msg-recipients)))
4617          (file-regexps
4618           (if message-subscribed-address-file
4619               (let (begin end item re)
4620                 (save-excursion
4621                   (with-temp-buffer
4622                     (insert-file-contents message-subscribed-address-file)
4623                     (while (not (eobp))
4624                       (setq begin (point))
4625                       (forward-line 1)
4626                       (setq end (point))
4627                       (if (bolp) (setq end (1- end)))
4628                       (setq item (regexp-quote (buffer-substring begin end)))
4629                       (if re (setq re (concat re "\\|" item))
4630                         (setq re (concat "\\`\\(" item))))
4631                     (and re (list (concat re "\\)\\'"))))))))
4632          (mft-regexps (apply 'append message-subscribed-regexps
4633                              (mapcar 'regexp-quote
4634                                      message-subscribed-addresses)
4635                              file-regexps
4636                              (mapcar 'funcall
4637                                      message-subscribed-address-functions))))
4638     (save-match-data
4639       (let ((subscribed-lists nil)
4640             (list
4641              (loop for recipient in recipients
4642                when (loop for regexp in mft-regexps
4643                       when (string-match regexp recipient) return t)
4644                return recipient)))
4645         (when list
4646           (if only-show-subscribed
4647               list
4648             msg-recipients))))))
4649
4650 (defun message-idna-inside-rhs-p ()
4651   "Return t iff point is inside a RHS (heuristically).
4652 Only works properly if header contains mailbox-list or address-list.
4653 I.e., calling it on a Subject: header is useless."
4654   (save-restriction
4655     (narrow-to-region (save-excursion (or (re-search-backward "^[^ \t]" nil t)
4656                                           (point-min)))
4657                       (save-excursion (or (re-search-forward "^[^ \t]" nil t)
4658                                           (point-max))))
4659     (if (re-search-backward "[\\\n\r\t ]"
4660                             (save-excursion (search-backward "@" nil t)) t)
4661         ;; whitespace between @ and point
4662         nil
4663       (let ((dquote 1) (paren 1))
4664         (while (save-excursion (re-search-backward "[^\\]\"" nil t dquote))
4665           (incf dquote))
4666         (while (save-excursion (re-search-backward "[^\\]\(" nil t paren))
4667           (incf paren))
4668         (and (= (% dquote 2) 1) (= (% paren 2) 1))))))
4669
4670 (autoload 'idna-to-ascii "idna")
4671
4672 (defun message-idna-to-ascii-rhs-1 (header)
4673   "Interactively potentially IDNA encode domain names in HEADER."
4674   (let (rhs ace start startpos endpos ovl)
4675     (goto-char (point-min))
4676     (while (re-search-forward (concat "^" header) nil t)
4677       (while (re-search-forward "@\\([^ \t\r\n>]+\\)"
4678                                 (or (save-excursion
4679                                       (re-search-forward "^[^ \t]" nil t))
4680                                     (point-max))
4681                                 t)
4682         (setq rhs (match-string-no-properties 1)
4683               startpos (match-beginning 1)
4684               endpos (match-end 1))
4685         (when (save-match-data
4686                 (and (message-idna-inside-rhs-p)
4687                      (setq ace (idna-to-ascii rhs))
4688                      (not (string= rhs ace))
4689                      (if (eq message-use-idna 'ask)
4690                          (unwind-protect
4691                              (progn
4692                                (setq ovl (message-make-overlay startpos
4693                                                                endpos))
4694                                (message-overlay-put ovl 'face 'highlight)
4695                                (y-or-n-p
4696                                 (format "Replace with `%s'? " ace)))
4697                            (message "")
4698                            (message-delete-overlay ovl))
4699                        message-use-idna)))
4700           (replace-match (concat "@" ace)))))))
4701
4702 (defun message-idna-to-ascii-rhs ()
4703   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
4704 See `message-idna-encode'."
4705   (interactive)
4706   (when message-use-idna
4707     (save-excursion
4708       (save-restriction
4709         (message-narrow-to-head)
4710         (message-idna-to-ascii-rhs-1 "From")
4711         (message-idna-to-ascii-rhs-1 "To")
4712         (message-idna-to-ascii-rhs-1 "Cc")))))
4713
4714 (defun message-generate-headers (headers)
4715   "Prepare article HEADERS.
4716 Headers already prepared in the buffer are not modified."
4717   (setq headers (append headers message-required-headers))
4718   (save-restriction
4719     (message-narrow-to-headers)
4720     (let* ((Date (message-make-date))
4721            (Message-ID (message-make-message-id))
4722            (Organization (message-make-organization))
4723            (From (message-make-from))
4724            (Path (message-make-path))
4725            (Subject nil)
4726            (Newsgroups nil)
4727            (In-Reply-To (message-make-in-reply-to))
4728            (References (message-make-references))
4729            (To nil)
4730            (Distribution (message-make-distribution))
4731            (Lines (message-make-lines))
4732            (User-Agent message-newsreader)
4733            (Expires (message-make-expires))
4734            (case-fold-search t)
4735            (optionalp nil)
4736            header value elem)
4737       ;; First we remove any old generated headers.
4738       (let ((headers message-deletable-headers))
4739         (unless (buffer-modified-p)
4740           (setq headers (delq 'Message-ID (copy-sequence headers))))
4741         (while headers
4742           (goto-char (point-min))
4743           (and (re-search-forward
4744                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4745                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4746                (message-delete-line))
4747           (pop headers)))
4748       ;; Go through all the required headers and see if they are in the
4749       ;; articles already.  If they are not, or are empty, they are
4750       ;; inserted automatically - except for Subject, Newsgroups and
4751       ;; Distribution.
4752       (while headers
4753         (goto-char (point-min))
4754         (setq elem (pop headers))
4755         (if (consp elem)
4756             (if (eq (car elem) 'optional)
4757                 (setq header (cdr elem)
4758                       optionalp t)
4759               (setq header (car elem)))
4760           (setq header elem))
4761         (when (or (not (re-search-forward
4762                         (concat "^"
4763                                 (regexp-quote
4764                                  (downcase
4765                                   (if (stringp header)
4766                                       header
4767                                     (symbol-name header))))
4768                                 ":")
4769                         nil t))
4770                   (progn
4771                     ;; The header was found.  We insert a space after the
4772                     ;; colon, if there is none.
4773                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
4774                     ;; Find out whether the header is empty.
4775                     (looking-at "[ \t]*\n[^ \t]")))
4776           ;; So we find out what value we should insert.
4777           (setq value
4778                 (cond
4779                  ((and (consp elem)
4780                        (eq (car elem) 'optional))
4781                   ;; This is an optional header.  If the cdr of this
4782                   ;; is something that is nil, then we do not insert
4783                   ;; this header.
4784                   (setq header (cdr elem))
4785                   (or (and (message-functionp (cdr elem))
4786                            (funcall (cdr elem)))
4787                       (and (boundp (cdr elem))
4788                            (symbol-value (cdr elem)))))
4789                  ((consp elem)
4790                   ;; The element is a cons.  Either the cdr is a
4791                   ;; string to be inserted verbatim, or it is a
4792                   ;; function, and we insert the value returned from
4793                   ;; this function.
4794                   (or (and (stringp (cdr elem))
4795                            (cdr elem))
4796                       (and (message-functionp (cdr elem))
4797                            (funcall (cdr elem)))))
4798                  ((and (boundp header)
4799                        (symbol-value header))
4800                   ;; The element is a symbol.  We insert the value
4801                   ;; of this symbol, if any.
4802                   (symbol-value header))
4803                  ((not (message-check-element header))
4804                   ;; We couldn't generate a value for this header,
4805                   ;; so we just ask the user.
4806                   (read-from-minibuffer
4807                    (format "Empty header for %s; enter value: " header)))))
4808           ;; Finally insert the header.
4809           (when (and value
4810                      (not (equal value "")))
4811             (save-excursion
4812               (if (bolp)
4813                   (progn
4814                     ;; This header didn't exist, so we insert it.
4815                     (goto-char (point-max))
4816                     (let ((formatter
4817                            (cdr (assq header message-header-format-alist))))
4818                       (if formatter
4819                           (funcall formatter header value)
4820                         (insert (if (stringp header)
4821                                     header (symbol-name header))
4822                                 ": " value))
4823                       ;; We check whether the value was ended by a
4824                       ;; newline.  If now, we insert one.
4825                       (unless (bolp)
4826                         (insert "\n"))
4827                       (forward-line -1)))
4828                 ;; The value of this header was empty, so we clear
4829                 ;; totally and insert the new value.
4830                 (delete-region (point) (gnus-point-at-eol))
4831                 ;; If the header is optional, and the header was
4832                 ;; empty, we con't insert it anyway.
4833                 (unless optionalp
4834                   (insert value)))
4835               ;; Add the deletable property to the headers that require it.
4836               (and (memq header message-deletable-headers)
4837                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4838                    (add-text-properties
4839                     (point) (match-end 0)
4840                     '(message-deletable t face italic) (current-buffer)))))))
4841       ;; Insert new Sender if the From is strange.
4842       (let ((from (message-fetch-field "from"))
4843             (sender (message-fetch-field "sender"))
4844             (secure-sender (message-make-sender)))
4845         (when (and from
4846                    (not (message-check-element 'sender))
4847                    (not (string=
4848                          (downcase
4849                           (cadr (mail-extract-address-components from)))
4850                          (downcase secure-sender)))
4851                    (or (null sender)
4852                        (not
4853                         (string=
4854                          (downcase
4855                           (cadr (mail-extract-address-components sender)))
4856                          (downcase secure-sender)))))
4857           (goto-char (point-min))
4858           ;; Rename any old Sender headers to Original-Sender.
4859           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4860             (beginning-of-line)
4861             (insert "Original-")
4862             (beginning-of-line))
4863           (when (or (message-news-p)
4864                     (string-match "@.+\\.." secure-sender))
4865             (insert "Sender: " secure-sender "\n"))))
4866       ;; Check for IDNA
4867       (message-idna-to-ascii-rhs))))
4868
4869 (defun message-insert-courtesy-copy ()
4870   "Insert a courtesy message in mail copies of combined messages."
4871   (let (newsgroups)
4872     (save-excursion
4873       (save-restriction
4874         (message-narrow-to-headers)
4875         (when (setq newsgroups (message-fetch-field "newsgroups"))
4876           (goto-char (point-max))
4877           (insert "Posted-To: " newsgroups "\n")))
4878       (forward-line 1)
4879       (when message-courtesy-message
4880         (cond
4881          ((string-match "%s" message-courtesy-message)
4882           (insert (format message-courtesy-message newsgroups)))
4883          (t
4884           (insert message-courtesy-message)))))))
4885
4886 ;;;
4887 ;;; Setting up a message buffer
4888 ;;;
4889
4890 (defun message-fill-address (header value)
4891   (save-restriction
4892     (narrow-to-region (point) (point))
4893     (insert (capitalize (symbol-name header))
4894             ": "
4895             (if (consp value) (car value) value)
4896             "\n")
4897     (narrow-to-region (point-min) (1- (point-max)))
4898     (let (quoted last)
4899       (goto-char (point-min))
4900       (while (not (eobp))
4901         (skip-chars-forward "^,\"" (point-max))
4902         (if (or (eq (char-after) ?,)
4903                 (eobp))
4904             (when (not quoted)
4905               (if (and (> (current-column) 78)
4906                        last)
4907                   (progn
4908                     (save-excursion
4909                       (goto-char last)
4910                       (insert "\n\t"))
4911                     (setq last (1+ (point))))
4912                 (setq last (1+ (point)))))
4913           (setq quoted (not quoted)))
4914         (unless (eobp)
4915           (forward-char 1))))
4916     (goto-char (point-max))
4917     (widen)
4918     (forward-line 1)))
4919
4920 (defun message-split-line ()
4921   "Split current line, moving portion beyond point vertically down.
4922 If the current line has `message-yank-prefix', insert it on the new line."
4923   (interactive "*")
4924   (condition-case nil
4925       (split-line message-yank-prefix) ;; Emacs 21.3.50+ supports arg.
4926     (error
4927      (split-line))))
4928      
4929
4930 (defun message-fill-header (header value)
4931   (let ((begin (point))
4932         (fill-column 78)
4933         (fill-prefix "\t"))
4934     (insert (capitalize (symbol-name header))
4935             ": "
4936             (if (consp value) (car value) value)
4937             "\n")
4938     (save-restriction
4939       (narrow-to-region begin (point))
4940       (fill-region-as-paragraph begin (point))
4941       ;; Tapdance around looong Message-IDs.
4942       (forward-line -1)
4943       (when (looking-at "[ \t]*$")
4944         (message-delete-line))
4945       (goto-char begin)
4946       (re-search-forward ":" nil t)
4947       (when (looking-at "\n[ \t]+")
4948         (replace-match " " t t))
4949       (goto-char (point-max)))))
4950
4951 (defun message-shorten-1 (list cut surplus)
4952   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4953   (setcdr (nthcdr (- cut 2) list)
4954           (nthcdr (+ (- cut 2) surplus 1) list)))
4955
4956 (defun message-shorten-references (header references)
4957   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4958 If folding is disallowed, also check that the REFERENCES are less
4959 than 988 characters long, and if they are not, trim them until they are."
4960   (let ((maxcount 21)
4961         (count 0)
4962         (cut 2)
4963         refs)
4964     (with-temp-buffer
4965       (insert references)
4966       (goto-char (point-min))
4967       ;; Cons a list of valid references.
4968       (while (re-search-forward "<[^>]+>" nil t)
4969         (push (match-string 0) refs))
4970       (setq refs (nreverse refs)
4971             count (length refs)))
4972
4973     ;; If the list has more than MAXCOUNT elements, trim it by
4974     ;; removing the CUTth element and the required number of
4975     ;; elements that follow.
4976     (when (> count maxcount)
4977       (let ((surplus (- count maxcount)))
4978         (message-shorten-1 refs cut surplus)
4979         (decf count surplus)))
4980
4981     ;; If folding is disallowed, make sure the total length (including
4982     ;; the spaces between) will be less than MAXSIZE characters.
4983     ;;
4984     ;; Only disallow folding for News messages. At this point the headers
4985     ;; have not been generated, thus we use message-this-is-news directly.
4986     (when (and message-this-is-news message-cater-to-broken-inn)
4987       (let ((maxsize 988)
4988             (totalsize (+ (apply #'+ (mapcar #'length refs))
4989                           (1- count)))
4990             (surplus 0)
4991             (ptr (nthcdr (1- cut) refs)))
4992         ;; Decide how many elements to cut off...
4993         (while (> totalsize maxsize)
4994           (decf totalsize (1+ (length (car ptr))))
4995           (incf surplus)
4996           (setq ptr (cdr ptr)))
4997         ;; ...and do it.
4998         (when (> surplus 0)
4999           (message-shorten-1 refs cut surplus))))
5000
5001     ;; Finally, collect the references back into a string and insert
5002     ;; it into the buffer.
5003     (let ((refstring (mapconcat #'identity refs " ")))
5004       (if (and message-this-is-news message-cater-to-broken-inn)
5005           (insert (capitalize (symbol-name header)) ": "
5006                   refstring "\n")
5007         (message-fill-header header refstring)))))
5008
5009 (defun message-position-point ()
5010   "Move point to where the user probably wants to find it."
5011   (message-narrow-to-headers)
5012   (cond
5013    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5014     (search-backward ":" )
5015     (widen)
5016     (forward-char 1)
5017     (if (eq (char-after) ? )
5018         (forward-char 1)
5019       (insert " ")))
5020    (t
5021     (goto-char (point-max))
5022     (widen)
5023     (forward-line 1)
5024     (unless (looking-at "$")
5025       (forward-line 2)))
5026    (sit-for 0)))
5027
5028 (defcustom message-beginning-of-line t
5029   "Whether C-a goes to beginning of header values."
5030   :group 'message-buffers
5031   :type 'boolean)
5032
5033 (defun message-beginning-of-line (&optional n)
5034   "Move point to beginning of header value or to beginning of line."
5035   (interactive "p")
5036   (let ((zrs 'zmacs-region-stays))
5037     (when (and (interactive-p) (boundp zrs))
5038       (set zrs t)))
5039   (if (and message-beginning-of-line
5040            (message-point-in-header-p))
5041       (let* ((here (point))
5042              (bol (progn (beginning-of-line n) (point)))
5043              (eol (gnus-point-at-eol))
5044              (eoh (re-search-forward ": *" eol t)))
5045         (if (or (not eoh) (equal here eoh))
5046             (goto-char bol)
5047           (goto-char eoh)))
5048     (beginning-of-line n)))
5049
5050 (defun message-buffer-name (type &optional to group)
5051   "Return a new (unique) buffer name based on TYPE and TO."
5052   (cond
5053    ;; Generate a new buffer name The Message Way.
5054    ((eq message-generate-new-buffers 'unique)
5055     (generate-new-buffer-name
5056      (concat "*" type
5057              (if to
5058                  (concat " to "
5059                          (or (car (mail-extract-address-components to))
5060                              to) "")
5061                "")
5062              (if (and group (not (string= group ""))) (concat " on " group) "")
5063              "*")))
5064    ;; Check whether `message-generate-new-buffers' is a function,
5065    ;; and if so, call it.
5066    ((message-functionp message-generate-new-buffers)
5067     (funcall message-generate-new-buffers type to group))
5068    ((eq message-generate-new-buffers 'unsent)
5069     (generate-new-buffer-name
5070      (concat "*unsent " type
5071              (if to
5072                  (concat " to "
5073                          (or (car (mail-extract-address-components to))
5074                              to) "")
5075                "")
5076              (if (and group (not (string= group ""))) (concat " on " group) "")
5077              "*")))
5078    ;; Use standard name.
5079    (t
5080     (format "*%s message*" type))))
5081
5082 (defun message-pop-to-buffer (name)
5083   "Pop to buffer NAME, and warn if it already exists and is modified."
5084   (let ((buffer (get-buffer name)))
5085     (if (and buffer
5086              (buffer-name buffer))
5087         (progn
5088           (set-buffer (pop-to-buffer buffer))
5089           (when (and (buffer-modified-p)
5090                      (not (y-or-n-p
5091                            "Message already being composed; erase? ")))
5092             (error "Message being composed")))
5093       (set-buffer (pop-to-buffer name)))
5094     (erase-buffer)
5095     (message-mode)))
5096
5097 (defun message-do-send-housekeeping ()
5098   "Kill old message buffers."
5099   ;; We might have sent this buffer already.  Delete it from the
5100   ;; list of buffers.
5101   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5102   (while (and message-max-buffers
5103               message-buffer-list
5104               (>= (length message-buffer-list) message-max-buffers))
5105     ;; Kill the oldest buffer -- unless it has been changed.
5106     (let ((buffer (pop message-buffer-list)))
5107       (when (and (buffer-name buffer)
5108                  (not (buffer-modified-p buffer)))
5109         (kill-buffer buffer))))
5110   ;; Rename the buffer.
5111   (if message-send-rename-function
5112       (funcall message-send-rename-function)
5113     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5114     (when (string-match
5115            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5116            (buffer-name))
5117       (let ((name (match-string 2 (buffer-name)))
5118             to group)
5119         (if (not (or (null name)
5120                      (string-equal name "mail")
5121                      (string-equal name "posting")))
5122             (setq name (concat "*sent " name "*"))
5123           (message-narrow-to-headers)
5124           (setq to (message-fetch-field "to"))
5125           (setq group (message-fetch-field "newsgroups"))
5126           (widen)
5127           (setq name
5128                 (cond
5129                  (to (concat "*sent mail to "
5130                              (or (car (mail-extract-address-components to))
5131                                  to) "*"))
5132                  ((and group (not (string= group "")))
5133                   (concat "*sent posting on " group "*"))
5134                  (t "*sent mail*"))))
5135         (unless (string-equal name (buffer-name))
5136           (rename-buffer name t)))))
5137   ;; Push the current buffer onto the list.
5138   (when message-max-buffers
5139     (setq message-buffer-list
5140           (nconc message-buffer-list (list (current-buffer))))))
5141
5142 (defun message-mail-user-agent ()
5143   (let ((mua (cond
5144               ((not message-mail-user-agent) nil)
5145               ((eq message-mail-user-agent t) mail-user-agent)
5146               (t message-mail-user-agent))))
5147     (if (memq mua '(message-user-agent gnus-user-agent))
5148         nil
5149       mua)))
5150
5151 (defun message-setup (headers &optional replybuffer actions switch-function)
5152   (let ((mua (message-mail-user-agent))
5153         subject to field yank-action)
5154     (if (not (and message-this-is-mail mua))
5155         (message-setup-1 headers replybuffer actions)
5156       (if replybuffer
5157           (setq yank-action (list 'insert-buffer replybuffer)))
5158       (setq headers (copy-sequence headers))
5159       (setq field (assq 'Subject headers))
5160       (when field
5161         (setq subject (cdr field))
5162         (setq headers (delq field headers)))
5163       (setq field (assq 'To headers))
5164       (when field
5165         (setq to (cdr field))
5166         (setq headers (delq field headers)))
5167       (let ((mail-user-agent mua))
5168         (compose-mail to subject
5169                       (mapcar (lambda (item)
5170                                 (cons
5171                                  (format "%s" (car item))
5172                                  (cdr item)))
5173                               headers)
5174                       nil switch-function yank-action actions)))))
5175
5176 (defun message-headers-to-generate (headers included-headers excluded-headers)
5177   "Return a list that includes all headers from HEADERS.
5178 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5179 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5180 are not included."
5181   (let ((result nil)
5182         header-name)
5183     (dolist (header headers)
5184       (setq header-name (cond
5185                          ((and (consp header)
5186                                (eq (car header) 'optional))
5187                           ;; On the form (optional . Header)
5188                           (cdr header))
5189                          ((consp header)
5190                           ;; On the form (Header . function)
5191                           (car header))
5192                          (t
5193                           ;; Just a Header.
5194                           header)))
5195       (when (and (not (memq header-name excluded-headers))
5196                  (or (eq included-headers t)
5197                      (memq header-name included-headers)))
5198         (push header result)))
5199     (nreverse result)))
5200
5201 (defun message-setup-1 (headers &optional replybuffer actions)
5202   (dolist (action actions)
5203     (condition-case nil
5204         (add-to-list 'message-send-actions
5205                      `(apply ',(car action) ',(cdr action)))))
5206   (setq message-reply-buffer replybuffer)
5207   (goto-char (point-min))
5208   ;; Insert all the headers.
5209   (mail-header-format
5210    (let ((h headers)
5211          (alist message-header-format-alist))
5212      (while h
5213        (unless (assq (caar h) message-header-format-alist)
5214          (push (list (caar h)) alist))
5215        (pop h))
5216      alist)
5217    headers)
5218   (delete-region (point) (progn (forward-line -1) (point)))
5219   (when message-default-headers
5220     (insert message-default-headers)
5221     (or (bolp) (insert ?\n)))
5222   (put-text-property
5223    (point)
5224    (progn
5225      (insert mail-header-separator "\n")
5226      (1- (point)))
5227    'read-only nil)
5228   (forward-line -1)
5229   (when (message-news-p)
5230     (when message-default-news-headers
5231       (insert message-default-news-headers)
5232       (or (bolp) (insert ?\n)))
5233     (when message-generate-headers-first
5234       (message-generate-headers
5235        (message-headers-to-generate
5236         (append message-required-news-headers
5237                 message-required-headers)
5238         message-generate-headers-first
5239         '(Lines Subject)))))
5240   (when (message-mail-p)
5241     (when message-default-mail-headers
5242       (insert message-default-mail-headers)
5243       (or (bolp) (insert ?\n)))
5244     (when message-generate-headers-first
5245       (message-generate-headers
5246        (message-headers-to-generate
5247         (append message-required-mail-headers
5248                 message-required-headers)
5249         message-generate-headers-first
5250         '(Lines Subject)))))
5251   (run-hooks 'message-signature-setup-hook)
5252   (message-insert-signature)
5253   (save-restriction
5254     (message-narrow-to-headers)
5255     (if message-alternative-emails
5256         (message-use-alternative-email-as-from))
5257     (run-hooks 'message-header-setup-hook))
5258   (set-buffer-modified-p nil)
5259   (setq buffer-undo-list nil)
5260   (run-hooks 'message-setup-hook)
5261   (message-position-point)
5262   (undo-boundary))
5263
5264 (defun message-set-auto-save-file-name ()
5265   "Associate the message buffer with a file in the drafts directory."
5266   (when message-auto-save-directory
5267     (unless (file-directory-p
5268              (directory-file-name message-auto-save-directory))
5269       (make-directory message-auto-save-directory t))
5270     (if (gnus-alive-p)
5271         (setq message-draft-article
5272               (nndraft-request-associate-buffer "drafts"))
5273       (setq buffer-file-name (expand-file-name
5274                               (if (memq system-type
5275                                         '(ms-dos ms-windows windows-nt
5276                                                  cygwin cygwin32 win32 w32
5277                                                  mswindows))
5278                                   "message"
5279                                 "*message*")
5280                               message-auto-save-directory))
5281       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5282     (clear-visited-file-modtime)
5283     (setq buffer-file-coding-system message-draft-coding-system)))
5284
5285 (defun message-disassociate-draft ()
5286   "Disassociate the message buffer from the drafts directory."
5287   (when message-draft-article
5288     (nndraft-request-expire-articles
5289      (list message-draft-article) "drafts" nil t)))
5290
5291 (defun message-insert-headers ()
5292   "Generate the headers for the article."
5293   (interactive)
5294   (save-excursion
5295     (save-restriction
5296       (message-narrow-to-headers)
5297       (when (message-news-p)
5298         (message-generate-headers
5299          (delq 'Lines
5300                (delq 'Subject
5301                      (copy-sequence message-required-news-headers)))))
5302       (when (message-mail-p)
5303         (message-generate-headers
5304          (delq 'Lines
5305                (delq 'Subject
5306                      (copy-sequence message-required-mail-headers))))))))
5307
5308 \f
5309
5310 ;;;
5311 ;;; Commands for interfacing with message
5312 ;;;
5313
5314 ;;;###autoload
5315 (defun message-mail (&optional to subject
5316                                other-headers continue switch-function
5317                                yank-action send-actions)
5318   "Start editing a mail message to be sent.
5319 OTHER-HEADERS is an alist of header/value pairs."
5320   (interactive)
5321   (let ((message-this-is-mail t) replybuffer)
5322     (unless (message-mail-user-agent)
5323       (message-pop-to-buffer (message-buffer-name "mail" to)))
5324     ;; FIXME: message-mail should do something if YANK-ACTION is not
5325     ;; insert-buffer.
5326     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5327          (setq replybuffer (nth 1 yank-action)))
5328     (message-setup
5329      (nconc
5330       `((To . ,(or to "")) (Subject . ,(or subject "")))
5331       (when other-headers other-headers))
5332      replybuffer send-actions)
5333     ;; FIXME: Should return nil if failure.
5334     t))
5335
5336 ;;;###autoload
5337 (defun message-news (&optional newsgroups subject)
5338   "Start editing a news article to be sent."
5339   (interactive)
5340   (let ((message-this-is-news t))
5341     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5342     (message-setup `((Newsgroups . ,(or newsgroups ""))
5343                      (Subject . ,(or subject ""))))))
5344
5345 (defun message-get-reply-headers (wide &optional to-address address-headers)
5346   (let (follow-to mct never-mct to cc author mft recipients)
5347     ;; Find all relevant headers we need.
5348     (setq to (message-fetch-field "to")
5349           cc (message-fetch-field "cc")
5350           mct (message-fetch-field "mail-copies-to")
5351           author (or (message-fetch-field "mail-reply-to")
5352                      (message-fetch-field "reply-to")
5353                      (message-fetch-field "from")
5354                      "")
5355           mft (and message-use-mail-followup-to
5356                    (message-fetch-field "mail-followup-to")))
5357
5358     ;; Handle special values of Mail-Copies-To.
5359     (when mct
5360       (cond ((or (equal (downcase mct) "never")
5361                  (equal (downcase mct) "nobody"))
5362              (setq never-mct t)
5363              (setq mct nil))
5364             ((or (equal (downcase mct) "always")
5365                  (equal (downcase mct) "poster"))
5366              (setq mct author))))
5367
5368     (save-match-data
5369       ;; Build (textual) list of new recipient addresses.
5370       (cond
5371        ((not wide)
5372         (setq recipients (concat ", " author)))
5373        (address-headers
5374         (dolist (header address-headers)
5375           (let ((value (message-fetch-field header)))
5376             (when value
5377               (setq recipients (concat recipients ", " value))))))
5378        ((and mft
5379              (string-match "[^ \t,]" mft)
5380              (or (not (eq message-use-mail-followup-to 'ask))
5381                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5382 You should normally obey the Mail-Followup-To: header.  In this
5383 article, it has the value of
5384
5385 " mft "
5386
5387 which directs your response to " (if (string-match "," mft)
5388                                      "the specified addresses"
5389                                    "that address only") ".
5390
5391 Most commonly, Mail-Followup-To is used by a mailing list poster to
5392 express that responses should be sent to just the list, and not the
5393 poster as well.
5394
5395 If a message is posted to several mailing lists, Mail-Followup-To may
5396 also be used to direct the following discussion to one list only,
5397 because discussions that are spread over several lists tend to be
5398 fragmented and very difficult to follow.
5399
5400 Also, some source/announcement lists are not intended for discussion;
5401 responses here are directed to other addresses.")))
5402         (setq recipients (concat ", " mft)))
5403        (to-address
5404         (setq recipients (concat ", " to-address))
5405         ;; If the author explicitly asked for a copy, we don't deny it to them.
5406         (if mct (setq recipients (concat recipients ", " mct))))
5407        (t
5408         (setq recipients (if never-mct "" (concat ", " author)))
5409         (if to  (setq recipients (concat recipients ", " to)))
5410         (if cc  (setq recipients (concat recipients ", " cc)))
5411         (if mct (setq recipients (concat recipients ", " mct)))))
5412       (if (>= (length recipients) 2)
5413           ;; Strip the leading ", ".
5414           (setq recipients (substring recipients 2)))
5415       ;; Squeeze whitespace.
5416       (while (string-match "[ \t][ \t]+" recipients)
5417         (setq recipients (replace-match " " t t recipients)))
5418       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5419       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5420         (setq recipients (rmail-dont-reply-to recipients)))
5421       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5422       (if (string-equal recipients "")
5423           (setq recipients author))
5424       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5425       (setq recipients
5426             (mapcar
5427              (lambda (addr)
5428                (cons (downcase (mail-strip-quoted-names addr)) addr))
5429              (message-tokenize-header recipients)))
5430       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5431       (let ((s recipients))
5432         (while s
5433           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5434
5435       ;; Remove hierarchical lists that are contained within each other,
5436       ;; if message-hierarchical-addresses is defined.
5437       (when message-hierarchical-addresses
5438         (let ((plain-addrs (mapcar 'car recipients))
5439               subaddrs recip)
5440           (while plain-addrs
5441             (setq subaddrs (assoc (car plain-addrs)
5442                                   message-hierarchical-addresses)
5443                   plain-addrs (cdr plain-addrs))
5444             (when subaddrs
5445               (setq subaddrs (cdr subaddrs))
5446               (while subaddrs
5447                 (setq recip (assoc (car subaddrs) recipients)
5448                       subaddrs (cdr subaddrs))
5449                 (if recip
5450                     (setq recipients (delq recip recipients))))))))
5451
5452       ;; Build the header alist.  Allow the user to be asked whether
5453       ;; or not to reply to all recipients in a wide reply.
5454       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5455       (when (and recipients
5456                  (or (not message-wide-reply-confirm-recipients)
5457                      (y-or-n-p "Reply to all recipients? ")))
5458         (setq recipients (mapconcat
5459                           (lambda (addr) (cdr addr)) recipients ", "))
5460         (if (string-match "^ +" recipients)
5461             (setq recipients (substring recipients (match-end 0))))
5462         (push (cons 'Cc recipients) follow-to)))
5463     follow-to))
5464
5465 ;;;###autoload
5466 (defun message-reply (&optional to-address wide)
5467   "Start editing a reply to the article in the current buffer."
5468   (interactive)
5469   (require 'gnus-sum)                   ; for gnus-list-identifiers
5470   (let ((cur (current-buffer))
5471         from subject date reply-to to cc
5472         references message-id follow-to
5473         (inhibit-point-motion-hooks t)
5474         (message-this-is-mail t)
5475         gnus-warning)
5476     (save-restriction
5477       (message-narrow-to-head-1)
5478       ;; Allow customizations to have their say.
5479       (if (not wide)
5480           ;; This is a regular reply.
5481           (when (message-functionp message-reply-to-function)
5482             (save-excursion
5483               (setq follow-to (funcall message-reply-to-function))))
5484         ;; This is a followup.
5485         (when (message-functionp message-wide-reply-to-function)
5486           (save-excursion
5487             (setq follow-to
5488                   (funcall message-wide-reply-to-function)))))
5489       (setq message-id (message-fetch-field "message-id" t)
5490             references (message-fetch-field "references")
5491             date (message-fetch-field "date")
5492             from (message-fetch-field "from")
5493             subject (or (message-fetch-field "subject") "none"))
5494       (when gnus-list-identifiers
5495         (setq subject (message-strip-list-identifiers subject)))
5496       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5497       (when message-subject-trailing-was-query
5498         (setq subject (message-strip-subject-trailing-was subject)))
5499
5500       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5501                  (string-match "<[^>]+>" gnus-warning))
5502         (setq message-id (match-string 0 gnus-warning)))
5503
5504       (unless follow-to
5505         (setq follow-to (message-get-reply-headers wide to-address))))
5506
5507     (unless (message-mail-user-agent)
5508       (message-pop-to-buffer
5509        (message-buffer-name
5510         (if wide "wide reply" "reply") from
5511         (if wide to-address nil))))
5512
5513     (setq message-reply-headers
5514           (vector 0 subject from date message-id references 0 0 ""))
5515
5516     (message-setup
5517      `((Subject . ,subject)
5518        ,@follow-to)
5519      cur)))
5520
5521 ;;;###autoload
5522 (defun message-wide-reply (&optional to-address)
5523   "Make a \"wide\" reply to the message in the current buffer."
5524   (interactive)
5525   (message-reply to-address t))
5526
5527 ;;;###autoload
5528 (defun message-followup (&optional to-newsgroups)
5529   "Follow up to the message in the current buffer.
5530 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5531   (interactive)
5532   (require 'gnus-sum)                   ; for gnus-list-identifiers
5533   (let ((cur (current-buffer))
5534         from subject date reply-to mrt mct
5535         references message-id follow-to
5536         (inhibit-point-motion-hooks t)
5537         (message-this-is-news t)
5538         followup-to distribution newsgroups gnus-warning posted-to)
5539     (save-restriction
5540       (narrow-to-region
5541        (goto-char (point-min))
5542        (if (search-forward "\n\n" nil t)
5543            (1- (point))
5544          (point-max)))
5545       (when (message-functionp message-followup-to-function)
5546         (setq follow-to
5547               (funcall message-followup-to-function)))
5548       (setq from (message-fetch-field "from")
5549             date (message-fetch-field "date")
5550             subject (or (message-fetch-field "subject") "none")
5551             references (message-fetch-field "references")
5552             message-id (message-fetch-field "message-id" t)
5553             followup-to (message-fetch-field "followup-to")
5554             newsgroups (message-fetch-field "newsgroups")
5555             posted-to (message-fetch-field "posted-to")
5556             reply-to (message-fetch-field "reply-to")
5557             mrt (message-fetch-field "mail-reply-to")
5558             distribution (message-fetch-field "distribution")
5559             mct (message-fetch-field "mail-copies-to"))
5560       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5561                  (string-match "<[^>]+>" gnus-warning))
5562         (setq message-id (match-string 0 gnus-warning)))
5563       ;; Remove bogus distribution.
5564       (when (and (stringp distribution)
5565                  (let ((case-fold-search t))
5566                    (string-match "world" distribution)))
5567         (setq distribution nil))
5568       (if gnus-list-identifiers
5569           (setq subject (message-strip-list-identifiers subject)))
5570       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5571       (when message-subject-trailing-was-query
5572         (setq subject (message-strip-subject-trailing-was subject)))
5573       (widen))
5574
5575     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5576
5577     (setq message-reply-headers
5578           (vector 0 subject from date message-id references 0 0 ""))
5579
5580     (message-setup
5581      `((Subject . ,subject)
5582        ,@(cond
5583           (to-newsgroups
5584            (list (cons 'Newsgroups to-newsgroups)))
5585           (follow-to follow-to)
5586           ((and followup-to message-use-followup-to)
5587            (list
5588             (cond
5589              ((equal (downcase followup-to) "poster")
5590               (if (or (eq message-use-followup-to 'use)
5591                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
5592 You should normally obey the Followup-To: header.
5593
5594 `Followup-To: poster' sends your response via e-mail instead of news.
5595
5596 A typical situation where `Followup-To: poster' is used is when the poster
5597 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5598                   (progn
5599                     (setq message-this-is-news nil)
5600                     (cons 'To (or mrt reply-to from "")))
5601                 (cons 'Newsgroups newsgroups)))
5602              (t
5603               (if (or (equal followup-to newsgroups)
5604                       (not (eq message-use-followup-to 'ask))
5605                       (message-y-or-n-p
5606                        (concat "Obey Followup-To: " followup-to "? ") t "\
5607 You should normally obey the Followup-To: header.
5608
5609         `Followup-To: " followup-to "'
5610 directs your response to " (if (string-match "," followup-to)
5611                                "the specified newsgroups"
5612                              "that newsgroup only") ".
5613
5614 If a message is posted to several newsgroups, Followup-To is often
5615 used to direct the following discussion to one newsgroup only,
5616 because discussions that are spread over several newsgroup tend to
5617 be fragmented and very difficult to follow.
5618
5619 Also, some source/announcement newsgroups are not intended for discussion;
5620 responses here are directed to other newsgroups."))
5621                   (cons 'Newsgroups followup-to)
5622                 (cons 'Newsgroups newsgroups))))))
5623           (posted-to
5624            `((Newsgroups . ,posted-to)))
5625           (t
5626            `((Newsgroups . ,newsgroups))))
5627        ,@(and distribution (list (cons 'Distribution distribution)))
5628        ,@(when (and mct
5629                     (not (or (equal (downcase mct) "never")
5630                              (equal (downcase mct) "nobody"))))
5631            (list (cons 'Cc (if (or (equal (downcase mct) "always")
5632                                    (equal (downcase mct) "poster"))
5633                                (or mrt reply-to from "")
5634                              mct)))))
5635
5636      cur)))
5637
5638
5639 ;;;###autoload
5640 (defun message-cancel-news (&optional arg)
5641   "Cancel an article you posted.
5642 If ARG, allow editing of the cancellation message."
5643   (interactive "P")
5644   (unless (message-news-p)
5645     (error "This is not a news article; canceling is impossible"))
5646   (let (from newsgroups message-id distribution buf sender)
5647     (save-excursion
5648       ;; Get header info from original article.
5649       (save-restriction
5650         (message-narrow-to-head-1)
5651         (setq from (message-fetch-field "from")
5652               sender (message-fetch-field "sender")
5653               newsgroups (message-fetch-field "newsgroups")
5654               message-id (message-fetch-field "message-id" t)
5655               distribution (message-fetch-field "distribution")))
5656       ;; Make sure that this article was written by the user.
5657       (unless (or
5658                ;; Canlock-logic as suggested by Per Abrahamsen
5659                ;; <abraham@dina.kvl.dk>
5660                ;;
5661                ;; IF article has cancel-lock THEN
5662                ;;   IF we can verify it THEN
5663                ;;     issue cancel
5664                ;;   ELSE
5665                ;;     error: cancellock: article is not yours
5666                ;; ELSE
5667                ;;   Use old rules, comparing sender...
5668                (if (message-fetch-field "Cancel-Lock")
5669                    (if (null (canlock-verify))
5670                        t
5671                      (error "Failed to verify Cancel-lock: This article is not yours"))
5672                  nil)
5673                (message-gnksa-enable-p 'cancel-messages)
5674                (and sender
5675                     (string-equal
5676                      (downcase sender)
5677                      (downcase (message-make-sender))))
5678                (string-equal
5679                 (downcase (cadr (mail-extract-address-components from)))
5680                 (downcase (cadr (mail-extract-address-components
5681                                  (message-make-from))))))
5682         (error "This article is not yours"))
5683       (when (yes-or-no-p "Do you really want to cancel this article? ")
5684         ;; Make control message.
5685         (if arg
5686             (message-news)
5687           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5688         (erase-buffer)
5689         (insert "Newsgroups: " newsgroups "\n"
5690                 "From: " from "\n"
5691                 "Subject: cmsg cancel " message-id "\n"
5692                 "Control: cancel " message-id "\n"
5693                 (if distribution
5694                     (concat "Distribution: " distribution "\n")
5695                   "")
5696                 mail-header-separator "\n"
5697                 message-cancel-message)
5698         (run-hooks 'message-cancel-hook)
5699         (unless arg
5700           (message "Canceling your article...")
5701           (if (let ((message-syntax-checks
5702                      'dont-check-for-anything-just-trust-me))
5703                 (funcall message-send-news-function))
5704               (message "Canceling your article...done"))
5705           (kill-buffer buf))))))
5706
5707 ;;;###autoload
5708 (defun message-supersede ()
5709   "Start composing a message to supersede the current message.
5710 This is done simply by taking the old article and adding a Supersedes
5711 header line with the old Message-ID."
5712   (interactive)
5713   (let ((cur (current-buffer))
5714         (sender (message-fetch-field "sender"))
5715         (from (message-fetch-field "from")))
5716     ;; Check whether the user owns the article that is to be superseded.
5717     (unless (or
5718              ;; Canlock-logic as suggested by Per Abrahamsen
5719              ;; <abraham@dina.kvl.dk>
5720              ;;
5721              ;; IF article has cancel-lock THEN
5722              ;;   IF we can verify it THEN
5723              ;;     issue cancel
5724              ;;   ELSE
5725              ;;     error: cancellock: article is not yours
5726              ;; ELSE
5727              ;;   Use old rules, comparing sender...
5728              (if (message-fetch-field "Cancel-Lock")
5729                  (if (null (canlock-verify))
5730                      t
5731                    (error "Failed to verify Cancel-lock: This article is not yours"))
5732                nil)
5733              (message-gnksa-enable-p 'cancel-messages)
5734                 (and sender
5735                      (string-equal
5736                       (downcase sender)
5737                       (downcase (message-make-sender))))
5738                 (string-equal
5739                  (downcase (cadr (mail-extract-address-components from)))
5740                  (downcase (cadr (mail-extract-address-components
5741                                   (message-make-from))))))
5742       (error "This article is not yours"))
5743     ;; Get a normal message buffer.
5744     (message-pop-to-buffer (message-buffer-name "supersede"))
5745     (insert-buffer-substring cur)
5746     (mime-to-mml)
5747     (message-narrow-to-head-1)
5748     ;; Remove unwanted headers.
5749     (when message-ignored-supersedes-headers
5750       (message-remove-header message-ignored-supersedes-headers t))
5751     (goto-char (point-min))
5752     (if (not (re-search-forward "^Message-ID: " nil t))
5753         (error "No Message-ID in this article")
5754       (replace-match "Supersedes: " t t))
5755     (goto-char (point-max))
5756     (insert mail-header-separator)
5757     (widen)
5758     (forward-line 1)))
5759
5760 ;;;###autoload
5761 (defun message-recover ()
5762   "Reread contents of current buffer from its last auto-save file."
5763   (interactive)
5764   (let ((file-name (make-auto-save-file-name)))
5765     (cond ((save-window-excursion
5766              (if (not (eq system-type 'vax-vms))
5767                  (with-output-to-temp-buffer "*Directory*"
5768                    (with-current-buffer standard-output
5769                      (fundamental-mode)) ; for Emacs 20.4+
5770                    (buffer-disable-undo standard-output)
5771                    (let ((default-directory "/"))
5772                      (call-process
5773                       "ls" nil standard-output nil "-l" file-name))))
5774              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5775            (let ((buffer-read-only nil))
5776              (erase-buffer)
5777              (insert-file-contents file-name nil)))
5778           (t (error "message-recover cancelled")))))
5779
5780 ;;; Washing Subject:
5781
5782 (defun message-wash-subject (subject)
5783   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
5784 Previous forwarders, replyers, etc. may add it."
5785   (with-temp-buffer
5786     (insert subject)
5787     (goto-char (point-min))
5788     ;; strip Re/Fwd stuff off the beginning
5789     (while (re-search-forward
5790             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
5791       (replace-match ""))
5792
5793     ;; and gnus-style forwards [foo@bar.com] subject
5794     (goto-char (point-min))
5795     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
5796       (replace-match ""))
5797
5798     ;; and off the end
5799     (goto-char (point-max))
5800     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
5801       (replace-match ""))
5802
5803     ;; and finally, any whitespace that was left-over
5804     (goto-char (point-min))
5805     (while (re-search-forward "^[ \t]+" nil t)
5806       (replace-match ""))
5807     (goto-char (point-max))
5808     (while (re-search-backward "[ \t]+$" nil t)
5809       (replace-match ""))
5810
5811     (buffer-string)))
5812
5813 ;;; Forwarding messages.
5814
5815 (defvar message-forward-decoded-p nil
5816   "Non-nil means the original message is decoded.")
5817
5818 (defun message-forward-subject-author-subject (subject)
5819   "Generate a SUBJECT for a forwarded message.
5820 The form is: [Source] Subject, where if the original message was mail,
5821 Source is the sender, and if the original message was news, Source is
5822 the list of newsgroups is was posted to."
5823   (concat "["
5824           (let ((prefix
5825                  (or (message-fetch-field "newsgroups")
5826                      (message-fetch-field "from")
5827                      "(nowhere)")))
5828             (if message-forward-decoded-p
5829                 prefix
5830               (mail-decode-encoded-word-string prefix)))
5831           "] " subject))
5832
5833 (defun message-forward-subject-fwd (subject)
5834   "Generate a SUBJECT for a forwarded message.
5835 The form is: Fwd: Subject, where Subject is the original subject of
5836 the message."
5837   (concat "Fwd: " subject))
5838
5839 (defun message-make-forward-subject ()
5840   "Return a Subject header suitable for the message in the current buffer."
5841   (save-excursion
5842     (save-restriction
5843       (message-narrow-to-head-1)
5844       (let ((funcs message-make-forward-subject-function)
5845             (subject (message-fetch-field "Subject")))
5846         (setq subject
5847               (if subject
5848                   (if message-forward-decoded-p
5849                       subject
5850                     (mail-decode-encoded-word-string subject))
5851                 ""))
5852         (if message-wash-forwarded-subjects
5853             (setq subject (message-wash-subject subject)))
5854         ;; Make sure funcs is a list.
5855         (and funcs
5856              (not (listp funcs))
5857              (setq funcs (list funcs)))
5858         ;; Apply funcs in order, passing subject generated by previous
5859         ;; func to the next one.
5860         (while funcs
5861           (when (message-functionp (car funcs))
5862             (setq subject (funcall (car funcs) subject)))
5863           (setq funcs (cdr funcs)))
5864         subject))))
5865
5866 (eval-when-compile
5867   (defvar gnus-article-decoded-p))
5868
5869
5870 ;;;###autoload
5871 (defun message-forward (&optional news digest)
5872   "Forward the current message via mail.
5873 Optional NEWS will use news to forward instead of mail.
5874 Optional DIGEST will use digest to forward."
5875   (interactive "P")
5876   (let* ((cur (current-buffer))
5877          (message-forward-decoded-p
5878           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
5879               gnus-article-decoded-p ;; In an article buffer.
5880             message-forward-decoded-p))
5881          (subject (message-make-forward-subject)))
5882     (if news
5883         (message-news nil subject)
5884       (message-mail nil subject))
5885     (message-forward-make-body cur digest)))
5886
5887 ;;;###autoload
5888 (defun message-forward-make-body (forward-buffer &optional digest)
5889   ;; Put point where we want it before inserting the forwarded
5890   ;; message.
5891   (if message-forward-before-signature
5892       (message-goto-body)
5893     (goto-char (point-max)))
5894   (if message-forward-as-mime
5895       (if digest
5896           (insert "\n<#multipart type=digest>\n")
5897         (if message-forward-show-mml
5898             (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
5899           (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
5900     (insert "\n-------------------- Start of forwarded message --------------------\n"))
5901   (let ((b (point)) e)
5902     (if digest
5903         (if message-forward-as-mime
5904             (insert-buffer-substring forward-buffer)
5905           (mml-insert-buffer forward-buffer))
5906       (if (and message-forward-show-mml
5907                (not message-forward-decoded-p))
5908           (insert
5909            (with-temp-buffer
5910              (mm-disable-multibyte-mule4)
5911              (insert
5912               (with-current-buffer forward-buffer
5913                 (mm-with-unibyte-current-buffer-mule4 (buffer-string))))
5914              (mm-enable-multibyte-mule4)
5915              (mime-to-mml)
5916              (goto-char (point-min))
5917              (when (looking-at "From ")
5918                (replace-match "X-From-Line: "))
5919              (buffer-string)))
5920         (save-restriction
5921           (narrow-to-region (point) (point))
5922           (mml-insert-buffer forward-buffer)
5923           (goto-char (point-min))
5924           (when (looking-at "From ")
5925             (replace-match "X-From-Line: "))
5926           (goto-char (point-max)))))
5927     (setq e (point))
5928     (if message-forward-as-mime
5929         (if digest
5930             (insert "<#/multipart>\n")
5931           (if message-forward-show-mml
5932               (insert "<#/mml>\n")
5933             (insert "<#/part>\n")))
5934       (insert "\n-------------------- End of forwarded message --------------------\n"))
5935     (if (and digest message-forward-as-mime)
5936         (save-restriction
5937           (narrow-to-region b e)
5938           (goto-char b)
5939           (narrow-to-region (point)
5940                             (or (search-forward "\n\n" nil t) (point)))
5941           (delete-region (point-min) (point-max)))
5942       (when (and (not current-prefix-arg)
5943                  message-forward-ignored-headers
5944                  ;; don't remove CTE, X-Gnus etc when doing "raw" forward:
5945                  message-forward-show-mml)
5946         (save-restriction
5947           (narrow-to-region b e)
5948           (goto-char b)
5949           (narrow-to-region (point)
5950                             (or (search-forward "\n\n" nil t) (point)))
5951           (message-remove-header message-forward-ignored-headers t)))))
5952   (message-position-point))
5953
5954 ;;;###autoload
5955 (defun message-forward-rmail-make-body (forward-buffer)
5956   (save-window-excursion
5957     (set-buffer forward-buffer)
5958     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
5959     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
5960     (if (rmail-msg-is-pruned)
5961         (rmail-msg-restore-non-pruned-header)))
5962   (message-forward-make-body forward-buffer))
5963
5964 ;;;###autoload
5965 (defun message-insinuate-rmail ()
5966   "Let RMAIL uses message to forward."
5967   (interactive)
5968   (setq rmail-enable-mime-composing t)
5969   (setq rmail-insert-mime-forwarded-message-function
5970         'message-forward-rmail-make-body))
5971
5972 ;;;###autoload
5973 (defun message-resend (address)
5974   "Resend the current article to ADDRESS."
5975   (interactive
5976    (list (message-read-from-minibuffer "Resend message to: ")))
5977   (message "Resending message to %s..." address)
5978   (save-excursion
5979     (let ((cur (current-buffer))
5980           beg)
5981       ;; We first set up a normal mail buffer.
5982       (unless (message-mail-user-agent)
5983         (set-buffer (get-buffer-create " *message resend*"))
5984         (erase-buffer))
5985       (let ((message-this-is-mail t)
5986             message-setup-hook)
5987         (message-setup `((To . ,address))))
5988       ;; Insert our usual headers.
5989       (message-generate-headers '(From Date To))
5990       (message-narrow-to-headers)
5991       ;; Remove X-Draft-From header etc.
5992       (message-remove-header message-ignored-mail-headers t)
5993       ;; Rename them all to "Resent-*".
5994       (goto-char (point-min))
5995       (while (re-search-forward "^[A-Za-z]" nil t)
5996         (forward-char -1)
5997         (insert "Resent-"))
5998       (widen)
5999       (forward-line)
6000       (delete-region (point) (point-max))
6001       (setq beg (point))
6002       ;; Insert the message to be resent.
6003       (insert-buffer-substring cur)
6004       (goto-char (point-min))
6005       (search-forward "\n\n")
6006       (forward-char -1)
6007       (save-restriction
6008         (narrow-to-region beg (point))
6009         (message-remove-header message-ignored-resent-headers t)
6010         (goto-char (point-max)))
6011       (insert mail-header-separator)
6012       ;; Rename all old ("Also-")Resent headers.
6013       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6014         (beginning-of-line)
6015         (insert "Also-"))
6016       ;; Quote any "From " lines at the beginning.
6017       (goto-char beg)
6018       (when (looking-at "From ")
6019         (replace-match "X-From-Line: "))
6020       ;; Send it.
6021       (let ((message-inhibit-body-encoding t)
6022             message-required-mail-headers)
6023         (message-send-mail))
6024       (kill-buffer (current-buffer)))
6025     (message "Resending message to %s...done" address)))
6026
6027 ;;;###autoload
6028 (defun message-bounce ()
6029   "Re-mail the current message.
6030 This only makes sense if the current message is a bounce message that
6031 contains some mail you have written which has been bounced back to
6032 you."
6033   (interactive)
6034   (let ((handles (mm-dissect-buffer t))
6035         boundary)
6036     (message-pop-to-buffer (message-buffer-name "bounce"))
6037     (if (stringp (car handles))
6038         ;; This is a MIME bounce.
6039         (mm-insert-part (car (last handles)))
6040       ;; This is a non-MIME bounce, so we try to remove things
6041       ;; manually.
6042       (mm-insert-part handles)
6043       (undo-boundary)
6044       (goto-char (point-min))
6045       (search-forward "\n\n" nil t)
6046       (if (or (and (re-search-forward message-unsent-separator nil t)
6047                    (forward-line 1))
6048               (re-search-forward "^Return-Path:.*\n" nil t))
6049           ;; We remove everything before the bounced mail.
6050           (delete-region
6051            (point-min)
6052            (if (re-search-forward "^[^ \n\t]+:" nil t)
6053                (match-beginning 0)
6054              (point)))
6055         (when (re-search-backward "^.?From .*\n" nil t)
6056           (delete-region (match-beginning 0) (match-end 0)))))
6057     (mm-enable-multibyte)
6058     (mime-to-mml)
6059     (save-restriction
6060       (message-narrow-to-head-1)
6061       (message-remove-header message-ignored-bounced-headers t)
6062       (goto-char (point-max))
6063       (insert mail-header-separator))
6064     (message-position-point)))
6065
6066 ;;;
6067 ;;; Interactive entry points for new message buffers.
6068 ;;;
6069
6070 ;;;###autoload
6071 (defun message-mail-other-window (&optional to subject)
6072   "Like `message-mail' command, but display mail buffer in another window."
6073   (interactive)
6074   (unless (message-mail-user-agent)
6075     (let ((pop-up-windows t)
6076           (special-display-buffer-names nil)
6077           (special-display-regexps nil)
6078           (same-window-buffer-names nil)
6079           (same-window-regexps nil))
6080       (message-pop-to-buffer (message-buffer-name "mail" to))))
6081   (let ((message-this-is-mail t))
6082     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6083                    nil nil 'switch-to-buffer-other-window)))
6084
6085 ;;;###autoload
6086 (defun message-mail-other-frame (&optional to subject)
6087   "Like `message-mail' command, but display mail buffer in another frame."
6088   (interactive)
6089   (unless (message-mail-user-agent)
6090     (let ((pop-up-frames t)
6091           (special-display-buffer-names nil)
6092           (special-display-regexps nil)
6093           (same-window-buffer-names nil)
6094           (same-window-regexps nil))
6095       (message-pop-to-buffer (message-buffer-name "mail" to))))
6096   (let ((message-this-is-mail t))
6097     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6098                    nil nil 'switch-to-buffer-other-frame)))
6099
6100 ;;;###autoload
6101 (defun message-news-other-window (&optional newsgroups subject)
6102   "Start editing a news article to be sent."
6103   (interactive)
6104   (let ((pop-up-windows t)
6105         (special-display-buffer-names nil)
6106         (special-display-regexps nil)
6107         (same-window-buffer-names nil)
6108         (same-window-regexps nil))
6109     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6110   (let ((message-this-is-news t))
6111     (message-setup `((Newsgroups . ,(or newsgroups ""))
6112                      (Subject . ,(or subject ""))))))
6113
6114 ;;;###autoload
6115 (defun message-news-other-frame (&optional newsgroups subject)
6116   "Start editing a news article to be sent."
6117   (interactive)
6118   (let ((pop-up-frames t)
6119         (special-display-buffer-names nil)
6120         (special-display-regexps nil)
6121         (same-window-buffer-names nil)
6122         (same-window-regexps nil))
6123     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6124   (let ((message-this-is-news t))
6125     (message-setup `((Newsgroups . ,(or newsgroups ""))
6126                      (Subject . ,(or subject ""))))))
6127
6128 ;;; underline.el
6129
6130 ;; This code should be moved to underline.el (from which it is stolen).
6131
6132 ;;;###autoload
6133 (defun bold-region (start end)
6134   "Bold all nonblank characters in the region.
6135 Works by overstriking characters.
6136 Called from program, takes two arguments START and END
6137 which specify the range to operate on."
6138   (interactive "r")
6139   (save-excursion
6140     (let ((end1 (make-marker)))
6141       (move-marker end1 (max start end))
6142       (goto-char (min start end))
6143       (while (< (point) end1)
6144         (or (looking-at "[_\^@- ]")
6145             (insert (char-after) "\b"))
6146         (forward-char 1)))))
6147
6148 ;;;###autoload
6149 (defun unbold-region (start end)
6150   "Remove all boldness (overstruck characters) in the region.
6151 Called from program, takes two arguments START and END
6152 which specify the range to operate on."
6153   (interactive "r")
6154   (save-excursion
6155     (let ((end1 (make-marker)))
6156       (move-marker end1 (max start end))
6157       (goto-char (min start end))
6158       (while (re-search-forward "\b" end1 t)
6159         (if (eq (char-after) (char-after (- (point) 2)))
6160             (delete-char -2))))))
6161
6162 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
6163 (defalias 'message-make-overlay 'make-overlay)
6164 (defalias 'message-delete-overlay 'delete-overlay)
6165 (defalias 'message-overlay-put 'overlay-put)
6166
6167 ;; Support for toolbar
6168 (eval-when-compile
6169   (defvar tool-bar-map)
6170   (defvar tool-bar-mode))
6171
6172 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6173   ;; We need to make tool bar entries in local keymaps with
6174   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6175   (if (fboundp 'tool-bar-local-item-from-menu)
6176       ;; This is for Emacs 21.3
6177       (tool-bar-local-item-from-menu command icon in-map from-map props)
6178     (tool-bar-add-item-from-menu command icon from-map props)))
6179
6180 (defun message-tool-bar-map ()
6181   (or message-tool-bar-map
6182       (setq message-tool-bar-map
6183             (and
6184              (condition-case nil (require 'tool-bar) (error nil))
6185              (fboundp 'tool-bar-add-item-from-menu)
6186              tool-bar-mode
6187              (let ((tool-bar-map (copy-keymap tool-bar-map))
6188                    (load-path (mm-image-load-path)))
6189                ;; Zap some items which aren't so relevant and take
6190                ;; up space.
6191                (dolist (key '(print-buffer kill-buffer save-buffer
6192                                            write-file dired open-file))
6193                  (define-key tool-bar-map (vector key) nil))
6194                (message-tool-bar-local-item-from-menu
6195                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
6196                (message-tool-bar-local-item-from-menu
6197                 'message-kill-buffer "close" tool-bar-map message-mode-map)
6198                (message-tool-bar-local-item-from-menu
6199                     'message-dont-send "cancel" tool-bar-map message-mode-map)
6200                (message-tool-bar-local-item-from-menu
6201                 'mml-attach-file "attach" tool-bar-map mml-mode-map)
6202                (message-tool-bar-local-item-from-menu
6203                 'ispell-message "spell" tool-bar-map message-mode-map)
6204                (message-tool-bar-local-item-from-menu
6205                 'mml-preview "preview"
6206                 tool-bar-map mml-mode-map)
6207                (message-tool-bar-local-item-from-menu
6208                 'message-insert-importance-high "important"
6209                 tool-bar-map message-mode-map)
6210                (message-tool-bar-local-item-from-menu
6211                 'message-insert-importance-low "unimportant"
6212                 tool-bar-map message-mode-map)
6213                (message-tool-bar-local-item-from-menu
6214                 'message-insert-disposition-notification-to "receipt"
6215                 tool-bar-map message-mode-map)
6216                tool-bar-map)))))
6217
6218 ;;; Group name completion.
6219
6220 (defcustom message-newgroups-header-regexp
6221   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6222   "Regexp that match headers that lists groups."
6223   :group 'message
6224   :type 'regexp)
6225
6226 (defcustom message-completion-alist
6227   (list (cons message-newgroups-header-regexp 'message-expand-group)
6228         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6229         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6230           . message-expand-name)
6231         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6232           . message-expand-name))
6233   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6234   :group 'message
6235   :type '(alist :key-type regexp :value-type function))
6236
6237 (defcustom message-tab-body-function nil
6238   "*Function to execute when `message-tab' (TAB) is executed in the body.
6239 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6240   :group 'message
6241   :type 'function)
6242
6243 (defun message-tab ()
6244   "Complete names according to `message-completion-alist'.
6245 Execute function specified by `message-tab-body-function' when not in
6246 those headers."
6247   (interactive)
6248   (let ((alist message-completion-alist))
6249     (while (and alist
6250                 (let ((mail-abbrev-mode-regexp (caar alist)))
6251                   (not (mail-abbrev-in-expansion-header-p))))
6252       (setq alist (cdr alist)))
6253     (funcall (or (cdar alist) message-tab-body-function
6254                  (lookup-key text-mode-map "\t")
6255                  (lookup-key global-map "\t")
6256                  'indent-relative))))
6257
6258 (defun message-expand-group ()
6259   "Expand the group name under point."
6260   (let* ((b (save-excursion
6261               (save-restriction
6262                 (narrow-to-region
6263                  (save-excursion
6264                    (beginning-of-line)
6265                    (skip-chars-forward "^:")
6266                    (1+ (point)))
6267                  (point))
6268                 (skip-chars-backward "^, \t\n") (point))))
6269          (completion-ignore-case t)
6270          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6271                                             (point))))
6272          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6273          (completions (all-completions string hashtb))
6274          comp)
6275     (delete-region b (point))
6276     (cond
6277      ((= (length completions) 1)
6278       (if (string= (car completions) string)
6279           (progn
6280             (insert string)
6281             (message "Only matching group"))
6282         (insert (car completions))))
6283      ((and (setq comp (try-completion string hashtb))
6284            (not (string= comp string)))
6285       (insert comp))
6286      (t
6287       (insert string)
6288       (if (not comp)
6289           (message "No matching groups")
6290         (save-selected-window
6291           (pop-to-buffer "*Completions*")
6292           (buffer-disable-undo)
6293           (let ((buffer-read-only nil))
6294             (erase-buffer)
6295             (let ((standard-output (current-buffer)))
6296               (display-completion-list (sort completions 'string<)))
6297             (goto-char (point-min))
6298             (delete-region (point) (progn (forward-line 3) (point))))))))))
6299
6300 (defun message-expand-name ()
6301   (if (fboundp 'bbdb-complete-name)
6302       (bbdb-complete-name)
6303     (expand-abbrev)))
6304
6305 ;;; Help stuff.
6306
6307 (defun message-talkative-question (ask question show &rest text)
6308   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6309 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6310 The following arguments may contain lists of values."
6311   (if (and show
6312            (setq text (message-flatten-list text)))
6313       (save-window-excursion
6314         (save-excursion
6315           (with-output-to-temp-buffer " *MESSAGE information message*"
6316             (set-buffer " *MESSAGE information message*")
6317             (fundamental-mode)          ; for Emacs 20.4+
6318             (mapcar 'princ text)
6319             (goto-char (point-min))))
6320         (funcall ask question))
6321     (funcall ask question)))
6322
6323 (defun message-flatten-list (list)
6324   "Return a new, flat list that contains all elements of LIST.
6325
6326 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6327 => (1 2 3 4 5 6 7)"
6328   (cond ((consp list)
6329          (apply 'append (mapcar 'message-flatten-list list)))
6330         (list
6331          (list list))))
6332
6333 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6334   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6335 Then clone the local variables and values from the old buffer to the
6336 new one, cloning only the locals having a substring matching the
6337 regexp varstr."
6338   (let ((oldbuf (current-buffer)))
6339     (save-excursion
6340       (set-buffer (generate-new-buffer name))
6341       (message-clone-locals oldbuf varstr)
6342       (current-buffer))))
6343
6344 (defun message-clone-locals (buffer &optional varstr)
6345   "Clone the local variables from BUFFER to the current buffer."
6346   (let ((locals (save-excursion
6347                   (set-buffer buffer)
6348                   (buffer-local-variables)))
6349         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
6350     (mapcar
6351      (lambda (local)
6352        (when (and (consp local)
6353                   (car local)
6354                   (string-match regexp (symbol-name (car local)))
6355                   (or (null varstr)
6356                       (string-match varstr (symbol-name (car local)))))
6357          (ignore-errors
6358            (set (make-local-variable (car local))
6359                 (cdr local)))))
6360      locals)))
6361
6362 ;;; Miscellaneous functions
6363
6364 (defsubst message-replace-chars-in-string (string from to)
6365   (mm-subst-char-in-string from to string))
6366
6367 ;;;
6368 ;;; MIME functions
6369 ;;;
6370
6371 (defvar message-inhibit-body-encoding nil)
6372
6373 (defun message-encode-message-body ()
6374   (unless message-inhibit-body-encoding
6375     (let ((mail-parse-charset (or mail-parse-charset
6376                                   message-default-charset))
6377           (case-fold-search t)
6378           lines content-type-p)
6379       (message-goto-body)
6380       (save-restriction
6381         (narrow-to-region (point) (point-max))
6382         (let ((new (mml-generate-mime)))
6383           (when new
6384             (delete-region (point-min) (point-max))
6385             (insert new)
6386             (goto-char (point-min))
6387             (if (eq (aref new 0) ?\n)
6388                 (delete-char 1)
6389               (search-forward "\n\n")
6390               (setq lines (buffer-substring (point-min) (1- (point))))
6391               (delete-region (point-min) (point))))))
6392       (save-restriction
6393         (message-narrow-to-headers-or-head)
6394         (message-remove-header "Mime-Version")
6395         (goto-char (point-max))
6396         (insert "MIME-Version: 1.0\n")
6397         (when lines
6398           (insert lines))
6399         (setq content-type-p
6400               (or mml-boundary
6401                   (re-search-backward "^Content-Type:" nil t))))
6402       (save-restriction
6403         (message-narrow-to-headers-or-head)
6404         (message-remove-first-header "Content-Type")
6405         (message-remove-first-header "Content-Transfer-Encoding"))
6406       ;; We always make sure that the message has a Content-Type
6407       ;; header.  This is because some broken MTAs and MUAs get
6408       ;; awfully confused when confronted with a message with a
6409       ;; MIME-Version header and without a Content-Type header.  For
6410       ;; instance, Solaris' /usr/bin/mail.
6411       (unless content-type-p
6412         (goto-char (point-min))
6413         ;; For unknown reason, MIME-Version doesn't exist.
6414         (when (re-search-forward "^MIME-Version:" nil t)
6415           (forward-line 1)
6416           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6417
6418 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6419   "Read from the minibuffer while providing abbrev expansion."
6420   (if (fboundp 'mail-abbrevs-setup)
6421       (let ((mail-abbrev-mode-regexp "")
6422             (minibuffer-setup-hook 'mail-abbrevs-setup)
6423             (minibuffer-local-map message-minibuffer-local-map))
6424         (read-from-minibuffer prompt initial-contents))
6425     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6426           (minibuffer-local-map message-minibuffer-local-map))
6427       (read-string prompt initial-contents))))
6428
6429 (defun message-use-alternative-email-as-from ()
6430   (require 'mail-utils)
6431   (let* ((fields '("To" "Cc"))
6432          (emails
6433           (split-string
6434            (mail-strip-quoted-names
6435             (mapconcat 'message-fetch-reply-field fields ","))
6436            "[ \f\t\n\r\v,]+"))
6437          email)
6438     (while emails
6439       (if (string-match message-alternative-emails (car emails))
6440           (setq email (car emails)
6441                 emails nil))
6442       (pop emails))
6443     (unless (or (not email) (equal email user-mail-address))
6444       (goto-char (point-max))
6445       (insert "From: " email "\n"))))
6446
6447 (defun message-options-get (symbol)
6448   (cdr (assq symbol message-options)))
6449
6450 (defun message-options-set (symbol value)
6451   (let ((the-cons (assq symbol message-options)))
6452     (if the-cons
6453         (if value
6454             (setcdr the-cons value)
6455           (setq message-options (delq the-cons message-options)))
6456       (and value
6457            (push (cons symbol value) message-options))))
6458   value)
6459
6460 (defun message-options-set-recipient ()
6461   (save-restriction
6462     (message-narrow-to-headers-or-head)
6463     (message-options-set 'message-sender
6464                          (mail-strip-quoted-names
6465                           (message-fetch-field "from")))
6466     (message-options-set 'message-recipients
6467                          (mail-strip-quoted-names
6468                           (let ((to (message-fetch-field "to"))
6469                                 (cc (message-fetch-field "cc"))
6470                                 (bcc (message-fetch-field "bcc")))
6471                             (concat
6472                              (or to "")
6473                              (if (and to cc) ", ")
6474                              (or cc "")
6475                              (if (and (or to cc) bcc) ", ")
6476                              (or bcc "")))))))
6477
6478 (defun message-hide-headers ()
6479   "Hide headers based on the `message-hidden-headers' variable."
6480   (let ((regexps (if (stringp message-hidden-headers)
6481                      (list message-hidden-headers)
6482                    message-hidden-headers))
6483         (inhibit-point-motion-hooks t))
6484     (when regexps
6485       (goto-char (point-min))
6486       (while (not (eobp))
6487         (if (not (message-hide-header-p regexps))
6488             (message-next-header)
6489           (let ((begin (point)))
6490             (message-next-header)
6491             (add-text-properties begin (point)
6492                                  '(intangible t invisible t
6493                                               message-hidden t))))))))
6494
6495 (defun message-hide-header-p (regexps)
6496   (let ((result nil))
6497     (dolist (regexp regexps)
6498       (setq result
6499             (or result
6500                 (cond
6501                  ((stringp regexp)
6502                   (looking-at regexp))
6503                  ((and (consp regexp)
6504                        (eq (car regexp) 'not))
6505                   (not (looking-at (cadr regexp))))
6506                  (t
6507                   (error "Invalid header match: %s" regexp))))))
6508     result))
6509
6510 (when (featurep 'xemacs)
6511   (require 'messagexmas)
6512   (message-xmas-redefine))
6513
6514 (provide 'message)
6515
6516 (run-hooks 'message-load-hook)
6517
6518 ;; Local Variables:
6519 ;; coding: iso-8859-1
6520 ;; End:
6521
6522 ;;; message.el ends here