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