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