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