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