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