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