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