* message.el (message-fix-before-sending): Fix highlighting of
[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-string (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   ;; Allow using comment commands to add/remove quoting.
2274   (set (make-local-variable 'comment-start) message-yank-prefix)
2275   (if (featurep 'xemacs)
2276       (message-setup-toolbar)
2277     (set (make-local-variable 'font-lock-defaults)
2278          '(message-font-lock-keywords t))
2279     (if (boundp 'tool-bar-map)
2280         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2281   (easy-menu-add message-mode-menu message-mode-map)
2282   (easy-menu-add message-mode-field-menu message-mode-map)
2283   ;; make-local-hook is harmless though obsolete in Emacs 21.
2284   ;; Emacs 20 and XEmacs need make-local-hook.
2285   (make-local-hook 'after-change-functions)
2286   ;; Mmmm... Forbidden properties...
2287   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2288             nil 'local)
2289   ;; Allow mail alias things.
2290   (when (eq message-mail-alias-type 'abbrev)
2291     (if (fboundp 'mail-abbrevs-setup)
2292         (mail-abbrevs-setup)
2293       (mail-aliases-setup)))
2294   (unless buffer-file-name
2295     (message-set-auto-save-file-name))
2296   (unless (buffer-base-buffer)
2297     ;; Don't enable multibyte on an indirect buffer.  Maybe enabling
2298     ;; multibyte is not necessary at all. -- zsh
2299     (mm-enable-multibyte))
2300   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
2301   (mml-mode))
2302
2303 (defun message-setup-fill-variables ()
2304   "Setup message fill variables."
2305   (set (make-local-variable 'fill-paragraph-function)
2306        'message-fill-paragraph)
2307   (make-local-variable 'paragraph-separate)
2308   (make-local-variable 'paragraph-start)
2309   (make-local-variable 'adaptive-fill-regexp)
2310   (unless (boundp 'adaptive-fill-first-line-regexp)
2311     (setq adaptive-fill-first-line-regexp nil))
2312   (make-local-variable 'adaptive-fill-first-line-regexp)
2313   (let ((quote-prefix-regexp
2314          ;; User should change message-cite-prefix-regexp if
2315          ;; message-yank-prefix is set to an abnormal value.
2316          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2317     (setq paragraph-start
2318           (concat
2319            (regexp-quote mail-header-separator) "$\\|"
2320            "[ \t]*$\\|"                 ; blank lines
2321            "-- $\\|"                    ; signature delimiter
2322            "---+$\\|"              ; delimiters for forwarded messages
2323            page-delimiter "$\\|"        ; spoiler warnings
2324            ".*wrote:$\\|"               ; attribution lines
2325            quote-prefix-regexp "$"))    ; empty lines in quoted text
2326     (setq paragraph-separate paragraph-start)
2327     (setq adaptive-fill-regexp
2328           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2329     (setq adaptive-fill-first-line-regexp
2330           (concat quote-prefix-regexp "\\|"
2331                   adaptive-fill-first-line-regexp)))
2332   (make-local-variable 'auto-fill-inhibit-regexp)
2333   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2334   (setq auto-fill-inhibit-regexp nil)
2335   (make-local-variable 'normal-auto-fill-function)
2336   (setq normal-auto-fill-function 'message-do-auto-fill)
2337   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2338   ;; In that case, ensure that it uses the right function.  The real
2339   ;; solution would be not to use `define-derived-mode', and run
2340   ;; `text-mode-hook' ourself at the end of the mode.
2341   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2342   (when auto-fill-function
2343     (setq auto-fill-function normal-auto-fill-function)))
2344
2345 \f
2346
2347 ;;;
2348 ;;; Message mode commands
2349 ;;;
2350
2351 ;;; Movement commands
2352
2353 (defun message-goto-to ()
2354   "Move point to the To header."
2355   (interactive)
2356   (message-position-on-field "To"))
2357
2358 (defun message-goto-from ()
2359   "Move point to the From header."
2360   (interactive)
2361   (message-position-on-field "From"))
2362
2363 (defun message-goto-subject ()
2364   "Move point to the Subject header."
2365   (interactive)
2366   (message-position-on-field "Subject"))
2367
2368 (defun message-goto-cc ()
2369   "Move point to the Cc header."
2370   (interactive)
2371   (message-position-on-field "Cc" "To"))
2372
2373 (defun message-goto-bcc ()
2374   "Move point to the Bcc  header."
2375   (interactive)
2376   (message-position-on-field "Bcc" "Cc" "To"))
2377
2378 (defun message-goto-fcc ()
2379   "Move point to the Fcc header."
2380   (interactive)
2381   (message-position-on-field "Fcc" "To" "Newsgroups"))
2382
2383 (defun message-goto-reply-to ()
2384   "Move point to the Reply-To header."
2385   (interactive)
2386   (message-position-on-field "Reply-To" "Subject"))
2387
2388 (defun message-goto-newsgroups ()
2389   "Move point to the Newsgroups header."
2390   (interactive)
2391   (message-position-on-field "Newsgroups"))
2392
2393 (defun message-goto-distribution ()
2394   "Move point to the Distribution header."
2395   (interactive)
2396   (message-position-on-field "Distribution"))
2397
2398 (defun message-goto-followup-to ()
2399   "Move point to the Followup-To header."
2400   (interactive)
2401   (message-position-on-field "Followup-To" "Newsgroups"))
2402
2403 (defun message-goto-mail-followup-to ()
2404   "Move point to the Mail-Followup-To header."
2405   (interactive)
2406   (message-position-on-field "Mail-Followup-To" "From"))
2407
2408 (defun message-goto-keywords ()
2409   "Move point to the Keywords header."
2410   (interactive)
2411   (message-position-on-field "Keywords" "Subject"))
2412
2413 (defun message-goto-summary ()
2414   "Move point to the Summary header."
2415   (interactive)
2416   (message-position-on-field "Summary" "Subject"))
2417
2418 (defun message-goto-body (&optional interactivep)
2419   "Move point to the beginning of the message body."
2420   (interactive (list t))
2421   (when (and interactivep
2422              (looking-at "[ \t]*\n"))
2423     (expand-abbrev))
2424   (goto-char (point-min))
2425   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2426       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2427
2428 (defun message-goto-eoh ()
2429   "Move point to the end of the headers."
2430   (interactive)
2431   (message-goto-body)
2432   (forward-line -1))
2433
2434 (defun message-goto-signature ()
2435   "Move point to the beginning of the message signature.
2436 If there is no signature in the article, go to the end and
2437 return nil."
2438   (interactive)
2439   (goto-char (point-min))
2440   (if (re-search-forward message-signature-separator nil t)
2441       (forward-line 1)
2442     (goto-char (point-max))
2443     nil))
2444
2445 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
2446   "Insert a reasonable MFT header in a post to an unsubscribed list.
2447 When making original posts to a mailing list you are not subscribed to,
2448 you have to type in a MFT header by hand.  The contents, usually, are
2449 the addresses of the list and your own address.  This function inserts
2450 such a header automatically.  It fetches the contents of the To: header
2451 in the current mail buffer, and appends the current `user-mail-address'.
2452
2453 If the optional argument INCLUDE-CC is non-nil, the addresses in the
2454 Cc: header are also put into the MFT."
2455
2456   (interactive "P")
2457   (message-remove-header "Mail-Followup-To")
2458   (let* ((cc (and include-cc (message-fetch-field "Cc")))
2459          (tos (if cc
2460                   (concat (message-fetch-field "To") "," cc)
2461                 (message-fetch-field "To"))))
2462     (message-goto-mail-followup-to)
2463     (insert (concat tos ", " user-mail-address))))
2464
2465 \f
2466
2467 (defun message-insert-to (&optional force)
2468   "Insert a To header that points to the author of the article being replied to.
2469 If the original author requested not to be sent mail, the function signals
2470 an error.
2471 With the prefix argument FORCE, insert the header anyway."
2472   (interactive "P")
2473   (let ((co (message-fetch-reply-field "mail-copies-to")))
2474     (when (and (null force)
2475                co
2476                (or (equal (downcase co) "never")
2477                    (equal (downcase co) "nobody")))
2478       (error "The user has requested not to have copies sent via mail")))
2479   (message-carefully-insert-headers
2480    (list (cons 'To
2481                (or (message-fetch-reply-field "mail-reply-to")
2482                    (message-fetch-reply-field "reply-to")
2483                    (message-fetch-reply-field "from")
2484                    "")))))
2485
2486 (defun message-insert-wide-reply ()
2487   "Insert To and Cc headers as if you were doing a wide reply."
2488   (interactive)
2489   (let ((headers (message-with-reply-buffer
2490                    (message-get-reply-headers t))))
2491     (message-carefully-insert-headers headers)))
2492
2493 (defun message-carefully-insert-headers (headers)
2494   (dolist (header headers)
2495     (let ((header-name (symbol-name (car header))))
2496       (when (and (message-position-on-field header-name)
2497                  (mail-fetch-field header-name)
2498                  (not (string-match "\\` *\\'"
2499                                     (mail-fetch-field header-name))))
2500         (insert ", "))
2501       (insert (cdr header)))))
2502
2503 (defun message-widen-reply ()
2504   "Widen the reply to include maximum recipients."
2505   (interactive)
2506   (let ((follow-to
2507          (and message-reply-buffer
2508               (buffer-name message-reply-buffer)
2509               (save-excursion
2510                 (set-buffer message-reply-buffer)
2511                 (message-get-reply-headers t)))))
2512     (save-excursion
2513       (save-restriction
2514         (message-narrow-to-headers)
2515         (dolist (elem follow-to)
2516           (message-remove-header (symbol-name (car elem)))
2517           (goto-char (point-min))
2518           (insert (symbol-name (car elem)) ": "
2519                   (cdr elem) "\n"))))))
2520
2521 (defun message-insert-newsgroups ()
2522   "Insert the Newsgroups header from the article being replied to."
2523   (interactive)
2524   (when (and (message-position-on-field "Newsgroups")
2525              (mail-fetch-field "newsgroups")
2526              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2527     (insert ","))
2528   (insert (or (message-fetch-reply-field "newsgroups") "")))
2529
2530 \f
2531
2532 ;;; Various commands
2533
2534 (defun message-delete-not-region (beg end)
2535   "Delete everything in the body of the current message outside of the region."
2536   (interactive "r")
2537   (let (citeprefix)
2538     (save-excursion
2539       (goto-char beg)
2540       ;; snarf citation prefix, if appropriate
2541       (unless (eq (point) (progn (beginning-of-line) (point)))
2542         (when (looking-at message-cite-prefix-regexp)
2543           (setq citeprefix (match-string 0))))
2544       (goto-char end)
2545       (delete-region (point) (if (not (message-goto-signature))
2546                                  (point)
2547                                (forward-line -2)
2548                                (point)))
2549       (insert "\n")
2550       (goto-char beg)
2551       (delete-region beg (progn (message-goto-body)
2552                                 (forward-line 2)
2553                                 (point)))
2554       (when citeprefix
2555         (insert citeprefix))))
2556   (when (message-goto-signature)
2557     (forward-line -2)))
2558
2559 (defun message-kill-to-signature ()
2560   "Deletes all text up to the signature."
2561   (interactive)
2562   (let ((point (point)))
2563     (message-goto-signature)
2564     (unless (eobp)
2565       (forward-line -2))
2566     (kill-region point (point))
2567     (unless (bolp)
2568       (insert "\n"))))
2569
2570 (defun message-newline-and-reformat (&optional arg not-break)
2571   "Insert four newlines, and then reformat if inside quoted text.
2572 Prefix arg means justify as well."
2573   (interactive (list (if current-prefix-arg 'full)))
2574   (let (quoted point beg end leading-space bolp)
2575     (setq point (point))
2576     (beginning-of-line)
2577     (setq beg (point))
2578     (setq bolp (= beg point))
2579     ;; Find first line of the paragraph.
2580     (if not-break
2581         (while (and (not (eobp))
2582                     (not (looking-at message-cite-prefix-regexp))
2583                     (looking-at paragraph-start))
2584           (forward-line 1)))
2585     ;; Find the prefix
2586     (when (looking-at message-cite-prefix-regexp)
2587       (setq quoted (match-string 0))
2588       (goto-char (match-end 0))
2589       (looking-at "[ \t]*")
2590       (setq leading-space (match-string 0)))
2591     (if (and quoted
2592              (not not-break)
2593              (not bolp)
2594              (< (- point beg) (length quoted)))
2595         ;; break inside the cite prefix.
2596         (setq quoted nil
2597               end nil))
2598     (if quoted
2599         (progn
2600           (forward-line 1)
2601           (while (and (not (eobp))
2602                       (not (looking-at paragraph-separate))
2603                       (looking-at message-cite-prefix-regexp)
2604                       (equal quoted (match-string 0)))
2605             (goto-char (match-end 0))
2606             (looking-at "[ \t]*")
2607             (if (> (length leading-space) (length (match-string 0)))
2608                 (setq leading-space (match-string 0)))
2609             (forward-line 1))
2610           (setq end (point))
2611           (goto-char beg)
2612           (while (and (if (bobp) nil (forward-line -1) t)
2613                       (not (looking-at paragraph-start))
2614                       (looking-at message-cite-prefix-regexp)
2615                       (equal quoted (match-string 0)))
2616             (setq beg (point))
2617             (goto-char (match-end 0))
2618             (looking-at "[ \t]*")
2619             (if (> (length leading-space) (length (match-string 0)))
2620                 (setq leading-space (match-string 0)))))
2621       (while (and (not (eobp))
2622                   (not (looking-at paragraph-separate))
2623                   (not (looking-at message-cite-prefix-regexp)))
2624         (forward-line 1))
2625       (setq end (point))
2626       (goto-char beg)
2627       (while (and (if (bobp) nil (forward-line -1) t)
2628                   (not (looking-at paragraph-start))
2629                   (not (looking-at message-cite-prefix-regexp)))
2630         (setq beg (point))))
2631     (goto-char point)
2632     (save-restriction
2633       (narrow-to-region beg end)
2634       (if not-break
2635           (setq point nil)
2636         (if bolp
2637             (newline)
2638           (newline)
2639           (newline))
2640         (setq point (point))
2641         ;; (newline 2) doesn't mark both newline's as hard, so call
2642         ;; newline twice. -jas
2643         (newline)
2644         (newline)
2645         (delete-region (point) (re-search-forward "[ \t]*"))
2646         (when (and quoted (not bolp))
2647           (insert quoted leading-space)))
2648       (if quoted
2649           (let* ((adaptive-fill-regexp
2650                   (regexp-quote (concat quoted leading-space)))
2651                  (adaptive-fill-first-line-regexp
2652                   adaptive-fill-regexp ))
2653             (fill-paragraph arg))
2654         (fill-paragraph arg))
2655       (if point (goto-char point)))))
2656
2657 (defun message-fill-paragraph (&optional arg)
2658   "Like `fill-paragraph'."
2659   (interactive (list (if current-prefix-arg 'full)))
2660   (if (and (boundp 'filladapt-mode) filladapt-mode)
2661       nil
2662     (message-newline-and-reformat arg t)
2663     t))
2664
2665 ;; Is it better to use `mail-header-end'?
2666 (defun message-point-in-header-p ()
2667   "Return t if point is in the header."
2668   (save-excursion
2669     (let ((p (point)))
2670       (goto-char (point-min))
2671       (not (re-search-forward
2672             (concat "^" (regexp-quote mail-header-separator) "\n")
2673             p t)))))
2674
2675 (defun message-do-auto-fill ()
2676   "Like `do-auto-fill', but don't fill in message header."
2677   (unless (message-point-in-header-p)
2678     (do-auto-fill)))
2679
2680 (defun message-insert-signature (&optional force)
2681   "Insert a signature.  See documentation for variable `message-signature'."
2682   (interactive (list 0))
2683   (let* ((signature
2684           (cond
2685            ((and (null message-signature)
2686                  (eq force 0))
2687             (save-excursion
2688               (goto-char (point-max))
2689               (not (re-search-backward message-signature-separator nil t))))
2690            ((and (null message-signature)
2691                  force)
2692             t)
2693            ((message-functionp message-signature)
2694             (funcall message-signature))
2695            ((listp message-signature)
2696             (eval message-signature))
2697            (t message-signature)))
2698          (signature
2699           (cond ((stringp signature)
2700                  signature)
2701                 ((and (eq t signature)
2702                       message-signature-file
2703                       (file-exists-p message-signature-file))
2704                  signature))))
2705     (when signature
2706       (goto-char (point-max))
2707       ;; Insert the signature.
2708       (unless (bolp)
2709         (insert "\n"))
2710       (when message-signature-insert-empty-line
2711         (insert "\n"))
2712       (insert "-- \n")
2713       (if (eq signature t)
2714           (insert-file-contents message-signature-file)
2715         (insert signature))
2716       (goto-char (point-max))
2717       (or (bolp) (insert "\n")))))
2718
2719 (defun message-insert-importance-high ()
2720   "Insert header to mark message as important."
2721   (interactive)
2722   (save-excursion
2723     (message-remove-header "Importance")
2724     (message-goto-eoh)
2725     (insert "Importance: high\n")))
2726
2727 (defun message-insert-importance-low ()
2728   "Insert header to mark message as unimportant."
2729   (interactive)
2730   (save-excursion
2731     (message-remove-header "Importance")
2732     (message-goto-eoh)
2733     (insert "Importance: low\n")))
2734
2735 (defun message-insert-or-toggle-importance ()
2736   "Insert a \"Importance: high\" header, or cycle through the header values.
2737 The three allowed values according to RFC 1327 are `high', `normal'
2738 and `low'."
2739   (interactive)
2740   (save-excursion
2741     (let ((valid '("high" "normal" "low"))
2742           (new "high")
2743           cur)
2744       (when (setq cur (message-fetch-field "Importance"))
2745         (message-remove-header "Importance")
2746         (setq new (cond ((string= cur "high")
2747                          "low")
2748                         ((string= cur "low")
2749                          "normal")
2750                         (t
2751                          "high"))))
2752       (message-goto-eoh)
2753       (insert (format "Importance: %s\n" new)))))
2754
2755 (defun message-insert-disposition-notification-to ()
2756   "Request a disposition notification (return receipt) to this message.
2757 Note that this should not be used in newsgroups."
2758   (interactive)
2759   (save-excursion
2760     (message-remove-header "Disposition-Notification-To")
2761     (message-goto-eoh)
2762     (insert (format "Disposition-Notification-To: %s\n"
2763                     (or (message-fetch-field "From") (message-make-from))))))
2764
2765 (defun message-elide-region (b e)
2766   "Elide the text in the region.
2767 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2768 text was killed."
2769   (interactive "r")
2770   (kill-region b e)
2771   (insert message-elide-ellipsis))
2772
2773 (defvar message-caesar-translation-table nil)
2774
2775 (defun message-caesar-region (b e &optional n)
2776   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2777   (interactive
2778    (list
2779     (min (point) (or (mark t) (point)))
2780     (max (point) (or (mark t) (point)))
2781     (when current-prefix-arg
2782       (prefix-numeric-value current-prefix-arg))))
2783
2784   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2785   (unless (or (zerop n)                 ; no action needed for a rot of 0
2786               (= b e))                  ; no region to rotate
2787     ;; We build the table, if necessary.
2788     (when (or (not message-caesar-translation-table)
2789               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2790       (setq message-caesar-translation-table
2791             (message-make-caesar-translation-table n)))
2792     (translate-region b e message-caesar-translation-table)))
2793
2794 (defun message-make-caesar-translation-table (n)
2795   "Create a rot table with offset N."
2796   (let ((i -1)
2797         (table (make-string 256 0)))
2798     (while (< (incf i) 256)
2799       (aset table i i))
2800     (concat
2801      (substring table 0 ?A)
2802      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2803      (substring table ?A (+ ?A n))
2804      (substring table (+ ?A 26) ?a)
2805      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2806      (substring table ?a (+ ?a n))
2807      (substring table (+ ?a 26) 255))))
2808
2809 (defun message-caesar-buffer-body (&optional rotnum)
2810   "Caesar rotate all letters in the current buffer by 13 places.
2811 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2812 With prefix arg, specifies the number of places to rotate each letter forward.
2813 Mail and USENET news headers are not rotated."
2814   (interactive (if current-prefix-arg
2815                    (list (prefix-numeric-value current-prefix-arg))
2816                  (list nil)))
2817   (save-excursion
2818     (save-restriction
2819       (when (message-goto-body)
2820         (narrow-to-region (point) (point-max)))
2821       (message-caesar-region (point-min) (point-max) rotnum))))
2822
2823 (defun message-pipe-buffer-body (program)
2824   "Pipe the message body in the current buffer through PROGRAM."
2825   (save-excursion
2826     (save-restriction
2827       (when (message-goto-body)
2828         (narrow-to-region (point) (point-max)))
2829       (shell-command-on-region
2830        (point-min) (point-max) program nil t))))
2831
2832 (defun message-rename-buffer (&optional enter-string)
2833   "Rename the *message* buffer to \"*message* RECIPIENT\".
2834 If the function is run with a prefix, it will ask for a new buffer
2835 name, rather than giving an automatic name."
2836   (interactive "Pbuffer name: ")
2837   (save-excursion
2838     (save-restriction
2839       (goto-char (point-min))
2840       (narrow-to-region (point)
2841                         (search-forward mail-header-separator nil 'end))
2842       (let* ((mail-to (or
2843                        (if (message-news-p) (message-fetch-field "Newsgroups")
2844                          (message-fetch-field "To"))
2845                        ""))
2846              (mail-trimmed-to
2847               (if (string-match "," mail-to)
2848                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2849                 mail-to))
2850              (name-default (concat "*message* " mail-trimmed-to))
2851              (name (if enter-string
2852                        (read-string "New buffer name: " name-default)
2853                      name-default)))
2854         (rename-buffer name t)))))
2855
2856 (defun message-fill-yanked-message (&optional justifyp)
2857   "Fill the paragraphs of a message yanked into this one.
2858 Numeric argument means justify as well."
2859   (interactive "P")
2860   (save-excursion
2861     (goto-char (point-min))
2862     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2863     (let ((fill-prefix message-yank-prefix))
2864       (fill-individual-paragraphs (point) (point-max) justifyp))))
2865
2866 (defun message-indent-citation ()
2867   "Modify text just inserted from a message to be cited.
2868 The inserted text should be the region.
2869 When this function returns, the region is again around the modified text.
2870
2871 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2872 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2873   (let ((start (point)))
2874     ;; Remove unwanted headers.
2875     (when message-ignored-cited-headers
2876       (let (all-removed)
2877         (save-restriction
2878           (narrow-to-region
2879            (goto-char start)
2880            (if (search-forward "\n\n" nil t)
2881                (1- (point))
2882              (point)))
2883           (message-remove-header message-ignored-cited-headers t)
2884           (when (= (point-min) (point-max))
2885             (setq all-removed t))
2886           (goto-char (point-max)))
2887         (if all-removed
2888             (goto-char start)
2889           (forward-line 1))))
2890     ;; Delete blank lines at the start of the buffer.
2891     (while (and (point-min)
2892                 (eolp)
2893                 (not (eobp)))
2894       (message-delete-line))
2895     ;; Delete blank lines at the end of the buffer.
2896     (goto-char (point-max))
2897     (unless (eolp)
2898       (insert "\n"))
2899     (while (and (zerop (forward-line -1))
2900                 (looking-at "$"))
2901       (message-delete-line))
2902     ;; Do the indentation.
2903     (if (null message-yank-prefix)
2904         (indent-rigidly start (mark t) message-indentation-spaces)
2905       (save-excursion
2906         (goto-char start)
2907         (while (< (point) (mark t))
2908           (if (or (looking-at ">") (looking-at "^$"))
2909               (insert message-yank-cited-prefix)
2910             (insert message-yank-prefix))
2911           (forward-line 1))))
2912     (goto-char start)))
2913
2914 (defun message-yank-original (&optional arg)
2915   "Insert the message being replied to, if any.
2916 Puts point before the text and mark after.
2917 Normally indents each nonblank line ARG spaces (default 3).  However,
2918 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2919
2920 This function uses `message-cite-function' to do the actual citing.
2921
2922 Just \\[universal-argument] as argument means don't indent, insert no
2923 prefix, and don't delete any headers."
2924   (interactive "P")
2925   (let ((modified (buffer-modified-p)))
2926     (when (and message-reply-buffer
2927                message-cite-function)
2928       (delete-windows-on message-reply-buffer t)
2929       (insert-buffer message-reply-buffer)
2930       (unless arg
2931         (funcall message-cite-function))
2932       (message-exchange-point-and-mark)
2933       (unless (bolp)
2934         (insert ?\n))
2935       (unless modified
2936         (setq message-checksum (message-checksum))))))
2937
2938 (defun message-yank-buffer (buffer)
2939   "Insert BUFFER into the current buffer and quote it."
2940   (interactive "bYank buffer: ")
2941   (let ((message-reply-buffer buffer))
2942     (save-window-excursion
2943       (message-yank-original))))
2944
2945 (defun message-buffers ()
2946   "Return a list of active message buffers."
2947   (let (buffers)
2948     (save-excursion
2949       (dolist (buffer (buffer-list t))
2950         (set-buffer buffer)
2951         (when (and (eq major-mode 'message-mode)
2952                    (null message-sent-message-via))
2953           (push (buffer-name buffer) buffers))))
2954     (nreverse buffers)))
2955
2956 (defun message-cite-original-without-signature ()
2957   "Cite function in the standard Message manner."
2958   (let ((start (point))
2959         (end (mark t))
2960         (functions
2961          (when message-indent-citation-function
2962            (if (listp message-indent-citation-function)
2963                message-indent-citation-function
2964              (list message-indent-citation-function)))))
2965     (mml-quote-region start end)
2966     ;; Allow undoing.
2967     (undo-boundary)
2968     (goto-char end)
2969     (when (re-search-backward message-signature-separator start t)
2970       ;; Also peel off any blank lines before the signature.
2971       (forward-line -1)
2972       (while (looking-at "^[ \t]*$")
2973         (forward-line -1))
2974       (forward-line 1)
2975       (delete-region (point) end)
2976       (unless (search-backward "\n\n" start t)
2977         ;; Insert a blank line if it is peeled off.
2978         (insert "\n")))
2979     (goto-char start)
2980     (while functions
2981       (funcall (pop functions)))
2982     (when message-citation-line-function
2983       (unless (bolp)
2984         (insert "\n"))
2985       (funcall message-citation-line-function))))
2986
2987 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
2988 (defun message-cite-original ()
2989   "Cite function in the standard Message manner."
2990   (if (and (boundp 'mail-citation-hook)
2991            mail-citation-hook)
2992       (run-hooks 'mail-citation-hook)
2993     (let ((start (point))
2994           (end (mark t))
2995           (functions
2996            (when message-indent-citation-function
2997              (if (listp message-indent-citation-function)
2998                  message-indent-citation-function
2999                (list message-indent-citation-function)))))
3000       (mml-quote-region start end)
3001       (goto-char start)
3002       (while functions
3003         (funcall (pop functions)))
3004       (when message-citation-line-function
3005         (unless (bolp)
3006           (insert "\n"))
3007         (funcall message-citation-line-function)))))
3008
3009 (defun message-insert-citation-line ()
3010   "Insert a simple citation line."
3011   (when message-reply-headers
3012     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3013
3014 (defun message-position-on-field (header &rest afters)
3015   (let ((case-fold-search t))
3016     (save-restriction
3017       (narrow-to-region
3018        (goto-char (point-min))
3019        (progn
3020          (re-search-forward
3021           (concat "^" (regexp-quote mail-header-separator) "$"))
3022          (match-beginning 0)))
3023       (goto-char (point-min))
3024       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3025           (progn
3026             (re-search-forward "^[^ \t]" nil 'move)
3027             (beginning-of-line)
3028             (skip-chars-backward "\n")
3029             t)
3030         (while (and afters
3031                     (not (re-search-forward
3032                           (concat "^" (regexp-quote (car afters)) ":")
3033                           nil t)))
3034           (pop afters))
3035         (when afters
3036           (re-search-forward "^[^ \t]" nil 'move)
3037           (beginning-of-line))
3038         (insert header ": \n")
3039         (forward-char -1)
3040         nil))))
3041
3042 (defun message-remove-signature ()
3043   "Remove the signature from the text between point and mark.
3044 The text will also be indented the normal way."
3045   (save-excursion
3046     (let ((start (point))
3047           mark)
3048       (if (not (re-search-forward message-signature-separator (mark t) t))
3049           ;; No signature here, so we just indent the cited text.
3050           (message-indent-citation)
3051         ;; Find the last non-empty line.
3052         (forward-line -1)
3053         (while (looking-at "[ \t]*$")
3054           (forward-line -1))
3055         (forward-line 1)
3056         (setq mark (set-marker (make-marker) (point)))
3057         (goto-char start)
3058         (message-indent-citation)
3059         ;; Enable undoing the deletion.
3060         (undo-boundary)
3061         (delete-region mark (mark t))
3062         (set-marker mark nil)))))
3063
3064 \f
3065
3066 ;;;
3067 ;;; Sending messages
3068 ;;;
3069
3070 (defun message-send-and-exit (&optional arg)
3071   "Send message like `message-send', then, if no errors, exit from mail buffer."
3072   (interactive "P")
3073   (let ((buf (current-buffer))
3074         (actions message-exit-actions))
3075     (when (and (message-send arg)
3076                (buffer-name buf))
3077       (if message-kill-buffer-on-exit
3078           (kill-buffer buf)
3079         (bury-buffer buf)
3080         (when (eq buf (current-buffer))
3081           (message-bury buf)))
3082       (message-do-actions actions)
3083       t)))
3084
3085 (defun message-dont-send ()
3086   "Don't send the message you have been editing.
3087 Instead, just auto-save the buffer and then bury it."
3088   (interactive)
3089   (set-buffer-modified-p t)
3090   (save-buffer)
3091   (let ((actions message-postpone-actions))
3092     (message-bury (current-buffer))
3093     (message-do-actions actions)))
3094
3095 (defun message-kill-buffer ()
3096   "Kill the current buffer."
3097   (interactive)
3098   (when (or (not (buffer-modified-p))
3099             (yes-or-no-p "Message modified; kill anyway? "))
3100     (let ((actions message-kill-actions)
3101           (draft-article message-draft-article)
3102           (auto-save-file-name buffer-auto-save-file-name)
3103           (file-name buffer-file-name)
3104           (modified (buffer-modified-p)))
3105       (setq buffer-file-name nil)
3106       (kill-buffer (current-buffer))
3107       (when (and (or (and auto-save-file-name
3108                           (file-exists-p auto-save-file-name))
3109                      (and file-name
3110                           (file-exists-p file-name)))
3111                (yes-or-no-p (format "Remove the backup file%s? "
3112                                     (if modified " too" ""))))
3113         (ignore-errors
3114           (delete-file auto-save-file-name))
3115         (let ((message-draft-article draft-article))
3116           (message-disassociate-draft)))
3117       (message-do-actions actions))))
3118
3119 (defun message-bury (buffer)
3120   "Bury this mail BUFFER."
3121   (let ((newbuf (other-buffer buffer)))
3122     (bury-buffer buffer)
3123     (if (and (fboundp 'frame-parameters)
3124              (cdr (assq 'dedicated (frame-parameters)))
3125              (not (null (delq (selected-frame) (visible-frame-list)))))
3126         (delete-frame (selected-frame))
3127       (switch-to-buffer newbuf))))
3128
3129 (defun message-send (&optional arg)
3130   "Send the message in the current buffer.
3131 If `message-interactive' is non-nil, wait for success indication or
3132 error messages, and inform user.
3133 Otherwise any failure is reported in a message back to the user from
3134 the mailer.
3135 The usage of ARG is defined by the instance that called Message.
3136 It should typically alter the sending method in some way or other."
3137   (interactive "P")
3138   ;; Make it possible to undo the coming changes.
3139   (undo-boundary)
3140   (let ((inhibit-read-only t))
3141     (put-text-property (point-min) (point-max) 'read-only nil))
3142   (message-fix-before-sending)
3143   (run-hooks 'message-send-hook)
3144   (message message-sending-message)
3145   (let ((alist message-send-method-alist)
3146         (success t)
3147         elem sent dont-barf-on-no-method
3148         (message-options message-options))
3149     (message-options-set-recipient)
3150     (while (and success
3151                 (setq elem (pop alist)))
3152       (when (funcall (cadr elem))
3153         (when (and (or (not (memq (car elem)
3154                                   message-sent-message-via))
3155                        (not (message-fetch-field "supersedes"))
3156                        (if (or (message-gnksa-enable-p 'multiple-copies)
3157                                (not (eq (car elem) 'news)))
3158                            (y-or-n-p
3159                             (format
3160                              "Already sent message via %s; resend? "
3161                              (car elem)))
3162                          (error "Denied posting -- multiple copies")))
3163                    (setq success (funcall (caddr elem) arg)))
3164           (setq sent t))))
3165     (unless (or sent
3166                 (not success)
3167                 (let ((fcc (message-fetch-field "Fcc"))
3168                       (gcc (message-fetch-field "Gcc")))
3169                   (when (or fcc gcc)
3170                     (or (eq message-allow-no-recipients 'always)
3171                         (and (not (eq message-allow-no-recipients 'never))
3172                              (setq dont-barf-on-no-method
3173                                    (gnus-y-or-n-p
3174                                     (format "No receiver, perform %s anyway? "
3175                                             (cond ((and fcc gcc) "Fcc and Gcc")
3176                                                   (fcc "Fcc")
3177                                                   (t "Gcc"))))))))))
3178       (error "No methods specified to send by"))
3179     (when (or dont-barf-on-no-method
3180               (and success sent))
3181       (message-do-fcc)
3182       (save-excursion
3183         (run-hooks 'message-sent-hook))
3184       (message "Sending...done")
3185       ;; Mark the buffer as unmodified and delete auto-save.
3186       (set-buffer-modified-p nil)
3187       (delete-auto-save-file-if-necessary t)
3188       (message-disassociate-draft)
3189       ;; Delete other mail buffers and stuff.
3190       (message-do-send-housekeeping)
3191       (message-do-actions message-send-actions)
3192       ;; Return success.
3193       t)))
3194
3195 (defun message-send-via-mail (arg)
3196   "Send the current message via mail."
3197   (message-send-mail arg))
3198
3199 (defun message-send-via-news (arg)
3200   "Send the current message via news."
3201   (funcall message-send-news-function arg))
3202
3203 (defmacro message-check (type &rest forms)
3204   "Eval FORMS if TYPE is to be checked."
3205   `(or (message-check-element ,type)
3206        (save-excursion
3207          ,@forms)))
3208
3209 (put 'message-check 'lisp-indent-function 1)
3210 (put 'message-check 'edebug-form-spec '(form body))
3211
3212 (defun message-text-with-property (prop)
3213   "Return a list of all points where the text has PROP."
3214   (let ((points nil)
3215         (point (point-min)))
3216     (save-excursion
3217       (while (< point (point-max))
3218         (when (get-text-property point prop)
3219           (push point points))
3220         (incf point)))
3221     (nreverse points)))
3222
3223 (defun message-fix-before-sending ()
3224   "Do various things to make the message nice before sending it."
3225   ;; Make sure there's a newline at the end of the message.
3226   (goto-char (point-max))
3227   (unless (bolp)
3228     (insert "\n"))
3229   ;; Delete all invisible text.
3230   (message-check 'invisible-text
3231     (let ((points (message-text-with-property 'invisible)))
3232       (when points
3233         (goto-char (car points))
3234         (dolist (point points)
3235           (add-text-properties point (1+ point)
3236                                '(invisible nil face highlight
3237                                            font-lock-face highlight)))
3238         (unless (yes-or-no-p
3239                  "Invisible text found and made visible; continue posting? ")
3240           (error "Invisible text found and made visible")))))
3241   (message-check 'illegible-text
3242     (let (found choice)
3243       (message-goto-body)
3244       (skip-chars-forward mm-7bit-chars)
3245       (while (not (eobp))
3246         (when (let ((char (char-after)))
3247                 (or (< (mm-char-int char) 128)
3248                     (and (mm-multibyte-p)
3249                          (memq (char-charset char)
3250                                '(eight-bit-control eight-bit-graphic
3251                                                    control-1)))))
3252           (add-text-properties (point) (1+ (point))
3253                                '(font-lock-face highlight face highlight))
3254           (setq found t))
3255         (forward-char)
3256         (skip-chars-forward mm-7bit-chars))
3257       (when found
3258         (setq choice
3259               (gnus-multiple-choice
3260                "Illegible text found.  Continue posting?"
3261                '((?d "Remove and continue posting")
3262                  (?r "Replace with dots and continue posting")
3263                  (?i "Ignore and continue posting")
3264                  (?e "Continue editing"))))
3265         (if (eq choice ?e)
3266           (error "Illegible text found"))
3267         (message-goto-body)
3268         (skip-chars-forward mm-7bit-chars)
3269         (while (not (eobp))
3270           (when (let ((char (char-after)))
3271                   (or (< (mm-char-int char) 128)
3272                       (and (mm-multibyte-p)
3273                            (memq (char-charset char)
3274                                  '(eight-bit-control eight-bit-graphic
3275                                                      control-1)))))
3276             (if (eq choice ?i)
3277                 (remove-text-properties (point) (1+ (point))
3278                                         '(font-lock-face highlight face highlight))
3279               (delete-char 1)
3280               (when (eq choice ?r)
3281                 (insert "."))))
3282           (forward-char)
3283           (skip-chars-forward mm-7bit-chars))))))
3284
3285 (defun message-add-action (action &rest types)
3286   "Add ACTION to be performed when doing an exit of type TYPES."
3287   (while types
3288     (add-to-list (intern (format "message-%s-actions" (pop types)))
3289                  action)))
3290
3291 (defun message-delete-action (action &rest types)
3292   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3293   (let (var)
3294     (while types
3295       (set (setq var (intern (format "message-%s-actions" (pop types))))
3296            (delq action (symbol-value var))))))
3297
3298 (defun message-do-actions (actions)
3299   "Perform all actions in ACTIONS."
3300   ;; Now perform actions on successful sending.
3301   (while actions
3302     (ignore-errors
3303       (cond
3304        ;; A simple function.
3305        ((message-functionp (car actions))
3306         (funcall (car actions)))
3307        ;; Something to be evaled.
3308        (t
3309         (eval (car actions)))))
3310     (pop actions)))
3311
3312 (defun message-send-mail-partially ()
3313   "Send mail as message/partial."
3314   ;; replace the header delimiter with a blank line
3315   (goto-char (point-min))
3316   (re-search-forward
3317    (concat "^" (regexp-quote mail-header-separator) "\n"))
3318   (replace-match "\n")
3319   (run-hooks 'message-send-mail-hook)
3320   (let ((p (goto-char (point-min)))
3321         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3322         (curbuf (current-buffer))
3323         (id (message-make-message-id)) (n 1)
3324         plist total  header required-mail-headers)
3325     (while (not (eobp))
3326       (if (< (point-max) (+ p message-send-mail-partially-limit))
3327           (goto-char (point-max))
3328         (goto-char (+ p message-send-mail-partially-limit))
3329         (beginning-of-line)
3330         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3331       (push p plist)
3332       (setq p (point)))
3333     (setq total (length plist))
3334     (push (point-max) plist)
3335     (setq plist (nreverse plist))
3336     (unwind-protect
3337         (save-excursion
3338           (setq p (pop plist))
3339           (while plist
3340             (set-buffer curbuf)
3341             (copy-to-buffer tembuf p (car plist))
3342             (set-buffer tembuf)
3343             (goto-char (point-min))
3344             (if header
3345                 (progn
3346                   (goto-char (point-min))
3347                   (narrow-to-region (point) (point))
3348                   (insert header))
3349               (message-goto-eoh)
3350               (setq header (buffer-substring (point-min) (point)))
3351               (goto-char (point-min))
3352               (narrow-to-region (point) (point))
3353               (insert header)
3354               (message-remove-header "Mime-Version")
3355               (message-remove-header "Content-Type")
3356               (message-remove-header "Content-Transfer-Encoding")
3357               (message-remove-header "Message-ID")
3358               (message-remove-header "Lines")
3359               (goto-char (point-max))
3360               (insert "Mime-Version: 1.0\n")
3361               (setq header (buffer-substring (point-min) (point-max))))
3362             (goto-char (point-max))
3363             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3364                             id n total))
3365             (forward-char -1)
3366             (let ((mail-header-separator ""))
3367               (when (memq 'Message-ID message-required-mail-headers)
3368                 (insert "Message-ID: " (message-make-message-id) "\n"))
3369               (when (memq 'Lines message-required-mail-headers)
3370                 (insert "Lines: " (message-make-lines) "\n"))
3371               (message-goto-subject)
3372               (end-of-line)
3373               (insert (format " (%d/%d)" n total))
3374               (widen)
3375               (mm-with-unibyte-current-buffer
3376                 (funcall (or message-send-mail-real-function
3377                              message-send-mail-function))))
3378             (setq n (+ n 1))
3379             (setq p (pop plist))
3380             (erase-buffer)))
3381       (kill-buffer tembuf))))
3382
3383 (defun message-send-mail (&optional arg)
3384   (require 'mail-utils)
3385   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3386          (case-fold-search nil)
3387          (news (message-news-p))
3388          (mailbuf (current-buffer))
3389          (message-this-is-mail t)
3390          (message-posting-charset
3391           (if (fboundp 'gnus-setup-posting-charset)
3392               (gnus-setup-posting-charset nil)
3393             message-posting-charset))
3394          (headers message-required-mail-headers))
3395     (save-restriction
3396       (message-narrow-to-headers)
3397       ;; Generate the Mail-Followup-To header if the header is not there...
3398       (if (and (message-subscribed-p)
3399                (not (mail-fetch-field "mail-followup-to")))
3400           (setq headers
3401                 (cons
3402                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
3403                  message-required-mail-headers))
3404         ;; otherwise, delete the MFT header if the field is empty
3405         (when (equal "" (mail-fetch-field "mail-followup-to"))
3406           (message-remove-header "^Mail-Followup-To:")))
3407       ;; Insert some headers.
3408       (let ((message-deletable-headers
3409              (if news nil message-deletable-headers)))
3410         (message-generate-headers headers))
3411       ;; Let the user do all of the above.
3412       (run-hooks 'message-header-hook))
3413     (unwind-protect
3414         (save-excursion
3415           (set-buffer tembuf)
3416           (erase-buffer)
3417           ;; Avoid copying text props (except hard newlines).
3418           (insert (with-current-buffer mailbuf
3419                     (mml-buffer-substring-no-properties-except-hard-newlines
3420                      (point-min) (point-max))))
3421           ;; Remove some headers.
3422           (message-encode-message-body)
3423           (save-restriction
3424             (message-narrow-to-headers)
3425             ;; We (re)generate the Lines header.
3426             (when (memq 'Lines message-required-mail-headers)
3427               (message-generate-headers '(Lines)))
3428             ;; Remove some headers.
3429             (message-remove-header message-ignored-mail-headers t)
3430             (let ((mail-parse-charset message-default-charset))
3431               (mail-encode-encoded-word-buffer)))
3432           (goto-char (point-max))
3433           ;; require one newline at the end.
3434           (or (= (preceding-char) ?\n)
3435               (insert ?\n))
3436           (message-cleanup-headers)
3437           (when
3438               (save-restriction
3439                 (message-narrow-to-headers)
3440                 (and news
3441                      (or (message-fetch-field "cc")
3442                          (message-fetch-field "to"))
3443                      (let ((content-type (message-fetch-field "content-type")))
3444                        (or
3445                         (not content-type)
3446                         (string= "text/plain"
3447                                  (car
3448                                   (mail-header-parse-content-type
3449                                    content-type)))))))
3450             (message-insert-courtesy-copy))
3451           (if (or (not message-send-mail-partially-limit)
3452                   (< (point-max) message-send-mail-partially-limit)
3453                   (not (message-y-or-n-p
3454                         "The message size is too large, split? "
3455                         t
3456                         "\
3457 The message size, "
3458                         (/ (point-max) 1000) "KB, is too large.
3459
3460 Some mail gateways (MTA's) bounce large messages.  To avoid the
3461 problem, answer `y', and the message will be split into several
3462 smaller pieces, the size of each is about "
3463                         (/ message-send-mail-partially-limit 1000)
3464                         "KB except the last
3465 one.
3466
3467 However, some mail readers (MUA's) can't read split messages, i.e.,
3468 mails in message/partially format. Answer `n', and the message will be
3469 sent in one piece.
3470
3471 The size limit is controlled by `message-send-mail-partially-limit'.
3472 If you always want Gnus to send messages in one piece, set
3473 `message-send-mail-partially-limit' to nil.
3474 ")))
3475               (mm-with-unibyte-current-buffer
3476                 (message "Sending via mail...")
3477                 (funcall (or message-send-mail-real-function
3478                              message-send-mail-function)))
3479             (message-send-mail-partially)))
3480       (kill-buffer tembuf))
3481     (set-buffer mailbuf)
3482     (push 'mail message-sent-message-via)))
3483
3484 (defun message-send-mail-with-sendmail ()
3485   "Send off the prepared buffer with sendmail."
3486   (let ((errbuf (if message-interactive
3487                     (message-generate-new-buffer-clone-locals
3488                      " sendmail errors")
3489                   0))
3490         resend-to-addresses delimline)
3491     (unwind-protect
3492         (progn
3493           (let ((case-fold-search t))
3494             (save-restriction
3495               (message-narrow-to-headers)
3496               (setq resend-to-addresses (message-fetch-field "resent-to")))
3497             ;; Change header-delimiter to be what sendmail expects.
3498             (goto-char (point-min))
3499             (re-search-forward
3500              (concat "^" (regexp-quote mail-header-separator) "\n"))
3501             (replace-match "\n")
3502             (backward-char 1)
3503             (setq delimline (point-marker))
3504             (run-hooks 'message-send-mail-hook)
3505             ;; Insert an extra newline if we need it to work around
3506             ;; Sun's bug that swallows newlines.
3507             (goto-char (1+ delimline))
3508             (when (eval message-mailer-swallows-blank-line)
3509               (newline))
3510             (when message-interactive
3511               (save-excursion
3512                 (set-buffer errbuf)
3513                 (erase-buffer))))
3514           (let* ((default-directory "/")
3515                  (coding-system-for-write message-send-coding-system)
3516                  (cpr (apply
3517                        'call-process-region
3518                        (append
3519                         (list (point-min) (point-max)
3520                               (if (boundp 'sendmail-program)
3521                                   sendmail-program
3522                                 "/usr/lib/sendmail")
3523                               nil errbuf nil "-oi")
3524                         ;; Always specify who from,
3525                         ;; since some systems have broken sendmails.
3526                         ;; But some systems are more broken with -f, so
3527                         ;; we'll let users override this.
3528                         (if (null message-sendmail-f-is-evil)
3529                             (list "-f" (message-make-address)))
3530                         ;; These mean "report errors by mail"
3531                         ;; and "deliver in background".
3532                         (if (null message-interactive) '("-oem" "-odb"))
3533                         ;; Get the addresses from the message
3534                         ;; unless this is a resend.
3535                         ;; We must not do that for a resend
3536                         ;; because we would find the original addresses.
3537                         ;; For a resend, include the specific addresses.
3538                         (if resend-to-addresses
3539                             (list resend-to-addresses)
3540                           '("-t"))))))
3541             (unless (or (null cpr) (zerop cpr))
3542               (error "Sending...failed with exit value %d" cpr)))
3543           (when message-interactive
3544             (save-excursion
3545               (set-buffer errbuf)
3546               (goto-char (point-min))
3547               (while (re-search-forward "\n\n* *" nil t)
3548                 (replace-match "; "))
3549               (if (not (zerop (buffer-size)))
3550                   (error "Sending...failed to %s"
3551                          (buffer-substring (point-min) (point-max)))))))
3552       (when (bufferp errbuf)
3553         (kill-buffer errbuf)))))
3554
3555 (defun message-send-mail-with-qmail ()
3556   "Pass the prepared message buffer to qmail-inject.
3557 Refer to the documentation for the variable `message-send-mail-function'
3558 to find out how to use this."
3559   ;; replace the header delimiter with a blank line
3560   (goto-char (point-min))
3561   (re-search-forward
3562    (concat "^" (regexp-quote mail-header-separator) "\n"))
3563   (replace-match "\n")
3564   (run-hooks 'message-send-mail-hook)
3565   ;; send the message
3566   (case
3567       (let ((coding-system-for-write message-send-coding-system))
3568         (apply
3569          'call-process-region 1 (point-max) message-qmail-inject-program
3570          nil nil nil
3571          ;; qmail-inject's default behaviour is to look for addresses on the
3572          ;; command line; if there're none, it scans the headers.
3573          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3574          ;;
3575          ;; in general, ALL of qmail-inject's defaults are perfect for simply
3576          ;; reading a formatted (i. e., at least a To: or Resent-To header)
3577          ;; message from stdin.
3578          ;;
3579          ;; qmail also has the advantage of not having been raped by
3580          ;; various vendors, so we don't have to allow for that, either --
3581          ;; compare this with message-send-mail-with-sendmail and weep
3582          ;; for sendmail's lost innocence.
3583          ;;
3584          ;; all this is way cool coz it lets us keep the arguments entirely
3585          ;; free for -inject-arguments -- a big win for the user and for us
3586          ;; since we don't have to play that double-guessing game and the user
3587          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3588          (if (message-functionp message-qmail-inject-args)
3589              (funcall message-qmail-inject-args)
3590            message-qmail-inject-args)))
3591     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3592     ;; we have to look at the retval instead
3593     (0 nil)
3594     (100 (error "qmail-inject reported permanent failure"))
3595     (111 (error "qmail-inject reported transient failure"))
3596     ;; should never happen
3597     (t   (error "qmail-inject reported unknown failure"))))
3598
3599 (defun message-send-mail-with-mh ()
3600   "Send the prepared message buffer with mh."
3601   (let ((mh-previous-window-config nil)
3602         (name (mh-new-draft-name)))
3603     (setq buffer-file-name name)
3604     ;; MH wants to generate these headers itself.
3605     (when message-mh-deletable-headers
3606       (let ((headers message-mh-deletable-headers))
3607         (while headers
3608           (goto-char (point-min))
3609           (and (re-search-forward
3610                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3611                (message-delete-line))
3612           (pop headers))))
3613     (run-hooks 'message-send-mail-hook)
3614     ;; Pass it on to mh.
3615     (mh-send-letter)))
3616
3617 (defun message-smtpmail-send-it ()
3618   "Send the prepared message buffer with `smtpmail-send-it'.
3619 This only differs from `smtpmail-send-it' that this command evaluates
3620 `message-send-mail-hook' just before sending a message.  It is useful
3621 if your ISP requires the POP-before-SMTP authentication.  See the
3622 documentation for the function `mail-source-touch-pop'."
3623   (run-hooks 'message-send-mail-hook)
3624   (smtpmail-send-it))
3625
3626 (defun message-canlock-generate ()
3627   "Return a string that is non-trival to guess.
3628 Do not use this for anything important, it is cryptographically weak."
3629   (let (sha1-maximum-internal-length)
3630     (sha1 (concat (message-unique-id)
3631                   (format "%x%x%x" (random) (random t) (random))
3632                   (prin1-to-string (recent-keys))
3633                   (prin1-to-string (garbage-collect))))))
3634
3635 (defun message-canlock-password ()
3636   "The password used by message for cancel locks.
3637 This is the value of `canlock-password', if that option is non-nil.
3638 Otherwise, generate and save a value for `canlock-password' first."
3639   (unless canlock-password
3640     (customize-save-variable 'canlock-password (message-canlock-generate))
3641     (setq canlock-password-for-verify canlock-password))
3642   canlock-password)
3643
3644 (defun message-insert-canlock ()
3645   (when message-insert-canlock
3646     (message-canlock-password)
3647     (canlock-insert-header)))
3648
3649 (defun message-send-news (&optional arg)
3650   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3651          (case-fold-search nil)
3652          (method (if (message-functionp message-post-method)
3653                      (funcall message-post-method arg)
3654                    message-post-method))
3655          (newsgroups-field (save-restriction
3656                             (message-narrow-to-headers-or-head)
3657                             (message-fetch-field "Newsgroups")))
3658          (followup-field (save-restriction
3659                            (message-narrow-to-headers-or-head)
3660                            (message-fetch-field "Followup-To")))
3661          ;; BUG: We really need to get the charset for each name in the
3662          ;; Newsgroups and Followup-To lines to allow crossposting
3663          ;; between group namess with incompatible character sets.
3664          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3665          (group-field-charset
3666           (gnus-group-name-charset method newsgroups-field))
3667          (followup-field-charset
3668           (gnus-group-name-charset method (or followup-field "")))
3669          (rfc2047-header-encoding-alist
3670           (append (when group-field-charset
3671                     (list (cons "Newsgroups" group-field-charset)))
3672                   (when followup-field-charset
3673                     (list (cons "Followup-To" followup-field-charset)))
3674                   rfc2047-header-encoding-alist))
3675          (messbuf (current-buffer))
3676          (message-syntax-checks
3677           (if (and arg
3678                    (listp message-syntax-checks))
3679               (cons '(existing-newsgroups . disabled)
3680                     message-syntax-checks)
3681             message-syntax-checks))
3682          (message-this-is-news t)
3683          (message-posting-charset
3684           (gnus-setup-posting-charset newsgroups-field))
3685          result)
3686     (if (not (message-check-news-body-syntax))
3687         nil
3688       (save-restriction
3689         (message-narrow-to-headers)
3690         ;; Insert some headers.
3691         (message-generate-headers message-required-news-headers)
3692         (message-insert-canlock)
3693         ;; Let the user do all of the above.
3694         (run-hooks 'message-header-hook))
3695       ;; Note: This check will be disabled by the ".*" default value for
3696       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3697       (when (and group-field-charset
3698                  (listp message-syntax-checks))
3699         (setq message-syntax-checks
3700               (cons '(valid-newsgroups . disabled)
3701                     message-syntax-checks)))
3702       (message-cleanup-headers)
3703       (if (not (let ((message-post-method method))
3704                  (message-check-news-syntax)))
3705           nil
3706         (unwind-protect
3707             (save-excursion
3708               (set-buffer tembuf)
3709               (buffer-disable-undo)
3710               (erase-buffer)
3711               ;; Avoid copying text props (except hard newlines).
3712               (insert
3713                (with-current-buffer messbuf
3714                  (mml-buffer-substring-no-properties-except-hard-newlines
3715                   (point-min) (point-max))))
3716               (message-encode-message-body)
3717               ;; Remove some headers.
3718               (save-restriction
3719                 (message-narrow-to-headers)
3720                 ;; We (re)generate the Lines header.
3721                 (when (memq 'Lines message-required-mail-headers)
3722                   (message-generate-headers '(Lines)))
3723                 ;; Remove some headers.
3724                 (message-remove-header message-ignored-news-headers t)
3725                 (let ((mail-parse-charset message-default-charset))
3726                   (mail-encode-encoded-word-buffer)))
3727               (goto-char (point-max))
3728               ;; require one newline at the end.
3729               (or (= (preceding-char) ?\n)
3730                   (insert ?\n))
3731               (let ((case-fold-search t))
3732                 ;; Remove the delimiter.
3733                 (goto-char (point-min))
3734                 (re-search-forward
3735                  (concat "^" (regexp-quote mail-header-separator) "\n"))
3736                 (replace-match "\n")
3737                 (backward-char 1))
3738               (run-hooks 'message-send-news-hook)
3739               (gnus-open-server method)
3740               (message "Sending news via %s..." (gnus-server-string method))
3741               (setq result (let ((mail-header-separator ""))
3742                              (gnus-request-post method))))
3743           (kill-buffer tembuf))
3744         (set-buffer messbuf)
3745         (if result
3746             (push 'news message-sent-message-via)
3747           (message "Couldn't send message via news: %s"
3748                    (nnheader-get-report (car method)))
3749           nil)))))
3750
3751 ;;;
3752 ;;; Header generation & syntax checking.
3753 ;;;
3754
3755 (defun message-check-element (type)
3756   "Return non-nil if this TYPE is not to be checked."
3757   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3758       t
3759     (let ((able (assq type message-syntax-checks)))
3760       (and (consp able)
3761            (eq (cdr able) 'disabled)))))
3762
3763 (defun message-check-news-syntax ()
3764   "Check the syntax of the message."
3765   (save-excursion
3766     (save-restriction
3767       (widen)
3768       ;; We narrow to the headers and check them first.
3769       (save-excursion
3770         (save-restriction
3771           (message-narrow-to-headers)
3772           (message-check-news-header-syntax))))))
3773
3774 (defun message-check-news-header-syntax ()
3775   (and
3776    ;; Check Newsgroups header.
3777    (message-check 'newsgroups
3778      (let ((group (message-fetch-field "newsgroups")))
3779        (or
3780         (and group
3781              (not (string-match "\\`[ \t]*\\'" group)))
3782         (ignore
3783          (message
3784           "The newsgroups field is empty or missing.  Posting is denied.")))))
3785    ;; Check the Subject header.
3786    (message-check 'subject
3787      (let* ((case-fold-search t)
3788             (subject (message-fetch-field "subject")))
3789        (or
3790         (and subject
3791              (not (string-match "\\`[ \t]*\\'" subject)))
3792         (ignore
3793          (message
3794           "The subject field is empty or missing.  Posting is denied.")))))
3795    ;; Check for commands in Subject.
3796    (message-check 'subject-cmsg
3797      (if (string-match "^cmsg " (message-fetch-field "subject"))
3798          (y-or-n-p
3799           "The control code \"cmsg\" is in the subject.  Really post? ")
3800        t))
3801    ;; Check long header lines.
3802    (message-check 'long-header-lines
3803      (let ((start (point))
3804            (header nil)
3805            (length 0)
3806            found)
3807        (while (and (not found)
3808                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
3809          (if (> (- (point) (match-beginning 0)) 998)
3810              (setq found t
3811                    length (- (point) (match-beginning 0)))
3812            (setq header (match-string-no-properties 1)))
3813          (setq start (match-beginning 0))
3814          (forward-line 1))
3815        (if found
3816            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
3817                              header length))
3818          t)))
3819    ;; Check for multiple identical headers.
3820    (message-check 'multiple-headers
3821      (let (found)
3822        (while (and (not found)
3823                    (re-search-forward "^[^ \t:]+: " nil t))
3824          (save-excursion
3825            (or (re-search-forward
3826                 (concat "^"
3827                         (regexp-quote
3828                          (setq found
3829                                (buffer-substring
3830                                 (match-beginning 0) (- (match-end 0) 2))))
3831                         ":")
3832                 nil t)
3833                (setq found nil))))
3834        (if found
3835            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3836          t)))
3837    ;; Check for Version and Sendsys.
3838    (message-check 'sendsys
3839      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3840          (y-or-n-p
3841           (format "The article contains a %s command.  Really post? "
3842                   (buffer-substring (match-beginning 0)
3843                                     (1- (match-end 0)))))
3844        t))
3845    ;; See whether we can shorten Followup-To.
3846    (message-check 'shorten-followup-to
3847      (let ((newsgroups (message-fetch-field "newsgroups"))
3848            (followup-to (message-fetch-field "followup-to"))
3849            to)
3850        (when (and newsgroups
3851                   (string-match "," newsgroups)
3852                   (not followup-to)
3853                   (not
3854                    (zerop
3855                     (length
3856                      (setq to (completing-read
3857                                "Followups to (default: no Followup-To header) "
3858                                (mapcar (lambda (g) (list g))
3859                                        (cons "poster"
3860                                              (message-tokenize-header
3861                                               newsgroups)))))))))
3862          (goto-char (point-min))
3863          (insert "Followup-To: " to "\n"))
3864        t))
3865    ;; Check "Shoot me".
3866    (message-check 'shoot
3867      (if (re-search-forward
3868           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3869          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3870        t))
3871    ;; Check for Approved.
3872    (message-check 'approved
3873      (if (re-search-forward "^Approved:" nil t)
3874          (y-or-n-p "The article contains an Approved header.  Really post? ")
3875        t))
3876    ;; Check the Message-ID header.
3877    (message-check 'message-id
3878      (let* ((case-fold-search t)
3879             (message-id (message-fetch-field "message-id" t)))
3880        (or (not message-id)
3881            ;; Is there an @ in the ID?
3882            (and (string-match "@" message-id)
3883                 ;; Is there a dot in the ID?
3884                 (string-match "@[^.]*\\." message-id)
3885                 ;; Does the ID end with a dot?
3886                 (not (string-match "\\.>" message-id)))
3887            (y-or-n-p
3888             (format "The Message-ID looks strange: \"%s\".  Really post? "
3889                     message-id)))))
3890    ;; Check the Newsgroups & Followup-To headers.
3891    (message-check 'existing-newsgroups
3892      (let* ((case-fold-search t)
3893             (newsgroups (message-fetch-field "newsgroups"))
3894             (followup-to (message-fetch-field "followup-to"))
3895             (groups (message-tokenize-header
3896                      (if followup-to
3897                          (concat newsgroups "," followup-to)
3898                        newsgroups)))
3899             (post-method (if (message-functionp message-post-method)
3900                              (funcall message-post-method)
3901                            message-post-method))
3902             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3903             ;; would probably involve a new nnoo function.
3904             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3905             (method (if (and (consp post-method)
3906                              (eq (car post-method) 'nnvirtual)
3907                              gnus-message-group-art)
3908                         (let ((group (car (nnvirtual-find-group-art
3909                                            (car gnus-message-group-art)
3910                                            (cdr gnus-message-group-art)))))
3911                           (gnus-find-method-for-group group))
3912                       post-method))
3913             (known-groups
3914              (mapcar (lambda (n)
3915                        (gnus-group-name-decode
3916                         (gnus-group-real-name n)
3917                         (gnus-group-name-charset method n)))
3918                      (gnus-groups-from-server method)))
3919             errors)
3920        (while groups
3921          (unless (or (equal (car groups) "poster")
3922                      (member (car groups) known-groups))
3923            (push (car groups) errors))
3924          (pop groups))
3925        (cond
3926         ;; Gnus is not running.
3927         ((or (not (and (boundp 'gnus-active-hashtb)
3928                        gnus-active-hashtb))
3929              (not (boundp 'gnus-read-active-file)))
3930          t)
3931         ;; We don't have all the group names.
3932         ((and (or (not gnus-read-active-file)
3933                   (eq gnus-read-active-file 'some))
3934               errors)
3935          (y-or-n-p
3936           (format
3937            "Really post to %s possibly unknown group%s: %s? "
3938            (if (= (length errors) 1) "this" "these")
3939            (if (= (length errors) 1) "" "s")
3940            (mapconcat 'identity errors ", "))))
3941         ;; There were no errors.
3942         ((not errors)
3943          t)
3944         ;; There are unknown groups.
3945         (t
3946          (y-or-n-p
3947           (format
3948            "Really post to %s unknown group%s: %s? "
3949            (if (= (length errors) 1) "this" "these")
3950            (if (= (length errors) 1) "" "s")
3951            (mapconcat 'identity errors ", ")))))))
3952    ;; Check continuation headers.
3953    (message-check 'continuation-headers
3954      (goto-char (point-min))
3955      (let ((do-posting t))
3956        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
3957          (if (y-or-n-p "Fix continuation lines? ")
3958              (progn
3959                (goto-char (match-beginning 0))
3960                (insert " "))
3961            (unless (y-or-n-p "Send anyway? ")
3962              (setq do-posting nil))))
3963        do-posting))
3964    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3965    (message-check 'valid-newsgroups
3966      (let ((case-fold-search t)
3967            (headers '("Newsgroups" "Followup-To"))
3968            header error)
3969        (while (and headers (not error))
3970          (when (setq header (mail-fetch-field (car headers)))
3971            (if (or
3972                 (not
3973                  (string-match
3974                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3975                   header))
3976                 (memq
3977                  nil (mapcar
3978                       (lambda (g)
3979                         (not (string-match "\\.\\'\\|\\.\\." g)))
3980                       (message-tokenize-header header ","))))
3981                (setq error t)))
3982          (unless error
3983            (pop headers)))
3984        (if (not error)
3985            t
3986          (y-or-n-p
3987           (format "The %s header looks odd: \"%s\".  Really post? "
3988                   (car headers) header)))))
3989    (message-check 'repeated-newsgroups
3990      (let ((case-fold-search t)
3991            (headers '("Newsgroups" "Followup-To"))
3992            header error groups group)
3993        (while (and headers
3994                    (not error))
3995          (when (setq header (mail-fetch-field (pop headers)))
3996            (setq groups (message-tokenize-header header ","))
3997            (while (setq group (pop groups))
3998              (when (member group groups)
3999                (setq error group
4000                      groups nil)))))
4001        (if (not error)
4002            t
4003          (y-or-n-p
4004           (format "Group %s is repeated in headers.  Really post? " error)))))
4005    ;; Check the From header.
4006    (message-check 'from
4007      (let* ((case-fold-search t)
4008             (from (message-fetch-field "from"))
4009             ad)
4010        (cond
4011         ((not from)
4012          (message "There is no From line.  Posting is denied.")
4013          nil)
4014         ((or (not (string-match
4015                    "@[^\\.]*\\."
4016                    (setq ad (nth 1 (mail-extract-address-components
4017                                     from))))) ;larsi@ifi
4018              (string-match "\\.\\." ad) ;larsi@ifi..uio
4019              (string-match "@\\." ad)   ;larsi@.ifi.uio
4020              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4021              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4022              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4023          (message
4024           "Denied posting -- the From looks strange: \"%s\"." from)
4025          nil)
4026         ((let ((addresses (rfc822-addresses from)))
4027            (while (and addresses
4028                        (not (eq (string-to-char (car addresses)) ?\()))
4029              (setq addresses (cdr addresses)))
4030            addresses)
4031          (message
4032           "Denied posting -- bad From address: \"%s\"." from)
4033          nil)
4034         (t t))))
4035    ;; Check the Reply-To header.
4036    (message-check 'reply-to
4037      (let* ((case-fold-search t)
4038             (reply-to (message-fetch-field "reply-to"))
4039             ad)
4040        (cond
4041         ((not reply-to)
4042          t)
4043         ((string-match "," reply-to)
4044          (y-or-n-p
4045           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4046                   reply-to)))
4047         ((or (not (string-match
4048                    "@[^\\.]*\\."
4049                    (setq ad (nth 1 (mail-extract-address-components
4050                                     reply-to))))) ;larsi@ifi
4051              (string-match "\\.\\." ad) ;larsi@ifi..uio
4052              (string-match "@\\." ad)   ;larsi@.ifi.uio
4053              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4054              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4055              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4056          (y-or-n-p
4057           (format
4058            "The Reply-To looks strange: \"%s\". Really post? "
4059            reply-to)))
4060         (t t))))))
4061
4062 (defun message-check-news-body-syntax ()
4063   (and
4064    ;; Check for long lines.
4065    (message-check 'long-lines
4066      (goto-char (point-min))
4067      (re-search-forward
4068       (concat "^" (regexp-quote mail-header-separator) "$"))
4069      (forward-line 1)
4070      (while (and
4071              (or (looking-at
4072                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
4073                  (let ((p (point)))
4074                    (end-of-line)
4075                    (< (- (point) p) 80)))
4076              (zerop (forward-line 1))))
4077      (or (bolp)
4078          (eobp)
4079          (y-or-n-p
4080           "You have lines longer than 79 characters.  Really post? ")))
4081    ;; Check whether the article is empty.
4082    (message-check 'empty
4083      (goto-char (point-min))
4084      (re-search-forward
4085       (concat "^" (regexp-quote mail-header-separator) "$"))
4086      (forward-line 1)
4087      (let ((b (point)))
4088        (goto-char (point-max))
4089        (re-search-backward message-signature-separator nil t)
4090        (beginning-of-line)
4091        (or (re-search-backward "[^ \n\t]" b t)
4092            (if (message-gnksa-enable-p 'empty-article)
4093                (y-or-n-p "Empty article.  Really post? ")
4094              (message "Denied posting -- Empty article.")
4095              nil))))
4096    ;; Check for control characters.
4097    (message-check 'control-chars
4098      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4099          (y-or-n-p
4100           "The article contains control characters.  Really post? ")
4101        t))
4102    ;; Check excessive size.
4103    (message-check 'size
4104      (if (> (buffer-size) 60000)
4105          (y-or-n-p
4106           (format "The article is %d octets long.  Really post? "
4107                   (buffer-size)))
4108        t))
4109    ;; Check whether any new text has been added.
4110    (message-check 'new-text
4111      (or
4112       (not message-checksum)
4113       (not (eq (message-checksum) message-checksum))
4114       (if (message-gnksa-enable-p 'quoted-text-only)
4115           (y-or-n-p
4116            "It looks like no new text has been added.  Really post? ")
4117         (message "Denied posting -- no new text has been added.")
4118         nil)))
4119    ;; Check the length of the signature.
4120    (message-check 'signature
4121      (goto-char (point-max))
4122      (if (> (count-lines (point) (point-max)) 5)
4123          (y-or-n-p
4124           (format
4125            "Your .sig is %d lines; it should be max 4.  Really post? "
4126            (1- (count-lines (point) (point-max)))))
4127        t))
4128    ;; Ensure that text follows last quoted portion.
4129    (message-check 'quoting-style
4130      (goto-char (point-max))
4131      (let ((no-problem t))
4132        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4133          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4134        (if no-problem
4135            t
4136          (if (message-gnksa-enable-p 'quoted-text-only)
4137              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4138            ;; Ensure that
4139            (goto-char (point-min))
4140            (re-search-forward
4141             (concat "^" (regexp-quote mail-header-separator) "$"))
4142            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4143                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4144              (message "Denied posting -- only quoted text.")
4145              nil)))))))
4146
4147 (defun message-checksum ()
4148   "Return a \"checksum\" for the current buffer."
4149   (let ((sum 0))
4150     (save-excursion
4151       (goto-char (point-min))
4152       (re-search-forward
4153        (concat "^" (regexp-quote mail-header-separator) "$"))
4154       (while (not (eobp))
4155         (when (not (looking-at "[ \t\n]"))
4156           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4157                             (char-after))))
4158         (forward-char 1)))
4159     sum))
4160
4161 (defun message-do-fcc ()
4162   "Process Fcc headers in the current buffer."
4163   (let ((case-fold-search t)
4164         (buf (current-buffer))
4165         list file
4166         (mml-externalize-attachments message-fcc-externalize-attachments))
4167     (save-excursion
4168       (save-restriction
4169         (message-narrow-to-headers)
4170         (setq file (message-fetch-field "fcc" t)))
4171       (when file
4172         (set-buffer (get-buffer-create " *message temp*"))
4173         (erase-buffer)
4174         (insert-buffer-substring buf)
4175         (message-encode-message-body)
4176         (save-restriction
4177           (message-narrow-to-headers)
4178           (while (setq file (message-fetch-field "fcc" t))
4179             (push file list)
4180             (message-remove-header "fcc" nil t))
4181           (let ((mail-parse-charset message-default-charset)
4182                 (rfc2047-header-encoding-alist
4183                  (cons '("Newsgroups" . default)
4184                        rfc2047-header-encoding-alist)))
4185             (mail-encode-encoded-word-buffer)))
4186         (goto-char (point-min))
4187         (when (re-search-forward
4188                (concat "^" (regexp-quote mail-header-separator) "$")
4189                nil t)
4190           (replace-match "" t t ))
4191         ;; Process FCC operations.
4192         (while list
4193           (setq file (pop list))
4194           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4195               ;; Pipe the article to the program in question.
4196               (call-process-region (point-min) (point-max) shell-file-name
4197                                    nil nil nil shell-command-switch
4198                                    (match-string 1 file))
4199             ;; Save the article.
4200             (setq file (expand-file-name file))
4201             (unless (file-exists-p (file-name-directory file))
4202               (make-directory (file-name-directory file) t))
4203             (if (and message-fcc-handler-function
4204                      (not (eq message-fcc-handler-function 'rmail-output)))
4205                 (funcall message-fcc-handler-function file)
4206               (if (and (file-readable-p file) (mail-file-babyl-p file))
4207                   (rmail-output file 1 nil t)
4208                 (let ((mail-use-rfc822 t))
4209                   (rmail-output file 1 t t))))))
4210         (kill-buffer (current-buffer))))))
4211
4212 (defun message-output (filename)
4213   "Append this article to Unix/babyl mail file FILENAME."
4214   (if (and (file-readable-p filename)
4215            (mail-file-babyl-p filename))
4216       (gnus-output-to-rmail filename t)
4217     (gnus-output-to-mail filename t)))
4218
4219 (defun message-cleanup-headers ()
4220   "Do various automatic cleanups of the headers."
4221   ;; Remove empty lines in the header.
4222   (save-restriction
4223     (message-narrow-to-headers)
4224     ;; Remove blank lines.
4225     (while (re-search-forward "^[ \t]*\n" nil t)
4226       (replace-match "" t t))
4227
4228     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4229     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4230     ;; embedded line breaks.
4231     (goto-char (point-min))
4232     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4233       (save-restriction
4234         (narrow-to-region
4235          (point)
4236          (if (re-search-forward "^[^ \t]" nil t)
4237              (match-beginning 0)
4238            (forward-line 1)
4239            (point)))
4240         (goto-char (point-min))
4241         (while (re-search-forward "\n[ \t]+" nil t)
4242           (replace-match " " t t))     ;No line breaks (too confusing)
4243         (goto-char (point-min))
4244         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4245           (replace-match "," t t))
4246         (goto-char (point-min))
4247         ;; Remove trailing commas.
4248         (when (re-search-forward ",+$" nil t)
4249           (replace-match "" t t))))))
4250
4251 (defun message-make-date (&optional now)
4252   "Make a valid data header.
4253 If NOW, use that time instead."
4254   (let* ((now (or now (current-time)))
4255          (zone (nth 8 (decode-time now)))
4256          (sign "+"))
4257     (when (< zone 0)
4258       (setq sign "-")
4259       (setq zone (- zone)))
4260     (concat
4261      ;; The day name of the %a spec is locale-specific.  Pfff.
4262      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4263                                              parse-time-weekdays))))
4264      (format-time-string "%d" now)
4265      ;; The month name of the %b spec is locale-specific.  Pfff.
4266      (format " %s "
4267              (capitalize (car (rassoc (nth 4 (decode-time now))
4268                                       parse-time-months))))
4269      (format-time-string "%Y %H:%M:%S " now)
4270      ;; We do all of this because XEmacs doesn't have the %z spec.
4271      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4272
4273 (defun message-make-message-id ()
4274   "Make a unique Message-ID."
4275   (concat "<" (message-unique-id)
4276           (let ((psubject (save-excursion (message-fetch-field "subject")))
4277                 (psupersedes
4278                  (save-excursion (message-fetch-field "supersedes"))))
4279             (if (or
4280                  (and message-reply-headers
4281                       (mail-header-references message-reply-headers)
4282                       (mail-header-subject message-reply-headers)
4283                       psubject
4284                       (not (string=
4285                             (message-strip-subject-re
4286                              (mail-header-subject message-reply-headers))
4287                             (message-strip-subject-re psubject))))
4288                  (and psupersedes
4289                       (string-match "_-_@" psupersedes)))
4290                 "_-_" ""))
4291           "@" (message-make-fqdn) ">"))
4292
4293 (defvar message-unique-id-char nil)
4294
4295 ;; If you ever change this function, make sure the new version
4296 ;; cannot generate IDs that the old version could.
4297 ;; You might for example insert a "." somewhere (not next to another dot
4298 ;; or string boundary), or modify the "fsf" string.
4299 (defun message-unique-id ()
4300   ;; Don't use microseconds from (current-time), they may be unsupported.
4301   ;; Instead we use this randomly inited counter.
4302   (setq message-unique-id-char
4303         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4304            ;; (current-time) returns 16-bit ints,
4305            ;; and 2^16*25 just fits into 4 digits i base 36.
4306            (* 25 25)))
4307   (let ((tm (current-time)))
4308     (concat
4309      (if (memq system-type '(ms-dos emx vax-vms))
4310          (let ((user (downcase (user-login-name))))
4311            (while (string-match "[^a-z0-9_]" user)
4312              (aset user (match-beginning 0) ?_))
4313            user)
4314        (message-number-base36 (user-uid) -1))
4315      (message-number-base36 (+ (car tm)
4316                                (lsh (% message-unique-id-char 25) 16)) 4)
4317      (message-number-base36 (+ (nth 1 tm)
4318                                (lsh (/ message-unique-id-char 25) 16)) 4)
4319      ;; Append the newsreader name, because while the generated
4320      ;; ID is unique to this newsreader, other newsreaders might
4321      ;; otherwise generate the same ID via another algorithm.
4322      ".fsf")))
4323
4324 (defun message-number-base36 (num len)
4325   (if (if (< len 0)
4326           (<= num 0)
4327         (= len 0))
4328       ""
4329     (concat (message-number-base36 (/ num 36) (1- len))
4330             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4331                                   (% num 36))))))
4332
4333 (defun message-make-organization ()
4334   "Make an Organization header."
4335   (let* ((organization
4336           (when message-user-organization
4337             (if (message-functionp message-user-organization)
4338                 (funcall message-user-organization)
4339               message-user-organization))))
4340     (save-excursion
4341       (message-set-work-buffer)
4342       (cond ((stringp organization)
4343              (insert organization))
4344             ((and (eq t organization)
4345                   message-user-organization-file
4346                   (file-exists-p message-user-organization-file))
4347              (insert-file-contents message-user-organization-file)))
4348       (goto-char (point-min))
4349       (while (re-search-forward "[\t\n]+" nil t)
4350         (replace-match "" t t))
4351       (unless (zerop (buffer-size))
4352         (buffer-string)))))
4353
4354 (defun message-make-lines ()
4355   "Count the number of lines and return numeric string."
4356   (save-excursion
4357     (save-restriction
4358       (widen)
4359       (message-goto-body)
4360       (int-to-string (count-lines (point) (point-max))))))
4361
4362 (defun message-make-references ()
4363   "Return the References header for this message."
4364   (when message-reply-headers
4365     (let ((message-id (mail-header-message-id message-reply-headers))
4366           (references (mail-header-references message-reply-headers))
4367           new-references)
4368       (if (or references message-id)
4369           (concat (or references "") (and references " ")
4370                   (or message-id ""))
4371         nil))))
4372
4373 (defun message-make-in-reply-to ()
4374   "Return the In-Reply-To header for this message."
4375   (when message-reply-headers
4376     (let ((from (mail-header-from message-reply-headers))
4377           (date (mail-header-date message-reply-headers))
4378           (msg-id (mail-header-message-id message-reply-headers)))
4379       (when from
4380         (let ((stop-pos
4381                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
4382           (concat msg-id (if msg-id " (")
4383                   (if (and stop-pos
4384                            (not (zerop stop-pos)))
4385                       (substring from 0 stop-pos) from)
4386                   "'s message of \""
4387                   (if (or (not date) (string= date ""))
4388                       "(unknown date)" date)
4389                   "\"" (if msg-id ")")))))))
4390
4391 (defun message-make-distribution ()
4392   "Make a Distribution header."
4393   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4394     (cond ((message-functionp message-distribution-function)
4395            (funcall message-distribution-function))
4396           (t orig-distribution))))
4397
4398 (defun message-make-expires ()
4399   "Return an Expires header based on `message-expires'."
4400   (let ((current (current-time))
4401         (future (* 1.0 message-expires 60 60 24)))
4402     ;; Add the future to current.
4403     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4404     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4405     (message-make-date current)))
4406
4407 (defun message-make-path ()
4408   "Return uucp path."
4409   (let ((login-name (user-login-name)))
4410     (cond ((null message-user-path)
4411            (concat (system-name) "!" login-name))
4412           ((stringp message-user-path)
4413            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4414            (concat message-user-path "!" login-name))
4415           (t login-name))))
4416
4417 (defun message-make-from ()
4418   "Make a From header."
4419   (let* ((style message-from-style)
4420          (login (message-make-address))
4421          (fullname
4422           (or (and (boundp 'user-full-name)
4423                    user-full-name)
4424               (user-full-name))))
4425     (when (string= fullname "&")
4426       (setq fullname (user-login-name)))
4427     (save-excursion
4428       (message-set-work-buffer)
4429       (cond
4430        ((or (null style)
4431             (equal fullname ""))
4432         (insert login))
4433        ((or (eq style 'angles)
4434             (and (not (eq style 'parens))
4435                  ;; Use angles if no quoting is needed, or if parens would
4436                  ;; need quoting too.
4437                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4438                      (let ((tmp (concat fullname nil)))
4439                        (while (string-match "([^()]*)" tmp)
4440                          (aset tmp (match-beginning 0) ?-)
4441                          (aset tmp (1- (match-end 0)) ?-))
4442                        (string-match "[\\()]" tmp)))))
4443         (insert fullname)
4444         (insert " <" login ">"))
4445        (t                               ; 'parens or default
4446         (insert login " (")
4447         (let ((fullname-start (point)))
4448           (insert fullname)
4449           (goto-char fullname-start)
4450           ;; RFC 822 says \ and nonmatching parentheses
4451           ;; must be escaped in comments.
4452           ;; Escape every instance of ()\ ...
4453           (while (re-search-forward "[()\\]" nil 1)
4454             (replace-match "\\\\\\&" t))
4455           ;; ... then undo escaping of matching parentheses,
4456           ;; including matching nested parentheses.
4457           (goto-char fullname-start)
4458           (while (re-search-forward
4459                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4460                   nil 1)
4461             (replace-match "\\1(\\3)" t)
4462             (goto-char fullname-start)))
4463         (insert ")")))
4464       (buffer-string))))
4465
4466 (defun message-make-sender ()
4467   "Return the \"real\" user address.
4468 This function tries to ignore all user modifications, and
4469 give as trustworthy answer as possible."
4470   (concat (user-login-name) "@" (system-name)))
4471
4472 (defun message-make-address ()
4473   "Make the address of the user."
4474   (or (message-user-mail-address)
4475       (concat (user-login-name) "@" (message-make-domain))))
4476
4477 (defun message-user-mail-address ()
4478   "Return the pertinent part of `user-mail-address'."
4479   (when user-mail-address
4480     (if (string-match " " user-mail-address)
4481         (nth 1 (mail-extract-address-components user-mail-address))
4482       user-mail-address)))
4483
4484 (defun message-make-fqdn ()
4485   "Return user's fully qualified domain name."
4486   (let ((system-name (system-name))
4487         (user-mail (message-user-mail-address)))
4488     (cond
4489      ((and (string-match "[^.]\\.[^.]" system-name)
4490            (not (string-match message-bogus-system-names system-name)))
4491       ;; `system-name' returned the right result.
4492       system-name)
4493      ;; Try `mail-host-address'.
4494      ((and (boundp 'mail-host-address)
4495            (stringp mail-host-address)
4496            (string-match "\\." mail-host-address))
4497       mail-host-address)
4498      ;; We try `user-mail-address' as a backup.
4499      ((and user-mail
4500            (string-match "\\." user-mail)
4501            (string-match "@\\(.*\\)\\'" user-mail))
4502       (match-string 1 user-mail))
4503      ;; Default to this bogus thing.
4504      (t
4505       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
4506
4507 (defun message-make-host-name ()
4508   "Return the name of the host."
4509   (let ((fqdn (message-make-fqdn)))
4510     (string-match "^[^.]+\\." fqdn)
4511     (substring fqdn 0 (1- (match-end 0)))))
4512
4513 (defun message-make-domain ()
4514   "Return the domain name."
4515   (or mail-host-address
4516       (message-make-fqdn)))
4517
4518 (defun message-to-list-only ()
4519   "Send a message to the list only.
4520 Remove all addresses but the list address from To and Cc headers."
4521   (interactive)
4522   (let ((listaddr (message-make-mail-followup-to t)))
4523     (when listaddr
4524       (save-excursion
4525         (message-remove-header "to")
4526         (message-remove-header "cc")
4527         (message-position-on-field "To" "X-Draft-From")
4528         (insert listaddr)))))
4529
4530 (defun message-make-mail-followup-to (&optional only-show-subscribed)
4531   "Return the Mail-Followup-To header.
4532 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
4533 subscribed address (and not the additional To and Cc header contents)."
4534   (let* ((case-fold-search t)
4535          (to (message-fetch-field "To"))
4536          (cc (message-fetch-field "cc"))
4537          (msg-recipients (concat to (and to cc ", ") cc))
4538          (recipients
4539           (mapcar 'mail-strip-quoted-names
4540                   (message-tokenize-header msg-recipients)))
4541          (file-regexps
4542           (if message-subscribed-address-file
4543               (let (begin end item re)
4544                 (save-excursion
4545                   (with-temp-buffer
4546                     (insert-file-contents message-subscribed-address-file)
4547                     (while (not (eobp))
4548                       (setq begin (point))
4549                       (forward-line 1)
4550                       (setq end (point))
4551                       (if (bolp) (setq end (1- end)))
4552                       (setq item (regexp-quote (buffer-substring begin end)))
4553                       (if re (setq re (concat re "\\|" item))
4554                         (setq re (concat "\\`\\(" item))))
4555                     (and re (list (concat re "\\)\\'"))))))))
4556          (mft-regexps (apply 'append message-subscribed-regexps
4557                              (mapcar 'regexp-quote
4558                                      message-subscribed-addresses)
4559                              file-regexps
4560                              (mapcar 'funcall
4561                                      message-subscribed-address-functions))))
4562     (save-match-data
4563       (let ((subscribed-lists nil)
4564             (list
4565              (loop for recipient in recipients
4566                when (loop for regexp in mft-regexps
4567                       when (string-match regexp recipient) return t)
4568                return recipient)))
4569         (when list
4570           (if only-show-subscribed
4571               list
4572             msg-recipients))))))
4573
4574 (defun message-generate-headers (headers)
4575   "Prepare article HEADERS.
4576 Headers already prepared in the buffer are not modified."
4577   (setq headers (append headers message-required-headers))
4578   (save-restriction
4579     (message-narrow-to-headers)
4580     (let* ((Date (message-make-date))
4581            (Message-ID (message-make-message-id))
4582            (Organization (message-make-organization))
4583            (From (message-make-from))
4584            (Path (message-make-path))
4585            (Subject nil)
4586            (Newsgroups nil)
4587            (In-Reply-To (message-make-in-reply-to))
4588            (References (message-make-references))
4589            (To nil)
4590            (Distribution (message-make-distribution))
4591            (Lines (message-make-lines))
4592            (User-Agent message-newsreader)
4593            (Expires (message-make-expires))
4594            (case-fold-search t)
4595            (optionalp nil)
4596            header value elem)
4597       ;; First we remove any old generated headers.
4598       (let ((headers message-deletable-headers))
4599         (unless (buffer-modified-p)
4600           (setq headers (delq 'Message-ID (copy-sequence headers))))
4601         (while headers
4602           (goto-char (point-min))
4603           (and (re-search-forward
4604                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4605                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4606                (message-delete-line))
4607           (pop headers)))
4608       ;; Go through all the required headers and see if they are in the
4609       ;; articles already.  If they are not, or are empty, they are
4610       ;; inserted automatically - except for Subject, Newsgroups and
4611       ;; Distribution.
4612       (while headers
4613         (goto-char (point-min))
4614         (setq elem (pop headers))
4615         (if (consp elem)
4616             (if (eq (car elem) 'optional)
4617                 (setq header (cdr elem)
4618                       optionalp t)
4619               (setq header (car elem)))
4620           (setq header elem))
4621         (when (or (not (re-search-forward
4622                         (concat "^"
4623                                 (regexp-quote
4624                                  (downcase
4625                                   (if (stringp header)
4626                                       header
4627                                     (symbol-name header))))
4628                                 ":")
4629                         nil t))
4630                   (progn
4631                     ;; The header was found.  We insert a space after the
4632                     ;; colon, if there is none.
4633                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
4634                     ;; Find out whether the header is empty.
4635                     (looking-at "[ \t]*\n[^ \t]")))
4636           ;; So we find out what value we should insert.
4637           (setq value
4638                 (cond
4639                  ((and (consp elem)
4640                        (eq (car elem) 'optional))
4641                   ;; This is an optional header.  If the cdr of this
4642                   ;; is something that is nil, then we do not insert
4643                   ;; this header.
4644                   (setq header (cdr elem))
4645                   (or (and (message-functionp (cdr elem))
4646                            (funcall (cdr elem)))
4647                       (and (boundp (cdr elem))
4648                            (symbol-value (cdr elem)))))
4649                  ((consp elem)
4650                   ;; The element is a cons.  Either the cdr is a
4651                   ;; string to be inserted verbatim, or it is a
4652                   ;; function, and we insert the value returned from
4653                   ;; this function.
4654                   (or (and (stringp (cdr elem))
4655                            (cdr elem))
4656                       (and (message-functionp (cdr elem))
4657                            (funcall (cdr elem)))))
4658                  ((and (boundp header)
4659                        (symbol-value header))
4660                   ;; The element is a symbol.  We insert the value
4661                   ;; of this symbol, if any.
4662                   (symbol-value header))
4663                  ((not (message-check-element header))
4664                   ;; We couldn't generate a value for this header,
4665                   ;; so we just ask the user.
4666                   (read-from-minibuffer
4667                    (format "Empty header for %s; enter value: " header)))))
4668           ;; Finally insert the header.
4669           (when (and value
4670                      (not (equal value "")))
4671             (save-excursion
4672               (if (bolp)
4673                   (progn
4674                     ;; This header didn't exist, so we insert it.
4675                     (goto-char (point-max))
4676                     (let ((formatter
4677                            (cdr (assq header message-header-format-alist))))
4678                       (if formatter
4679                           (funcall formatter header value)
4680                         (insert (if (stringp header)
4681                                     header (symbol-name header))
4682                                 ": " value))
4683                       ;; We check whether the value was ended by a
4684                       ;; newline.  If now, we insert one.
4685                       (unless (bolp)
4686                         (insert "\n"))
4687                       (forward-line -1)))
4688                 ;; The value of this header was empty, so we clear
4689                 ;; totally and insert the new value.
4690                 (delete-region (point) (gnus-point-at-eol))
4691                 ;; If the header is optional, and the header was
4692                 ;; empty, we con't insert it anyway.
4693                 (unless optionalp
4694                   (insert value)))
4695               ;; Add the deletable property to the headers that require it.
4696               (and (memq header message-deletable-headers)
4697                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4698                    (add-text-properties
4699                     (point) (match-end 0)
4700                     '(message-deletable t face italic) (current-buffer)))))))
4701       ;; Insert new Sender if the From is strange.
4702       (let ((from (message-fetch-field "from"))
4703             (sender (message-fetch-field "sender"))
4704             (secure-sender (message-make-sender)))
4705         (when (and from
4706                    (not (message-check-element 'sender))
4707                    (not (string=
4708                          (downcase
4709                           (cadr (mail-extract-address-components from)))
4710                          (downcase secure-sender)))
4711                    (or (null sender)
4712                        (not
4713                         (string=
4714                          (downcase
4715                           (cadr (mail-extract-address-components sender)))
4716                          (downcase secure-sender)))))
4717           (goto-char (point-min))
4718           ;; Rename any old Sender headers to Original-Sender.
4719           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4720             (beginning-of-line)
4721             (insert "Original-")
4722             (beginning-of-line))
4723           (when (or (message-news-p)
4724                     (string-match "@.+\\.." secure-sender))
4725             (insert "Sender: " secure-sender "\n")))))))
4726
4727 (defun message-insert-courtesy-copy ()
4728   "Insert a courtesy message in mail copies of combined messages."
4729   (let (newsgroups)
4730     (save-excursion
4731       (save-restriction
4732         (message-narrow-to-headers)
4733         (when (setq newsgroups (message-fetch-field "newsgroups"))
4734           (goto-char (point-max))
4735           (insert "Posted-To: " newsgroups "\n")))
4736       (forward-line 1)
4737       (when message-courtesy-message
4738         (cond
4739          ((string-match "%s" message-courtesy-message)
4740           (insert (format message-courtesy-message newsgroups)))
4741          (t
4742           (insert message-courtesy-message)))))))
4743
4744 ;;;
4745 ;;; Setting up a message buffer
4746 ;;;
4747
4748 (defun message-fill-address (header value)
4749   (save-restriction
4750     (narrow-to-region (point) (point))
4751     (insert (capitalize (symbol-name header))
4752             ": "
4753             (if (consp value) (car value) value)
4754             "\n")
4755     (narrow-to-region (point-min) (1- (point-max)))
4756     (let (quoted last)
4757       (goto-char (point-min))
4758       (while (not (eobp))
4759         (skip-chars-forward "^,\"" (point-max))
4760         (if (or (eq (char-after) ?,)
4761                 (eobp))
4762             (when (not quoted)
4763               (if (and (> (current-column) 78)
4764                        last)
4765                   (progn
4766                     (save-excursion
4767                       (goto-char last)
4768                       (insert "\n\t"))
4769                     (setq last (1+ (point))))
4770                 (setq last (1+ (point)))))
4771           (setq quoted (not quoted)))
4772         (unless (eobp)
4773           (forward-char 1))))
4774     (goto-char (point-max))
4775     (widen)
4776     (forward-line 1)))
4777
4778 (defun message-fill-header (header value)
4779   (let ((begin (point))
4780         (fill-column 78)
4781         (fill-prefix "\t"))
4782     (insert (capitalize (symbol-name header))
4783             ": "
4784             (if (consp value) (car value) value)
4785             "\n")
4786     (save-restriction
4787       (narrow-to-region begin (point))
4788       (fill-region-as-paragraph begin (point))
4789       ;; Tapdance around looong Message-IDs.
4790       (forward-line -1)
4791       (when (looking-at "[ \t]*$")
4792         (message-delete-line))
4793       (goto-char begin)
4794       (re-search-forward ":" nil t)
4795       (when (looking-at "\n[ \t]+")
4796         (replace-match " " t t))
4797       (goto-char (point-max)))))
4798
4799 (defun message-shorten-1 (list cut surplus)
4800   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4801   (setcdr (nthcdr (- cut 2) list)
4802           (nthcdr (+ (- cut 2) surplus 1) list)))
4803
4804 (defun message-shorten-references (header references)
4805   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4806 If folding is disallowed, also check that the REFERENCES are less
4807 than 988 characters long, and if they are not, trim them until they are."
4808   (let ((maxcount 21)
4809         (count 0)
4810         (cut 2)
4811         refs)
4812     (with-temp-buffer
4813       (insert references)
4814       (goto-char (point-min))
4815       ;; Cons a list of valid references.
4816       (while (re-search-forward "<[^>]+>" nil t)
4817         (push (match-string 0) refs))
4818       (setq refs (nreverse refs)
4819             count (length refs)))
4820
4821     ;; If the list has more than MAXCOUNT elements, trim it by
4822     ;; removing the CUTth element and the required number of
4823     ;; elements that follow.
4824     (when (> count maxcount)
4825       (let ((surplus (- count maxcount)))
4826         (message-shorten-1 refs cut surplus)
4827         (decf count surplus)))
4828
4829     ;; If folding is disallowed, make sure the total length (including
4830     ;; the spaces between) will be less than MAXSIZE characters.
4831     ;;
4832     ;; Only disallow folding for News messages. At this point the headers
4833     ;; have not been generated, thus we use message-this-is-news directly.
4834     (when (and message-this-is-news message-cater-to-broken-inn)
4835       (let ((maxsize 988)
4836             (totalsize (+ (apply #'+ (mapcar #'length refs))
4837                           (1- count)))
4838             (surplus 0)
4839             (ptr (nthcdr (1- cut) refs)))
4840         ;; Decide how many elements to cut off...
4841         (while (> totalsize maxsize)
4842           (decf totalsize (1+ (length (car ptr))))
4843           (incf surplus)
4844           (setq ptr (cdr ptr)))
4845         ;; ...and do it.
4846         (when (> surplus 0)
4847           (message-shorten-1 refs cut surplus))))
4848
4849     ;; Finally, collect the references back into a string and insert
4850     ;; it into the buffer.
4851     (let ((refstring (mapconcat #'identity refs " ")))
4852       (if (and message-this-is-news message-cater-to-broken-inn)
4853           (insert (capitalize (symbol-name header)) ": "
4854                   refstring "\n")
4855         (message-fill-header header refstring)))))
4856
4857 (defun message-position-point ()
4858   "Move point to where the user probably wants to find it."
4859   (message-narrow-to-headers)
4860   (cond
4861    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4862     (search-backward ":" )
4863     (widen)
4864     (forward-char 1)
4865     (if (eq (char-after) ? )
4866         (forward-char 1)
4867       (insert " ")))
4868    (t
4869     (goto-char (point-max))
4870     (widen)
4871     (forward-line 1)
4872     (unless (looking-at "$")
4873       (forward-line 2)))
4874    (sit-for 0)))
4875
4876 (defcustom message-beginning-of-line t
4877   "Whether C-a goes to beginning of header values."
4878   :group 'message-buffers
4879   :type 'boolean)
4880
4881 (defun message-beginning-of-line (&optional n)
4882   "Move point to beginning of header value or to beginning of line."
4883   (interactive "p")
4884   (let ((zrs 'zmacs-region-stays))
4885     (when (and (interactive-p) (boundp zrs))
4886       (set zrs t)))
4887   (if (and message-beginning-of-line
4888            (message-point-in-header-p))
4889       (let* ((here (point))
4890              (bol (progn (beginning-of-line n) (point)))
4891              (eol (gnus-point-at-eol))
4892              (eoh (re-search-forward ": *" eol t)))
4893         (if (or (not eoh) (equal here eoh))
4894             (goto-char bol)
4895           (goto-char eoh)))
4896     (beginning-of-line n)))
4897
4898 (defun message-buffer-name (type &optional to group)
4899   "Return a new (unique) buffer name based on TYPE and TO."
4900   (cond
4901    ;; Generate a new buffer name The Message Way.
4902    ((eq message-generate-new-buffers 'unique)
4903     (generate-new-buffer-name
4904      (concat "*" type
4905              (if to
4906                  (concat " to "
4907                          (or (car (mail-extract-address-components to))
4908                              to) "")
4909                "")
4910              (if (and group (not (string= group ""))) (concat " on " group) "")
4911              "*")))
4912    ;; Check whether `message-generate-new-buffers' is a function,
4913    ;; and if so, call it.
4914    ((message-functionp message-generate-new-buffers)
4915     (funcall message-generate-new-buffers type to group))
4916    ((eq message-generate-new-buffers 'unsent)
4917     (generate-new-buffer-name
4918      (concat "*unsent " type
4919              (if to
4920                  (concat " to "
4921                          (or (car (mail-extract-address-components to))
4922                              to) "")
4923                "")
4924              (if (and group (not (string= group ""))) (concat " on " group) "")
4925              "*")))
4926    ;; Use standard name.
4927    (t
4928     (format "*%s message*" type))))
4929
4930 (defun message-pop-to-buffer (name)
4931   "Pop to buffer NAME, and warn if it already exists and is modified."
4932   (let ((buffer (get-buffer name)))
4933     (if (and buffer
4934              (buffer-name buffer))
4935         (progn
4936           (set-buffer (pop-to-buffer buffer))
4937           (when (and (buffer-modified-p)
4938                      (not (y-or-n-p
4939                            "Message already being composed; erase? ")))
4940             (error "Message being composed")))
4941       (set-buffer (pop-to-buffer name)))
4942     (erase-buffer)
4943     (message-mode)))
4944
4945 (defun message-do-send-housekeeping ()
4946   "Kill old message buffers."
4947   ;; We might have sent this buffer already.  Delete it from the
4948   ;; list of buffers.
4949   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4950   (while (and message-max-buffers
4951               message-buffer-list
4952               (>= (length message-buffer-list) message-max-buffers))
4953     ;; Kill the oldest buffer -- unless it has been changed.
4954     (let ((buffer (pop message-buffer-list)))
4955       (when (and (buffer-name buffer)
4956                  (not (buffer-modified-p buffer)))
4957         (kill-buffer buffer))))
4958   ;; Rename the buffer.
4959   (if message-send-rename-function
4960       (funcall message-send-rename-function)
4961     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
4962     (when (string-match
4963            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
4964            (buffer-name))
4965       (let ((name (match-string 2 (buffer-name)))
4966             to group)
4967         (if (not (or (null name)
4968                      (string-equal name "mail")
4969                      (string-equal name "posting")))
4970             (setq name (concat "*sent " name "*"))
4971           (message-narrow-to-headers)
4972           (setq to (message-fetch-field "to"))
4973           (setq group (message-fetch-field "newsgroups"))
4974           (widen)
4975           (setq name
4976                 (cond
4977                  (to (concat "*sent mail to "
4978                              (or (car (mail-extract-address-components to))
4979                                  to) "*"))
4980                  ((and group (not (string= group "")))
4981                   (concat "*sent posting on " group "*"))
4982                  (t "*sent mail*"))))
4983         (unless (string-equal name (buffer-name))
4984           (rename-buffer name t)))))
4985   ;; Push the current buffer onto the list.
4986   (when message-max-buffers
4987     (setq message-buffer-list
4988           (nconc message-buffer-list (list (current-buffer))))))
4989
4990 (defun message-mail-user-agent ()
4991   (let ((mua (cond
4992               ((not message-mail-user-agent) nil)
4993               ((eq message-mail-user-agent t) mail-user-agent)
4994               (t message-mail-user-agent))))
4995     (if (memq mua '(message-user-agent gnus-user-agent))
4996         nil
4997       mua)))
4998
4999 (defun message-setup (headers &optional replybuffer actions switch-function)
5000   (let ((mua (message-mail-user-agent))
5001         subject to field yank-action)
5002     (if (not (and message-this-is-mail mua))
5003         (message-setup-1 headers replybuffer actions)
5004       (if replybuffer
5005           (setq yank-action (list 'insert-buffer replybuffer)))
5006       (setq headers (copy-sequence headers))
5007       (setq field (assq 'Subject headers))
5008       (when field
5009         (setq subject (cdr field))
5010         (setq headers (delq field headers)))
5011       (setq field (assq 'To headers))
5012       (when field
5013         (setq to (cdr field))
5014         (setq headers (delq field headers)))
5015       (let ((mail-user-agent mua))
5016         (compose-mail to subject
5017                       (mapcar (lambda (item)
5018                                 (cons
5019                                  (format "%s" (car item))
5020                                  (cdr item)))
5021                               headers)
5022                       nil switch-function yank-action actions)))))
5023
5024 (defun message-headers-to-generate (headers included-headers excluded-headers)
5025   "Return a list that includes all headers from HEADERS.
5026 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5027 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5028 are not included."
5029   (let ((result nil)
5030         header-name)
5031     (dolist (header headers)
5032       (setq header-name (cond
5033                          ((and (consp header)
5034                                (eq (car header) 'optional))
5035                           ;; On the form (optional . Header)
5036                           (cdr header))
5037                          ((consp header)
5038                           ;; On the form (Header . function)
5039                           (car header))
5040                          (t
5041                           ;; Just a Header.
5042                           header)))
5043       (when (and (not (memq header-name excluded-headers))
5044                  (or (eq included-headers t)
5045                      (memq header-name included-headers)))
5046         (push header result)))
5047     (nreverse result)))
5048
5049 (defun message-setup-1 (headers &optional replybuffer actions)
5050   (dolist (action actions)
5051     (condition-case nil
5052         (add-to-list 'message-send-actions
5053                      `(apply ',(car action) ',(cdr action)))))
5054   (setq message-reply-buffer replybuffer)
5055   (goto-char (point-min))
5056   ;; Insert all the headers.
5057   (mail-header-format
5058    (let ((h headers)
5059          (alist message-header-format-alist))
5060      (while h
5061        (unless (assq (caar h) message-header-format-alist)
5062          (push (list (caar h)) alist))
5063        (pop h))
5064      alist)
5065    headers)
5066   (delete-region (point) (progn (forward-line -1) (point)))
5067   (when message-default-headers
5068     (insert message-default-headers)
5069     (or (bolp) (insert ?\n)))
5070   (put-text-property
5071    (point)
5072    (progn
5073      (insert mail-header-separator "\n")
5074      (1- (point)))
5075    'read-only nil)
5076   (forward-line -1)
5077   (when (message-news-p)
5078     (when message-default-news-headers
5079       (insert message-default-news-headers)
5080       (or (bolp) (insert ?\n)))
5081     (when message-generate-headers-first
5082       (message-generate-headers
5083        (message-headers-to-generate
5084         (append message-required-news-headers
5085                 message-required-headers)
5086         message-generate-headers-first
5087         '(Lines Subject)))))
5088   (when (message-mail-p)
5089     (when message-default-mail-headers
5090       (insert message-default-mail-headers)
5091       (or (bolp) (insert ?\n)))
5092     (when message-generate-headers-first
5093       (message-generate-headers
5094        (message-headers-to-generate
5095         (append message-required-mail-headers
5096                 message-required-headers)
5097         message-generate-headers-first
5098         '(Lines Subject)))))
5099   (run-hooks 'message-signature-setup-hook)
5100   (message-insert-signature)
5101   (save-restriction
5102     (message-narrow-to-headers)
5103     (if message-alternative-emails
5104         (message-use-alternative-email-as-from))
5105     (run-hooks 'message-header-setup-hook))
5106   (set-buffer-modified-p nil)
5107   (setq buffer-undo-list nil)
5108   (run-hooks 'message-setup-hook)
5109   (message-position-point)
5110   (undo-boundary))
5111
5112 (defun message-set-auto-save-file-name ()
5113   "Associate the message buffer with a file in the drafts directory."
5114   (when message-auto-save-directory
5115     (unless (file-directory-p
5116              (directory-file-name message-auto-save-directory))
5117       (make-directory message-auto-save-directory t))
5118     (if (gnus-alive-p)
5119         (setq message-draft-article
5120               (nndraft-request-associate-buffer "drafts"))
5121       (setq buffer-file-name (expand-file-name
5122                               (if (memq system-type
5123                                         '(ms-dos ms-windows windows-nt
5124                                                  cygwin cygwin32 win32 w32
5125                                                  mswindows))
5126                                   "message"
5127                                 "*message*")
5128                               message-auto-save-directory))
5129       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5130     (clear-visited-file-modtime)
5131     (setq buffer-file-coding-system message-draft-coding-system)))
5132
5133 (defun message-disassociate-draft ()
5134   "Disassociate the message buffer from the drafts directory."
5135   (when message-draft-article
5136     (nndraft-request-expire-articles
5137      (list message-draft-article) "drafts" nil t)))
5138
5139 (defun message-insert-headers ()
5140   "Generate the headers for the article."
5141   (interactive)
5142   (save-excursion
5143     (save-restriction
5144       (message-narrow-to-headers)
5145       (when (message-news-p)
5146         (message-generate-headers
5147          (delq 'Lines
5148                (delq 'Subject
5149                      (copy-sequence message-required-news-headers)))))
5150       (when (message-mail-p)
5151         (message-generate-headers
5152          (delq 'Lines
5153                (delq 'Subject
5154                      (copy-sequence message-required-mail-headers))))))))
5155
5156 \f
5157
5158 ;;;
5159 ;;; Commands for interfacing with message
5160 ;;;
5161
5162 ;;;###autoload
5163 (defun message-mail (&optional to subject
5164                                other-headers continue switch-function
5165                                yank-action send-actions)
5166   "Start editing a mail message to be sent.
5167 OTHER-HEADERS is an alist of header/value pairs."
5168   (interactive)
5169   (let ((message-this-is-mail t) replybuffer)
5170     (unless (message-mail-user-agent)
5171       (message-pop-to-buffer (message-buffer-name "mail" to)))
5172     ;; FIXME: message-mail should do something if YANK-ACTION is not
5173     ;; insert-buffer.
5174     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5175          (setq replybuffer (nth 1 yank-action)))
5176     (message-setup
5177      (nconc
5178       `((To . ,(or to "")) (Subject . ,(or subject "")))
5179       (when other-headers other-headers))
5180      replybuffer send-actions)
5181     ;; FIXME: Should return nil if failure.
5182     t))
5183
5184 ;;;###autoload
5185 (defun message-news (&optional newsgroups subject)
5186   "Start editing a news article to be sent."
5187   (interactive)
5188   (let ((message-this-is-news t))
5189     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5190     (message-setup `((Newsgroups . ,(or newsgroups ""))
5191                      (Subject . ,(or subject ""))))))
5192
5193 (defun message-get-reply-headers (wide &optional to-address address-headers)
5194   (let (follow-to mct never-mct to cc author mft recipients)
5195     ;; Find all relevant headers we need.
5196     (setq to (message-fetch-field "to")
5197           cc (message-fetch-field "cc")
5198           mct (message-fetch-field "mail-copies-to")
5199           author (or (message-fetch-field "mail-reply-to")
5200                      (message-fetch-field "reply-to")
5201                      (message-fetch-field "from")
5202                      "")
5203           mft (and message-use-mail-followup-to
5204                    (message-fetch-field "mail-followup-to")))
5205
5206     ;; Handle special values of Mail-Copies-To.
5207     (when mct
5208       (cond ((or (equal (downcase mct) "never")
5209                  (equal (downcase mct) "nobody"))
5210              (setq never-mct t)
5211              (setq mct nil))
5212             ((or (equal (downcase mct) "always")
5213                  (equal (downcase mct) "poster"))
5214              (setq mct author))))
5215
5216     (save-match-data
5217       ;; Build (textual) list of new recipient addresses.
5218       (cond
5219        ((not wide)
5220         (setq recipients (concat ", " author)))
5221        (address-headers
5222         (dolist (header address-headers)
5223           (let ((value (message-fetch-field header)))
5224             (when value
5225               (setq recipients (concat recipients ", " value))))))
5226        ((and mft
5227              (string-match "[^ \t,]" mft)
5228              (or (not (eq message-use-mail-followup-to 'ask))
5229                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5230 You should normally obey the Mail-Followup-To: header.  In this
5231 article, it has the value of
5232
5233 " mft "
5234
5235 which directs your response to " (if (string-match "," mft)
5236                                      "the specified addresses"
5237                                    "that address only") ".
5238
5239 Most commonly, Mail-Followup-To is used by a mailing list poster to
5240 express that responses should be sent to just the list, and not the
5241 poster as well.
5242
5243 If a message is posted to several mailing lists, Mail-Followup-To may
5244 also be used to direct the following discussion to one list only,
5245 because discussions that are spread over several lists tend to be
5246 fragmented and very difficult to follow.
5247
5248 Also, some source/announcement lists are not intended for discussion;
5249 responses here are directed to other addresses.")))
5250         (setq recipients (concat ", " mft)))
5251        (to-address
5252         (setq recipients (concat ", " to-address))
5253         ;; If the author explicitly asked for a copy, we don't deny it to them.
5254         (if mct (setq recipients (concat recipients ", " mct))))
5255        (t
5256         (setq recipients (if never-mct "" (concat ", " author)))
5257         (if to  (setq recipients (concat recipients ", " to)))
5258         (if cc  (setq recipients (concat recipients ", " cc)))
5259         (if mct (setq recipients (concat recipients ", " mct)))))
5260       (if (>= (length recipients) 2)
5261           ;; Strip the leading ", ".
5262           (setq recipients (substring recipients 2)))
5263       ;; Squeeze whitespace.
5264       (while (string-match "[ \t][ \t]+" recipients)
5265         (setq recipients (replace-match " " t t recipients)))
5266       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5267       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5268         (setq recipients (rmail-dont-reply-to recipients)))
5269       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5270       (if (string-equal recipients "")
5271           (setq recipients author))
5272       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5273       (setq recipients
5274             (mapcar
5275              (lambda (addr)
5276                (cons (downcase (mail-strip-quoted-names addr)) addr))
5277              (message-tokenize-header recipients)))
5278       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5279       (let ((s recipients))
5280         (while s
5281           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5282
5283       ;; Remove hierarchical lists that are contained within each other,
5284       ;; if message-hierarchical-addresses is defined.
5285       (when message-hierarchical-addresses
5286         (let ((plain-addrs (mapcar 'car recipients))
5287               subaddrs recip)
5288           (while plain-addrs
5289             (setq subaddrs (assoc (car plain-addrs)
5290                                   message-hierarchical-addresses)
5291                   plain-addrs (cdr plain-addrs))
5292             (when subaddrs
5293               (setq subaddrs (cdr subaddrs))
5294               (while subaddrs
5295                 (setq recip (assoc (car subaddrs) recipients)
5296                       subaddrs (cdr subaddrs))
5297                 (if recip
5298                     (setq recipients (delq recip recipients))))))))
5299
5300       ;; Build the header alist.  Allow the user to be asked whether
5301       ;; or not to reply to all recipients in a wide reply.
5302       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5303       (when (and recipients
5304                  (or (not message-wide-reply-confirm-recipients)
5305                      (y-or-n-p "Reply to all recipients? ")))
5306         (setq recipients (mapconcat
5307                           (lambda (addr) (cdr addr)) recipients ", "))
5308         (if (string-match "^ +" recipients)
5309             (setq recipients (substring recipients (match-end 0))))
5310         (push (cons 'Cc recipients) follow-to)))
5311     follow-to))
5312
5313 ;;;###autoload
5314 (defun message-reply (&optional to-address wide)
5315   "Start editing a reply to the article in the current buffer."
5316   (interactive)
5317   (require 'gnus-sum)                   ; for gnus-list-identifiers
5318   (let ((cur (current-buffer))
5319         from subject date reply-to to cc
5320         references message-id follow-to
5321         (inhibit-point-motion-hooks t)
5322         (message-this-is-mail t)
5323         gnus-warning)
5324     (save-restriction
5325       (message-narrow-to-head-1)
5326       ;; Allow customizations to have their say.
5327       (if (not wide)
5328           ;; This is a regular reply.
5329           (when (message-functionp message-reply-to-function)
5330             (save-excursion
5331               (setq follow-to (funcall message-reply-to-function))))
5332         ;; This is a followup.
5333         (when (message-functionp message-wide-reply-to-function)
5334           (save-excursion
5335             (setq follow-to
5336                   (funcall message-wide-reply-to-function)))))
5337       (setq message-id (message-fetch-field "message-id" t)
5338             references (message-fetch-field "references")
5339             date (message-fetch-field "date")
5340             from (message-fetch-field "from")
5341             subject (or (message-fetch-field "subject") "none"))
5342       (when gnus-list-identifiers
5343         (setq subject (message-strip-list-identifiers subject)))
5344       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5345       (when message-subject-trailing-was-query
5346         (setq subject (message-strip-subject-trailing-was subject)))
5347
5348       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5349                  (string-match "<[^>]+>" gnus-warning))
5350         (setq message-id (match-string 0 gnus-warning)))
5351
5352       (unless follow-to
5353         (setq follow-to (message-get-reply-headers wide to-address))))
5354
5355     (unless (message-mail-user-agent)
5356       (message-pop-to-buffer
5357        (message-buffer-name
5358         (if wide "wide reply" "reply") from
5359         (if wide to-address nil))))
5360
5361     (setq message-reply-headers
5362           (vector 0 subject from date message-id references 0 0 ""))
5363
5364     (message-setup
5365      `((Subject . ,subject)
5366        ,@follow-to)
5367      cur)))
5368
5369 ;;;###autoload
5370 (defun message-wide-reply (&optional to-address)
5371   "Make a \"wide\" reply to the message in the current buffer."
5372   (interactive)
5373   (message-reply to-address t))
5374
5375 ;;;###autoload
5376 (defun message-followup (&optional to-newsgroups)
5377   "Follow up to the message in the current buffer.
5378 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5379   (interactive)
5380   (require 'gnus-sum)                   ; for gnus-list-identifiers
5381   (let ((cur (current-buffer))
5382         from subject date reply-to mrt mct
5383         references message-id follow-to
5384         (inhibit-point-motion-hooks t)
5385         (message-this-is-news t)
5386         followup-to distribution newsgroups gnus-warning posted-to)
5387     (save-restriction
5388       (narrow-to-region
5389        (goto-char (point-min))
5390        (if (search-forward "\n\n" nil t)
5391            (1- (point))
5392          (point-max)))
5393       (when (message-functionp message-followup-to-function)
5394         (setq follow-to
5395               (funcall message-followup-to-function)))
5396       (setq from (message-fetch-field "from")
5397             date (message-fetch-field "date")
5398             subject (or (message-fetch-field "subject") "none")
5399             references (message-fetch-field "references")
5400             message-id (message-fetch-field "message-id" t)
5401             followup-to (message-fetch-field "followup-to")
5402             newsgroups (message-fetch-field "newsgroups")
5403             posted-to (message-fetch-field "posted-to")
5404             reply-to (message-fetch-field "reply-to")
5405             mrt (message-fetch-field "mail-reply-to")
5406             distribution (message-fetch-field "distribution")
5407             mct (message-fetch-field "mail-copies-to"))
5408       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5409                  (string-match "<[^>]+>" gnus-warning))
5410         (setq message-id (match-string 0 gnus-warning)))
5411       ;; Remove bogus distribution.
5412       (when (and (stringp distribution)
5413                  (let ((case-fold-search t))
5414                    (string-match "world" distribution)))
5415         (setq distribution nil))
5416       (if gnus-list-identifiers
5417           (setq subject (message-strip-list-identifiers subject)))
5418       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5419       (when message-subject-trailing-was-query
5420         (setq subject (message-strip-subject-trailing-was subject)))
5421       (widen))
5422
5423     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5424
5425     (setq message-reply-headers
5426           (vector 0 subject from date message-id references 0 0 ""))
5427
5428     (message-setup
5429      `((Subject . ,subject)
5430        ,@(cond
5431           (to-newsgroups
5432            (list (cons 'Newsgroups to-newsgroups)))
5433           (follow-to follow-to)
5434           ((and followup-to message-use-followup-to)
5435            (list
5436             (cond
5437              ((equal (downcase followup-to) "poster")
5438               (if (or (eq message-use-followup-to 'use)
5439                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
5440 You should normally obey the Followup-To: header.
5441
5442 `Followup-To: poster' sends your response via e-mail instead of news.
5443
5444 A typical situation where `Followup-To: poster' is used is when the poster
5445 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5446                   (progn
5447                     (setq message-this-is-news nil)
5448                     (cons 'To (or mrt reply-to from "")))
5449                 (cons 'Newsgroups newsgroups)))
5450              (t
5451               (if (or (equal followup-to newsgroups)
5452                       (not (eq message-use-followup-to 'ask))
5453                       (message-y-or-n-p
5454                        (concat "Obey Followup-To: " followup-to "? ") t "\
5455 You should normally obey the Followup-To: header.
5456
5457         `Followup-To: " followup-to "'
5458 directs your response to " (if (string-match "," followup-to)
5459                                "the specified newsgroups"
5460                              "that newsgroup only") ".
5461
5462 If a message is posted to several newsgroups, Followup-To is often
5463 used to direct the following discussion to one newsgroup only,
5464 because discussions that are spread over several newsgroup tend to
5465 be fragmented and very difficult to follow.
5466
5467 Also, some source/announcement newsgroups are not intended for discussion;
5468 responses here are directed to other newsgroups."))
5469                   (cons 'Newsgroups followup-to)
5470                 (cons 'Newsgroups newsgroups))))))
5471           (posted-to
5472            `((Newsgroups . ,posted-to)))
5473           (t
5474            `((Newsgroups . ,newsgroups))))
5475        ,@(and distribution (list (cons 'Distribution distribution)))
5476        ,@(when (and mct
5477                     (not (or (equal (downcase mct) "never")
5478                              (equal (downcase mct) "nobody"))))
5479            (list (cons 'Cc (if (or (equal (downcase mct) "always")
5480                                    (equal (downcase mct) "poster"))
5481                                (or mrt reply-to from "")
5482                              mct)))))
5483
5484      cur)))
5485
5486
5487 ;;;###autoload
5488 (defun message-cancel-news (&optional arg)
5489   "Cancel an article you posted.
5490 If ARG, allow editing of the cancellation message."
5491   (interactive "P")
5492   (unless (message-news-p)
5493     (error "This is not a news article; canceling is impossible"))
5494   (let (from newsgroups message-id distribution buf sender)
5495     (save-excursion
5496       ;; Get header info from original article.
5497       (save-restriction
5498         (message-narrow-to-head-1)
5499         (setq from (message-fetch-field "from")
5500               sender (message-fetch-field "sender")
5501               newsgroups (message-fetch-field "newsgroups")
5502               message-id (message-fetch-field "message-id" t)
5503               distribution (message-fetch-field "distribution")))
5504       ;; Make sure that this article was written by the user.
5505       (unless (or
5506                ;; Canlock-logic as suggested by Per Abrahamsen
5507                ;; <abraham@dina.kvl.dk>
5508                ;;
5509                ;; IF article has cancel-lock THEN
5510                ;;   IF we can verify it THEN
5511                ;;     issue cancel
5512                ;;   ELSE
5513                ;;     error: cancellock: article is not yours
5514                ;; ELSE
5515                ;;   Use old rules, comparing sender...
5516                (if (message-fetch-field "Cancel-Lock")
5517                    (if (null (canlock-verify))
5518                        t
5519                      (error "Failed to verify Cancel-lock: This article is not yours"))
5520                  nil)
5521                (message-gnksa-enable-p 'cancel-messages)
5522                (and sender
5523                     (string-equal
5524                      (downcase sender)
5525                      (downcase (message-make-sender))))
5526                (string-equal
5527                 (downcase (cadr (mail-extract-address-components from)))
5528                 (downcase (cadr (mail-extract-address-components
5529                                  (message-make-from))))))
5530         (error "This article is not yours"))
5531       (when (yes-or-no-p "Do you really want to cancel this article? ")
5532         ;; Make control message.
5533         (if arg
5534             (message-news)
5535           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5536         (erase-buffer)
5537         (insert "Newsgroups: " newsgroups "\n"
5538                 "From: " from "\n"
5539                 "Subject: cmsg cancel " message-id "\n"
5540                 "Control: cancel " message-id "\n"
5541                 (if distribution
5542                     (concat "Distribution: " distribution "\n")
5543                   "")
5544                 mail-header-separator "\n"
5545                 message-cancel-message)
5546         (run-hooks 'message-cancel-hook)
5547         (unless arg
5548           (message "Canceling your article...")
5549           (if (let ((message-syntax-checks
5550                      'dont-check-for-anything-just-trust-me))
5551                 (funcall message-send-news-function))
5552               (message "Canceling your article...done"))
5553           (kill-buffer buf))))))
5554
5555 ;;;###autoload
5556 (defun message-supersede ()
5557   "Start composing a message to supersede the current message.
5558 This is done simply by taking the old article and adding a Supersedes
5559 header line with the old Message-ID."
5560   (interactive)
5561   (let ((cur (current-buffer))
5562         (sender (message-fetch-field "sender"))
5563         (from (message-fetch-field "from")))
5564     ;; Check whether the user owns the article that is to be superseded.
5565     (unless (or
5566              ;; Canlock-logic as suggested by Per Abrahamsen
5567              ;; <abraham@dina.kvl.dk>
5568              ;;
5569              ;; IF article has cancel-lock THEN
5570              ;;   IF we can verify it THEN
5571              ;;     issue cancel
5572              ;;   ELSE
5573              ;;     error: cancellock: article is not yours
5574              ;; ELSE
5575              ;;   Use old rules, comparing sender...
5576              (if (message-fetch-field "Cancel-Lock")
5577                  (if (null (canlock-verify))
5578                      t
5579                    (error "Failed to verify Cancel-lock: This article is not yours"))
5580                nil)
5581              (message-gnksa-enable-p 'cancel-messages)
5582                 (and sender
5583                      (string-equal
5584                       (downcase sender)
5585                       (downcase (message-make-sender))))
5586                 (string-equal
5587                  (downcase (cadr (mail-extract-address-components from)))
5588                  (downcase (cadr (mail-extract-address-components
5589                                   (message-make-from))))))
5590       (error "This article is not yours"))
5591     ;; Get a normal message buffer.
5592     (message-pop-to-buffer (message-buffer-name "supersede"))
5593     (insert-buffer-substring cur)
5594     (mime-to-mml)
5595     (message-narrow-to-head-1)
5596     ;; Remove unwanted headers.
5597     (when message-ignored-supersedes-headers
5598       (message-remove-header message-ignored-supersedes-headers t))
5599     (goto-char (point-min))
5600     (if (not (re-search-forward "^Message-ID: " nil t))
5601         (error "No Message-ID in this article")
5602       (replace-match "Supersedes: " t t))
5603     (goto-char (point-max))
5604     (insert mail-header-separator)
5605     (widen)
5606     (forward-line 1)))
5607
5608 ;;;###autoload
5609 (defun message-recover ()
5610   "Reread contents of current buffer from its last auto-save file."
5611   (interactive)
5612   (let ((file-name (make-auto-save-file-name)))
5613     (cond ((save-window-excursion
5614              (if (not (eq system-type 'vax-vms))
5615                  (with-output-to-temp-buffer "*Directory*"
5616                    (with-current-buffer standard-output
5617                      (fundamental-mode)) ; for Emacs 20.4+
5618                    (buffer-disable-undo standard-output)
5619                    (let ((default-directory "/"))
5620                      (call-process
5621                       "ls" nil standard-output nil "-l" file-name))))
5622              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5623            (let ((buffer-read-only nil))
5624              (erase-buffer)
5625              (insert-file-contents file-name nil)))
5626           (t (error "message-recover cancelled")))))
5627
5628 ;;; Washing Subject:
5629
5630 (defun message-wash-subject (subject)
5631   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
5632 Previous forwarders, replyers, etc. may add it."
5633   (with-temp-buffer
5634     (insert subject)
5635     (goto-char (point-min))
5636     ;; strip Re/Fwd stuff off the beginning
5637     (while (re-search-forward
5638             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
5639       (replace-match ""))
5640
5641     ;; and gnus-style forwards [foo@bar.com] subject
5642     (goto-char (point-min))
5643     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
5644       (replace-match ""))
5645
5646     ;; and off the end
5647     (goto-char (point-max))
5648     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
5649       (replace-match ""))
5650
5651     ;; and finally, any whitespace that was left-over
5652     (goto-char (point-min))
5653     (while (re-search-forward "^[ \t]+" nil t)
5654       (replace-match ""))
5655     (goto-char (point-max))
5656     (while (re-search-backward "[ \t]+$" nil t)
5657       (replace-match ""))
5658
5659     (buffer-string)))
5660
5661 ;;; Forwarding messages.
5662
5663 (defvar message-forward-decoded-p nil
5664   "Non-nil means the original message is decoded.")
5665
5666 (defun message-forward-subject-author-subject (subject)
5667   "Generate a SUBJECT for a forwarded message.
5668 The form is: [Source] Subject, where if the original message was mail,
5669 Source is the sender, and if the original message was news, Source is
5670 the list of newsgroups is was posted to."
5671   (concat "["
5672           (let ((prefix
5673                  (or (message-fetch-field "newsgroups")
5674                      (message-fetch-field "from")
5675                      "(nowhere)")))
5676             (if message-forward-decoded-p
5677                 prefix
5678               (mail-decode-encoded-word-string prefix)))
5679           "] " subject))
5680
5681 (defun message-forward-subject-fwd (subject)
5682   "Generate a SUBJECT for a forwarded message.
5683 The form is: Fwd: Subject, where Subject is the original subject of
5684 the message."
5685   (concat "Fwd: " subject))
5686
5687 (defun message-make-forward-subject ()
5688   "Return a Subject header suitable for the message in the current buffer."
5689   (save-excursion
5690     (save-restriction
5691       (message-narrow-to-head-1)
5692       (let ((funcs message-make-forward-subject-function)
5693             (subject (message-fetch-field "Subject")))
5694         (setq subject
5695               (if subject
5696                   (if message-forward-decoded-p
5697                       subject
5698                     (mail-decode-encoded-word-string subject))
5699                 ""))
5700         (if message-wash-forwarded-subjects
5701             (setq subject (message-wash-subject subject)))
5702         ;; Make sure funcs is a list.
5703         (and funcs
5704              (not (listp funcs))
5705              (setq funcs (list funcs)))
5706         ;; Apply funcs in order, passing subject generated by previous
5707         ;; func to the next one.
5708         (while funcs
5709           (when (message-functionp (car funcs))
5710             (setq subject (funcall (car funcs) subject)))
5711           (setq funcs (cdr funcs)))
5712         subject))))
5713
5714 (eval-when-compile
5715   (defvar gnus-article-decoded-p))
5716
5717
5718 ;;;###autoload
5719 (defun message-forward (&optional news digest)
5720   "Forward the current message via mail.
5721 Optional NEWS will use news to forward instead of mail.
5722 Optional DIGEST will use digest to forward."
5723   (interactive "P")
5724   (let* ((cur (current-buffer))
5725          (message-forward-decoded-p
5726           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
5727               gnus-article-decoded-p ;; In an article buffer.
5728             message-forward-decoded-p))
5729          (subject (message-make-forward-subject)))
5730     (if news
5731         (message-news nil subject)
5732       (message-mail nil subject))
5733     (message-forward-make-body cur digest)))
5734
5735 ;;;###autoload
5736 (defun message-forward-make-body (forward-buffer &optional digest)
5737   ;; Put point where we want it before inserting the forwarded
5738   ;; message.
5739   (if message-forward-before-signature
5740       (message-goto-body)
5741     (goto-char (point-max)))
5742   (if message-forward-as-mime
5743       (if digest
5744           (insert "\n<#multipart type=digest>\n")
5745         (if message-forward-show-mml
5746             (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
5747           (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
5748     (insert "\n-------------------- Start of forwarded message --------------------\n"))
5749   (let ((b (point)) e)
5750     (if digest
5751         (if message-forward-as-mime
5752             (insert-buffer-substring forward-buffer)
5753           (mml-insert-buffer forward-buffer))
5754       (if (and message-forward-show-mml
5755                (not message-forward-decoded-p))
5756           (insert
5757            (with-temp-buffer
5758              (mm-disable-multibyte-mule4)
5759              (insert
5760               (with-current-buffer forward-buffer
5761                 (mm-with-unibyte-current-buffer-mule4 (buffer-string))))
5762              (mm-enable-multibyte-mule4)
5763              (mime-to-mml)
5764              (goto-char (point-min))
5765              (when (looking-at "From ")
5766                (replace-match "X-From-Line: "))
5767              (buffer-string)))
5768         (save-restriction
5769           (narrow-to-region (point) (point))
5770           (mml-insert-buffer forward-buffer)
5771           (goto-char (point-min))
5772           (when (looking-at "From ")
5773             (replace-match "X-From-Line: "))
5774           (goto-char (point-max)))))
5775     (setq e (point))
5776     (if message-forward-as-mime
5777         (if digest
5778             (insert "<#/multipart>\n")
5779           (if message-forward-show-mml
5780               (insert "<#/mml>\n")
5781             (insert "<#/part>\n")))
5782       (insert "\n-------------------- End of forwarded message --------------------\n"))
5783     (if (and digest message-forward-as-mime)
5784         (save-restriction
5785           (narrow-to-region b e)
5786           (goto-char b)
5787           (narrow-to-region (point)
5788                             (or (search-forward "\n\n" nil t) (point)))
5789           (delete-region (point-min) (point-max)))
5790       (when (and (not current-prefix-arg)
5791                  message-forward-ignored-headers
5792                  ;; don't remove CTE, X-Gnus etc when doing "raw" forward:
5793                  message-forward-show-mml)
5794         (save-restriction
5795           (narrow-to-region b e)
5796           (goto-char b)
5797           (narrow-to-region (point)
5798                             (or (search-forward "\n\n" nil t) (point)))
5799           (message-remove-header message-forward-ignored-headers t)))))
5800   (message-position-point))
5801
5802 ;;;###autoload
5803 (defun message-forward-rmail-make-body (forward-buffer)
5804   (save-window-excursion
5805     (set-buffer forward-buffer)
5806     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
5807     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
5808     (if (rmail-msg-is-pruned)
5809         (rmail-msg-restore-non-pruned-header)))
5810   (message-forward-make-body forward-buffer))
5811
5812 ;;;###autoload
5813 (defun message-insinuate-rmail ()
5814   "Let RMAIL uses message to forward."
5815   (interactive)
5816   (setq rmail-enable-mime-composing t)
5817   (setq rmail-insert-mime-forwarded-message-function
5818         'message-forward-rmail-make-body))
5819
5820 ;;;###autoload
5821 (defun message-resend (address)
5822   "Resend the current article to ADDRESS."
5823   (interactive
5824    (list (message-read-from-minibuffer "Resend message to: ")))
5825   (message "Resending message to %s..." address)
5826   (save-excursion
5827     (let ((cur (current-buffer))
5828           beg)
5829       ;; We first set up a normal mail buffer.
5830       (unless (message-mail-user-agent)
5831         (set-buffer (get-buffer-create " *message resend*"))
5832         (erase-buffer))
5833       (let ((message-this-is-mail t))
5834         (message-setup `((To . ,address))))
5835       ;; Insert our usual headers.
5836       (message-generate-headers '(From Date To))
5837       (message-narrow-to-headers)
5838       ;; Rename them all to "Resent-*".
5839       (while (re-search-forward "^[A-Za-z]" nil t)
5840         (forward-char -1)
5841         (insert "Resent-"))
5842       (widen)
5843       (forward-line)
5844       (delete-region (point) (point-max))
5845       (setq beg (point))
5846       ;; Insert the message to be resent.
5847       (insert-buffer-substring cur)
5848       (goto-char (point-min))
5849       (search-forward "\n\n")
5850       (forward-char -1)
5851       (save-restriction
5852         (narrow-to-region beg (point))
5853         (message-remove-header message-ignored-resent-headers t)
5854         (goto-char (point-max)))
5855       (insert mail-header-separator)
5856       ;; Rename all old ("Also-")Resent headers.
5857       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5858         (beginning-of-line)
5859         (insert "Also-"))
5860       ;; Quote any "From " lines at the beginning.
5861       (goto-char beg)
5862       (when (looking-at "From ")
5863         (replace-match "X-From-Line: "))
5864       ;; Send it.
5865       (let ((message-inhibit-body-encoding t)
5866             message-required-mail-headers)
5867         (message-send-mail))
5868       (kill-buffer (current-buffer)))
5869     (message "Resending message to %s...done" address)))
5870
5871 ;;;###autoload
5872 (defun message-bounce ()
5873   "Re-mail the current message.
5874 This only makes sense if the current message is a bounce message that
5875 contains some mail you have written which has been bounced back to
5876 you."
5877   (interactive)
5878   (let ((handles (mm-dissect-buffer t))
5879         boundary)
5880     (message-pop-to-buffer (message-buffer-name "bounce"))
5881     (if (stringp (car handles))
5882         ;; This is a MIME bounce.
5883         (mm-insert-part (car (last handles)))
5884       ;; This is a non-MIME bounce, so we try to remove things
5885       ;; manually.
5886       (mm-insert-part handles)
5887       (undo-boundary)
5888       (goto-char (point-min))
5889       (search-forward "\n\n" nil t)
5890       (if (or (and (re-search-forward message-unsent-separator nil t)
5891                    (forward-line 1))
5892               (re-search-forward "^Return-Path:.*\n" nil t))
5893           ;; We remove everything before the bounced mail.
5894           (delete-region
5895            (point-min)
5896            (if (re-search-forward "^[^ \n\t]+:" nil t)
5897                (match-beginning 0)
5898              (point)))
5899         (when (re-search-backward "^.?From .*\n" nil t)
5900           (delete-region (match-beginning 0) (match-end 0)))))
5901     (mm-enable-multibyte)
5902     (mime-to-mml)
5903     (save-restriction
5904       (message-narrow-to-head-1)
5905       (message-remove-header message-ignored-bounced-headers t)
5906       (goto-char (point-max))
5907       (insert mail-header-separator))
5908     (message-position-point)))
5909
5910 ;;;
5911 ;;; Interactive entry points for new message buffers.
5912 ;;;
5913
5914 ;;;###autoload
5915 (defun message-mail-other-window (&optional to subject)
5916   "Like `message-mail' command, but display mail buffer in another window."
5917   (interactive)
5918   (unless (message-mail-user-agent)
5919     (let ((pop-up-windows t)
5920           (special-display-buffer-names nil)
5921           (special-display-regexps nil)
5922           (same-window-buffer-names nil)
5923           (same-window-regexps nil))
5924       (message-pop-to-buffer (message-buffer-name "mail" to))))
5925   (let ((message-this-is-mail t))
5926     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5927                    nil nil 'switch-to-buffer-other-window)))
5928
5929 ;;;###autoload
5930 (defun message-mail-other-frame (&optional to subject)
5931   "Like `message-mail' command, but display mail buffer in another frame."
5932   (interactive)
5933   (unless (message-mail-user-agent)
5934     (let ((pop-up-frames t)
5935           (special-display-buffer-names nil)
5936           (special-display-regexps nil)
5937           (same-window-buffer-names nil)
5938           (same-window-regexps nil))
5939       (message-pop-to-buffer (message-buffer-name "mail" to))))
5940   (let ((message-this-is-mail t))
5941     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5942                    nil nil 'switch-to-buffer-other-frame)))
5943
5944 ;;;###autoload
5945 (defun message-news-other-window (&optional newsgroups subject)
5946   "Start editing a news article to be sent."
5947   (interactive)
5948   (let ((pop-up-windows t)
5949         (special-display-buffer-names nil)
5950         (special-display-regexps nil)
5951         (same-window-buffer-names nil)
5952         (same-window-regexps nil))
5953     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
5954   (let ((message-this-is-news t))
5955     (message-setup `((Newsgroups . ,(or newsgroups ""))
5956                      (Subject . ,(or subject ""))))))
5957
5958 ;;;###autoload
5959 (defun message-news-other-frame (&optional newsgroups subject)
5960   "Start editing a news article to be sent."
5961   (interactive)
5962   (let ((pop-up-frames t)
5963         (special-display-buffer-names nil)
5964         (special-display-regexps nil)
5965         (same-window-buffer-names nil)
5966         (same-window-regexps nil))
5967     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
5968   (let ((message-this-is-news t))
5969     (message-setup `((Newsgroups . ,(or newsgroups ""))
5970                      (Subject . ,(or subject ""))))))
5971
5972 ;;; underline.el
5973
5974 ;; This code should be moved to underline.el (from which it is stolen).
5975
5976 ;;;###autoload
5977 (defun bold-region (start end)
5978   "Bold all nonblank characters in the region.
5979 Works by overstriking characters.
5980 Called from program, takes two arguments START and END
5981 which specify the range to operate on."
5982   (interactive "r")
5983   (save-excursion
5984     (let ((end1 (make-marker)))
5985       (move-marker end1 (max start end))
5986       (goto-char (min start end))
5987       (while (< (point) end1)
5988         (or (looking-at "[_\^@- ]")
5989             (insert (char-after) "\b"))
5990         (forward-char 1)))))
5991
5992 ;;;###autoload
5993 (defun unbold-region (start end)
5994   "Remove all boldness (overstruck characters) in the region.
5995 Called from program, takes two arguments START and END
5996 which specify the range to operate on."
5997   (interactive "r")
5998   (save-excursion
5999     (let ((end1 (make-marker)))
6000       (move-marker end1 (max start end))
6001       (goto-char (min start end))
6002       (while (re-search-forward "\b" end1 t)
6003         (if (eq (char-after) (char-after (- (point) 2)))
6004             (delete-char -2))))))
6005
6006 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
6007
6008 ;; Support for toolbar
6009 (eval-when-compile
6010   (defvar tool-bar-map)
6011   (defvar tool-bar-mode))
6012
6013 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6014   ;; We need to make tool bar entries in local keymaps with
6015   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6016   (if (fboundp 'tool-bar-local-item-from-menu)
6017       ;; This is for Emacs 21.3
6018       (tool-bar-local-item-from-menu command icon in-map from-map props)
6019     (tool-bar-add-item-from-menu command icon from-map props)))
6020
6021 (defun message-tool-bar-map ()
6022   (or message-tool-bar-map
6023       (setq message-tool-bar-map
6024             (and
6025              (condition-case nil (require 'tool-bar) (error nil))
6026              (fboundp 'tool-bar-add-item-from-menu)
6027              tool-bar-mode
6028              (let ((tool-bar-map (copy-keymap tool-bar-map))
6029                    (load-path (mm-image-load-path)))
6030                ;; Zap some items which aren't so relevant and take
6031                ;; up space.
6032                (dolist (key '(print-buffer kill-buffer save-buffer
6033                                            write-file dired open-file))
6034                  (define-key tool-bar-map (vector key) nil))
6035                (message-tool-bar-local-item-from-menu
6036                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
6037                (message-tool-bar-local-item-from-menu
6038                 'message-kill-buffer "close" tool-bar-map message-mode-map)
6039                (message-tool-bar-local-item-from-menu
6040                     'message-dont-send "cancel" tool-bar-map message-mode-map)
6041                (message-tool-bar-local-item-from-menu
6042                 'mml-attach-file "attach" tool-bar-map mml-mode-map)
6043                (message-tool-bar-local-item-from-menu
6044                 'ispell-message "spell" tool-bar-map message-mode-map)
6045                (message-tool-bar-local-item-from-menu
6046                 'mml-preview "preview"
6047                 tool-bar-map mml-mode-map)
6048                (message-tool-bar-local-item-from-menu
6049                 'message-insert-importance-high "important"
6050                 tool-bar-map message-mode-map)
6051                (message-tool-bar-local-item-from-menu
6052                 'message-insert-importance-low "unimportant"
6053                 tool-bar-map message-mode-map)
6054                (message-tool-bar-local-item-from-menu
6055                 'message-insert-disposition-notification-to "receipt"
6056                 tool-bar-map message-mode-map)
6057                tool-bar-map)))))
6058
6059 ;;; Group name completion.
6060
6061 (defcustom message-newgroups-header-regexp
6062   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6063   "Regexp that match headers that lists groups."
6064   :group 'message
6065   :type 'regexp)
6066
6067 (defcustom message-completion-alist
6068   (list (cons message-newgroups-header-regexp 'message-expand-group)
6069         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6070         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6071           . message-expand-name)
6072         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6073           . message-expand-name))
6074   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6075   :group 'message
6076   :type '(alist :key-type regexp :value-type function))
6077
6078 (defcustom message-tab-body-function nil
6079   "*Function to execute when `message-tab' (TAB) is executed in the body.
6080 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6081   :group 'message
6082   :type 'function)
6083
6084 (defun message-tab ()
6085   "Complete names according to `message-completion-alist'.
6086 Execute function specified by `message-tab-body-function' when not in
6087 those headers."
6088   (interactive)
6089   (let ((alist message-completion-alist))
6090     (while (and alist
6091                 (let ((mail-abbrev-mode-regexp (caar alist)))
6092                   (not (mail-abbrev-in-expansion-header-p))))
6093       (setq alist (cdr alist)))
6094     (funcall (or (cdar alist) message-tab-body-function
6095                  (lookup-key text-mode-map "\t")
6096                  (lookup-key global-map "\t")
6097                  'indent-relative))))
6098
6099 (defun message-expand-group ()
6100   "Expand the group name under point."
6101   (let* ((b (save-excursion
6102               (save-restriction
6103                 (narrow-to-region
6104                  (save-excursion
6105                    (beginning-of-line)
6106                    (skip-chars-forward "^:")
6107                    (1+ (point)))
6108                  (point))
6109                 (skip-chars-backward "^, \t\n") (point))))
6110          (completion-ignore-case t)
6111          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6112                                             (point))))
6113          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6114          (completions (all-completions string hashtb))
6115          comp)
6116     (delete-region b (point))
6117     (cond
6118      ((= (length completions) 1)
6119       (if (string= (car completions) string)
6120           (progn
6121             (insert string)
6122             (message "Only matching group"))
6123         (insert (car completions))))
6124      ((and (setq comp (try-completion string hashtb))
6125            (not (string= comp string)))
6126       (insert comp))
6127      (t
6128       (insert string)
6129       (if (not comp)
6130           (message "No matching groups")
6131         (save-selected-window
6132           (pop-to-buffer "*Completions*")
6133           (buffer-disable-undo)
6134           (let ((buffer-read-only nil))
6135             (erase-buffer)
6136             (let ((standard-output (current-buffer)))
6137               (display-completion-list (sort completions 'string<)))
6138             (goto-char (point-min))
6139             (delete-region (point) (progn (forward-line 3) (point))))))))))
6140
6141 (defun message-expand-name ()
6142   (if (fboundp 'bbdb-complete-name)
6143       (bbdb-complete-name)
6144     (expand-abbrev)))
6145
6146 ;;; Help stuff.
6147
6148 (defun message-talkative-question (ask question show &rest text)
6149   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6150 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6151 The following arguments may contain lists of values."
6152   (if (and show
6153            (setq text (message-flatten-list text)))
6154       (save-window-excursion
6155         (save-excursion
6156           (with-output-to-temp-buffer " *MESSAGE information message*"
6157             (set-buffer " *MESSAGE information message*")
6158             (fundamental-mode)          ; for Emacs 20.4+
6159             (mapcar 'princ text)
6160             (goto-char (point-min))))
6161         (funcall ask question))
6162     (funcall ask question)))
6163
6164 (defun message-flatten-list (list)
6165   "Return a new, flat list that contains all elements of LIST.
6166
6167 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6168 => (1 2 3 4 5 6 7)"
6169   (cond ((consp list)
6170          (apply 'append (mapcar 'message-flatten-list list)))
6171         (list
6172          (list list))))
6173
6174 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6175   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6176 Then clone the local variables and values from the old buffer to the
6177 new one, cloning only the locals having a substring matching the
6178 regexp varstr."
6179   (let ((oldbuf (current-buffer)))
6180     (save-excursion
6181       (set-buffer (generate-new-buffer name))
6182       (message-clone-locals oldbuf varstr)
6183       (current-buffer))))
6184
6185 (defun message-clone-locals (buffer &optional varstr)
6186   "Clone the local variables from BUFFER to the current buffer."
6187   (let ((locals (save-excursion
6188                   (set-buffer buffer)
6189                   (buffer-local-variables)))
6190         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
6191     (mapcar
6192      (lambda (local)
6193        (when (and (consp local)
6194                   (car local)
6195                   (string-match regexp (symbol-name (car local)))
6196                   (or (null varstr)
6197                       (string-match varstr (symbol-name (car local)))))
6198          (ignore-errors
6199            (set (make-local-variable (car local))
6200                 (cdr local)))))
6201      locals)))
6202
6203 ;;; Miscellaneous functions
6204
6205 (defsubst message-replace-chars-in-string (string from to)
6206   (mm-subst-char-in-string from to string))
6207
6208 ;;;
6209 ;;; MIME functions
6210 ;;;
6211
6212 (defvar message-inhibit-body-encoding nil)
6213
6214 (defun message-encode-message-body ()
6215   (unless message-inhibit-body-encoding
6216     (let ((mail-parse-charset (or mail-parse-charset
6217                                   message-default-charset))
6218           (case-fold-search t)
6219           lines content-type-p)
6220       (message-goto-body)
6221       (save-restriction
6222         (narrow-to-region (point) (point-max))
6223         (let ((new (mml-generate-mime)))
6224           (when new
6225             (delete-region (point-min) (point-max))
6226             (insert new)
6227             (goto-char (point-min))
6228             (if (eq (aref new 0) ?\n)
6229                 (delete-char 1)
6230               (search-forward "\n\n")
6231               (setq lines (buffer-substring (point-min) (1- (point))))
6232               (delete-region (point-min) (point))))))
6233       (save-restriction
6234         (message-narrow-to-headers-or-head)
6235         (message-remove-header "Mime-Version")
6236         (goto-char (point-max))
6237         (insert "MIME-Version: 1.0\n")
6238         (when lines
6239           (insert lines))
6240         (setq content-type-p
6241               (or mml-boundary
6242                   (re-search-backward "^Content-Type:" nil t))))
6243       (save-restriction
6244         (message-narrow-to-headers-or-head)
6245         (message-remove-first-header "Content-Type")
6246         (message-remove-first-header "Content-Transfer-Encoding"))
6247       ;; We always make sure that the message has a Content-Type
6248       ;; header.  This is because some broken MTAs and MUAs get
6249       ;; awfully confused when confronted with a message with a
6250       ;; MIME-Version header and without a Content-Type header.  For
6251       ;; instance, Solaris' /usr/bin/mail.
6252       (unless content-type-p
6253         (goto-char (point-min))
6254         ;; For unknown reason, MIME-Version doesn't exist.
6255         (when (re-search-forward "^MIME-Version:" nil t)
6256           (forward-line 1)
6257           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6258
6259 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6260   "Read from the minibuffer while providing abbrev expansion."
6261   (if (fboundp 'mail-abbrevs-setup)
6262       (let ((mail-abbrev-mode-regexp "")
6263             (minibuffer-setup-hook 'mail-abbrevs-setup)
6264             (minibuffer-local-map message-minibuffer-local-map))
6265         (read-from-minibuffer prompt initial-contents))
6266     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6267           (minibuffer-local-map message-minibuffer-local-map))
6268       (read-string prompt initial-contents))))
6269
6270 (defun message-use-alternative-email-as-from ()
6271   (require 'mail-utils)
6272   (let* ((fields '("To" "Cc"))
6273          (emails
6274           (split-string
6275            (mail-strip-quoted-names
6276             (mapconcat 'message-fetch-reply-field fields ","))
6277            "[ \f\t\n\r\v,]+"))
6278          email)
6279     (while emails
6280       (if (string-match message-alternative-emails (car emails))
6281           (setq email (car emails)
6282                 emails nil))
6283       (pop emails))
6284     (unless (or (not email) (equal email user-mail-address))
6285       (goto-char (point-max))
6286       (insert "From: " email "\n"))))
6287
6288 (defun message-options-get (symbol)
6289   (cdr (assq symbol message-options)))
6290
6291 (defun message-options-set (symbol value)
6292   (let ((the-cons (assq symbol message-options)))
6293     (if the-cons
6294         (if value
6295             (setcdr the-cons value)
6296           (setq message-options (delq the-cons message-options)))
6297       (and value
6298            (push (cons symbol value) message-options))))
6299   value)
6300
6301 (defun message-options-set-recipient ()
6302   (save-restriction
6303     (message-narrow-to-headers-or-head)
6304     (message-options-set 'message-sender
6305                          (mail-strip-quoted-names
6306                           (message-fetch-field "from")))
6307     (message-options-set 'message-recipients
6308                          (mail-strip-quoted-names
6309                           (let ((to (message-fetch-field "to"))
6310                                 (cc (message-fetch-field "cc"))
6311                                 (bcc (message-fetch-field "bcc")))
6312                             (concat
6313                              (or to "")
6314                              (if (and to cc) ", ")
6315                              (or cc "")
6316                              (if (and (or to cc) bcc) ", ")
6317                              (or bcc "")))))))
6318
6319 (when (featurep 'xemacs)
6320   (require 'messagexmas)
6321   (message-xmas-redefine))
6322
6323 (provide 'message)
6324
6325 (run-hooks 'message-load-hook)
6326
6327 ;; Local Variables:
6328 ;; coding: iso-8859-1
6329 ;; End:
6330
6331 ;;; message.el ends here