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