*** empty log message ***
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: mail, news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile 
33   (require 'cl))
34 (require 'mailheader)
35 (require 'rmail)
36 (require 'nnheader)
37 (require 'timezone)
38 (require 'easymenu)
39 (require 'custom)
40 (if (string-match "XEmacs\\|Lucid" emacs-version)
41     (require 'mail-abbrevs)
42   (require 'mailabbrev))
43
44 (defgroup message '((user-mail-address custom-variable)
45                     (user-full-name custom-variable))
46   "Mail and news message composing."
47   :link '(custom-manual "(message)Top")
48   :group 'emacs)
49
50 (put 'user-mail-address 'custom-type 'string)
51 (put 'user-full-name 'custom-type 'string)
52
53 (defgroup message-various nil
54   "Various Message Variables"
55   :link '(custom-manual "(message)Various Message Variables")
56   :group 'message)
57
58 (defgroup message-buffers nil
59   "Message Buffers"
60   :link '(custom-manual "(message)Message Buffers")
61   :group 'message)
62
63 (defgroup message-sending nil
64   "Message Sending"
65   :link '(custom-manual "(message)Sending Variables")
66   :group 'message)
67
68 (defgroup message-interface nil
69   "Message Interface"
70   :link '(custom-manual "(message)Interface")
71   :group 'message)
72
73 (defgroup message-forwarding nil
74   "Message Forwarding"
75   :link '(custom-manual "(message)Forwarding")
76   :group 'message-interface)
77
78 (defgroup message-insertion nil
79   "Message Insertion"
80   :link '(custom-manual "(message)Insertion")
81   :group 'message)
82
83 (defgroup message-headers nil
84   "Message Headers"
85   :link '(custom-manual "(message)Message Headers")
86   :group 'message)
87
88 (defgroup message-news nil
89   "Composing News Messages"
90   :group 'message)
91
92 (defgroup message-mail nil
93   "Composing Mail Messages"
94   :group 'message)
95
96 (defcustom message-directory "~/Mail/"
97   "*Directory from which all other mail file variables are derived."
98   :group 'message-various
99   :type 'directory)
100
101 (defcustom message-max-buffers 10
102   "*How many buffers to keep before starting to kill them off."
103   :group 'message-buffers
104   :type 'integer)
105
106 (defcustom message-send-rename-function nil
107   "Function called to rename the buffer after sending it."
108   :group 'message-buffers
109   :type 'function)
110
111 ;;;###autoload
112 (defcustom message-fcc-handler-function 'rmail-output
113   "*A function called to save outgoing articles.
114 This function will be called with the name of the file to store the
115 article in.  The default function is `rmail-output' which saves in Unix
116 mailbox format."
117   :type '(radio (function-item rmail-output)
118                 (function :tag "Other"))
119   :group 'message-sending)
120
121 (defcustom message-courtesy-message
122   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
123   "*This is inserted at the start of a mailed copy of a posted message.
124 If the string contains the format spec \"%s\", the Newsgroups
125 the article has been posted to will be inserted there.
126 If this variable is nil, no such courtesy message will be added."
127   :group 'message-sending
128   :type 'string)
129
130 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
131   "*Regexp that matches headers to be removed in resent bounced mail."
132   :group 'message-interface
133   :type 'regexp)
134
135 ;;;###autoload
136 (defcustom message-from-style 'default
137   "*Specifies how \"From\" headers look.
138
139 If `nil', they contain just the return address like:
140         king@grassland.com
141 If `parens', they look like:
142         king@grassland.com (Elvis Parsley)
143 If `angles', they look like:
144         Elvis Parsley <king@grassland.com>
145
146 Otherwise, most addresses look like `angles', but they look like
147 `parens' if `angles' would need quoting and `parens' would not."
148   :type '(choice (const :tag "simple" nil)
149                  (const parens)
150                  (const angles)
151                  (const default))
152   :group 'message-headers)
153
154 (defcustom message-syntax-checks nil
155   ;; Guess this one shouldn't be easy to customize...
156   "Controls what syntax checks should not be performed on outgoing posts.
157 To disable checking of long signatures, for instance, add
158  `(signature . disabled)' to this list.
159
160 Don't touch this variable unless you really know what you're doing.
161
162 Checks include subject-cmsg multiple-headers sendsys message-id from
163 long-lines control-chars size new-text redirected-followup signature
164 approved sender empty empty-headers message-id from subject
165 shorten-followup-to existing-newsgroups."
166   :group 'message-news)
167
168 (defcustom message-required-news-headers
169   '(From Newsgroups Subject Date Message-ID 
170          (optional . Organization) Lines 
171          (optional . X-Newsreader))
172   "Headers to be generated or prompted for when posting an article.
173 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
174 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
175 X-Newsreader are optional.  If don't you want message to insert some
176 header, remove it from this list."
177   :group 'message-news
178   :group 'message-headers
179   :type '(repeat sexp))
180
181 (defcustom message-required-mail-headers 
182   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
183          (optional . X-Mailer))
184   "Headers to be generated or prompted for when mailing a message.
185 RFC822 required that From, Date, To, Subject and Message-ID be
186 included.  Organization, Lines and X-Mailer are optional."
187   :group 'message-mail
188   :group 'message-headers
189   :type '(repeat sexp))
190
191 (defcustom message-deletable-headers '(Message-ID Date Lines)
192   "Headers to be deleted if they already exist and were generated by message previously."
193   :group 'message-headers
194   :type 'sexp)
195
196 (defcustom message-ignored-news-headers 
197   "^NNTP-Posting-Host:\\|^Xref:\\|^Bcc:\\|^Gcc:\\|^Fcc:\\|^Resent-Fcc:"
198   "*Regexp of headers to be removed unconditionally before posting."
199   :group 'message-news
200   :group 'message-headers
201   :type 'regexp)
202
203 (defcustom message-ignored-mail-headers "^Gcc:\\|^Fcc:\\|^Resent-Fcc:"
204   "*Regexp of headers to be removed unconditionally before mailing."
205   :group 'message-mail
206   :group 'message-headers
207   :type 'regexp)
208
209 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|Return-Path:\\|^Supersedes:"
210   "*Header lines matching this regexp will be deleted before posting.
211 It's best to delete old Path and Date headers before posting to avoid
212 any confusion."
213   :group 'message-interface
214   :type 'regexp)
215
216 ;;;###autoload
217 (defcustom message-signature-separator "^-- *$"
218   "Regexp matching the signature separator."
219   :type 'regexp
220   :group 'message-various)
221
222 (defcustom message-interactive nil 
223   "Non-nil means when sending a message wait for and display errors.
224 nil means let mailer mail back a message to report errors."
225   :group 'message-sending
226   :group 'message-mail
227   :type 'boolean)
228
229 (defcustom message-generate-new-buffers t
230   "*Non-nil means that a new message buffer will be created whenever `mail-setup' is called.
231 If this is a function, call that function with three parameters:  The type,
232 the to address and the group name.  (Any of these may be nil.)  The function
233 should return the new buffer name."
234   :group 'message-buffers
235   :type '(choice (const :tag "off" nil)
236                  (const :tag "on" t)
237                  (function fun)))
238
239 (defcustom message-kill-buffer-on-exit nil
240   "*Non-nil means that the message buffer will be killed after sending a message."
241   :group 'message-buffers
242   :type 'boolean)
243
244 (defvar gnus-local-organization)
245 (defcustom message-user-organization 
246   (or (and (boundp 'gnus-local-organization)
247            gnus-local-organization)
248       (getenv "ORGANIZATION")
249       t)
250   "*String to be used as an Organization header.
251 If t, use `message-user-organization-file'."
252   :group 'message-headers
253   :type '(choice string
254                  (const :tag "consult file" t)))
255
256 ;;;###autoload
257 (defcustom message-user-organization-file "/usr/lib/news/organization"
258   "*Local news organization file."
259   :type 'file
260   :group 'message-headers)
261
262 (defcustom message-autosave-directory "~/"
263   ; (concat (file-name-as-directory message-directory) "drafts/")
264   "*Directory where message autosaves buffers.
265 If nil, message won't autosave."
266   :group 'message-buffers
267   :type 'directory)
268
269 (defcustom message-forward-start-separator 
270   "------- Start of forwarded message -------\n"
271   "*Delimiter inserted before forwarded messages."
272   :group 'message-forwarding
273   :type 'string)
274
275 (defcustom message-forward-end-separator
276   "------- End of forwarded message -------\n"
277   "*Delimiter inserted after forwarded messages."
278   :group 'message-forwarding
279   :type 'string)
280
281 (defcustom message-signature-before-forwarded-message t
282   "*If non-nil, put the signature before any included forwarded message."
283   :group 'message-forwarding
284   :type 'boolean)
285
286 (defcustom message-included-forward-headers 
287   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^Followup-To:\\|^Reply-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Mail-Copies-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:"
288   "*Regexp matching headers to be included in forwarded messages."
289   :group 'message-forwarding
290   :type 'regexp)
291
292 (defcustom message-ignored-resent-headers "^Return-receipt"
293   "*All headers that match this regexp will be deleted when resending a message."
294   :group 'message-interface
295   :type 'regexp)
296
297 (defcustom message-ignored-cited-headers "."
298   "*Delete these headers from the messages you yank."
299   :group 'message-insertion
300   :type 'regexp)
301
302 (defcustom message-cancel-message "I am canceling my own article."
303   "Message to be inserted in the cancel message."
304   :group 'message-interface
305   :type 'string)
306
307 ;; Useful to set in site-init.el
308 ;;;###autoload
309 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
310   "Function to call to send the current buffer as mail.
311 The headers should be delimited by a line whose contents match the
312 variable `mail-header-separator'.
313
314 Legal values include `message-send-mail-with-sendmail' (the default),
315 `message-send-mail-with-mh' and `message-send-mail-with-qmail'."
316   :type '(radio (function-item message-send-mail-with-sendmail)
317                 (function-item message-send-mail-with-mh)
318                 (function-item message-send-mail-with-qmail)
319                 (function :tag "Other"))
320   :group 'message-sending
321   :group 'message-mail)
322
323 (defcustom message-send-news-function 'message-send-news
324   "Function to call to send the current buffer as news.
325 The headers should be delimited by a line whose contents match the
326 variable `mail-header-separator'."
327   :group 'message-sending
328   :group 'message-news
329   :type 'function)
330
331 (defcustom message-reply-to-function nil
332   "Function that should return a list of headers.
333 This function should pick out addresses from the To, Cc, and From headers
334 and respond with new To and Cc headers."
335   :group 'message-interface
336   :type 'function)
337
338 (defcustom message-wide-reply-to-function nil
339   "Function that should return a list of headers.
340 This function should pick out addresses from the To, Cc, and From headers
341 and respond with new To and Cc headers."
342   :group 'message-interface
343   :type 'function)
344
345 (defcustom message-followup-to-function nil
346   "Function that should return a list of headers.
347 This function should pick out addresses from the To, Cc, and From headers
348 and respond with new To and Cc headers."
349   :group 'message-interface
350   :type 'function)
351
352 (defcustom message-use-followup-to 'ask
353   "*Specifies what to do with Followup-To header.
354 If nil, ignore the header.  If it is t, use its value, but query before
355 using the \"poster\" value.  If it is the symbol `ask', query the user
356 whether to ignore the \"poster\" value.  If it is the symbol `use',
357 always use the value."
358   :group 'message-interface
359   :type '(choice (const :tag "ignore" nil)
360                  (const use)
361                  (const ask)))
362
363 ;; qmail-related stuff
364 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
365   "Location of the qmail-inject program."
366   :group 'message-sending
367   :type 'file)
368
369 (defcustom message-qmail-inject-args nil
370   "Arguments passed to qmail-inject programs.
371 This should be a list of strings, one string for each argument.
372
373 For e.g., if you wish to set the envelope sender address so that bounces
374 go to the right place or to deal with listserv's usage of that address, you
375 might set this variable to '(\"-f\" \"you@some.where\")."
376   :group 'message-sending
377   :type '(repeat string))
378
379 (defvar gnus-post-method)
380 (defvar gnus-select-method)
381 (defcustom message-post-method 
382   (cond ((and (boundp 'gnus-post-method)
383               gnus-post-method)
384          gnus-post-method)
385         ((boundp 'gnus-select-method)
386          gnus-select-method)
387         (t '(nnspool "")))
388   "Method used to post news."
389   :group 'message-news
390   :group 'mesage-sending
391   ;; This should be the `gnus-select-method' widget, but that might
392   ;; create a dependence to `gnus.el'.
393   :type 'sexp)
394
395 (defcustom message-generate-headers-first nil
396   "*If non-nil, generate all possible headers before composing."
397   :group 'message-headers
398   :type 'boolean)
399
400 (defcustom message-setup-hook nil
401   "Normal hook, run each time a new outgoing message is initialized.
402 The function `message-setup' runs this hook."
403   :group 'message-various
404   :type 'hook)
405
406 (defcustom message-signature-setup-hook nil
407   "Normal hook, run each time a new outgoing message is initialized.
408 It is run after the headers have been inserted and before 
409 the signature is inserted."
410   :group 'message-various
411   :type 'hook)
412
413 (defcustom message-mode-hook nil
414   "Hook run in message mode buffers."
415   :group 'message-various
416   :type 'hook)
417
418 (defcustom message-header-hook nil
419   "Hook run in a message mode buffer narrowed to the headers."
420   :group 'message-various
421   :type 'hook)
422
423 (defcustom message-header-setup-hook nil
424   "Hook called narrowed to the headers when setting up a message
425 buffer."
426   :group 'message-various
427   :type 'hook)
428
429 ;;;###autoload
430 (defcustom message-citation-line-function 'message-insert-citation-line
431   "*Function called to insert the \"Whomever writes:\" line."
432   :type 'function
433   :group 'message-insertion)
434
435 ;;;###autoload
436 (defcustom message-yank-prefix "> "
437   "*Prefix inserted on the lines of yanked messages.
438 nil means use indentation."
439   :type 'string
440   :group 'message-insertion)
441
442 (defcustom message-indentation-spaces 3
443   "*Number of spaces to insert at the beginning of each cited line.
444 Used by `message-yank-original' via `message-yank-cite'."
445   :group 'message-insertion
446   :type 'integer)
447
448 ;;;###autoload
449 (defcustom message-cite-function
450   (if (and (boundp 'mail-citation-hook)
451            mail-citation-hook)
452       mail-citation-hook
453     'message-cite-original)
454   "*Function for citing an original message."
455   :type '(radio (function-item message-cite-original)
456                 (function-item sc-cite-original)
457                 (function :tag "Other"))
458   :group 'message-insertion)
459
460 ;;;###autoload
461 (defcustom message-indent-citation-function 'message-indent-citation
462   "*Function for modifying a citation just inserted in the mail buffer.
463 This can also be a list of functions.  Each function can find the
464 citation between (point) and (mark t).  And each function should leave
465 point and mark around the citation text as modified."
466   :type 'function
467   :group 'message-insertion)
468
469 (defvar message-abbrevs-loaded nil)
470
471 ;;;###autoload
472 (defcustom message-signature t
473   "*String to be inserted at the end of the message buffer.
474 If t, the `message-signature-file' file will be inserted instead.
475 If a function, the result from the function will be used instead.
476 If a form, the result from the form will be used instead."
477   :type 'sexp
478   :group 'message-insertion)
479
480 ;;;###autoload
481 (defcustom message-signature-file "~/.signature"
482   "*File containing the text inserted at end of message buffer."
483   :type 'file
484   :group 'message-insertion)
485
486 (defcustom message-distribution-function nil
487   "*Function called to return a Distribution header."
488   :group 'message-news
489   :group 'message-headers
490   :type 'function)
491
492 (defcustom message-expires 14
493   "Number of days before your article expires."
494   :group 'message-news
495   :group 'message-headers
496   :link '(custom-manual "(message)News Headers")
497   :type 'integer)
498
499 (defcustom message-user-path nil
500   "If nil, use the NNTP server name in the Path header.
501 If stringp, use this; if non-nil, use no host name (user name only)."
502   :group 'message-news
503   :group 'message-headers
504   :link '(custom-manual "(message)News Headers")
505   :type '(choice (const :tag "nntp" nil)
506                  (string :tag "name")
507                  (sexp :tag "none" :format "%t" t)))
508
509 (defvar message-reply-buffer nil)
510 (defvar message-reply-headers nil)
511 (defvar message-newsreader nil)
512 (defvar message-mailer nil)
513 (defvar message-sent-message-via nil)
514 (defvar message-checksum nil)
515 (defvar message-send-actions nil
516   "A list of actions to be performed upon successful sending of a message.")
517 (defvar message-exit-actions nil
518   "A list of actions to be performed upon exiting after sending a message.")
519 (defvar message-kill-actions nil
520   "A list of actions to be performed before killing a message buffer.")
521 (defvar message-postpone-actions nil
522   "A list of actions to be performed after postponing a message.")
523
524 (defcustom message-default-headers ""
525   "*A string containing header lines to be inserted in outgoing messages.
526 It is inserted before you edit the message, so you can edit or delete
527 these lines."
528   :group 'message-headers
529   :type 'string)
530
531 (defcustom message-default-mail-headers ""
532   "*A string of header lines to be inserted in outgoing mails."
533   :group 'message-headers
534   :group 'message-mail
535   :type 'string)
536
537 (defcustom message-default-news-headers ""
538   "*A string of header lines to be inserted in outgoing news
539 articles."
540   :group 'message-headers
541   :group 'message-news
542   :type 'string)
543
544 ;; Note: could use /usr/ucb/mail instead of sendmail;
545 ;; options -t, and -v if not interactive.
546 (defcustom message-mailer-swallows-blank-line
547   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)" 
548                          system-configuration)
549            (file-readable-p "/etc/sendmail.cf")
550            (let ((buffer (get-buffer-create " *temp*")))
551              (unwind-protect
552                  (save-excursion
553                    (set-buffer buffer)
554                    (insert-file-contents "/etc/sendmail.cf")
555                    (goto-char (point-min))
556                    (let ((case-fold-search nil))
557                      (re-search-forward "^OR\\>" nil t)))
558                (kill-buffer buffer))))
559       ;; According to RFC822, "The field-name must be composed of printable
560       ;; ASCII characters (i. e., characters that have decimal values between
561       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
562       ;; space, or colon.
563       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
564   "Set this non-nil if the system's mailer runs the header and body together.
565 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
566 The value should be an expression to test whether the problem will
567 actually occur."
568   :group 'message-sending
569   :type 'sexp)
570
571 (ignore-errors
572   (define-mail-user-agent 'message-user-agent
573     'message-mail 'message-send-and-exit 
574     'message-kill-buffer 'message-send-hook))
575
576 ;;; Internal variables.
577 ;;; Well, not really internal.
578
579 (defvar message-mode-syntax-table 
580   (let ((table (copy-syntax-table text-mode-syntax-table)))
581     (modify-syntax-entry ?% ". " table)
582     table)
583   "Syntax table used while in Message mode.")
584
585 (defvar message-mode-abbrev-table text-mode-abbrev-table
586   "Abbrev table used in Message mode buffers.
587 Defaults to `text-mode-abbrev-table'.")
588
589 (defvar message-font-lock-keywords
590   (let* ((cite-prefix "A-Za-z") (cite-suffix (concat cite-prefix "0-9_.@-")))
591     (list '("^To:" . font-lock-function-name-face)
592           '("^[GBF]?[Cc][Cc]:\\|^Reply-To:" . font-lock-keyword-face)
593           '("^\\(Subject:\\)[ \t]*\\(.+\\)?"
594             (1 font-lock-comment-face) (2 font-lock-type-face nil t))
595           (list (concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
596                 1 'font-lock-comment-face)
597           (cons (concat "^[ \t]*"
598                         "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
599                         "[>|}].*")
600                 'font-lock-reference-face)
601           '("^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):.*"
602             . font-lock-string-face)))
603   "Additional expressions to highlight in Message mode.")
604
605 (defvar message-face-alist
606   '((bold . bold-region)
607     (underline . underline-region)
608     (default . (lambda (b e) 
609                  (unbold-region b e)
610                  (ununderline-region b e))))
611   "Alist of mail and news faces for facemenu.
612 The cdr of ech entry is a function for applying the face to a region.")
613
614 (defcustom message-send-hook nil
615   "Hook run before sending messages."
616   :group 'message-various
617   :options '(ispell-message)
618   :type 'hook)
619
620 (defcustom message-send-mail-hook nil
621   "Hook run before sending mail messages."
622   :group 'message-various
623   :type 'hook)
624
625 (defcustom message-send-news-hook nil
626   "Hook run before sending news messages."
627   :group 'message-various
628   :type 'hook)
629
630 (defcustom message-sent-hook nil
631   "Hook run after sending messages."
632   :group 'message-various
633   :type 'hook)
634
635 ;;; Internal variables.
636
637 (defvar message-buffer-list nil)
638
639 ;; Byte-compiler warning
640 (defvar gnus-active-hashtb)
641
642 ;;; Regexp matching the delimiter of messages in UNIX mail format
643 ;;; (UNIX From lines), minus the initial ^.  
644 (defvar message-unix-mail-delimiter
645   (let ((time-zone-regexp
646          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
647                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
648                  "\\|"
649                  "\\) *")))
650     (concat
651      "From "
652
653      ;; Username, perhaps with a quoted section that can contain spaces.
654      "\\("
655      "[^ \n]*"
656      "\\(\\|\".*\"[^ \n]*\\)"
657      "\\|<[^<>\n]+>"
658      "\\)  ?"
659
660      ;; The time the message was sent.
661      "\\([^ \n]*\\) *"                  ; day of the week
662      "\\([^ ]*\\) *"                    ; month
663      "\\([0-9]*\\) *"                   ; day of month
664      "\\([0-9:]*\\) *"                  ; time of day
665
666      ;; Perhaps a time zone, specified by an abbreviation, or by a
667      ;; numeric offset.
668      time-zone-regexp
669
670      ;; The year.
671      " [0-9][0-9]\\([0-9]*\\) *"
672
673      ;; On some systems the time zone can appear after the year, too.
674      time-zone-regexp
675
676      ;; Old uucp cruft.
677      "\\(remote from .*\\)?"
678
679      "\n")))
680
681 (defvar message-unsent-separator
682   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
683           "^ *---+ +Returned message +---+ *$\\|"
684           "^Start of returned message$\\|"
685           "^ *---+ +Original message +---+ *$\\|"
686           "^ *--+ +begin message +--+ *$\\|"
687           "^ *---+ +Original message follows +---+ *$\\|"
688           "^|? *---+ +Message text follows: +---+ *|?$")
689   "A regexp that matches the separator before the text of a failed message.")
690
691 (defvar message-header-format-alist 
692   `((Newsgroups)
693     (To . message-fill-address) 
694     (Cc . message-fill-address)
695     (Subject)
696     (In-Reply-To)
697     (Fcc)
698     (Bcc)
699     (Date)
700     (Organization)
701     (Distribution)
702     (Lines)
703     (Expires)
704     (Message-ID)
705     (References)
706     (X-Mailer)
707     (X-Newsreader))
708   "Alist used for formatting headers.")
709
710 (eval-and-compile
711   (autoload 'message-setup-toolbar "messagexmas")
712   (autoload 'mh-send-letter "mh-comp"))
713
714 \f
715
716 ;;; 
717 ;;; Utility functions.
718 ;;;
719
720 (defun message-point-at-bol ()
721   "Return point at the beginning of the line."
722   (let ((p (point)))
723     (beginning-of-line)
724     (prog1
725         (point)
726       (goto-char p))))
727
728 (defun message-point-at-eol ()
729   "Return point at the end of the line."
730   (let ((p (point)))
731     (end-of-line)
732     (prog1
733         (point)
734       (goto-char p))))
735
736 (defmacro message-y-or-n-p (question show &rest text)
737   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
738   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
739
740 ;; Delete the current line (and the next N lines.);
741 (defmacro message-delete-line (&optional n)
742   `(delete-region (progn (beginning-of-line) (point))
743                   (progn (forward-line ,(or n 1)) (point))))
744
745 (defun message-tokenize-header (header &optional separator)
746   "Split HEADER into a list of header elements.
747 \",\" is used as the separator."
748   (if (not header)
749       nil
750     (let ((regexp (format "[%s]+" (or separator ",")))
751           (beg 1)
752           (first t)
753           quoted elems paren)
754       (save-excursion
755         (message-set-work-buffer)
756         (insert header)
757         (goto-char (point-min))
758         (while (not (eobp))
759           (if first
760               (setq first nil)
761             (forward-char 1))
762           (cond ((and (> (point) beg)
763                       (or (eobp)
764                           (and (looking-at regexp)
765                                (not quoted)
766                                (not paren))))
767                  (push (buffer-substring beg (point)) elems)
768                  (setq beg (match-end 0)))
769                 ((= (following-char) ?\")
770                  (setq quoted (not quoted)))
771                 ((and (= (following-char) ?\()
772                       (not quoted))
773                  (setq paren t))
774                 ((and (= (following-char) ?\))
775                       (not quoted))
776                  (setq paren nil))))
777         (nreverse elems)))))
778
779 (defun message-fetch-field (header)
780   "The same as `mail-fetch-field', only remove all newlines."
781   (let ((value (mail-fetch-field header)))
782     (when value
783       (nnheader-replace-chars-in-string value ?\n ? ))))
784
785 (defun message-fetch-reply-field (header)
786   "Fetch FIELD from the message we're replying to."
787   (when (and message-reply-buffer
788              (buffer-name message-reply-buffer))
789     (save-excursion
790       (set-buffer message-reply-buffer)
791       (message-fetch-field header))))
792
793 (defun message-set-work-buffer ()
794   (if (get-buffer " *message work*")
795       (progn
796         (set-buffer " *message work*")
797         (erase-buffer))
798     (set-buffer (get-buffer-create " *message work*"))
799     (kill-all-local-variables)
800     (buffer-disable-undo (current-buffer))))
801
802 (defun message-functionp (form)
803   "Return non-nil if FORM is funcallable."
804   (or (and (symbolp form) (fboundp form))
805       (and (listp form) (eq (car form) 'lambda))))
806
807 (defun message-strip-subject-re (subject)
808   "Remove \"Re:\" from subject lines."
809   (if (string-match "^[Rr][Ee]: *" subject)
810       (substring subject (match-end 0))
811     subject))
812
813 (defun message-remove-header (header &optional is-regexp first reverse)
814   "Remove HEADER in the narrowed buffer.
815 If REGEXP, HEADER is a regular expression.
816 If FIRST, only remove the first instance of the header.
817 Return the number of headers removed."
818   (goto-char (point-min))
819   (let ((regexp (if is-regexp header (concat "^" header ":")))
820         (number 0)
821         (case-fold-search t)
822         last)
823     (while (and (not (eobp))
824                 (not last))
825       (if (if reverse
826               (not (looking-at regexp))
827             (looking-at regexp))
828           (progn
829             (incf number)
830             (when first
831               (setq last t))
832             (delete-region
833              (point)
834              ;; There might be a continuation header, so we have to search
835              ;; until we find a new non-continuation line.
836              (progn
837                (forward-line 1)
838                (if (re-search-forward "^[^ \t]" nil t)
839                    (goto-char (match-beginning 0))
840                  (point-max)))))
841         (forward-line 1)
842         (if (re-search-forward "^[^ \t]" nil t)
843             (goto-char (match-beginning 0))
844           (point-max))))
845     number))
846
847 (defun message-narrow-to-headers ()
848   "Narrow the buffer to the head of the message."
849   (widen)
850   (narrow-to-region
851    (goto-char (point-min))
852    (if (re-search-forward
853         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
854        (match-beginning 0)
855      (point-max)))
856   (goto-char (point-min)))
857
858 (defun message-narrow-to-head ()
859   "Narrow the buffer to the head of the message."
860   (widen)
861   (narrow-to-region
862    (goto-char (point-min))
863    (if (search-forward "\n\n" nil 1)
864        (1- (point))
865      (point-max)))
866   (goto-char (point-min)))
867
868 (defun message-news-p ()
869   "Say whether the current buffer contains a news message."
870   (save-excursion
871     (save-restriction
872       (message-narrow-to-headers)
873       (message-fetch-field "newsgroups"))))
874
875 (defun message-mail-p ()
876   "Say whether the current buffer contains a mail message."
877   (save-excursion
878     (save-restriction
879       (message-narrow-to-headers)
880       (or (message-fetch-field "to")
881           (message-fetch-field "cc")
882           (message-fetch-field "bcc")))))
883
884 (defun message-next-header ()
885   "Go to the beginning of the next header."
886   (beginning-of-line)
887   (or (eobp) (forward-char 1))
888   (not (if (re-search-forward "^[^ \t]" nil t)
889            (beginning-of-line)
890          (goto-char (point-max)))))
891     
892 (defun message-sort-headers-1 ()
893   "Sort the buffer as headers using `message-rank' text props."
894   (goto-char (point-min))
895   (sort-subr 
896    nil 'message-next-header 
897    (lambda ()
898      (message-next-header)
899      (unless (bobp)
900        (forward-char -1)))
901    (lambda ()
902      (or (get-text-property (point) 'message-rank)
903          10000))))
904
905 (defun message-sort-headers ()
906   "Sort the headers of the current message according to `message-header-format-alist'."
907   (interactive)
908   (save-excursion
909     (save-restriction
910       (let ((max (1+ (length message-header-format-alist)))
911             rank)
912         (message-narrow-to-headers)
913         (while (re-search-forward "^[^ \n]+:" nil t)
914           (put-text-property
915            (match-beginning 0) (1+ (match-beginning 0))
916            'message-rank
917            (if (setq rank (length (memq (assq (intern (buffer-substring
918                                                        (match-beginning 0)
919                                                        (1- (match-end 0))))
920                                               message-header-format-alist)
921                                         message-header-format-alist)))
922                (- max rank)
923              (1+ max)))))
924       (message-sort-headers-1))))
925
926 \f
927
928 ;;;
929 ;;; Message mode
930 ;;;
931
932 ;;; Set up keymap.
933
934 (defvar message-mode-map nil)
935
936 (unless message-mode-map
937   (setq message-mode-map (copy-keymap text-mode-map))
938   (define-key message-mode-map "\C-c?" 'describe-mode)
939
940   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
941   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
942   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
943   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
944   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
945   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
946   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
947   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
948   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
949   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
950   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
951   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
952   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
953
954   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
955   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
956   
957   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
958   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
959   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
960   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
961   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
962   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
963
964   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
965   (define-key message-mode-map "\C-c\C-s" 'message-send)
966   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
967   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
968
969   (define-key message-mode-map "\t" 'message-tab))
970
971 (easy-menu-define 
972  message-mode-menu message-mode-map "Message Menu."
973  '("Message"
974    ["Sort Headers" message-sort-headers t]
975    ["Yank Original" message-yank-original t]
976    ["Fill Yanked Message" message-fill-yanked-message t]
977    ["Insert Signature" message-insert-signature t]
978    ["Caesar (rot13) Message" message-caesar-buffer-body t]
979    ["Caesar (rot13) Region" message-caesar-region t]
980    ["Rename buffer" message-rename-buffer t]
981    ["Spellcheck" ispell-message t]
982    "----"
983    ["Send Message" message-send-and-exit t]
984    ["Abort Message" message-dont-send t]))
985
986 (easy-menu-define 
987  message-mode-field-menu message-mode-map ""
988  '("Field"
989    ["Fetch To" message-insert-to t]
990    ["Fetch Newsgroups" message-insert-newsgroups t]
991    "----"
992    ["To" message-goto-to t]
993    ["Subject" message-goto-subject t]
994    ["Cc" message-goto-cc t]
995    ["Reply-To" message-goto-reply-to t]
996    ["Summary" message-goto-summary t]
997    ["Keywords" message-goto-keywords t]
998    ["Newsgroups" message-goto-newsgroups t]
999    ["Followup-To" message-goto-followup-to t]
1000    ["Distribution" message-goto-distribution t]
1001    ["Body" message-goto-body t]
1002    ["Signature" message-goto-signature t]))
1003
1004 (defvar facemenu-add-face-function)
1005 (defvar facemenu-remove-face-function)
1006
1007 ;;;###autoload
1008 (defun message-mode ()
1009   "Major mode for editing mail and news to be sent.
1010 Like Text Mode but with these additional commands:
1011 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1012 C-c C-f  move to a header field (and create it if there isn't):
1013          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1014          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1015          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1016          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1017          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1018          C-c C-f C-f  move to Followup-To
1019 C-c C-t  message-insert-to (add a To header to a news followup)
1020 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1021 C-c C-b  message-goto-body (move to beginning of message text).
1022 C-c C-i  message-goto-signature (move to the beginning of the signature).
1023 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1024 C-c C-y  message-yank-original (insert current message, if any).
1025 C-c C-q  message-fill-yanked-message (fill what was yanked).
1026 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1027   (interactive)
1028   (kill-all-local-variables)
1029   (make-local-variable 'message-reply-buffer)
1030   (setq message-reply-buffer nil)
1031   (make-local-variable 'message-send-actions)
1032   (make-local-variable 'message-exit-actions)
1033   (make-local-variable 'message-kill-actions)
1034   (make-local-variable 'message-postpone-actions)
1035   (set-syntax-table message-mode-syntax-table)
1036   (use-local-map message-mode-map)
1037   (setq local-abbrev-table message-mode-abbrev-table)
1038   (setq major-mode 'message-mode)
1039   (setq mode-name "Message")
1040   (setq buffer-offer-save t)
1041   (make-local-variable 'font-lock-defaults)
1042   (setq font-lock-defaults '(message-font-lock-keywords t))
1043   (make-local-variable 'facemenu-add-face-function)
1044   (make-local-variable 'facemenu-remove-face-function)
1045   (setq facemenu-add-face-function
1046         (lambda (face end)
1047           (let ((face-fun (cdr (assq face message-face-alist))))
1048             (if face-fun
1049                 (funcall face-fun (point) end)
1050               (error "Face %s not configured for %s mode" face mode-name)))
1051           "")
1052         facemenu-remove-face-function t)
1053   (make-local-variable 'paragraph-separate)
1054   (make-local-variable 'paragraph-start)
1055   (setq paragraph-start (concat (regexp-quote mail-header-separator)
1056                                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
1057                                 "-- $\\|"
1058                                 paragraph-start))
1059   (setq paragraph-separate (concat (regexp-quote mail-header-separator)
1060                                    "$\\|[ \t]*[-_][-_][-_]+$\\|"
1061                                    "-- $\\|"
1062                                    paragraph-separate))
1063   (make-local-variable 'message-reply-headers)
1064   (setq message-reply-headers nil)
1065   (make-local-variable 'message-newsreader)
1066   (make-local-variable 'message-mailer)
1067   (make-local-variable 'message-post-method)
1068   (make-local-variable 'message-sent-message-via)
1069   (setq message-sent-message-via nil)
1070   (make-local-variable 'message-checksum)
1071   (setq message-checksum nil)
1072   ;;(when (fboundp 'mail-hist-define-keys)
1073   ;;  (mail-hist-define-keys))
1074   (when (string-match "XEmacs\\|Lucid" emacs-version)
1075     (message-setup-toolbar))
1076   (easy-menu-add message-mode-menu message-mode-map)
1077   ;; Allow mail alias things.
1078   (if (fboundp 'mail-abbrevs-setup)
1079       (mail-abbrevs-setup)
1080     (funcall (intern "mail-aliases-setup")))
1081   (run-hooks 'text-mode-hook 'message-mode-hook))
1082
1083 \f
1084
1085 ;;;
1086 ;;; Message mode commands
1087 ;;;
1088
1089 ;;; Movement commands
1090
1091 (defun message-goto-to ()
1092   "Move point to the To header."
1093   (interactive)
1094   (message-position-on-field "To"))
1095
1096 (defun message-goto-subject ()
1097   "Move point to the Subject header."
1098   (interactive)
1099   (message-position-on-field "Subject"))
1100
1101 (defun message-goto-cc ()
1102   "Move point to the Cc header."
1103   (interactive)
1104   (message-position-on-field "Cc" "To"))
1105
1106 (defun message-goto-bcc ()
1107   "Move point to the Bcc  header."
1108   (interactive)
1109   (message-position-on-field "Bcc" "Cc" "To"))
1110
1111 (defun message-goto-fcc ()
1112   "Move point to the Fcc header."
1113   (interactive)
1114   (message-position-on-field "Fcc" "To" "Newsgroups"))
1115
1116 (defun message-goto-reply-to ()
1117   "Move point to the Reply-To header."
1118   (interactive)
1119   (message-position-on-field "Reply-To" "Subject"))
1120
1121 (defun message-goto-newsgroups ()
1122   "Move point to the Newsgroups header."
1123   (interactive)
1124   (message-position-on-field "Newsgroups"))
1125
1126 (defun message-goto-distribution ()
1127   "Move point to the Distribution header."
1128   (interactive)
1129   (message-position-on-field "Distribution"))
1130
1131 (defun message-goto-followup-to ()
1132   "Move point to the Followup-To header."
1133   (interactive)
1134   (message-position-on-field "Followup-To" "Newsgroups"))
1135
1136 (defun message-goto-keywords ()
1137   "Move point to the Keywords header."
1138   (interactive)
1139   (message-position-on-field "Keywords" "Subject"))
1140
1141 (defun message-goto-summary ()
1142   "Move point to the Summary header."
1143   (interactive)
1144   (message-position-on-field "Summary" "Subject"))
1145
1146 (defun message-goto-body ()
1147   "Move point to the beginning of the message body."
1148   (interactive)
1149   (if (looking-at "[ \t]*\n") (expand-abbrev))
1150   (goto-char (point-min))
1151   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1152
1153 (defun message-goto-signature ()
1154   "Move point to the beginning of the message signature."
1155   (interactive)
1156   (goto-char (point-min))
1157   (if (re-search-forward message-signature-separator nil t)
1158       (forward-line 1)
1159     (goto-char (point-max))))
1160
1161 \f
1162
1163 (defun message-insert-to ()
1164   "Insert a To header that points to the author of the article being replied to."
1165   (interactive)
1166   (let ((co (message-fetch-field "courtesy-copies-to")))
1167     (when (and co 
1168                (equal (downcase co) "never"))
1169       (error "The user has requested not to have copies sent via mail")))
1170   (when (and (message-position-on-field "To")
1171              (mail-fetch-field "to")
1172              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1173     (insert ", "))
1174   (insert (or (message-fetch-reply-field "reply-to")
1175               (message-fetch-reply-field "from") "")))
1176
1177 (defun message-insert-newsgroups ()
1178   "Insert the Newsgroups header from the article being replied to."
1179   (interactive)
1180   (when (and (message-position-on-field "Newsgroups")
1181              (mail-fetch-field "newsgroups")
1182              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1183     (insert ","))
1184   (insert (or (message-fetch-reply-field "newsgroups") "")))
1185
1186 \f
1187
1188 ;;; Various commands
1189
1190 (defun message-insert-signature (&optional force)
1191   "Insert a signature.  See documentation for the `message-signature' variable."
1192   (interactive (list 0))
1193   (let* ((signature 
1194           (cond
1195            ((and (null message-signature)
1196                  (eq force 0))
1197             (save-excursion
1198               (goto-char (point-max))
1199               (not (re-search-backward
1200                     message-signature-separator nil t))))
1201            ((and (null message-signature)
1202                  force)
1203             t)
1204            ((message-functionp message-signature)
1205             (funcall message-signature))
1206            ((listp message-signature)
1207             (eval message-signature))
1208            (t message-signature)))
1209          (signature
1210           (cond ((stringp signature)
1211                  signature)
1212                 ((and (eq t signature)
1213                       message-signature-file
1214                       (file-exists-p message-signature-file))
1215                  signature))))
1216     (when signature
1217       (goto-char (point-max))
1218       ;; Insert the signature.
1219       (unless (bolp)
1220         (insert "\n"))
1221       (insert "\n-- \n")
1222       (if (eq signature t)
1223           (insert-file-contents message-signature-file)
1224         (insert signature))
1225       (goto-char (point-max))
1226       (or (bolp) (insert "\n")))))
1227
1228 (defvar message-caesar-translation-table nil)
1229
1230 (defun message-caesar-region (b e &optional n)
1231   "Caesar rotation of region by N, default 13, for decrypting netnews."
1232   (interactive
1233    (list
1234     (min (point) (or (mark t) (point)))
1235     (max (point) (or (mark t) (point)))
1236     (when current-prefix-arg
1237       (prefix-numeric-value current-prefix-arg))))
1238
1239   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1240   (unless (or (zerop n)                 ; no action needed for a rot of 0
1241               (= b e))                  ; no region to rotate
1242     ;; We build the table, if necessary.
1243     (when (or (not message-caesar-translation-table)
1244               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1245       (let ((i -1) 
1246             (table (make-string 256 0)))
1247         (while (< (incf i) 256)
1248           (aset table i i))
1249         (setq table
1250               (concat
1251                (substring table 0 ?A)
1252                (substring table (+ ?A n) (+ ?A n (- 26 n)))
1253                (substring table ?A (+ ?A n))
1254                (substring table (+ ?A 26) ?a)
1255                (substring table (+ ?a n) (+ ?a n (- 26 n)))
1256                (substring table ?a (+ ?a n))
1257                (substring table (+ ?a 26) 255)))
1258         (setq message-caesar-translation-table table)))
1259     ;; Then we translate the region.  Do it this way to retain 
1260     ;; text properties.
1261     (while (< b e)
1262       (subst-char-in-region 
1263        b (1+ b) (char-after b)
1264        (aref message-caesar-translation-table (char-after b)))
1265       (incf b))))
1266
1267 (defun message-caesar-buffer-body (&optional rotnum)
1268   "Caesar rotates all letters in the current buffer by 13 places.
1269 Used to encode/decode possibly offensive messages (commonly in net.jokes).
1270 With prefix arg, specifies the number of places to rotate each letter forward.
1271 Mail and USENET news headers are not rotated."
1272   (interactive (if current-prefix-arg
1273                    (list (prefix-numeric-value current-prefix-arg))
1274                  (list nil)))
1275   (save-excursion
1276     (save-restriction
1277       (when (message-goto-body)
1278         (narrow-to-region (point) (point-max)))
1279       (message-caesar-region (point-min) (point-max) rotnum))))
1280
1281 (defun message-rename-buffer (&optional enter-string)
1282   "Rename the *message* buffer to \"*message* RECIPIENT\".  
1283 If the function is run with a prefix, it will ask for a new buffer
1284 name, rather than giving an automatic name."
1285   (interactive "Pbuffer name: ")
1286   (save-excursion
1287     (save-restriction
1288       (goto-char (point-min))
1289       (narrow-to-region (point) 
1290                         (search-forward mail-header-separator nil 'end))
1291       (let* ((mail-to (if (message-news-p) (message-fetch-field "Newsgroups")
1292                         (message-fetch-field "To")))
1293              (mail-trimmed-to
1294               (if (string-match "," mail-to)
1295                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1296                 mail-to))
1297              (name-default (concat "*message* " mail-trimmed-to))
1298              (name (if enter-string
1299                        (read-string "New buffer name: " name-default)
1300                      name-default))
1301              (default-directory
1302                (file-name-as-directory message-autosave-directory)))
1303         (rename-buffer name t)))))
1304
1305 (defun message-fill-yanked-message (&optional justifyp)
1306   "Fill the paragraphs of a message yanked into this one.
1307 Numeric argument means justify as well."
1308   (interactive "P")
1309   (save-excursion
1310     (goto-char (point-min))
1311     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1312     (let ((fill-prefix message-yank-prefix))
1313       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1314
1315 (defun message-indent-citation ()
1316   "Modify text just inserted from a message to be cited.
1317 The inserted text should be the region.
1318 When this function returns, the region is again around the modified text.
1319
1320 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1321 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1322   (let ((start (point)))
1323     ;; Remove unwanted headers.
1324     (when message-ignored-cited-headers
1325       (save-restriction
1326         (narrow-to-region 
1327          (goto-char start)
1328          (if (search-forward "\n\n" nil t)
1329              (1- (point))
1330            (point)))
1331         (message-remove-header message-ignored-cited-headers t)
1332         (goto-char (point-max))))
1333     ;; Delete blank lines at the start of the buffer.
1334     (while (and (point-min)
1335                 (eolp)
1336                 (not (eobp)))
1337       (message-delete-line))
1338     ;; Delete blank lines at the end of the buffer.
1339     (goto-char (point-max))
1340     (unless (eolp)
1341       (insert "\n"))
1342     (while (and (zerop (forward-line -1))
1343                 (looking-at "$"))
1344       (message-delete-line))
1345     ;; Do the indentation.
1346     (if (null message-yank-prefix)
1347         (indent-rigidly start (mark t) message-indentation-spaces)
1348       (save-excursion
1349         (goto-char start)
1350         (while (< (point) (mark t))
1351           (insert message-yank-prefix)
1352           (forward-line 1)))
1353       (goto-char start))))
1354
1355 (defun message-yank-original (&optional arg)
1356   "Insert the message being replied to, if any.
1357 Puts point before the text and mark after.
1358 Normally indents each nonblank line ARG spaces (default 3).  However,
1359 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1360
1361 This function uses `message-cite-function' to do the actual citing.
1362
1363 Just \\[universal-argument] as argument means don't indent, insert no
1364 prefix, and don't delete any headers."
1365   (interactive "P")
1366   (let ((modified (buffer-modified-p)))
1367     (when (and message-reply-buffer
1368                message-cite-function)
1369       (delete-windows-on message-reply-buffer t)
1370       (insert-buffer message-reply-buffer)
1371       (funcall message-cite-function)
1372       (message-exchange-point-and-mark)
1373       (unless (bolp)
1374         (insert ?\n))
1375       (unless modified
1376         (setq message-checksum (cons (message-checksum) (buffer-size)))))))
1377
1378 (defun message-cite-original ()
1379   "Cite function in the standard Message manner."
1380   (let ((start (point))
1381         (functions 
1382          (when message-indent-citation-function
1383            (if (listp message-indent-citation-function)
1384                message-indent-citation-function
1385              (list message-indent-citation-function)))))
1386     (goto-char start)
1387     (while functions
1388       (funcall (pop functions)))
1389     (when message-citation-line-function
1390       (unless (bolp)
1391         (insert "\n"))
1392       (funcall message-citation-line-function))))
1393
1394 (defun message-insert-citation-line ()
1395   "Function that inserts a simple citation line."
1396   (when message-reply-headers
1397     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1398
1399 (defun message-position-on-field (header &rest afters)
1400   (let ((case-fold-search t))
1401     (save-restriction
1402       (narrow-to-region
1403        (goto-char (point-min))
1404        (progn
1405          (re-search-forward 
1406           (concat "^" (regexp-quote mail-header-separator) "$"))
1407          (match-beginning 0)))
1408       (goto-char (point-min))
1409       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1410           (progn
1411             (re-search-forward "^[^ \t]" nil 'move)
1412             (beginning-of-line)
1413             (skip-chars-backward "\n")
1414             t)
1415         (while (and afters
1416                     (not (re-search-forward 
1417                           (concat "^" (regexp-quote (car afters)) ":")
1418                           nil t)))
1419           (pop afters))
1420         (when afters
1421           (re-search-forward "^[^ \t]" nil 'move)
1422           (beginning-of-line))
1423         (insert header ": \n")
1424         (forward-char -1)
1425         nil))))
1426
1427 (defun message-remove-signature ()
1428   "Remove the signature from the text between point and mark.
1429 The text will also be indented the normal way."
1430   (save-excursion
1431     (let ((start (point))
1432           mark)
1433       (if (not (re-search-forward message-signature-separator (mark t) t))
1434           ;; No signature here, so we just indent the cited text.
1435           (message-indent-citation)
1436         ;; Find the last non-empty line.
1437         (forward-line -1)
1438         (while (looking-at "[ \t]*$")
1439           (forward-line -1))
1440         (forward-line 1)
1441         (setq mark (set-marker (make-marker) (point)))
1442         (goto-char start)
1443         (message-indent-citation)
1444         ;; Enable undoing the deletion.
1445         (undo-boundary)
1446         (delete-region mark (mark t))
1447         (set-marker mark nil)))))
1448
1449 \f
1450
1451 ;;;
1452 ;;; Sending messages
1453 ;;;
1454
1455 (defun message-send-and-exit (&optional arg)
1456   "Send message like `message-send', then, if no errors, exit from mail buffer."
1457   (interactive "P")
1458   (let ((buf (current-buffer))
1459         (actions message-exit-actions))
1460     (when (and (message-send arg)
1461                (buffer-name buf))
1462       (if message-kill-buffer-on-exit
1463           (kill-buffer buf)
1464         (bury-buffer buf)
1465         (when (eq buf (current-buffer))
1466           (message-bury buf)))
1467       (message-do-actions actions))))
1468
1469 (defun message-dont-send ()
1470   "Don't send the message you have been editing."
1471   (interactive)
1472   (let ((actions message-postpone-actions))
1473     (message-bury (current-buffer))
1474     (message-do-actions actions)))
1475
1476 (defun message-kill-buffer ()
1477   "Kill the current buffer."
1478   (interactive)
1479   (let ((actions message-kill-actions))
1480     (kill-buffer (current-buffer))
1481     (message-do-actions actions)))
1482
1483 (defun message-bury (buffer)
1484   "Bury this mail buffer."
1485   (let ((newbuf (other-buffer buffer)))
1486     (bury-buffer buffer)
1487     (if (and (fboundp 'frame-parameters)
1488              (cdr (assq 'dedicated (frame-parameters)))
1489              (not (null (delq (selected-frame) (visible-frame-list)))))
1490         (delete-frame (selected-frame))
1491       (switch-to-buffer newbuf))))
1492
1493 (defun message-send (&optional arg)
1494   "Send the message in the current buffer.
1495 If `message-interactive' is non-nil, wait for success indication
1496 or error messages, and inform user.
1497 Otherwise any failure is reported in a message back to
1498 the user from the mailer."
1499   (interactive "P")
1500   (when (if buffer-file-name
1501             (y-or-n-p (format "Send buffer contents as %s message? "
1502                               (if (message-mail-p)
1503                                   (if (message-news-p) "mail and news" "mail")
1504                                 "news")))
1505           (or (buffer-modified-p)
1506               (y-or-n-p "No changes in the buffer; really send? ")))
1507     ;; Make it possible to undo the coming changes.
1508     (undo-boundary)
1509     (let ((inhibit-read-only t))
1510       (put-text-property (point-min) (point-max) 'read-only nil))
1511     (message-fix-before-sending)
1512     (run-hooks 'message-send-hook)
1513     (message "Sending...")
1514     (when (and (or (not (message-news-p))
1515                    (and (or (not (memq 'news message-sent-message-via))
1516                             (y-or-n-p
1517                              "Already sent message via news; resend? "))
1518                         (funcall message-send-news-function arg)))
1519                (or (not (message-mail-p))
1520                    (and (or (not (memq 'mail message-sent-message-via))
1521                             (y-or-n-p
1522                              "Already sent message via mail; resend? "))
1523                         (message-send-mail arg))))
1524       (message-do-fcc)
1525       ;;(when (fboundp 'mail-hist-put-headers-into-history)
1526       ;; (mail-hist-put-headers-into-history))
1527       (run-hooks 'message-sent-hook)
1528       (message "Sending...done")
1529       ;; If buffer has no file, mark it as unmodified and delete autosave.
1530       (unless buffer-file-name
1531         (set-buffer-modified-p nil)
1532         (delete-auto-save-file-if-necessary t))
1533       ;; Delete other mail buffers and stuff.
1534       (message-do-send-housekeeping)
1535       (message-do-actions message-send-actions)
1536       ;; Return success.
1537       t)))
1538
1539 (defun message-fix-before-sending ()
1540   "Do various things to make the message nice before sending it."
1541   ;; Make sure there's a newline at the end of the message.
1542   (goto-char (point-max))
1543   (unless (bolp)
1544     (insert "\n")))
1545
1546 (defun message-add-action (action &rest types)
1547   "Add ACTION to be performed when doing an exit of type TYPES."
1548   (let (var)
1549     (while types
1550       (set (setq var (intern (format "message-%s-actions" (pop types))))
1551            (nconc (symbol-value var) (list action))))))
1552
1553 (defun message-do-actions (actions)
1554   "Perform all actions in ACTIONS."
1555   ;; Now perform actions on successful sending.
1556   (while actions
1557     (ignore-errors
1558       (cond 
1559        ;; A simple function.
1560        ((message-functionp (car actions))
1561         (funcall (car actions)))
1562        ;; Something to be evaled.
1563        (t
1564         (eval (car actions)))))
1565     (pop actions)))
1566
1567 (defun message-send-mail (&optional arg)
1568   (require 'mail-utils)
1569   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
1570         (case-fold-search nil)
1571         (news (message-news-p))
1572         (mailbuf (current-buffer)))
1573     (save-restriction
1574       (message-narrow-to-headers)
1575       ;; Insert some headers.
1576       (let ((message-deletable-headers
1577              (if news nil message-deletable-headers)))
1578         (message-generate-headers message-required-mail-headers))
1579       ;; Let the user do all of the above.
1580       (run-hooks 'message-header-hook))
1581     (unwind-protect
1582         (save-excursion
1583           (set-buffer tembuf)
1584           (erase-buffer)
1585           ;; Avoid copying text props.
1586           (insert (format 
1587                    "%s" (save-excursion
1588                           (set-buffer mailbuf)
1589                           (buffer-string))))
1590           ;; Remove some headers.
1591           (save-restriction
1592             (message-narrow-to-headers)
1593             ;; Remove some headers.
1594             (message-remove-header message-ignored-mail-headers t))
1595           (goto-char (point-max))
1596           ;; require one newline at the end.
1597           (or (= (preceding-char) ?\n)
1598               (insert ?\n))
1599           (when (and news
1600                      (or (message-fetch-field "cc")
1601                          (message-fetch-field "to")))
1602             (message-insert-courtesy-copy))
1603           (funcall message-send-mail-function))
1604       (kill-buffer tembuf))
1605     (set-buffer mailbuf)
1606     (push 'mail message-sent-message-via)))
1607
1608 (defun message-send-mail-with-sendmail ()
1609   "Send off the prepared buffer with sendmail."
1610   (let ((errbuf (if message-interactive
1611                     (generate-new-buffer " sendmail errors")
1612                   0))
1613         resend-to-addresses delimline)
1614     (let ((case-fold-search t))
1615       (save-restriction
1616         (message-narrow-to-headers)
1617         (setq resend-to-addresses (message-fetch-field "resent-to")))
1618       ;; Change header-delimiter to be what sendmail expects.
1619       (goto-char (point-min))
1620       (re-search-forward
1621        (concat "^" (regexp-quote mail-header-separator) "\n"))
1622       (replace-match "\n")
1623       (backward-char 1)
1624       (setq delimline (point-marker))
1625       (run-hooks 'message-send-mail-hook)
1626       ;; Insert an extra newline if we need it to work around
1627       ;; Sun's bug that swallows newlines.
1628       (goto-char (1+ delimline))
1629       (when (eval message-mailer-swallows-blank-line)
1630         (newline))
1631       (when message-interactive
1632         (save-excursion
1633           (set-buffer errbuf)
1634           (erase-buffer))))
1635     (let ((default-directory "/"))
1636       (apply 'call-process-region
1637              (append (list (point-min) (point-max)
1638                            (if (boundp 'sendmail-program)
1639                                sendmail-program
1640                              "/usr/lib/sendmail")
1641                            nil errbuf nil "-oi")
1642                      ;; Always specify who from,
1643                      ;; since some systems have broken sendmails.
1644                      (list "-f" (user-login-name))
1645                      ;; These mean "report errors by mail"
1646                      ;; and "deliver in background".
1647                      (if (null message-interactive) '("-oem" "-odb"))
1648                      ;; Get the addresses from the message
1649                      ;; unless this is a resend.
1650                      ;; We must not do that for a resend
1651                      ;; because we would find the original addresses.
1652                      ;; For a resend, include the specific addresses.
1653                      (if resend-to-addresses
1654                          (list resend-to-addresses)
1655                        '("-t")))))
1656     (when message-interactive
1657       (save-excursion
1658         (set-buffer errbuf)
1659         (goto-char (point-min))
1660         (while (re-search-forward "\n\n* *" nil t)
1661           (replace-match "; "))
1662         (if (not (zerop (buffer-size)))
1663             (error "Sending...failed to %s"
1664                    (buffer-substring (point-min) (point-max)))))
1665       (when (bufferp errbuf)
1666         (kill-buffer errbuf)))))
1667
1668 (defun message-send-mail-with-qmail ()
1669   "Pass the prepared message buffer to qmail-inject.
1670 Refer to the documentation for the variable `message-send-mail-function'
1671 to find out how to use this."
1672   ;; replace the header delimiter with a blank line
1673   (goto-char (point-min))
1674   (re-search-forward
1675    (concat "^" (regexp-quote mail-header-separator) "\n"))
1676   (replace-match "\n")
1677   (run-hooks 'message-send-mail-hook)
1678   ;; send the message
1679   (case
1680       (apply
1681        'call-process-region 1 (point-max) message-qmail-inject-program
1682        nil nil nil
1683        ;; qmail-inject's default behaviour is to look for addresses on the
1684        ;; command line; if there're none, it scans the headers.
1685        ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
1686        ;;
1687        ;; in general, ALL of qmail-inject's defaults are perfect for simply
1688        ;; reading a formatted (i. e., at least a To: or Resent-To header)
1689        ;; message from stdin.
1690        ;;
1691        ;; qmail also has the advantage of not having been raped by
1692        ;; various vendors, so we don't have to allow for that, either --
1693        ;; compare this with message-send-mail-with-sendmail and weep 
1694        ;; for sendmail's lost innocence.
1695        ;;
1696        ;; all this is way cool coz it lets us keep the arguments entirely
1697        ;; free for -inject-arguments -- a big win for the user and for us
1698        ;; since we don't have to play that double-guessing game and the user
1699        ;; gets full control (no gestapo'ish -f's, for instance).  --sj
1700        message-qmail-inject-args)
1701     ;; qmail-inject doesn't say anything on it's stdout/stderr,
1702     ;; we have to look at the retval instead
1703     (0 nil)
1704     (1   (error "qmail-inject reported permanent failure."))
1705     (111 (error "qmail-inject reported transient failure."))
1706     ;; should never happen
1707     (t   (error "qmail-inject reported unknown failure."))))
1708
1709 (defun message-send-mail-with-mh ()
1710   "Send the prepared message buffer with mh."
1711   (let ((mh-previous-window-config nil)
1712         (name (make-temp-name
1713                (concat (file-name-as-directory message-autosave-directory)
1714                        "msg."))))
1715     (setq buffer-file-name name)
1716     ;; MH wants to generate these headers itself.
1717     (let ((headers message-deletable-headers))
1718       (while headers
1719         (goto-char (point-min)) 
1720         ;;(message "Deleting header %s" (car headers)) (sit-for 5)
1721         (and (re-search-forward 
1722               (concat "^" (symbol-name (car headers)) ": *") nil t)
1723              (message-delete-line))
1724         (pop headers)))
1725     (run-hooks 'message-send-mail-hook)
1726     ;; Pass it on to mh.
1727     (mh-send-letter)))
1728
1729 (defun message-send-news (&optional arg)
1730   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
1731         (case-fold-search nil)
1732         (method (if (message-functionp message-post-method)
1733                     (funcall message-post-method arg)
1734                   message-post-method))
1735         (messbuf (current-buffer))
1736         (message-syntax-checks
1737          (if arg
1738              (cons '(existing-newsgroups . disabled)
1739                    message-syntax-checks)
1740            message-syntax-checks))
1741         result)
1742     (save-restriction
1743       (message-narrow-to-headers)
1744       ;; Insert some headers.
1745       (message-generate-headers message-required-news-headers)
1746       ;; Let the user do all of the above.
1747       (run-hooks 'message-header-hook))
1748     (message-cleanup-headers)
1749     (if (not (message-check-news-syntax))
1750         (progn
1751           ;;(message "Posting not performed")
1752           nil)
1753       (unwind-protect
1754           (save-excursion
1755             (set-buffer tembuf)
1756             (buffer-disable-undo (current-buffer))
1757             (erase-buffer) 
1758             ;; Avoid copying text props.
1759             (insert (format 
1760                      "%s" (save-excursion
1761                             (set-buffer messbuf)
1762                             (buffer-string))))
1763             ;; Remove some headers.
1764             (save-restriction
1765               (message-narrow-to-headers)
1766               ;; Remove some headers.
1767               (message-remove-header message-ignored-news-headers t))
1768             (goto-char (point-max))
1769             ;; require one newline at the end.
1770             (or (= (preceding-char) ?\n)
1771                 (insert ?\n))
1772             (let ((case-fold-search t))
1773               ;; Remove the delimiter.
1774               (goto-char (point-min))
1775               (re-search-forward
1776                (concat "^" (regexp-quote mail-header-separator) "\n"))
1777               (replace-match "\n")
1778               (backward-char 1))
1779             (run-hooks 'message-send-news-hook)
1780             (require (car method))
1781             (funcall (intern (format "%s-open-server" (car method)))
1782                      (cadr method) (cddr method))
1783             (setq result
1784                   (funcall (intern (format "%s-request-post" (car method))))))
1785         (kill-buffer tembuf))
1786       (set-buffer messbuf)
1787       (if result
1788           (push 'news message-sent-message-via)
1789         (message "Couldn't send message via news: %s"
1790                  (nnheader-get-report (car method)))
1791         nil))))
1792
1793 ;;;
1794 ;;; Header generation & syntax checking.
1795 ;;;
1796
1797 (defmacro message-check (type &rest forms)
1798   "Eval FORMS if TYPE is to be checked."
1799   `(or (message-check-element ,type)
1800        (save-excursion
1801          ,@forms)))
1802
1803 (put 'message-check 'lisp-indent-function 1)
1804 (put 'message-check 'edebug-form-spec '(form body))
1805
1806 (defun message-check-element (type)
1807   "Returns non-nil if this type is not to be checked."
1808   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
1809       t
1810     (let ((able (assq type message-syntax-checks)))
1811       (and (consp able)
1812            (eq (cdr able) 'disabled)))))
1813
1814 (defun message-check-news-syntax ()
1815   "Check the syntax of the message."
1816   (save-excursion
1817     (save-restriction
1818       (widen)
1819       (and 
1820        ;; We narrow to the headers and check them first.
1821        (save-excursion
1822          (save-restriction
1823            (message-narrow-to-headers)
1824            (message-check-news-header-syntax)))
1825        ;; Check the body.
1826        (message-check-news-body-syntax)))))
1827
1828 (defun message-check-news-header-syntax ()
1829   (and 
1830    ;; Check for commands in Subject.
1831    (message-check 'subject-cmsg
1832      (if (string-match "^cmsg " (message-fetch-field "subject"))
1833          (y-or-n-p
1834           "The control code \"cmsg\" is in the subject.  Really post? ")
1835        t))
1836    ;; Check for multiple identical headers.
1837    (message-check 'multiple-headers
1838      (let (found)
1839        (while (and (not found) 
1840                    (re-search-forward "^[^ \t:]+: " nil t))
1841          (save-excursion
1842            (or (re-search-forward 
1843                 (concat "^" 
1844                         (regexp-quote
1845                          (setq found
1846                                (buffer-substring
1847                                 (match-beginning 0) (- (match-end 0) 2))))
1848                         ":")
1849                 nil t)
1850                (setq found nil))))
1851        (if found
1852            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
1853          t)))
1854    ;; Check for Version and Sendsys.
1855    (message-check 'sendsys
1856      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
1857          (y-or-n-p
1858           (format "The article contains a %s command.  Really post? "
1859                   (buffer-substring (match-beginning 0) 
1860                                     (1- (match-end 0)))))
1861        t))
1862    ;; See whether we can shorten Followup-To.
1863    (message-check 'shorten-followup-to
1864      (let ((newsgroups (message-fetch-field "newsgroups"))
1865            (followup-to (message-fetch-field "followup-to"))
1866            to)
1867        (when (and newsgroups
1868                   (string-match "," newsgroups)
1869                   (not followup-to)
1870                   (not
1871                    (zerop
1872                     (length
1873                      (setq to (completing-read 
1874                                "Followups to: (default all groups) " 
1875                                (mapcar (lambda (g) (list g))
1876                                        (cons "poster" 
1877                                              (message-tokenize-header 
1878                                               newsgroups)))))))))
1879          (goto-char (point-min))
1880          (insert "Followup-To: " to "\n"))
1881        t))
1882    ;; Check "Shoot me".
1883    (message-check 'shoot
1884      (if (re-search-forward
1885           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
1886          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
1887        t))
1888    ;; Check for Approved.
1889    (message-check 'approved
1890      (if (re-search-forward "^Approved:" nil t)
1891          (y-or-n-p "The article contains an Approved header.  Really post? ")
1892        t))
1893    ;; Check the Message-ID header.
1894    (message-check 'message-id
1895      (let* ((case-fold-search t)
1896             (message-id (message-fetch-field "message-id")))
1897        (or (not message-id)
1898            (and (string-match "@" message-id)
1899                 (string-match "@[^\\.]*\\." message-id))
1900            (y-or-n-p
1901             (format "The Message-ID looks strange: \"%s\".  Really post? "
1902                     message-id)))))
1903    ;; Check the Subject header.
1904    (message-check 'subject
1905      (let* ((case-fold-search t)
1906             (subject (message-fetch-field "subject")))
1907        (or
1908         (and subject
1909              (not (string-match "\\`[ \t]*\\'" subject)))
1910         (ignore
1911          (message 
1912           "The subject field is empty or missing.  Posting is denied.")))))
1913    ;; Check the Newsgroups & Followup-To headers.
1914    (message-check 'existing-newsgroups
1915      (let* ((case-fold-search t)
1916             (newsgroups (message-fetch-field "newsgroups"))
1917             (followup-to (message-fetch-field "followup-to"))
1918             (groups (message-tokenize-header
1919                      (if followup-to
1920                          (concat newsgroups "," followup-to)
1921                        newsgroups)))
1922             (hashtb (and (boundp 'gnus-active-hashtb)
1923                          gnus-active-hashtb))
1924             errors)
1925        (if (not hashtb)
1926            t
1927          (while groups
1928            (when (and (not (boundp (intern (car groups) hashtb)))
1929                       (not (equal (car groups) "poster")))
1930              (push (car groups) errors))
1931            (pop groups))
1932          (if (not errors)
1933              t
1934            (y-or-n-p
1935             (format
1936              "Really post to %s unknown group%s: %s "
1937              (if (= (length errors) 1) "this" "these")
1938              (if (= (length errors) 1) "" "s")
1939              (mapconcat 'identity errors ", ")))))))
1940    ;; Check the Newsgroups & Followup-To headers for syntax errors.
1941    (message-check 'valid-newsgroups
1942      (let ((case-fold-search t)
1943            (headers '("Newsgroups" "Followup-To"))
1944            header error)
1945        (while (and headers (not error))
1946          (when (setq header (mail-fetch-field (car headers)))
1947            (if (or
1948                 (not 
1949                  (string-match
1950                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
1951                   header))
1952                 (memq 
1953                  nil (mapcar 
1954                       (lambda (g)
1955                         (not (string-match "\\.\\'\\|\\.\\." g)))
1956                       (message-tokenize-header header ","))))
1957                (setq error t)))
1958          (unless error
1959            (pop headers)))
1960        (if (not error)
1961            t
1962          (y-or-n-p
1963           (format "The %s header looks odd: \"%s\".  Really post? "
1964                   (car headers) header)))))
1965    ;; Check the From header.
1966    (message-check 'from
1967      (let* ((case-fold-search t)
1968             (from (message-fetch-field "from"))
1969             (ad (nth 1 (mail-extract-address-components from))))
1970        (cond
1971         ((not from)
1972          (message "There is no From line.  Posting is denied.")
1973          nil)
1974         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
1975              (string-match "\\.\\." ad) ;larsi@ifi..uio
1976              (string-match "@\\." ad)   ;larsi@.ifi.uio
1977              (string-match "\\.$" ad)   ;larsi@ifi.uio.
1978              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
1979              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
1980          (message
1981           "Denied posting -- the From looks strange: \"%s\"." from)
1982          nil)
1983         (t t))))))
1984
1985 (defun message-check-news-body-syntax ()
1986   (and
1987    ;; Check for long lines.
1988    (message-check 'long-lines
1989      (goto-char (point-min))
1990      (re-search-forward
1991       (concat "^" (regexp-quote mail-header-separator) "$"))
1992      (while (and
1993              (progn
1994                (end-of-line)
1995                (< (current-column) 80))
1996              (zerop (forward-line 1))))
1997      (or (bolp)
1998          (eobp)
1999          (y-or-n-p
2000           "You have lines longer than 79 characters.  Really post? ")))
2001    ;; Check whether the article is empty.
2002    (message-check 'empty
2003      (goto-char (point-min))
2004      (re-search-forward
2005       (concat "^" (regexp-quote mail-header-separator) "$"))
2006      (forward-line 1)
2007      (let ((b (point)))
2008        (goto-char (point-max))
2009        (re-search-backward message-signature-separator nil t)
2010        (beginning-of-line)
2011        (or (re-search-backward "[^ \n\t]" b t)
2012            (y-or-n-p "Empty article.  Really post? "))))
2013    ;; Check for control characters.
2014    (message-check 'control-chars
2015      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2016          (y-or-n-p 
2017           "The article contains control characters.  Really post? ")
2018        t))
2019    ;; Check excessive size.
2020    (message-check 'size
2021      (if (> (buffer-size) 60000)
2022          (y-or-n-p
2023           (format "The article is %d octets long.  Really post? "
2024                   (buffer-size)))
2025        t))
2026    ;; Check whether any new text has been added.
2027    (message-check 'new-text
2028      (or
2029       (not message-checksum)
2030       (not (and (eq (message-checksum) (car message-checksum))
2031                 (eq (buffer-size) (cdr message-checksum))))
2032       (y-or-n-p
2033        "It looks like no new text has been added.  Really post? ")))
2034    ;; Check the length of the signature.
2035    (message-check 'signature
2036      (goto-char (point-max))
2037      (if (or (not (re-search-backward message-signature-separator nil t))
2038              (search-forward message-forward-end-separator nil t))
2039          t
2040        (if (> (count-lines (point) (point-max)) 5)
2041            (y-or-n-p
2042             (format
2043              "Your .sig is %d lines; it should be max 4.  Really post? "
2044              (1- (count-lines (point) (point-max)))))
2045          t)))))
2046
2047 (defun message-checksum ()
2048   "Return a \"checksum\" for the current buffer."
2049   (let ((sum 0))
2050     (save-excursion
2051       (goto-char (point-min))
2052       (re-search-forward
2053        (concat "^" (regexp-quote mail-header-separator) "$"))
2054       (while (not (eobp))
2055         (when (not (looking-at "[ \t\n]"))
2056           (setq sum (logxor (ash sum 1) (following-char))))
2057         (forward-char 1)))
2058     sum))
2059
2060 (defun message-do-fcc ()
2061   "Process Fcc headers in the current buffer."
2062   (let ((case-fold-search t)
2063         (buf (current-buffer))
2064         list file)
2065     (save-excursion
2066       (set-buffer (get-buffer-create " *message temp*"))
2067       (buffer-disable-undo (current-buffer))
2068       (erase-buffer)
2069       (insert-buffer-substring buf)
2070       (save-restriction
2071         (message-narrow-to-headers)
2072         (while (setq file (message-fetch-field "fcc"))
2073           (push file list)
2074           (message-remove-header "fcc" nil t)))
2075       (goto-char (point-min))
2076       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2077       (replace-match "" t t)
2078       ;; Process FCC operations.
2079       (while list
2080         (setq file (pop list))
2081         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2082             ;; Pipe the article to the program in question.
2083             (call-process-region (point-min) (point-max) shell-file-name
2084                                  nil nil nil shell-command-switch
2085                                  (match-string 1 file))
2086           ;; Save the article.
2087           (setq file (expand-file-name file))
2088           (unless (file-exists-p (file-name-directory file))
2089             (make-directory (file-name-directory file) t))
2090           (if (and message-fcc-handler-function
2091                    (not (eq message-fcc-handler-function 'rmail-output)))
2092               (funcall message-fcc-handler-function file)
2093             (if (and (file-readable-p file) (mail-file-babyl-p file))
2094                 (rmail-output file 1 nil t)
2095               (let ((mail-use-rfc822 t))
2096                 (rmail-output file 1 t t))))))
2097       (kill-buffer (current-buffer)))))
2098
2099 (defun message-cleanup-headers ()
2100   "Do various automatic cleanups of the headers."
2101   ;; Remove empty lines in the header.
2102   (save-restriction
2103     (message-narrow-to-headers)
2104     (while (re-search-forward "^[ \t]*\n" nil t)
2105       (replace-match "" t t)))
2106
2107   ;; Correct Newsgroups and Followup-To headers: change sequence of
2108   ;; spaces to comma and eliminate spaces around commas.  Eliminate
2109   ;; embedded line breaks.
2110   (goto-char (point-min))
2111   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2112     (save-restriction
2113       (narrow-to-region
2114        (point)
2115        (if (re-search-forward "^[^ \t]" nil t)
2116            (match-beginning 0)
2117          (forward-line 1)
2118          (point)))
2119       (goto-char (point-min))
2120       (while (re-search-forward "\n[ \t]+" nil t)
2121         (replace-match " " t t))        ;No line breaks (too confusing)
2122       (goto-char (point-min))
2123       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2124         (replace-match "," t t))
2125       (goto-char (point-min))
2126       ;; Remove trailing commas.
2127       (when (re-search-forward ",+$" nil t)
2128         (replace-match "" t t)))))
2129
2130 (defun message-make-date ()
2131   "Make a valid data header."
2132   (let ((now (current-time)))
2133     (timezone-make-date-arpa-standard 
2134      (current-time-string now) (current-time-zone now))))
2135
2136 (defun message-make-message-id ()
2137   "Make a unique Message-ID."
2138   (concat "<" (message-unique-id) 
2139           (let ((psubject (save-excursion (message-fetch-field "subject"))))
2140             (if (and message-reply-headers
2141                      (mail-header-references message-reply-headers)
2142                      (mail-header-subject message-reply-headers)
2143                      psubject
2144                      (mail-header-subject message-reply-headers)
2145                      (not (string= 
2146                            (message-strip-subject-re
2147                             (mail-header-subject message-reply-headers))
2148                            (message-strip-subject-re psubject))))
2149                 "_-_" ""))
2150           "@" (message-make-fqdn) ">"))
2151
2152 (defvar message-unique-id-char nil)
2153
2154 ;; If you ever change this function, make sure the new version
2155 ;; cannot generate IDs that the old version could.
2156 ;; You might for example insert a "." somewhere (not next to another dot
2157 ;; or string boundary), or modify the "fsf" string.
2158 (defun message-unique-id ()
2159   ;; Don't use microseconds from (current-time), they may be unsupported.
2160   ;; Instead we use this randomly inited counter.
2161   (setq message-unique-id-char
2162         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2163            ;; (current-time) returns 16-bit ints,
2164            ;; and 2^16*25 just fits into 4 digits i base 36.
2165            (* 25 25)))
2166   (let ((tm (current-time)))
2167     (concat
2168      (if (memq system-type '(ms-dos emx vax-vms))
2169          (let ((user (downcase (user-login-name))))
2170            (while (string-match "[^a-z0-9_]" user)
2171              (aset user (match-beginning 0) ?_))
2172            user)
2173        (message-number-base36 (user-uid) -1))
2174      (message-number-base36 (+ (car   tm) 
2175                                (lsh (% message-unique-id-char 25) 16)) 4)
2176      (message-number-base36 (+ (nth 1 tm)
2177                                (lsh (/ message-unique-id-char 25) 16)) 4)
2178      ;; Append the newsreader name, because while the generated
2179      ;; ID is unique to this newsreader, other newsreaders might
2180      ;; otherwise generate the same ID via another algorithm.
2181      ".fsf")))
2182
2183 (defun message-number-base36 (num len)
2184   (if (if (< len 0) (<= num 0) (= len 0))
2185       ""
2186     (concat (message-number-base36 (/ num 36) (1- len))
2187             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2188                                   (% num 36))))))
2189
2190 (defun message-make-organization ()
2191   "Make an Organization header."
2192   (let* ((organization 
2193           (or (getenv "ORGANIZATION")
2194               (when message-user-organization
2195                 (if (message-functionp message-user-organization)
2196                     (funcall message-user-organization)
2197                   message-user-organization)))))
2198     (save-excursion
2199       (message-set-work-buffer)
2200       (cond ((stringp organization)
2201              (insert organization))
2202             ((and (eq t organization)
2203                   message-user-organization-file
2204                   (file-exists-p message-user-organization-file))
2205              (insert-file-contents message-user-organization-file)))
2206       (goto-char (point-min))
2207       (while (re-search-forward "[\t\n]+" nil t)
2208         (replace-match "" t t))
2209       (unless (zerop (buffer-size))
2210         (buffer-string)))))
2211
2212 (defun message-make-lines ()
2213   "Count the number of lines and return numeric string."
2214   (save-excursion
2215     (save-restriction
2216       (widen)
2217       (goto-char (point-min))
2218       (re-search-forward 
2219        (concat "^" (regexp-quote mail-header-separator) "$"))
2220       (forward-line 1)
2221       (int-to-string (count-lines (point) (point-max))))))
2222
2223 (defun message-make-in-reply-to ()
2224   "Return the In-Reply-To header for this message."
2225   (when message-reply-headers
2226     (let ((from (mail-header-from message-reply-headers))
2227           (date (mail-header-date message-reply-headers)))
2228       (when from
2229         (let ((stop-pos 
2230                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2231           (concat (if stop-pos (substring from 0 stop-pos) from)
2232                   "'s message of " 
2233                   (if (or (not date) (string= date ""))
2234                       "(unknown date)" date)))))))
2235
2236 (defun message-make-distribution ()
2237   "Make a Distribution header."
2238   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2239     (cond ((message-functionp message-distribution-function)
2240            (funcall message-distribution-function))
2241           (t orig-distribution))))
2242
2243 (defun message-make-expires ()
2244   "Return an Expires header based on `message-expires'."
2245   (let ((current (current-time))
2246         (future (* 1.0 message-expires 60 60 24)))
2247     ;; Add the future to current.
2248     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2249     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2250     ;; Return the date in the future in UT.
2251     (timezone-make-date-arpa-standard 
2252      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2253
2254 (defun message-make-path ()
2255   "Return uucp path."
2256   (let ((login-name (user-login-name)))
2257     (cond ((null message-user-path)
2258            (concat (system-name) "!" login-name))
2259           ((stringp message-user-path)
2260            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2261            (concat message-user-path "!" login-name))
2262           (t login-name))))
2263
2264 (defun message-make-from ()
2265   "Make a From header."
2266   (let* ((login (message-make-address))
2267          (fullname 
2268           (or (and (boundp 'user-full-name)
2269                    user-full-name)
2270               (user-full-name))))
2271     (when (string= fullname "&")
2272       (setq fullname (user-login-name)))
2273     (save-excursion
2274       (message-set-work-buffer)
2275       (cond 
2276        ((or (null message-from-style)
2277             (equal fullname ""))
2278         (insert login))
2279        ((or (eq message-from-style 'angles)
2280             (and (not (eq message-from-style 'parens))
2281                  ;; Use angles if no quoting is needed, or if parens would
2282                  ;; need quoting too.
2283                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2284                      (let ((tmp (concat fullname nil)))
2285                        (while (string-match "([^()]*)" tmp)
2286                          (aset tmp (match-beginning 0) ?-)
2287                          (aset tmp (1- (match-end 0)) ?-))
2288                        (string-match "[\\()]" tmp)))))
2289         (insert fullname)
2290         (goto-char (point-min))
2291         ;; Look for a character that cannot appear unquoted
2292         ;; according to RFC 822.
2293         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2294           ;; Quote fullname, escaping specials.
2295           (goto-char (point-min))
2296           (insert "\"")
2297           (while (re-search-forward "[\"\\]" nil 1)
2298             (replace-match "\\\\\\&" t))
2299           (insert "\""))
2300         (insert " <" login ">"))
2301        (t                               ; 'parens or default
2302         (insert login " (")
2303         (let ((fullname-start (point)))
2304           (insert fullname)
2305           (goto-char fullname-start)
2306           ;; RFC 822 says \ and nonmatching parentheses
2307           ;; must be escaped in comments.
2308           ;; Escape every instance of ()\ ...
2309           (while (re-search-forward "[()\\]" nil 1)
2310             (replace-match "\\\\\\&" t))
2311           ;; ... then undo escaping of matching parentheses,
2312           ;; including matching nested parentheses.
2313           (goto-char fullname-start)
2314           (while (re-search-forward 
2315                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2316                   nil 1)
2317             (replace-match "\\1(\\3)" t)
2318             (goto-char fullname-start)))
2319         (insert ")")))
2320       (buffer-string))))
2321
2322 (defun message-make-sender ()
2323   "Return the \"real\" user address.
2324 This function tries to ignore all user modifications, and 
2325 give as trustworthy answer as possible."
2326   (concat (user-login-name) "@" (system-name)))
2327
2328 (defun message-make-address ()
2329   "Make the address of the user."
2330   (or (message-user-mail-address)
2331       (concat (user-login-name) "@" (message-make-domain))))
2332
2333 (defun message-user-mail-address ()
2334   "Return the pertinent part of `user-mail-address'."
2335   (when user-mail-address
2336     (nth 1 (mail-extract-address-components user-mail-address))))
2337
2338 (defun message-make-fqdn ()
2339   "Return user's fully qualified domain name."
2340   (let ((system-name (system-name))
2341         (user-mail (message-user-mail-address)))
2342     (cond 
2343      ((string-match "[^.]\\.[^.]" system-name)
2344       ;; `system-name' returned the right result.
2345       system-name)
2346      ;; Try `mail-host-address'.
2347      ((and (boundp 'mail-host-address)
2348            (stringp mail-host-address)
2349            (string-match "\\." mail-host-address))
2350       mail-host-address)
2351      ;; We try `user-mail-address' as a backup.
2352      ((and (string-match "\\." user-mail)
2353            (string-match "@\\(.*\\)\\'" user-mail))
2354       (match-string 1 user-mail))
2355      ;; Default to this bogus thing.
2356      (t
2357       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2358
2359 (defun message-make-host-name ()
2360   "Return the name of the host."
2361   (let ((fqdn (message-make-fqdn)))
2362     (string-match "^[^.]+\\." fqdn)
2363     (substring fqdn 0 (1- (match-end 0)))))
2364
2365 (defun message-make-domain ()
2366   "Return the domain name."
2367   (or mail-host-address
2368       (message-make-fqdn)))
2369
2370 (defun message-generate-headers (headers)
2371   "Prepare article HEADERS.
2372 Headers already prepared in the buffer are not modified."
2373   (save-restriction
2374     (message-narrow-to-headers)
2375     (let* ((Date (message-make-date))
2376            (Message-ID (message-make-message-id))
2377            (Organization (message-make-organization))
2378            (From (message-make-from))
2379            (Path (message-make-path))
2380            (Subject nil)
2381            (Newsgroups nil)
2382            (In-Reply-To (message-make-in-reply-to))
2383            (To nil)
2384            (Distribution (message-make-distribution))
2385            (Lines (message-make-lines))
2386            (X-Newsreader message-newsreader)
2387            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2388                           message-mailer))
2389            (Expires (message-make-expires))
2390            (case-fold-search t)
2391            header value elem)
2392       ;; First we remove any old generated headers.
2393       (let ((headers message-deletable-headers))
2394         (while headers
2395           (goto-char (point-min))
2396           (and (re-search-forward 
2397                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2398                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2399                (message-delete-line))
2400           (pop headers)))
2401       ;; Go through all the required headers and see if they are in the
2402       ;; articles already.  If they are not, or are empty, they are
2403       ;; inserted automatically - except for Subject, Newsgroups and
2404       ;; Distribution. 
2405       (while headers
2406         (goto-char (point-min))
2407         (setq elem (pop headers))
2408         (if (consp elem)
2409             (if (eq (car elem) 'optional)
2410                 (setq header (cdr elem))
2411               (setq header (car elem)))
2412           (setq header elem))
2413         (when (or (not (re-search-forward 
2414                         (concat "^" (downcase (symbol-name header)) ":") 
2415                         nil t))
2416                   (progn
2417                     ;; The header was found.  We insert a space after the
2418                     ;; colon, if there is none.
2419                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2420                     ;; Find out whether the header is empty...
2421                     (looking-at "[ \t]*$")))
2422           ;; So we find out what value we should insert.
2423           (setq value
2424                 (cond 
2425                  ((and (consp elem) (eq (car elem) 'optional))
2426                   ;; This is an optional header.  If the cdr of this
2427                   ;; is something that is nil, then we do not insert
2428                   ;; this header.
2429                   (setq header (cdr elem))
2430                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2431                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2432                  ((consp elem)
2433                   ;; The element is a cons.  Either the cdr is a
2434                   ;; string to be inserted verbatim, or it is a
2435                   ;; function, and we insert the value returned from
2436                   ;; this function.
2437                   (or (and (stringp (cdr elem)) (cdr elem))
2438                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2439                  ((and (boundp header) (symbol-value header))
2440                   ;; The element is a symbol.  We insert the value
2441                   ;; of this symbol, if any.
2442                   (symbol-value header))
2443                  (t
2444                   ;; We couldn't generate a value for this header,
2445                   ;; so we just ask the user.
2446                   (read-from-minibuffer
2447                    (format "Empty header for %s; enter value: " header)))))
2448           ;; Finally insert the header.
2449           (when (and value 
2450                      (not (equal value "")))
2451             (save-excursion
2452               (if (bolp)
2453                   (progn
2454                     ;; This header didn't exist, so we insert it.
2455                     (goto-char (point-max))
2456                     (insert (symbol-name header) ": " value "\n")
2457                     (forward-line -1))
2458                 ;; The value of this header was empty, so we clear
2459                 ;; totally and insert the new value.
2460                 (delete-region (point) (message-point-at-eol))
2461                 (insert value))
2462               ;; Add the deletable property to the headers that require it.
2463               (and (memq header message-deletable-headers)
2464                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2465                    (add-text-properties 
2466                     (point) (match-end 0)
2467                     '(message-deletable t face italic) (current-buffer)))))))
2468       ;; Insert new Sender if the From is strange. 
2469       (let ((from (message-fetch-field "from"))
2470             (sender (message-fetch-field "sender"))
2471             (secure-sender (message-make-sender)))
2472         (when (and from 
2473                    (not (message-check-element 'sender))
2474                    (not (string=
2475                          (downcase
2476                           (cadr (mail-extract-address-components from)))
2477                          (downcase secure-sender)))
2478                    (or (null sender)
2479                        (not 
2480                         (string=
2481                          (downcase
2482                           (cadr (mail-extract-address-components sender)))
2483                          (downcase secure-sender)))))
2484           (goto-char (point-min))    
2485           ;; Rename any old Sender headers to Original-Sender.
2486           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2487             (beginning-of-line)
2488             (insert "Original-")
2489             (beginning-of-line))
2490           (insert "Sender: " secure-sender "\n"))))))
2491
2492 (defun message-insert-courtesy-copy ()
2493   "Insert a courtesy message in mail copies of combined messages."
2494   (let (newsgroups)
2495     (save-excursion
2496       (save-restriction
2497         (message-narrow-to-headers)
2498         (when (setq newsgroups (message-fetch-field "newsgroups"))
2499           (goto-char (point-max))
2500           (insert "Posted-To: " newsgroups "\n")))
2501       (forward-line 1)
2502       (when message-courtesy-message
2503         (cond
2504          ((string-match "%s" message-courtesy-message)
2505           (insert (format message-courtesy-message newsgroups)))
2506          (t
2507           (insert message-courtesy-message)))))))
2508     
2509 ;;;
2510 ;;; Setting up a message buffer
2511 ;;;
2512
2513 (defun message-fill-address (header value)
2514   (save-restriction
2515     (narrow-to-region (point) (point))
2516     (insert (capitalize (symbol-name header))
2517             ": "
2518             (if (consp value) (car value) value)
2519             "\n")
2520     (narrow-to-region (point-min) (1- (point-max)))
2521     (let (quoted last)
2522       (goto-char (point-min))
2523       (while (not (eobp))
2524         (skip-chars-forward "^,\"" (point-max))
2525         (if (or (= (following-char) ?,)
2526                 (eobp))
2527             (when (not quoted)
2528               (if (and (> (current-column) 78)
2529                        last)
2530                   (progn
2531                     (save-excursion
2532                       (goto-char last)
2533                       (insert "\n\t"))
2534                     (setq last (1+ (point))))
2535                 (setq last (1+ (point)))))
2536           (setq quoted (not quoted)))
2537         (unless (eobp)
2538           (forward-char 1))))
2539     (goto-char (point-max))
2540     (widen)
2541     (forward-line 1)))
2542
2543 (defun message-fill-header (header value)
2544   (let ((begin (point))
2545         (fill-column 78)
2546         (fill-prefix "\t"))
2547     (insert (capitalize (symbol-name header))
2548             ": "
2549             (if (consp value) (car value) value)
2550             "\n")
2551     (save-restriction
2552       (narrow-to-region begin (point))
2553       (fill-region-as-paragraph begin (point))
2554       ;; Tapdance around looong Message-IDs.
2555       (forward-line -1)
2556       (when (looking-at "[ \t]*$")
2557         (message-delete-line))
2558       (goto-char begin)
2559       (re-search-forward ":" nil t)
2560       (when (looking-at "\n[ \t]+")
2561         (replace-match " " t t))
2562       (goto-char (point-max)))))
2563
2564 (defun message-position-point ()
2565   "Move point to where the user probably wants to find it."
2566   (message-narrow-to-headers)
2567   (cond 
2568    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2569     (search-backward ":" )
2570     (widen)
2571     (forward-char 1)
2572     (if (= (following-char) ? )
2573         (forward-char 1)
2574       (insert " ")))
2575    (t
2576     (goto-char (point-max))
2577     (widen)
2578     (forward-line 1)
2579     (unless (looking-at "$")
2580       (forward-line 2)))
2581    (sit-for 0)))
2582
2583 (defun message-buffer-name (type &optional to group)
2584   "Return a new (unique) buffer name based on TYPE and TO."
2585   (cond
2586    ;; Check whether `message-generate-new-buffers' is a function, 
2587    ;; and if so, call it.
2588    ((message-functionp message-generate-new-buffers)
2589     (funcall message-generate-new-buffers type to group))
2590    ;; Generate a new buffer name The Message Way.
2591    (message-generate-new-buffers
2592     (generate-new-buffer-name
2593      (concat "*" type
2594              (if to
2595                  (concat " to "
2596                          (or (car (mail-extract-address-components to))
2597                              to) "")
2598                "")
2599              (if (and group (not (string= group ""))) (concat " on " group) "")
2600              "*")))
2601    ;; Use standard name.
2602    (t
2603     (format "*%s message*" type))))
2604
2605 (defun message-pop-to-buffer (name)
2606   "Pop to buffer NAME, and warn if it already exists and is modified."
2607   (let ((buffer (get-buffer name)))
2608     (if (and buffer
2609              (buffer-name buffer))
2610         (progn
2611           (set-buffer (pop-to-buffer buffer))
2612           (when (and (buffer-modified-p)
2613                      (not (y-or-n-p
2614                            "Message already being composed; erase? ")))
2615             (error "Message being composed")))
2616       (set-buffer (pop-to-buffer name))))
2617   (erase-buffer)
2618   (message-mode))
2619
2620 (defun message-do-send-housekeeping ()
2621   "Kill old message buffers."
2622   ;; We might have sent this buffer already.  Delete it from the
2623   ;; list of buffers.
2624   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2625   (while (and message-max-buffers
2626               (>= (length message-buffer-list) message-max-buffers))
2627     ;; Kill the oldest buffer -- unless it has been changed.
2628     (let ((buffer (pop message-buffer-list)))
2629       (when (and (buffer-name buffer)
2630                  (not (buffer-modified-p buffer)))
2631         (kill-buffer buffer))))
2632   ;; Rename the buffer.
2633   (if message-send-rename-function
2634       (funcall message-send-rename-function)
2635     (when (string-match "\\`\\*" (buffer-name))
2636       (rename-buffer 
2637        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2638   ;; Push the current buffer onto the list.
2639   (when message-max-buffers
2640     (setq message-buffer-list 
2641           (nconc message-buffer-list (list (current-buffer))))))
2642
2643 (defvar mc-modes-alist)
2644 (defun message-setup (headers &optional replybuffer actions)
2645   (when (and (boundp 'mc-modes-alist)
2646              (not (assq 'message-mode mc-modes-alist)))
2647     (push '(message-mode (encrypt . mc-encrypt-message)
2648                          (sign . mc-sign-message))
2649           mc-modes-alist))
2650   (when actions
2651     (setq message-send-actions actions))
2652   (setq message-reply-buffer replybuffer)
2653   (goto-char (point-min))
2654   ;; Insert all the headers.
2655   (mail-header-format 
2656    (let ((h headers)
2657          (alist message-header-format-alist))
2658      (while h
2659        (unless (assq (caar h) message-header-format-alist)
2660          (push (list (caar h)) alist))
2661        (pop h))
2662      alist)
2663    headers)
2664   (delete-region (point) (progn (forward-line -1) (point)))
2665   (when message-default-headers
2666     (insert message-default-headers))
2667   (put-text-property
2668    (point)
2669    (progn
2670      (insert mail-header-separator "\n")
2671      (1- (point)))
2672    'read-only nil)
2673   (forward-line -1)
2674   (when (message-news-p)
2675     (when message-default-news-headers
2676       (insert message-default-news-headers))
2677     (when message-generate-headers-first
2678       (message-generate-headers
2679        (delq 'Lines
2680              (delq 'Subject
2681                    (copy-sequence message-required-news-headers))))))
2682   (when (message-mail-p)
2683     (when message-default-mail-headers
2684       (insert message-default-mail-headers))
2685     (when message-generate-headers-first
2686       (message-generate-headers
2687        (delq 'Lines
2688              (delq 'Subject
2689                    (copy-sequence message-required-mail-headers))))))
2690   (run-hooks 'message-signature-setup-hook)
2691   (message-insert-signature)
2692   (message-set-auto-save-file-name)
2693   (save-restriction
2694     (message-narrow-to-headers)
2695     (run-hooks 'message-header-setup-hook))
2696   (set-buffer-modified-p nil)
2697   (run-hooks 'message-setup-hook)
2698   (message-position-point)
2699   (undo-boundary))
2700
2701 (defun message-set-auto-save-file-name ()
2702   "Associate the message buffer with a file in the drafts directory."
2703   (when message-autosave-directory
2704     (unless (file-exists-p message-autosave-directory)
2705       (make-directory message-autosave-directory t))
2706     (let ((name (make-temp-name
2707                  (concat (file-name-as-directory message-autosave-directory)
2708                          "msg."))))
2709       (setq buffer-auto-save-file-name
2710             (save-excursion
2711               (prog1
2712                   (progn
2713                     (set-buffer (get-buffer-create " *draft tmp*"))
2714                     (setq buffer-file-name name)
2715                     (make-auto-save-file-name))
2716                 (kill-buffer (current-buffer)))))
2717       (clear-visited-file-modtime))))
2718
2719 \f
2720
2721 ;;;
2722 ;;; Commands for interfacing with message
2723 ;;;
2724
2725 ;;;###autoload
2726 (defun message-mail (&optional to subject)
2727   "Start editing a mail message to be sent."
2728   (interactive)
2729   (message-pop-to-buffer (message-buffer-name "mail" to))
2730   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2731
2732 ;;;###autoload
2733 (defun message-news (&optional newsgroups subject)
2734   "Start editing a news article to be sent."
2735   (interactive)
2736   (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
2737   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2738                    (Subject . ,(or subject "")))))
2739
2740 ;;;###autoload
2741 (defun message-reply (&optional to-address wide ignore-reply-to)
2742   "Start editing a reply to the article in the current buffer."
2743   (interactive)
2744   (let ((cur (current-buffer))
2745         from subject date reply-to to cc
2746         references message-id follow-to 
2747         (inhibit-point-motion-hooks t)
2748         mct never-mct gnus-warning)
2749     (save-restriction
2750       (message-narrow-to-head)
2751       ;; Allow customizations to have their say.
2752       (if (not wide)
2753           ;; This is a regular reply.
2754           (if (message-functionp message-reply-to-function)
2755               (setq follow-to (funcall message-reply-to-function)))
2756         ;; This is a followup.
2757         (if (message-functionp message-wide-reply-to-function)
2758             (save-excursion
2759               (setq follow-to
2760                     (funcall message-wide-reply-to-function)))))
2761       ;; Find all relevant headers we need.
2762       (setq from (message-fetch-field "from")
2763             date (message-fetch-field "date") 
2764             subject (or (message-fetch-field "subject") "none")
2765             to (message-fetch-field "to")
2766             cc (message-fetch-field "cc")
2767             mct (message-fetch-field "mail-copies-to")
2768             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
2769             references (message-fetch-field "references")
2770             message-id (message-fetch-field "message-id"))
2771       ;; Remove any (buggy) Re:'s that are present and make a
2772       ;; proper one.
2773       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2774         (setq subject (substring subject (match-end 0))))
2775       (setq subject (concat "Re: " subject))
2776
2777       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2778                  (string-match "<[^>]+>" gnus-warning))
2779         (setq message-id (match-string 0 gnus-warning)))
2780             
2781       ;; Handle special values of Mail-Copies-To.
2782       (when mct
2783         (cond ((equal (downcase mct) "never")
2784                (setq never-mct t)
2785                (setq mct nil))
2786               ((equal (downcase mct) "always")
2787                (setq mct (or reply-to from)))))
2788
2789       (unless follow-to
2790         (if (or (not wide)
2791                 to-address)
2792             (setq follow-to (list (cons 'To (or to-address reply-to from))))
2793           (let (ccalist)
2794             (save-excursion
2795               (message-set-work-buffer)
2796               (unless never-mct
2797                 (insert (or reply-to from "")))
2798               (insert (if (bolp) "" ", ") (or to ""))
2799               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
2800               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
2801               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2802               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2803                         (erase-buffer)))
2804               (goto-char (point-min))
2805               (setq ccalist
2806                     (mapcar
2807                      (lambda (addr)
2808                        (cons (mail-strip-quoted-names addr) addr))
2809                      (message-tokenize-header (buffer-string))))
2810               (let ((s ccalist))
2811                 (while s
2812                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2813             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2814             (when ccalist
2815               (let ((ccs (cons 'Cc (mapconcat 
2816                                     (lambda (addr) (cdr addr)) ccalist ", "))))
2817                 (when (string-match "^ +" (cdr ccs))
2818                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
2819                 (push ccs follow-to))))))
2820       (widen))
2821
2822     (message-pop-to-buffer (message-buffer-name
2823                             (if wide "wide reply" "reply") from
2824                             (if wide to-address nil)))
2825
2826     (setq message-reply-headers
2827           (vector 0 subject from date message-id references 0 0 ""))
2828
2829     (message-setup
2830      `((Subject . ,subject)
2831        ,@follow-to 
2832        ,@(if (or references message-id)
2833              `((References . ,(concat (or references "") (and references " ")
2834                                       (or message-id ""))))
2835            nil))
2836      cur)))
2837
2838 ;;;###autoload
2839 (defun message-wide-reply (&optional to-address)
2840   "Make a \"wide\" reply to the message in the current buffer."
2841   (interactive)
2842   (message-reply to-address t))
2843
2844 ;;;###autoload
2845 (defun message-followup (&optional to-newsgroups)
2846   "Follow up to the message in the current buffer.
2847 If TO-NEWSGROUPS, use that as the new Newsgroups line."
2848   (interactive)
2849   (let ((cur (current-buffer))
2850         from subject date reply-to mct
2851         references message-id follow-to 
2852         (inhibit-point-motion-hooks t)
2853         followup-to distribution newsgroups gnus-warning)
2854     (save-restriction
2855       (narrow-to-region
2856        (goto-char (point-min))
2857        (if (search-forward "\n\n" nil t)
2858            (1- (point))
2859          (point-max)))
2860       (when (message-functionp message-followup-to-function)
2861         (setq follow-to
2862               (funcall message-followup-to-function)))
2863       (setq from (message-fetch-field "from")
2864             date (message-fetch-field "date") 
2865             subject (or (message-fetch-field "subject") "none")
2866             references (message-fetch-field "references")
2867             message-id (message-fetch-field "message-id")
2868             followup-to (message-fetch-field "followup-to")
2869             newsgroups (message-fetch-field "newsgroups")
2870             reply-to (message-fetch-field "reply-to")
2871             distribution (message-fetch-field "distribution")
2872             mct (message-fetch-field "mail-copies-to"))
2873       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2874                  (string-match "<[^>]+>" gnus-warning))
2875         (setq message-id (match-string 0 gnus-warning)))
2876       ;; Remove bogus distribution.
2877       (and (stringp distribution)
2878            (string-match "world" distribution)
2879            (setq distribution nil))
2880       ;; Remove any (buggy) Re:'s that are present and make a
2881       ;; proper one.
2882       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2883         (setq subject (substring subject (match-end 0))))
2884       (setq subject (concat "Re: " subject))
2885       (widen))
2886
2887     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
2888
2889     (message-setup
2890      `((Subject . ,subject)
2891        ,@(cond 
2892           (to-newsgroups
2893            (list (cons 'Newsgroups to-newsgroups)))
2894           (follow-to follow-to)
2895           ((and followup-to message-use-followup-to)
2896            (list
2897             (cond 
2898              ((equal (downcase followup-to) "poster")
2899               (if (or (eq message-use-followup-to 'use)
2900                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
2901 You should normally obey the Followup-To: header.
2902
2903 `Followup-To: poster' sends your response via e-mail instead of news.
2904
2905 A typical situation where `Followup-To: poster' is used is when the poster
2906 does not read the newsgroup, so he wouldn't see any replies sent to it."))
2907                   (cons 'To (or reply-to from ""))
2908                 (cons 'Newsgroups newsgroups)))
2909              (t
2910               (if (or (equal followup-to newsgroups)
2911                       (not (eq message-use-followup-to 'ask))
2912                       (message-y-or-n-p
2913                        (concat "Obey Followup-To: " followup-to "? ") t "\
2914 You should normally obey the Followup-To: header.
2915
2916         `Followup-To: " followup-to "'
2917 directs your response to " (if (string-match "," followup-to)
2918                                "the specified newsgroups"
2919                              "that newsgroup only") ".
2920
2921 If a message is posted to several newsgroups, Followup-To is often
2922 used to direct the following discussion to one newsgroup only,
2923 because discussions that are spread over several newsgroup tend to
2924 be fragmented and very difficult to follow.
2925
2926 Also, some source/announcement newsgroups are not indented for discussion;
2927 responses here are directed to other newsgroups."))
2928                   (cons 'Newsgroups followup-to)
2929                 (cons 'Newsgroups newsgroups))))))
2930           (t
2931            `((Newsgroups . ,newsgroups))))
2932        ,@(and distribution (list (cons 'Distribution distribution)))
2933        ,@(if (or references message-id)
2934              `((References . ,(concat (or references "") (and references " ")
2935                                       (or message-id "")))))
2936        ,@(when (and mct
2937                     (not (equal (downcase mct) "never")))
2938            (list (cons 'Cc (if (equal (downcase mct) "always")
2939                                (or reply-to from "")
2940                              mct)))))
2941
2942      cur)
2943
2944     (setq message-reply-headers
2945           (vector 0 subject from date message-id references 0 0 ""))))
2946
2947
2948 ;;;###autoload
2949 (defun message-cancel-news ()
2950   "Cancel an article you posted."
2951   (interactive)
2952   (unless (message-news-p)
2953     (error "This is not a news article; canceling is impossible"))
2954   (when (yes-or-no-p "Do you really want to cancel this article? ")
2955     (let (from newsgroups message-id distribution buf)
2956       (save-excursion
2957         ;; Get header info. from original article.
2958         (save-restriction
2959           (message-narrow-to-head)
2960           (setq from (message-fetch-field "from")
2961                 newsgroups (message-fetch-field "newsgroups")
2962                 message-id (message-fetch-field "message-id")
2963                 distribution (message-fetch-field "distribution")))
2964         ;; Make sure that this article was written by the user.
2965         (unless (string-equal
2966                  (downcase (cadr (mail-extract-address-components from)))
2967                  (downcase (message-make-address)))
2968           (error "This article is not yours"))
2969         ;; Make control message.
2970         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
2971         (buffer-disable-undo (current-buffer))
2972         (erase-buffer)
2973         (insert "Newsgroups: " newsgroups "\n"
2974                 "From: " (message-make-from) "\n"
2975                 "Subject: cmsg cancel " message-id "\n"
2976                 "Control: cancel " message-id "\n"
2977                 (if distribution
2978                     (concat "Distribution: " distribution "\n")
2979                   "")
2980                 mail-header-separator "\n"
2981                 message-cancel-message)
2982         (message "Canceling your article...")
2983         (let ((message-syntax-checks 'dont-check-for-anything-just-trust-me))
2984           (funcall message-send-news-function))
2985         (message "Canceling your article...done")
2986         (kill-buffer buf)))))
2987
2988 ;;;###autoload
2989 (defun message-supersede ()
2990   "Start composing a message to supersede the current message.
2991 This is done simply by taking the old article and adding a Supersedes
2992 header line with the old Message-ID."
2993   (interactive)
2994   (let ((cur (current-buffer)))
2995     ;; Check whether the user owns the article that is to be superseded. 
2996     (unless (string-equal
2997              (downcase (cadr (mail-extract-address-components
2998                               (message-fetch-field "from"))))
2999              (downcase (message-make-address)))
3000       (error "This article is not yours"))
3001     ;; Get a normal message buffer.
3002     (message-pop-to-buffer (message-buffer-name "supersede"))
3003     (insert-buffer-substring cur)
3004     (message-narrow-to-head)
3005     ;; Remove unwanted headers.
3006     (when message-ignored-supersedes-headers
3007       (message-remove-header message-ignored-supersedes-headers t))
3008     (goto-char (point-min))
3009     (if (not (re-search-forward "^Message-ID: " nil t))
3010         (error "No Message-ID in this article")
3011       (replace-match "Supersedes: " t t))
3012     (goto-char (point-max))
3013     (insert mail-header-separator)
3014     (widen)
3015     (forward-line 1)))
3016
3017 ;;;###autoload
3018 (defun message-recover ()
3019   "Reread contents of current buffer from its last auto-save file."
3020   (interactive)
3021   (let ((file-name (make-auto-save-file-name)))
3022     (cond ((save-window-excursion
3023              (if (not (eq system-type 'vax-vms))
3024                  (with-output-to-temp-buffer "*Directory*"
3025                    (buffer-disable-undo standard-output)
3026                    (let ((default-directory "/"))
3027                      (call-process
3028                       "ls" nil standard-output nil "-l" file-name))))
3029              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3030            (let ((buffer-read-only nil))
3031              (erase-buffer)
3032              (insert-file-contents file-name nil)))
3033           (t (error "message-recover cancelled")))))
3034
3035 ;;; Forwarding messages.
3036
3037 (defun message-make-forward-subject ()
3038   "Return a Subject header suitable for the message in the current buffer."
3039   (concat "[" (or (message-fetch-field 
3040                    (if (message-news-p) "newsgroups" "from"))
3041                   "(nowhere)")
3042           "] " (or (message-fetch-field "Subject") "")))
3043
3044 ;;;###autoload
3045 (defun message-forward (&optional news)
3046   "Forward the current message via mail.  
3047 Optional NEWS will use news to forward instead of mail."
3048   (interactive "P")
3049   (let ((cur (current-buffer))
3050         (subject (message-make-forward-subject))
3051         art-beg)
3052     (if news (message-news nil subject) (message-mail nil subject))
3053     ;; Put point where we want it before inserting the forwarded
3054     ;; message. 
3055     (if message-signature-before-forwarded-message
3056         (goto-char (point-max))
3057       (message-goto-body))
3058     ;; Make sure we're at the start of the line.
3059     (unless (eolp)
3060       (insert "\n"))
3061     ;; Narrow to the area we are to insert.
3062     (narrow-to-region (point) (point))
3063     ;; Insert the separators and the forwarded buffer.
3064     (insert message-forward-start-separator)
3065     (setq art-beg (point))
3066     (insert-buffer-substring cur)
3067     (goto-char (point-max))
3068     (insert message-forward-end-separator)
3069     (set-text-properties (point-min) (point-max) nil)
3070     ;; Remove all unwanted headers.
3071     (goto-char art-beg)
3072     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3073                                   (1- (point))
3074                                 (point)))
3075     (goto-char (point-min))
3076     (message-remove-header message-included-forward-headers t nil t)
3077     (widen)
3078     (message-position-point)))
3079
3080 ;;;###autoload
3081 (defun message-resend (address)
3082   "Resend the current article to ADDRESS."
3083   (interactive "sResend message to: ")
3084   (message "Resending message to %s..." address)
3085   (save-excursion
3086     (let ((cur (current-buffer))
3087           beg)
3088       ;; We first set up a normal mail buffer.
3089       (set-buffer (get-buffer-create " *message resend*"))
3090       (buffer-disable-undo (current-buffer))
3091       (erase-buffer)
3092       (message-setup `((To . ,address)))
3093       ;; Insert our usual headers.
3094       (message-generate-headers '(From Date To))
3095       (message-narrow-to-headers)
3096       ;; Rename them all to "Resent-*".
3097       (while (re-search-forward "^[A-Za-z]" nil t)
3098         (forward-char -1)
3099         (insert "Resent-"))
3100       (widen)
3101       (forward-line)
3102       (delete-region (point) (point-max))
3103       (setq beg (point))
3104       ;; Insert the message to be resent.
3105       (insert-buffer-substring cur)
3106       (goto-char (point-min))
3107       (search-forward "\n\n")
3108       (forward-char -1)
3109       (save-restriction
3110         (narrow-to-region beg (point))
3111         (message-remove-header message-ignored-resent-headers t)
3112         (goto-char (point-max)))
3113       (insert mail-header-separator)
3114       ;; Rename all old ("Also-")Resent headers.
3115       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
3116         (beginning-of-line)
3117         (insert "Also-"))
3118       ;; Send it.
3119       (message-send-mail)
3120       (kill-buffer (current-buffer)))
3121     (message "Resending message to %s...done" address)))
3122
3123 ;;;###autoload
3124 (defun message-bounce ()
3125   "Re-mail the current message.
3126 This only makes sense if the current message is a bounce message than
3127 contains some mail you have written which has been bounced back to
3128 you."
3129   (interactive)
3130   (let ((cur (current-buffer))
3131         boundary)
3132     (message-pop-to-buffer (message-buffer-name "bounce"))
3133     (insert-buffer-substring cur)
3134     (undo-boundary)
3135     (message-narrow-to-head)
3136     (if (and (message-fetch-field "Mime-Version")
3137              (setq boundary (message-fetch-field "Content-Type")))
3138         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3139             (setq boundary (concat (match-string 1 boundary) " *\n"
3140                                    "Content-Type: message/rfc822"))
3141           (setq boundary nil)))
3142     (widen)
3143     (goto-char (point-min))
3144     (search-forward "\n\n" nil t)
3145     (or (and boundary
3146              (re-search-forward boundary nil t)
3147              (forward-line 2))
3148         (and (re-search-forward message-unsent-separator nil t)
3149              (forward-line 1))
3150         (and (search-forward "\n\n" nil t)
3151              (re-search-forward "^Return-Path:.*\n" nil t)))
3152     ;; We remove everything before the bounced mail.
3153     (delete-region 
3154      (point-min)
3155      (if (re-search-forward "^[^ \n\t]+:" nil t)
3156          (match-beginning 0)
3157        (point)))
3158     (save-restriction
3159       (message-narrow-to-head)
3160       (message-remove-header message-ignored-bounced-headers t)
3161       (goto-char (point-max))
3162       (insert mail-header-separator))
3163     (message-position-point)))
3164
3165 ;;;
3166 ;;; Interactive entry points for new message buffers.
3167 ;;;
3168
3169 ;;;###autoload
3170 (defun message-mail-other-window (&optional to subject)
3171   "Like `message-mail' command, but display mail buffer in another window."
3172   (interactive)
3173   (let ((pop-up-windows t)
3174         (special-display-buffer-names nil)
3175         (special-display-regexps nil)
3176         (same-window-buffer-names nil)
3177         (same-window-regexps nil))
3178     (message-pop-to-buffer (message-buffer-name "mail" to)))
3179   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3180
3181 ;;;###autoload
3182 (defun message-mail-other-frame (&optional to subject)
3183   "Like `message-mail' command, but display mail buffer in another frame."
3184   (interactive)
3185   (let ((pop-up-frames t)
3186         (special-display-buffer-names nil)
3187         (special-display-regexps nil)
3188         (same-window-buffer-names nil)
3189         (same-window-regexps nil))
3190     (message-pop-to-buffer (message-buffer-name "mail" to)))
3191   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3192
3193 ;;;###autoload
3194 (defun message-news-other-window (&optional newsgroups subject)
3195   "Start editing a news article to be sent."
3196   (interactive)
3197   (let ((pop-up-windows t)
3198         (special-display-buffer-names nil)
3199         (special-display-regexps nil)
3200         (same-window-buffer-names nil)
3201         (same-window-regexps nil))
3202     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3203   (message-setup `((Newsgroups . ,(or newsgroups "")) 
3204                    (Subject . ,(or subject "")))))
3205
3206 ;;;###autoload
3207 (defun message-news-other-frame (&optional newsgroups subject)
3208   "Start editing a news article to be sent."
3209   (interactive)
3210   (let ((pop-up-frames t)
3211         (special-display-buffer-names nil)
3212         (special-display-regexps nil)
3213         (same-window-buffer-names nil)
3214         (same-window-regexps nil))
3215     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3216   (message-setup `((Newsgroups . ,(or newsgroups "")) 
3217                    (Subject . ,(or subject "")))))
3218
3219 ;;; underline.el
3220
3221 ;; This code should be moved to underline.el (from which it is stolen). 
3222
3223 ;;;###autoload
3224 (defun bold-region (start end)
3225   "Bold all nonblank characters in the region.
3226 Works by overstriking characters.
3227 Called from program, takes two arguments START and END
3228 which specify the range to operate on."
3229   (interactive "r")
3230   (save-excursion
3231     (let ((end1 (make-marker)))
3232       (move-marker end1 (max start end))
3233       (goto-char (min start end))
3234       (while (< (point) end1)
3235         (or (looking-at "[_\^@- ]")
3236             (insert (following-char) "\b"))
3237         (forward-char 1)))))
3238
3239 ;;;###autoload
3240 (defun unbold-region (start end)
3241   "Remove all boldness (overstruck characters) in the region.
3242 Called from program, takes two arguments START and END
3243 which specify the range to operate on."
3244   (interactive "r")
3245   (save-excursion
3246     (let ((end1 (make-marker)))
3247       (move-marker end1 (max start end))
3248       (goto-char (min start end)) 
3249       (while (re-search-forward "\b" end1 t)
3250         (if (eq (following-char) (char-after (- (point) 2)))
3251             (delete-char -2))))))
3252
3253 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3254
3255 ;; Support for toolbar
3256 (when (string-match "XEmacs\\|Lucid" emacs-version)
3257   (require 'messagexmas))
3258
3259 ;;; Group name completion.
3260
3261 (defvar message-newgroups-header-regexp
3262   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\):"
3263   "Regexp that match headers that lists groups.")
3264
3265 (defun message-tab ()
3266   "Expand group names in Newsgroups and Followup-To headers.
3267 Do a `tab-to-tab-stop' if not in those headers."
3268   (interactive)
3269   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3270         (mail-abbrev-in-expansion-header-p))
3271       (message-expand-group)
3272     (tab-to-tab-stop)))
3273
3274 (defvar gnus-active-hashtb)
3275 (defun message-expand-group ()
3276   (let* ((b (save-excursion (skip-chars-backward "^, :\t\n") (point)))
3277          (completion-ignore-case t)
3278          (string (buffer-substring b (point)))
3279          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3280          (completions (all-completions string hashtb))
3281          (cur (current-buffer))
3282          comp)
3283     (delete-region b (point))
3284     (cond 
3285      ((= (length completions) 1)
3286       (if (string= (car completions) string)
3287           (progn
3288             (insert string)
3289             (message "Only matching group"))
3290         (insert (car completions))))
3291      ((and (setq comp (try-completion string hashtb))
3292            (not (string= comp string)))
3293       (insert comp))
3294      (t
3295       (insert string)
3296       (if (not comp)
3297           (message "No matching groups")
3298         (pop-to-buffer "*Completions*")
3299         (buffer-disable-undo (current-buffer))
3300         (let ((buffer-read-only nil))
3301           (erase-buffer)
3302           (let ((standard-output (current-buffer)))
3303             (display-completion-list (sort completions 'string<)))
3304           (goto-char (point-min))
3305           (pop-to-buffer cur)))))))
3306
3307 ;;; Help stuff.
3308
3309 (defun message-talkative-question (ask question show &rest text)
3310   "Call FUNCTION with argument QUESTION, displaying the rest of the arguments in a temporary buffer if SHOW.  
3311 The following arguments may contain lists of values."
3312   (if (and show
3313            (setq text (message-flatten-list text)))
3314       (save-window-excursion
3315         (save-excursion
3316           (with-output-to-temp-buffer " *MESSAGE information message*"
3317             (set-buffer " *MESSAGE information message*")
3318             (mapcar 'princ text)
3319             (goto-char (point-min))))
3320         (funcall ask question))
3321     (funcall ask question)))
3322
3323 (defun message-flatten-list (list)
3324   "Return a new, flat list that contains all elements of LIST.
3325
3326 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3327 => (1 2 3 4 5 6 7)"
3328   (cond ((consp list) 
3329          (apply 'append (mapcar 'message-flatten-list list)))
3330         (list
3331          (list list))))
3332
3333 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3334   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3335 Then clone the local variables and values from the old buffer to the
3336 new one, cloning only the locals having a substring matching the
3337 regexp varstr."
3338   (let ((oldlocals (buffer-local-variables)))
3339     (save-excursion
3340       (set-buffer (generate-new-buffer name))
3341       (mapcar (lambda (dude)
3342                 (when (and (car dude)
3343                            (or (not varstr)
3344                                (string-match varstr (symbol-name (car dude)))))
3345                   (ignore-errors
3346                     (set (make-local-variable (car dude))
3347                          (cdr dude)))))
3348               oldlocals)
3349       (current-buffer))))
3350
3351 (run-hooks 'message-load-hook)
3352
3353 (provide 'message)
3354
3355 ;;; message.el ends here