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