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