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