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