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