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