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