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