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