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