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