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