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