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