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