(message-cite-original-without-signature)
[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     (mapc 'funcall functions)
3261     (when message-citation-line-function
3262       (unless (bolp)
3263         (insert "\n"))
3264       (funcall message-citation-line-function))))
3265
3266 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
3267 (defun message-cite-original ()
3268   "Cite function in the standard Message manner."
3269   (if (and (boundp 'mail-citation-hook)
3270            mail-citation-hook)
3271       (run-hooks 'mail-citation-hook)
3272     (let* ((start (point))
3273            (end (mark t))
3274            (x-no-archive nil)
3275            (functions
3276             (when message-indent-citation-function
3277               (if (listp message-indent-citation-function)
3278                   message-indent-citation-function
3279                 (list message-indent-citation-function))))
3280            ;; This function may be called by `gnus-summary-yank-message' and
3281            ;; may insert a different article from the original.  So, we will
3282            ;; modify the value of `message-reply-headers' with that article.
3283            (message-reply-headers
3284             (save-restriction
3285               (narrow-to-region start end)
3286               (message-narrow-to-head-1)
3287               (setq x-no-archive (message-fetch-field "x-no-archive"))
3288               (vector 0
3289                       (or (message-fetch-field "subject") "none")
3290                       (message-fetch-field "from")
3291                       (message-fetch-field "date")
3292                       (message-fetch-field "message-id" t)
3293                       (message-fetch-field "references")
3294                       0 0 ""))))
3295       (mml-quote-region start end)
3296       (goto-char start)
3297       (mapc 'funcall functions)
3298       (when message-citation-line-function
3299         (unless (bolp)
3300           (insert "\n"))
3301         (funcall message-citation-line-function))
3302       (when (and x-no-archive
3303                  (not message-cite-articles-with-x-no-archive)
3304                  (string-match "yes" x-no-archive))
3305         (undo-boundary)
3306         (delete-region (point) (mark t))
3307         (insert "> [Quoted text removed due to X-No-Archive]\n")
3308         (forward-line -1)))))
3309
3310 (defun message-insert-citation-line ()
3311   "Insert a simple citation line."
3312   (when message-reply-headers
3313     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3314
3315 (defun message-position-on-field (header &rest afters)
3316   (let ((case-fold-search t))
3317     (save-restriction
3318       (narrow-to-region
3319        (goto-char (point-min))
3320        (progn
3321          (re-search-forward
3322           (concat "^" (regexp-quote mail-header-separator) "$"))
3323          (match-beginning 0)))
3324       (goto-char (point-min))
3325       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3326           (progn
3327             (re-search-forward "^[^ \t]" nil 'move)
3328             (beginning-of-line)
3329             (skip-chars-backward "\n")
3330             t)
3331         (while (and afters
3332                     (not (re-search-forward
3333                           (concat "^" (regexp-quote (car afters)) ":")
3334                           nil t)))
3335           (pop afters))
3336         (when afters
3337           (re-search-forward "^[^ \t]" nil 'move)
3338           (beginning-of-line))
3339         (insert header ": \n")
3340         (forward-char -1)
3341         nil))))
3342
3343 (defun message-remove-signature ()
3344   "Remove the signature from the text between point and mark.
3345 The text will also be indented the normal way."
3346   (save-excursion
3347     (let ((start (point))
3348           mark)
3349       (if (not (re-search-forward message-signature-separator (mark t) t))
3350           ;; No signature here, so we just indent the cited text.
3351           (message-indent-citation)
3352         ;; Find the last non-empty line.
3353         (forward-line -1)
3354         (while (looking-at "[ \t]*$")
3355           (forward-line -1))
3356         (forward-line 1)
3357         (setq mark (set-marker (make-marker) (point)))
3358         (goto-char start)
3359         (message-indent-citation)
3360         ;; Enable undoing the deletion.
3361         (undo-boundary)
3362         (delete-region mark (mark t))
3363         (set-marker mark nil)))))
3364
3365 \f
3366
3367 ;;;
3368 ;;; Sending messages
3369 ;;;
3370
3371 (defun message-send-and-exit (&optional arg)
3372   "Send message like `message-send', then, if no errors, exit from mail buffer."
3373   (interactive "P")
3374   (let ((buf (current-buffer))
3375         (actions message-exit-actions))
3376     (when (and (message-send arg)
3377                (buffer-name buf))
3378       (if message-kill-buffer-on-exit
3379           (kill-buffer buf)
3380         (bury-buffer buf)
3381         (when (eq buf (current-buffer))
3382           (message-bury buf)))
3383       (message-do-actions actions)
3384       t)))
3385
3386 (defun message-dont-send ()
3387   "Don't send the message you have been editing.
3388 Instead, just auto-save the buffer and then bury it."
3389   (interactive)
3390   (set-buffer-modified-p t)
3391   (save-buffer)
3392   (let ((actions message-postpone-actions))
3393     (message-bury (current-buffer))
3394     (message-do-actions actions)))
3395
3396 (defun message-kill-buffer ()
3397   "Kill the current buffer."
3398   (interactive)
3399   (when (or (not (buffer-modified-p))
3400             (yes-or-no-p "Message modified; kill anyway? "))
3401     (let ((actions message-kill-actions)
3402           (draft-article message-draft-article)
3403           (auto-save-file-name buffer-auto-save-file-name)
3404           (file-name buffer-file-name)
3405           (modified (buffer-modified-p)))
3406       (setq buffer-file-name nil)
3407       (kill-buffer (current-buffer))
3408       (when (and (or (and auto-save-file-name
3409                           (file-exists-p auto-save-file-name))
3410                      (and file-name
3411                           (file-exists-p file-name)))
3412                (yes-or-no-p (format "Remove the backup file%s? "
3413                                     (if modified " too" ""))))
3414         (ignore-errors
3415           (delete-file auto-save-file-name))
3416         (let ((message-draft-article draft-article))
3417           (message-disassociate-draft)))
3418       (message-do-actions actions))))
3419
3420 (defun message-bury (buffer)
3421   "Bury this mail BUFFER."
3422   (let ((newbuf (other-buffer buffer)))
3423     (bury-buffer buffer)
3424     (if (and (fboundp 'frame-parameters)
3425              (cdr (assq 'dedicated (frame-parameters)))
3426              (not (null (delq (selected-frame) (visible-frame-list)))))
3427         (delete-frame (selected-frame))
3428       (switch-to-buffer newbuf))))
3429
3430 (defun message-send (&optional arg)
3431   "Send the message in the current buffer.
3432 If `message-interactive' is non-nil, wait for success indication or
3433 error messages, and inform user.
3434 Otherwise any failure is reported in a message back to the user from
3435 the mailer.
3436 The usage of ARG is defined by the instance that called Message.
3437 It should typically alter the sending method in some way or other."
3438   (interactive "P")
3439   ;; Make it possible to undo the coming changes.
3440   (undo-boundary)
3441   (let ((inhibit-read-only t))
3442     (put-text-property (point-min) (point-max) 'read-only nil))
3443   (message-fix-before-sending)
3444   (run-hooks 'message-send-hook)
3445   (message message-sending-message)
3446   (let ((alist message-send-method-alist)
3447         (success t)
3448         elem sent dont-barf-on-no-method
3449         (message-options message-options))
3450     (message-options-set-recipient)
3451     (while (and success
3452                 (setq elem (pop alist)))
3453       (when (funcall (cadr elem))
3454         (when (and (or (not (memq (car elem)
3455                                   message-sent-message-via))
3456                        (message-fetch-field "supersedes")
3457                        (if (or (message-gnksa-enable-p 'multiple-copies)
3458                                (not (eq (car elem) 'news)))
3459                            (y-or-n-p
3460                             (format
3461                              "Already sent message via %s; resend? "
3462                              (car elem)))
3463                          (error "Denied posting -- multiple copies")))
3464                    (setq success (funcall (caddr elem) arg)))
3465           (setq sent t))))
3466     (unless (or sent
3467                 (not success)
3468                 (let ((fcc (message-fetch-field "Fcc"))
3469                       (gcc (message-fetch-field "Gcc")))
3470                   (when (or fcc gcc)
3471                     (or (eq message-allow-no-recipients 'always)
3472                         (and (not (eq message-allow-no-recipients 'never))
3473                              (setq dont-barf-on-no-method
3474                                    (gnus-y-or-n-p
3475                                     (format "No receiver, perform %s anyway? "
3476                                             (cond ((and fcc gcc) "Fcc and Gcc")
3477                                                   (fcc "Fcc")
3478                                                   (t "Gcc"))))))))))
3479       (error "No methods specified to send by"))
3480     (when (or dont-barf-on-no-method
3481               (and success sent))
3482       (message-do-fcc)
3483       (save-excursion
3484         (run-hooks 'message-sent-hook))
3485       (message "Sending...done")
3486       ;; Mark the buffer as unmodified and delete auto-save.
3487       (set-buffer-modified-p nil)
3488       (delete-auto-save-file-if-necessary t)
3489       (message-disassociate-draft)
3490       ;; Delete other mail buffers and stuff.
3491       (message-do-send-housekeeping)
3492       (message-do-actions message-send-actions)
3493       ;; Return success.
3494       t)))
3495
3496 (defun message-send-via-mail (arg)
3497   "Send the current message via mail."
3498   (message-send-mail arg))
3499
3500 (defun message-send-via-news (arg)
3501   "Send the current message via news."
3502   (funcall message-send-news-function arg))
3503
3504 (defmacro message-check (type &rest forms)
3505   "Eval FORMS if TYPE is to be checked."
3506   `(or (message-check-element ,type)
3507        (save-excursion
3508          ,@forms)))
3509
3510 (put 'message-check 'lisp-indent-function 1)
3511 (put 'message-check 'edebug-form-spec '(form body))
3512
3513 (defun message-text-with-property (prop &optional start end reverse)
3514   "Return a list of start and end positions where the text has PROP.
3515 START and END bound the search, they default to `point-min' and
3516 `point-max' respectively.  If REVERSE is non-nil, find text which does
3517 not have PROP."
3518   (unless start
3519     (setq start (point-min)))
3520   (unless end
3521     (setq end (point-max)))
3522   (let (next regions)
3523     (if reverse
3524         (while (and start
3525                     (setq start (text-property-any start end prop nil)))
3526           (setq next (next-single-property-change start prop nil end))
3527           (push (cons start (or next end)) regions)
3528           (setq start next))
3529       (while (and start
3530                   (or (get-text-property start prop)
3531                       (and (setq start (next-single-property-change
3532                                         start prop nil end))
3533                            (get-text-property start prop))))
3534         (setq next (text-property-any start end prop nil))
3535         (push (cons start (or next end)) regions)
3536         (setq start next)))
3537     (nreverse regions)))
3538
3539 (defun message-fix-before-sending ()
3540   "Do various things to make the message nice before sending it."
3541   ;; Make sure there's a newline at the end of the message.
3542   (goto-char (point-max))
3543   (unless (bolp)
3544     (insert "\n"))
3545   ;; Make the hidden headers visible.
3546   (dolist (from-to (message-text-with-property 'message-hidden))
3547     (add-text-properties (car from-to) (cdr from-to)
3548                          '(invisible nil intangible nil)))
3549   ;; Make invisible text visible.
3550   ;; It doesn't seem as if this is useful, since the invisible property
3551   ;; is clobbered by an after-change hook anyhow.
3552   (message-check 'invisible-text
3553     (let ((regions (message-text-with-property 'invisible))
3554           from to)
3555       (when regions
3556         (while regions
3557           (setq from (caar regions)
3558                 to (cdar regions)
3559                 regions (cdr regions))
3560           (put-text-property from to 'invisible nil)
3561           (message-overlay-put (message-make-overlay from to)
3562                                'face 'highlight))
3563         (unless (yes-or-no-p
3564                  "Invisible text found and made visible; continue sending? ")
3565           (error "Invisible text found and made visible")))))
3566   (message-check 'illegible-text
3567     (let (found choice)
3568       (message-goto-body)
3569       (skip-chars-forward mm-7bit-chars)
3570       (while (not (eobp))
3571         (when (let ((char (char-after)))
3572                 (or (< (mm-char-int char) 128)
3573                     (and (mm-multibyte-p)
3574                          (memq (char-charset char)
3575                                '(eight-bit-control eight-bit-graphic
3576                                                    control-1))
3577                          (not (get-text-property
3578                                (point) 'untranslated-utf-8)))))
3579           (message-overlay-put (message-make-overlay (point) (1+ (point)))
3580                                'face 'highlight)
3581           (setq found t))
3582         (forward-char)
3583         (skip-chars-forward mm-7bit-chars))
3584       (when found
3585         (setq choice
3586               (gnus-multiple-choice
3587                "Non-printable characters found.  Continue sending?"
3588                '((?d "Remove non-printable characters and send")
3589                  (?r "Replace non-printable characters with dots and send")
3590                  (?i "Ignore non-printable characters and send")
3591                  (?e "Continue editing"))))
3592         (if (eq choice ?e)
3593           (error "Non-printable characters"))
3594         (message-goto-body)
3595         (skip-chars-forward mm-7bit-chars)
3596         (while (not (eobp))
3597           (when (let ((char (char-after)))
3598                   (or (< (mm-char-int char) 128)
3599                       (and (mm-multibyte-p)
3600                            ;; Fixme: Wrong for Emacs 22 and for things
3601                            ;; like undecable utf-8.  Should at least
3602                            ;; use find-coding-systems-region.
3603                            (memq (char-charset char)
3604                                  '(eight-bit-control eight-bit-graphic
3605                                                      control-1))
3606                            (not (get-text-property
3607                                  (point) 'untranslated-utf-8)))))
3608             (if (eq choice ?i)
3609                 (message-kill-all-overlays)
3610               (delete-char 1)
3611               (when (eq choice ?r)
3612                 (insert "."))))
3613           (forward-char)
3614           (skip-chars-forward mm-7bit-chars))))))
3615
3616 (defun message-add-action (action &rest types)
3617   "Add ACTION to be performed when doing an exit of type TYPES."
3618   (while types
3619     (add-to-list (intern (format "message-%s-actions" (pop types)))
3620                  action)))
3621
3622 (defun message-delete-action (action &rest types)
3623   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3624   (let (var)
3625     (while types
3626       (set (setq var (intern (format "message-%s-actions" (pop types))))
3627            (delq action (symbol-value var))))))
3628
3629 (defun message-do-actions (actions)
3630   "Perform all actions in ACTIONS."
3631   ;; Now perform actions on successful sending.
3632   (dolist (action actions)
3633     (ignore-errors
3634       (cond
3635        ;; A simple function.
3636        ((functionp action)
3637         (funcall action))
3638        ;; Something to be evaled.
3639        (t
3640         (eval action))))))
3641
3642 (defun message-send-mail-partially ()
3643   "Send mail as message/partial."
3644   ;; replace the header delimiter with a blank line
3645   (goto-char (point-min))
3646   (re-search-forward
3647    (concat "^" (regexp-quote mail-header-separator) "\n"))
3648   (replace-match "\n")
3649   (run-hooks 'message-send-mail-hook)
3650   (let ((p (goto-char (point-min)))
3651         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3652         (curbuf (current-buffer))
3653         (id (message-make-message-id)) (n 1)
3654         plist total  header required-mail-headers)
3655     (while (not (eobp))
3656       (if (< (point-max) (+ p message-send-mail-partially-limit))
3657           (goto-char (point-max))
3658         (goto-char (+ p message-send-mail-partially-limit))
3659         (beginning-of-line)
3660         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3661       (push p plist)
3662       (setq p (point)))
3663     (setq total (length plist))
3664     (push (point-max) plist)
3665     (setq plist (nreverse plist))
3666     (unwind-protect
3667         (save-excursion
3668           (setq p (pop plist))
3669           (while plist
3670             (set-buffer curbuf)
3671             (copy-to-buffer tembuf p (car plist))
3672             (set-buffer tembuf)
3673             (goto-char (point-min))
3674             (if header
3675                 (progn
3676                   (goto-char (point-min))
3677                   (narrow-to-region (point) (point))
3678                   (insert header))
3679               (message-goto-eoh)
3680               (setq header (buffer-substring (point-min) (point)))
3681               (goto-char (point-min))
3682               (narrow-to-region (point) (point))
3683               (insert header)
3684               (message-remove-header "Mime-Version")
3685               (message-remove-header "Content-Type")
3686               (message-remove-header "Content-Transfer-Encoding")
3687               (message-remove-header "Message-ID")
3688               (message-remove-header "Lines")
3689               (goto-char (point-max))
3690               (insert "Mime-Version: 1.0\n")
3691               (setq header (buffer-string)))
3692             (goto-char (point-max))
3693             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3694                             id n total))
3695             (forward-char -1)
3696             (let ((mail-header-separator ""))
3697               (when (memq 'Message-ID message-required-mail-headers)
3698                 (insert "Message-ID: " (message-make-message-id) "\n"))
3699               (when (memq 'Lines message-required-mail-headers)
3700                 (insert "Lines: " (message-make-lines) "\n"))
3701               (message-goto-subject)
3702               (end-of-line)
3703               (insert (format " (%d/%d)" n total))
3704               (widen)
3705               (mm-with-unibyte-current-buffer
3706                 (funcall (or message-send-mail-real-function
3707                              message-send-mail-function))))
3708             (setq n (+ n 1))
3709             (setq p (pop plist))
3710             (erase-buffer)))
3711       (kill-buffer tembuf))))
3712
3713 (defun message-send-mail (&optional arg)
3714   (require 'mail-utils)
3715   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3716          (case-fold-search nil)
3717          (news (message-news-p))
3718          (mailbuf (current-buffer))
3719          (message-this-is-mail t)
3720          (message-posting-charset
3721           (if (fboundp 'gnus-setup-posting-charset)
3722               (gnus-setup-posting-charset nil)
3723             message-posting-charset))
3724          (headers message-required-mail-headers))
3725     (save-restriction
3726       (message-narrow-to-headers)
3727       ;; Generate the Mail-Followup-To header if the header is not there...
3728       (if (and (message-subscribed-p)
3729                (not (mail-fetch-field "mail-followup-to")))
3730           (setq headers
3731                 (cons
3732                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
3733                  message-required-mail-headers))
3734         ;; otherwise, delete the MFT header if the field is empty
3735         (when (equal "" (mail-fetch-field "mail-followup-to"))
3736           (message-remove-header "^Mail-Followup-To:")))
3737       ;; Insert some headers.
3738       (let ((message-deletable-headers
3739              (if news nil message-deletable-headers)))
3740         (message-generate-headers headers))
3741       ;; Let the user do all of the above.
3742       (run-hooks 'message-header-hook))
3743     (unwind-protect
3744         (save-excursion
3745           (set-buffer tembuf)
3746           (erase-buffer)
3747           ;; Avoid copying text props (except hard newlines).
3748           (insert (with-current-buffer mailbuf
3749                     (mml-buffer-substring-no-properties-except-hard-newlines
3750                      (point-min) (point-max))))
3751           ;; Remove some headers.
3752           (message-encode-message-body)
3753           (save-restriction
3754             (message-narrow-to-headers)
3755             ;; We (re)generate the Lines header.
3756             (when (memq 'Lines message-required-mail-headers)
3757               (message-generate-headers '(Lines)))
3758             ;; Remove some headers.
3759             (message-remove-header message-ignored-mail-headers t)
3760             (let ((mail-parse-charset message-default-charset))
3761               (mail-encode-encoded-word-buffer)))
3762           (goto-char (point-max))
3763           ;; require one newline at the end.
3764           (or (= (preceding-char) ?\n)
3765               (insert ?\n))
3766           (message-cleanup-headers)
3767           ;; FIXME: we're inserting the courtesy copy after encoding.
3768           ;; This is wrong if the courtesy copy string contains
3769           ;; non-ASCII characters. -- jh
3770           (when
3771               (save-restriction
3772                 (message-narrow-to-headers)
3773                 (and news
3774                      (or (message-fetch-field "cc")
3775                          (message-fetch-field "bcc")
3776                          (message-fetch-field "to"))
3777                      (let ((content-type (message-fetch-field
3778                                           "content-type")))
3779                        (and
3780                         (or
3781                          (not content-type)
3782                          (string= "text/plain"
3783                                   (car
3784                                    (mail-header-parse-content-type
3785                                     content-type))))
3786                         (not
3787                          (string= "base64"
3788                                   (message-fetch-field
3789                                    "content-transfer-encoding")))))))
3790             (message-insert-courtesy-copy))
3791           (if (or (not message-send-mail-partially-limit)
3792                   (< (buffer-size) message-send-mail-partially-limit)
3793                   (not (message-y-or-n-p
3794                         "The message size is too large, split? "
3795                         t
3796                         "\
3797 The message size, "
3798                         (/ (buffer-size) 1000) "KB, is too large.
3799
3800 Some mail gateways (MTA's) bounce large messages.  To avoid the
3801 problem, answer `y', and the message will be split into several
3802 smaller pieces, the size of each is about "
3803                         (/ message-send-mail-partially-limit 1000)
3804                         "KB except the last
3805 one.
3806
3807 However, some mail readers (MUA's) can't read split messages, i.e.,
3808 mails in message/partially format. Answer `n', and the message will be
3809 sent in one piece.
3810
3811 The size limit is controlled by `message-send-mail-partially-limit'.
3812 If you always want Gnus to send messages in one piece, set
3813 `message-send-mail-partially-limit' to nil.
3814 ")))
3815               (mm-with-unibyte-current-buffer
3816                 (message "Sending via mail...")
3817                 (funcall (or message-send-mail-real-function
3818                              message-send-mail-function)))
3819             (message-send-mail-partially)))
3820       (kill-buffer tembuf))
3821     (set-buffer mailbuf)
3822     (push 'mail message-sent-message-via)))
3823
3824 (defun message-send-mail-with-sendmail ()
3825   "Send off the prepared buffer with sendmail."
3826   (let ((errbuf (if message-interactive
3827                     (message-generate-new-buffer-clone-locals
3828                      " sendmail errors")
3829                   0))
3830         resend-to-addresses delimline)
3831     (unwind-protect
3832         (progn
3833           (let ((case-fold-search t))
3834             (save-restriction
3835               (message-narrow-to-headers)
3836               (setq resend-to-addresses (message-fetch-field "resent-to")))
3837             ;; Change header-delimiter to be what sendmail expects.
3838             (goto-char (point-min))
3839             (re-search-forward
3840              (concat "^" (regexp-quote mail-header-separator) "\n"))
3841             (replace-match "\n")
3842             (backward-char 1)
3843             (setq delimline (point-marker))
3844             (run-hooks 'message-send-mail-hook)
3845             ;; Insert an extra newline if we need it to work around
3846             ;; Sun's bug that swallows newlines.
3847             (goto-char (1+ delimline))
3848             (when (eval message-mailer-swallows-blank-line)
3849               (newline))
3850             (when message-interactive
3851               (with-current-buffer errbuf
3852                 (erase-buffer))))
3853           (let* ((default-directory "/")
3854                  (coding-system-for-write message-send-coding-system)
3855                  (cpr (apply
3856                        'call-process-region
3857                        (append
3858                         (list (point-min) (point-max)
3859                               (if (boundp 'sendmail-program)
3860                                   sendmail-program
3861                                 "/usr/lib/sendmail")
3862                               nil errbuf nil "-oi")
3863                         ;; Always specify who from,
3864                         ;; since some systems have broken sendmails.
3865                         ;; But some systems are more broken with -f, so
3866                         ;; we'll let users override this.
3867                         (if (null message-sendmail-f-is-evil)
3868                             (list "-f" (message-sendmail-envelope-from)))
3869                         ;; These mean "report errors by mail"
3870                         ;; and "deliver in background".
3871                         (if (null message-interactive) '("-oem" "-odb"))
3872                         ;; Get the addresses from the message
3873                         ;; unless this is a resend.
3874                         ;; We must not do that for a resend
3875                         ;; because we would find the original addresses.
3876                         ;; For a resend, include the specific addresses.
3877                         (if resend-to-addresses
3878                             (list resend-to-addresses)
3879                           '("-t"))))))
3880             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
3881               (error "Sending...failed with exit value %d" cpr)))
3882           (when message-interactive
3883             (save-excursion
3884               (set-buffer errbuf)
3885               (goto-char (point-min))
3886               (while (re-search-forward "\n+ *" nil t)
3887                 (replace-match "; "))
3888               (if (not (zerop (buffer-size)))
3889                   (error "Sending...failed to %s"
3890                          (buffer-string))))))
3891       (when (bufferp errbuf)
3892         (kill-buffer errbuf)))))
3893
3894 (defun message-send-mail-with-qmail ()
3895   "Pass the prepared message buffer to qmail-inject.
3896 Refer to the documentation for the variable `message-send-mail-function'
3897 to find out how to use this."
3898   ;; replace the header delimiter with a blank line
3899   (goto-char (point-min))
3900   (re-search-forward
3901    (concat "^" (regexp-quote mail-header-separator) "\n"))
3902   (replace-match "\n")
3903   (run-hooks 'message-send-mail-hook)
3904   ;; send the message
3905   (case
3906       (let ((coding-system-for-write message-send-coding-system))
3907         (apply
3908          'call-process-region (point-min) (point-max)
3909          message-qmail-inject-program nil nil nil
3910          ;; qmail-inject's default behaviour is to look for addresses on the
3911          ;; command line; if there're none, it scans the headers.
3912          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3913          ;;
3914          ;; in general, ALL of qmail-inject's defaults are perfect for simply
3915          ;; reading a formatted (i. e., at least a To: or Resent-To header)
3916          ;; message from stdin.
3917          ;;
3918          ;; qmail also has the advantage of not having been raped by
3919          ;; various vendors, so we don't have to allow for that, either --
3920          ;; compare this with message-send-mail-with-sendmail and weep
3921          ;; for sendmail's lost innocence.
3922          ;;
3923          ;; all this is way cool coz it lets us keep the arguments entirely
3924          ;; free for -inject-arguments -- a big win for the user and for us
3925          ;; since we don't have to play that double-guessing game and the user
3926          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3927          (if (functionp message-qmail-inject-args)
3928              (funcall message-qmail-inject-args)
3929            message-qmail-inject-args)))
3930     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3931     ;; we have to look at the retval instead
3932     (0 nil)
3933     (100 (error "qmail-inject reported permanent failure"))
3934     (111 (error "qmail-inject reported transient failure"))
3935     ;; should never happen
3936     (t   (error "qmail-inject reported unknown failure"))))
3937
3938 (defun message-send-mail-with-mh ()
3939   "Send the prepared message buffer with mh."
3940   (let ((mh-previous-window-config nil)
3941         (name (mh-new-draft-name)))
3942     (setq buffer-file-name name)
3943     ;; MH wants to generate these headers itself.
3944     (when message-mh-deletable-headers
3945       (let ((headers message-mh-deletable-headers))
3946         (while headers
3947           (goto-char (point-min))
3948           (and (re-search-forward
3949                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3950                (message-delete-line))
3951           (pop headers))))
3952     (run-hooks 'message-send-mail-hook)
3953     ;; Pass it on to mh.
3954     (mh-send-letter)))
3955
3956 (defun message-smtpmail-send-it ()
3957   "Send the prepared message buffer with `smtpmail-send-it'.
3958 This only differs from `smtpmail-send-it' that this command evaluates
3959 `message-send-mail-hook' just before sending a message.  It is useful
3960 if your ISP requires the POP-before-SMTP authentication.  See the Gnus
3961 manual for details."
3962   (run-hooks 'message-send-mail-hook)
3963   (smtpmail-send-it))
3964
3965 (defun message-canlock-generate ()
3966   "Return a string that is non-trivial to guess.
3967 Do not use this for anything important, it is cryptographically weak."
3968   (require 'sha1)
3969   (let (sha1-maximum-internal-length)
3970     (sha1 (concat (message-unique-id)
3971                   (format "%x%x%x" (random) (random t) (random))
3972                   (prin1-to-string (recent-keys))
3973                   (prin1-to-string (garbage-collect))))))
3974
3975 (defun message-canlock-password ()
3976   "The password used by message for cancel locks.
3977 This is the value of `canlock-password', if that option is non-nil.
3978 Otherwise, generate and save a value for `canlock-password' first."
3979   (unless canlock-password
3980     (customize-save-variable 'canlock-password (message-canlock-generate))
3981     (setq canlock-password-for-verify canlock-password))
3982   canlock-password)
3983
3984 (defun message-insert-canlock ()
3985   (when message-insert-canlock
3986     (message-canlock-password)
3987     (canlock-insert-header)))
3988
3989 (defun message-send-news (&optional arg)
3990   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3991          (case-fold-search nil)
3992          (method (if (functionp message-post-method)
3993                      (funcall message-post-method arg)
3994                    message-post-method))
3995          (newsgroups-field (save-restriction
3996                             (message-narrow-to-headers-or-head)
3997                             (message-fetch-field "Newsgroups")))
3998          (followup-field (save-restriction
3999                            (message-narrow-to-headers-or-head)
4000                            (message-fetch-field "Followup-To")))
4001          ;; BUG: We really need to get the charset for each name in the
4002          ;; Newsgroups and Followup-To lines to allow crossposting
4003          ;; between group namess with incompatible character sets.
4004          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4005          (group-field-charset
4006           (gnus-group-name-charset method newsgroups-field))
4007          (followup-field-charset
4008           (gnus-group-name-charset method (or followup-field "")))
4009          (rfc2047-header-encoding-alist
4010           (append (when group-field-charset
4011                     (list (cons "Newsgroups" group-field-charset)))
4012                   (when followup-field-charset
4013                     (list (cons "Followup-To" followup-field-charset)))
4014                   rfc2047-header-encoding-alist))
4015          (messbuf (current-buffer))
4016          (message-syntax-checks
4017           (if (and arg
4018                    (listp message-syntax-checks))
4019               (cons '(existing-newsgroups . disabled)
4020                     message-syntax-checks)
4021             message-syntax-checks))
4022          (message-this-is-news t)
4023          (message-posting-charset
4024           (gnus-setup-posting-charset newsgroups-field))
4025          result)
4026     (if (not (message-check-news-body-syntax))
4027         nil
4028       (save-restriction
4029         (message-narrow-to-headers)
4030         ;; Insert some headers.
4031         (message-generate-headers message-required-news-headers)
4032         (message-insert-canlock)
4033         ;; Let the user do all of the above.
4034         (run-hooks 'message-header-hook))
4035       ;; Note: This check will be disabled by the ".*" default value for
4036       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4037       (when (and group-field-charset
4038                  (listp message-syntax-checks))
4039         (setq message-syntax-checks
4040               (cons '(valid-newsgroups . disabled)
4041                     message-syntax-checks)))
4042       (message-cleanup-headers)
4043       (if (not (let ((message-post-method method))
4044                  (message-check-news-syntax)))
4045           nil
4046         (unwind-protect
4047             (save-excursion
4048               (set-buffer tembuf)
4049               (buffer-disable-undo)
4050               (erase-buffer)
4051               ;; Avoid copying text props (except hard newlines).
4052               (insert
4053                (with-current-buffer messbuf
4054                  (mml-buffer-substring-no-properties-except-hard-newlines
4055                   (point-min) (point-max))))
4056               (message-encode-message-body)
4057               ;; Remove some headers.
4058               (save-restriction
4059                 (message-narrow-to-headers)
4060                 ;; We (re)generate the Lines header.
4061                 (when (memq 'Lines message-required-mail-headers)
4062                   (message-generate-headers '(Lines)))
4063                 ;; Remove some headers.
4064                 (message-remove-header message-ignored-news-headers t)
4065                 (let ((mail-parse-charset message-default-charset))
4066                   (mail-encode-encoded-word-buffer)))
4067               (goto-char (point-max))
4068               ;; require one newline at the end.
4069               (or (= (preceding-char) ?\n)
4070                   (insert ?\n))
4071               (let ((case-fold-search t))
4072                 ;; Remove the delimiter.
4073                 (goto-char (point-min))
4074                 (re-search-forward
4075                  (concat "^" (regexp-quote mail-header-separator) "\n"))
4076                 (replace-match "\n")
4077                 (backward-char 1))
4078               (run-hooks 'message-send-news-hook)
4079               (gnus-open-server method)
4080               (message "Sending news via %s..." (gnus-server-string method))
4081               (setq result (let ((mail-header-separator ""))
4082                              (gnus-request-post method))))
4083           (kill-buffer tembuf))
4084         (set-buffer messbuf)
4085         (if result
4086             (push 'news message-sent-message-via)
4087           (message "Couldn't send message via news: %s"
4088                    (nnheader-get-report (car method)))
4089           nil)))))
4090
4091 ;;;
4092 ;;; Header generation & syntax checking.
4093 ;;;
4094
4095 (defun message-check-element (type)
4096   "Return non-nil if this TYPE is not to be checked."
4097   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4098       t
4099     (let ((able (assq type message-syntax-checks)))
4100       (and (consp able)
4101            (eq (cdr able) 'disabled)))))
4102
4103 (defun message-check-news-syntax ()
4104   "Check the syntax of the message."
4105   (save-excursion
4106     (save-restriction
4107       (widen)
4108       ;; We narrow to the headers and check them first.
4109       (save-excursion
4110         (save-restriction
4111           (message-narrow-to-headers)
4112           (message-check-news-header-syntax))))))
4113
4114 (defun message-check-news-header-syntax ()
4115   (and
4116    ;; Check Newsgroups header.
4117    (message-check 'newsgroups
4118      (let ((group (message-fetch-field "newsgroups")))
4119        (or
4120         (and group
4121              (not (string-match "\\`[ \t]*\\'" group)))
4122         (ignore
4123          (message
4124           "The newsgroups field is empty or missing.  Posting is denied.")))))
4125    ;; Check the Subject header.
4126    (message-check 'subject
4127      (let* ((case-fold-search t)
4128             (subject (message-fetch-field "subject")))
4129        (or
4130         (and subject
4131              (not (string-match "\\`[ \t]*\\'" subject)))
4132         (ignore
4133          (message
4134           "The subject field is empty or missing.  Posting is denied.")))))
4135    ;; Check for commands in Subject.
4136    (message-check 'subject-cmsg
4137      (if (string-match "^cmsg " (message-fetch-field "subject"))
4138          (y-or-n-p
4139           "The control code \"cmsg\" is in the subject.  Really post? ")
4140        t))
4141    ;; Check long header lines.
4142    (message-check 'long-header-lines
4143      (let ((start (point))
4144            (header nil)
4145            (length 0)
4146            found)
4147        (while (and (not found)
4148                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4149          (if (> (- (point) (match-beginning 0)) 998)
4150              (setq found t
4151                    length (- (point) (match-beginning 0)))
4152            (setq header (match-string-no-properties 1)))
4153          (setq start (match-beginning 0))
4154          (forward-line 1))
4155        (if found
4156            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4157                              header length))
4158          t)))
4159    ;; Check for multiple identical headers.
4160    (message-check 'multiple-headers
4161      (let (found)
4162        (while (and (not found)
4163                    (re-search-forward "^[^ \t:]+: " nil t))
4164          (save-excursion
4165            (or (re-search-forward
4166                 (concat "^"
4167                         (regexp-quote
4168                          (setq found
4169                                (buffer-substring
4170                                 (match-beginning 0) (- (match-end 0) 2))))
4171                         ":")
4172                 nil t)
4173                (setq found nil))))
4174        (if found
4175            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4176          t)))
4177    ;; Check for Version and Sendsys.
4178    (message-check 'sendsys
4179      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4180          (y-or-n-p
4181           (format "The article contains a %s command.  Really post? "
4182                   (buffer-substring (match-beginning 0)
4183                                     (1- (match-end 0)))))
4184        t))
4185    ;; See whether we can shorten Followup-To.
4186    (message-check 'shorten-followup-to
4187      (let ((newsgroups (message-fetch-field "newsgroups"))
4188            (followup-to (message-fetch-field "followup-to"))
4189            to)
4190        (when (and newsgroups
4191                   (string-match "," newsgroups)
4192                   (not followup-to)
4193                   (not
4194                    (zerop
4195                     (length
4196                      (setq to (completing-read
4197                                "Followups to (default: no Followup-To header) "
4198                                (mapcar #'list
4199                                        (cons "poster"
4200                                              (message-tokenize-header
4201                                               newsgroups)))))))))
4202          (goto-char (point-min))
4203          (insert "Followup-To: " to "\n"))
4204        t))
4205    ;; Check "Shoot me".
4206    (message-check 'shoot
4207      (if (re-search-forward
4208           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4209          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4210        t))
4211    ;; Check for Approved.
4212    (message-check 'approved
4213      (if (re-search-forward "^Approved:" nil t)
4214          (y-or-n-p "The article contains an Approved header.  Really post? ")
4215        t))
4216    ;; Check the Message-ID header.
4217    (message-check 'message-id
4218      (let* ((case-fold-search t)
4219             (message-id (message-fetch-field "message-id" t)))
4220        (or (not message-id)
4221            ;; Is there an @ in the ID?
4222            (and (string-match "@" message-id)
4223                 ;; Is there a dot in the ID?
4224                 (string-match "@[^.]*\\." message-id)
4225                 ;; Does the ID end with a dot?
4226                 (not (string-match "\\.>" message-id)))
4227            (y-or-n-p
4228             (format "The Message-ID looks strange: \"%s\".  Really post? "
4229                     message-id)))))
4230    ;; Check the Newsgroups & Followup-To headers.
4231    (message-check 'existing-newsgroups
4232      (let* ((case-fold-search t)
4233             (newsgroups (message-fetch-field "newsgroups"))
4234             (followup-to (message-fetch-field "followup-to"))
4235             (groups (message-tokenize-header
4236                      (if followup-to
4237                          (concat newsgroups "," followup-to)
4238                        newsgroups)))
4239             (post-method (if (functionp message-post-method)
4240                              (funcall message-post-method)
4241                            message-post-method))
4242             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4243             ;; would probably involve a new nnoo function.
4244             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4245             (method (if (and (consp post-method)
4246                              (eq (car post-method) 'nnvirtual)
4247                              gnus-message-group-art)
4248                         (let ((group (car (nnvirtual-find-group-art
4249                                            (car gnus-message-group-art)
4250                                            (cdr gnus-message-group-art)))))
4251                           (gnus-find-method-for-group group))
4252                       post-method))
4253             (known-groups
4254              (mapcar (lambda (n)
4255                        (gnus-group-name-decode
4256                         (gnus-group-real-name n)
4257                         (gnus-group-name-charset method n)))
4258                      (gnus-groups-from-server method)))
4259             errors)
4260        (while groups
4261          (when (and (not (equal (car groups) "poster"))
4262                     (not (member (car groups) known-groups))
4263                     (not (member (car groups) errors)))
4264            (push (car groups) errors))
4265          (pop groups))
4266        (cond
4267         ;; Gnus is not running.
4268         ((or (not (and (boundp 'gnus-active-hashtb)
4269                        gnus-active-hashtb))
4270              (not (boundp 'gnus-read-active-file)))
4271          t)
4272         ;; We don't have all the group names.
4273         ((and (or (not gnus-read-active-file)
4274                   (eq gnus-read-active-file 'some))
4275               errors)
4276          (y-or-n-p
4277           (format
4278            "Really use %s possibly unknown group%s: %s? "
4279            (if (= (length errors) 1) "this" "these")
4280            (if (= (length errors) 1) "" "s")
4281            (mapconcat 'identity errors ", "))))
4282         ;; There were no errors.
4283         ((not errors)
4284          t)
4285         ;; There are unknown groups.
4286         (t
4287          (y-or-n-p
4288           (format
4289            "Really post to %s unknown group%s: %s? "
4290            (if (= (length errors) 1) "this" "these")
4291            (if (= (length errors) 1) "" "s")
4292            (mapconcat 'identity errors ", ")))))))
4293    ;; Check continuation headers.
4294    (message-check 'continuation-headers
4295      (goto-char (point-min))
4296      (let ((do-posting t))
4297        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4298          (if (y-or-n-p "Fix continuation lines? ")
4299              (progn
4300                (goto-char (match-beginning 0))
4301                (insert " "))
4302            (unless (y-or-n-p "Send anyway? ")
4303              (setq do-posting nil))))
4304        do-posting))
4305    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4306    (message-check 'valid-newsgroups
4307      (let ((case-fold-search t)
4308            (headers '("Newsgroups" "Followup-To"))
4309            header error)
4310        (while (and headers (not error))
4311          (when (setq header (mail-fetch-field (car headers)))
4312            (if (or
4313                 (not
4314                  (string-match
4315                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4316                   header))
4317                 (memq
4318                  nil (mapcar
4319                       (lambda (g)
4320                         (not (string-match "\\.\\'\\|\\.\\." g)))
4321                       (message-tokenize-header header ","))))
4322                (setq error t)))
4323          (unless error
4324            (pop headers)))
4325        (if (not error)
4326            t
4327          (y-or-n-p
4328           (format "The %s header looks odd: \"%s\".  Really post? "
4329                   (car headers) header)))))
4330    (message-check 'repeated-newsgroups
4331      (let ((case-fold-search t)
4332            (headers '("Newsgroups" "Followup-To"))
4333            header error groups group)
4334        (while (and headers
4335                    (not error))
4336          (when (setq header (mail-fetch-field (pop headers)))
4337            (setq groups (message-tokenize-header header ","))
4338            (while (setq group (pop groups))
4339              (when (member group groups)
4340                (setq error group
4341                      groups nil)))))
4342        (if (not error)
4343            t
4344          (y-or-n-p
4345           (format "Group %s is repeated in headers.  Really post? " error)))))
4346    ;; Check the From header.
4347    (message-check 'from
4348      (let* ((case-fold-search t)
4349             (from (message-fetch-field "from"))
4350             ad)
4351        (cond
4352         ((not from)
4353          (message "There is no From line.  Posting is denied.")
4354          nil)
4355         ((or (not (string-match
4356                    "@[^\\.]*\\."
4357                    (setq ad (nth 1 (mail-extract-address-components
4358                                     from))))) ;larsi@ifi
4359              (string-match "\\.\\." ad) ;larsi@ifi..uio
4360              (string-match "@\\." ad)   ;larsi@.ifi.uio
4361              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4362              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4363              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4364          (message
4365           "Denied posting -- the From looks strange: \"%s\"." from)
4366          nil)
4367         ((let ((addresses (rfc822-addresses from)))
4368            (while (and addresses
4369                        (not (eq (string-to-char (car addresses)) ?\()))
4370              (setq addresses (cdr addresses)))
4371            addresses)
4372          (message
4373           "Denied posting -- bad From address: \"%s\"." from)
4374          nil)
4375         (t t))))
4376    ;; Check the Reply-To header.
4377    (message-check 'reply-to
4378      (let* ((case-fold-search t)
4379             (reply-to (message-fetch-field "reply-to"))
4380             ad)
4381        (cond
4382         ((not reply-to)
4383          t)
4384         ((string-match "," reply-to)
4385          (y-or-n-p
4386           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4387                   reply-to)))
4388         ((or (not (string-match
4389                    "@[^\\.]*\\."
4390                    (setq ad (nth 1 (mail-extract-address-components
4391                                     reply-to))))) ;larsi@ifi
4392              (string-match "\\.\\." ad) ;larsi@ifi..uio
4393              (string-match "@\\." ad)   ;larsi@.ifi.uio
4394              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4395              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4396              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4397          (y-or-n-p
4398           (format
4399            "The Reply-To looks strange: \"%s\". Really post? "
4400            reply-to)))
4401         (t t))))))
4402
4403 (defun message-check-news-body-syntax ()
4404   (and
4405    ;; Check for long lines.
4406    (message-check 'long-lines
4407      (goto-char (point-min))
4408      (re-search-forward
4409       (concat "^" (regexp-quote mail-header-separator) "$"))
4410      (forward-line 1)
4411      (while (and
4412              (or (looking-at
4413                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
4414                  (let ((p (point)))
4415                    (end-of-line)
4416                    (< (- (point) p) 80)))
4417              (zerop (forward-line 1))))
4418      (or (bolp)
4419          (eobp)
4420          (y-or-n-p
4421           "You have lines longer than 79 characters.  Really post? ")))
4422    ;; Check whether the article is empty.
4423    (message-check 'empty
4424      (goto-char (point-min))
4425      (re-search-forward
4426       (concat "^" (regexp-quote mail-header-separator) "$"))
4427      (forward-line 1)
4428      (let ((b (point)))
4429        (goto-char (point-max))
4430        (re-search-backward message-signature-separator nil t)
4431        (beginning-of-line)
4432        (or (re-search-backward "[^ \n\t]" b t)
4433            (if (message-gnksa-enable-p 'empty-article)
4434                (y-or-n-p "Empty article.  Really post? ")
4435              (message "Denied posting -- Empty article.")
4436              nil))))
4437    ;; Check for control characters.
4438    (message-check 'control-chars
4439      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4440          (y-or-n-p
4441           "The article contains control characters.  Really post? ")
4442        t))
4443    ;; Check excessive size.
4444    (message-check 'size
4445      (if (> (buffer-size) 60000)
4446          (y-or-n-p
4447           (format "The article is %d octets long.  Really post? "
4448                   (buffer-size)))
4449        t))
4450    ;; Check whether any new text has been added.
4451    (message-check 'new-text
4452      (or
4453       (not message-checksum)
4454       (not (eq (message-checksum) message-checksum))
4455       (if (message-gnksa-enable-p 'quoted-text-only)
4456           (y-or-n-p
4457            "It looks like no new text has been added.  Really post? ")
4458         (message "Denied posting -- no new text has been added.")
4459         nil)))
4460    ;; Check the length of the signature.
4461    (message-check 'signature
4462      (goto-char (point-max))
4463      (if (> (count-lines (point) (point-max)) 5)
4464          (y-or-n-p
4465           (format
4466            "Your .sig is %d lines; it should be max 4.  Really post? "
4467            (1- (count-lines (point) (point-max)))))
4468        t))
4469    ;; Ensure that text follows last quoted portion.
4470    (message-check 'quoting-style
4471      (goto-char (point-max))
4472      (let ((no-problem t))
4473        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4474          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4475        (if no-problem
4476            t
4477          (if (message-gnksa-enable-p 'quoted-text-only)
4478              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4479            ;; Ensure that
4480            (goto-char (point-min))
4481            (re-search-forward
4482             (concat "^" (regexp-quote mail-header-separator) "$"))
4483            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4484                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4485              (message "Denied posting -- only quoted text.")
4486              nil)))))))
4487
4488 (defun message-checksum ()
4489   "Return a \"checksum\" for the current buffer."
4490   (let ((sum 0))
4491     (save-excursion
4492       (goto-char (point-min))
4493       (re-search-forward
4494        (concat "^" (regexp-quote mail-header-separator) "$"))
4495       (while (not (eobp))
4496         (when (not (looking-at "[ \t\n]"))
4497           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4498                             (char-after))))
4499         (forward-char 1)))
4500     sum))
4501
4502 (defun message-do-fcc ()
4503   "Process Fcc headers in the current buffer."
4504   (let ((case-fold-search t)
4505         (buf (current-buffer))
4506         list file
4507         (mml-externalize-attachments message-fcc-externalize-attachments))
4508     (save-excursion
4509       (save-restriction
4510         (message-narrow-to-headers)
4511         (setq file (message-fetch-field "fcc" t)))
4512       (when file
4513         (set-buffer (get-buffer-create " *message temp*"))
4514         (erase-buffer)
4515         (insert-buffer-substring buf)
4516         (message-encode-message-body)
4517         (save-restriction
4518           (message-narrow-to-headers)
4519           (while (setq file (message-fetch-field "fcc" t))
4520             (push file list)
4521             (message-remove-header "fcc" nil t))
4522           (let ((mail-parse-charset message-default-charset)
4523                 (rfc2047-header-encoding-alist
4524                  (cons '("Newsgroups" . default)
4525                        rfc2047-header-encoding-alist)))
4526             (mail-encode-encoded-word-buffer)))
4527         (goto-char (point-min))
4528         (when (re-search-forward
4529                (concat "^" (regexp-quote mail-header-separator) "$")
4530                nil t)
4531           (replace-match "" t t ))
4532         ;; Process FCC operations.
4533         (while list
4534           (setq file (pop list))
4535           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4536               ;; Pipe the article to the program in question.
4537               (call-process-region (point-min) (point-max) shell-file-name
4538                                    nil nil nil shell-command-switch
4539                                    (match-string 1 file))
4540             ;; Save the article.
4541             (setq file (expand-file-name file))
4542             (unless (file-exists-p (file-name-directory file))
4543               (make-directory (file-name-directory file) t))
4544             (if (and message-fcc-handler-function
4545                      (not (eq message-fcc-handler-function 'rmail-output)))
4546                 (funcall message-fcc-handler-function file)
4547               (if (and (file-readable-p file) (mail-file-babyl-p file))
4548                   (rmail-output file 1 nil t)
4549                 (let ((mail-use-rfc822 t))
4550                   (rmail-output file 1 t t))))))
4551         (kill-buffer (current-buffer))))))
4552
4553 (defun message-output (filename)
4554   "Append this article to Unix/babyl mail file FILENAME."
4555   (if (and (file-readable-p filename)
4556            (mail-file-babyl-p filename))
4557       (gnus-output-to-rmail filename t)
4558     (gnus-output-to-mail filename t)))
4559
4560 (defun message-cleanup-headers ()
4561   "Do various automatic cleanups of the headers."
4562   ;; Remove empty lines in the header.
4563   (save-restriction
4564     (message-narrow-to-headers)
4565     ;; Remove blank lines.
4566     (while (re-search-forward "^[ \t]*\n" nil t)
4567       (replace-match "" t t))
4568
4569     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4570     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4571     ;; embedded line breaks.
4572     (goto-char (point-min))
4573     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4574       (save-restriction
4575         (narrow-to-region
4576          (point)
4577          (if (re-search-forward "^[^ \t]" nil t)
4578              (match-beginning 0)
4579            (forward-line 1)
4580            (point)))
4581         (goto-char (point-min))
4582         (while (re-search-forward "\n[ \t]+" nil t)
4583           (replace-match " " t t))     ;No line breaks (too confusing)
4584         (goto-char (point-min))
4585         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4586           (replace-match "," t t))
4587         (goto-char (point-min))
4588         ;; Remove trailing commas.
4589         (when (re-search-forward ",+$" nil t)
4590           (replace-match "" t t))))))
4591
4592 (defun message-make-date (&optional now)
4593   "Make a valid data header.
4594 If NOW, use that time instead."
4595   (let ((system-time-locale "C"))
4596     (format-time-string "%a, %d %b %Y %T %z" now)))
4597
4598 (defun message-make-message-id ()
4599   "Make a unique Message-ID."
4600   (concat "<" (message-unique-id)
4601           (let ((psubject (save-excursion (message-fetch-field "subject")))
4602                 (psupersedes
4603                  (save-excursion (message-fetch-field "supersedes"))))
4604             (if (or
4605                  (and message-reply-headers
4606                       (mail-header-references message-reply-headers)
4607                       (mail-header-subject message-reply-headers)
4608                       psubject
4609                       (not (string=
4610                             (message-strip-subject-re
4611                              (mail-header-subject message-reply-headers))
4612                             (message-strip-subject-re psubject))))
4613                  (and psupersedes
4614                       (string-match "_-_@" psupersedes)))
4615                 "_-_" ""))
4616           "@" (message-make-fqdn) ">"))
4617
4618 (defvar message-unique-id-char nil)
4619
4620 ;; If you ever change this function, make sure the new version
4621 ;; cannot generate IDs that the old version could.
4622 ;; You might for example insert a "." somewhere (not next to another dot
4623 ;; or string boundary), or modify the "fsf" string.
4624 (defun message-unique-id ()
4625   ;; Don't use microseconds from (current-time), they may be unsupported.
4626   ;; Instead we use this randomly inited counter.
4627   (setq message-unique-id-char
4628         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4629            ;; (current-time) returns 16-bit ints,
4630            ;; and 2^16*25 just fits into 4 digits i base 36.
4631            (* 25 25)))
4632   (let ((tm (current-time)))
4633     (concat
4634      (if (memq system-type '(ms-dos emx vax-vms))
4635          (let ((user (downcase (user-login-name))))
4636            (while (string-match "[^a-z0-9_]" user)
4637              (aset user (match-beginning 0) ?_))
4638            user)
4639        (message-number-base36 (user-uid) -1))
4640      (message-number-base36 (+ (car tm)
4641                                (lsh (% message-unique-id-char 25) 16)) 4)
4642      (message-number-base36 (+ (nth 1 tm)
4643                                (lsh (/ message-unique-id-char 25) 16)) 4)
4644      ;; Append a given name, because while the generated ID is unique
4645      ;; to this newsreader, other newsreaders might otherwise generate
4646      ;; the same ID via another algorithm.
4647      ".fsf")))
4648
4649 (defun message-number-base36 (num len)
4650   (if (if (< len 0)
4651           (<= num 0)
4652         (= len 0))
4653       ""
4654     (concat (message-number-base36 (/ num 36) (1- len))
4655             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4656                                   (% num 36))))))
4657
4658 (defun message-make-organization ()
4659   "Make an Organization header."
4660   (let* ((organization
4661           (when message-user-organization
4662             (if (functionp message-user-organization)
4663                 (funcall message-user-organization)
4664               message-user-organization))))
4665     (with-temp-buffer
4666       (mm-enable-multibyte)
4667       (cond ((stringp organization)
4668              (insert organization))
4669             ((and (eq t organization)
4670                   message-user-organization-file
4671                   (file-exists-p message-user-organization-file))
4672              (insert-file-contents message-user-organization-file)))
4673       (goto-char (point-min))
4674       (while (re-search-forward "[\t\n]+" nil t)
4675         (replace-match "" t t))
4676       (unless (zerop (buffer-size))
4677         (buffer-string)))))
4678
4679 (defun message-make-lines ()
4680   "Count the number of lines and return numeric string."
4681   (save-excursion
4682     (save-restriction
4683       (widen)
4684       (message-goto-body)
4685       (int-to-string (count-lines (point) (point-max))))))
4686
4687 (defun message-make-references ()
4688   "Return the References header for this message."
4689   (when message-reply-headers
4690     (let ((message-id (mail-header-message-id message-reply-headers))
4691           (references (mail-header-references message-reply-headers))
4692           new-references)
4693       (if (or references message-id)
4694           (concat (or references "") (and references " ")
4695                   (or message-id ""))
4696         nil))))
4697
4698 (defun message-make-in-reply-to ()
4699   "Return the In-Reply-To header for this message."
4700   (when message-reply-headers
4701     (let ((from (mail-header-from message-reply-headers))
4702           (date (mail-header-date message-reply-headers))
4703           (msg-id (mail-header-message-id message-reply-headers)))
4704       (when from
4705         (let ((name (mail-extract-address-components from)))
4706           (concat msg-id (if msg-id " (")
4707                   (or (car name)
4708                       (nth 1 name))
4709                   "'s message of \""
4710                   (if (or (not date) (string= date ""))
4711                       "(unknown date)" date)
4712                   "\"" (if msg-id ")")))))))
4713
4714 (defun message-make-distribution ()
4715   "Make a Distribution header."
4716   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4717     (cond ((functionp message-distribution-function)
4718            (funcall message-distribution-function))
4719           (t orig-distribution))))
4720
4721 (defun message-make-expires ()
4722   "Return an Expires header based on `message-expires'."
4723   (let ((current (current-time))
4724         (future (* 1.0 message-expires 60 60 24)))
4725     ;; Add the future to current.
4726     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4727     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4728     (message-make-date current)))
4729
4730 (defun message-make-path ()
4731   "Return uucp path."
4732   (let ((login-name (user-login-name)))
4733     (cond ((null message-user-path)
4734            (concat (system-name) "!" login-name))
4735           ((stringp message-user-path)
4736            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4737            (concat message-user-path "!" login-name))
4738           (t login-name))))
4739
4740 (defun message-make-from ()
4741   "Make a From header."
4742   (let* ((style message-from-style)
4743          (login (message-make-address))
4744          (fullname
4745           (or (and (boundp 'user-full-name)
4746                    user-full-name)
4747               (user-full-name))))
4748     (when (string= fullname "&")
4749       (setq fullname (user-login-name)))
4750     (with-temp-buffer
4751       (mm-enable-multibyte)
4752       (cond
4753        ((or (null style)
4754             (equal fullname ""))
4755         (insert login))
4756        ((or (eq style 'angles)
4757             (and (not (eq style 'parens))
4758                  ;; Use angles if no quoting is needed, or if parens would
4759                  ;; need quoting too.
4760                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4761                      (let ((tmp (concat fullname nil)))
4762                        (while (string-match "([^()]*)" tmp)
4763                          (aset tmp (match-beginning 0) ?-)
4764                          (aset tmp (1- (match-end 0)) ?-))
4765                        (string-match "[\\()]" tmp)))))
4766         (insert fullname)
4767         (goto-char (point-min))
4768         ;; Look for a character that cannot appear unquoted
4769         ;; according to RFC 822.
4770         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
4771           ;; Quote fullname, escaping specials.
4772           (goto-char (point-min))
4773           (insert "\"")
4774           (while (re-search-forward "[\"\\]" nil 1)
4775             (replace-match "\\\\\\&" t))
4776           (insert "\""))
4777         (insert " <" login ">"))
4778        (t                               ; 'parens or default
4779         (insert login " (")
4780         (let ((fullname-start (point)))
4781           (insert fullname)
4782           (goto-char fullname-start)
4783           ;; RFC 822 says \ and nonmatching parentheses
4784           ;; must be escaped in comments.
4785           ;; Escape every instance of ()\ ...
4786           (while (re-search-forward "[()\\]" nil 1)
4787             (replace-match "\\\\\\&" t))
4788           ;; ... then undo escaping of matching parentheses,
4789           ;; including matching nested parentheses.
4790           (goto-char fullname-start)
4791           (while (re-search-forward
4792                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4793                   nil 1)
4794             (replace-match "\\1(\\3)" t)
4795             (goto-char fullname-start)))
4796         (insert ")")))
4797       (buffer-string))))
4798
4799 (defun message-make-sender ()
4800   "Return the \"real\" user address.
4801 This function tries to ignore all user modifications, and
4802 give as trustworthy answer as possible."
4803   (concat (user-login-name) "@" (system-name)))
4804
4805 (defun message-make-address ()
4806   "Make the address of the user."
4807   (or (message-user-mail-address)
4808       (concat (user-login-name) "@" (message-make-domain))))
4809
4810 (defun message-user-mail-address ()
4811   "Return the pertinent part of `user-mail-address'."
4812   (when (and user-mail-address
4813              (string-match "@.*\\." user-mail-address))
4814     (if (string-match " " user-mail-address)
4815         (nth 1 (mail-extract-address-components user-mail-address))
4816       user-mail-address)))
4817
4818 (defun message-sendmail-envelope-from ()
4819   "Return the envelope from."
4820   (cond ((eq message-sendmail-envelope-from 'header)
4821          (nth 1 (mail-extract-address-components
4822                  (message-fetch-field "from"))))
4823         ((stringp message-sendmail-envelope-from)
4824          message-sendmail-envelope-from)
4825         (t
4826          (message-make-address))))
4827
4828 (defun message-make-fqdn ()
4829   "Return user's fully qualified domain name."
4830   (let* ((system-name (system-name))
4831          (user-mail (message-user-mail-address))
4832          (user-domain
4833           (if (and user-mail
4834                    (string-match "@\\(.*\\)\\'" user-mail))
4835               (match-string 1 user-mail)))
4836          (case-fold-search t))
4837     (cond
4838      ((and message-user-fqdn
4839            (stringp message-user-fqdn)
4840            (string-match message-valid-fqdn-regexp message-user-fqdn)
4841            (not (string-match message-bogus-system-names message-user-fqdn)))
4842       message-user-fqdn)
4843      ;; `message-user-fqdn' seems to be valid
4844      ((and (string-match message-valid-fqdn-regexp system-name)
4845            (not (string-match message-bogus-system-names system-name)))
4846       ;; `system-name' returned the right result.
4847       system-name)
4848      ;; Try `mail-host-address'.
4849      ((and (boundp 'mail-host-address)
4850            (stringp mail-host-address)
4851            (string-match message-valid-fqdn-regexp mail-host-address)
4852            (not (string-match message-bogus-system-names mail-host-address)))
4853       mail-host-address)
4854      ;; We try `user-mail-address' as a backup.
4855      ((and user-domain
4856            (stringp user-domain)
4857            (string-match message-valid-fqdn-regexp user-domain)
4858            (not (string-match message-bogus-system-names user-domain)))
4859       user-domain)
4860      ;; Default to this bogus thing.
4861      (t
4862       (concat system-name
4863               ".i-did-not-set--mail-host-address--so-tickle-me")))))
4864
4865 (defun message-make-host-name ()
4866   "Return the name of the host."
4867   (let ((fqdn (message-make-fqdn)))
4868     (string-match "^[^.]+\\." fqdn)
4869     (substring fqdn 0 (1- (match-end 0)))))
4870
4871 (defun message-make-domain ()
4872   "Return the domain name."
4873   (or mail-host-address
4874       (message-make-fqdn)))
4875
4876 (defun message-to-list-only ()
4877   "Send a message to the list only.
4878 Remove all addresses but the list address from To and Cc headers."
4879   (interactive)
4880   (let ((listaddr (message-make-mail-followup-to t)))
4881     (when listaddr
4882       (save-excursion
4883         (message-remove-header "to")
4884         (message-remove-header "cc")
4885         (message-position-on-field "To" "X-Draft-From")
4886         (insert listaddr)))))
4887
4888 (defun message-make-mail-followup-to (&optional only-show-subscribed)
4889   "Return the Mail-Followup-To header.
4890 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
4891 subscribed address (and not the additional To and Cc header contents)."
4892   (let* ((case-fold-search t)
4893          (to (message-fetch-field "To"))
4894          (cc (message-fetch-field "cc"))
4895          (msg-recipients (concat to (and to cc ", ") cc))
4896          (recipients
4897           (mapcar 'mail-strip-quoted-names
4898                   (message-tokenize-header msg-recipients)))
4899          (file-regexps
4900           (if message-subscribed-address-file
4901               (let (begin end item re)
4902                 (save-excursion
4903                   (with-temp-buffer
4904                     (insert-file-contents message-subscribed-address-file)
4905                     (while (not (eobp))
4906                       (setq begin (point))
4907                       (forward-line 1)
4908                       (setq end (point))
4909                       (if (bolp) (setq end (1- end)))
4910                       (setq item (regexp-quote (buffer-substring begin end)))
4911                       (if re (setq re (concat re "\\|" item))
4912                         (setq re (concat "\\`\\(" item))))
4913                     (and re (list (concat re "\\)\\'"))))))))
4914          (mft-regexps (apply 'append message-subscribed-regexps
4915                              (mapcar 'regexp-quote
4916                                      message-subscribed-addresses)
4917                              file-regexps
4918                              (mapcar 'funcall
4919                                      message-subscribed-address-functions))))
4920     (save-match-data
4921       (let ((subscribed-lists nil)
4922             (list
4923              (loop for recipient in recipients
4924                when (loop for regexp in mft-regexps
4925                       when (string-match regexp recipient) return t)
4926                return recipient)))
4927         (when list
4928           (if only-show-subscribed
4929               list
4930             msg-recipients))))))
4931
4932 (defun message-idna-to-ascii-rhs-1 (header)
4933   "Interactively potentially IDNA encode domain names in HEADER."
4934   (let ((field (message-fetch-field header))
4935         rhs ace  address)
4936     (when field
4937       (dolist (address (mail-header-parse-addresses field))
4938         (setq address (car address)
4939               rhs (downcase (or (cadr (split-string address "@")) ""))
4940               ace (downcase (idna-to-ascii rhs)))
4941         (when (and (not (equal rhs ace))
4942                    (or (not (eq message-use-idna 'ask))
4943                        (y-or-n-p (format "Replace %s with %s? " rhs ace))))
4944           (goto-char (point-min))
4945           (while (re-search-forward (concat "^" header ":") nil t)
4946             (message-narrow-to-field)
4947             (while (search-forward (concat "@" rhs) nil t)
4948               (replace-match (concat "@" ace) t t))
4949             (goto-char (point-max))
4950             (widen)))))))
4951
4952 (defun message-idna-to-ascii-rhs ()
4953   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
4954 See `message-idna-encode'."
4955   (interactive)
4956   (when message-use-idna
4957     (save-excursion
4958       (save-restriction
4959         (message-narrow-to-head)
4960         (message-idna-to-ascii-rhs-1 "From")
4961         (message-idna-to-ascii-rhs-1 "To")
4962         (message-idna-to-ascii-rhs-1 "Cc")))))
4963
4964 (defun message-generate-headers (headers)
4965   "Prepare article HEADERS.
4966 Headers already prepared in the buffer are not modified."
4967   (setq headers (append headers message-required-headers))
4968   (save-restriction
4969     (message-narrow-to-headers)
4970     (let* ((Date (message-make-date))
4971            (Message-ID (message-make-message-id))
4972            (Organization (message-make-organization))
4973            (From (message-make-from))
4974            (Path (message-make-path))
4975            (Subject nil)
4976            (Newsgroups nil)
4977            (In-Reply-To (message-make-in-reply-to))
4978            (References (message-make-references))
4979            (To nil)
4980            (Distribution (message-make-distribution))
4981            (Lines (message-make-lines))
4982            (User-Agent message-newsreader)
4983            (Expires (message-make-expires))
4984            (case-fold-search t)
4985            (optionalp nil)
4986            header value elem header-string)
4987       ;; First we remove any old generated headers.
4988       (let ((headers message-deletable-headers))
4989         (unless (buffer-modified-p)
4990           (setq headers (delq 'Message-ID (copy-sequence headers))))
4991         (while headers
4992           (goto-char (point-min))
4993           (and (re-search-forward
4994                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4995                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4996                (message-delete-line))
4997           (pop headers)))
4998       ;; Go through all the required headers and see if they are in the
4999       ;; articles already.  If they are not, or are empty, they are
5000       ;; inserted automatically - except for Subject, Newsgroups and
5001       ;; Distribution.
5002       (while headers
5003         (goto-char (point-min))
5004         (setq elem (pop headers))
5005         (if (consp elem)
5006             (if (eq (car elem) 'optional)
5007                 (setq header (cdr elem)
5008                       optionalp t)
5009               (setq header (car elem)))
5010           (setq header elem))
5011         (setq header-string  (if (stringp header)
5012                                  header
5013                                (symbol-name header)))
5014         (when (or (not (re-search-forward
5015                         (concat "^"
5016                                 (regexp-quote (downcase header-string))
5017                                 ":")
5018                         nil t))
5019                   (progn
5020                     ;; The header was found.  We insert a space after the
5021                     ;; colon, if there is none.
5022                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5023                     ;; Find out whether the header is empty.
5024                     (looking-at "[ \t]*\n[^ \t]")))
5025           ;; So we find out what value we should insert.
5026           (setq value
5027                 (cond
5028                  ((and (consp elem)
5029                        (eq (car elem) 'optional)
5030                        (not (member header-string message-inserted-headers)))
5031                   ;; This is an optional header.  If the cdr of this
5032                   ;; is something that is nil, then we do not insert
5033                   ;; this header.
5034                   (setq header (cdr elem))
5035                   (or (and (functionp (cdr elem))
5036                            (funcall (cdr elem)))
5037                       (and (boundp (cdr elem))
5038                            (symbol-value (cdr elem)))))
5039                  ((consp elem)
5040                   ;; The element is a cons.  Either the cdr is a
5041                   ;; string to be inserted verbatim, or it is a
5042                   ;; function, and we insert the value returned from
5043                   ;; this function.
5044                   (or (and (stringp (cdr elem))
5045                            (cdr elem))
5046                       (and (functionp (cdr elem))
5047                            (funcall (cdr elem)))))
5048                  ((and (boundp header)
5049                        (symbol-value header))
5050                   ;; The element is a symbol.  We insert the value
5051                   ;; of this symbol, if any.
5052                   (symbol-value header))
5053                  ((not (message-check-element header))
5054                   ;; We couldn't generate a value for this header,
5055                   ;; so we just ask the user.
5056                   (read-from-minibuffer
5057                    (format "Empty header for %s; enter value: " header)))))
5058           ;; Finally insert the header.
5059           (when (and value
5060                      (not (equal value "")))
5061             (save-excursion
5062               (if (bolp)
5063                   (progn
5064                     ;; This header didn't exist, so we insert it.
5065                     (goto-char (point-max))
5066                     (let ((formatter
5067                            (cdr (assq header message-header-format-alist))))
5068                       (if formatter
5069                           (funcall formatter header value)
5070                         (insert header-string ": " value))
5071                       (goto-char (message-fill-field))
5072                       ;; We check whether the value was ended by a
5073                       ;; newline.  If not, we insert one.
5074                       (unless (bolp)
5075                         (insert "\n"))
5076                       (forward-line -1)))
5077                 ;; The value of this header was empty, so we clear
5078                 ;; totally and insert the new value.
5079                 (delete-region (point) (point-at-eol))
5080                 ;; If the header is optional, and the header was
5081                 ;; empty, we con't insert it anyway.
5082                 (unless optionalp
5083                   (push header-string message-inserted-headers)
5084                   (insert value)
5085                   (message-fill-field)))
5086               ;; Add the deletable property to the headers that require it.
5087               (and (memq header message-deletable-headers)
5088                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5089                    (add-text-properties
5090                     (point) (match-end 0)
5091                     '(message-deletable t face italic) (current-buffer)))))))
5092       ;; Insert new Sender if the From is strange.
5093       (let ((from (message-fetch-field "from"))
5094             (sender (message-fetch-field "sender"))
5095             (secure-sender (message-make-sender)))
5096         (when (and from
5097                    (not (message-check-element 'sender))
5098                    (not (string=
5099                          (downcase
5100                           (cadr (mail-extract-address-components from)))
5101                          (downcase secure-sender)))
5102                    (or (null sender)
5103                        (not
5104                         (string=
5105                          (downcase
5106                           (cadr (mail-extract-address-components sender)))
5107                          (downcase secure-sender)))))
5108           (goto-char (point-min))
5109           ;; Rename any old Sender headers to Original-Sender.
5110           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5111             (beginning-of-line)
5112             (insert "Original-")
5113             (beginning-of-line))
5114           (when (or (message-news-p)
5115                     (string-match "@.+\\.." secure-sender))
5116             (insert "Sender: " secure-sender "\n"))))
5117       ;; Check for IDNA
5118       (message-idna-to-ascii-rhs))))
5119
5120 (defun message-insert-courtesy-copy ()
5121   "Insert a courtesy message in mail copies of combined messages."
5122   (let (newsgroups)
5123     (save-excursion
5124       (save-restriction
5125         (message-narrow-to-headers)
5126         (when (setq newsgroups (message-fetch-field "newsgroups"))
5127           (goto-char (point-max))
5128           (insert "Posted-To: " newsgroups "\n")))
5129       (forward-line 1)
5130       (when message-courtesy-message
5131         (cond
5132          ((string-match "%s" message-courtesy-message)
5133           (insert (format message-courtesy-message newsgroups)))
5134          (t
5135           (insert message-courtesy-message)))))))
5136
5137 ;;;
5138 ;;; Setting up a message buffer
5139 ;;;
5140
5141 (defun message-skip-to-next-address ()
5142   (let ((end (save-excursion
5143                (message-next-header)
5144                (point)))
5145         quoted char)
5146     (when (looking-at ",")
5147       (forward-char 1))
5148     (while (and (not (= (point) end))
5149                 (or (not (eq char ?,))
5150                     quoted))
5151       (skip-chars-forward "^,\"" (point-max))
5152       (when (eq (setq char (following-char)) ?\")
5153         (setq quoted (not quoted)))
5154       (unless (= (point) end)
5155         (forward-char 1)))
5156     (skip-chars-forward " \t\n")))
5157
5158 (defun message-fill-address (header value)
5159   (insert (capitalize (symbol-name header))
5160           ": "
5161           (if (consp value) (car value) value)
5162           "\n")
5163   (message-fill-field-address))
5164
5165 (defun message-split-line ()
5166   "Split current line, moving portion beyond point vertically down.
5167 If the current line has `message-yank-prefix', insert it on the new line."
5168   (interactive "*")
5169   (condition-case nil
5170       (split-line message-yank-prefix) ;; Emacs 21.3.50+ supports arg.
5171     (error
5172      (split-line))))
5173
5174 (defun message-insert-header (header value)
5175   (insert (capitalize (symbol-name header))
5176           ": "
5177           (if (consp value) (car value) value)))
5178
5179 (defun message-field-name ()
5180   (save-excursion
5181     (goto-char (point-min))
5182     (when (looking-at "\\([^:]+\\):")
5183       (intern (capitalize (match-string 1))))))
5184
5185 (defun message-fill-field ()
5186   (save-excursion
5187     (save-restriction
5188       (message-narrow-to-field)
5189       (let ((field-name (message-field-name)))
5190         (funcall (or (cadr (assq field-name message-field-fillers))
5191                      'message-fill-field-general)))
5192       (point-max))))
5193
5194 (defun message-fill-field-address ()
5195   (while (not (eobp))
5196     (message-skip-to-next-address)
5197     (let (last)
5198       (if (and (> (current-column) 78)
5199                last)
5200           (progn
5201             (save-excursion
5202               (goto-char last)
5203               (insert "\n\t"))
5204             (setq last (1+ (point))))
5205         (setq last (1+ (point)))))))
5206   
5207 (defun message-fill-field-general ()
5208   (let ((begin (point))
5209         (fill-column 78)
5210         (fill-prefix "\t"))
5211     (while (and (search-forward "\n" nil t)
5212                 (not (eobp)))
5213       (replace-match " " t t))
5214     (fill-region-as-paragraph begin (point-max))
5215     ;; Tapdance around looong Message-IDs.
5216     (forward-line -1)
5217     (when (looking-at "[ \t]*$")
5218       (message-delete-line))
5219     (goto-char begin)
5220     (search-forward ":" nil t)
5221     (when (looking-at "\n[ \t]+")
5222       (replace-match " " t t))
5223     (goto-char (point-max))))
5224
5225 (defun message-shorten-1 (list cut surplus)
5226   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5227   (setcdr (nthcdr (- cut 2) list)
5228           (nthcdr (+ (- cut 2) surplus 1) list)))
5229
5230 (defun message-shorten-references (header references)
5231   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5232 When sending via news, also check that the REFERENCES are less
5233 than 988 characters long, and if they are not, trim them until
5234 they are."
5235   (let ((maxcount 21)
5236         (count 0)
5237         (cut 2)
5238         refs)
5239     (with-temp-buffer
5240       (insert references)
5241       (goto-char (point-min))
5242       ;; Cons a list of valid references.
5243       (while (re-search-forward "<[^>]+>" nil t)
5244         (push (match-string 0) refs))
5245       (setq refs (nreverse refs)
5246             count (length refs)))
5247
5248     ;; If the list has more than MAXCOUNT elements, trim it by
5249     ;; removing the CUTth element and the required number of
5250     ;; elements that follow.
5251     (when (> count maxcount)
5252       (let ((surplus (- count maxcount)))
5253         (message-shorten-1 refs cut surplus)
5254         (decf count surplus)))
5255
5256     ;; When sending via news, make sure the total folded length will
5257     ;; be less than 998 characters.  This is to cater to broken INN
5258     ;; 2.3 which counts the total number of characters in a header
5259     ;; rather than the physical line length of each line, as it should.
5260     ;;
5261     ;; This hack should be removed when it's believed than INN 2.3 is
5262     ;; no longer widely used.
5263     ;;
5264     ;; At this point the headers have not been generated, thus we use
5265     ;; message-this-is-news directly.
5266     (when message-this-is-news
5267       (while (< 998
5268                 (with-temp-buffer
5269                   (message-insert-header
5270                    header (mapconcat #'identity refs " "))
5271                   (buffer-size)))
5272         (message-shorten-1 refs cut 1)))
5273     ;; Finally, collect the references back into a string and insert
5274     ;; it into the buffer.
5275     (message-insert-header header (mapconcat #'identity refs " "))))
5276
5277 (defun message-position-point ()
5278   "Move point to where the user probably wants to find it."
5279   (message-narrow-to-headers)
5280   (cond
5281    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5282     (search-backward ":" )
5283     (widen)
5284     (forward-char 1)
5285     (if (eq (char-after) ? )
5286         (forward-char 1)
5287       (insert " ")))
5288    (t
5289     (goto-char (point-max))
5290     (widen)
5291     (forward-line 1)
5292     (unless (looking-at "$")
5293       (forward-line 2)))
5294    (sit-for 0)))
5295
5296 (defcustom message-beginning-of-line t
5297   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5298  goes to beginning of header values."
5299   :version "21.4"
5300   :group 'message-buffers
5301   :link '(custom-manual "(message)Movement")
5302   :type 'boolean)
5303
5304 (defun message-beginning-of-line (&optional n)
5305   "Move point to beginning of header value or to beginning of line.
5306 The prefix argument N is passed directly to `beginning-of-line'.
5307
5308 This command is identical to `beginning-of-line' if point is
5309 outside the message header or if the option `message-beginning-of-line'
5310 is nil.
5311
5312 If point is in the message header and on a (non-continued) header
5313 line, move point to the beginning of the header value.  If point
5314 is already there, move point to beginning of line.  Therefore,
5315 repeated calls will toggle point between beginning of field and
5316 beginning of line."
5317   (interactive "p")
5318   (let ((zrs 'zmacs-region-stays))
5319     (when (and (interactive-p) (boundp zrs))
5320       (set zrs t)))
5321   (if (and message-beginning-of-line
5322            (message-point-in-header-p))
5323       (let* ((here (point))
5324              (bol (progn (beginning-of-line n) (point)))
5325              (eol (point-at-eol))
5326              (eoh (re-search-forward ": *" eol t)))
5327         (if (or (not eoh) (equal here eoh))
5328             (goto-char bol)
5329           (goto-char eoh)))
5330     (beginning-of-line n)))
5331
5332 (defun message-buffer-name (type &optional to group)
5333   "Return a new (unique) buffer name based on TYPE and TO."
5334   (cond
5335    ;; Generate a new buffer name The Message Way.
5336    ((eq message-generate-new-buffers 'unique)
5337     (generate-new-buffer-name
5338      (concat "*" type
5339              (if to
5340                  (concat " to "
5341                          (or (car (mail-extract-address-components to))
5342                              to) "")
5343                "")
5344              (if (and group (not (string= group ""))) (concat " on " group) "")
5345              "*")))
5346    ;; Check whether `message-generate-new-buffers' is a function,
5347    ;; and if so, call it.
5348    ((functionp message-generate-new-buffers)
5349     (funcall message-generate-new-buffers type to group))
5350    ((eq message-generate-new-buffers 'unsent)
5351     (generate-new-buffer-name
5352      (concat "*unsent " type
5353              (if to
5354                  (concat " to "
5355                          (or (car (mail-extract-address-components to))
5356                              to) "")
5357                "")
5358              (if (and group (not (string= group ""))) (concat " on " group) "")
5359              "*")))
5360    ;; Use standard name.
5361    (t
5362     (format "*%s message*" type))))
5363
5364 (defun message-pop-to-buffer (name)
5365   "Pop to buffer NAME, and warn if it already exists and is modified."
5366   (let ((buffer (get-buffer name)))
5367     (if (and buffer
5368              (buffer-name buffer))
5369         (progn
5370           (set-buffer (pop-to-buffer buffer))
5371           (when (and (buffer-modified-p)
5372                      (not (y-or-n-p
5373                            "Message already being composed; erase? ")))
5374             (error "Message being composed")))
5375       (set-buffer (pop-to-buffer name)))
5376     (erase-buffer)
5377     (message-mode)))
5378
5379 (defun message-do-send-housekeeping ()
5380   "Kill old message buffers."
5381   ;; We might have sent this buffer already.  Delete it from the
5382   ;; list of buffers.
5383   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5384   (while (and message-max-buffers
5385               message-buffer-list
5386               (>= (length message-buffer-list) message-max-buffers))
5387     ;; Kill the oldest buffer -- unless it has been changed.
5388     (let ((buffer (pop message-buffer-list)))
5389       (when (and (buffer-name buffer)
5390                  (not (buffer-modified-p buffer)))
5391         (kill-buffer buffer))))
5392   ;; Rename the buffer.
5393   (if message-send-rename-function
5394       (funcall message-send-rename-function)
5395     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5396     (when (string-match
5397            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5398            (buffer-name))
5399       (let ((name (match-string 2 (buffer-name)))
5400             to group)
5401         (if (not (or (null name)
5402                      (string-equal name "mail")
5403                      (string-equal name "posting")))
5404             (setq name (concat "*sent " name "*"))
5405           (message-narrow-to-headers)
5406           (setq to (message-fetch-field "to"))
5407           (setq group (message-fetch-field "newsgroups"))
5408           (widen)
5409           (setq name
5410                 (cond
5411                  (to (concat "*sent mail to "
5412                              (or (car (mail-extract-address-components to))
5413                                  to) "*"))
5414                  ((and group (not (string= group "")))
5415                   (concat "*sent posting on " group "*"))
5416                  (t "*sent mail*"))))
5417         (unless (string-equal name (buffer-name))
5418           (rename-buffer name t)))))
5419   ;; Push the current buffer onto the list.
5420   (when message-max-buffers
5421     (setq message-buffer-list
5422           (nconc message-buffer-list (list (current-buffer))))))
5423
5424 (defun message-mail-user-agent ()
5425   (let ((mua (cond
5426               ((not message-mail-user-agent) nil)
5427               ((eq message-mail-user-agent t) mail-user-agent)
5428               (t message-mail-user-agent))))
5429     (if (memq mua '(message-user-agent gnus-user-agent))
5430         nil
5431       mua)))
5432
5433 (defun message-setup (headers &optional replybuffer actions switch-function)
5434   (let ((mua (message-mail-user-agent))
5435         subject to field yank-action)
5436     (if (not (and message-this-is-mail mua))
5437         (message-setup-1 headers replybuffer actions)
5438       (if replybuffer
5439           (setq yank-action (list 'insert-buffer replybuffer)))
5440       (setq headers (copy-sequence headers))
5441       (setq field (assq 'Subject headers))
5442       (when field
5443         (setq subject (cdr field))
5444         (setq headers (delq field headers)))
5445       (setq field (assq 'To headers))
5446       (when field
5447         (setq to (cdr field))
5448         (setq headers (delq field headers)))
5449       (let ((mail-user-agent mua))
5450         (compose-mail to subject
5451                       (mapcar (lambda (item)
5452                                 (cons
5453                                  (format "%s" (car item))
5454                                  (cdr item)))
5455                               headers)
5456                       nil switch-function yank-action actions)))))
5457
5458 (defun message-headers-to-generate (headers included-headers excluded-headers)
5459   "Return a list that includes all headers from HEADERS.
5460 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5461 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5462 are not included."
5463   (let ((result nil)
5464         header-name)
5465     (dolist (header headers)
5466       (setq header-name (cond
5467                          ((and (consp header)
5468                                (eq (car header) 'optional))
5469                           ;; On the form (optional . Header)
5470                           (cdr header))
5471                          ((consp header)
5472                           ;; On the form (Header . function)
5473                           (car header))
5474                          (t
5475                           ;; Just a Header.
5476                           header)))
5477       (when (and (not (memq header-name excluded-headers))
5478                  (or (eq included-headers t)
5479                      (memq header-name included-headers)))
5480         (push header result)))
5481     (nreverse result)))
5482
5483 (defun message-setup-1 (headers &optional replybuffer actions)
5484   (dolist (action actions)
5485     (condition-case nil
5486         (add-to-list 'message-send-actions
5487                      `(apply ',(car action) ',(cdr action)))))
5488   (setq message-reply-buffer replybuffer)
5489   (goto-char (point-min))
5490   ;; Insert all the headers.
5491   (mail-header-format
5492    (let ((h headers)
5493          (alist message-header-format-alist))
5494      (while h
5495        (unless (assq (caar h) message-header-format-alist)
5496          (push (list (caar h)) alist))
5497        (pop h))
5498      alist)
5499    headers)
5500   (delete-region (point) (progn (forward-line -1) (point)))
5501   (when message-default-headers
5502     (insert message-default-headers)
5503     (or (bolp) (insert ?\n)))
5504   (insert mail-header-separator "\n")
5505   (forward-line -1)
5506   (when (message-news-p)
5507     (when message-default-news-headers
5508       (insert message-default-news-headers)
5509       (or (bolp) (insert ?\n)))
5510     (when message-generate-headers-first
5511       (message-generate-headers
5512        (message-headers-to-generate
5513         (append message-required-news-headers
5514                 message-required-headers)
5515         message-generate-headers-first
5516         '(Lines Subject)))))
5517   (when (message-mail-p)
5518     (when message-default-mail-headers
5519       (insert message-default-mail-headers)
5520       (or (bolp) (insert ?\n)))
5521     (save-restriction
5522       (message-narrow-to-headers)
5523       (if message-alternative-emails
5524           (message-use-alternative-email-as-from)))
5525     (when message-generate-headers-first
5526       (message-generate-headers
5527        (message-headers-to-generate
5528         (append message-required-mail-headers
5529                 message-required-headers)
5530         message-generate-headers-first
5531         '(Lines Subject)))))
5532   (run-hooks 'message-signature-setup-hook)
5533   (message-insert-signature)
5534   (save-restriction
5535     (message-narrow-to-headers)
5536     (run-hooks 'message-header-setup-hook))
5537   (set-buffer-modified-p nil)
5538   (setq buffer-undo-list nil)
5539   (run-hooks 'message-setup-hook)
5540   (message-position-point)
5541   (undo-boundary))
5542
5543 (defun message-set-auto-save-file-name ()
5544   "Associate the message buffer with a file in the drafts directory."
5545   (when message-auto-save-directory
5546     (unless (file-directory-p
5547              (directory-file-name message-auto-save-directory))
5548       (make-directory message-auto-save-directory t))
5549     (if (gnus-alive-p)
5550         (setq message-draft-article
5551               (nndraft-request-associate-buffer "drafts"))
5552       (setq buffer-file-name (expand-file-name
5553                               (if (memq system-type
5554                                         '(ms-dos ms-windows windows-nt
5555                                                  cygwin cygwin32 win32 w32
5556                                                  mswindows))
5557                                   "message"
5558                                 "*message*")
5559                               message-auto-save-directory))
5560       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5561     (clear-visited-file-modtime)
5562     (setq buffer-file-coding-system message-draft-coding-system)))
5563
5564 (defun message-disassociate-draft ()
5565   "Disassociate the message buffer from the drafts directory."
5566   (when message-draft-article
5567     (nndraft-request-expire-articles
5568      (list message-draft-article) "drafts" nil t)))
5569
5570 (defun message-insert-headers ()
5571   "Generate the headers for the article."
5572   (interactive)
5573   (save-excursion
5574     (save-restriction
5575       (message-narrow-to-headers)
5576       (when (message-news-p)
5577         (message-generate-headers
5578          (delq 'Lines
5579                (delq 'Subject
5580                      (copy-sequence message-required-news-headers)))))
5581       (when (message-mail-p)
5582         (message-generate-headers
5583          (delq 'Lines
5584                (delq 'Subject
5585                      (copy-sequence message-required-mail-headers))))))))
5586
5587 \f
5588
5589 ;;;
5590 ;;; Commands for interfacing with message
5591 ;;;
5592
5593 ;;;###autoload
5594 (defun message-mail (&optional to subject
5595                                other-headers continue switch-function
5596                                yank-action send-actions)
5597   "Start editing a mail message to be sent.
5598 OTHER-HEADERS is an alist of header/value pairs."
5599   (interactive)
5600   (let ((message-this-is-mail t) replybuffer)
5601     (unless (message-mail-user-agent)
5602       (message-pop-to-buffer (message-buffer-name "mail" to)))
5603     ;; FIXME: message-mail should do something if YANK-ACTION is not
5604     ;; insert-buffer.
5605     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5606          (setq replybuffer (nth 1 yank-action)))
5607     (message-setup
5608      (nconc
5609       `((To . ,(or to "")) (Subject . ,(or subject "")))
5610       (when other-headers other-headers))
5611      replybuffer send-actions)
5612     ;; FIXME: Should return nil if failure.
5613     t))
5614
5615 ;;;###autoload
5616 (defun message-news (&optional newsgroups subject)
5617   "Start editing a news article to be sent."
5618   (interactive)
5619   (let ((message-this-is-news t))
5620     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5621     (message-setup `((Newsgroups . ,(or newsgroups ""))
5622                      (Subject . ,(or subject ""))))))
5623
5624 (defun message-get-reply-headers (wide &optional to-address address-headers)
5625   (let (follow-to mct never-mct to cc author mft recipients)
5626     ;; Find all relevant headers we need.
5627     (save-restriction
5628       (message-narrow-to-headers-or-head)
5629       ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
5630       ;; message-header-synonyms.
5631       (setq to (or (message-fetch-field "to")
5632                    (and (loop for synonym in message-header-synonyms
5633                               when (memq 'Original-To synonym)
5634                               return t)
5635                         (message-fetch-field "original-to")))
5636             cc (message-fetch-field "cc")
5637             mct (message-fetch-field "mail-copies-to")
5638             author (or (message-fetch-field "mail-reply-to")
5639                        (message-fetch-field "reply-to")
5640                        (message-fetch-field "from")
5641                        "")
5642             mft (and message-use-mail-followup-to
5643                      (message-fetch-field "mail-followup-to"))))
5644
5645     ;; Handle special values of Mail-Copies-To.
5646     (when mct
5647       (cond ((or (equal (downcase mct) "never")
5648                  (equal (downcase mct) "nobody"))
5649              (setq never-mct t)
5650              (setq mct nil))
5651             ((or (equal (downcase mct) "always")
5652                  (equal (downcase mct) "poster"))
5653              (setq mct author))))
5654
5655     (save-match-data
5656       ;; Build (textual) list of new recipient addresses.
5657       (cond
5658        ((not wide)
5659         (setq recipients (concat ", " author)))
5660        (address-headers
5661         (dolist (header address-headers)
5662           (let ((value (message-fetch-field header)))
5663             (when value
5664               (setq recipients (concat recipients ", " value))))))
5665        ((and mft
5666              (string-match "[^ \t,]" mft)
5667              (or (not (eq message-use-mail-followup-to 'ask))
5668                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5669 You should normally obey the Mail-Followup-To: header.  In this
5670 article, it has the value of
5671
5672 " mft "
5673
5674 which directs your response to " (if (string-match "," mft)
5675                                      "the specified addresses"
5676                                    "that address only") ".
5677
5678 Most commonly, Mail-Followup-To is used by a mailing list poster to
5679 express that responses should be sent to just the list, and not the
5680 poster as well.
5681
5682 If a message is posted to several mailing lists, Mail-Followup-To may
5683 also be used to direct the following discussion to one list only,
5684 because discussions that are spread over several lists tend to be
5685 fragmented and very difficult to follow.
5686
5687 Also, some source/announcement lists are not intended for discussion;
5688 responses here are directed to other addresses.")))
5689         (setq recipients (concat ", " mft)))
5690        (to-address
5691         (setq recipients (concat ", " to-address))
5692         ;; If the author explicitly asked for a copy, we don't deny it to them.
5693         (if mct (setq recipients (concat recipients ", " mct))))
5694        (t
5695         (setq recipients (if never-mct "" (concat ", " author)))
5696         (if to  (setq recipients (concat recipients ", " to)))
5697         (if cc  (setq recipients (concat recipients ", " cc)))
5698         (if mct (setq recipients (concat recipients ", " mct)))))
5699       (if (>= (length recipients) 2)
5700           ;; Strip the leading ", ".
5701           (setq recipients (substring recipients 2)))
5702       ;; Squeeze whitespace.
5703       (while (string-match "[ \t][ \t]+" recipients)
5704         (setq recipients (replace-match " " t t recipients)))
5705       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5706       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5707         (setq recipients (rmail-dont-reply-to recipients)))
5708       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5709       (if (string-equal recipients "")
5710           (setq recipients author))
5711       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5712       (setq recipients
5713             (mapcar
5714              (lambda (addr)
5715                (cons (downcase (mail-strip-quoted-names addr)) addr))
5716              (message-tokenize-header recipients)))
5717       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5718       (let ((s recipients))
5719         (while s
5720           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5721
5722       ;; Remove hierarchical lists that are contained within each other,
5723       ;; if message-hierarchical-addresses is defined.
5724       (when message-hierarchical-addresses
5725         (let ((plain-addrs (mapcar 'car recipients))
5726               subaddrs recip)
5727           (while plain-addrs
5728             (setq subaddrs (assoc (car plain-addrs)
5729                                   message-hierarchical-addresses)
5730                   plain-addrs (cdr plain-addrs))
5731             (when subaddrs
5732               (setq subaddrs (cdr subaddrs))
5733               (while subaddrs
5734                 (setq recip (assoc (car subaddrs) recipients)
5735                       subaddrs (cdr subaddrs))
5736                 (if recip
5737                     (setq recipients (delq recip recipients))))))))
5738
5739       ;; Build the header alist.  Allow the user to be asked whether
5740       ;; or not to reply to all recipients in a wide reply.
5741       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5742       (when (and recipients
5743                  (or (not message-wide-reply-confirm-recipients)
5744                      (y-or-n-p "Reply to all recipients? ")))
5745         (setq recipients (mapconcat
5746                           (lambda (addr) (cdr addr)) recipients ", "))
5747         (if (string-match "^ +" recipients)
5748             (setq recipients (substring recipients (match-end 0))))
5749         (push (cons 'Cc recipients) follow-to)))
5750     follow-to))
5751
5752 ;;;###autoload
5753 (defun message-reply (&optional to-address wide)
5754   "Start editing a reply to the article in the current buffer."
5755   (interactive)
5756   (require 'gnus-sum)                   ; for gnus-list-identifiers
5757   (let ((cur (current-buffer))
5758         from subject date reply-to to cc
5759         references message-id follow-to
5760         (inhibit-point-motion-hooks t)
5761         (message-this-is-mail t)
5762         gnus-warning)
5763     (save-restriction
5764       (message-narrow-to-head-1)
5765       ;; Allow customizations to have their say.
5766       (if (not wide)
5767           ;; This is a regular reply.
5768           (when (functionp message-reply-to-function)
5769             (save-excursion
5770               (setq follow-to (funcall message-reply-to-function))))
5771         ;; This is a followup.
5772         (when (functionp message-wide-reply-to-function)
5773           (save-excursion
5774             (setq follow-to
5775                   (funcall message-wide-reply-to-function)))))
5776       (setq message-id (message-fetch-field "message-id" t)
5777             references (message-fetch-field "references")
5778             date (message-fetch-field "date")
5779             from (message-fetch-field "from")
5780             subject (or (message-fetch-field "subject") "none"))
5781       (when gnus-list-identifiers
5782         (setq subject (message-strip-list-identifiers subject)))
5783       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5784       (when message-subject-trailing-was-query
5785         (setq subject (message-strip-subject-trailing-was subject)))
5786
5787       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5788                  (string-match "<[^>]+>" gnus-warning))
5789         (setq message-id (match-string 0 gnus-warning)))
5790
5791       (unless follow-to
5792         (setq follow-to (message-get-reply-headers wide to-address))))
5793
5794     (unless (message-mail-user-agent)
5795       (message-pop-to-buffer
5796        (message-buffer-name
5797         (if wide "wide reply" "reply") from
5798         (if wide to-address nil))))
5799
5800     (setq message-reply-headers
5801           (vector 0 subject from date message-id references 0 0 ""))
5802
5803     (message-setup
5804      `((Subject . ,subject)
5805        ,@follow-to)
5806      cur)))
5807
5808 ;;;###autoload
5809 (defun message-wide-reply (&optional to-address)
5810   "Make a \"wide\" reply to the message in the current buffer."
5811   (interactive)
5812   (message-reply to-address t))
5813
5814 ;;;###autoload
5815 (defun message-followup (&optional to-newsgroups)
5816   "Follow up to the message in the current buffer.
5817 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5818   (interactive)
5819   (require 'gnus-sum)                   ; for gnus-list-identifiers
5820   (let ((cur (current-buffer))
5821         from subject date reply-to mrt mct
5822         references message-id follow-to
5823         (inhibit-point-motion-hooks t)
5824         (message-this-is-news t)
5825         followup-to distribution newsgroups gnus-warning posted-to)
5826     (save-restriction
5827       (narrow-to-region
5828        (goto-char (point-min))
5829        (if (search-forward "\n\n" nil t)
5830            (1- (point))
5831          (point-max)))
5832       (when (functionp message-followup-to-function)
5833         (setq follow-to
5834               (funcall message-followup-to-function)))
5835       (setq from (message-fetch-field "from")
5836             date (message-fetch-field "date")
5837             subject (or (message-fetch-field "subject") "none")
5838             references (message-fetch-field "references")
5839             message-id (message-fetch-field "message-id" t)
5840             followup-to (message-fetch-field "followup-to")
5841             newsgroups (message-fetch-field "newsgroups")
5842             posted-to (message-fetch-field "posted-to")
5843             reply-to (message-fetch-field "reply-to")
5844             mrt (message-fetch-field "mail-reply-to")
5845             distribution (message-fetch-field "distribution")
5846             mct (message-fetch-field "mail-copies-to"))
5847       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5848                  (string-match "<[^>]+>" gnus-warning))
5849         (setq message-id (match-string 0 gnus-warning)))
5850       ;; Remove bogus distribution.
5851       (when (and (stringp distribution)
5852                  (let ((case-fold-search t))
5853                    (string-match "world" distribution)))
5854         (setq distribution nil))
5855       (if gnus-list-identifiers
5856           (setq subject (message-strip-list-identifiers subject)))
5857       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5858       (when message-subject-trailing-was-query
5859         (setq subject (message-strip-subject-trailing-was subject)))
5860       (widen))
5861
5862     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5863
5864     (setq message-reply-headers
5865           (vector 0 subject from date message-id references 0 0 ""))
5866
5867     (message-setup
5868      `((Subject . ,subject)
5869        ,@(cond
5870           (to-newsgroups
5871            (list (cons 'Newsgroups to-newsgroups)))
5872           (follow-to follow-to)
5873           ((and followup-to message-use-followup-to)
5874            (list
5875             (cond
5876              ((equal (downcase followup-to) "poster")
5877               (if (or (eq message-use-followup-to 'use)
5878                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
5879 You should normally obey the Followup-To: header.
5880
5881 `Followup-To: poster' sends your response via e-mail instead of news.
5882
5883 A typical situation where `Followup-To: poster' is used is when the poster
5884 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5885                   (progn
5886                     (setq message-this-is-news nil)
5887                     (cons 'To (or mrt reply-to from "")))
5888                 (cons 'Newsgroups newsgroups)))
5889              (t
5890               (if (or (equal followup-to newsgroups)
5891                       (not (eq message-use-followup-to 'ask))
5892                       (message-y-or-n-p
5893                        (concat "Obey Followup-To: " followup-to "? ") t "\
5894 You should normally obey the Followup-To: header.
5895
5896         `Followup-To: " followup-to "'
5897 directs your response to " (if (string-match "," followup-to)
5898                                "the specified newsgroups"
5899                              "that newsgroup only") ".
5900
5901 If a message is posted to several newsgroups, Followup-To is often
5902 used to direct the following discussion to one newsgroup only,
5903 because discussions that are spread over several newsgroup tend to
5904 be fragmented and very difficult to follow.
5905
5906 Also, some source/announcement newsgroups are not intended for discussion;
5907 responses here are directed to other newsgroups."))
5908                   (cons 'Newsgroups followup-to)
5909                 (cons 'Newsgroups newsgroups))))))
5910           (posted-to
5911            `((Newsgroups . ,posted-to)))
5912           (t
5913            `((Newsgroups . ,newsgroups))))
5914        ,@(and distribution (list (cons 'Distribution distribution)))
5915        ,@(when (and mct
5916                     (not (or (equal (downcase mct) "never")
5917                              (equal (downcase mct) "nobody"))))
5918            (list (cons 'Cc (if (or (equal (downcase mct) "always")
5919                                    (equal (downcase mct) "poster"))
5920                                (or mrt reply-to from "")
5921                              mct)))))
5922
5923      cur)))
5924
5925 (defun message-is-yours-p ()
5926   "Non-nil means current article is yours.
5927 If you have added 'cancel-messages to 'message-shoot-gnksa-feet', all articles
5928 are yours except those that have Cancel-Lock header not belonging to you.
5929 Instead of shooting GNKSA feet, you should modify 'message-alternative-emails'
5930 regexp to match all of yours addresses."
5931   ;; Canlock-logic as suggested by Per Abrahamsen
5932   ;; <abraham@dina.kvl.dk>
5933   ;;
5934   ;; IF article has cancel-lock THEN
5935   ;;   IF we can verify it THEN
5936   ;;     issue cancel
5937   ;;   ELSE
5938   ;;     error: cancellock: article is not yours
5939   ;; ELSE
5940   ;;   Use old rules, comparing sender...
5941   (save-excursion
5942     (save-restriction
5943       (message-narrow-to-head-1)
5944       (if (message-fetch-field "Cancel-Lock")
5945           (if (null (canlock-verify))
5946               t
5947             (error "Failed to verify Cancel-lock: This article is not yours"))
5948         (let (sender from)
5949           (or
5950            (message-gnksa-enable-p 'cancel-messages)
5951            (and (setq sender (message-fetch-field "sender"))
5952                 (string-equal (downcase sender)
5953                               (downcase (message-make-sender))))
5954            ;; Email address in From field equals to our address
5955            (and (setq from (message-fetch-field "from"))
5956                 (string-equal
5957                  (downcase (cadr (mail-extract-address-components from)))
5958                  (downcase (cadr (mail-extract-address-components
5959                                   (message-make-from))))))
5960            ;; Email address in From field matches
5961            ;; 'message-alternative-emails' regexp
5962            (and from
5963                 message-alternative-emails
5964                 (string-match
5965                  message-alternative-emails
5966                  (cadr (mail-extract-address-components from))))))))))
5967
5968 ;;;###autoload
5969 (defun message-cancel-news (&optional arg)
5970   "Cancel an article you posted.
5971 If ARG, allow editing of the cancellation message."
5972   (interactive "P")
5973   (unless (message-news-p)
5974     (error "This is not a news article; canceling is impossible"))
5975   (let (from newsgroups message-id distribution buf)
5976     (save-excursion
5977       ;; Get header info from original article.
5978       (save-restriction
5979         (message-narrow-to-head-1)
5980         (setq from (message-fetch-field "from")
5981               newsgroups (message-fetch-field "newsgroups")
5982               message-id (message-fetch-field "message-id" t)
5983               distribution (message-fetch-field "distribution")))
5984       ;; Make sure that this article was written by the user.
5985       (unless (message-is-yours-p)
5986         (error "This article is not yours"))
5987       (when (yes-or-no-p "Do you really want to cancel this article? ")
5988         ;; Make control message.
5989         (if arg
5990             (message-news)
5991           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5992         (erase-buffer)
5993         (insert "Newsgroups: " newsgroups "\n"
5994                 "From: " from "\n"
5995                 "Subject: cmsg cancel " message-id "\n"
5996                 "Control: cancel " message-id "\n"
5997                 (if distribution
5998                     (concat "Distribution: " distribution "\n")
5999                   "")
6000                 mail-header-separator "\n"
6001                 message-cancel-message)
6002         (run-hooks 'message-cancel-hook)
6003         (unless arg
6004           (message "Canceling your article...")
6005           (if (let ((message-syntax-checks
6006                      'dont-check-for-anything-just-trust-me))
6007                 (funcall message-send-news-function))
6008               (message "Canceling your article...done"))
6009           (kill-buffer buf))))))
6010
6011 ;;;###autoload
6012 (defun message-supersede ()
6013   "Start composing a message to supersede the current message.
6014 This is done simply by taking the old article and adding a Supersedes
6015 header line with the old Message-ID."
6016   (interactive)
6017   (let ((cur (current-buffer)))
6018     ;; Check whether the user owns the article that is to be superseded.
6019     (unless (message-is-yours-p)
6020       (error "This article is not yours"))
6021     ;; Get a normal message buffer.
6022     (message-pop-to-buffer (message-buffer-name "supersede"))
6023     (insert-buffer-substring cur)
6024     (mime-to-mml)
6025     (message-narrow-to-head-1)
6026     ;; Remove unwanted headers.
6027     (when message-ignored-supersedes-headers
6028       (message-remove-header message-ignored-supersedes-headers t))
6029     (goto-char (point-min))
6030     (if (not (re-search-forward "^Message-ID: " nil t))
6031         (error "No Message-ID in this article")
6032       (replace-match "Supersedes: " t t))
6033     (goto-char (point-max))
6034     (insert mail-header-separator)
6035     (widen)
6036     (forward-line 1)))
6037
6038 ;;;###autoload
6039 (defun message-recover ()
6040   "Reread contents of current buffer from its last auto-save file."
6041   (interactive)
6042   (let ((file-name (make-auto-save-file-name)))
6043     (cond ((save-window-excursion
6044              (if (not (eq system-type 'vax-vms))
6045                  (with-output-to-temp-buffer "*Directory*"
6046                    (with-current-buffer standard-output
6047                      (fundamental-mode)) ; for Emacs 20.4+
6048                    (buffer-disable-undo standard-output)
6049                    (let ((default-directory "/"))
6050                      (call-process
6051                       "ls" nil standard-output nil "-l" file-name))))
6052              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6053            (let ((buffer-read-only nil))
6054              (erase-buffer)
6055              (insert-file-contents file-name nil)))
6056           (t (error "message-recover cancelled")))))
6057
6058 ;;; Washing Subject:
6059
6060 (defun message-wash-subject (subject)
6061   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6062 Previous forwarders, replyers, etc. may add it."
6063   (with-temp-buffer
6064     (insert subject)
6065     (goto-char (point-min))
6066     ;; strip Re/Fwd stuff off the beginning
6067     (while (re-search-forward
6068             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6069       (replace-match ""))
6070
6071     ;; and gnus-style forwards [foo@bar.com] subject
6072     (goto-char (point-min))
6073     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6074       (replace-match ""))
6075
6076     ;; and off the end
6077     (goto-char (point-max))
6078     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6079       (replace-match ""))
6080
6081     ;; and finally, any whitespace that was left-over
6082     (goto-char (point-min))
6083     (while (re-search-forward "^[ \t]+" nil t)
6084       (replace-match ""))
6085     (goto-char (point-max))
6086     (while (re-search-backward "[ \t]+$" nil t)
6087       (replace-match ""))
6088
6089     (buffer-string)))
6090
6091 ;;; Forwarding messages.
6092
6093 (defvar message-forward-decoded-p nil
6094   "Non-nil means the original message is decoded.")
6095
6096 (defun message-forward-subject-name-subject (subject)
6097   "Generate a SUBJECT for a forwarded message.
6098 The form is: [Source] Subject, where if the original message was mail,
6099 Source is the name of the sender, and if the original message was
6100 news, Source is the list of newsgroups is was posted to."
6101   (let* ((group (message-fetch-field "newsgroups"))
6102          (from (message-fetch-field "from"))
6103          (prefix
6104           (if group
6105               (gnus-group-decoded-name group)
6106             (or (and from (car (gnus-extract-address-components from)))
6107                 "(nowhere)"))))
6108     (concat "["
6109             (if message-forward-decoded-p
6110                 prefix
6111               (mail-decode-encoded-word-string prefix))
6112             "] " subject)))
6113
6114 (defun message-forward-subject-author-subject (subject)
6115   "Generate a SUBJECT for a forwarded message.
6116 The form is: [Source] Subject, where if the original message was mail,
6117 Source is the sender, and if the original message was news, Source is
6118 the list of newsgroups is was posted to."
6119   (let* ((group (message-fetch-field "newsgroups"))
6120          (prefix
6121           (if group
6122               (gnus-group-decoded-name group)
6123             (or (message-fetch-field "from")
6124                 "(nowhere)"))))
6125     (concat "["
6126             (if message-forward-decoded-p
6127                 prefix
6128               (mail-decode-encoded-word-string prefix))
6129             "] " subject)))
6130
6131 (defun message-forward-subject-fwd (subject)
6132   "Generate a SUBJECT for a forwarded message.
6133 The form is: Fwd: Subject, where Subject is the original subject of
6134 the message."
6135   (if (string-match "^Fwd: " subject)
6136       subject
6137     (concat "Fwd: " subject)))
6138
6139 (defun message-make-forward-subject ()
6140   "Return a Subject header suitable for the message in the current buffer."
6141   (save-excursion
6142     (save-restriction
6143       (message-narrow-to-head-1)
6144       (let ((funcs message-make-forward-subject-function)
6145             (subject (message-fetch-field "Subject")))
6146         (setq subject
6147               (if subject
6148                   (if message-forward-decoded-p
6149                       subject
6150                     (mail-decode-encoded-word-string subject))
6151                 ""))
6152         (when message-wash-forwarded-subjects
6153           (setq subject (message-wash-subject subject)))
6154         ;; Make sure funcs is a list.
6155         (and funcs
6156              (not (listp funcs))
6157              (setq funcs (list funcs)))
6158         ;; Apply funcs in order, passing subject generated by previous
6159         ;; func to the next one.
6160         (dolist (func funcs)
6161           (when (functionp func)
6162             (setq subject (funcall func subject))))
6163         subject))))
6164
6165 (eval-when-compile
6166   (defvar gnus-article-decoded-p))
6167
6168
6169 ;;;###autoload
6170 (defun message-forward (&optional news digest)
6171   "Forward the current message via mail.
6172 Optional NEWS will use news to forward instead of mail.
6173 Optional DIGEST will use digest to forward."
6174   (interactive "P")
6175   (let* ((cur (current-buffer))
6176          (message-forward-decoded-p
6177           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
6178               gnus-article-decoded-p ;; In an article buffer.
6179             message-forward-decoded-p))
6180          (subject (message-make-forward-subject)))
6181     (if news
6182         (message-news nil subject)
6183       (message-mail nil subject))
6184     (message-forward-make-body cur digest)))
6185
6186 (defun message-forward-make-body-plain (forward-buffer)
6187   (insert
6188    "\n-------------------- Start of forwarded message --------------------\n")
6189   (let ((b (point)) e)
6190     (insert
6191      (with-temp-buffer
6192        (mm-disable-multibyte)
6193        (insert
6194         (with-current-buffer forward-buffer
6195           (mm-with-unibyte-current-buffer (buffer-string))))
6196        (mm-enable-multibyte)
6197        (mime-to-mml)
6198        (goto-char (point-min))
6199        (when (looking-at "From ")
6200          (replace-match "X-From-Line: "))
6201        (buffer-string)))
6202     (setq e (point))
6203     (insert
6204      "\n-------------------- End of forwarded message --------------------\n")
6205     (when (and (not current-prefix-arg)
6206                message-forward-ignored-headers)
6207       (save-restriction
6208         (narrow-to-region b e)
6209         (goto-char b)
6210         (narrow-to-region (point)
6211                           (or (search-forward "\n\n" nil t) (point)))
6212         (message-remove-header message-forward-ignored-headers t)))))
6213
6214 (defun message-forward-make-body-mime (forward-buffer)
6215   (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
6216   (let ((b (point)) e)
6217     (save-restriction
6218       (narrow-to-region (point) (point))
6219       (mml-insert-buffer forward-buffer)
6220       (goto-char (point-min))
6221       (when (looking-at "From ")
6222         (replace-match "X-From-Line: "))
6223       (goto-char (point-max)))
6224     (setq e (point))
6225     (insert "<#/part>\n")))
6226
6227 (defun message-forward-make-body-mml (forward-buffer)
6228   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
6229   (let ((b (point)) e)
6230     (if (not message-forward-decoded-p)
6231         (insert
6232          (with-temp-buffer
6233            (mm-disable-multibyte)
6234            (insert
6235             (with-current-buffer forward-buffer
6236               (mm-with-unibyte-current-buffer (buffer-string))))
6237            (mm-enable-multibyte)
6238            (mime-to-mml)
6239            (goto-char (point-min))
6240            (when (looking-at "From ")
6241              (replace-match "X-From-Line: "))
6242            (buffer-string)))
6243       (save-restriction
6244         (narrow-to-region (point) (point))
6245         (mml-insert-buffer forward-buffer)
6246         (goto-char (point-min))
6247         (when (looking-at "From ")
6248           (replace-match "X-From-Line: "))
6249         (goto-char (point-max))))
6250     (setq e (point))
6251     (insert "<#/mml>\n")
6252     (when (and (not current-prefix-arg)
6253                message-forward-ignored-headers)
6254       (save-restriction
6255         (narrow-to-region b e)
6256         (goto-char b)
6257         (narrow-to-region (point)
6258                           (or (search-forward "\n\n" nil t) (point)))
6259         (message-remove-header message-forward-ignored-headers t)))))
6260
6261 (defun message-forward-make-body-digest-plain (forward-buffer)
6262   (insert
6263    "\n-------------------- Start of forwarded message --------------------\n")
6264   (let ((b (point)) e)
6265     (mml-insert-buffer forward-buffer)
6266     (setq e (point))
6267     (insert
6268      "\n-------------------- End of forwarded message --------------------\n")))
6269
6270 (defun message-forward-make-body-digest-mime (forward-buffer)
6271   (insert "\n<#multipart type=digest>\n")
6272   (let ((b (point)) e)
6273     (insert-buffer-substring forward-buffer)
6274     (setq e (point))
6275     (insert "<#/multipart>\n")
6276     (save-restriction
6277       (narrow-to-region b e)
6278       (goto-char b)
6279       (narrow-to-region (point)
6280                         (or (search-forward "\n\n" nil t) (point)))
6281       (delete-region (point-min) (point-max)))))
6282
6283 (defun message-forward-make-body-digest (forward-buffer)
6284   (if message-forward-as-mime
6285       (message-forward-make-body-digest-mime forward-buffer)
6286     (message-forward-make-body-digest-plain forward-buffer)))
6287
6288 ;;;###autoload
6289 (defun message-forward-make-body (forward-buffer &optional digest)
6290   ;; Put point where we want it before inserting the forwarded
6291   ;; message.
6292   (if message-forward-before-signature
6293       (message-goto-body)
6294     (goto-char (point-max)))
6295   (if digest
6296       (message-forward-make-body-digest forward-buffer)
6297     (if message-forward-as-mime
6298         (if (and message-forward-show-mml
6299                  (not (and (eq message-forward-show-mml 'best)
6300                            (with-current-buffer forward-buffer
6301                              (goto-char (point-min))
6302                              (re-search-forward
6303                               "Content-Type: *multipart/\\(signed\\|encrypted\\)"
6304                               nil t)))))
6305             (message-forward-make-body-mml forward-buffer)
6306           (message-forward-make-body-mime forward-buffer))
6307       (message-forward-make-body-plain forward-buffer)))
6308   (message-position-point))
6309
6310 ;;;###autoload
6311 (defun message-forward-rmail-make-body (forward-buffer)
6312   (save-window-excursion
6313     (set-buffer forward-buffer)
6314     (if (rmail-msg-is-pruned)
6315         (rmail-msg-restore-non-pruned-header)))
6316   (message-forward-make-body forward-buffer))
6317
6318 (eval-when-compile (defvar rmail-enable-mime-composing))
6319
6320 ;; Fixme: Should have defcustom.
6321 ;;;###autoload
6322 (defun message-insinuate-rmail ()
6323   "Let RMAIL use message to forward."
6324   (interactive)
6325   (setq rmail-enable-mime-composing t)
6326   (setq rmail-insert-mime-forwarded-message-function
6327         'message-forward-rmail-make-body))
6328
6329 ;;;###autoload
6330 (defun message-resend (address)
6331   "Resend the current article to ADDRESS."
6332   (interactive
6333    (list (message-read-from-minibuffer "Resend message to: ")))
6334   (message "Resending message to %s..." address)
6335   (save-excursion
6336     (let ((cur (current-buffer))
6337           beg)
6338       ;; We first set up a normal mail buffer.
6339       (unless (message-mail-user-agent)
6340         (set-buffer (get-buffer-create " *message resend*"))
6341         (erase-buffer))
6342       (let ((message-this-is-mail t)
6343             message-setup-hook)
6344         (message-setup `((To . ,address))))
6345       ;; Insert our usual headers.
6346       (message-generate-headers '(From Date To Message-ID))
6347       (message-narrow-to-headers)
6348       ;; Remove X-Draft-From header etc.
6349       (message-remove-header message-ignored-mail-headers t)
6350       ;; Rename them all to "Resent-*".
6351       (goto-char (point-min))
6352       (while (re-search-forward "^[A-Za-z]" nil t)
6353         (forward-char -1)
6354         (insert "Resent-"))
6355       (widen)
6356       (forward-line)
6357       (delete-region (point) (point-max))
6358       (setq beg (point))
6359       ;; Insert the message to be resent.
6360       (insert-buffer-substring cur)
6361       (goto-char (point-min))
6362       (search-forward "\n\n")
6363       (forward-char -1)
6364       (save-restriction
6365         (narrow-to-region beg (point))
6366         (message-remove-header message-ignored-resent-headers t)
6367         (goto-char (point-max)))
6368       (insert mail-header-separator)
6369       ;; Rename all old ("Also-")Resent headers.
6370       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6371         (beginning-of-line)
6372         (insert "Also-"))
6373       ;; Quote any "From " lines at the beginning.
6374       (goto-char beg)
6375       (when (looking-at "From ")
6376         (replace-match "X-From-Line: "))
6377       ;; Send it.
6378       (let ((message-inhibit-body-encoding t)
6379             message-required-mail-headers
6380             rfc2047-encode-encoded-words)
6381         (message-send-mail))
6382       (kill-buffer (current-buffer)))
6383     (message "Resending message to %s...done" address)))
6384
6385 ;;;###autoload
6386 (defun message-bounce ()
6387   "Re-mail the current message.
6388 This only makes sense if the current message is a bounce message that
6389 contains some mail you have written which has been bounced back to
6390 you."
6391   (interactive)
6392   (let ((handles (mm-dissect-buffer t))
6393         boundary)
6394     (message-pop-to-buffer (message-buffer-name "bounce"))
6395     (if (stringp (car handles))
6396         ;; This is a MIME bounce.
6397         (mm-insert-part (car (last handles)))
6398       ;; This is a non-MIME bounce, so we try to remove things
6399       ;; manually.
6400       (mm-insert-part handles)
6401       (undo-boundary)
6402       (goto-char (point-min))
6403       (re-search-forward "\n\n+" nil t)
6404       (setq boundary (point))
6405       ;; We remove everything before the bounced mail.
6406       (if (or (re-search-forward message-unsent-separator nil t)
6407               (progn
6408                 (search-forward "\n\n" nil 'move)
6409                 (re-search-backward "^Return-Path:.*\n" boundary t)))
6410           (progn
6411             (forward-line 1)
6412             (delete-region (point-min)
6413                            (if (re-search-forward "^[^ \n\t]+:" nil t)
6414                                (match-beginning 0)
6415                              (point))))
6416         (goto-char boundary)
6417         (when (re-search-backward "^.?From .*\n" nil t)
6418           (delete-region (match-beginning 0) (match-end 0)))))
6419     (mm-enable-multibyte)
6420     (save-restriction
6421       (message-narrow-to-head-1)
6422       (message-remove-header message-ignored-bounced-headers t)
6423       (goto-char (point-max))
6424       (insert mail-header-separator))
6425     (message-position-point)))
6426
6427 ;;;
6428 ;;; Interactive entry points for new message buffers.
6429 ;;;
6430
6431 ;;;###autoload
6432 (defun message-mail-other-window (&optional to subject)
6433   "Like `message-mail' command, but display mail buffer in another window."
6434   (interactive)
6435   (unless (message-mail-user-agent)
6436     (let ((pop-up-windows t)
6437           (special-display-buffer-names nil)
6438           (special-display-regexps nil)
6439           (same-window-buffer-names nil)
6440           (same-window-regexps nil))
6441       (message-pop-to-buffer (message-buffer-name "mail" to))))
6442   (let ((message-this-is-mail t))
6443     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6444                    nil nil 'switch-to-buffer-other-window)))
6445
6446 ;;;###autoload
6447 (defun message-mail-other-frame (&optional to subject)
6448   "Like `message-mail' command, but display mail buffer in another frame."
6449   (interactive)
6450   (unless (message-mail-user-agent)
6451     (let ((pop-up-frames t)
6452           (special-display-buffer-names nil)
6453           (special-display-regexps nil)
6454           (same-window-buffer-names nil)
6455           (same-window-regexps nil))
6456       (message-pop-to-buffer (message-buffer-name "mail" to))))
6457   (let ((message-this-is-mail t))
6458     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6459                    nil nil 'switch-to-buffer-other-frame)))
6460
6461 ;;;###autoload
6462 (defun message-news-other-window (&optional newsgroups subject)
6463   "Start editing a news article to be sent."
6464   (interactive)
6465   (let ((pop-up-windows t)
6466         (special-display-buffer-names nil)
6467         (special-display-regexps nil)
6468         (same-window-buffer-names nil)
6469         (same-window-regexps nil))
6470     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6471   (let ((message-this-is-news t))
6472     (message-setup `((Newsgroups . ,(or newsgroups ""))
6473                      (Subject . ,(or subject ""))))))
6474
6475 ;;;###autoload
6476 (defun message-news-other-frame (&optional newsgroups subject)
6477   "Start editing a news article to be sent."
6478   (interactive)
6479   (let ((pop-up-frames t)
6480         (special-display-buffer-names nil)
6481         (special-display-regexps nil)
6482         (same-window-buffer-names nil)
6483         (same-window-regexps nil))
6484     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6485   (let ((message-this-is-news t))
6486     (message-setup `((Newsgroups . ,(or newsgroups ""))
6487                      (Subject . ,(or subject ""))))))
6488
6489 ;;; underline.el
6490
6491 ;; This code should be moved to underline.el (from which it is stolen).
6492
6493 ;;;###autoload
6494 (defun bold-region (start end)
6495   "Bold all nonblank characters in the region.
6496 Works by overstriking characters.
6497 Called from program, takes two arguments START and END
6498 which specify the range to operate on."
6499   (interactive "r")
6500   (save-excursion
6501     (let ((end1 (make-marker)))
6502       (move-marker end1 (max start end))
6503       (goto-char (min start end))
6504       (while (< (point) end1)
6505         (or (looking-at "[_\^@- ]")
6506             (insert (char-after) "\b"))
6507         (forward-char 1)))))
6508
6509 ;;;###autoload
6510 (defun unbold-region (start end)
6511   "Remove all boldness (overstruck characters) in the region.
6512 Called from program, takes two arguments START and END
6513 which specify the range to operate on."
6514   (interactive "r")
6515   (save-excursion
6516     (let ((end1 (make-marker)))
6517       (move-marker end1 (max start end))
6518       (goto-char (min start end))
6519       (while (search-forward "\b" end1 t)
6520         (if (eq (char-after) (char-after (- (point) 2)))
6521             (delete-char -2))))))
6522
6523 (defun message-exchange-point-and-mark ()
6524   "Exchange point and mark, but don't activate region if it was inactive."
6525   (unless (prog1
6526               (message-mark-active-p)
6527             (exchange-point-and-mark))
6528     (setq mark-active nil)))
6529
6530 (defalias 'message-make-overlay 'make-overlay)
6531 (defalias 'message-delete-overlay 'delete-overlay)
6532 (defalias 'message-overlay-put 'overlay-put)
6533 (defun message-kill-all-overlays ()
6534   (if (featurep 'xemacs)
6535       (map-extents (lambda (extent ignore) (delete-extent extent)))
6536     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
6537
6538 ;; Support for toolbar
6539 (eval-when-compile
6540   (defvar tool-bar-map)
6541   (defvar tool-bar-mode))
6542
6543 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6544   ;; We need to make tool bar entries in local keymaps with
6545   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6546   (if (fboundp 'tool-bar-local-item-from-menu)
6547       ;; This is for Emacs 21.3
6548       (tool-bar-local-item-from-menu command icon in-map from-map props)
6549     (tool-bar-add-item-from-menu command icon from-map props)))
6550
6551 (defun message-tool-bar-map ()
6552   (or message-tool-bar-map
6553       (setq message-tool-bar-map
6554             (and
6555              (condition-case nil (require 'tool-bar) (error nil))
6556              (fboundp 'tool-bar-add-item-from-menu)
6557              tool-bar-mode
6558              (let ((tool-bar-map (copy-keymap tool-bar-map))
6559                    (load-path (mm-image-load-path)))
6560                ;; Zap some items which aren't so relevant and take
6561                ;; up space.
6562                (dolist (key '(print-buffer kill-buffer save-buffer
6563                                            write-file dired open-file))
6564                  (define-key tool-bar-map (vector key) nil))
6565                (message-tool-bar-local-item-from-menu
6566                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
6567                (message-tool-bar-local-item-from-menu
6568                 'message-kill-buffer "close" tool-bar-map message-mode-map)
6569                (message-tool-bar-local-item-from-menu
6570                     'message-dont-send "cancel" tool-bar-map message-mode-map)
6571                (message-tool-bar-local-item-from-menu
6572                 'mml-attach-file "attach" tool-bar-map mml-mode-map)
6573                (message-tool-bar-local-item-from-menu
6574                 'ispell-message "spell" tool-bar-map message-mode-map)
6575                (message-tool-bar-local-item-from-menu
6576                 'mml-preview "preview"
6577                 tool-bar-map mml-mode-map)
6578                (message-tool-bar-local-item-from-menu
6579                 'message-insert-importance-high "important"
6580                 tool-bar-map message-mode-map)
6581                (message-tool-bar-local-item-from-menu
6582                 'message-insert-importance-low "unimportant"
6583                 tool-bar-map message-mode-map)
6584                (message-tool-bar-local-item-from-menu
6585                 'message-insert-disposition-notification-to "receipt"
6586                 tool-bar-map message-mode-map)
6587                tool-bar-map)))))
6588
6589 ;;; Group name completion.
6590
6591 (defcustom message-newgroups-header-regexp
6592   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6593   "Regexp that match headers that lists groups."
6594   :group 'message
6595   :type 'regexp)
6596
6597 (defcustom message-completion-alist
6598   (list (cons message-newgroups-header-regexp 'message-expand-group)
6599         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6600         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6601           . message-expand-name)
6602         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6603           . message-expand-name))
6604   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6605   :group 'message
6606   :type '(alist :key-type regexp :value-type function))
6607
6608 (defcustom message-expand-name-databases
6609   (list 'bbdb 'eudc)
6610   "List of databases to try for name completion (`message-expand-name').
6611 Each element is a symbol and can be `bbdb' or `eudc'."
6612   :group 'message
6613   :type '(set (const bbdb) (const eudc)))
6614
6615 (defcustom message-tab-body-function nil
6616   "*Function to execute when `message-tab' (TAB) is executed in the body.
6617 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6618   :version "21.4"
6619   :group 'message
6620   :link '(custom-manual "(message)Various Commands")
6621   :type 'function)
6622
6623 (defun message-tab ()
6624   "Complete names according to `message-completion-alist'.
6625 Execute function specified by `message-tab-body-function' when not in
6626 those headers."
6627   (interactive)
6628   (let ((alist message-completion-alist))
6629     (while (and alist
6630                 (let ((mail-abbrev-mode-regexp (caar alist)))
6631                   (not (mail-abbrev-in-expansion-header-p))))
6632       (setq alist (cdr alist)))
6633     (funcall (or (cdar alist) message-tab-body-function
6634                  (lookup-key text-mode-map "\t")
6635                  (lookup-key global-map "\t")
6636                  'indent-relative))))
6637
6638 (defun message-expand-group ()
6639   "Expand the group name under point."
6640   (let* ((b (save-excursion
6641               (save-restriction
6642                 (narrow-to-region
6643                  (save-excursion
6644                    (beginning-of-line)
6645                    (skip-chars-forward "^:")
6646                    (1+ (point)))
6647                  (point))
6648                 (skip-chars-backward "^, \t\n") (point))))
6649          (completion-ignore-case t)
6650          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6651                                             (point))))
6652          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6653          (completions (all-completions string hashtb))
6654          comp)
6655     (delete-region b (point))
6656     (cond
6657      ((= (length completions) 1)
6658       (if (string= (car completions) string)
6659           (progn
6660             (insert string)
6661             (message "Only matching group"))
6662         (insert (car completions))))
6663      ((and (setq comp (try-completion string hashtb))
6664            (not (string= comp string)))
6665       (insert comp))
6666      (t
6667       (insert string)
6668       (if (not comp)
6669           (message "No matching groups")
6670         (save-selected-window
6671           (pop-to-buffer "*Completions*")
6672           (buffer-disable-undo)
6673           (let ((buffer-read-only nil))
6674             (erase-buffer)
6675             (let ((standard-output (current-buffer)))
6676               (display-completion-list (sort completions 'string<)))
6677             (goto-char (point-min))
6678             (delete-region (point) (progn (forward-line 3) (point))))))))))
6679
6680 (defun message-expand-name ()
6681   (cond ((and (memq 'eudc message-expand-name-databases)
6682                     (boundp 'eudc-protocol)
6683                     eudc-protocol)
6684          (eudc-expand-inline))
6685         ((and (memq 'bbdb message-expand-name-databases)
6686               (fboundp 'bbdb-complete-name))
6687          (bbdb-complete-name))
6688         (t
6689          (expand-abbrev))))
6690
6691 ;;; Help stuff.
6692
6693 (defun message-talkative-question (ask question show &rest text)
6694   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6695 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6696 The following arguments may contain lists of values."
6697   (if (and show
6698            (setq text (message-flatten-list text)))
6699       (save-window-excursion
6700         (save-excursion
6701           (with-output-to-temp-buffer " *MESSAGE information message*"
6702             (set-buffer " *MESSAGE information message*")
6703             (fundamental-mode)          ; for Emacs 20.4+
6704             (mapcar 'princ text)
6705             (goto-char (point-min))))
6706         (funcall ask question))
6707     (funcall ask question)))
6708
6709 (defun message-flatten-list (list)
6710   "Return a new, flat list that contains all elements of LIST.
6711
6712 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6713 => (1 2 3 4 5 6 7)"
6714   (cond ((consp list)
6715          (apply 'append (mapcar 'message-flatten-list list)))
6716         (list
6717          (list list))))
6718
6719 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6720   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
6721 Then clone the local variables and values from the old buffer to the
6722 new one, cloning only the locals having a substring matching the
6723 regexp VARSTR."
6724   (let ((oldbuf (current-buffer)))
6725     (save-excursion
6726       (set-buffer (generate-new-buffer name))
6727       (message-clone-locals oldbuf varstr)
6728       (current-buffer))))
6729
6730 (defun message-clone-locals (buffer &optional varstr)
6731   "Clone the local variables from BUFFER to the current buffer."
6732   (let ((locals (save-excursion
6733                   (set-buffer buffer)
6734                   (buffer-local-variables)))
6735         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address"))
6736     (mapcar
6737      (lambda (local)
6738        (when (and (consp local)
6739                   (car local)
6740                   (string-match regexp (symbol-name (car local)))
6741                   (or (null varstr)
6742                       (string-match varstr (symbol-name (car local)))))
6743          (ignore-errors
6744            (set (make-local-variable (car local))
6745                 (cdr local)))))
6746      locals)))
6747
6748 ;;;
6749 ;;; MIME functions
6750 ;;;
6751
6752 (defvar message-inhibit-body-encoding nil)
6753
6754 (defun message-encode-message-body ()
6755   (unless message-inhibit-body-encoding
6756     (let ((mail-parse-charset (or mail-parse-charset
6757                                   message-default-charset))
6758           (case-fold-search t)
6759           lines content-type-p)
6760       (message-goto-body)
6761       (save-restriction
6762         (narrow-to-region (point) (point-max))
6763         (let ((new (mml-generate-mime)))
6764           (when new
6765             (delete-region (point-min) (point-max))
6766             (insert new)
6767             (goto-char (point-min))
6768             (if (eq (aref new 0) ?\n)
6769                 (delete-char 1)
6770               (search-forward "\n\n")
6771               (setq lines (buffer-substring (point-min) (1- (point))))
6772               (delete-region (point-min) (point))))))
6773       (save-restriction
6774         (message-narrow-to-headers-or-head)
6775         (message-remove-header "Mime-Version")
6776         (goto-char (point-max))
6777         (insert "MIME-Version: 1.0\n")
6778         (when lines
6779           (insert lines))
6780         (setq content-type-p
6781               (or mml-boundary
6782                   (re-search-backward "^Content-Type:" nil t))))
6783       (save-restriction
6784         (message-narrow-to-headers-or-head)
6785         (message-remove-first-header "Content-Type")
6786         (message-remove-first-header "Content-Transfer-Encoding"))
6787       ;; We always make sure that the message has a Content-Type
6788       ;; header.  This is because some broken MTAs and MUAs get
6789       ;; awfully confused when confronted with a message with a
6790       ;; MIME-Version header and without a Content-Type header.  For
6791       ;; instance, Solaris' /usr/bin/mail.
6792       (unless content-type-p
6793         (goto-char (point-min))
6794         ;; For unknown reason, MIME-Version doesn't exist.
6795         (when (re-search-forward "^MIME-Version:" nil t)
6796           (forward-line 1)
6797           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6798
6799 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6800   "Read from the minibuffer while providing abbrev expansion."
6801   (if (fboundp 'mail-abbrevs-setup)
6802       (let ((mail-abbrev-mode-regexp "")
6803             (minibuffer-setup-hook 'mail-abbrevs-setup)
6804             (minibuffer-local-map message-minibuffer-local-map))
6805         (read-from-minibuffer prompt initial-contents))
6806     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6807           (minibuffer-local-map message-minibuffer-local-map))
6808       (read-string prompt initial-contents))))
6809
6810 (defun message-use-alternative-email-as-from ()
6811   (require 'mail-utils)
6812   (let* ((fields '("To" "Cc"))
6813          (emails
6814           (split-string
6815            (mail-strip-quoted-names
6816             (mapconcat 'message-fetch-reply-field fields ","))
6817            "[ \f\t\n\r\v,]+"))
6818          email)
6819     (while emails
6820       (if (string-match message-alternative-emails (car emails))
6821           (setq email (car emails)
6822                 emails nil))
6823       (pop emails))
6824     (unless (or (not email) (equal email user-mail-address))
6825       (goto-char (point-max))
6826       (insert "From: " email "\n"))))
6827
6828 (defun message-options-get (symbol)
6829   (cdr (assq symbol message-options)))
6830
6831 (defun message-options-set (symbol value)
6832   (let ((the-cons (assq symbol message-options)))
6833     (if the-cons
6834         (if value
6835             (setcdr the-cons value)
6836           (setq message-options (delq the-cons message-options)))
6837       (and value
6838            (push (cons symbol value) message-options))))
6839   value)
6840
6841 (defun message-options-set-recipient ()
6842   (save-restriction
6843     (message-narrow-to-headers-or-head)
6844     (message-options-set 'message-sender
6845                          (mail-strip-quoted-names
6846                           (message-fetch-field "from")))
6847     (message-options-set 'message-recipients
6848                          (mail-strip-quoted-names
6849                           (let ((to (message-fetch-field "to"))
6850                                 (cc (message-fetch-field "cc"))
6851                                 (bcc (message-fetch-field "bcc")))
6852                             (concat
6853                              (or to "")
6854                              (if (and to cc) ", ")
6855                              (or cc "")
6856                              (if (and (or to cc) bcc) ", ")
6857                              (or bcc "")))))))
6858
6859 (defun message-hide-headers ()
6860   "Hide headers based on the `message-hidden-headers' variable."
6861   (let ((regexps (if (stringp message-hidden-headers)
6862                      (list message-hidden-headers)
6863                    message-hidden-headers))
6864         (inhibit-point-motion-hooks t)
6865         (after-change-functions nil))
6866     (when regexps
6867       (save-excursion
6868         (save-restriction
6869           (message-narrow-to-headers)
6870           (goto-char (point-min))
6871           (while (not (eobp))
6872             (if (not (message-hide-header-p regexps))
6873                 (message-next-header)
6874               (let ((begin (point)))
6875                 (message-next-header)
6876                 (add-text-properties
6877                  begin (point)
6878                  '(invisible t message-hidden t))))))))))
6879
6880 (defun message-hide-header-p (regexps)
6881   (let ((result nil)
6882         (reverse nil))
6883     (when (eq (car regexps) 'not)
6884       (setq reverse t)
6885       (pop regexps))
6886     (dolist (regexp regexps)
6887       (setq result (or result (looking-at regexp))))
6888     (if reverse
6889         (not result)
6890       result)))
6891
6892 (when (featurep 'xemacs)
6893   (require 'messagexmas)
6894   (message-xmas-redefine))
6895
6896 (provide 'message)
6897
6898 (run-hooks 'message-load-hook)
6899
6900 ;; Local Variables:
6901 ;; coding: iso-8859-1
6902 ;; End:
6903
6904 ;;; arch-tag: 94b32cac-4504-4b6c-8181-030ebf380ee0
6905 ;;; message.el ends here