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