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