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