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