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