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