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