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