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