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