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