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