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