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