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