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