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