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