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