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