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