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