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