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