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