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