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