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