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