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