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