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