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