Sync 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 'message-reply-headers)
1845   (setq message-reply-headers nil)
1846   (make-local-variable 'message-user-agent)
1847   (make-local-variable 'message-post-method)
1848   (set (make-local-variable 'message-sent-message-via) nil)
1849   (set (make-local-variable 'message-checksum) nil)
1850   (make-local-variable 'message-parameter-alist)
1851   (setq message-parameter-alist
1852         (copy-sequence message-startup-parameter-alist))
1853   (message-setup-fill-variables)
1854   ;;(when (fboundp 'mail-hist-define-keys)
1855   ;;  (mail-hist-define-keys))
1856   (if (featurep 'xemacs)
1857       (message-setup-toolbar)
1858     (set (make-local-variable 'font-lock-defaults)
1859          '((message-font-lock-keywords
1860             message-font-lock-keywords-1
1861             message-font-lock-keywords-2)
1862            nil nil nil nil
1863            (font-lock-mark-block-function . mark-paragraph))))
1864   (set (make-local-variable 'message-font-lock-last-position) nil)
1865   (easy-menu-add message-mode-menu message-mode-map)
1866   (easy-menu-add message-mode-field-menu message-mode-map)
1867   ;; Allow mail alias things.
1868   (when (eq message-mail-alias-type 'abbrev)
1869     (if (fboundp 'mail-abbrevs-setup)
1870         (mail-abbrevs-setup)
1871       (mail-aliases-setup)))
1872   (message-set-auto-save-file-name)
1873   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1874   (setq indent-tabs-mode nil)
1875   (run-hooks 'text-mode-hook 'message-mode-hook))
1876
1877 (defun message-setup-fill-variables ()
1878   "Setup message fill variables."
1879   (make-local-variable 'paragraph-separate)
1880   (make-local-variable 'paragraph-start)
1881   (make-local-variable 'adaptive-fill-regexp)
1882   (unless (boundp 'adaptive-fill-first-line-regexp)
1883     (setq adaptive-fill-first-line-regexp nil))
1884   (make-local-variable 'adaptive-fill-first-line-regexp)
1885   (make-local-variable 'auto-fill-inhibit-regexp)
1886   (let ((quote-prefix-regexp
1887          (concat
1888           "[ \t]*"                      ; possible initial space
1889           "\\(\\(" (regexp-quote message-yank-prefix) "\\|" ; user's prefix
1890           "\\w+>\\|"                    ; supercite-style prefix
1891           "[|:>]"                       ; standard prefix
1892           "\\)[ \t]*\\)+")))            ; possible space after each prefix
1893     (setq paragraph-start
1894           (concat
1895            (regexp-quote mail-header-separator) "$\\|"
1896            "[ \t]*$\\|"                 ; blank lines
1897            "-- $\\|"                    ; signature delimiter
1898            "---+$\\|"                   ; delimiters for forwarded messages
1899            page-delimiter "$\\|"        ; spoiler warnings
1900            ".*wrote:$\\|"               ; attribution lines
1901            quote-prefix-regexp "$"))    ; empty lines in quoted text
1902     (setq paragraph-separate paragraph-start)
1903     (setq adaptive-fill-regexp
1904           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1905     (setq adaptive-fill-first-line-regexp
1906           (concat quote-prefix-regexp "\\|"
1907                   adaptive-fill-first-line-regexp))
1908     (setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")))
1909
1910 \f
1911
1912 ;;;
1913 ;;; Message mode commands
1914 ;;;
1915
1916 ;;; Movement commands
1917
1918 (defun message-goto-to ()
1919   "Move point to the To header."
1920   (interactive)
1921   (message-position-on-field "To"))
1922
1923 (defun message-goto-subject ()
1924   "Move point to the Subject header."
1925   (interactive)
1926   (message-position-on-field "Subject"))
1927
1928 (defun message-goto-cc ()
1929   "Move point to the Cc header."
1930   (interactive)
1931   (message-position-on-field "Cc" "To"))
1932
1933 (defun message-goto-bcc ()
1934   "Move point to the Bcc  header."
1935   (interactive)
1936   (message-position-on-field "Bcc" "Cc" "To"))
1937
1938 (defun message-goto-fcc ()
1939   "Move point to the Fcc header."
1940   (interactive)
1941   (message-position-on-field "Fcc" "To" "Newsgroups"))
1942
1943 (defun message-goto-reply-to ()
1944   "Move point to the Reply-To header."
1945   (interactive)
1946   (message-position-on-field "Reply-To" "Subject"))
1947
1948 (defun message-goto-mail-reply-to ()
1949   "Move point to the Mail-Reply-To header."
1950   (interactive)
1951   (message-position-on-field "Mail-Reply-To" "Subject"))
1952
1953 (defun message-goto-mail-followup-to ()
1954   "Move point to the Mail-Followup-To header.  If the header is newly created
1955 and To field contains only one address, the address is inserted in default."
1956   (interactive)
1957   (unless (message-position-on-field "Mail-Followup-To" "Subject")
1958     (let ((start (point))
1959           addresses)
1960       (save-restriction
1961         (message-narrow-to-headers)
1962         (setq addresses (split-string (mail-strip-quoted-names
1963                                        (or (std11-fetch-field "to") ""))
1964                                       "[ \f\t\n\r\v,]+"))
1965         (when (eq 1 (length addresses))
1966           (goto-char start)
1967           (insert (car addresses))
1968           (goto-char start))))))
1969
1970 (defun message-goto-mail-copies-to ()
1971   "Move point to the Mail-Copies-To header.  If the header is newly created,
1972 a string \"never\" is inserted in default."
1973   (interactive)
1974   (unless (message-position-on-field "Mail-Copies-To" "Subject")
1975     (insert "never")
1976     (backward-char 5)))
1977
1978 (defun message-goto-newsgroups ()
1979   "Move point to the Newsgroups header."
1980   (interactive)
1981   (message-position-on-field "Newsgroups"))
1982
1983 (defun message-goto-distribution ()
1984   "Move point to the Distribution header."
1985   (interactive)
1986   (message-position-on-field "Distribution"))
1987
1988 (defun message-goto-followup-to ()
1989   "Move point to the Followup-To header."
1990   (interactive)
1991   (message-position-on-field "Followup-To" "Newsgroups"))
1992
1993 (defun message-goto-keywords ()
1994   "Move point to the Keywords header."
1995   (interactive)
1996   (message-position-on-field "Keywords" "Subject"))
1997
1998 (defun message-goto-summary ()
1999   "Move point to the Summary header."
2000   (interactive)
2001   (message-position-on-field "Summary" "Subject"))
2002
2003 (defun message-goto-body ()
2004   "Move point to the beginning of the message body."
2005   (interactive)
2006   (if (looking-at "[ \t]*\n") (expand-abbrev))
2007   (goto-char (point-min))
2008   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2009       (search-forward "\n\n" nil t)))
2010
2011 (defun message-goto-eoh ()
2012   "Move point to the end of the headers."
2013   (interactive)
2014   (message-goto-body)
2015   (forward-line -1))
2016
2017 (defun message-goto-signature ()
2018   "Move point to the beginning of the message signature.
2019 If there is no signature in the article, go to the end and
2020 return nil."
2021   (interactive)
2022   (goto-char (point-min))
2023   (if (re-search-forward message-signature-separator nil t)
2024       (forward-line 1)
2025     (goto-char (point-max))
2026     nil))
2027
2028 \f
2029
2030 (defun message-insert-to (&optional force)
2031   "Insert a To header that points to the author of the article being replied to.
2032 If the original author requested not to be sent mail, the function signals
2033 an error.
2034 With the prefix argument FORCE, insert the header anyway."
2035   (interactive "P")
2036   (let ((co (message-fetch-reply-field "mail-copies-to")))
2037     (when (and (null force)
2038                co
2039                (or (equal (downcase co) "never")
2040                    (equal (downcase co) "nobody")))
2041       (error "The user has requested not to have copies sent via mail")))
2042   (when (and (message-position-on-field "To")
2043              (mail-fetch-field "to")
2044              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
2045     (insert ", "))
2046   (insert (or (message-fetch-reply-field "reply-to")
2047               (message-fetch-reply-field "from") "")))
2048
2049 (defun message-widen-reply ()
2050   "Widen the reply to include maximum recipients."
2051   (interactive)
2052   (let ((follow-to
2053          (and message-reply-buffer
2054               (buffer-name message-reply-buffer)
2055               (save-excursion
2056                 (set-buffer message-reply-buffer)
2057                 (message-get-reply-headers t)))))
2058     (save-excursion
2059       (save-restriction
2060         (message-narrow-to-headers)
2061         (dolist (elem follow-to)
2062           (message-remove-header (symbol-name (car elem)))
2063           (goto-char (point-min))
2064           (insert (symbol-name (car elem)) ": "
2065                   (cdr elem) "\n"))))))
2066
2067 (defun message-insert-newsgroups ()
2068   "Insert the Newsgroups header from the article being replied to."
2069   (interactive)
2070   (when (and (message-position-on-field "Newsgroups")
2071              (mail-fetch-field "newsgroups")
2072              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2073     (insert ","))
2074   (insert (or (message-fetch-reply-field "newsgroups") "")))
2075
2076 \f
2077
2078 ;;; Various commands
2079
2080 (defun message-delete-not-region (beg end)
2081   "Delete everything in the body of the current message that is outside of the region."
2082   (interactive "r")
2083   (save-excursion
2084     (goto-char end)
2085     (delete-region (point) (if (not (message-goto-signature))
2086                                (point)
2087                              (forward-line -2)
2088                              (point)))
2089     (insert "\n")
2090     (goto-char beg)
2091     (delete-region beg (progn (message-goto-body)
2092                               (forward-line 2)
2093                               (point))))
2094   (when (message-goto-signature)
2095     (forward-line -2)))
2096
2097 (defun message-kill-to-signature ()
2098   "Deletes all text up to the signature."
2099   (interactive)
2100   (let ((point (point)))
2101     (message-goto-signature)
2102     (unless (eobp)
2103       (forward-line -2))
2104     (kill-region point (point))
2105     (unless (bolp)
2106       (insert "\n"))))
2107
2108 (defun message-newline-and-reformat ()
2109   "Insert four newlines, and then reformat if inside quoted text."
2110   (interactive)
2111   (let ((prefix "[]>»|:}+ \t]*")
2112         (supercite-thing "[-._a-zA-Z0-9]*[>]+[ \t]*")
2113         quoted point)
2114     (unless (bolp)
2115       (save-excursion
2116         (beginning-of-line)
2117         (when (looking-at (concat prefix
2118                                   supercite-thing))
2119           (setq quoted (match-string 0))))
2120       (insert "\n"))
2121     (setq point (point))
2122     (insert "\n\n\n")
2123     (delete-region (point) (re-search-forward "[ \t]*"))
2124     (when quoted
2125       (insert quoted))
2126     (fill-paragraph nil)
2127     (goto-char point)
2128     (forward-line 1)))
2129
2130 (defun message-insert-signature (&optional force)
2131   "Insert a signature.  See documentation for the `message-signature' variable."
2132   (interactive (list 0))
2133   (let* ((signature
2134           (cond
2135            ((and (null message-signature)
2136                  (eq force 0))
2137             (save-excursion
2138               (goto-char (point-max))
2139               (not (re-search-backward message-signature-separator nil t))))
2140            ((and (null message-signature)
2141                  force)
2142             t)
2143            ((message-functionp message-signature)
2144             (funcall message-signature))
2145            ((listp message-signature)
2146             (eval message-signature))
2147            (t message-signature)))
2148          (signature
2149           (cond ((stringp signature)
2150                  signature)
2151                 ((and (eq t signature)
2152                       message-signature-file
2153                       (file-exists-p message-signature-file))
2154                  signature))))
2155     (when signature
2156       (goto-char (point-max))
2157       ;; Insert the signature.
2158       (unless (bolp)
2159         (insert "\n"))
2160       (insert "\n-- \n")
2161       (if (eq signature t)
2162           (insert-file-contents message-signature-file)
2163         (insert signature))
2164       (goto-char (point-max))
2165       (or (bolp) (insert "\n")))))
2166
2167 (defun message-elide-region (b e)
2168   "Elide the text between point and mark.
2169 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2170 text was killed."
2171   (interactive "r")
2172   (kill-region b e)
2173   (insert message-elide-ellipsis))
2174
2175 (defvar message-caesar-translation-table nil)
2176
2177 (defun message-caesar-region (b e &optional n)
2178   "Caesar rotation of region by N, default 13, for decrypting netnews."
2179   (interactive
2180    (list
2181     (min (point) (or (mark t) (point)))
2182     (max (point) (or (mark t) (point)))
2183     (when current-prefix-arg
2184       (prefix-numeric-value current-prefix-arg))))
2185
2186   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2187   (unless (or (zerop n)                 ; no action needed for a rot of 0
2188               (= b e))                  ; no region to rotate
2189     ;; We build the table, if necessary.
2190     (when (or (not message-caesar-translation-table)
2191               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2192       (setq message-caesar-translation-table
2193             (message-make-caesar-translation-table n)))
2194     (translate-region b e message-caesar-translation-table)))
2195
2196 (defun message-make-caesar-translation-table (n)
2197   "Create a rot table with offset N."
2198   (let ((i -1)
2199         (table (make-string 256 0)))
2200     (while (< (incf i) 256)
2201       (aset table i i))
2202     (concat
2203      (substring table 0 ?A)
2204      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2205      (substring table ?A (+ ?A n))
2206      (substring table (+ ?A 26) ?a)
2207      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2208      (substring table ?a (+ ?a n))
2209      (substring table (+ ?a 26) 255))))
2210
2211 (defun message-caesar-buffer-body (&optional rotnum)
2212   "Caesar rotates all letters in the current buffer by 13 places.
2213 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
2214 With prefix arg, specifies the number of places to rotate each letter forward.
2215 Mail and USENET news headers are not rotated."
2216   (interactive (if current-prefix-arg
2217                    (list (prefix-numeric-value current-prefix-arg))
2218                  (list nil)))
2219   (save-excursion
2220     (save-restriction
2221       (when (message-goto-body)
2222         (narrow-to-region (point) (point-max)))
2223       (message-caesar-region (point-min) (point-max) rotnum))))
2224
2225 (defun message-pipe-buffer-body (program)
2226   "Pipe the message body in the current buffer through PROGRAM."
2227   (save-excursion
2228     (save-restriction
2229       (when (message-goto-body)
2230         (narrow-to-region (point) (point-max)))
2231       (shell-command-on-region
2232        (point-min) (point-max) program nil t))))
2233
2234 (defun message-rename-buffer (&optional enter-string)
2235   "Rename the *message* buffer to \"*message* RECIPIENT\".
2236 If the function is run with a prefix, it will ask for a new buffer
2237 name, rather than giving an automatic name."
2238   (interactive "Pbuffer name: ")
2239   (save-excursion
2240     (save-restriction
2241       (goto-char (point-min))
2242       (narrow-to-region (point)
2243                         (search-forward mail-header-separator nil 'end))
2244       (let* ((mail-to (or
2245                        (if (message-news-p) (message-fetch-field "Newsgroups")
2246                          (message-fetch-field "To"))
2247                        ""))
2248              (mail-trimmed-to
2249               (if (string-match "," mail-to)
2250                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2251                 mail-to))
2252              (name-default (concat "*message* " mail-trimmed-to))
2253              (name (if enter-string
2254                        (read-string "New buffer name: " name-default)
2255                      name-default)))
2256         (rename-buffer name t)))))
2257
2258 (defun message-fill-yanked-message (&optional justifyp)
2259   "Fill the paragraphs of a message yanked into this one.
2260 Numeric argument means justify as well."
2261   (interactive "P")
2262   (save-excursion
2263     (goto-char (point-min))
2264     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2265     (let ((fill-prefix message-yank-prefix))
2266       (fill-individual-paragraphs (point) (point-max) justifyp))))
2267
2268 (defun message-indent-citation ()
2269   "Modify text just inserted from a message to be cited.
2270 The inserted text should be the region.
2271 When this function returns, the region is again around the modified text.
2272
2273 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2274 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2275   (let ((start (point)))
2276     ;; Remove unwanted headers.
2277     (when message-ignored-cited-headers
2278       (let (all-removed)
2279         (save-restriction
2280           (narrow-to-region
2281            (goto-char start)
2282            (if (search-forward "\n\n" nil t)
2283                (1- (point))
2284              (point)))
2285           (message-remove-header message-ignored-cited-headers t)
2286           (when (= (point-min) (point-max))
2287             (setq all-removed t))
2288           (goto-char (point-max)))
2289         (if all-removed
2290             (goto-char start)
2291           (forward-line 1))))
2292     ;; Delete blank lines at the start of the buffer.
2293     (while (and (point-min)
2294                 (eolp)
2295                 (not (eobp)))
2296       (message-delete-line))
2297     ;; Delete blank lines at the end of the buffer.
2298     (goto-char (point-max))
2299     (unless (bolp)
2300       (insert "\n"))
2301     (while (and (zerop (forward-line -1))
2302                 (looking-at "$"))
2303       (message-delete-line))
2304     ;; Do the indentation.
2305     (if (null message-yank-prefix)
2306         (indent-rigidly start (mark t) message-indentation-spaces)
2307       (save-excursion
2308         (goto-char start)
2309         (while (< (point) (mark t))
2310           (insert message-yank-prefix)
2311           (forward-line 1))))
2312     (goto-char start)))
2313
2314 (defun message-list-references (refs-list &rest refs-strs)
2315   "Add `Message-ID's which appear in REFS-STRS but not in REFS-LIST,
2316 to REFS-LIST."
2317   (let (refs ref id saved-id)
2318     (when (and refs-list
2319                (integerp message-list-references-add-position))
2320       (let ((pos message-list-references-add-position))
2321         (while (and refs-list
2322                     (> pos 0))
2323           (push (pop refs-list) saved-id)
2324           (setq pos (1- pos)))))
2325     (while refs-strs
2326       (when (setq refs (pop refs-strs))
2327         (setq refs (std11-parse-msg-ids (std11-lexical-analyze refs)))
2328         (while refs
2329           (when (eq (car (setq ref (pop refs))) 'msg-id)
2330             (setq id (concat "<" (mapconcat 'cdr (cdr ref) "") ">"))
2331             (or (member id refs-list)
2332                 (member id saved-id)
2333                 (push id refs-list))))))
2334     (while saved-id
2335       (push (pop saved-id) refs-list))
2336     refs-list))
2337
2338 (defvar gnus-article-copy)
2339 (defun message-yank-original (&optional arg)
2340   "Insert the message being replied to, if any.
2341 Puts point before the text and mark after.
2342 Normally indents each nonblank line ARG spaces (default 3).  However,
2343 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2344
2345 This function uses `message-cite-function' to do the actual citing.
2346
2347 Just \\[universal-argument] as argument means don't indent, insert no
2348 prefix, and don't delete any headers.
2349
2350 In addition, if `message-yank-add-new-references' is non-nil and this
2351 command is called interactively, new IDs from the yanked article will
2352 be added to \"References\" field.
2353 \(See also `message-yank-add-new-references'.)"
2354   (interactive "P")
2355   (let ((modified (buffer-modified-p))
2356         (buffer (message-eval-parameter message-reply-buffer))
2357         start end refs)
2358     (when (and buffer
2359                message-cite-function)
2360       (delete-windows-on buffer t)
2361       (insert-buffer buffer) ; mark will be set at the end of article.
2362       (setq start (point)
2363             end (mark t))
2364
2365       ;; Add new IDs to References field.
2366       (when (and message-yank-add-new-references (interactive-p))
2367         (save-excursion
2368           (save-restriction
2369             (message-narrow-to-headers)
2370             (setq refs (message-list-references
2371                         nil
2372                         (message-fetch-field "References")))
2373             (widen)
2374             (narrow-to-region start end)
2375             (std11-narrow-to-header)
2376             (when (setq refs (message-list-references
2377                               refs
2378                               (unless (eq message-yank-add-new-references
2379                                           'message-id-only)
2380                                 (or (message-fetch-field "References")
2381                                     (message-fetch-field "In-Reply-To")))
2382                               (message-fetch-field "Message-ID")))
2383               (widen)
2384               (message-narrow-to-headers)
2385               (goto-char (point-min))
2386               (let ((case-fold-search t))
2387                 (if (re-search-forward "^References:\\([\t ]+.+\n\\)+" nil t)
2388                     (replace-match "")
2389                   (goto-char (point-max))))
2390               (mail-header-format
2391                (list (or (assq 'References message-header-format-alist)
2392                          '(References . message-fill-references)))
2393                (list (cons 'References
2394                            (mapconcat 'identity (nreverse refs) " "))))
2395               (backward-delete-char 1)))))
2396
2397       (funcall message-cite-function)
2398       (message-exchange-point-and-mark)
2399       (unless (bolp)
2400         (insert ?\n))
2401       (unless modified
2402         (setq message-checksum (message-checksum))))))
2403
2404 (defun message-yank-buffer (buffer)
2405   "Insert BUFFER into the current buffer and quote it."
2406   (interactive "bYank buffer: ")
2407   (let ((message-reply-buffer buffer))
2408     (save-window-excursion
2409       (message-yank-original))))
2410
2411 (defun message-buffers ()
2412   "Return a list of active message buffers."
2413   (let (buffers)
2414     (save-excursion
2415       (dolist (buffer (buffer-list t))
2416         (set-buffer buffer)
2417         (when (and (eq major-mode 'message-mode)
2418                    (null message-sent-message-via))
2419           (push (buffer-name buffer) buffers))))
2420     (nreverse buffers)))
2421
2422 (defun message-cite-original-without-signature ()
2423   "Cite function in the standard Message manner."
2424   (let ((start (point))
2425         (end (mark t))
2426         (functions
2427          (when message-indent-citation-function
2428            (if (listp message-indent-citation-function)
2429                message-indent-citation-function
2430              (list message-indent-citation-function)))))
2431     ;; Allow undoing.
2432     (undo-boundary)
2433     (goto-char end)
2434     (when (re-search-backward message-signature-separator start t)
2435       ;; Also peel off any blank lines before the signature.
2436       (forward-line -1)
2437       (while (looking-at "^[ \t]*$")
2438         (forward-line -1))
2439       (forward-line 1)
2440       (delete-region (point) end))
2441     (goto-char start)
2442     (while functions
2443       (funcall (pop functions)))
2444     (when message-citation-line-function
2445       (unless (bolp)
2446         (insert "\n"))
2447       (funcall message-citation-line-function))))
2448
2449 (defvar mail-citation-hook)             ;Compiler directive
2450 (defun message-cite-original ()
2451   "Cite function in the standard Message manner."
2452   (if (and (boundp 'mail-citation-hook)
2453            mail-citation-hook)
2454       (run-hooks 'mail-citation-hook)
2455     (let ((start (point))
2456           (end (mark t))
2457           (functions
2458            (when message-indent-citation-function
2459              (if (listp message-indent-citation-function)
2460                  message-indent-citation-function
2461                (list message-indent-citation-function))))
2462           (message-reply-headers (or message-reply-headers
2463                                      (make-mail-header))))
2464       (mail-header-set-from message-reply-headers
2465                             (save-restriction
2466                               (narrow-to-region
2467                                (point)
2468                                (if (search-forward "\n\n" nil t)
2469                                    (1- (point))
2470                                  (point-max)))
2471                               (or (message-fetch-field "from")
2472                                   "unknown sender")))
2473       (goto-char start)
2474       (while functions
2475         (funcall (pop functions)))
2476       (when message-citation-line-function
2477         (unless (bolp)
2478           (insert "\n"))
2479         (funcall message-citation-line-function)))))
2480
2481 (defun message-insert-citation-line ()
2482   "Function that inserts a simple citation line."
2483   (when message-reply-headers
2484     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2485
2486 (defun message-position-on-field (header &rest afters)
2487   (let ((case-fold-search t))
2488     (save-restriction
2489       (narrow-to-region
2490        (goto-char (point-min))
2491        (progn
2492          (re-search-forward
2493           (concat "^" (regexp-quote mail-header-separator) "$"))
2494          (match-beginning 0)))
2495       (goto-char (point-min))
2496       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2497           (progn
2498             (re-search-forward "^[^ \t]" nil 'move)
2499             (beginning-of-line)
2500             (skip-chars-backward "\n")
2501             t)
2502         (while (and afters
2503                     (not (re-search-forward
2504                           (concat "^" (regexp-quote (car afters)) ":")
2505                           nil t)))
2506           (pop afters))
2507         (when afters
2508           (re-search-forward "^[^ \t]" nil 'move)
2509           (beginning-of-line))
2510         (insert header ": \n")
2511         (forward-char -1)
2512         nil))))
2513
2514 (defun message-remove-signature ()
2515   "Remove the signature from the text between point and mark.
2516 The text will also be indented the normal way."
2517   (save-excursion
2518     (let ((start (point))
2519           mark)
2520       (if (not (re-search-forward message-signature-separator (mark t) t))
2521           ;; No signature here, so we just indent the cited text.
2522           (message-indent-citation)
2523         ;; Find the last non-empty line.
2524         (forward-line -1)
2525         (while (looking-at "[ \t]*$")
2526           (forward-line -1))
2527         (forward-line 1)
2528         (setq mark (set-marker (make-marker) (point)))
2529         (goto-char start)
2530         (message-indent-citation)
2531         ;; Enable undoing the deletion.
2532         (undo-boundary)
2533         (delete-region mark (mark t))
2534         (set-marker mark nil)))))
2535
2536 \f
2537
2538 ;;;
2539 ;;; Sending messages
2540 ;;;
2541
2542 ;; Avoid byte-compile warning.
2543 (defvar message-encoding-buffer nil)
2544 (defvar message-edit-buffer nil)
2545 (defvar message-mime-mode nil)
2546
2547 (defun message-send-and-exit (&optional arg)
2548   "Send message like `message-send', then, if no errors, exit from mail buffer."
2549   (interactive "P")
2550   (let ((buf (current-buffer))
2551         (actions message-exit-actions)
2552         (frame (selected-frame))
2553         (org-frame message-original-frame))
2554     (when (and (message-send arg)
2555                (buffer-name buf))
2556       (if message-kill-buffer-on-exit
2557           (kill-buffer buf)
2558         (bury-buffer buf)
2559         (when (eq buf (current-buffer))
2560           (message-bury buf)))
2561       (message-do-actions actions)
2562       (message-delete-frame frame org-frame)
2563       t)))
2564
2565 (defun message-dont-send ()
2566   "Don't send the message you have been editing."
2567   (interactive)
2568   (message-save-drafts)
2569   (let ((actions message-postpone-actions)
2570         (frame (selected-frame))
2571         (org-frame message-original-frame))
2572     (message-bury (current-buffer))
2573     (message-do-actions actions)
2574     (message-delete-frame frame org-frame)))
2575
2576 (defun message-kill-buffer ()
2577   "Kill the current buffer."
2578   (interactive)
2579   (when (or (not (buffer-modified-p))
2580             (eq t message-kill-buffer-query-function)
2581             (funcall message-kill-buffer-query-function
2582                      "The buffer modified; kill anyway? "))
2583     (let ((actions message-kill-actions)
2584           (frame (selected-frame))
2585           (org-frame message-original-frame))
2586       (setq buffer-file-name nil)
2587       (kill-buffer (current-buffer))
2588       (message-do-actions actions)
2589       (message-delete-frame frame org-frame)))
2590   (message ""))
2591
2592 (defun message-mimic-kill-buffer ()
2593   "Kill the current buffer with query."
2594   (interactive)
2595   (unless (eq 'message-mode major-mode)
2596     (error "%s must be invoked from a message buffer." this-command))
2597   (let ((command this-command)
2598         (bufname (read-buffer (format "Kill buffer: (default %s) "
2599                                       (buffer-name)))))
2600     (if (or (not bufname)
2601             (string-equal bufname "")
2602             (string-equal bufname (buffer-name)))
2603         (message-kill-buffer)
2604       (message "%s must be invoked only for the current buffer." command))))
2605
2606 (defun message-delete-frame (frame org-frame)
2607   "Delete frame for editing message."
2608   (when (and (or (static-if (featurep 'xemacs)
2609                      (device-on-window-system-p)
2610                    window-system)
2611                  (>= emacs-major-version 20))
2612              (or (and (eq message-delete-frame-on-exit t)
2613                       (select-frame frame)
2614                       (or (eq frame org-frame)
2615                           (prog1
2616                               (y-or-n-p "Delete this frame?")
2617                             (message ""))))
2618                  (and (eq message-delete-frame-on-exit 'ask)
2619                       (select-frame frame)
2620                       (prog1
2621                           (y-or-n-p "Delete this frame?")
2622                         (message "")))))
2623     (delete-frame frame)))
2624
2625 (defun message-bury (buffer)
2626   "Bury this mail buffer."
2627   (let ((newbuf (other-buffer buffer)))
2628     (bury-buffer buffer)
2629     (if (and (fboundp 'frame-parameters)
2630              (cdr (assq 'dedicated (frame-parameters)))
2631              (not (null (delq (selected-frame) (visible-frame-list)))))
2632         (delete-frame (selected-frame))
2633       (switch-to-buffer newbuf))))
2634
2635 (defun message-send (&optional arg)
2636   "Send the message in the current buffer.
2637 If `message-interactive' is non-nil, wait for success indication or
2638 error messages, and inform user.
2639 Otherwise any failure is reported in a message back to the user from
2640 the mailer.
2641 The usage of ARG is defined by the instance that called Message.
2642 It should typically alter the sending method in some way or other."
2643   (interactive "P")
2644   ;; Disabled test.
2645   (when (or (buffer-modified-p)
2646             (message-check-element 'unchanged)
2647             (y-or-n-p "No changes in the buffer; really send? "))
2648     ;; Make it possible to undo the coming changes.
2649     (undo-boundary)
2650     (let ((inhibit-read-only t))
2651       (put-text-property (point-min) (point-max) 'read-only nil))
2652     (run-hooks 'message-send-hook)
2653     (message-fix-before-sending)
2654     (message "Sending...")
2655     (let ((message-encoding-buffer
2656            (message-generate-new-buffer-clone-locals " message encoding"))
2657           (message-edit-buffer (current-buffer))
2658           (message-mime-mode mime-edit-mode-flag)
2659           (alist message-send-method-alist)
2660           (success t)
2661           elem sent)
2662       (save-excursion
2663         (set-buffer message-encoding-buffer)
2664         (erase-buffer)
2665         (insert-buffer message-edit-buffer)
2666         (funcall message-encode-function)
2667         (while (and success
2668                     (setq elem (pop alist)))
2669           (when (funcall (cadr elem))
2670             (when (and (or (not (memq (car elem)
2671                                       message-sent-message-via))
2672                            (y-or-n-p
2673                             (format
2674                              "Already sent message via %s; resend? "
2675                              (car elem))))
2676                        (setq success (funcall (caddr elem) arg)))
2677               (setq sent t)))))
2678       (unless (or sent (not success))
2679         (error "No methods specified to send by"))
2680       (prog1
2681           (when (and success sent)
2682             (message-do-fcc)
2683             (save-excursion
2684               (run-hooks 'message-sent-hook))
2685             (message "Sending...done")
2686             ;; Mark the buffer as unmodified and delete autosave.
2687             (set-buffer-modified-p nil)
2688             (delete-auto-save-file-if-necessary t)
2689             (message-disassociate-draft)
2690             ;; Delete other mail buffers and stuff.
2691             (message-do-send-housekeeping)
2692             (message-do-actions message-send-actions)
2693             ;; Return success.
2694             t)
2695         (kill-buffer message-encoding-buffer)))))
2696
2697 (defun message-send-via-mail (arg)
2698   "Send the current message via mail."
2699   (message-send-mail arg))
2700
2701 (defun message-send-via-news (arg)
2702   "Send the current message via news."
2703   (message-send-news arg))
2704
2705 (defmacro message-check (type &rest forms)
2706   "Eval FORMS if TYPE is to be checked."
2707   `(or (message-check-element ,type)
2708        (save-excursion
2709          ,@forms)))
2710
2711 (put 'message-check 'lisp-indent-function 1)
2712 (put 'message-check 'edebug-form-spec '(form body))
2713
2714 ;; This function will be used by MIME-Edit when inserting invisible parts.
2715 (defun message-invisible-region (start end)
2716   (if (featurep 'xemacs)
2717       (if (save-excursion
2718             (goto-char start)
2719             (eq (following-char) ?\n))
2720           (setq start (1+ start)))
2721     (if (save-excursion
2722           (goto-char (1- end))
2723           (eq (following-char) ?\n))
2724         (setq end (1- end))))
2725   (put-text-property start end 'invisible t)
2726   (if (eq 'message-mode major-mode)
2727       (put-text-property start end 'message-invisible t)))
2728
2729 (eval-after-load "invisible"
2730   '(defalias 'invisible-region 'message-invisible-region))
2731
2732 (defun message-fix-before-sending ()
2733   "Do various things to make the message nice before sending it."
2734   ;; Make sure there's a newline at the end of the message.
2735   (widen)
2736   (goto-char (point-max))
2737   (unless (bolp)
2738     (insert "\n"))
2739   ;; Expose all invisible text with the property `message-invisible'.
2740   ;; We should believe that the things might be created by MIME-Edit.
2741   (let (start)
2742     (while (setq start (text-property-any (point-min) (point-max)
2743                                           'message-invisible t))
2744       (remove-text-properties start
2745                               (or (text-property-not-all start (point-max)
2746                                                          'message-invisible t)
2747                                   (point-max))
2748                               '(invisible nil message-invisible nil))))
2749   ;; Expose all invisible text.
2750   (message-check 'invisible-text
2751     (when (text-property-any (point-min) (point-max) 'invisible t)
2752       (put-text-property (point-min) (point-max) 'invisible nil)
2753       (unless (yes-or-no-p
2754                "Invisible text found and made visible; continue posting? ")
2755         (error "Invisible text found and made visible")))))
2756
2757 (defun message-add-action (action &rest types)
2758   "Add ACTION to be performed when doing an exit of type TYPES."
2759   (let (var)
2760     (while types
2761       (set (setq var (intern (format "message-%s-actions" (pop types))))
2762            (nconc (symbol-value var) (list action))))))
2763
2764 (defun message-do-actions (actions)
2765   "Perform all actions in ACTIONS."
2766   ;; Now perform actions on successful sending.
2767   (while actions
2768     (ignore-errors
2769       (cond
2770        ;; A simple function.
2771        ((message-functionp (car actions))
2772         (funcall (car actions)))
2773        ;; Something to be evaled.
2774        (t
2775         (eval (car actions)))))
2776     (pop actions)))
2777
2778 (defsubst message-maybe-split-and-send-mail ()
2779   "Split a message if necessary, and send it via mail.
2780 Returns nil if sending succeeded, returns any string if sending failed.
2781 This sub function is for exclusive use of `message-send-mail'."
2782   (let ((mime-edit-split-ignored-field-regexp
2783          mime-edit-split-ignored-field-regexp)
2784         (case-fold-search t)
2785         failure)
2786     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
2787       (setq mime-edit-split-ignored-field-regexp
2788             (concat (substring mime-edit-split-ignored-field-regexp
2789                                0 (match-beginning 0))
2790                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
2791                     "_so_don't_rape_it!"
2792                     (substring mime-edit-split-ignored-field-regexp
2793                                (match-end 0)))))
2794     (setq failure
2795           (or
2796            (catch 'message-sending-mail-failure
2797              (mime-edit-maybe-split-and-send
2798               (function
2799                (lambda ()
2800                  (interactive)
2801                  (save-restriction
2802                    (std11-narrow-to-header mail-header-separator)
2803                    (goto-char (point-min))
2804                    (when (re-search-forward "^Message-ID:" nil t)
2805                      (delete-region (match-end 0) (std11-field-end))
2806                      (insert " " (message-make-message-id))))
2807                  (condition-case err
2808                      (funcall message-send-mail-function)
2809                    (error
2810                     (throw 'message-sending-mail-failure err))))))
2811              nil)
2812            (condition-case err
2813                (progn
2814                  (funcall message-send-mail-function)
2815                  nil)
2816              (error err))))
2817     (when failure
2818       (if (eq 'error (car failure))
2819           (cadr failure)
2820         (prin1-to-string failure)))))
2821
2822 (defun message-send-mail-partially ()
2823   "Sendmail as message/partial."
2824   (let ((p (goto-char (point-min)))
2825         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2826         (curbuf (current-buffer))
2827         (id (message-make-message-id)) (n 1)
2828         plist total  header required-mail-headers)
2829     (while (not (eobp))
2830       (if (< (point-max) (+ p message-send-mail-partially-limit))
2831           (goto-char (point-max))
2832         (goto-char (+ p message-send-mail-partially-limit))
2833         (beginning-of-line)
2834         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2835       (push p plist)
2836       (setq p (point)))
2837     (setq total (length plist))
2838     (push (point-max) plist)
2839     (setq plist (nreverse plist))
2840     (unwind-protect
2841         (save-excursion
2842           (setq p (pop plist))
2843           (while plist
2844             (set-buffer curbuf)
2845             (copy-to-buffer tembuf p (car plist))
2846             (set-buffer tembuf)
2847             (goto-char (point-min))
2848             (if header
2849                 (progn
2850                   (goto-char (point-min))
2851                   (narrow-to-region (point) (point))
2852                   (insert header))
2853               (message-goto-eoh)
2854               (setq header (buffer-substring (point-min) (point)))
2855               (goto-char (point-min))
2856               (narrow-to-region (point) (point))
2857               (insert header)
2858               (message-remove-header "Mime-Version")
2859               (message-remove-header "Content-Type")
2860               (message-remove-header "Content-Transfer-Encoding")
2861               (message-remove-header "Message-ID")
2862               (message-remove-header "Lines")
2863               (goto-char (point-max))
2864               (insert "Mime-Version: 1.0\n")
2865               (setq header (buffer-substring (point-min) (point-max))))
2866             (goto-char (point-max))
2867             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n"
2868                             id n total))
2869             (let ((mail-header-separator ""))
2870               (when (memq 'Message-ID message-required-mail-headers)
2871                 (insert "Message-ID: " (message-make-message-id) "\n"))
2872               (when (memq 'Lines message-required-mail-headers)
2873                 (let ((mail-header-separator ""))
2874                   (insert "Lines: " (message-make-lines) "\n")))
2875               (message-goto-subject)
2876               (end-of-line)
2877               (insert (format " (%d/%d)" n total))
2878               (goto-char (point-max))
2879               (insert "\n")
2880               (widen)
2881               (mm-with-unibyte-current-buffer
2882                 (funcall message-send-mail-function)))
2883             (setq n (+ n 1))
2884             (setq p (pop plist))
2885             (erase-buffer)))
2886       (kill-buffer tembuf))))
2887
2888 (defun message-send-mail (&optional arg)
2889   (require 'mail-utils)
2890   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2891          (case-fold-search nil)
2892          (news (message-news-p))
2893          (message-this-is-mail t)
2894          failure)
2895     (save-restriction
2896       (message-narrow-to-headers)
2897       ;; Insert some headers.
2898       (let ((message-deletable-headers
2899              (if news nil message-deletable-headers)))
2900         (message-generate-headers message-required-mail-headers))
2901       ;; Let the user do all of the above.
2902       (run-hooks 'message-header-hook))
2903     (if (not (message-check-mail-syntax))
2904         (progn
2905           (message "")
2906           nil)
2907       (unwind-protect
2908           (save-excursion
2909             (set-buffer tembuf)
2910             (erase-buffer)
2911             (insert-buffer message-encoding-buffer)
2912             ;; Remove some headers.
2913             (save-restriction
2914               (message-narrow-to-headers)
2915 ;; We Semi-gnus people have no use for it.
2916 ;;            ;; We (re)generate the Lines header.
2917 ;;            (when (memq 'Lines message-required-mail-headers)
2918 ;;              (message-generate-headers '(Lines)))
2919               ;; Remove some headers.
2920               (message-remove-header message-ignored-mail-headers t))
2921             (goto-char (point-max))
2922             ;; require one newline at the end.
2923             (or (= (preceding-char) ?\n)
2924                 (insert ?\n))
2925             (when
2926                 (save-restriction
2927                   (message-narrow-to-headers)
2928                   (and news
2929                        (or (message-fetch-field "cc")
2930                            (message-fetch-field "to"))
2931                        (let ((ct (mime-read-Content-Type)))
2932                          (and (eq 'text (cdr (assq 'type ct)))
2933                               (eq 'plain (cdr (assq 'subtype ct)))))))
2934               (message-insert-courtesy-copy))
2935             (setq failure (message-maybe-split-and-send-mail)))
2936         (kill-buffer tembuf))
2937       (set-buffer message-edit-buffer)
2938       (if failure
2939           (progn
2940             (message "Couldn't send message via mail: %s" failure)
2941             nil)
2942         (push 'mail message-sent-message-via)))))
2943
2944 (defun message-send-mail-with-sendmail ()
2945   "Send off the prepared buffer with sendmail."
2946   (let ((errbuf (if message-interactive
2947                     (message-generate-new-buffer-clone-locals
2948                      " sendmail errors")
2949                   0))
2950         resend-to-addresses delimline)
2951     (let ((case-fold-search t))
2952       (save-restriction
2953         (message-narrow-to-headers)
2954         (setq resend-to-addresses (message-fetch-field "resent-to")))
2955       ;; Change header-delimiter to be what sendmail expects.
2956       (goto-char (point-min))
2957       (re-search-forward
2958        (concat "^" (regexp-quote mail-header-separator) "\n"))
2959       (replace-match "\n")
2960       (backward-char 1)
2961       (setq delimline (point-marker))
2962       (run-hooks 'message-send-mail-hook)
2963       ;; Insert an extra newline if we need it to work around
2964       ;; Sun's bug that swallows newlines.
2965       (goto-char (1+ delimline))
2966       (when (eval message-mailer-swallows-blank-line)
2967         (newline))
2968       (when message-interactive
2969         (save-excursion
2970           (set-buffer errbuf)
2971           (erase-buffer))))
2972     (let ((default-directory "/"))
2973       (as-binary-process
2974        (apply 'call-process-region
2975               (append (list (point-min) (point-max)
2976                             (if (boundp 'sendmail-program)
2977                                 sendmail-program
2978                               "/usr/lib/sendmail")
2979                             nil errbuf nil "-oi")
2980                       ;; Always specify who from,
2981                       ;; since some systems have broken sendmails.
2982                       ;; But some systems are more broken with -f, so
2983                       ;; we'll let users override this.
2984                       (if (null message-sendmail-f-is-evil)
2985                           (list "-f" (message-make-address)))
2986                       ;; These mean "report errors by mail"
2987                       ;; and "deliver in background".
2988                       (if (null message-interactive) '("-oem" "-odb"))
2989                       ;; Get the addresses from the message
2990                       ;; unless this is a resend.
2991                       ;; We must not do that for a resend
2992                       ;; because we would find the original addresses.
2993                       ;; For a resend, include the specific addresses.
2994                       (if resend-to-addresses
2995                           (list resend-to-addresses)
2996                         '("-t"))))))
2997     (when message-interactive
2998       (save-excursion
2999         (set-buffer errbuf)
3000         (goto-char (point-min))
3001         (while (re-search-forward "\n\n* *" nil t)
3002           (replace-match "; "))
3003         (if (not (zerop (buffer-size)))
3004             (error "Sending...failed to %s"
3005                    (buffer-substring (point-min) (point-max)))))
3006       (when (bufferp errbuf)
3007         (kill-buffer errbuf)))))
3008
3009 (defun message-send-mail-with-qmail ()
3010   "Pass the prepared message buffer to qmail-inject.
3011 Refer to the documentation for the variable `message-send-mail-function'
3012 to find out how to use this."
3013   ;; replace the header delimiter with a blank line
3014   (goto-char (point-min))
3015   (re-search-forward
3016    (concat "^" (regexp-quote mail-header-separator) "\n"))
3017   (replace-match "\n")
3018   (backward-char 1)
3019   (run-hooks 'message-send-mail-hook)
3020   ;; send the message
3021   (case
3022       (as-binary-process
3023        (apply
3024         'call-process-region 1 (point-max) message-qmail-inject-program
3025         nil nil nil
3026         ;; qmail-inject's default behaviour is to look for addresses on the
3027         ;; command line; if there're none, it scans the headers.
3028         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3029         ;;
3030         ;; in general, ALL of qmail-inject's defaults are perfect for simply
3031         ;; reading a formatted (i. e., at least a To: or Resent-To header)
3032         ;; message from stdin.
3033         ;;
3034         ;; qmail also has the advantage of not having been raped by
3035         ;; various vendors, so we don't have to allow for that, either --
3036         ;; compare this with message-send-mail-with-sendmail and weep
3037         ;; for sendmail's lost innocence.
3038         ;;
3039         ;; all this is way cool coz it lets us keep the arguments entirely
3040         ;; free for -inject-arguments -- a big win for the user and for us
3041         ;; since we don't have to play that double-guessing game and the user
3042         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3043         message-qmail-inject-args))
3044     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3045     ;; we have to look at the retval instead
3046     (0 nil)
3047     (1   (error "qmail-inject reported permanent failure"))
3048     (111 (error "qmail-inject reported transient failure"))
3049     ;; should never happen
3050     (t   (error "qmail-inject reported unknown failure"))))
3051
3052 (defun message-send-mail-with-mh ()
3053   "Send the prepared message buffer with mh."
3054   (let ((mh-previous-window-config nil)
3055         (name (mh-new-draft-name)))
3056     (setq buffer-file-name name)
3057     ;; MH wants to generate these headers itself.
3058     (when message-mh-deletable-headers
3059       (let ((headers message-mh-deletable-headers))
3060         (while headers
3061           (goto-char (point-min))
3062           (and (re-search-forward
3063                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3064                (message-delete-line))
3065           (pop headers))))
3066     (run-hooks 'message-send-mail-hook)
3067     ;; Pass it on to mh.
3068     (mh-send-letter)))
3069
3070 (defun message-send-mail-with-smtp ()
3071   "Send off the prepared buffer with SMTP."
3072   (require 'smtp) ; XXX
3073   (let ((case-fold-search t)
3074         recipients)
3075     (save-restriction
3076       (message-narrow-to-headers)
3077       (setq recipients
3078             ;; XXX: Should be replaced by better one.
3079             (smtp-deduce-address-list (current-buffer)
3080                                       (point-min) (point-max)))
3081       ;; Remove BCC lines.
3082       (message-remove-header "bcc"))
3083     ;; replace the header delimiter with a blank line.
3084     (goto-char (point-min))
3085     (re-search-forward
3086      (concat "^" (regexp-quote mail-header-separator) "\n"))
3087     (replace-match "\n")
3088     (backward-char 1)
3089     (run-hooks 'message-send-mail-hook)
3090     (if recipients
3091         (let ((result (smtp-via-smtp user-mail-address
3092                                      recipients
3093                                      (current-buffer))))
3094           (unless (eq result t)
3095             (error "Sending failed; " result)))
3096       (error "Sending failed; no recipients"))))
3097
3098 (defsubst message-maybe-split-and-send-news (method)
3099   "Split a message if necessary, and send it via news.
3100 Returns nil if sending succeeded, returns t if sending failed.
3101 This sub function is for exclusive use of `message-send-news'."
3102   (let ((mime-edit-split-ignored-field-regexp
3103          mime-edit-split-ignored-field-regexp)
3104         (case-fold-search t))
3105     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3106       (setq mime-edit-split-ignored-field-regexp
3107             (concat (substring mime-edit-split-ignored-field-regexp
3108                                0 (match-beginning 0))
3109                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3110                     "_so_don't_rape_it!"
3111                     (substring mime-edit-split-ignored-field-regexp
3112                                (match-end 0)))))
3113     (or
3114      (catch 'message-sending-news-failure
3115        (mime-edit-maybe-split-and-send
3116         (function
3117          (lambda ()
3118            (interactive)
3119            (save-restriction
3120              (std11-narrow-to-header mail-header-separator)
3121              (goto-char (point-min))
3122              (when (re-search-forward "^Message-ID:" nil t)
3123                (delete-region (match-end 0) (std11-field-end))
3124                (insert " " (message-make-message-id))))
3125            (unless (funcall message-send-news-function method)
3126              (throw 'message-sending-news-failure t)))))
3127        nil)
3128      (not (funcall message-send-news-function method)))))
3129
3130 (defun message-send-news (&optional arg)
3131   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3132          (case-fold-search nil)
3133          (method (if (message-functionp message-post-method)
3134                      (funcall message-post-method arg)
3135                    message-post-method))
3136          (group-name-charset (gnus-group-name-charset method ""))
3137          (message-syntax-checks
3138           (if arg
3139               (cons '(existing-newsgroups . disabled)
3140                     message-syntax-checks)
3141             message-syntax-checks))
3142          (message-this-is-news t)
3143          result)
3144     (save-restriction
3145       (message-narrow-to-headers)
3146       ;; Insert some headers.
3147       (message-generate-headers message-required-news-headers)
3148       ;; Let the user do all of the above.
3149       (run-hooks 'message-header-hook))
3150     (if group-name-charset
3151         (setq message-syntax-checks
3152               (cons '(valid-newsgroups . disabled)
3153                     message-syntax-checks)))
3154     (message-cleanup-headers)
3155     (if (not (message-check-news-syntax))
3156         nil
3157       (unwind-protect
3158           (save-excursion
3159             (set-buffer tembuf)
3160             (buffer-disable-undo)
3161             (erase-buffer)
3162             (insert-buffer message-encoding-buffer)
3163             ;; Remove some headers.
3164             (save-restriction
3165               (message-narrow-to-headers)
3166 ;; We Semi-gnus people have no use for it.
3167 ;;            ;; We (re)generate the Lines header.
3168 ;;            (when (memq 'Lines message-required-mail-headers)
3169 ;;              (message-generate-headers '(Lines)))
3170               ;; Remove some headers.
3171               (message-remove-header message-ignored-news-headers t))
3172             (goto-char (point-max))
3173             ;; require one newline at the end.
3174             (or (= (preceding-char) ?\n)
3175                 (insert ?\n))
3176             (setq result (message-maybe-split-and-send-news method)))
3177         (kill-buffer tembuf))
3178       (set-buffer message-edit-buffer)
3179       (if result
3180           (progn
3181             (message "Couldn't send message via news: %s"
3182                      (nnheader-get-report (car method)))
3183             nil)
3184         (push 'news message-sent-message-via)))))
3185
3186 ;; 1997-09-29 by MORIOKA Tomohiko
3187 (defun message-send-news-with-gnus (method)
3188   (let ((case-fold-search t))
3189     ;; Remove the delimiter.
3190     (goto-char (point-min))
3191     (re-search-forward
3192      (concat "^" (regexp-quote mail-header-separator) "\n"))
3193     (replace-match "\n")
3194     (backward-char 1)
3195     (run-hooks 'message-send-news-hook)
3196     (gnus-open-server method)
3197     (gnus-request-post method)
3198     ))
3199
3200 ;;;
3201 ;;; Header generation & syntax checking.
3202 ;;;
3203
3204 (defun message-check-element (type)
3205   "Returns non-nil if this type is not to be checked."
3206   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3207       t
3208     (let ((able (assq type message-syntax-checks)))
3209       (and (consp able)
3210            (eq (cdr able) 'disabled)))))
3211
3212 (defun message-check-news-syntax ()
3213   "Check the syntax of the message."
3214   (save-excursion
3215     (save-restriction
3216       (widen)
3217       (and
3218        ;; We narrow to the headers and check them first.
3219        (save-excursion
3220          (save-restriction
3221            (message-narrow-to-headers)
3222            (message-check-news-header-syntax)))
3223        ;; Check the body.
3224        (save-excursion
3225          (set-buffer message-edit-buffer)
3226          (message-check-news-body-syntax))))))
3227
3228 (defun message-check-news-header-syntax ()
3229   (and
3230    ;; Check Newsgroups header.
3231    (message-check 'newsgroups
3232      (let ((group (message-fetch-field "newsgroups")))
3233        (or
3234         (and group
3235              (not (string-match "\\`[ \t]*\\'" group)))
3236         (ignore
3237          (message
3238           "The newsgroups field is empty or missing.  Posting is denied.")))))
3239    ;; Check the Subject header.
3240    (message-check 'subject
3241      (let* ((case-fold-search t)
3242             (subject (message-fetch-field "subject")))
3243        (or
3244         (and subject
3245              (not (string-match "\\`[ \t]*\\'" subject)))
3246         (ignore
3247          (message
3248           "The subject field is empty or missing.  Posting is denied.")))))
3249    ;; Check for commands in Subject.
3250    (message-check 'subject-cmsg
3251      (if (string-match "^cmsg " (message-fetch-field "subject"))
3252          (y-or-n-p
3253           "The control code \"cmsg\" is in the subject.  Really post? ")
3254        t))
3255    ;; Check for multiple identical headers.
3256    (message-check 'multiple-headers
3257      (let (found)
3258        (while (and (not found)
3259                    (re-search-forward "^[^ \t:]+: " nil t))
3260          (save-excursion
3261            (or (re-search-forward
3262                 (concat "^"
3263                         (regexp-quote
3264                          (setq found
3265                                (buffer-substring
3266                                 (match-beginning 0) (- (match-end 0) 2))))
3267                         ":")
3268                 nil t)
3269                (setq found nil))))
3270        (if found
3271            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3272          t)))
3273    ;; Check for Version and Sendsys.
3274    (message-check 'sendsys
3275      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3276          (y-or-n-p
3277           (format "The article contains a %s command.  Really post? "
3278                   (buffer-substring (match-beginning 0)
3279                                     (1- (match-end 0)))))
3280        t))
3281    ;; See whether we can shorten Followup-To.
3282    (message-check 'shorten-followup-to
3283      (let ((newsgroups (message-fetch-field "newsgroups"))
3284            (followup-to (message-fetch-field "followup-to"))
3285            to)
3286        (when (and newsgroups
3287                   (string-match "," newsgroups)
3288                   (not followup-to)
3289                   (not
3290                    (zerop
3291                     (length
3292                      (setq to (completing-read
3293                                "Followups to: (default all groups) "
3294                                (mapcar (lambda (g) (list g))
3295                                        (cons "poster"
3296                                              (message-tokenize-header
3297                                               newsgroups)))))))))
3298          (goto-char (point-min))
3299          (insert "Followup-To: " to "\n"))
3300        t))
3301    ;; Check "Shoot me".
3302    (message-check 'shoot
3303      (if (re-search-forward
3304           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3305          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3306        t))
3307    ;; Check for Approved.
3308    (message-check 'approved
3309      (if (re-search-forward "^Approved:" nil t)
3310          (y-or-n-p "The article contains an Approved header.  Really post? ")
3311        t))
3312    ;; Check the Message-ID header.
3313    (message-check 'message-id
3314      (let* ((case-fold-search t)
3315             (message-id (message-fetch-field "message-id" t)))
3316        (or (not message-id)
3317            ;; Is there an @ in the ID?
3318            (and (string-match "@" message-id)
3319                 ;; Is there a dot in the ID?
3320                 (string-match "@[^.]*\\." message-id)
3321                 ;; Does the ID end with a dot?
3322                 (not (string-match "\\.>" message-id)))
3323            (y-or-n-p
3324             (format "The Message-ID looks strange: \"%s\".  Really post? "
3325                     message-id)))))
3326    ;; Check the Newsgroups & Followup-To headers.
3327    (message-check 'existing-newsgroups
3328      (let* ((case-fold-search t)
3329             (newsgroups (message-fetch-field "newsgroups"))
3330             (followup-to (message-fetch-field "followup-to"))
3331             (groups (message-tokenize-header
3332                      (if followup-to
3333                          (concat newsgroups "," followup-to)
3334                        newsgroups)))
3335             (hashtb (and (boundp 'gnus-active-hashtb)
3336                          gnus-active-hashtb))
3337             errors)
3338        (if (or (not hashtb)
3339                (not (boundp 'gnus-read-active-file))
3340                (not gnus-read-active-file)
3341                (eq gnus-read-active-file 'some))
3342            t
3343          (while groups
3344            (when (and (not (boundp (intern (car groups) hashtb)))
3345                       (not (equal (car groups) "poster")))
3346              (push (car groups) errors))
3347            (pop groups))
3348          (if (not errors)
3349              t
3350            (y-or-n-p
3351             (format
3352              "Really post to %s unknown group%s: %s "
3353              (if (= (length errors) 1) "this" "these")
3354              (if (= (length errors) 1) "" "s")
3355              (mapconcat 'identity errors ", ")))))))
3356    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3357    (message-check 'valid-newsgroups
3358      (let ((case-fold-search t)
3359            (headers '("Newsgroups" "Followup-To"))
3360            header error)
3361        (while (and headers (not error))
3362          (when (setq header (mail-fetch-field (car headers)))
3363            (if (or
3364                 (not
3365                  (string-match
3366                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3367                   header))
3368                 (memq
3369                  nil (mapcar
3370                       (lambda (g)
3371                         (not (string-match "\\.\\'\\|\\.\\." g)))
3372                       (message-tokenize-header header ","))))
3373                (setq error t)))
3374          (unless error
3375            (pop headers)))
3376        (if (not error)
3377            t
3378          (y-or-n-p
3379           (format "The %s header looks odd: \"%s\".  Really post? "
3380                   (car headers) header)))))
3381    (message-check 'repeated-newsgroups
3382      (let ((case-fold-search t)
3383            (headers '("Newsgroups" "Followup-To"))
3384            header error groups group)
3385        (while (and headers
3386                    (not error))
3387          (when (setq header (mail-fetch-field (pop headers)))
3388            (setq groups (message-tokenize-header header ","))
3389            (while (setq group (pop groups))
3390              (when (member group groups)
3391                (setq error group
3392                      groups nil)))))
3393        (if (not error)
3394            t
3395          (y-or-n-p
3396           (format "Group %s is repeated in headers.  Really post? " error)))))
3397    ;; Check the From header.
3398    (message-check 'from
3399      (let* ((case-fold-search t)
3400             (from (message-fetch-field "from"))
3401             ad)
3402        (cond
3403         ((not from)
3404          (message "There is no From line.  Posting is denied.")
3405          nil)
3406         ((or (not (string-match
3407                    "@[^\\.]*\\."
3408                    (setq ad (nth 1 (mail-extract-address-components
3409                                     from))))) ;larsi@ifi
3410              (string-match "\\.\\." ad) ;larsi@ifi..uio
3411              (string-match "@\\." ad)   ;larsi@.ifi.uio
3412              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3413              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3414              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3415          (message
3416           "Denied posting -- the From looks strange: \"%s\"." from)
3417          nil)
3418         (t t))))))
3419
3420 (defun message-check-news-body-syntax ()
3421   (and
3422    ;; Check for long lines.
3423    (message-check 'long-lines
3424      (goto-char (point-min))
3425      (re-search-forward
3426       (concat "^" (regexp-quote mail-header-separator) "$"))
3427      (while (and
3428              (progn
3429                (end-of-line)
3430                (< (current-column) 80))
3431              (zerop (forward-line 1))))
3432      (or (bolp)
3433          (eobp)
3434          (y-or-n-p
3435           "You have lines longer than 79 characters.  Really post? ")))
3436    ;; Check whether the article is empty.
3437    (message-check 'empty
3438      (goto-char (point-min))
3439      (re-search-forward
3440       (concat "^" (regexp-quote mail-header-separator) "$"))
3441      (forward-line 1)
3442      (let ((b (point)))
3443        (goto-char (point-max))
3444        (re-search-backward message-signature-separator nil t)
3445        (beginning-of-line)
3446        (or (re-search-backward "[^ \n\t]" b t)
3447            (y-or-n-p "Empty article.  Really post? "))))
3448    ;; Check for control characters.
3449    (message-check 'control-chars
3450      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3451          (y-or-n-p
3452           "The article contains control characters.  Really post? ")
3453        t))
3454    ;; Check 8bit characters.
3455    (message-check '8bit
3456      (message-check-8bit))
3457    ;; Check excessive size.
3458    (message-check 'size
3459      (if (> (buffer-size) 60000)
3460          (y-or-n-p
3461           (format "The article is %d octets long.  Really post? "
3462                   (buffer-size)))
3463        t))
3464    ;; Check whether any new text has been added.
3465    (message-check 'new-text
3466      (or
3467       (not message-checksum)
3468       (not (eq (message-checksum) message-checksum))
3469       (y-or-n-p
3470        "It looks like no new text has been added.  Really post? ")))
3471    ;; Check the length of the signature.
3472    (message-check 'signature
3473      (goto-char (point-max))
3474      (if (> (count-lines (point) (point-max)) 5)
3475          (y-or-n-p
3476           (format
3477            "Your .sig is %d lines; it should be max 4.  Really post? "
3478            (1- (count-lines (point) (point-max)))))
3479        t))
3480    ;; Ensure that text follows last quoted portion.
3481    (message-check 'quoting-style
3482      (goto-char (point-max))
3483      (let ((no-problem t))
3484        (when (search-backward-regexp "^>[^\n]*\n>" nil t)
3485          (setq no-problem nil)
3486          (while (not (eobp))
3487            (when (and (not (eolp)) (looking-at "[^> \t]"))
3488              (setq no-problem t))
3489            (forward-line)))
3490        (if no-problem
3491            t
3492          (y-or-n-p "Your text should follow quoted text.  Really post? "))))))
3493
3494 (defun message-check-mail-syntax ()
3495   "Check the syntax of the message."
3496   (save-excursion
3497     (save-restriction
3498       (widen)
3499       (and
3500        ;; We narrow to the headers and check them first.
3501        (save-excursion
3502          (save-restriction
3503            (message-narrow-to-headers)
3504            (message-check-mail-header-syntax)))
3505        ;; Check the body.
3506        (save-excursion
3507          (set-buffer message-edit-buffer)
3508          (message-check-mail-body-syntax))))))
3509
3510 (defun message-check-mail-header-syntax ()
3511   t)
3512
3513 (defun message-check-mail-body-syntax ()
3514   (and
3515    ;; Check 8bit characters.
3516    (message-check '8bit
3517      (message-check-8bit)
3518      )))
3519
3520 (defun message-check-8bit ()
3521   "Check the article contains 8bit characters."
3522   (save-excursion
3523     (set-buffer message-encoding-buffer)
3524     (message-narrow-to-headers)
3525     (let* ((case-fold-search t)
3526            (field-value (message-fetch-field "content-transfer-encoding")))
3527       (if (and field-value
3528                (member (downcase field-value) message-8bit-encoding-list))
3529           t
3530         (widen)
3531         (set-buffer (get-buffer-create " message syntax"))
3532         (erase-buffer)
3533         (goto-char (point-min))
3534         (set-buffer-multibyte nil)
3535         (insert-buffer message-encoding-buffer)
3536         (goto-char (point-min))
3537         (if (re-search-forward "[^\x00-\x7f]" nil t)
3538             (y-or-n-p
3539              "The article contains 8bit characters.  Really post? ")
3540           t)))))
3541
3542 (defun message-checksum ()
3543   "Return a \"checksum\" for the current buffer."
3544   (let ((sum 0))
3545     (save-excursion
3546       (goto-char (point-min))
3547       (re-search-forward
3548        (concat "^" (regexp-quote mail-header-separator) "$"))
3549       (while (not (eobp))
3550         (when (not (looking-at "[ \t\n]"))
3551           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3552                             (char-after))))
3553         (forward-char 1)))
3554     sum))
3555
3556 (defun message-do-fcc ()
3557   "Process Fcc headers in the current buffer."
3558   (let ((case-fold-search t)
3559         (coding-system-for-write 'raw-text)
3560         (output-coding-system 'raw-text)
3561         list file)
3562     (save-excursion
3563       (set-buffer (get-buffer-create " *message temp*"))
3564       (erase-buffer)
3565       (insert-buffer-substring message-encoding-buffer)
3566       (save-restriction
3567         (message-narrow-to-headers)
3568         (while (setq file (message-fetch-field "fcc"))
3569           (push file list)
3570           (message-remove-header "fcc" nil t)))
3571       (goto-char (point-min))
3572       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
3573       (replace-match "" t t)
3574       ;; Process FCC operations.
3575       (while list
3576         (setq file (pop list))
3577         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3578             ;; Pipe the article to the program in question.
3579             (call-process-region (point-min) (point-max) shell-file-name
3580                                  nil nil nil shell-command-switch
3581                                  (match-string 1 file))
3582           ;; Save the article.
3583           (setq file (expand-file-name file))
3584           (unless (file-exists-p (file-name-directory file))
3585             (make-directory (file-name-directory file) t))
3586           (if (and message-fcc-handler-function
3587                    (not (eq message-fcc-handler-function 'rmail-output)))
3588               (funcall message-fcc-handler-function file)
3589             (if (and (file-readable-p file) (mail-file-babyl-p file))
3590                 (rmail-output file 1 nil t)
3591               (let ((mail-use-rfc822 t))
3592                 (rmail-output file 1 t t))))))
3593       (kill-buffer (current-buffer)))))
3594
3595 (defun message-output (filename)
3596   "Append this article to Unix/babyl mail file.."
3597   (if (and (file-readable-p filename)
3598            (mail-file-babyl-p filename))
3599       (gnus-output-to-rmail filename t)
3600     (gnus-output-to-mail filename t)))
3601
3602 (defun message-cleanup-headers ()
3603   "Do various automatic cleanups of the headers."
3604   ;; Remove empty lines in the header.
3605   (save-restriction
3606     (message-narrow-to-headers)
3607     ;; Remove blank lines.
3608     (while (re-search-forward "^[ \t]*\n" nil t)
3609       (replace-match "" t t))
3610
3611     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3612     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3613     ;; embedded line breaks.
3614     (goto-char (point-min))
3615     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3616       (save-restriction
3617         (narrow-to-region
3618          (point)
3619          (if (re-search-forward "^[^ \t]" nil t)
3620              (match-beginning 0)
3621            (forward-line 1)
3622            (point)))
3623         (goto-char (point-min))
3624         (while (re-search-forward "\n[ \t]+" nil t)
3625           (replace-match " " t t))      ;No line breaks (too confusing)
3626         (goto-char (point-min))
3627         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3628           (replace-match "," t t))
3629         (goto-char (point-min))
3630         ;; Remove trailing commas.
3631         (when (re-search-forward ",+$" nil t)
3632           (replace-match "" t t))))))
3633
3634 (defun message-make-date (&optional now)
3635   "Make a valid data header.
3636 If NOW, use that time instead."
3637   (let* ((now (or now (current-time)))
3638          (zone (nth 8 (decode-time now)))
3639          (sign "+"))
3640     (when (< zone 0)
3641       (setq sign "-")
3642       (setq zone (- zone)))
3643     (concat
3644      (format-time-string "%d" now)
3645      ;; The month name of the %b spec is locale-specific.  Pfff.
3646      (format " %s "
3647              (capitalize (car (rassoc (nth 4 (decode-time now))
3648                                       parse-time-months))))
3649      (format-time-string "%Y %H:%M:%S " now)
3650      ;; We do all of this because XEmacs doesn't have the %z spec.
3651      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3652
3653 (defun message-make-followup-subject (subject)
3654   "Make a followup Subject."
3655   (cond
3656    ((and (eq message-use-subject-re 'guess)
3657          (string-match message-subject-encoded-re-regexp subject))
3658     subject)
3659    (message-use-subject-re
3660     (concat "Re: " (message-strip-subject-re subject)))
3661    (t subject)))
3662
3663 (defun message-make-message-id ()
3664   "Make a unique Message-ID."
3665   (concat "<" (message-unique-id)
3666           (let ((psubject (save-excursion (message-fetch-field "subject")))
3667                 (psupersedes
3668                  (save-excursion (message-fetch-field "supersedes"))))
3669             (if (or
3670                  (and message-reply-headers
3671                       (mail-header-references message-reply-headers)
3672                       (mail-header-subject message-reply-headers)
3673                       psubject
3674                       (mail-header-subject message-reply-headers)
3675                       (not (string=
3676                             (message-strip-subject-re
3677                              (mail-header-subject message-reply-headers))
3678                             (message-strip-subject-re psubject))))
3679                  (and psupersedes
3680                       (string-match "_-_@" psupersedes)))
3681                 "_-_" ""))
3682           "@" (message-make-fqdn) ">"))
3683
3684 (defvar message-unique-id-char nil)
3685
3686 ;; If you ever change this function, make sure the new version
3687 ;; cannot generate IDs that the old version could.
3688 ;; You might for example insert a "." somewhere (not next to another dot
3689 ;; or string boundary), or modify the "fsf" string.
3690 (defun message-unique-id ()
3691   ;; Don't use microseconds from (current-time), they may be unsupported.
3692   ;; Instead we use this randomly inited counter.
3693   (setq message-unique-id-char
3694         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3695            ;; (current-time) returns 16-bit ints,
3696            ;; and 2^16*25 just fits into 4 digits i base 36.
3697            (* 25 25)))
3698   (let ((tm (current-time)))
3699     (concat
3700      (if (memq system-type '(ms-dos emx vax-vms))
3701          (let ((user (downcase (user-login-name))))
3702            (while (string-match "[^a-z0-9_]" user)
3703              (aset user (match-beginning 0) ?_))
3704            user)
3705        (message-number-base36 (user-uid) -1))
3706      (message-number-base36 (+ (car   tm)
3707                                (lsh (% message-unique-id-char 25) 16)) 4)
3708      (message-number-base36 (+ (nth 1 tm)
3709                                (lsh (/ message-unique-id-char 25) 16)) 4)
3710      ;; Append the newsreader name, because while the generated
3711      ;; ID is unique to this newsreader, other newsreaders might
3712      ;; otherwise generate the same ID via another algorithm.
3713      ".fsf")))
3714
3715 (defun message-number-base36 (num len)
3716   (if (if (< len 0)
3717           (<= num 0)
3718         (= len 0))
3719       ""
3720     (concat (message-number-base36 (/ num 36) (1- len))
3721             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3722                                   (% num 36))))))
3723
3724 (defun message-make-organization ()
3725   "Make an Organization header."
3726   (let* ((organization
3727           (when message-user-organization
3728             (if (message-functionp message-user-organization)
3729                 (funcall message-user-organization)
3730               message-user-organization))))
3731     (save-excursion
3732       (message-set-work-buffer)
3733       (cond ((stringp organization)
3734              (insert organization))
3735             ((and (eq t organization)
3736                   message-user-organization-file
3737                   (file-exists-p message-user-organization-file))
3738              (insert-file-contents message-user-organization-file)))
3739       (goto-char (point-min))
3740       (while (re-search-forward "[\t\n]+" nil t)
3741         (replace-match "" t t))
3742       (unless (zerop (buffer-size))
3743         (buffer-string)))))
3744
3745 (defun message-make-lines ()
3746   "Count the number of lines and return numeric string."
3747   (save-excursion
3748     (save-restriction
3749       (widen)
3750       (goto-char (point-min))
3751       (re-search-forward
3752        (concat "^" (regexp-quote mail-header-separator) "$"))
3753       (forward-line 1)
3754       (int-to-string (count-lines (point) (point-max))))))
3755
3756 (defun message-make-in-reply-to ()
3757   "Return the In-Reply-To header for this message."
3758   (when message-reply-headers
3759     (let ((mid (mail-header-message-id message-reply-headers))
3760           (from (mail-header-from message-reply-headers))
3761           (date (mail-header-date message-reply-headers)))
3762       (when mid
3763         (concat mid
3764                 (when from
3765                   (let ((pair (std11-extract-address-components from)))
3766                     (concat "\n ("
3767                             (or (car pair) (cadr pair))
3768                             "'s message of \""
3769                             (if (or (not date) (string= date ""))
3770                                 "(unknown date)" date)
3771                             "\")"))))))))
3772
3773 (defun message-make-distribution ()
3774   "Make a Distribution header."
3775   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3776     (cond ((message-functionp message-distribution-function)
3777            (funcall message-distribution-function))
3778           (t orig-distribution))))
3779
3780 (defun message-make-expires ()
3781   "Return an Expires header based on `message-expires'."
3782   (let ((current (current-time))
3783         (future (* 1.0 message-expires 60 60 24)))
3784     ;; Add the future to current.
3785     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3786     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3787     (message-make-date current)))
3788
3789 (defun message-make-path ()
3790   "Return uucp path."
3791   (let ((login-name (user-login-name)))
3792     (cond ((null message-user-path)
3793            (concat (system-name) "!" login-name))
3794           ((stringp message-user-path)
3795            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3796            (concat message-user-path "!" login-name))
3797           (t login-name))))
3798
3799 (defun message-make-from ()
3800   "Make a From header."
3801   (let* ((style message-from-style)
3802          (login (message-make-address))
3803          (fullname
3804           (or (and (boundp 'user-full-name)
3805                    user-full-name)
3806               (user-full-name))))
3807     (when (string= fullname "&")
3808       (setq fullname (user-login-name)))
3809     (save-excursion
3810       (message-set-work-buffer)
3811       (cond
3812        ((or (null style)
3813             (equal fullname ""))
3814         (insert login))
3815        ((or (eq style 'angles)
3816             (and (not (eq style 'parens))
3817                  ;; Use angles if no quoting is needed, or if parens would
3818                  ;; need quoting too.
3819                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3820                      (let ((tmp (concat fullname nil)))
3821                        (while (string-match "([^()]*)" tmp)
3822                          (aset tmp (match-beginning 0) ?-)
3823                          (aset tmp (1- (match-end 0)) ?-))
3824                        (string-match "[\\()]" tmp)))))
3825         (insert fullname)
3826         (goto-char (point-min))
3827         ;; Look for a character that cannot appear unquoted
3828         ;; according to RFC 822.
3829         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3830           ;; Quote fullname, escaping specials.
3831           (goto-char (point-min))
3832           (insert "\"")
3833           (while (re-search-forward "[\"\\]" nil 1)
3834             (replace-match "\\\\\\&" t))
3835           (insert "\""))
3836         (insert " <" login ">"))
3837        (t                               ; 'parens or default
3838         (insert login " (")
3839         (let ((fullname-start (point)))
3840           (insert fullname)
3841           (goto-char fullname-start)
3842           ;; RFC 822 says \ and nonmatching parentheses
3843           ;; must be escaped in comments.
3844           ;; Escape every instance of ()\ ...
3845           (while (re-search-forward "[()\\]" nil 1)
3846             (replace-match "\\\\\\&" t))
3847           ;; ... then undo escaping of matching parentheses,
3848           ;; including matching nested parentheses.
3849           (goto-char fullname-start)
3850           (while (re-search-forward
3851                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3852                   nil 1)
3853             (replace-match "\\1(\\3)" t)
3854             (goto-char fullname-start)))
3855         (insert ")")))
3856       (buffer-string))))
3857
3858 (defun message-make-sender ()
3859   "Return the \"real\" user address.
3860 This function tries to ignore all user modifications, and
3861 give as trustworthy answer as possible."
3862   (concat (user-login-name) "@" (system-name)))
3863
3864 (defun message-make-address ()
3865   "Make the address of the user."
3866   (or (message-user-mail-address)
3867       (concat (user-login-name) "@" (message-make-domain))))
3868
3869 (defun message-user-mail-address ()
3870   "Return the pertinent part of `user-mail-address'."
3871   (when user-mail-address
3872     (if (string-match " " user-mail-address)
3873         (nth 1 (std11-extract-address-components user-mail-address))
3874       user-mail-address)))
3875
3876 (defun message-make-fqdn ()
3877   "Return user's fully qualified domain name."
3878   (let ((system-name (system-name))
3879         (user-mail (message-user-mail-address)))
3880     (cond
3881      ((string-match "[^.]\\.[^.]" system-name)
3882       ;; `system-name' returned the right result.
3883       system-name)
3884      ;; Try `mail-host-address'.
3885      ((and (boundp 'mail-host-address)
3886            (stringp mail-host-address)
3887            (string-match "\\." mail-host-address))
3888       mail-host-address)
3889      ;; We try `user-mail-address' as a backup.
3890      ((and user-mail
3891            (string-match "\\." user-mail)
3892            (string-match "@\\(.*\\)\\'" user-mail))
3893       (match-string 1 user-mail))
3894      ;; Default to this bogus thing.
3895      (t
3896       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3897
3898 (defun message-make-host-name ()
3899   "Return the name of the host."
3900   (let ((fqdn (message-make-fqdn)))
3901     (string-match "^[^.]+\\." fqdn)
3902     (substring fqdn 0 (1- (match-end 0)))))
3903
3904 (defun message-make-domain ()
3905   "Return the domain name."
3906   (or mail-host-address
3907       (message-make-fqdn)))
3908
3909 ;; Dummy to avoid byte-compile warning.
3910 (defvar mule-version)
3911 (defvar emacs-beta-version)
3912 (defvar xemacs-codename)
3913 (defvar gnus-inviolable-extended-version)
3914
3915 (defun message-make-user-agent ()
3916   "Return user-agent info if the value `message-user-agent' is non-nil. If the
3917 \"User-Agent\" field has already exist, it's value will be added in the return
3918 string."
3919   (when message-user-agent
3920     (save-excursion
3921       (goto-char (point-min))
3922       (let ((case-fold-search t)
3923             user-agent start p end)
3924         (if (re-search-forward "^User-Agent:[\t ]*" nil t)
3925             (progn
3926               (setq start (match-beginning 0)
3927                     p (match-end 0)
3928                     end (std11-field-end)
3929                     user-agent (buffer-substring-no-properties p end))
3930               (delete-region start (1+ end))
3931               (concat message-user-agent " " user-agent))
3932           message-user-agent)))))
3933
3934 (defun message-generate-headers (headers)
3935   "Prepare article HEADERS.
3936 Headers already prepared in the buffer are not modified."
3937   (save-restriction
3938     (message-narrow-to-headers)
3939     (let* ((Date (message-make-date))
3940            (Message-ID (message-make-message-id))
3941            (Organization (message-make-organization))
3942            (From (message-make-from))
3943            (Path (message-make-path))
3944            (Subject nil)
3945            (Newsgroups nil)
3946            (In-Reply-To (message-make-in-reply-to))
3947            (To nil)
3948            (Distribution (message-make-distribution))
3949            (Lines (message-make-lines))
3950            (User-Agent (message-make-user-agent))
3951            (Expires (message-make-expires))
3952            (case-fold-search t)
3953            header value elem)
3954       ;; First we remove any old generated headers.
3955       (let ((headers message-deletable-headers))
3956         (unless (buffer-modified-p)
3957           (setq headers (delq 'Message-ID (copy-sequence headers))))
3958         (while headers
3959           (goto-char (point-min))
3960           (and (re-search-forward
3961                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3962                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3963                (message-delete-line))
3964           (pop headers)))
3965       ;; Go through all the required headers and see if they are in the
3966       ;; articles already.  If they are not, or are empty, they are
3967       ;; inserted automatically - except for Subject, Newsgroups and
3968       ;; Distribution.
3969       (while headers
3970         (goto-char (point-min))
3971         (setq elem (pop headers))
3972         (if (consp elem)
3973             (if (eq (car elem) 'optional)
3974                 (setq header (cdr elem))
3975               (setq header (car elem)))
3976           (setq header elem))
3977         (when (or (not (re-search-forward
3978                         (concat "^"
3979                                 (regexp-quote
3980                                  (downcase
3981                                   (if (stringp header)
3982                                       header
3983                                     (symbol-name header))))
3984                                 ":")
3985                         nil t))
3986                   (progn
3987                     ;; The header was found.  We insert a space after the
3988                     ;; colon, if there is none.
3989                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3990                     ;; Find out whether the header is empty...
3991                     (looking-at "[ \t]*\n[^ \t]")))
3992           ;; So we find out what value we should insert.
3993           (setq value
3994                 (cond
3995                  ((and (consp elem) (eq (car elem) 'optional))
3996                   ;; This is an optional header.  If the cdr of this
3997                   ;; is something that is nil, then we do not insert
3998                   ;; this header.
3999                   (setq header (cdr elem))
4000                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
4001                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
4002                  ((consp elem)
4003                   ;; The element is a cons.  Either the cdr is a
4004                   ;; string to be inserted verbatim, or it is a
4005                   ;; function, and we insert the value returned from
4006                   ;; this function.
4007                   (or (and (stringp (cdr elem)) (cdr elem))
4008                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
4009                  ((and (boundp header) (symbol-value header))
4010                   ;; The element is a symbol.  We insert the value
4011                   ;; of this symbol, if any.
4012                   (symbol-value header))
4013                  ((not (message-check-element header))
4014                   ;; We couldn't generate a value for this header,
4015                   ;; so we just ask the user.
4016                   (read-from-minibuffer
4017                    (format "Empty header for %s; enter value: " header)))))
4018           ;; Finally insert the header.
4019           (when (and value
4020                      (not (equal value "")))
4021             (save-excursion
4022               (if (bolp)
4023                   (progn
4024                     ;; This header didn't exist, so we insert it.
4025                     (goto-char (point-max))
4026                     (insert (if (stringp header) header (symbol-name header))
4027                             ": " value)
4028                     (unless (bolp)
4029                       (insert "\n"))
4030                     (forward-line -1))
4031                 ;; The value of this header was empty, so we clear
4032                 ;; totally and insert the new value.
4033                 (delete-region (point) (gnus-point-at-eol))
4034                 (insert value)
4035                 (when (bolp)
4036                   (delete-char -1)))
4037               ;; Add the deletable property to the headers that require it.
4038               (and (memq header message-deletable-headers)
4039                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4040                    (add-text-properties
4041                     (point) (match-end 0)
4042                     '(message-deletable t face italic) (current-buffer)))))))
4043       ;; Insert new Sender if the From is strange.
4044       (let ((from (message-fetch-field "from"))
4045             (sender (message-fetch-field "sender"))
4046             (secure-sender (message-make-sender)))
4047         (when (and from
4048                    (not (message-check-element 'sender))
4049                    (not (string=
4050                          (downcase
4051                           (cadr (std11-extract-address-components from)))
4052                          (downcase secure-sender)))
4053                    (or (null sender)
4054                        (not
4055                         (string=
4056                          (downcase
4057                           (cadr (std11-extract-address-components sender)))
4058                          (downcase secure-sender)))))
4059           (goto-char (point-min))
4060           ;; Rename any old Sender headers to Original-Sender.
4061           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4062             (beginning-of-line)
4063             (insert "Original-")
4064             (beginning-of-line))
4065           (when (or (message-news-p)
4066                     (string-match "@.+\\.." secure-sender))
4067             (insert "Sender: " secure-sender "\n")))))))
4068
4069 (defun message-insert-courtesy-copy ()
4070   "Insert a courtesy message in mail copies of combined messages."
4071   (let (newsgroups)
4072     (save-excursion
4073       (save-restriction
4074         (message-narrow-to-headers)
4075         (when (setq newsgroups (message-fetch-field "newsgroups"))
4076           (goto-char (point-max))
4077           (insert "Posted-To: " newsgroups "\n")))
4078       (forward-line 1)
4079       (when message-courtesy-message
4080         (cond
4081          ((string-match "%s" message-courtesy-message)
4082           (insert (format message-courtesy-message newsgroups)))
4083          (t
4084           (insert message-courtesy-message)))))))
4085
4086 ;;;
4087 ;;; Setting up a message buffer
4088 ;;;
4089
4090 (defun message-fill-address (header value)
4091   (save-restriction
4092     (narrow-to-region (point) (point))
4093     (insert (capitalize (symbol-name header))
4094             ": "
4095             (if (consp value) (car value) value)
4096             "\n")
4097     (narrow-to-region (point-min) (1- (point-max)))
4098     (let (quoted last)
4099       (goto-char (point-min))
4100       (while (not (eobp))
4101         (skip-chars-forward "^,\"" (point-max))
4102         (if (or (eq (char-after) ?,)
4103                 (eobp))
4104             (when (not quoted)
4105               (if (and (> (current-column) 78)
4106                        last)
4107                   (save-excursion
4108                     (goto-char last)
4109                     (looking-at "[ \t]*")
4110                     (replace-match "\n " t t)))
4111               (setq last (1+ (point))))
4112           (setq quoted (not quoted)))
4113         (unless (eobp)
4114           (forward-char 1))))
4115     (goto-char (point-max))
4116     (widen)
4117     (forward-line 1)))
4118
4119 (defun message-fill-references (header value)
4120   (insert (capitalize (symbol-name header))
4121           ": "
4122           (std11-fill-msg-id-list-string
4123           (if (consp value) (car value) value))
4124           "\n"))
4125
4126 (defun message-fill-header (header value)
4127   (let ((begin (point))
4128         (fill-column 78)
4129         (fill-prefix " "))
4130     (insert (capitalize (symbol-name header))
4131             ": "
4132             (if (consp value) (car value) value)
4133             "\n")
4134     (save-restriction
4135       (narrow-to-region begin (point))
4136       (fill-region-as-paragraph begin (point))
4137       ;; Tapdance around looong Message-IDs.
4138       (forward-line -1)
4139       (when (looking-at "[ \t]*$")
4140         (message-delete-line))
4141       (goto-char begin)
4142       (re-search-forward ":" nil t)
4143       (when (looking-at "\n[ \t]+")
4144         (replace-match " " t t))
4145       (goto-char (point-max)))))
4146
4147 (defun message-shorten-1 (list cut surplus)
4148   ;; Cut SURPLUS elements out of LIST, beginning with CUTth one.
4149   (setcdr (nthcdr (- cut 2) list)
4150           (nthcdr (+ (- cut 2) surplus 1) list)))
4151
4152 (defun message-shorten-references (header references)
4153   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
4154 If folding is disallowed, also check that the REFERENCES are less
4155 than 988 characters long, and if they are not, trim them until they are."
4156   (let ((maxcount 31)
4157         (count 0)
4158         (cut 6)
4159         refs)
4160     (with-temp-buffer
4161       (insert references)
4162       (goto-char (point-min))
4163       ;; Cons a list of valid references.
4164       (while (re-search-forward "<[^>]+>" nil t)
4165         (push (match-string 0) refs))
4166       (setq refs (nreverse refs)
4167             count (length refs)))
4168
4169     ;; If the list has more than MAXCOUNT elements, trim it by
4170     ;; removing the CUTth element and the required number of
4171     ;; elements that follow.
4172     (when (> count maxcount)
4173       (let ((surplus (- count maxcount)))
4174         (message-shorten-1 refs cut surplus)
4175         (decf count surplus)))
4176
4177     ;; If folding is disallowed, make sure the total length (including
4178     ;; the spaces between) will be less than MAXSIZE characters.
4179     ;;
4180     ;; Only disallow folding for News messages. At this point the headers
4181     ;; have not been generated, thus we use message-this-is-news directly.
4182     (when (and message-this-is-news message-cater-to-broken-inn)
4183       (let ((maxsize 988)
4184             (totalsize (+ (apply #'+ (mapcar #'length refs))
4185                           (1- count)))
4186             (surplus 0)
4187             (ptr (nthcdr (1- cut) refs)))
4188         ;; Decide how many elements to cut off...
4189         (while (> totalsize maxsize)
4190           (decf totalsize (1+ (length (car ptr))))
4191           (incf surplus)
4192           (setq ptr (cdr ptr)))
4193         ;; ...and do it.
4194         (when (> surplus 0)
4195           (message-shorten-1 refs cut surplus))))
4196
4197     ;; Finally, collect the references back into a string and insert
4198     ;; it into the buffer.
4199     (let ((refstring (mapconcat #'identity refs " ")))
4200       (if (and message-this-is-news message-cater-to-broken-inn)
4201           (insert (capitalize (symbol-name header)) ": "
4202                   refstring "\n")
4203         (message-fill-header header refstring)))))
4204
4205 (defun message-position-point ()
4206   "Move point to where the user probably wants to find it."
4207   (message-narrow-to-headers)
4208   (cond
4209    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4210     (search-backward ":" )
4211     (widen)
4212     (forward-char 1)
4213     (if (eq (char-after) ? )
4214         (forward-char 1)
4215       (insert " ")))
4216    (t
4217     (goto-char (point-max))
4218     (widen)
4219     (forward-line 1)
4220     (unless (looking-at "$")
4221       (forward-line 2)))
4222    (sit-for 0)))
4223
4224 (defun message-buffer-name (type &optional to group)
4225   "Return a new (unique) buffer name based on TYPE and TO."
4226   (cond
4227    ;; Generate a new buffer name The Message Way.
4228    ((eq message-generate-new-buffers 'unique)
4229     (generate-new-buffer-name
4230      (concat "*" type
4231              (if to
4232                  (concat " to "
4233                          (or (car (std11-extract-address-components to))
4234                              to) "")
4235                "")
4236              (if (and group (not (string= group ""))) (concat " on " group) "")
4237              "*")))
4238    ;; Check whether `message-generate-new-buffers' is a function,
4239    ;; and if so, call it.
4240    ((message-functionp message-generate-new-buffers)
4241     (funcall message-generate-new-buffers type to group))
4242    ((eq message-generate-new-buffers 'unsent)
4243     (generate-new-buffer-name
4244      (concat "*unsent " type
4245              (if to
4246                  (concat " to "
4247                          (or (car (mail-extract-address-components to))
4248                              to) "")
4249                "")
4250              (if (and group (not (string= group ""))) (concat " on " group) "")
4251              "*")))
4252    ;; Use standard name.
4253    (t
4254     (format "*%s message*" type))))
4255
4256 (defmacro message-pop-to-buffer-1 (buffer)
4257   `(if pop-up-frames
4258        (let (special-display-buffer-names
4259              special-display-regexps
4260              same-window-buffer-names
4261              same-window-regexps)
4262          (pop-to-buffer ,buffer))
4263      (pop-to-buffer ,buffer)))
4264
4265 (defun message-pop-to-buffer (name)
4266   "Pop to buffer NAME, and warn if it already exists and is modified."
4267   (let ((buffer (get-buffer name))
4268         (pop-up-frames (and (or (static-if (featurep 'xemacs)
4269                                     (device-on-window-system-p)
4270                                   window-system)
4271                                 (>= emacs-major-version 20))
4272                             message-use-multi-frames)))
4273     (if (and buffer
4274              (buffer-name buffer))
4275         (progn
4276           (message-pop-to-buffer-1 buffer)
4277           (when (and (buffer-modified-p)
4278                      (not (y-or-n-p
4279                            "Message already being composed; erase? ")))
4280             (error "Message being composed")))
4281       (message-pop-to-buffer-1 name))
4282     (erase-buffer)
4283     (message-mode)
4284     (when pop-up-frames
4285       (set (make-local-variable 'message-original-frame) (selected-frame)))))
4286
4287 (defun message-do-send-housekeeping ()
4288   "Kill old message buffers."
4289   ;; We might have sent this buffer already.  Delete it from the
4290   ;; list of buffers.
4291   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4292   (while (and message-max-buffers
4293               message-buffer-list
4294               (>= (length message-buffer-list) message-max-buffers))
4295     ;; Kill the oldest buffer -- unless it has been changed.
4296     (let ((buffer (pop message-buffer-list)))
4297       (when (and (buffer-name buffer)
4298                  (not (buffer-modified-p buffer)))
4299         (kill-buffer buffer))))
4300   ;; Rename the buffer.
4301   (if message-send-rename-function
4302       (funcall message-send-rename-function)
4303     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
4304       (rename-buffer
4305        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
4306   ;; Push the current buffer onto the list.
4307   (when message-max-buffers
4308     (setq message-buffer-list
4309           (nconc message-buffer-list (list (current-buffer))))))
4310
4311 (defvar mc-modes-alist)
4312 (defun message-setup (headers &optional replybuffer actions)
4313   (when (and (boundp 'mc-modes-alist)
4314              (not (assq 'message-mode mc-modes-alist)))
4315     (push '(message-mode (encrypt . mc-encrypt-message)
4316                          (sign . mc-sign-message))
4317           mc-modes-alist))
4318   (when actions
4319     (setq message-send-actions actions))
4320   (setq message-reply-buffer
4321         (or (message-get-parameter 'reply-buffer)
4322             replybuffer))
4323   (goto-char (point-min))
4324   ;; Insert all the headers.
4325   (mail-header-format
4326    (let ((h headers)
4327          (alist message-header-format-alist))
4328      (while h
4329        (unless (assq (caar h) message-header-format-alist)
4330          (push (list (caar h)) alist))
4331        (pop h))
4332      alist)
4333    headers)
4334   (delete-region (point) (progn (forward-line -1) (point)))
4335   (when message-default-headers
4336     (insert message-default-headers)
4337     (or (bolp) (insert ?\n)))
4338   (put-text-property
4339    (point)
4340    (progn
4341      (insert mail-header-separator "\n")
4342      (1- (point)))
4343    'read-only nil)
4344   (forward-line -1)
4345   (when (message-news-p)
4346     (when message-default-news-headers
4347       (insert message-default-news-headers)
4348       (or (bolp) (insert ?\n)))
4349     (when message-generate-headers-first
4350       (message-generate-headers
4351        (delq 'Lines
4352              (delq 'Subject
4353                    (copy-sequence message-required-news-headers))))))
4354   (when (message-mail-p)
4355     (when message-default-mail-headers
4356       (insert message-default-mail-headers)
4357       (or (bolp) (insert ?\n)))
4358     (when message-generate-headers-first
4359       (message-generate-headers
4360        (delq 'Lines
4361              (delq 'Subject
4362                    (copy-sequence message-required-mail-headers))))))
4363   (run-hooks 'message-signature-setup-hook)
4364   (message-insert-signature)
4365   (save-restriction
4366     (message-narrow-to-headers)
4367     (run-hooks 'message-header-setup-hook))
4368   (set-buffer-modified-p nil)
4369   (setq buffer-undo-list nil)
4370   (run-hooks 'message-setup-hook)
4371   (message-position-point)
4372   (undo-boundary))
4373
4374 (defun message-set-auto-save-file-name ()
4375   "Associate the message buffer with a file in the drafts directory."
4376   (when message-auto-save-directory
4377     (if (gnus-alive-p)
4378         (setq message-draft-article
4379               (nndraft-request-associate-buffer "drafts"))
4380       (setq buffer-file-name (expand-file-name "*message*"
4381                                                message-auto-save-directory))
4382       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4383     (clear-visited-file-modtime)
4384     (static-if (boundp 'MULE)
4385         (set-file-coding-system message-draft-coding-system)
4386       (setq buffer-file-coding-system message-draft-coding-system))))
4387
4388 (defun message-disassociate-draft ()
4389   "Disassociate the message buffer from the drafts directory."
4390   (when message-draft-article
4391     (nndraft-request-expire-articles
4392      (list message-draft-article) "drafts" nil t)))
4393
4394 (defun message-insert-headers ()
4395   "Generate the headers for the article."
4396   (interactive)
4397   (save-excursion
4398     (save-restriction
4399       (message-narrow-to-headers)
4400       (when (message-news-p)
4401         (message-generate-headers
4402          (delq 'Lines
4403                (delq 'Subject
4404                      (copy-sequence message-required-news-headers)))))
4405       (when (message-mail-p)
4406         (message-generate-headers
4407          (delq 'Lines
4408                (delq 'Subject
4409                      (copy-sequence message-required-mail-headers))))))))
4410
4411 \f
4412
4413 ;;;
4414 ;;; Commands for interfacing with message
4415 ;;;
4416
4417 ;;;###autoload
4418 (defun message-mail (&optional to subject
4419                                other-headers continue switch-function
4420                                yank-action send-actions)
4421   "Start editing a mail message to be sent.
4422 OTHER-HEADERS is an alist of header/value pairs."
4423   (interactive)
4424   (let ((message-this-is-mail t))
4425     (message-pop-to-buffer (message-buffer-name "mail" to))
4426     (message-setup
4427      (nconc
4428       `((To . ,(or to "")) (Subject . ,(or subject "")))
4429       (when other-headers other-headers)))))
4430
4431 ;;;###autoload
4432 (defun message-news (&optional newsgroups subject)
4433   "Start editing a news article to be sent."
4434   (interactive)
4435   (let ((message-this-is-news t))
4436     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
4437     (message-setup `((Newsgroups . ,(or newsgroups ""))
4438                      (Subject . ,(or subject ""))))))
4439
4440 (defun message-get-reply-headers (wide &optional to-address)
4441   (let (follow-to mct never-mct from to cc reply-to mft)
4442     ;; Find all relevant headers we need.
4443     (setq from (message-fetch-field "from")
4444           to (message-fetch-field "to")
4445           cc (message-fetch-field "cc")
4446           mct (when message-use-mail-copies-to
4447                 (message-fetch-field "mail-copies-to"))
4448           reply-to (when message-use-mail-reply-to
4449                      (or (message-fetch-field "mail-reply-to")
4450                          (message-fetch-field "reply-to")))
4451           mft (when (and (not to-address)
4452                          (not reply-to)
4453                          message-use-mail-followup-to)
4454                 (message-fetch-field "mail-followup-to")))
4455
4456     ;; Handle special values of Mail-Copies-To.
4457     (when mct
4458       (cond
4459        ((and (or (equal (downcase mct) "never")
4460                  (equal (downcase mct) "nobody"))
4461              (or (not (eq message-use-mail-copies-to 'ask))
4462                  (message-y-or-n-p
4463                   (concat "Obey Mail-Copies-To: never? ") t "\
4464 You should normally obey the Mail-Copies-To: header.
4465
4466         `Mail-Copies-To: never'
4467 directs you not to send your response to the author.")))
4468         (setq never-mct t)
4469         (setq mct nil))
4470        ((and (or (equal (downcase mct) "always")
4471                  (equal (downcase mct) "poster"))
4472              (or (not (eq message-use-mail-copies-to 'ask))
4473                  (message-y-or-n-p
4474                   (concat "Obey Mail-Copies-To: always? ") t "\
4475 You should normally obey the Mail-Copies-To: header.
4476
4477         `Mail-Copies-To: always'
4478 sends a copy of your response to the author.")))
4479         (setq mct (or reply-to from)))
4480        ((and (eq message-use-mail-copies-to 'ask)
4481              (not
4482               (message-y-or-n-p
4483                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
4484 You should normally obey the Mail-Copies-To: header.
4485
4486         `Mail-Copies-To: " mct "'
4487 sends a copy of your response to " (if (string-match "," mct)
4488                                        "the specified addresses"
4489                                      "that address") ".")))
4490         (setq mct nil))))
4491
4492     ;; Handle Mail-Followup-To.
4493     (when (and mft
4494                (eq message-use-mail-followup-to 'ask)
4495                (not (message-y-or-n-p
4496                      (concat "Obey Mail-Followup-To: " mft "? ") t "\
4497 You should normally obey the Mail-Followup-To: header.
4498
4499         `Mail-Followup-To: " mft "'
4500 directs your response to " (if (string-match "," mft)
4501                                "the specified addresses"
4502                              "that address only") ".
4503
4504 A typical situation where Mail-Followup-To is used is when the author thinks
4505 that further discussion should take place only in "
4506                              (if (string-match "," mft)
4507                                  "the specified mailing lists"
4508                                "that mailing list") ".")))
4509       (setq mft nil))
4510
4511     (if (or (not wide)
4512             to-address)
4513         (progn
4514           (setq follow-to (list (cons 'To (or to-address reply-to mft from))))
4515           (when (and wide mct)
4516             (push (cons 'Cc mct) follow-to)))
4517       (let (ccalist)
4518         (save-excursion
4519           (message-set-work-buffer)
4520           (unless never-mct
4521             (insert (or reply-to from "")))
4522           (insert (if mft (concat (if (bolp) "" ", ") mft "") ""))
4523           (insert (if to (concat (if (bolp) "" ", ") to "") ""))
4524           (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
4525           (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
4526           (goto-char (point-min))
4527           (while (re-search-forward "[ \t]+" nil t)
4528             (replace-match " " t t))
4529           ;; Remove addresses that match `rmail-dont-reply-to-names'.
4530           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4531             (insert (prog1 (rmail-dont-reply-to (buffer-string))
4532                       (erase-buffer))))
4533           (goto-char (point-min))
4534           ;; Perhaps "Mail-Copies-To: never" removed the only address?
4535           (when (eobp)
4536             (insert (or reply-to from "")))
4537           (setq ccalist
4538                 (mapcar
4539                  (lambda (addr)
4540                    (cons (mail-strip-quoted-names addr) addr))
4541                  (message-tokenize-header (buffer-string))))
4542           (let ((s ccalist))
4543             (while s
4544               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
4545         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
4546         (when ccalist
4547           (let ((ccs (cons 'Cc (mapconcat
4548                                 (lambda (addr) (cdr addr)) ccalist ", "))))
4549             (when (string-match "^ +" (cdr ccs))
4550               (setcdr ccs (substring (cdr ccs) (match-end 0))))
4551             (push ccs follow-to)))))
4552     follow-to))
4553
4554 ;;;###autoload
4555 (defun message-reply (&optional to-address wide)
4556   "Start editing a reply to the article in the current buffer."
4557   (interactive)
4558   (require 'gnus-sum)                   ; for gnus-list-identifiers
4559   (let ((cur (current-buffer))
4560         from subject date
4561         references message-id follow-to
4562         (inhibit-point-motion-hooks t)
4563         (message-this-is-mail t)
4564         gnus-warning in-reply-to)
4565     (save-restriction
4566       (message-narrow-to-head)
4567       ;; Allow customizations to have their say.
4568       (if (not wide)
4569           ;; This is a regular reply.
4570           (if (message-functionp message-reply-to-function)
4571               (setq follow-to (funcall message-reply-to-function)))
4572         ;; This is a followup.
4573         (if (message-functionp message-wide-reply-to-function)
4574             (save-excursion
4575               (setq follow-to
4576                     (funcall message-wide-reply-to-function)))))
4577       (setq message-id (message-fetch-field "message-id" t)
4578             references (message-fetch-field "references")
4579             date (message-fetch-field "date")
4580             from (message-fetch-field "from")
4581             subject (or (message-fetch-field "subject") "none"))
4582       (if gnus-list-identifiers
4583           (setq subject (message-strip-list-identifiers subject)))
4584       (setq subject (message-make-followup-subject subject))
4585
4586       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4587                  (string-match "<[^>]+>" gnus-warning))
4588         (setq message-id (match-string 0 gnus-warning)))
4589
4590       (unless follow-to
4591         (setq follow-to (message-get-reply-headers wide to-address)))
4592
4593       ;; Get the references from "In-Reply-To" field if there were
4594       ;; no references and "In-Reply-To" field looks promising.
4595       (unless references
4596         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
4597                    (string-match "<[^>]+>" in-reply-to))
4598           (setq references (match-string 0 in-reply-to)))))
4599
4600     (message-pop-to-buffer
4601      (message-buffer-name
4602       (if wide "wide reply" "reply") from
4603       (if wide to-address nil)))
4604
4605     (setq message-reply-headers
4606           (make-full-mail-header-from-decoded-header
4607            0 subject from date message-id references 0 0 ""))
4608
4609     (message-setup
4610      `((Subject . ,subject)
4611        ,@follow-to
4612        ,@(if (or references message-id)
4613              `((References . ,(concat (or references "") (and references " ")
4614                                       (or message-id ""))))
4615            nil))
4616      cur)))
4617
4618 ;;;###autoload
4619 (defun message-wide-reply (&optional to-address)
4620   "Make a \"wide\" reply to the message in the current buffer."
4621   (interactive)
4622   (message-reply to-address t))
4623
4624 ;;;###autoload
4625 (defun message-followup (&optional to-newsgroups)
4626   "Follow up to the message in the current buffer.
4627 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4628   (interactive)
4629   (let ((cur (current-buffer))
4630         from subject date mct
4631         references message-id follow-to
4632         (inhibit-point-motion-hooks t)
4633         (message-this-is-news t)
4634         followup-to distribution newsgroups gnus-warning posted-to mft mrt)
4635     (save-restriction
4636       (message-narrow-to-head)
4637       (when (message-functionp message-followup-to-function)
4638         (setq follow-to
4639               (funcall message-followup-to-function)))
4640       (setq from (message-fetch-field "from")
4641             date (message-fetch-field "date" t)
4642             subject (or (message-fetch-field "subject") "none")
4643             references (message-fetch-field "references")
4644             message-id (message-fetch-field "message-id" t)
4645             followup-to (when message-use-followup-to
4646                           (message-fetch-field "followup-to"))
4647             distribution (message-fetch-field "distribution")
4648             newsgroups (message-fetch-field "newsgroups")
4649             posted-to (message-fetch-field "posted-to")
4650             mct (when message-use-mail-copies-to
4651                   (message-fetch-field "mail-copies-to"))
4652             mft (when message-use-mail-followup-to
4653                   (message-fetch-field "mail-followup-to"))
4654             mrt (when message-use-mail-reply-to
4655                   (or (message-fetch-field "mail-reply-to")
4656                       (message-fetch-field "reply-to")))
4657             gnus-warning (message-fetch-field "gnus-warning"))
4658       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
4659         (setq message-id (match-string 0 gnus-warning)))
4660       ;; Remove bogus distribution.
4661       (when (and (stringp distribution)
4662                  (let ((case-fold-search t))
4663                    (string-match "world" distribution)))
4664         (setq distribution nil))
4665       (if gnus-list-identifiers
4666           (setq subject (message-strip-list-identifiers subject)))
4667       (setq subject (message-make-followup-subject subject))
4668       (widen))
4669
4670     ;; Handle special values of Mail-Copies-To.
4671     (when mct
4672       (cond
4673        ((and (or (equal (downcase mct) "never")
4674                  (equal (downcase mct) "nobody"))
4675              (or (not (eq message-use-mail-copies-to 'ask))
4676                  (message-y-or-n-p
4677                   (concat "Obey Mail-Copies-To: never? ") t "\
4678 You should normally obey the Mail-Copies-To: header.
4679
4680         `Mail-Copies-To: never'
4681 directs you not to send your response to the author.")))
4682         (setq mct nil))
4683        ((and (or (equal (downcase mct) "always")
4684                  (equal (downcase mct) "poster"))
4685              (or (not (eq message-use-mail-copies-to 'ask))
4686                  (message-y-or-n-p
4687                   (concat "Obey Mail-Copies-To: always? ") t "\
4688 You should normally obey the Mail-Copies-To: header.
4689
4690         `Mail-Copies-To: always'
4691 sends a copy of your response to the author.")))
4692         (setq mct (or mrt from)))
4693        ((and (eq message-use-mail-copies-to 'ask)
4694              (not
4695               (message-y-or-n-p
4696                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
4697 You should normally obey the Mail-Copies-To: header.
4698
4699         `Mail-Copies-To: " mct "'
4700 sends a copy of your response to " (if (string-match "," mct)
4701                                        "the specified addresses"
4702                                      "that address") ".")))
4703         (setq mct nil))
4704        ))
4705
4706     (unless follow-to
4707       (cond
4708        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
4709        ;; Handle Followup-To.
4710        (followup-to
4711         (cond
4712          ((equal (downcase followup-to) "poster")
4713           (if (or (eq message-use-followup-to 'use)
4714                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
4715 You should normally obey the Followup-To: header.
4716
4717         `Followup-To: poster'
4718 sends your response via e-mail instead of news.
4719
4720 A typical situation where `Followup-To: poster' is used is when the author
4721 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4722               (setq message-this-is-news nil
4723                     distribution nil
4724                     follow-to (list (cons 'To (or mrt from ""))))
4725             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
4726          (t
4727           (if (or (equal followup-to newsgroups)
4728                   (not (eq message-use-followup-to 'ask))
4729                   (message-y-or-n-p
4730                    (concat "Obey Followup-To: " followup-to "? ") t "\
4731 You should normally obey the Followup-To: header.
4732
4733         `Followup-To: " followup-to "'
4734 directs your response to " (if (string-match "," followup-to)
4735                                "the specified newsgroups"
4736                              "that newsgroup only") ".
4737
4738 If a message is posted to several newsgroups, Followup-To is often
4739 used to direct the following discussion to one newsgroup only,
4740 because discussions that are spread over several newsgroup tend to
4741 be fragmented and very difficult to follow.
4742
4743 Also, some source/announcement newsgroups are not indented for discussion;
4744 responses here are directed to other newsgroups."))
4745               (setq follow-to (list (cons 'Newsgroups followup-to)))
4746             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
4747        ;; Handle Mail-Followup-To, followup via e-mail.
4748        ((and mft
4749              (or (not (eq message-use-mail-followup-to 'ask))
4750                  (message-y-or-n-p
4751                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
4752 You should normally obey the Mail-Followup-To: header.
4753
4754         `Mail-Followup-To: " mft "'
4755 directs your response to " (if (string-match "," mft)
4756                                "the specified addresses"
4757                              "that address only") " instead of news.
4758
4759 A typical situation where Mail-Followup-To is used is when the author thinks
4760 that further discussion should take place only in "
4761                              (if (string-match "," mft)
4762                                  "the specified mailing lists"
4763                                "that mailing list") ".")))
4764         (setq message-this-is-news nil
4765               distribution nil
4766               follow-to (list (cons 'To mft))))
4767        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
4768        (t
4769         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
4770
4771     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4772
4773     (setq message-reply-headers
4774           (make-full-mail-header-from-decoded-header
4775            0 subject from date message-id references 0 0 ""))
4776
4777     (message-setup
4778      `((Subject . ,subject)
4779        ,@follow-to
4780        ,@(and mct (list (cons 'Cc mct)))
4781        ,@(and distribution (list (cons 'Distribution distribution)))
4782        ,@(if (or references message-id)
4783              `((References . ,(concat (or references "") (and references " ")
4784                                       (or message-id ""))))))
4785      cur)))
4786
4787 ;;;###autoload
4788 (defun message-cancel-news (&optional arg)
4789   "Cancel an article you posted.
4790 If ARG, allow editing of the cancellation message."
4791   (interactive "P")
4792   (unless (message-news-p)
4793     (error "This is not a news article; canceling is impossible"))
4794   (when (yes-or-no-p "Do you really want to cancel this article? ")
4795     (let (from newsgroups message-id distribution buf sender)
4796       (save-excursion
4797         ;; Get header info from original article.
4798         (save-restriction
4799           (message-narrow-to-head)
4800           (setq from (message-fetch-field "from")
4801                 sender (message-fetch-field "sender")
4802                 newsgroups (message-fetch-field "newsgroups")
4803                 message-id (message-fetch-field "message-id" t)
4804                 distribution (message-fetch-field "distribution")))
4805         ;; Make sure that this article was written by the user.
4806         (unless (or (and sender
4807                          (string-equal
4808                           (downcase sender)
4809                           (downcase (message-make-sender))))
4810                     (string-equal
4811                      (downcase (cadr (std11-extract-address-components
4812                                       from)))
4813                      (downcase (cadr (std11-extract-address-components
4814                                       (message-make-from))))))
4815           (error "This article is not yours"))
4816         ;; Make control message.
4817         (if arg
4818             (message-news)
4819           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4820         (erase-buffer)
4821         (insert "Newsgroups: " newsgroups "\n"
4822                "From: " from "\n"
4823                 "Subject: cmsg cancel " message-id "\n"
4824                 "Control: cancel " message-id "\n"
4825                 (if distribution
4826                     (concat "Distribution: " distribution "\n")
4827                   "")
4828                 mail-header-separator "\n"
4829                 message-cancel-message)
4830         (run-hooks 'message-cancel-hook)
4831         (message "Canceling your article...")
4832         (unless arg
4833           (if (let ((message-syntax-checks
4834                      'dont-check-for-anything-just-trust-me)
4835                     (message-encoding-buffer (current-buffer))
4836                     (message-edit-buffer (current-buffer)))
4837                 (message-send-news))
4838               (message "Canceling your article...done"))
4839           (kill-buffer buf))))))
4840
4841 (defun message-supersede-setup-for-mime-edit ()
4842   (set (make-local-variable 'message-setup-hook) nil)
4843   (mime-edit-again))
4844
4845 ;;;###autoload
4846 (defun message-supersede ()
4847   "Start composing a message to supersede the current message.
4848 This is done simply by taking the old article and adding a Supersedes
4849 header line with the old Message-ID."
4850   (interactive)
4851   (let ((cur (current-buffer))
4852         (sender (message-fetch-field "sender"))
4853         (from (message-fetch-field "from")))
4854     ;; Check whether the user owns the article that is to be superseded.
4855     (unless (or (and sender
4856                      (string-equal
4857                       (downcase sender)
4858                       (downcase (message-make-sender))))
4859                 (string-equal
4860                  (downcase (cadr (std11-extract-address-components from)))
4861                  (downcase (cadr (std11-extract-address-components
4862                                   (message-make-from))))))
4863       (error "This article is not yours"))
4864     ;; Get a normal message buffer.
4865     (message-pop-to-buffer (message-buffer-name "supersede"))
4866     (insert-buffer-substring cur)
4867     (message-narrow-to-head)
4868     ;; Remove unwanted headers.
4869     (when message-ignored-supersedes-headers
4870       (message-remove-header message-ignored-supersedes-headers t))
4871     (goto-char (point-min))
4872     (if (not (re-search-forward "^Message-ID: " nil t))
4873         (error "No Message-ID in this article")
4874       (replace-match "Supersedes: " t t))
4875     (goto-char (point-max))
4876     (insert mail-header-separator)
4877     (widen)
4878     (when message-supersede-setup-function
4879       (funcall message-supersede-setup-function))
4880     (run-hooks 'message-supersede-setup-hook)
4881     (goto-char (point-min))
4882     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
4883
4884 ;;;###autoload
4885 (defun message-recover ()
4886   "Reread contents of current buffer from its last auto-save file."
4887   (interactive)
4888   (let ((file-name (make-auto-save-file-name)))
4889     (cond ((save-window-excursion
4890              (if (not (eq system-type 'vax-vms))
4891                  (with-output-to-temp-buffer "*Directory*"
4892                    (with-current-buffer standard-output
4893                      (fundamental-mode)) ; for Emacs 20.4+
4894                    (buffer-disable-undo standard-output)
4895                    (let ((default-directory "/"))
4896                      (call-process
4897                       "ls" nil standard-output nil "-l" file-name))))
4898              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4899            (let ((buffer-read-only nil))
4900              (erase-buffer)
4901              (insert-file-contents file-name nil)))
4902           (t (error "message-recover cancelled")))))
4903
4904 ;;; Washing Subject:
4905
4906 (defun message-wash-subject (subject)
4907   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4908   (with-temp-buffer
4909     (insert-string subject)
4910     (goto-char (point-min))
4911     ;; strip Re/Fwd stuff off the beginning
4912     (while (re-search-forward
4913             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4914       (replace-match ""))
4915
4916     ;; and gnus-style forwards [foo@bar.com] subject
4917     (goto-char (point-min))
4918     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4919       (replace-match ""))
4920
4921     ;; and off the end
4922     (goto-char (point-max))
4923     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4924       (replace-match ""))
4925
4926     ;; and finally, any whitespace that was left-over
4927     (goto-char (point-min))
4928     (while (re-search-forward "^[ \t]+" nil t)
4929       (replace-match ""))
4930     (goto-char (point-max))
4931     (while (re-search-backward "[ \t]+$" nil t)
4932       (replace-match ""))
4933
4934     (buffer-string)))
4935
4936 ;;; Forwarding messages.
4937
4938 (defun message-forward-subject-author-subject (subject)
4939   "Generate a subject for a forwarded message.
4940 The form is: [Source] Subject, where if the original message was mail,
4941 Source is the sender, and if the original message was news, Source is
4942 the list of newsgroups is was posted to."
4943   (concat "["
4944           (or (message-fetch-field
4945                (if (message-news-p) "newsgroups" "from"))
4946               "(nowhere)")
4947           "] " subject))
4948
4949 (defun message-forward-subject-fwd (subject)
4950   "Generate a subject for a forwarded message.
4951 The form is: Fwd: Subject, where Subject is the original subject of
4952 the message."
4953   (concat "Fwd: " subject))
4954
4955 (defun message-make-forward-subject ()
4956   "Return a Subject header suitable for the message in the current buffer."
4957   (save-excursion
4958     (save-restriction
4959       (message-narrow-to-head)
4960       (let ((funcs message-make-forward-subject-function)
4961             (subject (message-fetch-field "Subject")))
4962         (setq subject
4963               (if subject
4964                   (if message-wash-forwarded-subjects
4965                       (message-wash-subject
4966                        (nnheader-decode-subject subject))
4967                     (nnheader-decode-subject subject))
4968                 "(none)"))
4969         ;; Make sure funcs is a list.
4970         (and funcs
4971              (not (listp funcs))
4972              (setq funcs (list funcs)))
4973         ;; Apply funcs in order, passing subject generated by previous
4974         ;; func to the next one.
4975         (while funcs
4976           (when (message-functionp (car funcs))
4977             (setq subject (funcall (car funcs) subject)))
4978           (setq funcs (cdr funcs)))
4979         subject))))
4980
4981 ;;;###autoload
4982 (defun message-forward (&optional news)
4983   "Forward the current message via mail.
4984 Optional NEWS will use news to forward instead of mail."
4985   (interactive "P")
4986   (let ((cur (current-buffer))
4987         (subject (message-make-forward-subject))
4988         art-beg)
4989     (if news
4990         (message-news nil subject)
4991       (message-mail nil subject))
4992     ;; Put point where we want it before inserting the forwarded
4993     ;; message.
4994     (if message-forward-before-signature
4995         (message-goto-body)
4996       (goto-char (point-max)))
4997     ;; Make sure we're at the start of the line.
4998     (unless (bolp)
4999       (insert "\n"))
5000     ;; Narrow to the area we are to insert.
5001     (narrow-to-region (point) (point))
5002     ;; Insert the separators and the forwarded buffer.
5003     (insert message-forward-start-separator)
5004     (setq art-beg (point))
5005     (insert-buffer-substring cur)
5006     (goto-char (point-max))
5007     (insert message-forward-end-separator)
5008     (set-text-properties (point-min) (point-max) nil)
5009     ;; Remove all unwanted headers.
5010     (goto-char art-beg)
5011     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
5012                                   (1- (point))
5013                                 (point)))
5014     (goto-char (point-min))
5015     (message-remove-header message-included-forward-headers t nil t)
5016     (widen)
5017     (message-position-point)))
5018
5019 ;;;###autoload
5020 (defun message-resend (address)
5021   "Resend the current article to ADDRESS."
5022   (interactive
5023    (list (message-read-from-minibuffer "Resend message to: ")))
5024   (message "Resending message to %s..." address)
5025   (save-excursion
5026     (let ((cur (current-buffer))
5027           beg)
5028       ;; We first set up a normal mail buffer.
5029       (set-buffer (get-buffer-create " *message resend*"))
5030       (erase-buffer)
5031       ;; avoid to turn-on-mime-edit
5032       (let (message-setup-hook)
5033         (message-setup `((To . ,address)))
5034         )
5035       ;; Insert our usual headers.
5036       (message-generate-headers '(From Date To))
5037       (message-narrow-to-headers)
5038       ;; Rename them all to "Resent-*".
5039       (while (re-search-forward "^[A-Za-z]" nil t)
5040         (forward-char -1)
5041         (insert "Resent-"))
5042       (widen)
5043       (forward-line)
5044       (delete-region (point) (point-max))
5045       (setq beg (point))
5046       ;; Insert the message to be resent.
5047       (insert-buffer-substring cur)
5048       (goto-char (point-min))
5049       (search-forward "\n\n")
5050       (forward-char -1)
5051       (save-restriction
5052         (narrow-to-region beg (point))
5053         (message-remove-header message-ignored-resent-headers t)
5054         (goto-char (point-max)))
5055       (insert mail-header-separator)
5056       ;; Rename all old ("Also-")Resent headers.
5057       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5058         (beginning-of-line)
5059         (insert "Also-"))
5060       ;; Quote any "From " lines at the beginning.
5061       (goto-char beg)
5062       (when (looking-at "From ")
5063         (replace-match "X-From-Line: "))
5064       ;; Send it.
5065       (let ((message-encoding-buffer (current-buffer))
5066             (message-edit-buffer (current-buffer)))
5067         (let (message-required-mail-headers)
5068           (message-send-mail)))
5069       (kill-buffer (current-buffer)))
5070     (message "Resending message to %s...done" address)))
5071
5072 (defun message-bounce-setup-for-mime-edit ()
5073   (set (make-local-variable 'message-setup-hook) nil)
5074   (mime-edit-again))
5075
5076 ;;;###autoload
5077 (defun message-bounce ()
5078   "Re-mail the current message.
5079 This only makes sense if the current message is a bounce message that
5080 contains some mail you have written which has been bounced back to
5081 you."
5082   (interactive)
5083   (let ((cur (current-buffer))
5084         boundary)
5085     (message-pop-to-buffer (message-buffer-name "bounce"))
5086     (insert-buffer-substring cur)
5087     (undo-boundary)
5088     (message-narrow-to-head)
5089     (if (and (message-fetch-field "MIME-Version")
5090              (setq boundary (message-fetch-field "Content-Type")))
5091         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
5092             (setq boundary (concat (match-string 1 boundary) " *\n"
5093                                    "Content-Type: message/rfc822"))
5094           (setq boundary nil)))
5095     (widen)
5096     (goto-char (point-min))
5097     (search-forward "\n\n" nil t)
5098     (or (and boundary
5099              (re-search-forward boundary nil t)
5100              (forward-line 2))
5101         (and (re-search-forward message-unsent-separator nil t)
5102              (forward-line 1))
5103         (re-search-forward "^Return-Path:.*\n" nil t))
5104     ;; We remove everything before the bounced mail.
5105     (delete-region
5106      (point-min)
5107      (if (re-search-forward "^[^ \n\t]+:" nil t)
5108          (match-beginning 0)
5109        (point)))
5110     (save-restriction
5111       (message-narrow-to-head)
5112       (message-remove-header message-ignored-bounced-headers t)
5113       (goto-char (point-max))
5114       (insert mail-header-separator))
5115     (when message-bounce-setup-function
5116       (funcall message-bounce-setup-function))
5117     (run-hooks 'message-bounce-setup-hook)
5118     (message-position-point)))
5119
5120 ;;;
5121 ;;; Interactive entry points for new message buffers.
5122 ;;;
5123
5124 ;;;###autoload
5125 (defun message-mail-other-window (&optional to subject)
5126   "Like `message-mail' command, but display mail buffer in another window."
5127   (interactive)
5128   (let ((pop-up-windows t)
5129         (special-display-buffer-names nil)
5130         (special-display-regexps nil)
5131         (same-window-buffer-names nil)
5132         (same-window-regexps nil))
5133     (message-pop-to-buffer (message-buffer-name "mail" to)))
5134   (let ((message-this-is-mail t))
5135     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
5136
5137 ;;;###autoload
5138 (defun message-mail-other-frame (&optional to subject)
5139   "Like `message-mail' command, but display mail buffer in another frame."
5140   (interactive)
5141   (let ((pop-up-frames t)
5142         (special-display-buffer-names nil)
5143         (special-display-regexps nil)
5144         (same-window-buffer-names nil)
5145         (same-window-regexps nil))
5146     (message-pop-to-buffer (message-buffer-name "mail" to)))
5147   (let ((message-this-is-mail t))
5148     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
5149
5150 ;;;###autoload
5151 (defun message-news-other-window (&optional newsgroups subject)
5152   "Start editing a news article to be sent."
5153   (interactive)
5154   (let ((pop-up-windows t)
5155         (special-display-buffer-names nil)
5156         (special-display-regexps nil)
5157         (same-window-buffer-names nil)
5158         (same-window-regexps nil))
5159     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5160   (let ((message-this-is-news t))
5161     (message-setup `((Newsgroups . ,(or newsgroups ""))
5162                      (Subject . ,(or subject ""))))))
5163
5164 ;;;###autoload
5165 (defun message-news-other-frame (&optional newsgroups subject)
5166   "Start editing a news article to be sent."
5167   (interactive)
5168   (let ((pop-up-frames t)
5169         (special-display-buffer-names nil)
5170         (special-display-regexps nil)
5171         (same-window-buffer-names nil)
5172         (same-window-regexps nil))
5173     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5174   (let ((message-this-is-news t))
5175     (message-setup `((Newsgroups . ,(or newsgroups ""))
5176                      (Subject . ,(or subject ""))))))
5177
5178 ;;; underline.el
5179
5180 ;; This code should be moved to underline.el (from which it is stolen).
5181
5182 ;;;###autoload
5183 (defun bold-region (start end)
5184   "Bold all nonblank characters in the region.
5185 Works by overstriking characters.
5186 Called from program, takes two arguments START and END
5187 which specify the range to operate on."
5188   (interactive "r")
5189   (save-excursion
5190     (let ((end1 (make-marker)))
5191       (move-marker end1 (max start end))
5192       (goto-char (min start end))
5193       (while (< (point) end1)
5194         (or (looking-at "[_\^@- ]")
5195             (insert (char-after) "\b"))
5196         (forward-char 1)))))
5197
5198 ;;;###autoload
5199 (defun unbold-region (start end)
5200   "Remove all boldness (overstruck characters) in the region.
5201 Called from program, takes two arguments START and END
5202 which specify the range to operate on."
5203   (interactive "r")
5204   (save-excursion
5205     (let ((end1 (make-marker)))
5206       (move-marker end1 (max start end))
5207       (goto-char (min start end))
5208       (while (re-search-forward "\b" end1 t)
5209         (if (eq (char-after) (char-after (- (point) 2)))
5210             (delete-char -2))))))
5211
5212 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5213
5214 ;; Support for toolbar
5215 (when (featurep 'xemacs)
5216   (require 'messagexmas))
5217
5218 ;;; Group name completion.
5219
5220 (defvar message-newgroups-header-regexp
5221   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5222   "Regexp that match headers that lists groups.")
5223
5224 (defun message-tab ()
5225   "Expand group names in Newsgroups and Followup-To headers.
5226 Do a `tab-to-tab-stop' if not in those headers."
5227   (interactive)
5228   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
5229         (mail-abbrev-in-expansion-header-p))
5230       (message-expand-group)
5231     (tab-to-tab-stop)))
5232
5233 (defvar gnus-active-hashtb)
5234 (defun message-expand-group ()
5235   "Expand the group name under point."
5236   (let* ((b (save-excursion
5237               (save-restriction
5238                 (narrow-to-region
5239                  (save-excursion
5240                    (beginning-of-line)
5241                    (skip-chars-forward "^:")
5242                    (1+ (point)))
5243                  (point))
5244                 (skip-chars-backward "^, \t\n") (point))))
5245          (completion-ignore-case t)
5246          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5247                                             (point))))
5248          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5249          (completions (all-completions string hashtb))
5250          comp)
5251     (delete-region b (point))
5252     (cond
5253      ((= (length completions) 1)
5254       (if (string= (car completions) string)
5255           (progn
5256             (insert string)
5257             (message "Only matching group"))
5258         (insert (car completions))))
5259      ((and (setq comp (try-completion string hashtb))
5260            (not (string= comp string)))
5261       (insert comp))
5262      (t
5263       (insert string)
5264       (if (not comp)
5265           (message "No matching groups")
5266         (save-selected-window
5267           (pop-to-buffer "*Completions*")
5268           (buffer-disable-undo)
5269           (let ((buffer-read-only nil))
5270             (erase-buffer)
5271             (let ((standard-output (current-buffer)))
5272               (display-completion-list (sort completions 'string<)))
5273             (goto-char (point-min))
5274             (delete-region (point) (progn (forward-line 3) (point))))))))))
5275
5276 ;;; Help stuff.
5277
5278 (defun message-talkative-question (ask question show &rest text)
5279   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
5280 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
5281 The following arguments may contain lists of values."
5282   (if (and show
5283            (setq text (message-flatten-list text)))
5284       (save-window-excursion
5285         (save-excursion
5286           (with-output-to-temp-buffer " *MESSAGE information message*"
5287             (set-buffer " *MESSAGE information message*")
5288             (fundamental-mode)          ; for Emacs 20.4+
5289             (mapcar 'princ text)
5290             (goto-char (point-min))))
5291         (funcall ask question))
5292     (funcall ask question)))
5293
5294 (defun message-flatten-list (list)
5295   "Return a new, flat list that contains all elements of LIST.
5296
5297 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
5298 => (1 2 3 4 5 6 7)"
5299   (cond ((consp list)
5300          (apply 'append (mapcar 'message-flatten-list list)))
5301         (list
5302          (list list))))
5303
5304 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
5305   "Create and return a buffer with a name based on NAME using generate-new-buffer.
5306 Then clone the local variables and values from the old buffer to the
5307 new one, cloning only the locals having a substring matching the
5308 regexp varstr."
5309   (let ((oldbuf (current-buffer)))
5310     (save-excursion
5311       (set-buffer (generate-new-buffer name))
5312       (message-clone-locals oldbuf varstr)
5313       (current-buffer))))
5314
5315 (defun message-clone-locals (buffer &optional varstr)
5316   "Clone the local variables from BUFFER to the current buffer."
5317   (let ((locals (save-excursion
5318                   (set-buffer buffer)
5319                   (buffer-local-variables)))
5320         (regexp
5321          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
5322     (mapcar
5323      (lambda (local)
5324        (when (and (consp local)
5325                   (car local)
5326                   (string-match regexp (symbol-name (car local)))
5327                   (or (null varstr)
5328                       (string-match varstr (symbol-name (car local)))))
5329          (ignore-errors
5330            (set (make-local-variable (car local))
5331                 (cdr local)))))
5332      locals)))
5333
5334
5335 ;;; @ for MIME Edit mode
5336 ;;;
5337
5338 (defun message-maybe-encode ()
5339   (when message-mime-mode
5340     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
5341     (let ((pgp-processing (with-current-buffer message-edit-buffer
5342                             mime-edit-pgp-processing)))
5343       (setq mime-edit-pgp-processing pgp-processing))
5344     (run-hooks 'mime-edit-translate-hook)
5345     (if (catch 'mime-edit-error
5346           (save-excursion
5347             (mime-edit-pgp-enclose-buffer)
5348             (mime-edit-translate-body)
5349             ))
5350         (error "Translation error!")
5351       )
5352     (end-of-invisible)
5353     (run-hooks 'mime-edit-exit-hook)
5354     ))
5355
5356 (defun message-mime-insert-article (&optional full-headers)
5357   (interactive "P")
5358   (let ((message-cite-function 'mime-edit-inserted-message-filter)
5359         (message-reply-buffer
5360          (message-get-parameter-with-eval 'original-buffer))
5361         (start (point)))
5362     (message-yank-original nil)
5363     (save-excursion
5364       (narrow-to-region (goto-char start)
5365                         (if (search-forward "\n\n" nil t)
5366                             (1- (point))
5367                           (point-max)))
5368       (goto-char (point-min))
5369       (let ((message-included-forward-headers
5370              (if full-headers "" message-included-forward-headers)))
5371         (message-remove-header message-included-forward-headers t nil t))
5372       (widen))))
5373
5374 (set-alist 'mime-edit-message-inserter-alist
5375            'message-mode (function message-mime-insert-article))
5376
5377 ;;; Miscellaneous functions
5378
5379 ;; stolen (and renamed) from nnheader.el
5380 (static-if (fboundp 'subst-char-in-string)
5381     (defsubst message-replace-chars-in-string (string from to)
5382       (subst-char-in-string from to string))
5383   (defun message-replace-chars-in-string (string from to)
5384     "Replace characters in STRING from FROM to TO."
5385     (let ((string (substring string 0)) ;Copy string.
5386           (len (length string))
5387           (idx 0))
5388       ;; Replace all occurrences of FROM with TO.
5389       (while (< idx len)
5390         (when (= (aref string idx) from)
5391           (aset string idx to))
5392         (setq idx (1+ idx)))
5393       string)))
5394
5395 ;;;
5396 ;;; MIME functions
5397 ;;;
5398
5399 (defvar message-inhibit-body-encoding t)
5400
5401 (defun message-encode-message-body ()
5402   (unless message-inhibit-body-encoding
5403     (let ((mail-parse-charset (or mail-parse-charset
5404                                   message-default-charset))
5405           (case-fold-search t)
5406           lines content-type-p)
5407       (message-goto-body)
5408       (save-restriction
5409         (narrow-to-region (point) (point-max))
5410         (let ((new (mml-generate-mime)))
5411           (when new
5412             (delete-region (point-min) (point-max))
5413             (insert new)
5414             (goto-char (point-min))
5415             (if (eq (aref new 0) ?\n)
5416                 (delete-char 1)
5417               (search-forward "\n\n")
5418               (setq lines (buffer-substring (point-min) (1- (point))))
5419               (delete-region (point-min) (point))))))
5420       (save-restriction
5421         (message-narrow-to-headers-or-head)
5422         (message-remove-header "Mime-Version")
5423         (goto-char (point-max))
5424         (insert "MIME-Version: 1.0\n")
5425         (when lines
5426           (insert lines))
5427         (setq content-type-p
5428               (re-search-backward "^Content-Type:" nil t)))
5429       (save-restriction
5430         (message-narrow-to-headers-or-head)
5431         (message-remove-first-header "Content-Type")
5432         (message-remove-first-header "Content-Transfer-Encoding"))
5433       ;; We always make sure that the message has a Content-Type header.
5434       ;; This is because some broken MTAs and MUAs get awfully confused
5435       ;; when confronted with a message with a MIME-Version header and
5436       ;; without a Content-Type header.  For instance, Solaris'
5437       ;; /usr/bin/mail.
5438       (unless content-type-p
5439         (goto-char (point-min))
5440         (re-search-forward "^MIME-Version:")
5441         (forward-line 1)
5442         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
5443
5444 (defun message-read-from-minibuffer (prompt)
5445   "Read from the minibuffer while providing abbrev expansion."
5446   (if (fboundp 'mail-abbrevs-setup)
5447       (let ((mail-abbrev-mode-regexp "")
5448             (minibuffer-setup-hook 'mail-abbrevs-setup))
5449         (read-from-minibuffer prompt))
5450     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
5451       (read-string prompt))))
5452
5453 (defun message-save-drafts ()
5454   "Postponing the message."
5455   (interactive)
5456   (message "Saving %s..." buffer-file-name)
5457   (let ((reply-headers message-reply-headers)
5458         (msg (buffer-substring-no-properties (point-min) (point-max))))
5459     (with-temp-file buffer-file-name
5460       (insert msg)
5461       (setq message-reply-headers reply-headers)
5462       (message-generate-headers '((optional . In-Reply-To)))
5463       (mime-edit-translate-buffer))
5464     (set-buffer-modified-p nil))
5465   (message "Saving %s...done" buffer-file-name))
5466
5467 (provide 'message)
5468
5469 (run-hooks 'message-load-hook)
5470
5471 ;; Local Variables:
5472 ;; coding: iso-8859-1
5473 ;; End:
5474
5475 ;;; message.el ends here