Synch to No Gnus 200409231508.
[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     (while functions
3602       (funcall (pop functions)))
3603     (when message-citation-line-function
3604       (unless (bolp)
3605         (insert "\n"))
3606       (funcall message-citation-line-function))))
3607
3608 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
3609 (defun message-cite-original ()
3610   "Cite function in the standard Message manner."
3611   (if (and (boundp 'mail-citation-hook)
3612            mail-citation-hook)
3613       (run-hooks 'mail-citation-hook)
3614     (let ((start (point))
3615           (end (mark t))
3616           (x-no-archive nil)
3617           (functions
3618            (when message-indent-citation-function
3619              (if (listp message-indent-citation-function)
3620                  message-indent-citation-function
3621                (list message-indent-citation-function))))
3622           (message-reply-headers (or message-reply-headers
3623                                      (make-mail-header))))
3624       (save-restriction
3625         (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3626                                       (1- (point))
3627                                     (point-max)))
3628         (mail-header-set-from message-reply-headers
3629                               (or (message-fetch-field "from")
3630                                   "unknown sender"))
3631         (setq x-no-archive (message-fetch-field "x-no-archive")))
3632       (goto-char start)
3633       (while functions
3634         (funcall (pop functions)))
3635       (when message-citation-line-function
3636         (unless (bolp)
3637           (insert "\n"))
3638         (funcall message-citation-line-function))
3639       (when (and x-no-archive
3640                  (not message-cite-articles-with-x-no-archive)
3641                  (string-match "yes" x-no-archive))
3642         (undo-boundary)
3643         (delete-region (point) (mark t))
3644         (insert "> [Quoted text removed due to X-No-Archive]\n")
3645         (forward-line -1)))))
3646
3647 (defun message-insert-citation-line ()
3648   "Insert a simple citation line."
3649   (when message-reply-headers
3650     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3651
3652 (defun message-position-on-field (header &rest afters)
3653   (let ((case-fold-search t))
3654     (save-restriction
3655       (narrow-to-region
3656        (goto-char (point-min))
3657        (progn
3658          (re-search-forward
3659           (concat "^" (regexp-quote mail-header-separator) "$"))
3660          (match-beginning 0)))
3661       (goto-char (point-min))
3662       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3663           (progn
3664             (re-search-forward "^[^ \t]" nil 'move)
3665             (beginning-of-line)
3666             (skip-chars-backward "\n")
3667             t)
3668         (while (and afters
3669                     (not (re-search-forward
3670                           (concat "^" (regexp-quote (car afters)) ":")
3671                           nil t)))
3672           (pop afters))
3673         (when afters
3674           (re-search-forward "^[^ \t]" nil 'move)
3675           (beginning-of-line))
3676         (insert header ": \n")
3677         (forward-char -1)
3678         nil))))
3679
3680 (defun message-remove-signature ()
3681   "Remove the signature from the text between point and mark.
3682 The text will also be indented the normal way."
3683   (save-excursion
3684     (let ((start (point))
3685           mark)
3686       (if (not (re-search-forward message-signature-separator (mark t) t))
3687           ;; No signature here, so we just indent the cited text.
3688           (message-indent-citation)
3689         ;; Find the last non-empty line.
3690         (forward-line -1)
3691         (while (looking-at "[ \t]*$")
3692           (forward-line -1))
3693         (forward-line 1)
3694         (setq mark (set-marker (make-marker) (point)))
3695         (goto-char start)
3696         (message-indent-citation)
3697         ;; Enable undoing the deletion.
3698         (undo-boundary)
3699         (delete-region mark (mark t))
3700         (set-marker mark nil)))))
3701
3702 \f
3703
3704 ;;;
3705 ;;; Sending messages
3706 ;;;
3707
3708 ;; Avoid byte-compile warning.
3709 (defvar message-encoding-buffer nil)
3710 (defvar message-edit-buffer nil)
3711 (defvar message-mime-mode nil)
3712
3713 (defun message-send-and-exit (&optional arg)
3714   "Send message like `message-send', then, if no errors, exit from mail buffer."
3715   (interactive "P")
3716   (let ((buf (current-buffer))
3717         (actions message-exit-actions)
3718         (frame (selected-frame))
3719         (org-frame message-original-frame))
3720     (when (and (message-send arg)
3721                (buffer-name buf))
3722       (if message-kill-buffer-on-exit
3723           (kill-buffer buf)
3724         (bury-buffer buf)
3725         (when (eq buf (current-buffer))
3726           (message-bury buf)))
3727       (message-do-actions actions)
3728       (message-delete-frame frame org-frame)
3729       t)))
3730
3731 (defun message-dont-send ()
3732   "Don't send the message you have been editing.
3733 Instead, just auto-save the buffer and then bury it."
3734   (interactive)
3735   (set-buffer-modified-p t)
3736   (save-buffer)
3737   (let ((actions message-postpone-actions)
3738         (frame (selected-frame))
3739         (org-frame message-original-frame))
3740     (message-bury (current-buffer))
3741     (message-do-actions actions)
3742     (message-delete-frame frame org-frame)))
3743
3744 (defun message-kill-buffer ()
3745   "Kill the current buffer."
3746   (interactive)
3747   (when (or (not (buffer-modified-p))
3748             (eq t message-kill-buffer-query-function)
3749             (funcall message-kill-buffer-query-function
3750                      "The buffer modified; kill anyway? "))
3751     (let ((actions message-kill-actions)
3752           (draft-article message-draft-article)
3753           (auto-save-file-name buffer-auto-save-file-name)
3754           (file-name buffer-file-name)
3755           (modified (buffer-modified-p))
3756           (frame (selected-frame))
3757           (org-frame message-original-frame))
3758       (setq buffer-file-name nil)
3759       (kill-buffer (current-buffer))
3760       (when (and message-kill-buffer-and-remove-file
3761                  (or (and auto-save-file-name
3762                           (file-exists-p auto-save-file-name))
3763                      (and file-name
3764                           (file-exists-p file-name)))
3765                  (yes-or-no-p (format "Remove the backup file%s? "
3766                                       (if modified " too" ""))))
3767         (ignore-errors
3768           (delete-file auto-save-file-name))
3769         (let ((message-draft-article draft-article))
3770           (message-disassociate-draft)))
3771       (message-do-actions actions)
3772       (message-delete-frame frame org-frame)))
3773   (message ""))
3774
3775 (defun message-mimic-kill-buffer ()
3776   "Kill the current buffer with query.  This is an imitation for
3777 `kill-buffer', but it will delete a message frame."
3778   (interactive)
3779   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
3780                                       (buffer-name))))
3781         message-kill-buffer-and-remove-file)
3782     (when (or (not bufname)
3783               (string-equal bufname "")
3784               (string-equal bufname (buffer-name)))
3785       (message-kill-buffer))))
3786
3787 (defun message-delete-frame (frame org-frame)
3788   "Delete frame for editing message."
3789   (when (and (static-if (featurep 'xemacs)
3790                  (device-on-window-system-p)
3791                window-system)
3792              (or (and (eq message-delete-frame-on-exit t)
3793                       (select-frame frame)
3794                       (or (eq frame org-frame)
3795                           (prog1
3796                               (y-or-n-p "Delete this frame?")
3797                             (message ""))))
3798                  (and (eq message-delete-frame-on-exit 'ask)
3799                       (select-frame frame)
3800                       (prog1
3801                           (y-or-n-p "Delete this frame?")
3802                         (message "")))))
3803     (delete-frame frame)))
3804
3805 (defun message-bury (buffer)
3806   "Bury this mail BUFFER."
3807   (let ((newbuf (other-buffer buffer)))
3808     (bury-buffer buffer)
3809     (if (and (fboundp 'frame-parameters)
3810              (cdr (assq 'dedicated (frame-parameters)))
3811              (not (null (delq (selected-frame) (visible-frame-list)))))
3812         (delete-frame (selected-frame))
3813       (switch-to-buffer newbuf))))
3814
3815 (defun message-send (&optional arg)
3816   "Send the message in the current buffer.
3817 If `message-interactive' is non-nil, wait for success indication or
3818 error messages, and inform user.
3819 Otherwise any failure is reported in a message back to the user from
3820 the mailer.
3821 The usage of ARG is defined by the instance that called Message.
3822 It should typically alter the sending method in some way or other."
3823   (interactive "P")
3824   ;; Disabled test.
3825   (when (or (buffer-modified-p)
3826             (message-check-element 'unchanged)
3827             (y-or-n-p "No changes in the buffer; really send? "))
3828     ;; Make it possible to undo the coming changes.
3829     (undo-boundary)
3830     (let ((inhibit-read-only t))
3831       (put-text-property (point-min) (point-max) 'read-only nil))
3832     (run-hooks 'message-send-hook)
3833     (message-fix-before-sending)
3834     (message message-sending-message)
3835     (let ((message-encoding-buffer
3836            (message-generate-new-buffer-clone-locals " message encoding"))
3837           (message-edit-buffer (current-buffer))
3838           (message-mime-mode mime-edit-mode-flag)
3839           (alist message-send-method-alist)
3840           (success t)
3841           elem sent dont-barf-on-no-method
3842           (message-options message-options))
3843       (unwind-protect
3844           (progn
3845             (message-options-set-recipient)
3846             (save-excursion
3847               (set-buffer message-encoding-buffer)
3848               (erase-buffer)
3849               ;; ;; Avoid copying text props (except hard newlines).
3850               ;; T-gnus change: copy all text props from the editing buffer
3851               ;; into the encoding buffer.
3852               (insert-buffer-substring message-edit-buffer)
3853               (funcall message-encode-function)
3854               (while (and success
3855                           (setq elem (pop alist)))
3856                 (when (funcall (cadr elem))
3857                   (when (and
3858                          (or (not (memq (car elem)
3859                                         message-sent-message-via))
3860                              (message-fetch-field "supersedes")
3861                              (if (or (message-gnksa-enable-p 'multiple-copies)
3862                                      (not (eq (car elem) 'news)))
3863                                  (y-or-n-p
3864                                   (format
3865                                    "Already sent message via %s; resend? "
3866                                    (car elem)))
3867                                (error "Denied posting -- multiple copies")))
3868                          (setq success (funcall (caddr elem) arg)))
3869                     (setq sent t)))))
3870             (unless
3871                 (or
3872                  sent
3873                  (not success)
3874                  (let ((fcc (message-fetch-field "Fcc"))
3875                        (gcc (message-fetch-field "Gcc")))
3876                    (when (or fcc gcc)
3877                      (or
3878                       (eq message-allow-no-recipients 'always)
3879                       (and (not (eq message-allow-no-recipients 'never))
3880                            (setq dont-barf-on-no-method
3881                                  (gnus-y-or-n-p
3882                                   (format "No receiver, perform %s anyway? "
3883                                           (cond ((and fcc gcc) "Fcc and Gcc")
3884                                                 (fcc "Fcc")
3885                                                 (t "Gcc"))))))))))
3886               (error "No methods specified to send by"))
3887             (when (or dont-barf-on-no-method
3888                       (and success sent))
3889               (message-do-fcc)
3890               (save-excursion
3891                 (run-hooks 'message-sent-hook))
3892               (message "Sending...done")
3893               ;; Mark the buffer as unmodified and delete auto-save.
3894               (set-buffer-modified-p nil)
3895               (delete-auto-save-file-if-necessary t)
3896               (message-disassociate-draft)
3897               ;; Delete other mail buffers and stuff.
3898               (message-do-send-housekeeping)
3899               (message-do-actions message-send-actions)
3900               ;; Return success.
3901               t))
3902         (kill-buffer message-encoding-buffer)))))
3903
3904 (defun message-send-via-mail (arg)
3905   "Send the current message via mail."
3906   (message-send-mail arg))
3907
3908 (defun message-send-via-news (arg)
3909   "Send the current message via news."
3910   (message-send-news arg))
3911
3912 (defmacro message-check (type &rest forms)
3913   "Eval FORMS if TYPE is to be checked."
3914   `(or (message-check-element ,type)
3915        (save-excursion
3916          ,@forms)))
3917
3918 (put 'message-check 'lisp-indent-function 1)
3919 (put 'message-check 'edebug-form-spec '(form body))
3920
3921 ;; Advise the function `invisible-region'.
3922 (let (current-load-list)
3923   (eval
3924    `(defadvice invisible-region (around add-mime-edit-invisible (start end)
3925                                         activate)
3926       "Advised by T-gnus Message.
3927 Add the text property `mime-edit-invisible' to an invisible text when
3928 the buffer's major mode is `message-mode'.  The added property will be
3929 used to distinguish whether the invisible text is a MIME part or not."
3930       ,(if (featurep 'xemacs)
3931            '(if (eq ?\n (char-after start))
3932                 (setq start (1+ start)))
3933          '(if (eq ?\n (char-after (1- end)))
3934               (setq end (1- end))))
3935       (setq ad-return-value
3936             (if (eq 'message-mode major-mode)
3937                 (add-text-properties start end
3938                                      '(invisible t mime-edit-invisible t))
3939               (put-text-property start end 'invisible t))))))
3940
3941 (defun message-text-with-property (prop &optional start end reverse)
3942   "Return a list of start and end positions where the text has PROP.
3943 START and END bound the search, they default to `point-min' and
3944 `point-max' respectively.  If REVERSE is non-nil, find text which does
3945 not have PROP."
3946   (unless start
3947     (setq start (point-min)))
3948   (unless end
3949     (setq end (point-max)))
3950   (let (next regions)
3951     (if reverse
3952         (while (and start
3953                     (setq start (text-property-any start end prop nil)))
3954           (setq next (next-single-property-change start prop nil end))
3955           (push (cons start (or next end)) regions)
3956           (setq start next))
3957       (while (and start
3958                   (or (get-text-property start prop)
3959                       (and (setq start (next-single-property-change
3960                                         start prop nil end))
3961                            (get-text-property start prop))))
3962         (setq next (text-property-any start end prop nil))
3963         (push (cons start (or next end)) regions)
3964         (setq start next)))
3965     (nreverse regions)))
3966
3967 (defun message-fix-before-sending ()
3968   "Do various things to make the message nice before sending it."
3969   ;; Make sure there's a newline at the end of the message.
3970   (widen)
3971   (goto-char (point-max))
3972   (unless (bolp)
3973     (insert "\n"))
3974   ;; Make the hidden headers visible.
3975   (dolist (from-to (message-text-with-property 'message-hidden))
3976     (add-text-properties (car from-to) (cdr from-to)
3977                          '(invisible nil intangible nil)))
3978   ;; Make invisible text visible except for mime parts which may be
3979   ;; inserted by the MIME-Edit.
3980   ;; It doesn't seem as if this is useful, since the invisible property
3981   ;; is clobbered by an after-change hook anyhow.
3982   (message-check 'invisible-text
3983     ;; FIXME T-gnus: It should also detect invisible overlays.
3984     (let (from
3985           (to (point-min))
3986           mime-from mime-to hidden-start)
3987       (while (setq from (text-property-any to (point-max) 'invisible t))
3988         (setq to (or (text-property-not-all from (point-max) 'invisible t)
3989                      (point-max))
3990               mime-to from)
3991         (while (setq mime-from (text-property-any mime-to to
3992                                                   'mime-edit-invisible t))
3993           (when (> mime-from mime-to)
3994             (setq hidden-start (or hidden-start mime-to))
3995             (add-text-properties mime-to mime-from
3996                                  '(invisible nil face highlight
3997                                              font-lock-face highlight)))
3998           (setq mime-to (or (text-property-not-all mime-from to
3999                                                    'mime-edit-invisible t)
4000                             to)))
4001         (when (< mime-to to)
4002           (setq hidden-start (or hidden-start mime-to))
4003           (add-text-properties mime-to to
4004                                '(invisible nil face highlight
4005                                            font-lock-face highlight))))
4006       (when hidden-start
4007         (goto-char hidden-start)
4008         (set-window-start (selected-window) (point-at-bol))
4009         (unless (yes-or-no-p
4010                  "Invisible text found and made visible; continue sending? ")
4011           (error "Invisible text found and made visible")))))
4012 ;; The following check is needless to T-gnus since T-gnus determines
4013 ;; a MIME charset forcibly (even if it cannot be determined properly,
4014 ;; the value of the `default-mime-charset-for-write' variable is used).
4015 ;;  (message-check 'illegible-text
4016 ;;    (let (found choice)
4017 ;;      (message-goto-body)
4018 ;;      (skip-chars-forward mm-7bit-chars)
4019 ;;      (while (not (eobp))
4020 ;;      (when (let ((char (char-after)))
4021 ;;              (or (< (mm-char-int char) 128)
4022 ;;                  (and (mm-multibyte-p)
4023 ;;                       (memq (char-charset char)
4024 ;;                             '(eight-bit-control eight-bit-graphic
4025 ;;                                                 control-1))
4026 ;;                       (not (get-text-property
4027 ;;                             (point) 'untranslated-utf-8)))))
4028 ;;        (message-overlay-put (message-make-overlay (point) (1+ (point)))
4029 ;;                             'face 'highlight)
4030 ;;        (setq found t))
4031 ;;      (forward-char)
4032 ;;      (skip-chars-forward mm-7bit-chars))
4033 ;;      (when found
4034 ;;      (setq choice
4035 ;;            (gnus-multiple-choice
4036 ;;             "Non-printable characters found.  Continue sending?"
4037 ;;             '((?d "Remove non-printable characters and send")
4038 ;;               (?r "Replace non-printable characters with dots and send")
4039 ;;               (?i "Ignore non-printable characters and send")
4040 ;;               (?e "Continue editing"))))
4041 ;;      (if (eq choice ?e)
4042 ;;          (error "Non-printable characters"))
4043 ;;      (message-goto-body)
4044 ;;      (skip-chars-forward mm-7bit-chars)
4045 ;;      (while (not (eobp))
4046 ;;        (when (let ((char (char-after)))
4047 ;;                (or (< (mm-char-int char) 128)
4048 ;;                    (and (mm-multibyte-p)
4049 ;;                         ;; Fixme: Wrong for Emacs 22 and for things
4050 ;;                         ;; like undecable utf-8.  Should at least
4051 ;;                         ;; use find-coding-systems-region.
4052 ;;                         (memq (char-charset char)
4053 ;;                               '(eight-bit-control eight-bit-graphic
4054 ;;                                                   control-1))
4055 ;;                         (not (get-text-property
4056 ;;                               (point) 'untranslated-utf-8)))))
4057 ;;          (if (eq choice ?i)
4058 ;;              (message-kill-all-overlays)
4059 ;;            (delete-char 1)
4060 ;;            (when (eq choice ?r)
4061 ;;              (insert "."))))
4062 ;;        (forward-char)
4063 ;;        (skip-chars-forward mm-7bit-chars)))))
4064   )
4065
4066 (defun message-add-action (action &rest types)
4067   "Add ACTION to be performed when doing an exit of type TYPES."
4068   (while types
4069     (add-to-list (intern (format "message-%s-actions" (pop types)))
4070                  action)))
4071
4072 (defun message-delete-action (action &rest types)
4073   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
4074   (let (var)
4075     (while types
4076       (set (setq var (intern (format "message-%s-actions" (pop types))))
4077            (delq action (symbol-value var))))))
4078
4079 (defun message-do-actions (actions)
4080   "Perform all actions in ACTIONS."
4081   ;; Now perform actions on successful sending.
4082   (while actions
4083     (ignore-errors
4084       (cond
4085        ;; A simple function.
4086        ((functionp (car actions))
4087         (funcall (car actions)))
4088        ;; Something to be evaled.
4089        (t
4090         (eval (car actions)))))
4091     (pop actions)))
4092
4093 (defsubst message-maybe-split-and-send-mail ()
4094   "Split a message if necessary, and send it via mail.
4095 Returns nil if sending succeeded, returns any string if sending failed.
4096 This sub function is for exclusive use of `message-send-mail'."
4097   (let ((mime-edit-split-ignored-field-regexp
4098          mime-edit-split-ignored-field-regexp)
4099         (case-fold-search t)
4100         failure)
4101     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4102       (setq mime-edit-split-ignored-field-regexp
4103             (concat (substring mime-edit-split-ignored-field-regexp
4104                                0 (match-beginning 0))
4105                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4106                     "_so_don't_rape_it!"
4107                     (substring mime-edit-split-ignored-field-regexp
4108                                (match-end 0)))))
4109     (setq failure
4110           (or
4111            (catch 'message-sending-mail-failure
4112              (mime-edit-maybe-split-and-send
4113               (function
4114                (lambda ()
4115                  (interactive)
4116                  (save-restriction
4117                    (std11-narrow-to-header mail-header-separator)
4118                    (goto-char (point-min))
4119                    (when (re-search-forward "^Message-ID:" nil t)
4120                      (delete-region (match-end 0) (std11-field-end))
4121                      (insert " " (message-make-message-id))))
4122                  (condition-case err
4123                      (funcall (or message-send-mail-real-function
4124                                   message-send-mail-function))
4125                    (error
4126                     (throw 'message-sending-mail-failure err))))))
4127              nil)
4128            (condition-case err
4129                (progn
4130                  (funcall (or message-send-mail-real-function
4131                               message-send-mail-function))
4132                  nil)
4133              (error err))))
4134     (when failure
4135       (if (eq 'error (car failure))
4136           (cadr failure)
4137         (prin1-to-string failure)))))
4138
4139 (defun message-send-mail-partially ()
4140   "Send mail as message/partial."
4141   ;; replace the header delimiter with a blank line
4142   (goto-char (point-min))
4143   (re-search-forward
4144    (concat "^" (regexp-quote mail-header-separator) "\n"))
4145   (replace-match "\n")
4146   (run-hooks 'message-send-mail-hook)
4147   (let ((p (goto-char (point-min)))
4148         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
4149         (curbuf (current-buffer))
4150         (id (message-make-message-id)) (n 1)
4151         plist total  header required-mail-headers)
4152     (while (not (eobp))
4153       (if (< (point-max) (+ p message-send-mail-partially-limit))
4154           (goto-char (point-max))
4155         (goto-char (+ p message-send-mail-partially-limit))
4156         (beginning-of-line)
4157         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
4158       (push p plist)
4159       (setq p (point)))
4160     (setq total (length plist))
4161     (push (point-max) plist)
4162     (setq plist (nreverse plist))
4163     (unwind-protect
4164         (save-excursion
4165           (setq p (pop plist))
4166           (while plist
4167             (set-buffer curbuf)
4168             (copy-to-buffer tembuf p (car plist))
4169             (set-buffer tembuf)
4170             (goto-char (point-min))
4171             (if header
4172                 (progn
4173                   (goto-char (point-min))
4174                   (narrow-to-region (point) (point))
4175                   (insert header))
4176               (message-goto-eoh)
4177               (setq header (buffer-substring (point-min) (point)))
4178               (goto-char (point-min))
4179               (narrow-to-region (point) (point))
4180               (insert header)
4181               (message-remove-header "Mime-Version")
4182               (message-remove-header "Content-Type")
4183               (message-remove-header "Content-Transfer-Encoding")
4184               (message-remove-header "Message-ID")
4185               (message-remove-header "Lines")
4186               (goto-char (point-max))
4187               (insert "Mime-Version: 1.0\n")
4188               (setq header (buffer-string)))
4189             (goto-char (point-max))
4190             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
4191                             id n total))
4192             (forward-char -1)
4193             (let ((mail-header-separator ""))
4194               (when (memq 'Message-ID message-required-mail-headers)
4195                 (insert "Message-ID: " (message-make-message-id) "\n"))
4196               (when (memq 'Lines message-required-mail-headers)
4197                 (insert "Lines: " (message-make-lines) "\n"))
4198               (message-goto-subject)
4199               (end-of-line)
4200               (insert (format " (%d/%d)" n total))
4201               (widen)
4202               (mm-with-unibyte-current-buffer
4203                 (funcall (or message-send-mail-real-function
4204                              message-send-mail-function))))
4205             (setq n (+ n 1))
4206             (setq p (pop plist))
4207             (erase-buffer)))
4208       (kill-buffer tembuf))))
4209
4210 (defun message-send-mail (&optional arg)
4211   (require 'mail-utils)
4212   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
4213          (case-fold-search nil)
4214          (news (message-news-p))
4215          (message-this-is-mail t)
4216          (headers message-required-mail-headers)
4217          failure)
4218     (save-restriction
4219       (message-narrow-to-headers)
4220       ;; Generate the Mail-Followup-To header if the header is not there...
4221       (if (and (message-subscribed-p)
4222                (not (mail-fetch-field "mail-followup-to")))
4223           (setq headers
4224                 (cons
4225                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4226                  message-required-mail-headers))
4227         ;; otherwise, delete the MFT header if the field is empty
4228         (when (equal "" (mail-fetch-field "mail-followup-to"))
4229           (message-remove-header "^Mail-Followup-To:")))
4230       ;; Insert some headers.
4231       (let ((message-deletable-headers
4232              (if news nil message-deletable-headers)))
4233         (message-generate-headers headers))
4234       ;; Let the user do all of the above.
4235       (run-hooks 'message-header-hook))
4236     (if (not (message-check-mail-syntax))
4237         (progn
4238           (message "")
4239           nil)
4240       (unwind-protect
4241           (save-excursion
4242             (set-buffer tembuf)
4243             (erase-buffer)
4244             ;; ;; Avoid copying text props (except hard newlines).
4245             ;; T-gnus change: copy all text props from the editing buffer
4246             ;; into the encoding buffer.
4247             (insert-buffer-substring message-encoding-buffer)
4248             ;; Remove some headers.
4249             (save-restriction
4250               (message-narrow-to-headers)
4251 ;; We Semi-gnus people have no use for it.
4252 ;;            ;; We (re)generate the Lines header.
4253 ;;            (when (memq 'Lines message-required-mail-headers)
4254 ;;              (message-generate-headers '(Lines)))
4255               (message-remove-header message-ignored-mail-headers t))
4256             (goto-char (point-max))
4257             ;; require one newline at the end.
4258             (or (= (preceding-char) ?\n)
4259                 (insert ?\n))
4260             (message-cleanup-headers)
4261             ;; FIXME: we're inserting the courtesy copy after encoding.
4262             ;; This is wrong if the courtesy copy string contains
4263             ;; non-ASCII characters. -- jh
4264             (when
4265                 (save-restriction
4266                   (message-narrow-to-headers)
4267                   (and news
4268                        (or (message-fetch-field "cc")
4269                            (message-fetch-field "bcc")
4270                            (message-fetch-field "to"))
4271                        (let ((content-type (mime-read-Content-Type)))
4272                          (and
4273                           (or
4274                            (not content-type)
4275                            (and
4276                             (eq 'text (cdr (assq 'type content-type)))
4277                             (eq 'plain (cdr (assq 'subtype content-type)))))
4278                           (not
4279                            (string= "base64"
4280                                     (mime-read-Content-Transfer-Encoding)))))))
4281               (message-insert-courtesy-copy))
4282             (setq failure (message-maybe-split-and-send-mail)))
4283         (kill-buffer tembuf))
4284       (set-buffer message-edit-buffer)
4285       (if failure
4286           (progn
4287             (message "Couldn't send message via mail: %s" failure)
4288             nil)
4289         (push 'mail message-sent-message-via)))))
4290
4291 (defun message-send-mail-with-sendmail ()
4292   "Send off the prepared buffer with sendmail."
4293   (let ((errbuf (if message-interactive
4294                     (message-generate-new-buffer-clone-locals
4295                      " sendmail errors")
4296                   0))
4297         resend-to-addresses delimline)
4298     (unwind-protect
4299         (progn
4300           (let ((case-fold-search t))
4301             (save-restriction
4302               (message-narrow-to-headers)
4303               (setq resend-to-addresses (message-fetch-field "resent-to")))
4304             ;; Change header-delimiter to be what sendmail expects.
4305             (goto-char (point-min))
4306             (re-search-forward
4307              (concat "^" (regexp-quote mail-header-separator) "\n"))
4308             (replace-match "\n")
4309             (backward-char 1)
4310             (setq delimline (point-marker))
4311             (run-hooks 'message-send-mail-hook)
4312             ;; Insert an extra newline if we need it to work around
4313             ;; Sun's bug that swallows newlines.
4314             (goto-char (1+ delimline))
4315             (when (eval message-mailer-swallows-blank-line)
4316               (newline))
4317             (when message-interactive
4318               (with-current-buffer errbuf
4319                 (erase-buffer))))
4320           (let* ((default-directory "/")
4321                  (cpr (as-binary-process
4322                        (apply
4323                         'call-process-region
4324                         (append
4325                          (list (point-min) (point-max)
4326                                (if (boundp 'sendmail-program)
4327                                    sendmail-program
4328                                  "/usr/lib/sendmail")
4329                                nil errbuf nil "-oi")
4330                          ;; Always specify who from,
4331                          ;; since some systems have broken sendmails.
4332                          ;; But some systems are more broken with -f, so
4333                          ;; we'll let users override this.
4334                          (if (null message-sendmail-f-is-evil)
4335                              (list "-f" (message-sendmail-envelope-from)))
4336                          ;; These mean "report errors by mail"
4337                          ;; and "deliver in background".
4338                          (if (null message-interactive) '("-oem" "-odb"))
4339                          ;; Get the addresses from the message
4340                          ;; unless this is a resend.
4341                          ;; We must not do that for a resend
4342                          ;; because we would find the original addresses.
4343                          ;; For a resend, include the specific addresses.
4344                          (if resend-to-addresses
4345                              (list resend-to-addresses)
4346                            '("-t")))))))
4347             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
4348               (error "Sending...failed with exit value %d" cpr)))
4349           (when message-interactive
4350             (save-excursion
4351               (set-buffer errbuf)
4352               (goto-char (point-min))
4353               (while (re-search-forward "\n+ *" nil t)
4354                 (replace-match "; "))
4355               (if (not (zerop (buffer-size)))
4356                   (error "Sending...failed to %s"
4357                          (buffer-string))))))
4358       (when (bufferp errbuf)
4359         (kill-buffer errbuf)))))
4360
4361 (defun message-send-mail-with-qmail ()
4362   "Pass the prepared message buffer to qmail-inject.
4363 Refer to the documentation for the variable `message-send-mail-function'
4364 to find out how to use this."
4365   ;; replace the header delimiter with a blank line
4366   (goto-char (point-min))
4367   (re-search-forward
4368    (concat "^" (regexp-quote mail-header-separator) "\n"))
4369   (replace-match "\n")
4370   (backward-char 1)
4371   (run-hooks 'message-send-mail-hook)
4372   ;; send the message
4373   (case
4374       (as-binary-process
4375        (apply
4376         'call-process-region (point-min) (point-max)
4377         message-qmail-inject-program nil nil nil
4378         ;; qmail-inject's default behaviour is to look for addresses on the
4379         ;; command line; if there're none, it scans the headers.
4380         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4381         ;;
4382         ;; in general, ALL of qmail-inject's defaults are perfect for simply
4383         ;; reading a formatted (i. e., at least a To: or Resent-To header)
4384         ;; message from stdin.
4385         ;;
4386         ;; qmail also has the advantage of not having been raped by
4387         ;; various vendors, so we don't have to allow for that, either --
4388         ;; compare this with message-send-mail-with-sendmail and weep
4389         ;; for sendmail's lost innocence.
4390         ;;
4391         ;; all this is way cool coz it lets us keep the arguments entirely
4392         ;; free for -inject-arguments -- a big win for the user and for us
4393         ;; since we don't have to play that double-guessing game and the user
4394         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4395         (if (functionp message-qmail-inject-args)
4396             (funcall message-qmail-inject-args)
4397           message-qmail-inject-args)))
4398     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4399     ;; we have to look at the retval instead
4400     (0 nil)
4401     (100 (error "qmail-inject reported permanent failure"))
4402     (111 (error "qmail-inject reported transient failure"))
4403     ;; should never happen
4404     (t   (error "qmail-inject reported unknown failure"))))
4405
4406 (defun message-send-mail-with-mh ()
4407   "Send the prepared message buffer with mh."
4408   (let ((mh-previous-window-config nil)
4409         (name (mh-new-draft-name)))
4410     (setq buffer-file-name name)
4411     ;; MH wants to generate these headers itself.
4412     (when message-mh-deletable-headers
4413       (let ((headers message-mh-deletable-headers))
4414         (while headers
4415           (goto-char (point-min))
4416           (and (re-search-forward
4417                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4418                (message-delete-line))
4419           (pop headers))))
4420     (run-hooks 'message-send-mail-hook)
4421     ;; Pass it on to mh.
4422     (mh-send-letter)))
4423
4424 (defun message-send-mail-with-smtp ()
4425   "Send off the prepared buffer with SMTP."
4426   (require 'smtp) ; XXX
4427   (let ((case-fold-search t)
4428         recipients)
4429     (save-restriction
4430       (message-narrow-to-headers)
4431       (setq recipients
4432             ;; XXX: Should be replaced by better one.
4433             (smtp-deduce-address-list (current-buffer)
4434                                       (point-min) (point-max)))
4435       ;; Remove BCC lines.
4436       (message-remove-header "bcc"))
4437     ;; replace the header delimiter with a blank line.
4438     (goto-char (point-min))
4439     (re-search-forward
4440      (concat "^" (regexp-quote mail-header-separator) "\n"))
4441     (replace-match "\n")
4442     (backward-char 1)
4443     (run-hooks 'message-send-mail-hook)
4444     (if recipients
4445         (smtp-send-buffer user-mail-address recipients (current-buffer))
4446       (error "Sending failed; no recipients"))))
4447
4448 (defsubst message-maybe-split-and-send-news (method)
4449   "Split a message if necessary, and send it via news.
4450 Returns nil if sending succeeded, returns t if sending failed.
4451 This sub function is for exclusive use of `message-send-news'."
4452   (let ((mime-edit-split-ignored-field-regexp
4453          mime-edit-split-ignored-field-regexp)
4454         (case-fold-search t))
4455     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4456       (setq mime-edit-split-ignored-field-regexp
4457             (concat (substring mime-edit-split-ignored-field-regexp
4458                                0 (match-beginning 0))
4459                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4460                     "_so_don't_rape_it!"
4461                     (substring mime-edit-split-ignored-field-regexp
4462                                (match-end 0)))))
4463     (or
4464      (catch 'message-sending-news-failure
4465        (mime-edit-maybe-split-and-send
4466         (function
4467          (lambda ()
4468            (interactive)
4469            (save-restriction
4470              (std11-narrow-to-header mail-header-separator)
4471              (goto-char (point-min))
4472              (when (re-search-forward "^Message-ID:" nil t)
4473                (delete-region (match-end 0) (std11-field-end))
4474                (insert " " (message-make-message-id))))
4475            (unless (funcall message-send-news-function method)
4476              (throw 'message-sending-news-failure t)))))
4477        nil)
4478      (not (funcall message-send-news-function method)))))
4479
4480 (defun message-smtpmail-send-it ()
4481   "Send the prepared message buffer with `smtpmail-send-it'.
4482 This only differs from `smtpmail-send-it' that this command evaluates
4483 `message-send-mail-hook' just before sending a message.  It is useful
4484 if your ISP requires the POP-before-SMTP authentication.  See the Gnus
4485 manual for details."
4486   (run-hooks 'message-send-mail-hook)
4487   (smtpmail-send-it))
4488
4489 (defun message-canlock-generate ()
4490   "Return a string that is non-trivial to guess.
4491 Do not use this for anything important, it is cryptographically weak."
4492   (require 'sha1)
4493   (let (sha1-maximum-internal-length)
4494     (sha1 (concat (message-unique-id)
4495                   (format "%x%x%x" (random) (random t) (random))
4496                   (prin1-to-string (recent-keys))
4497                   (prin1-to-string (garbage-collect))))))
4498
4499 (defun message-canlock-password ()
4500   "The password used by message for cancel locks.
4501 This is the value of `canlock-password', if that option is non-nil.
4502 Otherwise, generate and save a value for `canlock-password' first."
4503   (unless canlock-password
4504     (customize-save-variable 'canlock-password (message-canlock-generate))
4505     (setq canlock-password-for-verify canlock-password))
4506   canlock-password)
4507
4508 (defun message-insert-canlock ()
4509   (when message-insert-canlock
4510     (message-canlock-password)
4511     (canlock-insert-header)))
4512
4513 (defun message-send-news (&optional arg)
4514   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4515          (case-fold-search nil)
4516          (method (if (functionp message-post-method)
4517                      (funcall message-post-method arg)
4518                    message-post-method))
4519          (newsgroups-field (save-restriction
4520                              (message-narrow-to-headers-or-head)
4521                              (message-fetch-field "Newsgroups")))
4522          (followup-field (save-restriction
4523                            (message-narrow-to-headers-or-head)
4524                            (message-fetch-field "Followup-To")))
4525          ;; BUG: We really need to get the charset for each name in the
4526          ;; Newsgroups and Followup-To lines to allow crossposting
4527          ;; between group namess with incompatible character sets.
4528          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4529          (group-field-charset
4530           (gnus-group-name-charset method newsgroups-field))
4531          (followup-field-charset
4532           (gnus-group-name-charset method (or followup-field "")))
4533          (mime-field-encoding-method-alist
4534           (append (when group-field-charset
4535                     (list (cons "Newsgroups" group-field-charset)))
4536                   (when followup-field-charset
4537                     (list (cons "Followup-To" followup-field-charset)))
4538                   mime-field-encoding-method-alist))
4539          (message-syntax-checks
4540           (if (and arg
4541                    (listp message-syntax-checks))
4542               (cons '(existing-newsgroups . disabled)
4543                     message-syntax-checks)
4544             message-syntax-checks))
4545          (message-this-is-news t)
4546          result)
4547     (save-restriction
4548       (message-narrow-to-headers)
4549       ;; Insert some headers.
4550       (message-generate-headers message-required-news-headers)
4551       (message-insert-canlock)
4552       ;; Let the user do all of the above.
4553       (run-hooks 'message-header-hook))
4554     ;; Note: This check will be disabled by the ".*" default value for
4555     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4556     (when (and group-field-charset
4557                (listp message-syntax-checks))
4558       (setq message-syntax-checks
4559             (cons '(valid-newsgroups . disabled)
4560                   message-syntax-checks)))
4561     (message-cleanup-headers)
4562     (if (not (let ((message-post-method method))
4563                (message-check-news-syntax)))
4564         nil
4565       (unwind-protect
4566           (save-excursion
4567             (set-buffer tembuf)
4568             (buffer-disable-undo)
4569             (erase-buffer)
4570             (insert-buffer-substring message-encoding-buffer)
4571             ;; Remove some headers.
4572             (save-restriction
4573               (message-narrow-to-headers)
4574 ;; We Semi-gnus people have no use for it.
4575 ;;            ;; We (re)generate the Lines header.
4576 ;;            (when (memq 'Lines message-required-mail-headers)
4577 ;;              (message-generate-headers '(Lines)))
4578               ;; Remove some headers.
4579               (message-remove-header message-ignored-news-headers t))
4580             (goto-char (point-max))
4581             ;; require one newline at the end.
4582             (or (= (preceding-char) ?\n)
4583                 (insert ?\n))
4584             (setq result (message-maybe-split-and-send-news method)))
4585         (kill-buffer tembuf))
4586       (set-buffer message-edit-buffer)
4587       (if result
4588           (progn
4589             (message "Couldn't send message via news: %s"
4590                      (nnheader-get-report (car method)))
4591             nil)
4592         (push 'news message-sent-message-via)))))
4593
4594 ;; 1997-09-29 by MORIOKA Tomohiko
4595 (defun message-send-news-with-gnus (method)
4596   (let ((case-fold-search t))
4597     ;; Remove the delimiter.
4598     (goto-char (point-min))
4599     (re-search-forward
4600      (concat "^" (regexp-quote mail-header-separator) "\n"))
4601     (replace-match "\n")
4602     (backward-char 1)
4603     (run-hooks 'message-send-news-hook)
4604     (gnus-open-server method)
4605     (message "Sending news via %s..." (gnus-server-string method))
4606     (gnus-request-post method)
4607     ))
4608
4609 ;;;
4610 ;;; Header generation & syntax checking.
4611 ;;;
4612
4613 (defun message-check-element (type)
4614   "Return non-nil if this TYPE is not to be checked."
4615   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4616       t
4617     (let ((able (assq type message-syntax-checks)))
4618       (and (consp able)
4619            (eq (cdr able) 'disabled)))))
4620
4621 (defun message-check-news-syntax ()
4622   "Check the syntax of the message."
4623   (save-excursion
4624     (save-restriction
4625       (widen)
4626       (and
4627        ;; We narrow to the headers and check them first.
4628        (save-excursion
4629          (save-restriction
4630            (message-narrow-to-headers)
4631            (message-check-news-header-syntax)))
4632        ;; Check the body.
4633        (save-excursion
4634          (set-buffer message-edit-buffer)
4635          (message-check-news-body-syntax))))))
4636
4637 (defun message-check-news-header-syntax ()
4638   (and
4639    ;; Check Newsgroups header.
4640    (message-check 'newsgroups
4641      (let ((group (message-fetch-field "newsgroups")))
4642        (or
4643         (and group
4644              (not (string-match "\\`[ \t]*\\'" group)))
4645         (ignore
4646          (message
4647           "The newsgroups field is empty or missing.  Posting is denied.")))))
4648    ;; Check the Subject header.
4649    (message-check 'subject
4650      (let* ((case-fold-search t)
4651             (subject (message-fetch-field "subject")))
4652        (or
4653         (and subject
4654              (not (string-match "\\`[ \t]*\\'" subject)))
4655         (ignore
4656          (message
4657           "The subject field is empty or missing.  Posting is denied.")))))
4658    ;; Check for commands in Subject.
4659    (message-check 'subject-cmsg
4660      (if (string-match "^cmsg " (message-fetch-field "subject"))
4661          (y-or-n-p
4662           "The control code \"cmsg\" is in the subject.  Really post? ")
4663        t))
4664    ;; Check long header lines.
4665    (message-check 'long-header-lines
4666      (let ((start (point))
4667            (header nil)
4668            (length 0)
4669            found)
4670        (while (and (not found)
4671                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4672          (if (> (- (point) (match-beginning 0)) 998)
4673              (setq found t
4674                    length (- (point) (match-beginning 0)))
4675            (setq header (match-string-no-properties 1)))
4676          (setq start (match-beginning 0))
4677          (forward-line 1))
4678        (if found
4679            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4680                              header length))
4681          t)))
4682    ;; Check for multiple identical headers.
4683    (message-check 'multiple-headers
4684      (let (found)
4685        (while (and (not found)
4686                    (re-search-forward "^[^ \t:]+: " nil t))
4687          (save-excursion
4688            (or (re-search-forward
4689                 (concat "^"
4690                         (regexp-quote
4691                          (setq found
4692                                (buffer-substring
4693                                 (match-beginning 0) (- (match-end 0) 2))))
4694                         ":")
4695                 nil t)
4696                (setq found nil))))
4697        (if found
4698            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4699          t)))
4700    ;; Check for Version and Sendsys.
4701    (message-check 'sendsys
4702      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4703          (y-or-n-p
4704           (format "The article contains a %s command.  Really post? "
4705                   (buffer-substring (match-beginning 0)
4706                                     (1- (match-end 0)))))
4707        t))
4708    ;; See whether we can shorten Followup-To.
4709    (message-check 'shorten-followup-to
4710      (let ((newsgroups (message-fetch-field "newsgroups"))
4711            (followup-to (message-fetch-field "followup-to"))
4712            to)
4713        (when (and newsgroups
4714                   (string-match "," newsgroups)
4715                   (not followup-to)
4716                   (not
4717                    (zerop
4718                     (length
4719                      (setq to (completing-read
4720                                "Followups to (default: no Followup-To header) "
4721                                (mapcar #'list
4722                                        (cons "poster"
4723                                              (message-tokenize-header
4724                                               newsgroups)))))))))
4725          (goto-char (point-min))
4726          (insert "Followup-To: " to "\n"))
4727        t))
4728    ;; Check "Shoot me".
4729    (message-check 'shoot
4730      (if (re-search-forward
4731           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4732          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4733        t))
4734    ;; Check for Approved.
4735    (message-check 'approved
4736      (if (re-search-forward "^Approved:" nil t)
4737          (y-or-n-p "The article contains an Approved header.  Really post? ")
4738        t))
4739    ;; Check the Message-ID header.
4740    (message-check 'message-id
4741      (let* ((case-fold-search t)
4742             (message-id (message-fetch-field "message-id" t)))
4743        (or (not message-id)
4744            ;; Is there an @ in the ID?
4745            (and (string-match "@" message-id)
4746                 ;; Is there a dot in the ID?
4747                 (string-match "@[^.]*\\." message-id)
4748                 ;; Does the ID end with a dot?
4749                 (not (string-match "\\.>" message-id)))
4750            (y-or-n-p
4751             (format "The Message-ID looks strange: \"%s\".  Really post? "
4752                     message-id)))))
4753    ;; Check the Newsgroups & Followup-To headers.
4754    (message-check 'existing-newsgroups
4755      (let* ((case-fold-search t)
4756             (newsgroups (message-fetch-field "newsgroups"))
4757             (followup-to (message-fetch-field "followup-to"))
4758             (groups (message-tokenize-header
4759                      (if followup-to
4760                          (concat newsgroups "," followup-to)
4761                        newsgroups)))
4762             (post-method (if (functionp message-post-method)
4763                              (funcall message-post-method)
4764                            message-post-method))
4765             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4766             ;; would probably involve a new nnoo function.
4767             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4768             (method (if (and (consp post-method)
4769                              (eq (car post-method) 'nnvirtual)
4770                              gnus-message-group-art)
4771                         (let ((group (car (nnvirtual-find-group-art
4772                                            (car gnus-message-group-art)
4773                                            (cdr gnus-message-group-art)))))
4774                           (gnus-find-method-for-group group))
4775                       post-method))
4776             (known-groups
4777              (mapcar (lambda (n)
4778                        (gnus-group-name-decode
4779                         (gnus-group-real-name n)
4780                         (gnus-group-name-charset method n)))
4781                      (gnus-groups-from-server method)))
4782             errors)
4783        (while groups
4784          (when (and (not (equal (car groups) "poster"))
4785                     (not (member (car groups) known-groups))
4786                     (not (member (car groups) errors)))
4787            (push (car groups) errors))
4788          (pop groups))
4789        (cond
4790         ;; Gnus is not running.
4791         ((or (not (and (boundp 'gnus-active-hashtb)
4792                        gnus-active-hashtb))
4793              (not (boundp 'gnus-read-active-file)))
4794          t)
4795         ;; We don't have all the group names.
4796         ((and (or (not gnus-read-active-file)
4797                   (eq gnus-read-active-file 'some))
4798               errors)
4799          (y-or-n-p
4800           (format
4801            "Really use %s possibly unknown group%s: %s? "
4802            (if (= (length errors) 1) "this" "these")
4803            (if (= (length errors) 1) "" "s")
4804            (mapconcat 'identity errors ", "))))
4805         ;; There were no errors.
4806         ((not errors)
4807          t)
4808         ;; There are unknown groups.
4809         (t
4810          (y-or-n-p
4811           (format
4812            "Really post to %s unknown group%s: %s? "
4813            (if (= (length errors) 1) "this" "these")
4814            (if (= (length errors) 1) "" "s")
4815            (mapconcat 'identity errors ", ")))))))
4816    ;; Check continuation headers.
4817    (message-check 'continuation-headers
4818      (goto-char (point-min))
4819      (let ((do-posting t))
4820        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4821          (if (y-or-n-p "Fix continuation lines? ")
4822              (progn
4823                (goto-char (match-beginning 0))
4824                (insert " "))
4825            (unless (y-or-n-p "Send anyway? ")
4826              (setq do-posting nil))))
4827        do-posting))
4828    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4829    (message-check 'valid-newsgroups
4830      (let ((case-fold-search t)
4831            (headers '("Newsgroups" "Followup-To"))
4832            header error)
4833        (while (and headers (not error))
4834          (when (setq header (mail-fetch-field (car headers)))
4835            (if (or
4836                 (not
4837                  (string-match
4838                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4839                   header))
4840                 (memq
4841                  nil (mapcar
4842                       (lambda (g)
4843                         (not (string-match "\\.\\'\\|\\.\\." g)))
4844                       (message-tokenize-header header ","))))
4845                (setq error t)))
4846          (unless error
4847            (pop headers)))
4848        (if (not error)
4849            t
4850          (y-or-n-p
4851           (format "The %s header looks odd: \"%s\".  Really post? "
4852                   (car headers) header)))))
4853    (message-check 'repeated-newsgroups
4854      (let ((case-fold-search t)
4855            (headers '("Newsgroups" "Followup-To"))
4856            header error groups group)
4857        (while (and headers
4858                    (not error))
4859          (when (setq header (mail-fetch-field (pop headers)))
4860            (setq groups (message-tokenize-header header ","))
4861            (while (setq group (pop groups))
4862              (when (member group groups)
4863                (setq error group
4864                      groups nil)))))
4865        (if (not error)
4866            t
4867          (y-or-n-p
4868           (format "Group %s is repeated in headers.  Really post? " error)))))
4869    ;; Check the From header.
4870    (message-check 'from
4871      (let* ((case-fold-search t)
4872             (from (message-fetch-field "from"))
4873             ad)
4874        (cond
4875         ((not from)
4876          (message "There is no From line.  Posting is denied.")
4877          nil)
4878         ((or (not (string-match
4879                    "@[^\\.]*\\."
4880                    (setq ad (nth 1 (std11-extract-address-components
4881                                     from))))) ;larsi@ifi
4882              (string-match "\\.\\." ad) ;larsi@ifi..uio
4883              (string-match "@\\." ad)   ;larsi@.ifi.uio
4884              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4885              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4886              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4887          (message
4888           "Denied posting -- the From looks strange: \"%s\"." from)
4889          nil)
4890         ((let ((addresses (rfc822-addresses from)))
4891            (while (and addresses
4892                        (not (eq (string-to-char (car addresses)) ?\()))
4893              (setq addresses (cdr addresses)))
4894            addresses)
4895          (message
4896           "Denied posting -- bad From address: \"%s\"." from)
4897          nil)
4898         (t t))))
4899    ;; Check the Reply-To header.
4900    (message-check 'reply-to
4901      (let* ((case-fold-search t)
4902             (reply-to (message-fetch-field "reply-to"))
4903             ad)
4904        (cond
4905         ((not reply-to)
4906          t)
4907         ((string-match "," reply-to)
4908          (y-or-n-p
4909           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4910                   reply-to)))
4911         ((or (not (string-match
4912                    "@[^\\.]*\\."
4913                    (setq ad (nth 1 (std11-extract-address-components
4914                                     reply-to))))) ;larsi@ifi
4915              (string-match "\\.\\." ad) ;larsi@ifi..uio
4916              (string-match "@\\." ad)   ;larsi@.ifi.uio
4917              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4918              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4919              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4920          (y-or-n-p
4921           (format
4922            "The Reply-To looks strange: \"%s\". Really post? "
4923            reply-to)))
4924         (t t))))))
4925
4926 (defun message-check-news-body-syntax ()
4927   (and
4928    ;; Check for long lines.
4929    (message-check 'long-lines
4930      (goto-char (point-min))
4931      (re-search-forward
4932       (concat "^" (regexp-quote mail-header-separator) "$"))
4933      (forward-line 1)
4934      (while (and
4935              (or (looking-at
4936                   mime-edit-tag-regexp)
4937                  (let ((p (point)))
4938                    (end-of-line)
4939                    (< (- (point) p) 80)))
4940              (zerop (forward-line 1))))
4941      (or (bolp)
4942          (eobp)
4943          (y-or-n-p
4944           "You have lines longer than 79 characters.  Really post? ")))
4945    ;; Check whether the article is empty.
4946    (message-check 'empty
4947      (goto-char (point-min))
4948      (re-search-forward
4949       (concat "^" (regexp-quote mail-header-separator) "$"))
4950      (forward-line 1)
4951      (let ((b (point)))
4952        (goto-char (point-max))
4953        (re-search-backward message-signature-separator nil t)
4954        (beginning-of-line)
4955        (or (re-search-backward "[^ \n\t]" b t)
4956            (if (message-gnksa-enable-p 'empty-article)
4957                (y-or-n-p "Empty article.  Really post? ")
4958              (message "Denied posting -- Empty article.")
4959              nil))))
4960    ;; Check for control characters.
4961    (message-check 'control-chars
4962      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4963          (y-or-n-p
4964           "The article contains control characters.  Really post? ")
4965        t))
4966    ;; Check 8bit characters.
4967    (message-check '8bit
4968      (message-check-8bit))
4969    ;; Check excessive size.
4970    (message-check 'size
4971      (if (> (buffer-size) 60000)
4972          (y-or-n-p
4973           (format "The article is %d octets long.  Really post? "
4974                   (buffer-size)))
4975        t))
4976    ;; Check whether any new text has been added.
4977    (message-check 'new-text
4978      (or
4979       (not message-checksum)
4980       (not (eq (message-checksum) message-checksum))
4981       (if (message-gnksa-enable-p 'quoted-text-only)
4982           (y-or-n-p
4983            "It looks like no new text has been added.  Really post? ")
4984         (message "Denied posting -- no new text has been added.")
4985         nil)))
4986    ;; Check the length of the signature.
4987    (message-check 'signature
4988      (goto-char (point-max))
4989      (if (> (count-lines (point) (point-max)) 5)
4990          (y-or-n-p
4991           (format
4992            "Your .sig is %d lines; it should be max 4.  Really post? "
4993            (1- (count-lines (point) (point-max)))))
4994        t))
4995    ;; Ensure that text follows last quoted portion.
4996    (message-check 'quoting-style
4997      (goto-char (point-max))
4998      (let ((no-problem t))
4999        (when (search-backward-regexp "^>[^\n]*\n" nil t)
5000          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
5001        (if no-problem
5002            t
5003          (if (message-gnksa-enable-p 'quoted-text-only)
5004              (y-or-n-p "Your text should follow quoted text.  Really post? ")
5005            ;; Ensure that
5006            (goto-char (point-min))
5007            (re-search-forward
5008             (concat "^" (regexp-quote mail-header-separator) "$"))
5009            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
5010                (y-or-n-p "Your text should follow quoted text.  Really post? ")
5011              (message "Denied posting -- only quoted text.")
5012              nil)))))))
5013
5014 (defun message-check-mail-syntax ()
5015   "Check the syntax of the message."
5016   (save-excursion
5017     (save-restriction
5018       (widen)
5019       (and
5020        ;; We narrow to the headers and check them first.
5021        (save-excursion
5022          (save-restriction
5023            (message-narrow-to-headers)
5024            (message-check-mail-header-syntax)))
5025        ;; Check the body.
5026        (save-excursion
5027          (set-buffer message-edit-buffer)
5028          (message-check-mail-body-syntax))))))
5029
5030 (defun message-check-mail-header-syntax ()
5031   t)
5032
5033 (defun message-check-mail-body-syntax ()
5034   (and
5035    ;; Check 8bit characters.
5036    (message-check '8bit
5037      (message-check-8bit)
5038      )))
5039
5040 (defun message-check-8bit ()
5041   "Check the article contains 8bit characters."
5042   (save-excursion
5043     (set-buffer message-encoding-buffer)
5044     (message-narrow-to-headers)
5045     (let* ((case-fold-search t)
5046            (field-value (message-fetch-field "content-transfer-encoding")))
5047       (if (and field-value
5048                (member (downcase field-value) message-8bit-encoding-list))
5049           t
5050         (widen)
5051         (set-buffer (get-buffer-create " message syntax"))
5052         (erase-buffer)
5053         (goto-char (point-min))
5054         (set-buffer-multibyte nil)
5055         (insert-buffer-substring message-encoding-buffer)
5056         (goto-char (point-min))
5057         (if (re-search-forward "[^\x00-\x7f]" nil t)
5058             (y-or-n-p
5059              "The article contains 8bit characters.  Really post? ")
5060           t)))))
5061
5062 (defun message-checksum ()
5063   "Return a \"checksum\" for the current buffer."
5064   (let ((sum 0))
5065     (save-excursion
5066       (goto-char (point-min))
5067       (re-search-forward
5068        (concat "^" (regexp-quote mail-header-separator) "$"))
5069       (while (not (eobp))
5070         (when (not (looking-at "[ \t\n]"))
5071           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
5072                             (char-after))))
5073         (forward-char 1)))
5074     sum))
5075
5076 (defun message-do-fcc ()
5077   "Process Fcc headers in the current buffer."
5078   (let ((case-fold-search t)
5079         (coding-system-for-write 'raw-text)
5080         list file
5081         (mml-externalize-attachments message-fcc-externalize-attachments))
5082     (save-excursion
5083       (save-restriction
5084         (message-narrow-to-headers)
5085         (setq file (message-fetch-field "fcc" t)))
5086       (when file
5087         (set-buffer (get-buffer-create " *message temp*"))
5088         (erase-buffer)
5089         (insert-buffer-substring message-encoding-buffer)
5090         (save-restriction
5091           (message-narrow-to-headers)
5092           (while (setq file (message-fetch-field "fcc"))
5093             (push file list)
5094             (message-remove-header "fcc" nil t)))
5095         (goto-char (point-min))
5096         (when (re-search-forward
5097                (concat "^" (regexp-quote mail-header-separator) "$")
5098                nil t)
5099           (replace-match "" t t))
5100         ;; Process FCC operations.
5101         (while list
5102           (setq file (pop list))
5103           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
5104               ;; Pipe the article to the program in question.
5105               (call-process-region (point-min) (point-max) shell-file-name
5106                                    nil nil nil shell-command-switch
5107                                    (match-string 1 file))
5108             ;; Save the article.
5109             (setq file (expand-file-name file))
5110             (unless (file-exists-p (file-name-directory file))
5111               (make-directory (file-name-directory file) t))
5112             (if (and message-fcc-handler-function
5113                      (not (eq message-fcc-handler-function 'rmail-output)))
5114                 (funcall message-fcc-handler-function file)
5115               (if (and (file-readable-p file) (mail-file-babyl-p file))
5116                   (rmail-output file 1 nil t)
5117                 (let ((mail-use-rfc822 t))
5118                   (rmail-output file 1 t t))))))
5119         (kill-buffer (current-buffer))))))
5120
5121 (defun message-output (filename)
5122   "Append this article to Unix/babyl mail file FILENAME."
5123   (if (and (file-readable-p filename)
5124            (mail-file-babyl-p filename))
5125       (gnus-output-to-rmail filename t)
5126     (gnus-output-to-mail filename t)))
5127
5128 (defun message-cleanup-headers ()
5129   "Do various automatic cleanups of the headers."
5130   ;; Remove empty lines in the header.
5131   (save-restriction
5132     (message-narrow-to-headers)
5133     ;; Remove blank lines.
5134     (while (re-search-forward "^[ \t]*\n" nil t)
5135       (replace-match "" t t))
5136
5137     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
5138     ;; spaces to comma and eliminate spaces around commas.  Eliminate
5139     ;; embedded line breaks.
5140     (goto-char (point-min))
5141     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
5142       (save-restriction
5143         (narrow-to-region
5144          (point)
5145          (if (re-search-forward "^[^ \t]" nil t)
5146              (match-beginning 0)
5147            (forward-line 1)
5148            (point)))
5149         (goto-char (point-min))
5150         (while (re-search-forward "\n[ \t]+" nil t)
5151           (replace-match " " t t))      ;No line breaks (too confusing)
5152         (goto-char (point-min))
5153         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
5154           (replace-match "," t t))
5155         (goto-char (point-min))
5156         ;; Remove trailing commas.
5157         (when (re-search-forward ",+$" nil t)
5158           (replace-match "" t t))))))
5159
5160 (defun message-make-date (&optional now)
5161   "Make a valid data header.
5162 If NOW, use that time instead."
5163   (let ((system-time-locale "C"))
5164     (format-time-string "%a, %d %b %Y %T %z" now)))
5165
5166 (defun message-make-followup-subject (subject)
5167   "Make a followup Subject."
5168   (cond
5169    ((and (eq message-use-subject-re 'guess)
5170          (string-match message-subject-encoded-re-regexp subject))
5171     subject)
5172    (message-use-subject-re
5173     (concat "Re: " (message-strip-subject-re subject)))
5174    (t subject)))
5175
5176 (defun message-make-message-id ()
5177   "Make a unique Message-ID."
5178   (concat "<" (message-unique-id)
5179           (let ((psubject (save-excursion (message-fetch-field "subject")))
5180                 (psupersedes
5181                  (save-excursion (message-fetch-field "supersedes"))))
5182             (if (or
5183                  (and message-reply-headers
5184                       (mail-header-references message-reply-headers)
5185                       (mail-header-subject message-reply-headers)
5186                       psubject
5187                       (not (string=
5188                             (message-strip-subject-re
5189                              (mail-header-subject message-reply-headers))
5190                             (message-strip-subject-re psubject))))
5191                  (and psupersedes
5192                       (string-match "_-_@" psupersedes)))
5193                 "_-_" ""))
5194           "@" (message-make-fqdn) ">"))
5195
5196 (defvar message-unique-id-char nil)
5197
5198 ;; If you ever change this function, make sure the new version
5199 ;; cannot generate IDs that the old version could.
5200 ;; You might for example insert a "." somewhere (not next to another dot
5201 ;; or string boundary), or modify the "fsf" string.
5202 (defun message-unique-id ()
5203   ;; Don't use microseconds from (current-time), they may be unsupported.
5204   ;; Instead we use this randomly inited counter.
5205   (setq message-unique-id-char
5206         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
5207            ;; (current-time) returns 16-bit ints,
5208            ;; and 2^16*25 just fits into 4 digits i base 36.
5209            (* 25 25)))
5210   (let ((tm (current-time)))
5211     (concat
5212      (if (memq system-type '(ms-dos emx vax-vms))
5213          (let ((user (downcase (user-login-name))))
5214            (while (string-match "[^a-z0-9_]" user)
5215              (aset user (match-beginning 0) ?_))
5216            user)
5217        (message-number-base36 (user-uid) -1))
5218      (message-number-base36 (+ (car tm)
5219                                (lsh (% message-unique-id-char 25) 16)) 4)
5220      (message-number-base36 (+ (nth 1 tm)
5221                                (lsh (/ message-unique-id-char 25) 16)) 4)
5222      ;; Append a given name, because while the generated ID is unique
5223      ;; to this newsreader, other newsreaders might otherwise generate
5224      ;; the same ID via another algorithm.
5225      ".fsf")))
5226
5227 (defun message-number-base36 (num len)
5228   (if (if (< len 0)
5229           (<= num 0)
5230         (= len 0))
5231       ""
5232     (concat (message-number-base36 (/ num 36) (1- len))
5233             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5234                                   (% num 36))))))
5235
5236 (defun message-make-organization ()
5237   "Make an Organization header."
5238   (let* ((organization
5239           (when message-user-organization
5240             (if (functionp message-user-organization)
5241                 (funcall message-user-organization)
5242               message-user-organization))))
5243     (with-temp-buffer
5244       (set-buffer-multibyte t)
5245       (cond ((stringp organization)
5246              (insert organization))
5247             ((and (eq t organization)
5248                   message-user-organization-file
5249                   (file-exists-p message-user-organization-file))
5250              (insert-file-contents message-user-organization-file)))
5251       (goto-char (point-min))
5252       (while (re-search-forward "[\t\n]+" nil t)
5253         (replace-match "" t t))
5254       (unless (zerop (buffer-size))
5255         (buffer-string)))))
5256
5257 (defun message-make-lines ()
5258   "Count the number of lines and return numeric string."
5259   (save-excursion
5260     (save-restriction
5261       (widen)
5262       (message-goto-body)
5263       (int-to-string (count-lines (point) (point-max))))))
5264
5265 (defun message-make-references ()
5266   "Return the References header for this message."
5267   (when message-reply-headers
5268     (let ((message-id (mail-header-message-id message-reply-headers))
5269           (references (mail-header-references message-reply-headers))
5270           new-references)
5271       (if (or references message-id)
5272           (concat (or references "") (and references " ")
5273                   (or message-id ""))
5274         nil))))
5275
5276 (defun message-make-in-reply-to ()
5277   "Return the In-Reply-To header for this message."
5278   (when message-reply-headers
5279     (let ((from (mail-header-from message-reply-headers))
5280           (date (mail-header-date message-reply-headers))
5281           (msg-id (mail-header-message-id message-reply-headers)))
5282       (when from
5283         (let ((name (std11-extract-address-components from)))
5284           (concat msg-id (if msg-id " (")
5285                   (or (car name)
5286                       (nth 1 name))
5287                   "'s message of \""
5288                   (if (or (not date) (string= date ""))
5289                       "(unknown date)" date)
5290                   "\"" (if msg-id ")")))))))
5291
5292 (defun message-make-distribution ()
5293   "Make a Distribution header."
5294   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5295     (cond ((functionp message-distribution-function)
5296            (funcall message-distribution-function))
5297           (t orig-distribution))))
5298
5299 (defun message-make-expires ()
5300   "Return an Expires header based on `message-expires'."
5301   (let ((current (current-time))
5302         (future (* 1.0 message-expires 60 60 24)))
5303     ;; Add the future to current.
5304     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5305     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5306     (message-make-date current)))
5307
5308 (defun message-make-path ()
5309   "Return uucp path."
5310   (let ((login-name (user-login-name)))
5311     (cond ((null message-user-path)
5312            (concat (system-name) "!" login-name))
5313           ((stringp message-user-path)
5314            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5315            (concat message-user-path "!" login-name))
5316           (t login-name))))
5317
5318 (defun message-make-from ()
5319   "Make a From header."
5320   (let* ((style message-from-style)
5321          (login (message-make-address))
5322          (fullname
5323           (or (and (boundp 'user-full-name)
5324                    user-full-name)
5325               (user-full-name))))
5326     (when (string= fullname "&")
5327       (setq fullname (user-login-name)))
5328     (with-temp-buffer
5329       (set-buffer-multibyte t)
5330       (cond
5331        ((or (null style)
5332             (equal fullname ""))
5333         (insert login))
5334        ((or (eq style 'angles)
5335             (and (not (eq style 'parens))
5336                  ;; Use angles if no quoting is needed, or if parens would
5337                  ;; need quoting too.
5338                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5339                      (let ((tmp (concat fullname nil)))
5340                        (while (string-match "([^()]*)" tmp)
5341                          (aset tmp (match-beginning 0) ?-)
5342                          (aset tmp (1- (match-end 0)) ?-))
5343                        (string-match "[\\()]" tmp)))))
5344         (insert fullname)
5345         (goto-char (point-min))
5346         ;; Look for a character that cannot appear unquoted
5347         ;; according to RFC 822.
5348         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5349           ;; Quote fullname, escaping specials.
5350           (goto-char (point-min))
5351           (insert "\"")
5352           (while (re-search-forward "[\"\\]" nil 1)
5353             (replace-match "\\\\\\&" t))
5354           (insert "\""))
5355         (insert " <" login ">"))
5356        (t                               ; 'parens or default
5357         (insert login " (")
5358         (let ((fullname-start (point)))
5359           (insert fullname)
5360           (goto-char fullname-start)
5361           ;; RFC 822 says \ and nonmatching parentheses
5362           ;; must be escaped in comments.
5363           ;; Escape every instance of ()\ ...
5364           (while (re-search-forward "[()\\]" nil 1)
5365             (replace-match "\\\\\\&" t))
5366           ;; ... then undo escaping of matching parentheses,
5367           ;; including matching nested parentheses.
5368           (goto-char fullname-start)
5369           (while (re-search-forward
5370                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5371                   nil 1)
5372             (replace-match "\\1(\\3)" t)
5373             (goto-char fullname-start)))
5374         (insert ")")))
5375       (buffer-string))))
5376
5377 (defun message-make-sender ()
5378   "Return the \"real\" user address.
5379 This function tries to ignore all user modifications, and
5380 give as trustworthy answer as possible."
5381   (concat (user-login-name) "@" (system-name)))
5382
5383 (defun message-make-address ()
5384   "Make the address of the user."
5385   (or (message-user-mail-address)
5386       (concat (user-login-name) "@" (message-make-domain))))
5387
5388 (defun message-user-mail-address ()
5389   "Return the pertinent part of `user-mail-address'."
5390   (when (and user-mail-address
5391              (string-match "@.*\\." user-mail-address))
5392     (if (string-match " " user-mail-address)
5393         (nth 1 (std11-extract-address-components user-mail-address))
5394       user-mail-address)))
5395
5396 (defun message-sendmail-envelope-from ()
5397   "Return the envelope from."
5398   (cond ((eq message-sendmail-envelope-from 'header)
5399          (nth 1 (std11-extract-address-components
5400                  (message-fetch-field "from"))))
5401         ((stringp message-sendmail-envelope-from)
5402          message-sendmail-envelope-from)
5403         (t
5404          (message-make-address))))
5405
5406 (defun message-make-fqdn ()
5407   "Return user's fully qualified domain name."
5408   (let* ((system-name (system-name))
5409          (user-mail (message-user-mail-address))
5410          (user-domain
5411           (if (and user-mail
5412                    (string-match "@\\(.*\\)\\'" user-mail))
5413               (match-string 1 user-mail)))
5414          (case-fold-search t))
5415     (cond
5416      ((and message-user-fqdn
5417            (stringp message-user-fqdn)
5418            (string-match message-valid-fqdn-regexp message-user-fqdn)
5419            (not (string-match message-bogus-system-names message-user-fqdn)))
5420       message-user-fqdn)
5421      ;; `message-user-fqdn' seems to be valid
5422      ((and (string-match message-valid-fqdn-regexp system-name)
5423            (not (string-match message-bogus-system-names system-name)))
5424       ;; `system-name' returned the right result.
5425       system-name)
5426      ;; Try `mail-host-address'.
5427      ((and (boundp 'mail-host-address)
5428            (stringp mail-host-address)
5429            (string-match message-valid-fqdn-regexp mail-host-address)
5430            (not (string-match message-bogus-system-names mail-host-address)))
5431       mail-host-address)
5432      ;; We try `user-mail-address' as a backup.
5433      ((and user-domain
5434            (stringp user-domain)
5435            (string-match message-valid-fqdn-regexp user-domain)
5436            (not (string-match message-bogus-system-names user-domain)))
5437       user-domain)
5438      ;; Default to this bogus thing.
5439      (t
5440       (concat system-name
5441               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5442
5443 (defun message-make-host-name ()
5444   "Return the name of the host."
5445   (let ((fqdn (message-make-fqdn)))
5446     (string-match "^[^.]+\\." fqdn)
5447     (substring fqdn 0 (1- (match-end 0)))))
5448
5449 (defun message-make-domain ()
5450   "Return the domain name."
5451   (or mail-host-address
5452       (message-make-fqdn)))
5453
5454 (defun message-to-list-only ()
5455   "Send a message to the list only.
5456 Remove all addresses but the list address from To and Cc headers."
5457   (interactive)
5458   (let ((listaddr (message-make-mail-followup-to t)))
5459     (when listaddr
5460       (save-excursion
5461         (message-remove-header "to")
5462         (message-remove-header "cc")
5463         (message-position-on-field "To" "X-Draft-From")
5464         (insert listaddr)))))
5465
5466 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5467   "Return the Mail-Followup-To header.
5468 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5469 subscribed address (and not the additional To and Cc header contents)."
5470   (let* ((case-fold-search t)
5471          (to (message-fetch-field "To"))
5472          (cc (message-fetch-field "cc"))
5473          (msg-recipients (concat to (and to cc ", ") cc))
5474          (recipients
5475           (mapcar 'mail-strip-quoted-names
5476                   (message-tokenize-header msg-recipients)))
5477          (file-regexps
5478           (if message-subscribed-address-file
5479               (let (begin end item re)
5480                 (save-excursion
5481                   (with-temp-buffer
5482                     (insert-file-contents message-subscribed-address-file)
5483                     (while (not (eobp))
5484                       (setq begin (point))
5485                       (forward-line 1)
5486                       (setq end (point))
5487                       (if (bolp) (setq end (1- end)))
5488                       (setq item (regexp-quote (buffer-substring begin end)))
5489                       (if re (setq re (concat re "\\|" item))
5490                         (setq re (concat "\\`\\(" item))))
5491                     (and re (list (concat re "\\)\\'"))))))))
5492          (mft-regexps (apply 'append message-subscribed-regexps
5493                              (mapcar 'regexp-quote
5494                                      message-subscribed-addresses)
5495                              file-regexps
5496                              (mapcar 'funcall
5497                                      message-subscribed-address-functions))))
5498     (save-match-data
5499       (let ((subscribed-lists nil)
5500             (list
5501              (loop for recipient in recipients
5502                when (loop for regexp in mft-regexps
5503                       when (string-match regexp recipient) return t)
5504                return recipient)))
5505         (when list
5506           (if only-show-subscribed
5507               list
5508             msg-recipients))))))
5509
5510 ;; Dummy to avoid byte-compile warning.
5511 (defvar mule-version)
5512 (defvar emacs-beta-version)
5513 (defvar xemacs-codename)
5514 (defvar gnus-inviolable-extended-version)
5515
5516 (defun message-make-user-agent ()
5517   "Return user-agent info if the value `message-user-agent' is non-nil. If the
5518 \"User-Agent\" field has already exist, remove it."
5519   (when message-user-agent
5520     (save-excursion
5521       (goto-char (point-min))
5522       (let ((case-fold-search t))
5523         (when (re-search-forward "^User-Agent:[\t ]*" nil t)
5524           (delete-region (match-beginning 0) (1+ (std11-field-end)))))))
5525   message-user-agent)
5526
5527 (defun message-idna-to-ascii-rhs-1 (header)
5528   "Interactively potentially IDNA encode domain names in HEADER."
5529   (let ((field (message-fetch-field header))
5530         rhs ace  address)
5531     (when field
5532       (dolist (address (mail-header-parse-addresses field))
5533         (setq address (car address)
5534               rhs (downcase (or (cadr (split-string address "@")) ""))
5535               ace (downcase (idna-to-ascii rhs)))
5536         (when (and (not (equal rhs ace))
5537                    (or (not (eq message-use-idna 'ask))
5538                        (y-or-n-p (format "Replace %s with %s? " rhs ace))))
5539           (goto-char (point-min))
5540           (while (re-search-forward (concat "^" header ":") nil t)
5541             (message-narrow-to-field)
5542             (while (search-forward (concat "@" rhs) nil t)
5543               (replace-match (concat "@" ace) t t))
5544             (goto-char (point-max))
5545             (widen)))))))
5546
5547 (defun message-idna-to-ascii-rhs ()
5548   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5549 See `message-idna-encode'."
5550   (interactive)
5551   (when message-use-idna
5552     (save-excursion
5553       (save-restriction
5554         (message-narrow-to-head)
5555         (message-idna-to-ascii-rhs-1 "From")
5556         (message-idna-to-ascii-rhs-1 "To")
5557         (message-idna-to-ascii-rhs-1 "Cc")))))
5558
5559 (defun message-generate-headers (headers)
5560   "Prepare article HEADERS.
5561 Headers already prepared in the buffer are not modified."
5562   (setq headers (append headers message-required-headers))
5563   (save-restriction
5564     (message-narrow-to-headers)
5565     (let* ((Date (message-make-date))
5566            (Message-ID (message-make-message-id))
5567            (Organization (message-make-organization))
5568            (From (message-make-from))
5569            (Path (message-make-path))
5570            (Subject nil)
5571            (Newsgroups nil)
5572            (In-Reply-To (message-make-in-reply-to))
5573            (References (message-make-references))
5574            (To nil)
5575            (Distribution (message-make-distribution))
5576            (Lines (message-make-lines))
5577            (User-Agent (message-make-user-agent))
5578            (Expires (message-make-expires))
5579            (case-fold-search t)
5580            (optionalp nil)
5581            header value elem header-string)
5582       ;; First we remove any old generated headers.
5583       (let ((headers message-deletable-headers))
5584         (unless (buffer-modified-p)
5585           (setq headers (delq 'Message-ID (copy-sequence headers))))
5586         (while headers
5587           (goto-char (point-min))
5588           (and (re-search-forward
5589                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5590                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5591                (message-delete-line))
5592           (pop headers)))
5593       ;; Go through all the required headers and see if they are in the
5594       ;; articles already.  If they are not, or are empty, they are
5595       ;; inserted automatically - except for Subject, Newsgroups and
5596       ;; Distribution.
5597       (while headers
5598         (goto-char (point-min))
5599         (setq elem (pop headers))
5600         (if (consp elem)
5601             (if (eq (car elem) 'optional)
5602                 (setq header (cdr elem)
5603                       optionalp t)
5604               (setq header (car elem)))
5605           (setq header elem))
5606         (setq header-string  (if (stringp header)
5607                                  header
5608                                (symbol-name header)))
5609         (when (or (not (re-search-forward
5610                         (concat "^"
5611                                 (regexp-quote (downcase header-string))
5612                                 ":")
5613                         nil t))
5614                   (progn
5615                     ;; The header was found.  We insert a space after the
5616                     ;; colon, if there is none.
5617                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5618                     ;; Find out whether the header is empty.
5619                     (looking-at "[ \t]*\n[^ \t]")))
5620           ;; So we find out what value we should insert.
5621           (setq value
5622                 (cond
5623                  ((and (consp elem)
5624                        (eq (car elem) 'optional)
5625                        (not (member header-string message-inserted-headers)))
5626                   ;; This is an optional header.  If the cdr of this
5627                   ;; is something that is nil, then we do not insert
5628                   ;; this header.
5629                   (setq header (cdr elem))
5630                   (or (and (functionp (cdr elem))
5631                            (funcall (cdr elem)))
5632                       (and (boundp (cdr elem))
5633                            (symbol-value (cdr elem)))))
5634                  ((consp elem)
5635                   ;; The element is a cons.  Either the cdr is a
5636                   ;; string to be inserted verbatim, or it is a
5637                   ;; function, and we insert the value returned from
5638                   ;; this function.
5639                   (or (and (stringp (cdr elem))
5640                            (cdr elem))
5641                       (and (functionp (cdr elem))
5642                            (funcall (cdr elem)))))
5643                  ((and (boundp header)
5644                        (symbol-value header))
5645                   ;; The element is a symbol.  We insert the value
5646                   ;; of this symbol, if any.
5647                   (symbol-value header))
5648                  ((not (message-check-element header))
5649                   ;; We couldn't generate a value for this header,
5650                   ;; so we just ask the user.
5651                   (read-from-minibuffer
5652                    (format "Empty header for %s; enter value: " header)))))
5653           ;; Finally insert the header.
5654           (when (and value
5655                      (not (equal value "")))
5656             (save-excursion
5657               (if (bolp)
5658                   (progn
5659                     ;; This header didn't exist, so we insert it.
5660                     (goto-char (point-max))
5661                     (let ((formatter
5662                            (cdr (assq header message-header-format-alist))))
5663                       (if formatter
5664                           (funcall formatter header value)
5665                         (insert header-string ": " value))
5666                       (goto-char (message-fill-field))
5667                       ;; We check whether the value was ended by a
5668                       ;; newline.  If not, we insert one.
5669                       (unless (bolp)
5670                         (insert "\n"))
5671                       (forward-line -1)))
5672                 ;; The value of this header was empty, so we clear
5673                 ;; totally and insert the new value.
5674                 (delete-region (point) (point-at-eol))
5675                 ;; If the header is optional, and the header was
5676                 ;; empty, we can't insert it anyway.
5677                 (unless optionalp
5678                   (push header-string message-inserted-headers)
5679                   (insert value)
5680                   (message-fill-field)))
5681               ;; Add the deletable property to the headers that require it.
5682               (and (memq header message-deletable-headers)
5683                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5684                    (add-text-properties
5685                     (point) (match-end 0)
5686                     '(message-deletable t face italic) (current-buffer)))))))
5687       ;; Insert new Sender if the From is strange.
5688       (let ((from (message-fetch-field "from"))
5689             (sender (message-fetch-field "sender"))
5690             (secure-sender (message-make-sender)))
5691         (when (and from
5692                    (not (message-check-element 'sender))
5693                    (not (string=
5694                          (downcase
5695                           (cadr (std11-extract-address-components from)))
5696                          (downcase secure-sender)))
5697                    (or (null sender)
5698                        (not
5699                         (string=
5700                          (downcase
5701                           (cadr (std11-extract-address-components sender)))
5702                          (downcase secure-sender)))))
5703           (goto-char (point-min))
5704           ;; Rename any old Sender headers to Original-Sender.
5705           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5706             (beginning-of-line)
5707             (insert "Original-")
5708             (beginning-of-line))
5709           (when (or (message-news-p)
5710                     (string-match "@.+\\.." secure-sender))
5711             (insert "Sender: " secure-sender "\n"))))
5712       ;; Check for IDNA
5713       (message-idna-to-ascii-rhs))))
5714
5715 (defun message-insert-courtesy-copy ()
5716   "Insert a courtesy message in mail copies of combined messages."
5717   (let (newsgroups)
5718     (save-excursion
5719       (save-restriction
5720         (message-narrow-to-headers)
5721         (when (setq newsgroups (message-fetch-field "newsgroups"))
5722           (goto-char (point-max))
5723           (insert "Posted-To: " newsgroups "\n")))
5724       (forward-line 1)
5725       (when message-courtesy-message
5726         (cond
5727          ((string-match "%s" message-courtesy-message)
5728           (insert (format message-courtesy-message newsgroups)))
5729          (t
5730           (insert message-courtesy-message)))))))
5731
5732 ;;;
5733 ;;; Setting up a message buffer
5734 ;;;
5735
5736 (defun message-skip-to-next-address ()
5737   (let ((end (save-excursion
5738                (message-next-header)
5739                (point)))
5740         quoted char)
5741     (when (looking-at ",")
5742       (forward-char 1))
5743     (while (and (not (= (point) end))
5744                 (or (not (eq char ?,))
5745                     quoted))
5746       (skip-chars-forward "^,\"" (point-max))
5747       (when (eq (setq char (following-char)) ?\")
5748         (setq quoted (not quoted)))
5749       (unless (= (point) end)
5750         (forward-char 1)))
5751     (skip-chars-forward " \t\n")))
5752
5753 (defun message-fill-address (header value)
5754   (insert (capitalize (symbol-name header))
5755           ": "
5756           (if (consp value) (car value) value)
5757           "\n")
5758   (message-fill-field-address))
5759
5760 (defun message-fill-references (header value)
5761   (insert (capitalize (symbol-name header))
5762           ": "
5763           (std11-fill-msg-id-list-string
5764            (if (consp value) (car value) value))
5765           "\n"))
5766
5767 (defun message-split-line ()
5768   "Split current line, moving portion beyond point vertically down.
5769 If the current line has `message-yank-prefix', insert it on the new line."
5770   (interactive "*")
5771   (condition-case nil
5772       (split-line message-yank-prefix) ;; Emacs 21.3.50+ supports arg.
5773     (error
5774      (split-line))))
5775
5776 (defun message-insert-header (header value)
5777   (insert (capitalize (symbol-name header))
5778           ": "
5779           (if (consp value) (car value) value)))
5780
5781 (defun message-field-name ()
5782   (save-excursion
5783     (goto-char (point-min))
5784     (when (looking-at "\\([^:]+\\):")
5785       (intern (capitalize (match-string 1))))))
5786
5787 (defun message-fill-field ()
5788   (save-excursion
5789     (save-restriction
5790       (message-narrow-to-field)
5791       (let ((field-name (message-field-name)))
5792         (funcall (or (cadr (assq field-name message-field-fillers))
5793                      'message-fill-field-general)))
5794       (point-max))))
5795
5796 (defun message-fill-field-address ()
5797   (while (not (eobp))
5798     (message-skip-to-next-address)
5799     (let (last)
5800       (if (and (> (current-column) 78)
5801                last)
5802           (progn
5803             (save-excursion
5804               (goto-char last)
5805               (insert "\n\t"))
5806             (setq last (1+ (point))))
5807         (setq last (1+ (point)))))))
5808
5809 (defun message-fill-field-general ()
5810   (let ((begin (point))
5811         (fill-column 78)
5812         (fill-prefix " "))
5813     (while (and (search-forward "\n" nil t)
5814                 (not (eobp)))
5815       (replace-match " " t t))
5816     (fill-region-as-paragraph begin (point-max))
5817     ;; Tapdance around looong Message-IDs.
5818     (forward-line -1)
5819     (when (looking-at "[ \t]*$")
5820       (message-delete-line))
5821     (goto-char begin)
5822     (search-forward ":" nil t)
5823     (when (looking-at "\n[ \t]+")
5824       (replace-match " " t t))
5825     (goto-char (point-max))))
5826
5827 (defun message-shorten-1 (list cut surplus)
5828   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5829   (setcdr (nthcdr (- cut 2) list)
5830           (nthcdr (+ (- cut 2) surplus 1) list)))
5831
5832 (defun message-shorten-references (header references)
5833   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5834 When sending via news, also check that the REFERENCES are less
5835 than 988 characters long, and if they are not, trim them until
5836 they are."
5837   (let ((maxcount 21)
5838         (count 0)
5839         (cut 2)
5840         refs)
5841     (with-temp-buffer
5842       (insert references)
5843       (goto-char (point-min))
5844       ;; Cons a list of valid references.
5845       (while (re-search-forward "<[^>]+>" nil t)
5846         (push (match-string 0) refs))
5847       (setq refs (nreverse refs)
5848             count (length refs)))
5849
5850     ;; If the list has more than MAXCOUNT elements, trim it by
5851     ;; removing the CUTth element and the required number of
5852     ;; elements that follow.
5853     (when (> count maxcount)
5854       (let ((surplus (- count maxcount)))
5855         (message-shorten-1 refs cut surplus)
5856         (decf count surplus)))
5857
5858     ;; When sending via news, make sure the total folded length will
5859     ;; be less than 998 characters.  This is to cater to broken INN
5860     ;; 2.3 which counts the total number of characters in a header
5861     ;; rather than the physical line length of each line, as it shuld.
5862     ;;
5863     ;; This hack should be removed when it's believed than INN 2.3 is
5864     ;; no longer widely used.
5865     ;;
5866     ;; At this point the headers have not been generated, thus we use
5867     ;; message-this-is-news directly.
5868     (when message-this-is-news
5869       (while (< 998
5870                 (with-temp-buffer
5871                   (message-insert-header
5872                    header (mapconcat #'identity refs " "))
5873                   (buffer-size)))
5874         (message-shorten-1 refs cut 1)))
5875     ;; Finally, collect the references back into a string and insert
5876     ;; it into the buffer.
5877     (message-insert-header header (mapconcat #'identity refs " "))))
5878
5879 (defun message-position-point ()
5880   "Move point to where the user probably wants to find it."
5881   (message-narrow-to-headers)
5882   (cond
5883    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5884     (search-backward ":" )
5885     (widen)
5886     (forward-char 1)
5887     (if (eq (char-after) ? )
5888         (forward-char 1)
5889       (insert " ")))
5890    (t
5891     (goto-char (point-max))
5892     (widen)
5893     (forward-line 1)
5894     (unless (looking-at "$")
5895       (forward-line 2)))
5896    (sit-for 0)))
5897
5898 (defcustom message-beginning-of-line t
5899   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5900  goes to beginning of header values."
5901   :version "21.4"
5902   :group 'message-buffers
5903   :link '(custom-manual "(message)Movement")
5904   :type 'boolean)
5905
5906 (defun message-beginning-of-line (&optional n)
5907   "Move point to beginning of header value or to beginning of line.
5908 The prefix argument N is passed directly to `beginning-of-line'.
5909
5910 This command is identical to `beginning-of-line' if point is
5911 outside the message header or if the option `message-beginning-of-line'
5912 is nil.
5913
5914 If point is in the message header and on a (non-continued) header
5915 line, move point to the beginning of the header value.  If point
5916 is already there, move point to beginning of line.  Therefore,
5917 repeated calls will toggle point between beginning of field and
5918 beginning of line."
5919   (interactive "p")
5920   (let ((zrs 'zmacs-region-stays))
5921     (when (and (interactive-p) (boundp zrs))
5922       (set zrs t)))
5923   (if (and message-beginning-of-line
5924            (message-point-in-header-p))
5925       (let* ((here (point))
5926              (bol (progn (beginning-of-line n) (point)))
5927              (eol (point-at-eol))
5928              (eoh (re-search-forward ": *" eol t)))
5929         (if (or (not eoh) (equal here eoh))
5930             (goto-char bol)
5931           (goto-char eoh)))
5932     (beginning-of-line n)))
5933
5934 (defun message-buffer-name (type &optional to group)
5935   "Return a new (unique) buffer name based on TYPE and TO."
5936   (cond
5937    ;; Generate a new buffer name The Message Way.
5938    ((eq message-generate-new-buffers 'unique)
5939     (generate-new-buffer-name
5940      (concat "*" type
5941              (if to
5942                  (concat " to "
5943                          (or (car (std11-extract-address-components to))
5944                              to) "")
5945                "")
5946              (if (and group (not (string= group ""))) (concat " on " group) "")
5947              "*")))
5948    ;; Check whether `message-generate-new-buffers' is a function,
5949    ;; and if so, call it.
5950    ((functionp message-generate-new-buffers)
5951     (funcall message-generate-new-buffers type to group))
5952    ((eq message-generate-new-buffers 'unsent)
5953     (generate-new-buffer-name
5954      (concat "*unsent " type
5955              (if to
5956                  (concat " to "
5957                          (or (car (std11-extract-address-components to))
5958                              to) "")
5959                "")
5960              (if (and group (not (string= group ""))) (concat " on " group) "")
5961              "*")))
5962    ;; Use standard name.
5963    (t
5964     (format "*%s message*" type))))
5965
5966 (defmacro message-pop-to-buffer-1 (buffer)
5967   `(if pop-up-frames
5968        (let (special-display-buffer-names
5969              special-display-regexps
5970              same-window-buffer-names
5971              same-window-regexps)
5972          (pop-to-buffer ,buffer))
5973      (pop-to-buffer ,buffer)))
5974
5975 (defun message-pop-to-buffer (name)
5976   "Pop to buffer NAME, and warn if it already exists and is modified."
5977   (let ((buffer (get-buffer name))
5978         (pop-up-frames (and (static-if (featurep 'xemacs)
5979                                 (device-on-window-system-p)
5980                               window-system)
5981                             message-use-multi-frames)))
5982     (if (and buffer
5983              (buffer-name buffer))
5984         (progn
5985           (message-pop-to-buffer-1 buffer)
5986           (when (and (buffer-modified-p)
5987                      (not (y-or-n-p
5988                            "Message already being composed; erase? ")))
5989             (error "Message being composed")))
5990       (message-pop-to-buffer-1 name))
5991     (erase-buffer)
5992     (message-mode)
5993     (when pop-up-frames
5994       (set (make-local-variable 'message-original-frame) (selected-frame)))))
5995
5996 (defun message-do-send-housekeeping ()
5997   "Kill old message buffers."
5998   ;; We might have sent this buffer already.  Delete it from the
5999   ;; list of buffers.
6000   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
6001   (while (and message-max-buffers
6002               message-buffer-list
6003               (>= (length message-buffer-list) message-max-buffers))
6004     ;; Kill the oldest buffer -- unless it has been changed.
6005     (let ((buffer (pop message-buffer-list)))
6006       (when (and (buffer-name buffer)
6007                  (not (buffer-modified-p buffer)))
6008         (kill-buffer buffer))))
6009   ;; Rename the buffer.
6010   (if message-send-rename-function
6011       (funcall message-send-rename-function)
6012     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
6013     (when (string-match
6014            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
6015            (buffer-name))
6016       (let ((name (match-string 2 (buffer-name)))
6017             to group)
6018         (if (not (or (null name)
6019                      (string-equal name "mail")
6020                      (string-equal name "posting")))
6021             (setq name (concat "*sent " name "*"))
6022           (message-narrow-to-headers)
6023           (setq to (message-fetch-field "to"))
6024           (setq group (message-fetch-field "newsgroups"))
6025           (widen)
6026           (setq name
6027                 (cond
6028                  (to (concat "*sent mail to "
6029                              (or (car (std11-extract-address-components to))
6030                                  to) "*"))
6031                  ((and group (not (string= group "")))
6032                   (concat "*sent posting on " group "*"))
6033                  (t "*sent mail*"))))
6034         (unless (string-equal name (buffer-name))
6035           (rename-buffer name t)))))
6036   ;; Push the current buffer onto the list.
6037   (when message-max-buffers
6038     (setq message-buffer-list
6039           (nconc message-buffer-list (list (current-buffer))))))
6040
6041 (defun message-mail-user-agent ()
6042   (let ((mua (cond
6043               ((not message-mail-user-agent) nil)
6044               ((eq message-mail-user-agent t) mail-user-agent)
6045               (t message-mail-user-agent))))
6046     (if (memq mua '(message-user-agent gnus-user-agent))
6047         nil
6048       mua)))
6049
6050 (defun message-setup (headers &optional replybuffer actions switch-function)
6051   (let ((mua (message-mail-user-agent))
6052         subject to field yank-action)
6053     (if (not (and message-this-is-mail mua))
6054         (message-setup-1 headers replybuffer actions)
6055       (if replybuffer
6056           (setq yank-action (list 'insert-buffer replybuffer)))
6057       (setq headers (copy-sequence headers))
6058       (setq field (assq 'Subject headers))
6059       (when field
6060         (setq subject (cdr field))
6061         (setq headers (delq field headers)))
6062       (setq field (assq 'To headers))
6063       (when field
6064         (setq to (cdr field))
6065         (setq headers (delq field headers)))
6066       (let ((mail-user-agent mua))
6067         (compose-mail to subject
6068                       (mapcar (lambda (item)
6069                                 (cons
6070                                  (format "%s" (car item))
6071                                  (cdr item)))
6072                               headers)
6073                       nil switch-function yank-action actions)))))
6074
6075 (defun message-headers-to-generate (headers included-headers excluded-headers)
6076   "Return a list that includes all headers from HEADERS.
6077 If INCLUDED-HEADERS is a list, just include those headers.  If if is
6078 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
6079 are not included."
6080   (let ((result nil)
6081         header-name)
6082     (dolist (header headers)
6083       (setq header-name (cond
6084                          ((and (consp header)
6085                                (eq (car header) 'optional))
6086                           ;; On the form (optional . Header)
6087                           (cdr header))
6088                          ((consp header)
6089                           ;; On the form (Header . function)
6090                           (car header))
6091                          (t
6092                           ;; Just a Header.
6093                           header)))
6094       (when (and (not (memq header-name excluded-headers))
6095                  (or (eq included-headers t)
6096                      (memq header-name included-headers)))
6097         (push header result)))
6098     (nreverse result)))
6099
6100 (defun message-setup-1 (headers &optional replybuffer actions)
6101   (dolist (action actions)
6102     (condition-case nil
6103         (add-to-list 'message-send-actions
6104                      `(apply ',(car action) ',(cdr action)))))
6105   (setq message-reply-buffer
6106         (or (message-get-parameter 'reply-buffer)
6107             replybuffer))
6108   (goto-char (point-min))
6109   ;; Insert all the headers.
6110   (mail-header-format
6111    (let ((h headers)
6112          (alist message-header-format-alist))
6113      (while h
6114        (unless (assq (caar h) message-header-format-alist)
6115          (push (list (caar h)) alist))
6116        (pop h))
6117      alist)
6118    headers)
6119   (delete-region (point) (progn (forward-line -1) (point)))
6120   (when message-default-headers
6121     (insert message-default-headers)
6122     (or (bolp) (insert ?\n)))
6123   (insert mail-header-separator "\n")
6124   (forward-line -1)
6125   (when (message-news-p)
6126     (when message-default-news-headers
6127       (insert message-default-news-headers)
6128       (or (bolp) (insert ?\n)))
6129     (when message-generate-headers-first
6130       (message-generate-headers
6131        (message-headers-to-generate
6132         (append message-required-news-headers
6133                 message-required-headers)
6134         message-generate-headers-first
6135         '(Lines Subject)))))
6136   (when (message-mail-p)
6137     (when message-default-mail-headers
6138       (insert message-default-mail-headers)
6139       (or (bolp) (insert ?\n)))
6140     (save-restriction
6141       (message-narrow-to-headers)
6142       (if (and replybuffer
6143                message-alternative-emails)
6144           (message-use-alternative-email-as-from)))
6145     (when message-generate-headers-first
6146       (message-generate-headers
6147        (message-headers-to-generate
6148         (append message-required-mail-headers
6149                 message-required-headers)
6150         message-generate-headers-first
6151         '(Lines Subject)))))
6152   (run-hooks 'message-signature-setup-hook)
6153   (message-insert-signature)
6154   (save-restriction
6155     (message-narrow-to-headers)
6156     (run-hooks 'message-header-setup-hook))
6157   (set-buffer-modified-p nil)
6158   (setq buffer-undo-list nil)
6159   (run-hooks 'message-setup-hook)
6160   (message-position-point)
6161   (undo-boundary))
6162
6163 (defun message-set-auto-save-file-name ()
6164   "Associate the message buffer with a file in the drafts directory."
6165   (when message-auto-save-directory
6166     (unless (file-directory-p
6167              (directory-file-name message-auto-save-directory))
6168       (make-directory message-auto-save-directory t))
6169     (if (gnus-alive-p)
6170         (setq message-draft-article
6171               (nndraft-request-associate-buffer "drafts"))
6172       (setq buffer-file-name (expand-file-name
6173                               (if (memq system-type
6174                                         '(ms-dos ms-windows windows-nt
6175                                                  cygwin cygwin32 win32 w32
6176                                                  mswindows))
6177                                   "message"
6178                                 "*message*")
6179                               message-auto-save-directory))
6180       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6181     (clear-visited-file-modtime)
6182     (setq buffer-file-coding-system message-draft-coding-system)))
6183
6184 (defun message-disassociate-draft ()
6185   "Disassociate the message buffer from the drafts directory."
6186   (when message-draft-article
6187     (nndraft-request-expire-articles
6188      (list message-draft-article) "drafts" nil t)))
6189
6190 (defun message-insert-headers ()
6191   "Generate the headers for the article."
6192   (interactive)
6193   (save-excursion
6194     (save-restriction
6195       (message-narrow-to-headers)
6196       (when (message-news-p)
6197         (message-generate-headers
6198          (delq 'Lines
6199                (delq 'Subject
6200                      (copy-sequence message-required-news-headers)))))
6201       (when (message-mail-p)
6202         (message-generate-headers
6203          (delq 'Lines
6204                (delq 'Subject
6205                      (copy-sequence message-required-mail-headers))))))))
6206
6207 \f
6208
6209 ;;;
6210 ;;; Commands for interfacing with message
6211 ;;;
6212
6213 ;;;###autoload
6214 (defun message-mail (&optional to subject
6215                                other-headers continue switch-function
6216                                yank-action send-actions)
6217   "Start editing a mail message to be sent.
6218 OTHER-HEADERS is an alist of header/value pairs."
6219   (interactive)
6220   (let ((message-this-is-mail t) replybuffer)
6221     (unless (message-mail-user-agent)
6222       (message-pop-to-buffer (message-buffer-name "mail" to)))
6223     ;; FIXME: message-mail should do something if YANK-ACTION is not
6224     ;; insert-buffer.
6225     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
6226          (setq replybuffer (nth 1 yank-action)))
6227     (message-setup
6228      (nconc
6229       `((To . ,(or to "")) (Subject . ,(or subject "")))
6230       (when other-headers other-headers))
6231      replybuffer send-actions)
6232     ;; FIXME: Should return nil if failure.
6233     t))
6234
6235 ;;;###autoload
6236 (defun message-news (&optional newsgroups subject)
6237   "Start editing a news article to be sent."
6238   (interactive)
6239   (let ((message-this-is-news t))
6240     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6241     (message-setup `((Newsgroups . ,(or newsgroups ""))
6242                      (Subject . ,(or subject ""))))))
6243
6244 (defun message-get-reply-headers (wide &optional to-address address-headers)
6245   (let (follow-to mct never-mct to cc author mft recipients)
6246     ;; Find all relevant headers we need.
6247     (save-restriction
6248       (message-narrow-to-headers-or-head)
6249       (let ((mrt (when message-use-mail-reply-to
6250                    (message-fetch-field "mail-reply-to")))
6251             (reply-to (message-fetch-field "reply-to")))
6252         ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
6253         ;; message-header-synonyms.
6254         (setq to (or (message-fetch-field "to")
6255                      (and (loop for synonym in message-header-synonyms
6256                             when (memq 'Original-To synonym)
6257                             return t)
6258                           (message-fetch-field "original-to")))
6259               cc (message-fetch-field "cc")
6260               mct (when message-use-mail-copies-to
6261                     (message-fetch-field "mail-copies-to"))
6262               author (or mrt
6263                          reply-to
6264                          (message-fetch-field "from")
6265                          "")
6266               mft (when (and (not (or to-address mrt reply-to))
6267                              message-use-mail-followup-to)
6268                     (message-fetch-field "mail-followup-to")))))
6269
6270     (save-match-data
6271       ;; Handle special values of Mail-Copies-To.
6272       (when mct
6273         (cond ((or (equal (downcase mct) "never")
6274                    (equal (downcase mct) "nobody"))
6275                (when (or (not (eq message-use-mail-copies-to 'ask))
6276                          (message-y-or-n-p
6277                           (concat "Obey Mail-Copies-To: never? ") t "\
6278 You should normally obey the Mail-Copies-To: header.
6279
6280         `Mail-Copies-To: " mct "'
6281 directs you not to send your response to the author."))
6282                  (setq never-mct t))
6283                (setq mct nil))
6284               ((or (equal (downcase mct) "always")
6285                    (equal (downcase mct) "poster"))
6286                (if (or (not (eq message-use-mail-copies-to 'ask))
6287                        (message-y-or-n-p
6288                         (concat "Obey Mail-Copies-To: always? ") t "\
6289 You should normally obey the Mail-Copies-To: header.
6290
6291         `Mail-Copies-To: " mct "'
6292 sends a copy of your response to the author."))
6293                    (setq mct author)
6294                  (setq mct nil)))
6295               ((and (eq message-use-mail-copies-to 'ask)
6296                     (not (message-y-or-n-p
6297                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6298 You should normally obey the Mail-Copies-To: header.
6299
6300         `Mail-Copies-To: " mct "'
6301 sends a copy of your response to " (if (string-match "," mct)
6302                                        "the specified addresses"
6303                                      "that address") ".")))
6304                (setq mct nil))))
6305
6306       ;; Build (textual) list of new recipient addresses.
6307       (cond
6308        ((not wide)
6309         (setq recipients (concat ", " author)))
6310        (address-headers
6311         (dolist (header address-headers)
6312           (let ((value (message-fetch-field header)))
6313             (when value
6314               (setq recipients (concat recipients ", " value))))))
6315        ((and mft
6316              (string-match "[^ \t,]" mft)
6317              (or (not (eq message-use-mail-followup-to 'ask))
6318                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6319 You should normally obey the Mail-Followup-To: header.  In this
6320 article, it has the value of
6321
6322 " mft "
6323
6324 which directs your response to " (if (string-match "," mft)
6325                                      "the specified addresses"
6326                                    "that address only") ".
6327
6328 Most commonly, Mail-Followup-To is used by a mailing list poster to
6329 express that responses should be sent to just the list, and not the
6330 poster as well.
6331
6332 If a message is posted to several mailing lists, Mail-Followup-To may
6333 also be used to direct the following discussion to one list only,
6334 because discussions that are spread over several lists tend to be
6335 fragmented and very difficult to follow.
6336
6337 Also, some source/announcement lists are not intended for discussion;
6338 responses here are directed to other addresses.")))
6339         (setq recipients (concat ", " mft)))
6340        (to-address
6341         (setq recipients (concat ", " to-address))
6342         ;; If the author explicitly asked for a copy, we don't deny it to them.
6343         (if mct (setq recipients (concat recipients ", " mct))))
6344        (t
6345         (setq recipients (if never-mct "" (concat ", " author)))
6346         (if to  (setq recipients (concat recipients ", " to)))
6347         (if cc  (setq recipients (concat recipients ", " cc)))
6348         (if mct (setq recipients (concat recipients ", " mct)))))
6349       (if (>= (length recipients) 2)
6350           ;; Strip the leading ", ".
6351           (setq recipients (substring recipients 2)))
6352       ;; Squeeze whitespace.
6353       (while (string-match "[ \t][ \t]+" recipients)
6354         (setq recipients (replace-match " " t t recipients)))
6355       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6356       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
6357         (setq recipients (rmail-dont-reply-to recipients)))
6358       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6359       (if (string-equal recipients "")
6360           (setq recipients author))
6361       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6362       (setq recipients
6363             (mapcar
6364              (lambda (addr)
6365                (cons (downcase (mail-strip-quoted-names addr)) addr))
6366              (message-tokenize-header recipients)))
6367       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6368       (let ((s recipients))
6369         (while s
6370           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6371
6372       ;; Remove hierarchical lists that are contained within each other,
6373       ;; if message-hierarchical-addresses is defined.
6374       (when message-hierarchical-addresses
6375         (let ((plain-addrs (mapcar 'car recipients))
6376               subaddrs recip)
6377           (while plain-addrs
6378             (setq subaddrs (assoc (car plain-addrs)
6379                                   message-hierarchical-addresses)
6380                   plain-addrs (cdr plain-addrs))
6381             (when subaddrs
6382               (setq subaddrs (cdr subaddrs))
6383               (while subaddrs
6384                 (setq recip (assoc (car subaddrs) recipients)
6385                       subaddrs (cdr subaddrs))
6386                 (if recip
6387                     (setq recipients (delq recip recipients))))))))
6388
6389       ;; Build the header alist.  Allow the user to be asked whether
6390       ;; or not to reply to all recipients in a wide reply.
6391       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6392       (when (and recipients
6393                  (or (not message-wide-reply-confirm-recipients)
6394                      (y-or-n-p "Reply to all recipients? ")))
6395         (setq recipients (mapconcat
6396                           (lambda (addr) (cdr addr)) recipients ", "))
6397         (if (string-match "^ +" recipients)
6398             (setq recipients (substring recipients (match-end 0))))
6399         (push (cons 'Cc recipients) follow-to)))
6400     follow-to))
6401
6402 ;;;###autoload
6403 (defun message-reply (&optional to-address wide)
6404   "Start editing a reply to the article in the current buffer."
6405   (interactive)
6406   (require 'gnus-sum)                   ; for gnus-list-identifiers
6407   (let ((cur (current-buffer))
6408         from subject date
6409         references message-id follow-to
6410         (inhibit-point-motion-hooks t)
6411         (message-this-is-mail t)
6412         gnus-warning in-reply-to)
6413     (save-restriction
6414       (message-narrow-to-head-1)
6415       ;; Allow customizations to have their say.
6416       (if (not wide)
6417           ;; This is a regular reply.
6418           (when (functionp message-reply-to-function)
6419             (save-excursion
6420               (setq follow-to (funcall message-reply-to-function))))
6421         ;; This is a followup.
6422         (when (functionp message-wide-reply-to-function)
6423           (save-excursion
6424             (setq follow-to
6425                   (funcall message-wide-reply-to-function)))))
6426       (setq message-id (message-fetch-field "message-id" t)
6427             references (message-fetch-field "references")
6428             date (message-fetch-field "date")
6429             from (message-fetch-field "from")
6430             subject (or (message-fetch-field "subject") "none"))
6431       (when gnus-list-identifiers
6432         (setq subject (message-strip-list-identifiers subject)))
6433       (setq subject (message-make-followup-subject subject))
6434       (when message-subject-trailing-was-query
6435         (setq subject (message-strip-subject-trailing-was subject)))
6436
6437       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6438                  (string-match "<[^>]+>" gnus-warning))
6439         (setq message-id (match-string 0 gnus-warning)))
6440
6441       (unless follow-to
6442         (setq follow-to (message-get-reply-headers wide to-address)))
6443
6444       ;; Get the references from "In-Reply-To" field if there were
6445       ;; no references and "In-Reply-To" field looks promising.
6446       (unless references
6447         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
6448                    (string-match "<[^>]+>" in-reply-to))
6449           (setq references (match-string 0 in-reply-to)))))
6450
6451     (unless (message-mail-user-agent)
6452       (message-pop-to-buffer
6453        (message-buffer-name
6454         (if wide "wide reply" "reply") from
6455         (if wide to-address nil))))
6456
6457     (setq message-reply-headers
6458           (make-full-mail-header-from-decoded-header
6459            0 subject from date message-id references 0 0 ""))
6460
6461     (message-setup
6462      `((Subject . ,subject)
6463        ,@follow-to)
6464      cur)))
6465
6466 ;;;###autoload
6467 (defun message-wide-reply (&optional to-address)
6468   "Make a \"wide\" reply to the message in the current buffer."
6469   (interactive)
6470   (message-reply to-address t))
6471
6472 ;;;###autoload
6473 (defun message-followup (&optional to-newsgroups)
6474   "Follow up to the message in the current buffer.
6475 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6476   (interactive)
6477   (require 'gnus-sum)                   ; for gnus-list-identifiers
6478   (let ((cur (current-buffer))
6479         from subject date reply-to mrt mct mft
6480         references message-id follow-to
6481         (inhibit-point-motion-hooks t)
6482         (message-this-is-news t)
6483         followup-to distribution newsgroups gnus-warning posted-to)
6484     (save-restriction
6485       (message-narrow-to-head)
6486       (when (functionp message-followup-to-function)
6487         (setq follow-to
6488               (funcall message-followup-to-function)))
6489       (setq from (message-fetch-field "from")
6490             date (message-fetch-field "date")
6491             subject (or (message-fetch-field "subject") "none")
6492             references (message-fetch-field "references")
6493             message-id (message-fetch-field "message-id" t)
6494             followup-to (message-fetch-field "followup-to")
6495             newsgroups (message-fetch-field "newsgroups")
6496             posted-to (message-fetch-field "posted-to")
6497             reply-to (message-fetch-field "reply-to")
6498             mrt (when message-use-mail-reply-to
6499                   (message-fetch-field "mail-reply-to"))
6500             distribution (message-fetch-field "distribution")
6501             mct (when message-use-mail-copies-to
6502                   (message-fetch-field "mail-copies-to"))
6503             mft (when message-use-mail-followup-to
6504                   (message-fetch-field "mail-followup-to")))
6505       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6506                  (string-match "<[^>]+>" gnus-warning))
6507         (setq message-id (match-string 0 gnus-warning)))
6508       ;; Remove bogus distribution.
6509       (when (and (stringp distribution)
6510                  (let ((case-fold-search t))
6511                    (string-match "world" distribution)))
6512         (setq distribution nil))
6513       (if gnus-list-identifiers
6514           (setq subject (message-strip-list-identifiers subject)))
6515       (setq subject (message-make-followup-subject subject))
6516       (when message-subject-trailing-was-query
6517         (setq subject (message-strip-subject-trailing-was subject)))
6518       (widen))
6519
6520     ;; Handle special values of Mail-Copies-To.
6521     (when mct
6522       (cond
6523        ((and (or (equal (downcase mct) "never")
6524                  (equal (downcase mct) "nobody")))
6525         (setq mct nil))
6526        ((and (or (equal (downcase mct) "always")
6527                  (equal (downcase mct) "poster")))
6528         (if (or (not (eq message-use-mail-copies-to 'ask))
6529                 (message-y-or-n-p
6530                  (concat "Obey Mail-Copies-To: always? ") t "\
6531 You should normally obey the Mail-Copies-To: header.
6532
6533         `Mail-Copies-To: " mct "'
6534 sends a copy of your response to the author."))
6535             (setq mct (or mrt reply-to from))
6536           (setq mct nil)))
6537        ((and (eq message-use-mail-copies-to 'ask)
6538              (not
6539               (message-y-or-n-p
6540                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6541 You should normally obey the Mail-Copies-To: header.
6542
6543         `Mail-Copies-To: " mct "'
6544 sends a copy of your response to " (if (string-match "," mct)
6545                                        "the specified addresses"
6546                                      "that address") ".")))
6547         (setq mct nil))))
6548
6549     (unless follow-to
6550       (cond
6551        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
6552        ;; Handle Followup-To.
6553        (followup-to
6554         (cond
6555          ((equal (downcase followup-to) "poster")
6556           (if (or (and followup-to (eq message-use-followup-to 'use))
6557                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
6558 You should normally obey the Followup-To: header.
6559
6560         `Followup-To: poster'
6561 sends your response via e-mail instead of news.
6562
6563 A typical situation where `Followup-To: poster' is used is when the author
6564 does not read the newsgroup, so he wouldn't see any replies sent to it."))
6565               (setq message-this-is-news nil
6566                     distribution nil
6567                     follow-to (list (cons 'To (or mrt reply-to from ""))))
6568             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
6569          (t
6570           (if (or (equal followup-to newsgroups)
6571                   (not (and followup-to (eq message-use-followup-to 'ask)))
6572                   (message-y-or-n-p
6573                    (concat "Obey Followup-To: " followup-to "? ") t "\
6574 You should normally obey the Followup-To: header.
6575
6576         `Followup-To: " followup-to "'
6577 directs your response to " (if (string-match "," followup-to)
6578                                "the specified newsgroups"
6579                              "that newsgroup only") ".
6580
6581 If a message is posted to several newsgroups, Followup-To is often
6582 used to direct the following discussion to one newsgroup only,
6583 because discussions that are spread over several newsgroup tend to
6584 be fragmented and very difficult to follow.
6585
6586 Also, some source/announcement newsgroups are not intended for discussion;
6587 responses here are directed to other newsgroups."))
6588               (setq follow-to (list (cons 'Newsgroups followup-to)))
6589             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
6590        ;; Handle Mail-Followup-To, followup via e-mail.
6591        ((and mft
6592              (or (not (eq message-use-mail-followup-to 'ask))
6593                  (message-y-or-n-p
6594                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
6595 You should normally obey the Mail-Followup-To: header.
6596
6597         `Mail-Followup-To: " mft "'
6598 directs your response to " (if (string-match "," mft)
6599                                "the specified addresses"
6600                              "that address only") " instead of news.
6601
6602 A typical situation where Mail-Followup-To is used is when the author thinks
6603 that further discussion should take place only in "
6604                              (if (string-match "," mft)
6605                                  "the specified mailing lists"
6606                                "that mailing list") ".")))
6607         (setq message-this-is-news nil
6608               distribution nil
6609               follow-to (list (cons 'To mft))))
6610        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
6611        (t
6612         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
6613
6614     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6615
6616     (setq message-reply-headers
6617           (make-full-mail-header-from-decoded-header
6618            0 subject from date message-id references 0 0 ""))
6619
6620     (message-setup
6621      `((Subject . ,subject)
6622        ,@follow-to
6623        ,@(and mct (list (cons 'Cc mct)))
6624        ,@(and distribution (list (cons 'Distribution distribution))))
6625      cur)))
6626
6627 (defun message-is-yours-p ()
6628   "Non-nil means current article is yours.
6629 If you have added 'cancel-messages to 'message-shoot-gnksa-feet', all articles
6630 are yours except those that have Cancel-Lock header not belonging to you.
6631 Instead of shooting GNKSA feet, you should modify 'message-alternative-emails'
6632 regexp to match all of yours addresses."
6633   ;; Canlock-logic as suggested by Per Abrahamsen
6634   ;; <abraham@dina.kvl.dk>
6635   ;;
6636   ;; IF article has cancel-lock THEN
6637   ;;   IF we can verify it THEN
6638   ;;     issue cancel
6639   ;;   ELSE
6640   ;;     error: cancellock: article is not yours
6641   ;; ELSE
6642   ;;   Use old rules, comparing sender...
6643   (save-excursion
6644     (save-restriction
6645       (message-narrow-to-head-1)
6646       (if (message-fetch-field "Cancel-Lock")
6647           (if (null (canlock-verify))
6648               t
6649             (error "Failed to verify Cancel-lock: This article is not yours"))
6650         (let (sender from)
6651           (or
6652            (message-gnksa-enable-p 'cancel-messages)
6653            (and (setq sender (message-fetch-field "sender"))
6654                 (string-equal (downcase sender)
6655                               (downcase (message-make-sender))))
6656            ;; Email address in From field equals to our address
6657            (and (setq from (message-fetch-field "from"))
6658                 (string-equal
6659                  (downcase (cadr (std11-extract-address-components from)))
6660                  (downcase (cadr (std11-extract-address-components
6661                                   (message-make-from))))))
6662            ;; Email address in From field matches
6663            ;; 'message-alternative-emails' regexp
6664            (and from
6665                 message-alternative-emails
6666                 (string-match
6667                  message-alternative-emails
6668                  (cadr (std11-extract-address-components from))))))))))
6669
6670 ;;;###autoload
6671 (defun message-cancel-news (&optional arg)
6672   "Cancel an article you posted.
6673 If ARG, allow editing of the cancellation message."
6674   (interactive "P")
6675   (unless (message-news-p)
6676     (error "This is not a news article; canceling is impossible"))
6677   (let (from newsgroups message-id distribution buf)
6678     (save-excursion
6679       ;; Get header info from original article.
6680       (save-restriction
6681         (message-narrow-to-head-1)
6682         (setq from (message-fetch-field "from")
6683               newsgroups (message-fetch-field "newsgroups")
6684               message-id (message-fetch-field "message-id" t)
6685               distribution (message-fetch-field "distribution")))
6686       ;; Make sure that this article was written by the user.
6687       (unless (message-is-yours-p)
6688         (error "This article is not yours"))
6689       (when (yes-or-no-p "Do you really want to cancel this article? ")
6690         ;; Make control message.
6691         (if arg
6692             (message-news)
6693           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6694         (erase-buffer)
6695         (insert "Newsgroups: " newsgroups "\n"
6696                 "From: " from "\n"
6697                 "Subject: cmsg cancel " message-id "\n"
6698                 "Control: cancel " message-id "\n"
6699                 (if distribution
6700                     (concat "Distribution: " distribution "\n")
6701                   "")
6702                 mail-header-separator "\n"
6703                 message-cancel-message)
6704         (run-hooks 'message-cancel-hook)
6705         (unless arg
6706           (message "Canceling your article...")
6707           (if (let ((message-syntax-checks
6708                      'dont-check-for-anything-just-trust-me)
6709                     (message-encoding-buffer (current-buffer))
6710                     (message-edit-buffer (current-buffer)))
6711                 (message-send-news))
6712               (message "Canceling your article...done"))
6713           (kill-buffer buf))))))
6714
6715 (defun message-supersede-setup-for-mime-edit ()
6716   (set (make-local-variable 'message-setup-hook) nil)
6717   (mime-edit-again))
6718
6719 ;;;###autoload
6720 (defun message-supersede ()
6721   "Start composing a message to supersede the current message.
6722 This is done simply by taking the old article and adding a Supersedes
6723 header line with the old Message-ID."
6724   (interactive)
6725   (let ((cur (current-buffer)))
6726     ;; Check whether the user owns the article that is to be superseded.
6727     (unless (message-is-yours-p)
6728       (error "This article is not yours"))
6729     ;; Get a normal message buffer.
6730     (message-pop-to-buffer (message-buffer-name "supersede"))
6731     (insert-buffer-substring cur)
6732     (message-narrow-to-head-1)
6733     ;; Remove unwanted headers.
6734     (when message-ignored-supersedes-headers
6735       (message-remove-header message-ignored-supersedes-headers t))
6736     (goto-char (point-min))
6737     (if (not (re-search-forward "^Message-ID: " nil t))
6738         (error "No Message-ID in this article")
6739       (replace-match "Supersedes: " t t))
6740     (goto-char (point-max))
6741     (insert mail-header-separator)
6742     (widen)
6743     (when message-supersede-setup-function
6744       (funcall message-supersede-setup-function))
6745     (run-hooks 'message-supersede-setup-hook)
6746     (goto-char (point-min))
6747     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
6748
6749 ;;;###autoload
6750 (defun message-recover ()
6751   "Reread contents of current buffer from its last auto-save file."
6752   (interactive)
6753   (let ((file-name (make-auto-save-file-name)))
6754     (cond ((save-window-excursion
6755              (if (not (eq system-type 'vax-vms))
6756                  (with-output-to-temp-buffer "*Directory*"
6757                    (with-current-buffer standard-output
6758                      (fundamental-mode)) ; for Emacs 20.4+
6759                    (buffer-disable-undo standard-output)
6760                    (let ((default-directory "/"))
6761                      (call-process
6762                       "ls" nil standard-output nil "-l" file-name))))
6763              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6764            (let ((buffer-read-only nil))
6765              (erase-buffer)
6766              (insert-file-contents file-name nil)))
6767           (t (error "message-recover cancelled")))))
6768
6769 ;;; Washing Subject:
6770
6771 (defun message-wash-subject (subject)
6772   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6773 Previous forwarders, replyers, etc. may add it."
6774   (with-temp-buffer
6775     (insert subject)
6776     (goto-char (point-min))
6777     ;; strip Re/Fwd stuff off the beginning
6778     (while (re-search-forward
6779             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6780       (replace-match ""))
6781
6782     ;; and gnus-style forwards [foo@bar.com] subject
6783     (goto-char (point-min))
6784     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6785       (replace-match ""))
6786
6787     ;; and off the end
6788     (goto-char (point-max))
6789     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6790       (replace-match ""))
6791
6792     ;; and finally, any whitespace that was left-over
6793     (goto-char (point-min))
6794     (while (re-search-forward "^[ \t]+" nil t)
6795       (replace-match ""))
6796     (goto-char (point-max))
6797     (while (re-search-backward "[ \t]+$" nil t)
6798       (replace-match ""))
6799
6800     (buffer-string)))
6801
6802 ;;; Forwarding messages.
6803
6804 (defvar message-forward-decoded-p nil
6805   "Non-nil means the original message is decoded.")
6806
6807 (defun message-forward-subject-name-subject (subject)
6808   "Generate a SUBJECT for a forwarded message.
6809 The form is: [Source] Subject, where if the original message was mail,
6810 Source is the name of the sender, and if the original message was
6811 news, Source is the list of newsgroups is was posted to."
6812   (concat "["
6813           (let ((group (message-fetch-field "newsgroups"))
6814                 from)
6815             (if group
6816                 (gnus-group-decoded-name group)
6817               (or (and (setq from (message-fetch-field "from"))
6818                        (car (std11-extract-address-components
6819                              (nnheader-decode-from from))))
6820                   "(nowhere)")))
6821           "] " subject))
6822
6823 (defun message-forward-subject-author-subject (subject)
6824   "Generate a SUBJECT for a forwarded message.
6825 The form is: [Source] Subject, where if the original message was mail,
6826 Source is the sender, and if the original message was news, Source is
6827 the list of newsgroups is was posted to."
6828   (concat "["
6829           (let ((group (message-fetch-field "newsgroups"))
6830                 from)
6831             (if group
6832                 (gnus-group-decoded-name group)
6833               (if (setq from (message-fetch-field "from"))
6834                   (nnheader-decode-from from)
6835                 "(nowhere)")))
6836           "] " subject))
6837
6838 (defun message-forward-subject-fwd (subject)
6839   "Generate a SUBJECT for a forwarded message.
6840 The form is: Fwd: Subject, where Subject is the original subject of
6841 the message."
6842   (if (string-match "^Fwd: " subject)
6843       subject
6844     (concat "Fwd: " subject)))
6845
6846 (defun message-make-forward-subject ()
6847   "Return a Subject header suitable for the message in the current buffer."
6848   (save-excursion
6849     (save-restriction
6850       (message-narrow-to-head-1)
6851       (let ((funcs message-make-forward-subject-function)
6852             (subject (message-fetch-field "Subject")))
6853         (setq subject
6854               (if subject
6855                   (if message-forward-decoded-p
6856                       subject
6857                     (nnheader-decode-subject subject))
6858                 ""))
6859         (if message-wash-forwarded-subjects
6860             (setq subject (message-wash-subject subject)))
6861         ;; Make sure funcs is a list.
6862         (and funcs
6863              (not (listp funcs))
6864              (setq funcs (list funcs)))
6865         ;; Apply funcs in order, passing subject generated by previous
6866         ;; func to the next one.
6867         (while funcs
6868           (when (functionp (car funcs))
6869             (setq subject (funcall (car funcs) subject)))
6870           (setq funcs (cdr funcs)))
6871         subject))))
6872
6873 ;;;###autoload
6874 (defun message-forward (&optional news)
6875   "Forward the current message via mail.
6876 Optional NEWS will use news to forward instead of mail."
6877   (interactive "P")
6878   (let ((cur (current-buffer))
6879         (subject (message-make-forward-subject)))
6880     (if news
6881         (message-news nil subject)
6882       (message-mail nil subject))
6883     (message-forward-make-body cur)))
6884
6885 (defun message-forward-make-body-plain (forward-buffer)
6886   (insert
6887    "\n-------------------- Start of forwarded message --------------------\n")
6888   (let ((b (point)) e)
6889     (insert
6890      (with-temp-buffer
6891        (mm-disable-multibyte)
6892        (insert
6893         (with-current-buffer forward-buffer
6894           (mm-with-unibyte-current-buffer (buffer-string))))
6895        (mm-enable-multibyte)
6896        (mime-to-mml)
6897        (goto-char (point-min))
6898        (when (looking-at "From ")
6899          (replace-match "X-From-Line: "))
6900        (buffer-string)))
6901     (setq e (point))
6902     (insert
6903      "\n-------------------- End of forwarded message --------------------\n")
6904     (when (and (not current-prefix-arg)
6905                message-forward-ignored-headers)
6906       (save-restriction
6907         (narrow-to-region b e)
6908         (goto-char b)
6909         (narrow-to-region (point)
6910                           (or (search-forward "\n\n" nil t) (point)))
6911         (message-remove-header message-forward-ignored-headers t)))))
6912
6913 (defun message-forward-make-body-mime (forward-buffer)
6914   (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
6915   (let ((b (point)) e)
6916     (save-restriction
6917       (narrow-to-region (point) (point))
6918       (mml-insert-buffer forward-buffer)
6919       (goto-char (point-min))
6920       (when (looking-at "From ")
6921         (replace-match "X-From-Line: "))
6922       (goto-char (point-max)))
6923     (setq e (point))
6924     (insert "<#/part>\n")))
6925
6926 (defun message-forward-make-body-mml (forward-buffer)
6927   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
6928   (let ((b (point)) e)
6929     (if (not message-forward-decoded-p)
6930         (insert
6931          (with-temp-buffer
6932            (mm-disable-multibyte)
6933            (insert
6934             (with-current-buffer forward-buffer
6935               (mm-with-unibyte-current-buffer (buffer-string))))
6936            (mm-enable-multibyte)
6937            (mime-to-mml)
6938            (goto-char (point-min))
6939            (when (looking-at "From ")
6940              (replace-match "X-From-Line: "))
6941            (buffer-string)))
6942       (save-restriction
6943         (narrow-to-region (point) (point))
6944         (mml-insert-buffer forward-buffer)
6945         (goto-char (point-min))
6946         (when (looking-at "From ")
6947           (replace-match "X-From-Line: "))
6948         (goto-char (point-max))))
6949     (setq e (point))
6950     (insert "<#/mml>\n")
6951     (when (and (not current-prefix-arg)
6952                message-forward-ignored-headers)
6953       (save-restriction
6954         (narrow-to-region b e)
6955         (goto-char b)
6956         (narrow-to-region (point)
6957                           (or (search-forward "\n\n" nil t) (point)))
6958         (message-remove-header message-forward-ignored-headers t)))))
6959
6960 (defun message-forward-make-body-digest-plain (forward-buffer)
6961   (insert
6962    "\n-------------------- Start of forwarded message --------------------\n")
6963   (let ((b (point)) e)
6964     (mml-insert-buffer forward-buffer)
6965     (setq e (point))
6966     (insert
6967      "\n-------------------- End of forwarded message --------------------\n")))
6968
6969 (defun message-forward-make-body-digest-mime (forward-buffer)
6970   (insert "\n<#multipart type=digest>\n")
6971   (let ((b (point)) e)
6972     (insert-buffer-substring forward-buffer)
6973     (setq e (point))
6974     (insert "<#/multipart>\n")
6975     (save-restriction
6976       (narrow-to-region b e)
6977       (goto-char b)
6978       (narrow-to-region (point)
6979                         (or (search-forward "\n\n" nil t) (point)))
6980       (delete-region (point-min) (point-max)))))
6981
6982 (defun message-forward-make-body-digest (forward-buffer)
6983   (if message-forward-as-mime
6984       (message-forward-make-body-digest-mime forward-buffer)
6985     (message-forward-make-body-digest-plain forward-buffer)))
6986
6987 ;;;###autoload
6988 (defun message-forward-make-body (forward-buffer)
6989   ;; Put point where we want it before inserting the forwarded
6990   ;; message.
6991   ;; Note that this function definition for T-gnus is totally different
6992   ;; from the original Gnus."
6993   (if message-forward-before-signature
6994       (message-goto-body)
6995     (goto-char (point-max)))
6996   ;; Make sure we're at the start of the line.
6997   (unless (bolp)
6998     (insert "\n"))
6999   ;; Narrow to the area we are to insert.
7000   (narrow-to-region (point) (point))
7001   ;; Insert the separators and the forwarded buffer.
7002   (insert message-forward-start-separator)
7003   (let ((art-beg (point)))
7004     (insert-buffer-substring forward-buffer)
7005     (goto-char (point-max))
7006     (insert message-forward-end-separator)
7007     (set-text-properties (point-min) (point-max) nil)
7008     ;; Remove all unwanted headers.
7009     (goto-char art-beg)
7010     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
7011                                   (1- (point))
7012                                 (point)))
7013     (goto-char (point-min))
7014     (message-remove-header message-included-forward-headers t nil t)
7015     (widen)
7016     (message-position-point)))
7017
7018 ;;;###autoload
7019 (defun message-forward-rmail-make-body (forward-buffer)
7020   (save-window-excursion
7021     (set-buffer forward-buffer)
7022     (if (rmail-msg-is-pruned)
7023         (rmail-msg-restore-non-pruned-header)))
7024   (message-forward-make-body forward-buffer))
7025
7026 (eval-when-compile (defvar rmail-enable-mime-composing))
7027
7028 ;; Fixme: Should have defcustom.
7029 ;;;###autoload
7030 (defun message-insinuate-rmail ()
7031   "Let RMAIL use message to forward."
7032   (interactive)
7033   (setq rmail-enable-mime-composing t)
7034   (setq rmail-insert-mime-forwarded-message-function
7035         'message-forward-rmail-make-body))
7036
7037 ;;;###autoload
7038 (defun message-resend (address)
7039   "Resend the current article to ADDRESS."
7040   (interactive
7041    (list (message-read-from-minibuffer "Resend message to: ")))
7042   (message "Resending message to %s..." address)
7043   (save-excursion
7044     (let ((cur (current-buffer))
7045           beg)
7046       ;; We first set up a normal mail buffer.
7047       (unless (message-mail-user-agent)
7048         (set-buffer (get-buffer-create " *message resend*"))
7049         (erase-buffer))
7050       (let ((message-this-is-mail t)
7051             message-setup-hook)
7052         (message-setup `((To . ,address))))
7053       ;; Insert our usual headers.
7054       (message-generate-headers '(From Date To Message-ID))
7055       (message-narrow-to-headers)
7056       ;; Remove X-Draft-From header etc.
7057       (message-remove-header message-ignored-mail-headers t)
7058       ;; Rename them all to "Resent-*".
7059       (goto-char (point-min))
7060       (while (re-search-forward "^[A-Za-z]" nil t)
7061         (forward-char -1)
7062         (insert "Resent-"))
7063       (widen)
7064       (forward-line)
7065       (delete-region (point) (point-max))
7066       (setq beg (point))
7067       ;; Insert the message to be resent.
7068       (insert-buffer-substring cur)
7069       (goto-char (point-min))
7070       (search-forward "\n\n")
7071       (forward-char -1)
7072       (save-restriction
7073         (narrow-to-region beg (point))
7074         (message-remove-header message-ignored-resent-headers t)
7075         (goto-char (point-max)))
7076       (insert mail-header-separator)
7077       ;; Rename all old ("Also-")Resent headers.
7078       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
7079         (beginning-of-line)
7080         (insert "Also-"))
7081       ;; Quote any "From " lines at the beginning.
7082       (goto-char beg)
7083       (when (looking-at "From ")
7084         (replace-match "X-From-Line: "))
7085       ;; Send it.
7086       (let ((message-encoding-buffer (current-buffer))
7087             (message-edit-buffer (current-buffer))
7088             message-required-mail-headers)
7089         (message-send-mail))
7090       (kill-buffer (current-buffer)))
7091     (message "Resending message to %s...done" address)))
7092
7093 (defun message-bounce-setup-for-mime-edit ()
7094   (set (make-local-variable 'message-setup-hook) nil)
7095   (mime-edit-again))
7096
7097 ;;;###autoload
7098 (defun message-bounce ()
7099   "Re-mail the current message.
7100 This only makes sense if the current message is a bounce message that
7101 contains some mail you have written which has been bounced back to
7102 you."
7103   (interactive)
7104   (let ((cur (current-buffer))
7105         mime-boundary boundary)
7106     (message-pop-to-buffer (message-buffer-name "bounce"))
7107     (insert-buffer-substring cur)
7108     (undo-boundary)
7109     (message-narrow-to-head)
7110     (if (and (message-fetch-field "MIME-Version")
7111              (setq mime-boundary (message-fetch-field "Content-Type")))
7112         (if (string-match "boundary=\"\\([^\"]+\\)\"" mime-boundary)
7113             (setq mime-boundary (concat (regexp-quote
7114                                          (match-string 1 mime-boundary))
7115                                         " *\nContent-Type: message/rfc822"))
7116           (setq mime-boundary nil)))
7117     (widen)
7118     (goto-char (point-min))
7119     (re-search-forward "\n\n+" nil t)
7120     (setq boundary (point))
7121     ;; We remove everything before the bounced mail.
7122     (if (or (and mime-boundary
7123                  (re-search-forward mime-boundary nil t)
7124                  (forward-line 1))
7125             (re-search-forward message-unsent-separator nil t)
7126             (progn
7127               (search-forward "\n\n" nil 'move)
7128               (re-search-backward "^Return-Path:.*\n" boundary t)))
7129         (progn
7130           (forward-line 1)
7131           (delete-region (point-min)
7132                          (if (re-search-forward "^[^ \n\t]+:" nil t)
7133                              (match-beginning 0)
7134                            (point))))
7135       (when (re-search-backward "^.?From .*\n" nil t)
7136         (delete-region (match-beginning 0) (match-end 0))))
7137     (save-restriction
7138       (message-narrow-to-head-1)
7139       (message-remove-header message-ignored-bounced-headers t)
7140       (goto-char (point-max))
7141       (insert mail-header-separator))
7142     (when message-bounce-setup-function
7143       (funcall message-bounce-setup-function))
7144     (run-hooks 'message-bounce-setup-hook)
7145     (message-position-point)))
7146
7147 ;;;
7148 ;;; Interactive entry points for new message buffers.
7149 ;;;
7150
7151 ;;;###autoload
7152 (defun message-mail-other-window (&optional to subject)
7153   "Like `message-mail' command, but display mail buffer in another window."
7154   (interactive)
7155   (unless (message-mail-user-agent)
7156     (let ((pop-up-windows t)
7157           (special-display-buffer-names nil)
7158           (special-display-regexps nil)
7159           (same-window-buffer-names nil)
7160           (same-window-regexps nil))
7161       (message-pop-to-buffer (message-buffer-name "mail" to))))
7162   (let ((message-this-is-mail t))
7163     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7164                    nil nil 'switch-to-buffer-other-window)))
7165
7166 ;;;###autoload
7167 (defun message-mail-other-frame (&optional to subject)
7168   "Like `message-mail' command, but display mail buffer in another frame."
7169   (interactive)
7170   (unless (message-mail-user-agent)
7171     (let ((pop-up-frames t)
7172           (special-display-buffer-names nil)
7173           (special-display-regexps nil)
7174           (same-window-buffer-names nil)
7175           (same-window-regexps nil))
7176       (message-pop-to-buffer (message-buffer-name "mail" to))))
7177   (let ((message-this-is-mail t))
7178     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7179                    nil nil 'switch-to-buffer-other-frame)))
7180
7181 ;;;###autoload
7182 (defun message-news-other-window (&optional newsgroups subject)
7183   "Start editing a news article to be sent."
7184   (interactive)
7185   (let ((pop-up-windows t)
7186         (special-display-buffer-names nil)
7187         (special-display-regexps nil)
7188         (same-window-buffer-names nil)
7189         (same-window-regexps nil))
7190     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7191   (let ((message-this-is-news t))
7192     (message-setup `((Newsgroups . ,(or newsgroups ""))
7193                      (Subject . ,(or subject ""))))))
7194
7195 ;;;###autoload
7196 (defun message-news-other-frame (&optional newsgroups subject)
7197   "Start editing a news article to be sent."
7198   (interactive)
7199   (let ((pop-up-frames t)
7200         (special-display-buffer-names nil)
7201         (special-display-regexps nil)
7202         (same-window-buffer-names nil)
7203         (same-window-regexps nil))
7204     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7205   (let ((message-this-is-news t))
7206     (message-setup `((Newsgroups . ,(or newsgroups ""))
7207                      (Subject . ,(or subject ""))))))
7208
7209 ;;; underline.el
7210
7211 ;; This code should be moved to underline.el (from which it is stolen).
7212
7213 ;;;###autoload
7214 (defun bold-region (start end)
7215   "Bold all nonblank characters in the region.
7216 Works by overstriking characters.
7217 Called from program, takes two arguments START and END
7218 which specify the range to operate on."
7219   (interactive "r")
7220   (save-excursion
7221     (let ((end1 (make-marker)))
7222       (move-marker end1 (max start end))
7223       (goto-char (min start end))
7224       (while (< (point) end1)
7225         (or (looking-at "[_\^@- ]")
7226             (insert (char-after) "\b"))
7227         (forward-char 1)))))
7228
7229 ;;;###autoload
7230 (defun unbold-region (start end)
7231   "Remove all boldness (overstruck characters) in the region.
7232 Called from program, takes two arguments START and END
7233 which specify the range to operate on."
7234   (interactive "r")
7235   (save-excursion
7236     (let ((end1 (make-marker)))
7237       (move-marker end1 (max start end))
7238       (goto-char (min start end))
7239       (while (search-forward "\b" end1 t)
7240         (if (eq (char-after) (char-after (- (point) 2)))
7241             (delete-char -2))))))
7242
7243 (defun message-exchange-point-and-mark ()
7244   "Exchange point and mark, but don't activate region if it was inactive."
7245   (unless (prog1
7246               (message-mark-active-p)
7247             (exchange-point-and-mark))
7248     (setq mark-active nil)))
7249
7250 (defalias 'message-make-overlay 'make-overlay)
7251 (defalias 'message-delete-overlay 'delete-overlay)
7252 (defalias 'message-overlay-put 'overlay-put)
7253 (defun message-kill-all-overlays ()
7254   (if (featurep 'xemacs)
7255       (map-extents (lambda (extent ignore) (delete-extent extent)))
7256     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
7257
7258 ;; Support for toolbar
7259 (eval-when-compile
7260   (defvar tool-bar-map)
7261   (defvar tool-bar-mode))
7262
7263 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
7264   ;; We need to make tool bar entries in local keymaps with
7265   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
7266   (if (fboundp 'tool-bar-local-item-from-menu)
7267       ;; This is for Emacs 21.3
7268       (tool-bar-local-item-from-menu command icon in-map from-map props)
7269     (tool-bar-add-item-from-menu command icon from-map props)))
7270
7271 (defun message-tool-bar-map ()
7272   (or message-tool-bar-map
7273       (setq message-tool-bar-map
7274             (and
7275              (condition-case nil (require 'tool-bar) (error nil))
7276              (fboundp 'tool-bar-add-item-from-menu)
7277              tool-bar-mode
7278              (let ((tool-bar-map (copy-keymap tool-bar-map))
7279                    (load-path (mm-image-load-path)))
7280                ;; Zap some items which aren't so relevant and take
7281                ;; up space.
7282                (dolist (key '(print-buffer kill-buffer save-buffer
7283                                            write-file dired open-file))
7284                  (define-key tool-bar-map (vector key) nil))
7285                (message-tool-bar-local-item-from-menu
7286                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
7287                (message-tool-bar-local-item-from-menu
7288                 'message-kill-buffer "close" tool-bar-map message-mode-map)
7289                (message-tool-bar-local-item-from-menu
7290                 'message-dont-send "cancel" tool-bar-map message-mode-map)
7291 ;;             (message-tool-bar-local-item-from-menu
7292 ;;              'mime-edit-insert-file "attach"
7293 ;;              tool-bar-map mime-edit-mode-map)
7294                (message-tool-bar-local-item-from-menu
7295                 'ispell-message "spell" tool-bar-map message-mode-map)
7296 ;;             (message-tool-bar-local-item-from-menu
7297 ;;              'mime-edit-preview-message "preview"
7298 ;;              tool-bar-map mime-edit-mode-map)
7299                (message-tool-bar-local-item-from-menu
7300                 'message-insert-importance-high "important"
7301                 tool-bar-map message-mode-map)
7302                (message-tool-bar-local-item-from-menu
7303                 'message-insert-importance-low "unimportant"
7304                 tool-bar-map message-mode-map)
7305                (message-tool-bar-local-item-from-menu
7306                 'message-insert-disposition-notification-to "receipt"
7307                 tool-bar-map message-mode-map)
7308                tool-bar-map)))))
7309
7310 ;;; Group name completion.
7311
7312 (defcustom message-newgroups-header-regexp
7313   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7314   "Regexp that match headers that lists groups."
7315   :group 'message
7316   :type 'regexp)
7317
7318 (defcustom message-completion-alist
7319   (list (cons message-newgroups-header-regexp 'message-expand-group)
7320         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7321         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7322           . message-expand-name)
7323         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7324           . message-expand-name))
7325   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7326   :group 'message
7327   :type '(alist :key-type regexp :value-type function))
7328
7329 (defcustom message-expand-name-databases
7330   (list 'bbdb 'eudc 'lsdb)
7331   "List of databases to try for name completion (`message-expand-name').
7332 Each element is a symbol and can be `bbdb', `eudc' or `lsdb'."
7333   :group 'message
7334   :type '(set (const bbdb) (const eudc) (const lsdb)))
7335
7336 (defcustom message-expand-name-function
7337   (cond ((and (boundp 'eudc-protocol)
7338               eudc-protocol)
7339          'eudc-expand-inline)
7340         ((fboundp 'bbdb-complete-name)
7341          'bbdb-complete-name)
7342         ((fboundp 'lsdb-complete-name)
7343          'lsdb-complete-name)
7344         (t 'expand-abbrev))
7345   "*A function called to expand addresses in field body.
7346 This variable is semi-obsolete, set it as nil and use
7347 `message-expand-name-databases' instead."
7348   :group 'message
7349   :type '(radio (const :format "Invalidate it: %v\n" nil)
7350                 (function-item :format "eudc: %v\n" eudc-expand-inline)
7351                 (function-item :format "bbdb: %v\n" bbdb-complete-name)
7352                 (function-item :format "lsdb: %v\n" lsdb-complete-name)
7353                 (function :size 0 :value expand-abbrev)))
7354
7355 (defcustom message-tab-body-function nil
7356   "*Function to execute when `message-tab' (TAB) is executed in the body.
7357 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7358   :version "21.4"
7359   :group 'message
7360   :link '(custom-manual "(message)Various Commands")
7361   :type 'function)
7362
7363 (defun message-tab ()
7364   "Complete names according to `message-completion-alist'.
7365 Execute function specified by `message-tab-body-function' when not in
7366 those headers."
7367   (interactive)
7368   (let ((alist message-completion-alist))
7369     (while (and alist
7370                 (let ((mail-abbrev-mode-regexp (caar alist)))
7371                   (not (mail-abbrev-in-expansion-header-p))))
7372       (setq alist (cdr alist)))
7373     (funcall (or (cdar alist) message-tab-body-function
7374                  (lookup-key text-mode-map "\t")
7375                  (lookup-key global-map "\t")
7376                  'indent-relative))))
7377
7378 (defun message-expand-group ()
7379   "Expand the group name under point."
7380   (let* ((b (save-excursion
7381               (save-restriction
7382                 (narrow-to-region
7383                  (save-excursion
7384                    (beginning-of-line)
7385                    (skip-chars-forward "^:")
7386                    (1+ (point)))
7387                  (point))
7388                 (skip-chars-backward "^, \t\n") (point))))
7389          (completion-ignore-case t)
7390          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
7391                                             (point))))
7392          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
7393          (completions (all-completions string hashtb))
7394          comp)
7395     (delete-region b (point))
7396     (cond
7397      ((= (length completions) 1)
7398       (if (string= (car completions) string)
7399           (progn
7400             (insert string)
7401             (message "Only matching group"))
7402         (insert (car completions))))
7403      ((and (setq comp (try-completion string hashtb))
7404            (not (string= comp string)))
7405       (insert comp))
7406      (t
7407       (insert string)
7408       (if (not comp)
7409           (message "No matching groups")
7410         (save-selected-window
7411           (pop-to-buffer "*Completions*")
7412           (buffer-disable-undo)
7413           (let ((buffer-read-only nil))
7414             (erase-buffer)
7415             (let ((standard-output (current-buffer)))
7416               (display-completion-list (sort completions 'string<)))
7417             (goto-char (point-min))
7418             (delete-region (point) (progn (forward-line 3) (point))))))))))
7419
7420 (defun message-expand-name ()
7421   (cond (message-expand-name-function
7422          (funcall message-expand-name-function))
7423         ((and (memq 'eudc message-expand-name-databases)
7424               (boundp 'eudc-protocol)
7425               eudc-protocol)
7426          (eudc-expand-inline))
7427         ((and (memq 'bbdb message-expand-name-databases)
7428               (fboundp 'bbdb-complete-name))
7429          (bbdb-complete-name))
7430         ((and (memq 'lsdb message-expand-name-databases)
7431               (fboundp 'lsdb-complete-name))
7432          (lsdb-complete-name))
7433         (t 'expand-abbrev)))
7434
7435 ;;; Help stuff.
7436
7437 (defun message-talkative-question (ask question show &rest text)
7438   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7439 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7440 The following arguments may contain lists of values."
7441   (if (and show
7442            (setq text (message-flatten-list text)))
7443       (save-window-excursion
7444         (save-excursion
7445           (with-output-to-temp-buffer " *MESSAGE information message*"
7446             (set-buffer " *MESSAGE information message*")
7447             (fundamental-mode)          ; for Emacs 20.4+
7448             (mapcar 'princ text)
7449             (goto-char (point-min))))
7450         (funcall ask question))
7451     (funcall ask question)))
7452
7453 (defun message-flatten-list (list)
7454   "Return a new, flat list that contains all elements of LIST.
7455
7456 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7457 => (1 2 3 4 5 6 7)"
7458   (cond ((consp list)
7459          (apply 'append (mapcar 'message-flatten-list list)))
7460         (list
7461          (list list))))
7462
7463 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7464   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
7465 Then clone the local variables and values from the old buffer to the
7466 new one, cloning only the locals having a substring matching the
7467 regexp VARSTR."
7468   (let ((oldbuf (current-buffer)))
7469     (save-excursion
7470       (set-buffer (generate-new-buffer name))
7471       (message-clone-locals oldbuf varstr)
7472       (current-buffer))))
7473
7474 (defun message-clone-locals (buffer &optional varstr)
7475   "Clone the local variables from BUFFER to the current buffer."
7476   (let ((locals (save-excursion
7477                   (set-buffer buffer)
7478                   (buffer-local-variables)))
7479         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address\\|^user-full-name"))
7480     (mapcar
7481      (lambda (local)
7482        (when (and (consp local)
7483                   (car local)
7484                   (string-match regexp (symbol-name (car local)))
7485                   (or (null varstr)
7486                       (string-match varstr (symbol-name (car local)))))
7487          (ignore-errors
7488            (set (make-local-variable (car local))
7489                 (cdr local)))))
7490      locals)))
7491
7492 ;;; @ for MIME Edit mode
7493 ;;;
7494
7495 (defun message-maybe-encode ()
7496   (when message-mime-mode
7497     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
7498     (let ((pgp-processing (with-current-buffer message-edit-buffer
7499                             mime-edit-pgp-processing)))
7500       (setq mime-edit-pgp-processing pgp-processing))
7501     (run-hooks 'mime-edit-translate-hook)
7502     (if (catch 'mime-edit-error
7503           (save-excursion
7504             (mime-edit-pgp-enclose-buffer)
7505             (mime-edit-translate-body)))
7506         (error "Translation error!"))
7507     (run-hooks 'mime-edit-exit-hook)))
7508
7509 (defun message-mime-insert-article (&optional full-headers)
7510   (interactive "P")
7511   (let ((message-cite-function 'mime-edit-inserted-message-filter)
7512         (message-reply-buffer
7513          (message-get-parameter-with-eval 'original-buffer))
7514         (start (point)))
7515     (message-yank-original nil)
7516     (save-excursion
7517       (narrow-to-region (goto-char start)
7518                         (if (search-forward "\n\n" nil t)
7519                             (1- (point))
7520                           (point-max)))
7521       (goto-char (point-min))
7522       (let ((message-included-forward-headers
7523              (if full-headers "" message-included-forward-headers)))
7524         (message-remove-header message-included-forward-headers t nil t))
7525       (widen))))
7526
7527 (set-alist 'mime-edit-message-inserter-alist
7528            'message-mode (function message-mime-insert-article))
7529
7530 ;;;
7531 ;;; MIME functions
7532 ;;;
7533
7534 (defvar message-inhibit-body-encoding t)
7535
7536 (defun message-encode-message-body ()
7537   (unless message-inhibit-body-encoding
7538     (let ((mail-parse-charset (or mail-parse-charset
7539                                   message-default-charset))
7540           (case-fold-search t)
7541           lines content-type-p)
7542       (message-goto-body)
7543       (save-restriction
7544         (narrow-to-region (point) (point-max))
7545         (let ((new (mml-generate-mime)))
7546           (when new
7547             (delete-region (point-min) (point-max))
7548             (insert new)
7549             (goto-char (point-min))
7550             (if (eq (aref new 0) ?\n)
7551                 (delete-char 1)
7552               (search-forward "\n\n")
7553               (setq lines (buffer-substring (point-min) (1- (point))))
7554               (delete-region (point-min) (point))))))
7555       (save-restriction
7556         (message-narrow-to-headers-or-head)
7557         (message-remove-header "Mime-Version")
7558         (goto-char (point-max))
7559         (insert "MIME-Version: 1.0\n")
7560         (when lines
7561           (insert lines))
7562         (setq content-type-p
7563               (or mml-boundary
7564                   (re-search-backward "^Content-Type:" nil t))))
7565       (save-restriction
7566         (message-narrow-to-headers-or-head)
7567         (message-remove-first-header "Content-Type")
7568         (message-remove-first-header "Content-Transfer-Encoding"))
7569       ;; We always make sure that the message has a Content-Type
7570       ;; header.  This is because some broken MTAs and MUAs get
7571       ;; awfully confused when confronted with a message with a
7572       ;; MIME-Version header and without a Content-Type header.  For
7573       ;; instance, Solaris' /usr/bin/mail.
7574       (unless content-type-p
7575         (goto-char (point-min))
7576         ;; For unknown reason, MIME-Version doesn't exist.
7577         (when (re-search-forward "^MIME-Version:" nil t)
7578           (forward-line 1)
7579           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7580
7581 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7582   "Read from the minibuffer while providing abbrev expansion."
7583   (if (fboundp 'mail-abbrevs-setup)
7584       (let ((mail-abbrev-mode-regexp "")
7585             (minibuffer-setup-hook 'mail-abbrevs-setup)
7586             (minibuffer-local-map message-minibuffer-local-map))
7587         (read-from-minibuffer prompt initial-contents))
7588     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7589           (minibuffer-local-map message-minibuffer-local-map))
7590       (read-string prompt initial-contents))))
7591
7592 (defun message-use-alternative-email-as-from ()
7593   (require 'mail-utils)
7594   (let* ((fields '("To" "Cc"))
7595          (emails
7596           (split-string
7597            (mail-strip-quoted-names
7598             (mapconcat 'message-fetch-reply-field fields ","))
7599            "[ \f\t\n\r\v,]+"))
7600          email)
7601     (while emails
7602       (if (string-match message-alternative-emails (car emails))
7603           (setq email (car emails)
7604                 emails nil))
7605       (pop emails))
7606     (unless (or (not email) (equal email user-mail-address))
7607       (goto-char (point-max))
7608       (insert "From: " email "\n"))))
7609
7610 (defun message-options-get (symbol)
7611   (cdr (assq symbol message-options)))
7612
7613 (defun message-options-set (symbol value)
7614   (let ((the-cons (assq symbol message-options)))
7615     (if the-cons
7616         (if value
7617             (setcdr the-cons value)
7618           (setq message-options (delq the-cons message-options)))
7619       (and value
7620            (push (cons symbol value) message-options))))
7621   value)
7622
7623 (defun message-options-set-recipient ()
7624   (save-restriction
7625     (message-narrow-to-headers-or-head)
7626     (message-options-set 'message-sender
7627                          (mail-strip-quoted-names
7628                           (message-fetch-field "from")))
7629     (message-options-set 'message-recipients
7630                          (mail-strip-quoted-names
7631                           (let ((to (message-fetch-field "to"))
7632                                 (cc (message-fetch-field "cc"))
7633                                 (bcc (message-fetch-field "bcc")))
7634                             (concat
7635                              (or to "")
7636                              (if (and to cc) ", ")
7637                              (or cc "")
7638                              (if (and (or to cc) bcc) ", ")
7639                              (or bcc "")))))))
7640
7641 (defun message-hide-headers ()
7642   "Hide headers based on the `message-hidden-headers' variable."
7643   (let ((regexps (if (stringp message-hidden-headers)
7644                      (list message-hidden-headers)
7645                    message-hidden-headers))
7646         (inhibit-point-motion-hooks t)
7647         (after-change-functions nil))
7648     (when regexps
7649       (save-excursion
7650         (save-restriction
7651           (message-narrow-to-headers)
7652           (goto-char (point-min))
7653           (while (not (eobp))
7654             (if (not (message-hide-header-p regexps))
7655                 (message-next-header)
7656               (let ((begin (point)))
7657                 (message-next-header)
7658                 (add-text-properties
7659                  begin (point)
7660                  '(invisible t message-hidden t))))))))))
7661
7662 (defun message-hide-header-p (regexps)
7663   (let ((result nil)
7664         (reverse nil))
7665     (when (eq (car regexps) 'not)
7666       (setq reverse t)
7667       (pop regexps))
7668     (dolist (regexp regexps)
7669       (setq result (or result (looking-at regexp))))
7670     (if reverse
7671         (not result)
7672       result)))
7673
7674 (when (featurep 'xemacs)
7675   (require 'messagexmas)
7676   (message-xmas-redefine))
7677
7678 (provide 'message)
7679
7680 (run-hooks 'message-load-hook)
7681
7682 ;; Local Variables:
7683 ;; coding: iso-8859-1
7684 ;; End:
7685
7686 ;;; message.el ends here