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