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