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