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