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