XEmacs 21.2.27 "Hera".
[chise/xemacs-chise.git.1] / src / print.c
1 /* Lisp object printing and output streams.
2    Copyright (C) 1985, 1986, 1988, 1992-1995 Free Software Foundation, Inc.
3    Copyright (C) 1995, 1996 Ben Wing.
4
5 This file is part of XEmacs.
6
7 XEmacs is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
10 later version.
11
12 XEmacs is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with XEmacs; see the file COPYING.  If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 /* Synched up with: Not synched with FSF. */
23
24 /* This file has been Mule-ized. */
25
26 /* Seriously hacked on by Ben Wing for Mule. */
27
28 #include <config.h>
29 #include "lisp.h"
30
31 #include "backtrace.h"
32 #include "buffer.h"
33 #include "bytecode.h"
34 #include "console-tty.h"
35 #include "console-stream.h"
36 #include "extents.h"
37 #include "frame.h"
38 #include "insdel.h"
39 #include "lstream.h"
40 #include "sysfile.h"
41
42 #include <limits.h>
43 #include <float.h>
44 /* Define if not in float.h */
45 #ifndef DBL_DIG
46 #define DBL_DIG 16
47 #endif
48
49 Lisp_Object Vstandard_output, Qstandard_output;
50
51 /* The subroutine object for external-debugging-output is kept here
52    for the convenience of the debugger.  */
53 Lisp_Object Qexternal_debugging_output;
54
55 /* Avoid actual stack overflow in print.  */
56 static int print_depth;
57
58 /* Detect most circularities to print finite output.  */
59 #define PRINT_CIRCLE 200
60 static Lisp_Object being_printed[PRINT_CIRCLE];
61
62 /* Maximum length of list or vector to print in full; noninteger means
63    effectively infinity */
64
65 Lisp_Object Vprint_length;
66 Lisp_Object Qprint_length;
67
68 /* Maximum length of string to print in full; noninteger means
69    effectively infinity */
70
71 Lisp_Object Vprint_string_length;
72 Lisp_Object Qprint_string_length;
73
74 /* Maximum depth of list to print in full; noninteger means
75    effectively infinity.  */
76
77 Lisp_Object Vprint_level;
78
79 /* Label to use when making echo-area messages. */
80
81 Lisp_Object Vprint_message_label;
82
83 /* Nonzero means print newlines in strings as \n.  */
84
85 int print_escape_newlines;
86 int print_readably;
87
88 /* Non-nil means print #: before uninterned symbols.
89    Neither t nor nil means so that and don't clear Vprint_gensym_alist
90    on entry to and exit from print functions.  */
91 Lisp_Object Vprint_gensym;
92 Lisp_Object Vprint_gensym_alist;
93
94 Lisp_Object Qdisplay_error;
95 Lisp_Object Qprint_message_label;
96
97 /* Force immediate output of all printed data.  Used for debugging. */
98 int print_unbuffered;
99
100 FILE *termscript;       /* Stdio stream being used for copy of all output.  */
101
102 \f
103
104 int stdout_needs_newline;
105
106 /* Write a string (in internal format) to stdio stream STREAM. */
107
108 void
109 write_string_to_stdio_stream (FILE *stream, struct console *con,
110                               CONST Bufbyte *str,
111                               Bytecount offset, Bytecount len,
112                               enum external_data_format fmt)
113 {
114   int extlen;
115   CONST Extbyte *extptr;
116
117   GET_CHARPTR_EXT_DATA_ALLOCA (str + offset, len, fmt, extptr, extlen);
118   if (stream)
119     {
120       fwrite (extptr, 1, extlen, stream);
121 #ifdef WINDOWSNT
122       /* Q122442 says that pipes are "treated as files, not as
123          devices", and that this is a feature. Before I found that
124          article, I thought it was a bug. Thanks MS, I feel much
125          better now. - kkm */
126       if (stream == stdout || stream == stderr)
127         fflush (stream);
128 #endif
129     }
130   else
131     {
132       assert (CONSOLE_TTY_P (con));
133       Lstream_write (XLSTREAM (CONSOLE_TTY_DATA (con)->outstream),
134                      extptr, extlen);
135     }
136   if (stream == stdout || stream == stderr ||
137       (!stream && CONSOLE_TTY_DATA (con)->is_stdio))
138     {
139       if (termscript)
140         {
141           fwrite (extptr, 1, extlen, termscript);
142           fflush (termscript);
143         }
144       stdout_needs_newline = (extptr[extlen - 1] != '\n');
145     }
146 }
147
148 /* Write a string to the output location specified in FUNCTION.
149    Arguments NONRELOC, RELOC, OFFSET, and LEN are as in
150    buffer_insert_string_1() in insdel.c. */
151
152 static void
153 output_string (Lisp_Object function, CONST Bufbyte *nonreloc,
154                Lisp_Object reloc, Bytecount offset, Bytecount len)
155 {
156   /* This function can GC */
157   Charcount cclen;
158   /* We change the value of nonreloc (fetching it from reloc as
159      necessary), but we don't want to pass this changed value on to
160      other functions that take both a nonreloc and a reloc, or things
161      may get confused and an assertion failure in
162      fixup_internal_substring() may get triggered. */
163   CONST Bufbyte *newnonreloc = nonreloc;
164   struct gcpro gcpro1, gcpro2;
165
166   /* Emacs won't print while GCing, but an external debugger might */
167   if (gc_in_progress) return;
168
169   /* Perhaps not necessary but probably safer. */
170   GCPRO2 (function, reloc);
171
172   fixup_internal_substring (newnonreloc, reloc, offset, &len);
173
174   if (STRINGP (reloc))
175     newnonreloc = XSTRING_DATA (reloc);
176
177   cclen = bytecount_to_charcount (newnonreloc + offset, len);
178
179   if (LSTREAMP (function))
180     {
181       if (STRINGP (reloc))
182         {
183           /* Protect against Lstream_write() causing a GC and
184              relocating the string.  For small strings, we do it by
185              alloc'ing the string and using a copy; for large strings,
186              we inhibit GC.  */
187           if (len < 65536)
188             {
189               Bufbyte *copied = alloca_array (Bufbyte, len);
190               memcpy (copied, newnonreloc + offset, len);
191               Lstream_write (XLSTREAM (function), copied, len);
192             }
193           else
194             {
195               int speccount = specpdl_depth ();
196               record_unwind_protect (restore_gc_inhibit,
197                                      make_int (gc_currently_forbidden));
198               gc_currently_forbidden = 1;
199               Lstream_write (XLSTREAM (function), newnonreloc + offset, len);
200               unbind_to (speccount, Qnil);
201             }
202         }
203       else
204         Lstream_write (XLSTREAM (function), newnonreloc + offset, len);
205
206       if (print_unbuffered)
207         Lstream_flush (XLSTREAM (function));
208     }
209   else if (BUFFERP (function))
210     {
211       CHECK_LIVE_BUFFER (function);
212       buffer_insert_string (XBUFFER (function), nonreloc, reloc, offset, len);
213     }
214   else if (MARKERP (function))
215     {
216       /* marker_position() will err if marker doesn't point anywhere.  */
217       Bufpos spoint = marker_position (function);
218
219       buffer_insert_string_1 (XMARKER (function)->buffer,
220                               spoint, nonreloc, reloc, offset, len,
221                               0);
222       Fset_marker (function, make_int (spoint + cclen),
223                    Fmarker_buffer (function));
224     }
225   else if (FRAMEP (function))
226     {
227       /* This gets used by functions not invoking print_prepare(),
228          such as Fwrite_char, Fterpri, etc..  */
229       struct frame *f = XFRAME (function);
230       CHECK_LIVE_FRAME (function);
231
232       if (!EQ (Vprint_message_label, echo_area_status (f)))
233         clear_echo_area_from_print (f, Qnil, 1);
234       echo_area_append (f, nonreloc, reloc, offset, len, Vprint_message_label);
235     }
236   else if (EQ (function, Qt) || EQ (function, Qnil))
237     {
238       write_string_to_stdio_stream (stdout, 0, newnonreloc, offset, len,
239                                     FORMAT_TERMINAL);
240     }
241   else
242     {
243       Charcount ccoff = bytecount_to_charcount (newnonreloc, offset);
244       Charcount iii;
245
246       for (iii = ccoff; iii < cclen + ccoff; iii++)
247         {
248           call1 (function,
249                  make_char (charptr_emchar_n (newnonreloc, iii)));
250           if (STRINGP (reloc))
251             newnonreloc = XSTRING_DATA (reloc);
252         }
253     }
254
255   UNGCPRO;
256 }
257 \f
258 #define RESET_PRINT_GENSYM do {                 \
259   if (!CONSP (Vprint_gensym))                   \
260     Vprint_gensym_alist = Qnil;                 \
261 } while (0)
262
263 static Lisp_Object
264 canonicalize_printcharfun (Lisp_Object printcharfun)
265 {
266   if (NILP (printcharfun))
267     printcharfun = Vstandard_output;
268
269   if (EQ (printcharfun, Qt) || NILP (printcharfun))
270     printcharfun = Fselected_frame (Qnil); /* print to minibuffer */
271
272   return printcharfun;
273 }
274
275 static Lisp_Object
276 print_prepare (Lisp_Object printcharfun, Lisp_Object *frame_kludge)
277 {
278   /* Emacs won't print while GCing, but an external debugger might */
279   if (gc_in_progress)
280     return Qnil;
281
282   RESET_PRINT_GENSYM;
283
284   printcharfun = canonicalize_printcharfun (printcharfun);
285
286   /* Here we could safely return the canonicalized PRINTCHARFUN.
287      However, if PRINTCHARFUN is a frame, printing of complex
288      structures becomes very expensive, because `append-message'
289      (called by echo_area_append) gets called as many times as
290      output_string() is called (and that's a *lot*).  append-message
291      tries to keep top of the message-stack in sync with the contents
292      of " *Echo Area" buffer, consing a new string for each component
293      of the printed structure.  For instance, if you print (a a),
294      append-message will cons up the following strings:
295
296          "("
297          "(a"
298          "(a "
299          "(a a"
300          "(a a)"
301
302      and will use only the last one.  With larger objects, this turns
303      into an O(n^2) consing frenzy that locks up XEmacs in incessant
304      garbage collection.
305
306      We prevent this by creating a resizing_buffer stream and letting
307      the printer write into it.  print_finish() will notice this
308      stream, and invoke echo_area_append() with the stream's buffer,
309      only once.  */
310   if (FRAMEP (printcharfun))
311     {
312       CHECK_LIVE_FRAME (printcharfun);
313       *frame_kludge = printcharfun;
314       printcharfun = make_resizing_buffer_output_stream ();
315     }
316
317   return printcharfun;
318 }
319
320 static void
321 print_finish (Lisp_Object stream, Lisp_Object frame_kludge)
322 {
323   /* Emacs won't print while GCing, but an external debugger might */
324   if (gc_in_progress)
325     return;
326
327   RESET_PRINT_GENSYM;
328
329   /* See the comment in print_prepare().  */
330   if (FRAMEP (frame_kludge))
331     {
332       struct frame *f = XFRAME (frame_kludge);
333       Lstream *str = XLSTREAM (stream);
334       CHECK_LIVE_FRAME (frame_kludge);
335
336       Lstream_flush (str);
337       if (!EQ (Vprint_message_label, echo_area_status (f)))
338         clear_echo_area_from_print (f, Qnil, 1);
339       echo_area_append (f, resizing_buffer_stream_ptr (str),
340                         Qnil, 0, Lstream_byte_count (str),
341                         Vprint_message_label);
342       Lstream_delete (str);
343     }
344 }
345 \f
346 /* Used for printing a single-byte character (*not* any Emchar).  */
347 #define write_char_internal(string_of_length_1, stream)                 \
348   output_string (stream, (CONST Bufbyte *) (string_of_length_1),        \
349                  Qnil, 0, 1)
350
351 /* NOTE: Do not call this with the data of a Lisp_String, as
352    printcharfun might cause a GC, which might cause the string's data
353    to be relocated.  To princ a Lisp string, use:
354
355        print_internal (string, printcharfun, 0);
356
357    Also note that STREAM should be the result of
358    canonicalize_printcharfun() (i.e. Qnil means stdout, not
359    Vstandard_output, etc.)  */
360 void
361 write_string_1 (CONST Bufbyte *str, Bytecount size, Lisp_Object stream)
362 {
363   /* This function can GC */
364 #ifdef ERROR_CHECK_BUFPOS
365   assert (size >= 0);
366 #endif
367   output_string (stream, str, Qnil, 0, size);
368 }
369
370 void
371 write_c_string (CONST char *str, Lisp_Object stream)
372 {
373   /* This function can GC */
374   write_string_1 ((CONST Bufbyte *) str, strlen (str), stream);
375 }
376
377 \f
378 DEFUN ("write-char", Fwrite_char, 1, 2, 0, /*
379 Output character CH to stream STREAM.
380 STREAM defaults to the value of `standard-output' (which see).
381 */
382        (ch, stream))
383 {
384   /* This function can GC */
385   Bufbyte str[MAX_EMCHAR_LEN];
386   Bytecount len;
387
388   CHECK_CHAR_COERCE_INT (ch);
389   len = set_charptr_emchar (str, XCHAR (ch));
390   output_string (canonicalize_printcharfun (stream), str, Qnil, 0, len);
391   return ch;
392 }
393
394 void
395 temp_output_buffer_setup (Lisp_Object bufname)
396 {
397   /* This function can GC */
398   struct buffer *old = current_buffer;
399   Lisp_Object buf;
400
401 #ifdef I18N3
402   /* #### This function should accept a Lisp_Object instead of a char *,
403      so that proper translation on the buffer name can occur. */
404 #endif
405
406   Fset_buffer (Fget_buffer_create (bufname));
407
408   current_buffer->read_only = Qnil;
409   Ferase_buffer (Qnil);
410
411   XSETBUFFER (buf, current_buffer);
412   specbind (Qstandard_output, buf);
413
414   set_buffer_internal (old);
415 }
416
417 Lisp_Object
418 internal_with_output_to_temp_buffer (Lisp_Object bufname,
419                                      Lisp_Object (*function) (Lisp_Object arg),
420                                      Lisp_Object arg,
421                                      Lisp_Object same_frame)
422 {
423   int speccount = specpdl_depth ();
424   struct gcpro gcpro1, gcpro2, gcpro3;
425   Lisp_Object buf = Qnil;
426
427   GCPRO3 (buf, arg, same_frame);
428
429   temp_output_buffer_setup (bufname);
430   buf = Vstandard_output;
431
432   arg = (*function) (arg);
433
434   temp_output_buffer_show (buf, same_frame);
435   UNGCPRO;
436
437   return unbind_to (speccount, arg);
438 }
439
440 DEFUN ("with-output-to-temp-buffer", Fwith_output_to_temp_buffer, 1, UNEVALLED, 0, /*
441 Bind `standard-output' to buffer BUFNAME, eval BODY, then show that buffer.
442 The buffer is cleared out initially, and marked as unmodified when done.
443 All output done by BODY is inserted in that buffer by default.
444 The buffer is displayed in another window, but not selected.
445 The value of the last form in BODY is returned.
446 If BODY does not finish normally, the buffer BUFNAME is not displayed.
447
448 If variable `temp-buffer-show-function' is non-nil, call it at the end
449 to get the buffer displayed.  It gets one argument, the buffer to display.
450 */
451        (args))
452 {
453   /* This function can GC */
454   Lisp_Object name = Qnil;
455   int speccount = specpdl_depth ();
456   struct gcpro gcpro1, gcpro2;
457   Lisp_Object val = Qnil;
458
459 #ifdef I18N3
460   /* #### should set the buffer to be translating.  See print_internal(). */
461 #endif
462
463   GCPRO2 (name, val);
464   name = Feval (XCAR (args));
465
466   CHECK_STRING (name);
467
468   temp_output_buffer_setup (name);
469   UNGCPRO;
470
471   val = Fprogn (XCDR (args));
472
473   temp_output_buffer_show (Vstandard_output, Qnil);
474
475   return unbind_to (speccount, val);
476 }
477 \f
478 DEFUN ("terpri", Fterpri, 0, 1, 0, /*
479 Output a newline to STREAM.
480 If STREAM is omitted or nil, the value of `standard-output' is used.
481 */
482        (stream))
483 {
484   /* This function can GC */
485   write_char_internal ("\n", canonicalize_printcharfun (stream));
486   return Qt;
487 }
488
489 DEFUN ("prin1", Fprin1, 1, 2, 0, /*
490 Output the printed representation of OBJECT, any Lisp object.
491 Quoting characters are printed when needed to make output that `read'
492 can handle, whenever this is possible.
493 Output stream is STREAM, or value of `standard-output' (which see).
494 */
495        (object, stream))
496 {
497   /* This function can GC */
498   Lisp_Object frame = Qnil;
499   struct gcpro gcpro1, gcpro2;
500   GCPRO2 (object, stream);
501
502   print_depth = 0;
503   stream = print_prepare (stream, &frame);
504   print_internal (object, stream, 1);
505   print_finish (stream, frame);
506
507   UNGCPRO;
508   return object;
509 }
510
511 DEFUN ("prin1-to-string", Fprin1_to_string, 1, 2, 0, /*
512 Return a string containing the printed representation of OBJECT,
513 any Lisp object.  Quoting characters are used when needed to make output
514 that `read' can handle, whenever this is possible, unless the optional
515 second argument NOESCAPE is non-nil.
516 */
517        (object, noescape))
518 {
519   /* This function can GC */
520   Lisp_Object result = Qnil;
521   Lisp_Object stream = make_resizing_buffer_output_stream ();
522   Lstream *str = XLSTREAM (stream);
523   /* gcpro OBJECT in case a caller forgot to do so */
524   struct gcpro gcpro1, gcpro2, gcpro3;
525   GCPRO3 (object, stream, result);
526
527   print_depth = 0;
528   RESET_PRINT_GENSYM;
529   print_internal (object, stream, NILP (noescape));
530   RESET_PRINT_GENSYM;
531   Lstream_flush (str);
532   UNGCPRO;
533   result = make_string (resizing_buffer_stream_ptr (str),
534                         Lstream_byte_count (str));
535   Lstream_delete (str);
536   return result;
537 }
538
539 DEFUN ("princ", Fprinc, 1, 2, 0, /*
540 Output the printed representation of OBJECT, any Lisp object.
541 No quoting characters are used; no delimiters are printed around
542 the contents of strings.
543 Output stream is STREAM, or value of standard-output (which see).
544 */
545        (object, stream))
546 {
547   /* This function can GC */
548   Lisp_Object frame = Qnil;
549   struct gcpro gcpro1, gcpro2;
550
551   GCPRO2 (object, stream);
552   stream = print_prepare (stream, &frame);
553   print_depth = 0;
554   print_internal (object, stream, 0);
555   print_finish (stream, frame);
556   UNGCPRO;
557   return object;
558 }
559
560 DEFUN ("print", Fprint, 1, 2, 0, /*
561 Output the printed representation of OBJECT, with newlines around it.
562 Quoting characters are printed when needed to make output that `read'
563 can handle, whenever this is possible.
564 Output stream is STREAM, or value of `standard-output' (which see).
565 */
566        (object, stream))
567 {
568   /* This function can GC */
569   Lisp_Object frame = Qnil;
570   struct gcpro gcpro1, gcpro2;
571
572   GCPRO2 (object, stream);
573   stream = print_prepare (stream, &frame);
574   print_depth = 0;
575   write_char_internal ("\n", stream);
576   print_internal (object, stream, 1);
577   write_char_internal ("\n", stream);
578   print_finish (stream, frame);
579   UNGCPRO;
580   return object;
581 }
582 \f
583 /* Print an error message for the error DATA to STREAM.  This is a
584    complete implementation of `display-error', which used to be in
585    Lisp (see prim/cmdloop.el).  It was ported to C so it can be used
586    efficiently by Ferror_message_string.  Fdisplay_error and
587    Ferror_message_string are trivial wrappers around this function.
588
589    STREAM should be the result of canonicalize_printcharfun().  */
590 static void
591 print_error_message (Lisp_Object error_object, Lisp_Object stream)
592 {
593   /* This function can GC */
594   Lisp_Object type = Fcar_safe (error_object);
595   Lisp_Object method = Qnil;
596   Lisp_Object tail;
597
598   /* No need to GCPRO anything under the assumption that ERROR_OBJECT
599      is GCPRO'd.  */
600
601   if (! (CONSP (error_object) && SYMBOLP (type)
602          && CONSP (Fget (type, Qerror_conditions, Qnil))))
603     goto error_throw;
604
605   tail = XCDR (error_object);
606   while (!NILP (tail))
607     {
608       if (CONSP (tail))
609         tail = XCDR (tail);
610       else
611         goto error_throw;
612     }
613   tail = Fget (type, Qerror_conditions, Qnil);
614   while (!NILP (tail))
615     {
616       if (!(CONSP (tail) && SYMBOLP (XCAR (tail))))
617         goto error_throw;
618       else if (!NILP (Fget (XCAR (tail), Qdisplay_error, Qnil)))
619         {
620           method = Fget (XCAR (tail), Qdisplay_error, Qnil);
621           goto error_throw;
622         }
623       else
624         tail = XCDR (tail);
625     }
626   /* Default method */
627   {
628     int first = 1;
629     int speccount = specpdl_depth ();
630     Lisp_Object frame = Qnil;
631     struct gcpro gcpro1;
632     GCPRO1 (stream);
633
634     specbind (Qprint_message_label, Qerror);
635     stream = print_prepare (stream, &frame);
636
637     tail = Fcdr (error_object);
638     if (EQ (type, Qerror))
639       {
640         print_internal (Fcar (tail), stream, 0);
641         tail = Fcdr (tail);
642       }
643     else
644       {
645         Lisp_Object errmsg = Fget (type, Qerror_message, Qnil);
646         if (NILP (errmsg))
647           print_internal (type, stream, 0);
648         else
649           print_internal (LISP_GETTEXT (errmsg), stream, 0);
650       }
651     while (!NILP (tail))
652       {
653         write_c_string (first ? ": " : ", ", stream);
654         print_internal (Fcar (tail), stream, 1);
655         tail = Fcdr (tail);
656         first = 0;
657       }
658     print_finish (stream, frame);
659     UNGCPRO;
660     unbind_to (speccount, Qnil);
661     return;
662     /* not reached */
663   }
664
665  error_throw:
666   if (NILP (method))
667     {
668       write_c_string (GETTEXT ("Peculiar error "), stream);
669       print_internal (error_object, stream, 1);
670       return;
671     }
672   else
673     {
674       call2 (method, error_object, stream);
675     }
676 }
677
678 DEFUN ("error-message-string", Ferror_message_string, 1, 1, 0, /*
679 Convert ERROR-OBJECT to an error message, and return it.
680
681 The format of ERROR-OBJECT should be (ERROR-SYMBOL . DATA).  The
682 message is equivalent to the one that would be issued by
683 `display-error' with the same argument.
684 */
685        (error_object))
686 {
687   /* This function can GC */
688   Lisp_Object result = Qnil;
689   Lisp_Object stream = make_resizing_buffer_output_stream ();
690   struct gcpro gcpro1;
691   GCPRO1 (stream);
692
693   print_error_message (error_object, stream);
694   Lstream_flush (XLSTREAM (stream));
695   result = make_string (resizing_buffer_stream_ptr (XLSTREAM (stream)),
696                         Lstream_byte_count (XLSTREAM (stream)));
697   Lstream_delete (XLSTREAM (stream));
698
699   UNGCPRO;
700   return result;
701 }
702
703 DEFUN ("display-error", Fdisplay_error, 2, 2, 0, /*
704 Display ERROR-OBJECT on STREAM in a user-friendly way.
705 */
706        (error_object, stream))
707 {
708   /* This function can GC */
709   print_error_message (error_object, canonicalize_printcharfun (stream));
710   return Qnil;
711 }
712
713 \f
714 #ifdef LISP_FLOAT_TYPE
715
716 Lisp_Object Vfloat_output_format;
717
718 /*
719  * This buffer should be at least as large as the max string size of the
720  * largest float, printed in the biggest notation.  This is undoubtably
721  * 20d float_output_format, with the negative of the C-constant "HUGE"
722  * from <math.h>.
723  *
724  * On the vax the worst case is -1e38 in 20d format which takes 61 bytes.
725  *
726  * I assume that IEEE-754 format numbers can take 329 bytes for the worst
727  * case of -1e307 in 20d float_output_format. What is one to do (short of
728  * re-writing _doprnt to be more sane)?
729  *                      -wsr
730  */
731 void
732 float_to_string (char *buf, double data)
733 {
734   Bufbyte *cp, c;
735   int width;
736
737   if (NILP (Vfloat_output_format)
738       || !STRINGP (Vfloat_output_format))
739   lose:
740     sprintf (buf, "%.16g", data);
741   else                  /* oink oink */
742     {
743       /* Check that the spec we have is fully valid.
744          This means not only valid for printf,
745          but meant for floats, and reasonable.  */
746       cp = XSTRING_DATA (Vfloat_output_format);
747
748       if (cp[0] != '%')
749         goto lose;
750       if (cp[1] != '.')
751         goto lose;
752
753       cp += 2;
754       for (width = 0; (c = *cp, isdigit (c)); cp++)
755         {
756           width *= 10;
757           width += c - '0';
758         }
759
760       if (*cp != 'e' && *cp != 'f' && *cp != 'g' && *cp != 'E' && *cp != 'G')
761         goto lose;
762
763       if (width < (int) (*cp != 'e' && *cp != 'E') || width > DBL_DIG)
764         goto lose;
765
766       if (cp[1] != 0)
767         goto lose;
768
769       sprintf (buf, (char *) XSTRING_DATA (Vfloat_output_format),
770                data);
771     }
772
773   /* added by jwz: don't allow "1.0" to print as "1"; that destroys
774      the read-equivalence of lisp objects.  (* x 1) and (* x 1.0) do
775      not do the same thing, so it's important that the printed
776      representation of that form not be corrupted by the printer.
777    */
778   {
779     Bufbyte *s = (Bufbyte *) buf; /* don't use signed chars here!
780                                      isdigit() can't hack them! */
781     if (*s == '-') s++;
782     for (; *s; s++)
783       /* if there's a non-digit, then there is a decimal point, or
784          it's in exponential notation, both of which are ok. */
785       if (!isdigit (*s))
786         goto DONE_LABEL;
787     /* otherwise, we need to hack it. */
788     *s++ = '.';
789     *s++ = '0';
790     *s = 0;
791   }
792  DONE_LABEL:
793
794   /* Some machines print "0.4" as ".4".  I don't like that. */
795   if (buf [0] == '.' || (buf [0] == '-' && buf [1] == '.'))
796     {
797       int i;
798       for (i = strlen (buf) + 1; i >= 0; i--)
799         buf [i+1] = buf [i];
800       buf [(buf [0] == '-' ? 1 : 0)] = '0';
801     }
802 }
803 #endif /* LISP_FLOAT_TYPE */
804
805 /* Print NUMBER to BUFFER.  The digits are first written in reverse
806    order (the least significant digit first), and are then reversed.
807    This is equivalent to sprintf(buffer, "%ld", number), only much
808    faster.
809
810    BUFFER should accept 24 bytes.  This should suffice for the longest
811    numbers on 64-bit machines, including the `-' sign and the trailing
812    \0.  */
813 void
814 long_to_string (char *buffer, long number)
815 {
816 #if (SIZEOF_LONG != 4) && (SIZEOF_LONG != 8)
817   /* Huh? */
818   sprintf (buffer, "%ld", number);
819 #else /* (SIZEOF_LONG == 4) || (SIZEOF_LONG == 8) */
820   char *p = buffer;
821   int force = 0;
822
823   if (number < 0)
824     {
825       *p++ = '-';
826       number = -number;
827     }
828
829 #define FROB(figure) do {                                               \
830     if (force || number >= figure)                                      \
831       *p++ = number / figure + '0', number %= figure, force = 1;        \
832     } while (0)
833 #if SIZEOF_LONG == 8
834   FROB (1000000000000000000L);
835   FROB (100000000000000000L);
836   FROB (10000000000000000L);
837   FROB (1000000000000000L);
838   FROB (100000000000000L);
839   FROB (10000000000000L);
840   FROB (1000000000000L);
841   FROB (100000000000L);
842   FROB (10000000000L);
843 #endif /* SIZEOF_LONG == 8 */
844   FROB (1000000000);
845   FROB (100000000);
846   FROB (10000000);
847   FROB (1000000);
848   FROB (100000);
849   FROB (10000);
850   FROB (1000);
851   FROB (100);
852   FROB (10);
853 #undef FROB
854   *p++ = number + '0';
855   *p = '\0';
856 #endif /* (SIZEOF_LONG == 4) || (SIZEOF_LONG == 8) */
857 }
858 \f
859 static void
860 print_vector_internal (CONST char *start, CONST char *end,
861                        Lisp_Object obj,
862                        Lisp_Object printcharfun, int escapeflag)
863 {
864   /* This function can GC */
865   int i;
866   int len = XVECTOR_LENGTH (obj);
867   int last = len;
868   struct gcpro gcpro1, gcpro2;
869   GCPRO2 (obj, printcharfun);
870
871   if (INTP (Vprint_length))
872     {
873       int max = XINT (Vprint_length);
874       if (max < len) last = max;
875     }
876
877   write_c_string (start, printcharfun);
878   for (i = 0; i < last; i++)
879     {
880       Lisp_Object elt = XVECTOR_DATA (obj)[i];
881       if (i != 0) write_char_internal (" ", printcharfun);
882       print_internal (elt, printcharfun, escapeflag);
883     }
884   UNGCPRO;
885   if (last != len)
886     write_c_string (" ...", printcharfun);
887   write_c_string (end, printcharfun);
888 }
889
890 void
891 print_cons (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
892 {
893   /* This function can GC */
894   struct gcpro gcpro1, gcpro2;
895
896   /* If print_readably is on, print (quote -foo-) as '-foo-
897      (Yeah, this should really be what print-pretty does, but we
898      don't have the rest of a pretty printer, and this actually
899      has non-negligible impact on size/speed of .elc files.)
900   */
901   if (print_readably &&
902       EQ (XCAR (obj), Qquote) &&
903       CONSP (XCDR (obj)) &&
904       NILP (XCDR (XCDR (obj))))
905     {
906       obj = XCAR (XCDR (obj));
907       GCPRO2 (obj, printcharfun);
908       write_char_internal ("\'", printcharfun);
909       UNGCPRO;
910       print_internal (obj, printcharfun, escapeflag);
911       return;
912     }
913
914   GCPRO2 (obj, printcharfun);
915   write_char_internal ("(", printcharfun);
916
917   {
918     int len;
919     int max = INTP (Vprint_length) ? XINT (Vprint_length) : INT_MAX;
920     Lisp_Object tortoise;
921     /* Use tortoise/hare to make sure circular lists don't infloop */
922
923     for (tortoise = obj, len = 0;
924          CONSP (obj);
925          obj = XCDR (obj), len++)
926       {
927         if (len > 0)
928           write_char_internal (" ", printcharfun);
929         if (EQ (obj, tortoise) && len > 0)
930           {
931             if (print_readably)
932               error ("printing unreadable circular list");
933             else
934               write_c_string ("... <circular list>", printcharfun);
935             break;
936           }
937         if (len & 1)
938           tortoise = XCDR (tortoise);
939         if (len > max)
940           {
941             write_c_string ("...", printcharfun);
942             break;
943           }
944         print_internal (XCAR (obj), printcharfun, escapeflag);
945       }
946   }
947   if (!LISTP (obj))
948     {
949       write_c_string (" . ", printcharfun);
950       print_internal (obj, printcharfun, escapeflag);
951     }
952   UNGCPRO;
953
954   write_char_internal (")", printcharfun);
955   return;
956 }
957
958 void
959 print_vector (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
960 {
961   print_vector_internal ("[", "]", obj, printcharfun, escapeflag);
962 }
963
964 void
965 print_string (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
966 {
967   struct Lisp_String *s = XSTRING (obj);
968   /* We distinguish between Bytecounts and Charcounts, to make
969      Vprint_string_length work correctly under Mule.  */
970   Charcount size = string_char_length (s);
971   Charcount max = size;
972   Bytecount bcmax = string_length (s);
973   struct gcpro gcpro1, gcpro2;
974   GCPRO2 (obj, printcharfun);
975
976   if (INTP (Vprint_string_length) &&
977       XINT (Vprint_string_length) < max)
978     {
979       max = XINT (Vprint_string_length);
980       bcmax = charcount_to_bytecount (string_data (s), max);
981     }
982   if (max < 0)
983     {
984       max = 0;
985       bcmax = 0;
986     }
987
988   if (!escapeflag)
989     {
990       /* This deals with GC-relocation and Mule. */
991       output_string (printcharfun, 0, obj, 0, bcmax);
992       if (max < size)
993         write_c_string (" ...", printcharfun);
994     }
995   else
996     {
997       Bytecount i, last = 0;
998
999       write_char_internal ("\"", printcharfun);
1000       for (i = 0; i < bcmax; i++)
1001         {
1002           Bufbyte ch = string_byte (s, i);
1003           if (ch == '\"' || ch == '\\'
1004               || (ch == '\n' && print_escape_newlines))
1005             {
1006               if (i > last)
1007                 {
1008                   output_string (printcharfun, 0, obj, last,
1009                                  i - last);
1010                 }
1011               if (ch == '\n')
1012                 {
1013                   write_c_string ("\\n", printcharfun);
1014                 }
1015               else
1016                 {
1017                   write_char_internal ("\\", printcharfun);
1018                   /* This is correct for Mule because the
1019                      character is either \ or " */
1020                   write_char_internal (string_data (s) + i, printcharfun);
1021                 }
1022               last = i + 1;
1023             }
1024         }
1025       if (bcmax > last)
1026         {
1027           output_string (printcharfun, 0, obj, last,
1028                          bcmax - last);
1029         }
1030       if (max < size)
1031         write_c_string (" ...", printcharfun);
1032       write_char_internal ("\"", printcharfun);
1033     }
1034   UNGCPRO;
1035 }
1036
1037 static void
1038 default_object_printer (Lisp_Object obj, Lisp_Object printcharfun,
1039                         int escapeflag)
1040 {
1041   struct lcrecord_header *header =
1042     (struct lcrecord_header *) XPNTR (obj);
1043   char buf[200];
1044
1045   if (print_readably)
1046     error ("printing unreadable object #<%s 0x%x>",
1047            LHEADER_IMPLEMENTATION (&header->lheader)->name,
1048            header->uid);
1049
1050   sprintf (buf, "#<%s 0x%x>",
1051            LHEADER_IMPLEMENTATION (&header->lheader)->name,
1052            header->uid);
1053   write_c_string (buf, printcharfun);
1054 }
1055
1056 void
1057 internal_object_printer (Lisp_Object obj, Lisp_Object printcharfun,
1058                          int escapeflag)
1059 {
1060   char buf[200];
1061   sprintf (buf, "#<INTERNAL OBJECT (XEmacs bug?) (%s) 0x%lx>",
1062            XRECORD_LHEADER_IMPLEMENTATION (obj)->name,
1063            (unsigned long) XPNTR (obj));
1064   write_c_string (buf, printcharfun);
1065 }
1066
1067 void
1068 print_internal (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
1069 {
1070   /* This function can GC */
1071
1072   QUIT;
1073
1074   /* Emacs won't print while GCing, but an external debugger might */
1075   if (gc_in_progress) return;
1076
1077 #ifdef I18N3
1078   /* #### Both input and output streams should have a flag associated
1079      with them indicating whether output to that stream, or strings
1080      read from the stream, get translated using Fgettext().  Such a
1081      stream is called a "translating stream".  For the minibuffer and
1082      external-debugging-output this is always true on output, and
1083      with-output-to-temp-buffer sets the flag to true for the buffer
1084      it creates.  This flag should also be user-settable.  Perhaps it
1085      should be split up into two flags, one for input and one for
1086      output. */
1087 #endif
1088
1089   /* Detect circularities and truncate them.
1090      No need to offer any alternative--this is better than an error.  */
1091   if (CONSP (obj) || VECTORP (obj) || COMPILED_FUNCTIONP (obj))
1092     {
1093       int i;
1094       for (i = 0; i < print_depth; i++)
1095         if (EQ (obj, being_printed[i]))
1096           {
1097             char buf[32];
1098             *buf = '#';
1099             long_to_string (buf + 1, i);
1100             write_c_string (buf, printcharfun);
1101             return;
1102           }
1103     }
1104
1105   being_printed[print_depth] = obj;
1106   print_depth++;
1107
1108   if (print_depth > PRINT_CIRCLE)
1109     error ("Apparently circular structure being printed");
1110
1111   switch (XTYPE (obj))
1112     {
1113     case Lisp_Type_Int_Even:
1114     case Lisp_Type_Int_Odd:
1115       {
1116         /* ASCII Decimal representation uses 2.4 times as many bits as
1117            machine binary.  */
1118         char buf[3 * sizeof (EMACS_INT) + 5];
1119         long_to_string (buf, XINT (obj));
1120         write_c_string (buf, printcharfun);
1121         break;
1122       }
1123
1124     case Lisp_Type_Char:
1125       {
1126         /* God intended that this be #\..., you know. */
1127         char buf[16];
1128         Emchar ch = XCHAR (obj);
1129         char *p = buf;
1130         *p++ = '?';
1131         if (ch < 32)
1132           {
1133             *p++ = '\\';
1134             switch (ch)
1135               {
1136               case '\t': *p++ = 't'; break;
1137               case '\n': *p++ = 'n'; break;
1138               case '\r': *p++ = 'r'; break;
1139               default:
1140                 *p++ = '^';
1141                 *p++ = ch + 64;
1142                 if ((ch + 64) == '\\')
1143                   *p++ = '\\';
1144                 break;
1145               }
1146           }
1147         else if (ch < 127)
1148           {
1149             /* syntactically special characters should be escaped. */
1150             switch (ch)
1151               {
1152               case ' ':
1153               case '"':
1154               case '#':
1155               case '\'':
1156               case '(':
1157               case ')':
1158               case ',':
1159               case '.':
1160               case ';':
1161               case '?':
1162               case '[':
1163               case '\\':
1164               case ']':
1165               case '`':
1166                 *p++ = '\\';
1167               }
1168             *p++ = ch;
1169           }
1170         else if (ch == 127)
1171           {
1172             *p++ = '\\', *p++ = '^', *p++ = '?';
1173           }
1174         else if (ch < 160)
1175           {
1176             *p++ = '\\', *p++ = '^';
1177             p += set_charptr_emchar ((Bufbyte *) p, ch + 64);
1178           }
1179         else
1180           {
1181             p += set_charptr_emchar ((Bufbyte *) p, ch);
1182           }
1183           
1184         output_string (printcharfun, (Bufbyte *) buf, Qnil, 0, p - buf);
1185
1186         break;
1187       }
1188
1189     case Lisp_Type_Record:
1190       {
1191         struct lrecord_header *lheader = XRECORD_LHEADER (obj);
1192         struct gcpro gcpro1, gcpro2;
1193
1194         if (CONSP (obj) || VECTORP(obj))
1195           {
1196             /* If deeper than spec'd depth, print placeholder.  */
1197             if (INTP (Vprint_level)
1198                 && print_depth > XINT (Vprint_level))
1199               {
1200                 GCPRO2 (obj, printcharfun);
1201                 write_c_string ("...", printcharfun);
1202                 UNGCPRO;
1203                 break;
1204               }
1205           }
1206
1207         GCPRO2 (obj, printcharfun);
1208         if (LHEADER_IMPLEMENTATION (lheader)->printer)
1209           ((LHEADER_IMPLEMENTATION (lheader)->printer)
1210            (obj, printcharfun, escapeflag));
1211         else
1212           default_object_printer (obj, printcharfun, escapeflag);
1213         UNGCPRO;
1214         break;
1215       }
1216
1217     default:
1218       {
1219 #ifdef ERROR_CHECK_TYPECHECK
1220         abort ();
1221 #else  /* not ERROR_CHECK_TYPECHECK */
1222         char buf[128];
1223         /* We're in trouble if this happens! */
1224         if (print_readably)
1225           error ("printing illegal data type #o%03o",
1226                  (int) XTYPE (obj));
1227         write_c_string ("#<EMACS BUG: ILLEGAL DATATYPE ",
1228                         printcharfun);
1229         sprintf (buf, "(#o%3o)", (int) XTYPE (obj));
1230         write_c_string (buf, printcharfun);
1231         write_c_string
1232           (" Save your buffers immediately and please report this bug>",
1233            printcharfun);
1234 #endif /* not ERROR_CHECK_TYPECHECK */
1235         break;
1236       }
1237     }
1238
1239   print_depth--;
1240 }
1241
1242
1243 #ifdef LISP_FLOAT_TYPE
1244 void
1245 print_float (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
1246 {
1247   char pigbuf[350];     /* see comments in float_to_string */
1248
1249   float_to_string (pigbuf, XFLOAT_DATA (obj));
1250   write_c_string (pigbuf, printcharfun);
1251 }
1252 #endif /* LISP_FLOAT_TYPE */
1253
1254 void
1255 print_symbol (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
1256 {
1257   /* This function can GC */
1258   /* #### Bug!! (intern "") isn't printed in some distinguished way */
1259   /* ####  (the reader also loses on it) */
1260   struct Lisp_String *name = symbol_name (XSYMBOL (obj));
1261   Bytecount size = string_length (name);
1262   struct gcpro gcpro1, gcpro2;
1263
1264   if (!escapeflag)
1265     {
1266       /* This deals with GC-relocation */
1267       Lisp_Object nameobj;
1268       XSETSTRING (nameobj, name);
1269       output_string (printcharfun, 0, nameobj, 0, size);
1270       return;
1271     }
1272   GCPRO2 (obj, printcharfun);
1273
1274   /* If we print an uninterned symbol as part of a complex object and
1275      the flag print-gensym is non-nil, prefix it with #n= to read the
1276      object back with the #n# reader syntax later if needed.  */
1277   if (!NILP (Vprint_gensym)
1278       /* #### Test whether this produces a noticable slow-down for
1279          printing when print-gensym is non-nil.  */
1280       && !EQ (obj, oblookup (Vobarray,
1281                              string_data (symbol_name (XSYMBOL (obj))),
1282                              string_length (symbol_name (XSYMBOL (obj))))))
1283     {
1284       if (print_depth > 1)
1285         {
1286           Lisp_Object tem = Fassq (obj, Vprint_gensym_alist);
1287           if (CONSP (tem))
1288             {
1289               write_char_internal ("#", printcharfun);
1290               print_internal (XCDR (tem), printcharfun, escapeflag);
1291               write_char_internal ("#", printcharfun);
1292               return;
1293             }
1294           else
1295             {
1296               if (CONSP (Vprint_gensym_alist))
1297                 {
1298                   /* Vprint_gensym_alist is exposed to Lisp, so we
1299                      have to be careful.  */
1300                   CHECK_CONS (XCAR (Vprint_gensym_alist));
1301                   CHECK_INT (XCDR (XCAR (Vprint_gensym_alist)));
1302                   XSETINT (tem, XINT (XCDR (XCAR (Vprint_gensym_alist))) + 1);
1303                 }
1304               else
1305                 XSETINT (tem, 1);
1306               Vprint_gensym_alist = Fcons (Fcons (obj, tem), Vprint_gensym_alist);
1307
1308               write_char_internal ("#", printcharfun);
1309               print_internal (tem, printcharfun, escapeflag);
1310               write_char_internal ("=", printcharfun);
1311             }
1312         }
1313       write_c_string ("#:", printcharfun);
1314     }
1315
1316   /* Does it look like an integer or a float? */
1317   {
1318     Bufbyte *data = string_data (name);
1319     Bytecount confusing = 0;
1320
1321     if (size == 0)
1322       goto not_yet_confused;    /* Really confusing */
1323     else if (isdigit (data[0]))
1324       confusing = 0;
1325     else if (size == 1)
1326       goto not_yet_confused;
1327     else if (data[0] == '-' || data[0] == '+')
1328       confusing = 1;
1329     else
1330       goto not_yet_confused;
1331
1332     for (; confusing < size; confusing++)
1333       {
1334         if (!isdigit (data[confusing]))
1335           {
1336             confusing = 0;
1337             break;
1338           }
1339       }
1340   not_yet_confused:
1341
1342 #ifdef LISP_FLOAT_TYPE
1343     if (!confusing)
1344       /* #### Ugh, this is needlessly complex and slow for what we
1345          need here.  It might be a good idea to copy equivalent code
1346          from FSF.  --hniksic */
1347       confusing = isfloat_string ((char *) data);
1348 #endif
1349     if (confusing)
1350       write_char_internal ("\\", printcharfun);
1351   }
1352
1353   {
1354     Lisp_Object nameobj;
1355     Bytecount i;
1356     Bytecount last = 0;
1357
1358     XSETSTRING (nameobj, name);
1359     for (i = 0; i < size; i++)
1360       {
1361         switch (string_byte (name, i))
1362           {
1363           case  0: case  1: case  2: case  3:
1364           case  4: case  5: case  6: case  7:
1365           case  8: case  9: case 10: case 11:
1366           case 12: case 13: case 14: case 15:
1367           case 16: case 17: case 18: case 19:
1368           case 20: case 21: case 22: case 23:
1369           case 24: case 25: case 26: case 27:
1370           case 28: case 29: case 30: case 31:
1371           case ' ': case '\"': case '\\': case '\'':
1372           case ';': case '#' : case '(' : case ')':
1373           case ',': case '.' : case '`' :
1374           case '[': case ']' : case '?' :
1375             if (i > last)
1376               output_string (printcharfun, 0, nameobj, last, i - last);
1377             write_char_internal ("\\", printcharfun);
1378             last = i;
1379           }
1380       }
1381     output_string (printcharfun, 0, nameobj, last, size - last);
1382   }
1383   UNGCPRO;
1384 }
1385 \f
1386 /* #ifdef DEBUG_XEMACS */
1387
1388 /* I don't like seeing `Note: Strange doc (not fboundp) for function
1389    alternate-debugging-output @ 429542' -slb */
1390 /* #### Eek!  Any clue how to get rid of it?  In fact, how about
1391    getting rid of this function altogether?  Does anything actually
1392    *use* it?  --hniksic */
1393
1394 static int alternate_do_pointer;
1395 static char alternate_do_string[5000];
1396
1397 DEFUN ("alternate-debugging-output", Falternate_debugging_output, 1, 1, 0, /*
1398 Append CHARACTER to the array `alternate_do_string'.
1399 This can be used in place of `external-debugging-output' as a function
1400 to be passed to `print'.  Before calling `print', set `alternate_do_pointer'
1401 to 0.
1402 */
1403        (character))
1404 {
1405   Bufbyte str[MAX_EMCHAR_LEN];
1406   Bytecount len;
1407   int extlen;
1408   CONST Extbyte *extptr;
1409
1410   CHECK_CHAR_COERCE_INT (character);
1411   len = set_charptr_emchar (str, XCHAR (character));
1412   GET_CHARPTR_EXT_DATA_ALLOCA (str, len, FORMAT_TERMINAL, extptr, extlen);
1413   memcpy (alternate_do_string + alternate_do_pointer, extptr, extlen);
1414   alternate_do_pointer += extlen;
1415   alternate_do_string[alternate_do_pointer] = 0;
1416   return character;
1417 }
1418 /* #endif / * DEBUG_XEMACS */
1419
1420 DEFUN ("external-debugging-output", Fexternal_debugging_output, 1, 3, 0, /*
1421 Write CHAR-OR-STRING to stderr or stdout.
1422 If optional arg STDOUT-P is non-nil, write to stdout; otherwise, write
1423 to stderr.  You can use this function to write directly to the terminal.
1424 This function can be used as the STREAM argument of Fprint() or the like.
1425
1426 If you have opened a termscript file (using `open-termscript'), then
1427 the output also will be logged to this file.
1428 */
1429        (char_or_string, stdout_p, device))
1430 {
1431   FILE *file = 0;
1432   struct console *con = 0;
1433
1434   if (NILP (device))
1435     {
1436       if (!NILP (stdout_p))
1437         file = stdout;
1438       else
1439         file = stderr;
1440     }
1441   else
1442     {
1443       CHECK_LIVE_DEVICE (device);
1444       if (!DEVICE_TTY_P (XDEVICE (device)) &&
1445           !DEVICE_STREAM_P (XDEVICE (device)))
1446         signal_simple_error ("Must be tty or stream device", device);
1447       con = XCONSOLE (DEVICE_CONSOLE (XDEVICE (device)));
1448       if (DEVICE_TTY_P (XDEVICE (device)))
1449         file = 0;
1450       else if (!NILP (stdout_p))
1451         file = CONSOLE_STREAM_DATA (con)->out;
1452       else
1453         file = CONSOLE_STREAM_DATA (con)->err;
1454     }
1455
1456   if (STRINGP (char_or_string))
1457     write_string_to_stdio_stream (file, con,
1458                                   XSTRING_DATA (char_or_string),
1459                                   0, XSTRING_LENGTH (char_or_string),
1460                                   FORMAT_TERMINAL);
1461   else
1462     {
1463       Bufbyte str[MAX_EMCHAR_LEN];
1464       Bytecount len;
1465
1466       CHECK_CHAR_COERCE_INT (char_or_string);
1467       len = set_charptr_emchar (str, XCHAR (char_or_string));
1468       write_string_to_stdio_stream (file, con, str, 0, len, FORMAT_TERMINAL);
1469     }
1470
1471   return char_or_string;
1472 }
1473
1474 DEFUN ("open-termscript", Fopen_termscript, 1, 1, "FOpen termscript file: ", /*
1475 Start writing all terminal output to FILE as well as the terminal.
1476 FILE = nil means just close any termscript file currently open.
1477 */
1478        (file))
1479 {
1480   /* This function can GC */
1481   if (termscript != 0)
1482     fclose (termscript);
1483   termscript = 0;
1484
1485   if (! NILP (file))
1486     {
1487       file = Fexpand_file_name (file, Qnil);
1488       termscript = fopen ((char *) XSTRING_DATA (file), "w");
1489       if (termscript == NULL)
1490         report_file_error ("Opening termscript", list1 (file));
1491     }
1492   return Qnil;
1493 }
1494
1495 #if 1
1496 /* Debugging kludge -- unbuffered */
1497 static int debug_print_length = 50;
1498 static int debug_print_level = 15;
1499
1500 static void
1501 debug_print_no_newline (Lisp_Object debug_print_obj)
1502 {
1503   /* This function can GC */
1504   int old_print_readably = print_readably;
1505   int old_print_depth = print_depth;
1506   Lisp_Object old_print_length = Vprint_length;
1507   Lisp_Object old_print_level = Vprint_level;
1508   Lisp_Object old_inhibit_quit = Vinhibit_quit;
1509   struct gcpro gcpro1, gcpro2, gcpro3;
1510   GCPRO3 (old_print_level, old_print_length, old_inhibit_quit);
1511
1512   if (gc_in_progress)
1513     stderr_out ("** gc-in-progress!  Bad idea to print anything! **\n");
1514
1515   print_depth = 0;
1516   print_readably = 0;
1517   print_unbuffered++;
1518   /* Could use unwind-protect, but why bother? */
1519   if (debug_print_length > 0)
1520     Vprint_length = make_int (debug_print_length);
1521   if (debug_print_level > 0)
1522     Vprint_level = make_int (debug_print_level);
1523   print_internal (debug_print_obj, Qexternal_debugging_output, 1);
1524   Vinhibit_quit = old_inhibit_quit;
1525   Vprint_level = old_print_level;
1526   Vprint_length = old_print_length;
1527   print_depth = old_print_depth;
1528   print_readably = old_print_readably;
1529   print_unbuffered--;
1530   UNGCPRO;
1531 }
1532
1533 void
1534 debug_print (Lisp_Object debug_print_obj)
1535 {
1536   debug_print_no_newline (debug_print_obj);
1537   stderr_out ("\n");
1538   fflush (stderr);
1539 }
1540
1541 /* Debugging kludge -- unbuffered */
1542 /* This function provided for the benefit of the debugger.  */
1543 void debug_backtrace (void);
1544 void
1545 debug_backtrace (void)
1546 {
1547   /* This function can GC */
1548   int         old_print_readably = print_readably;
1549   int         old_print_depth    = print_depth;
1550   Lisp_Object old_print_length   = Vprint_length;
1551   Lisp_Object old_print_level    = Vprint_level;
1552   Lisp_Object old_inhibit_quit   = Vinhibit_quit;
1553
1554   struct gcpro gcpro1, gcpro2, gcpro3;
1555   GCPRO3 (old_print_level, old_print_length, old_inhibit_quit);
1556
1557   if (gc_in_progress)
1558     stderr_out ("** gc-in-progress!  Bad idea to print anything! **\n");
1559
1560   print_depth = 0;
1561   print_readably = 0;
1562   print_unbuffered++;
1563   /* Could use unwind-protect, but why bother? */
1564   if (debug_print_length > 0)
1565     Vprint_length = make_int (debug_print_length);
1566   if (debug_print_level > 0)
1567     Vprint_level = make_int (debug_print_level);
1568
1569   Fbacktrace (Qexternal_debugging_output, Qt);
1570   stderr_out ("\n");
1571   fflush (stderr);
1572
1573   Vinhibit_quit  = old_inhibit_quit;
1574   Vprint_level   = old_print_level;
1575   Vprint_length  = old_print_length;
1576   print_depth    = old_print_depth;
1577   print_readably = old_print_readably;
1578   print_unbuffered--;
1579
1580   UNGCPRO;
1581 }
1582
1583 void
1584 debug_short_backtrace (int length)
1585 {
1586   int first = 1;
1587   struct backtrace *bt = backtrace_list;
1588   stderr_out ("   [");
1589   fflush (stderr);
1590   while (length > 0 && bt)
1591     {
1592       if (!first)
1593         {
1594           stderr_out (", ");
1595           fflush (stderr);
1596         }
1597       if (COMPILED_FUNCTIONP (*bt->function))
1598         {
1599 #if defined(COMPILED_FUNCTION_ANNOTATION_HACK)
1600           Lisp_Object ann =
1601             compiled_function_annotation (XCOMPILED_FUNCTION (*bt->function));
1602 #else
1603           Lisp_Object ann = Qnil;
1604 #endif
1605           if (!NILP (ann))
1606             {
1607               stderr_out ("<compiled-function from ");
1608               fflush (stderr);
1609               debug_print_no_newline (ann);
1610               stderr_out (">");
1611               fflush (stderr);
1612             }
1613           else
1614             {
1615               stderr_out ("<compiled-function of unknown origin>");
1616               fflush (stderr);
1617             }
1618         }
1619       else
1620         debug_print_no_newline (*bt->function);
1621       first = 0;
1622       length--;
1623       bt = bt->next;
1624     }
1625   stderr_out ("]\n");
1626   fflush (stderr);
1627 }
1628
1629 #endif /* debugging kludge */
1630
1631 \f
1632 void
1633 syms_of_print (void)
1634 {
1635   defsymbol (&Qstandard_output, "standard-output");
1636
1637   defsymbol (&Qprint_length, "print-length");
1638
1639   defsymbol (&Qprint_string_length, "print-string-length");
1640
1641   defsymbol (&Qdisplay_error, "display-error");
1642   defsymbol (&Qprint_message_label, "print-message-label");
1643
1644   DEFSUBR (Fprin1);
1645   DEFSUBR (Fprin1_to_string);
1646   DEFSUBR (Fprinc);
1647   DEFSUBR (Fprint);
1648   DEFSUBR (Ferror_message_string);
1649   DEFSUBR (Fdisplay_error);
1650   DEFSUBR (Fterpri);
1651   DEFSUBR (Fwrite_char);
1652   DEFSUBR (Falternate_debugging_output);
1653   DEFSUBR (Fexternal_debugging_output);
1654   DEFSUBR (Fopen_termscript);
1655   defsymbol (&Qexternal_debugging_output, "external-debugging-output");
1656   DEFSUBR (Fwith_output_to_temp_buffer);
1657 }
1658
1659 void
1660 reinit_vars_of_print (void)
1661 {
1662   alternate_do_pointer = 0;
1663 }
1664
1665 void
1666 vars_of_print (void)
1667 {
1668   reinit_vars_of_print ();
1669
1670   DEFVAR_LISP ("standard-output", &Vstandard_output /*
1671 Output stream `print' uses by default for outputting a character.
1672 This may be any function of one argument.
1673 It may also be a buffer (output is inserted before point)
1674 or a marker (output is inserted and the marker is advanced)
1675 or the symbol t (output appears in the minibuffer line).
1676 */ );
1677   Vstandard_output = Qt;
1678
1679 #ifdef LISP_FLOAT_TYPE
1680   DEFVAR_LISP ("float-output-format", &Vfloat_output_format /*
1681 The format descriptor string that lisp uses to print floats.
1682 This is a %-spec like those accepted by `printf' in C,
1683 but with some restrictions.  It must start with the two characters `%.'.
1684 After that comes an integer precision specification,
1685 and then a letter which controls the format.
1686 The letters allowed are `e', `f' and `g'.
1687 Use `e' for exponential notation "DIG.DIGITSeEXPT"
1688 Use `f' for decimal point notation "DIGITS.DIGITS".
1689 Use `g' to choose the shorter of those two formats for the number at hand.
1690 The precision in any of these cases is the number of digits following
1691 the decimal point.  With `f', a precision of 0 means to omit the
1692 decimal point.  0 is not allowed with `f' or `g'.
1693
1694 A value of nil means to use `%.16g'.
1695
1696 Regardless of the value of `float-output-format', a floating point number
1697 will never be printed in such a way that it is ambiguous with an integer;
1698 that is, a floating-point number will always be printed with a decimal
1699 point and/or an exponent, even if the digits following the decimal point
1700 are all zero.  This is to preserve read-equivalence.
1701 */ );
1702   Vfloat_output_format = Qnil;
1703 #endif /* LISP_FLOAT_TYPE */
1704
1705   DEFVAR_LISP ("print-length", &Vprint_length /*
1706 Maximum length of list or vector to print before abbreviating.
1707 A value of nil means no limit.
1708 */ );
1709   Vprint_length = Qnil;
1710
1711   DEFVAR_LISP ("print-string-length", &Vprint_string_length /*
1712 Maximum length of string to print before abbreviating.
1713 A value of nil means no limit.
1714 */ );
1715   Vprint_string_length = Qnil;
1716
1717   DEFVAR_LISP ("print-level", &Vprint_level /*
1718 Maximum depth of list nesting to print before abbreviating.
1719 A value of nil means no limit.
1720 */ );
1721   Vprint_level = Qnil;
1722
1723   DEFVAR_BOOL ("print-escape-newlines", &print_escape_newlines /*
1724 Non-nil means print newlines in strings as backslash-n.
1725 */ );
1726   print_escape_newlines = 0;
1727
1728   DEFVAR_BOOL ("print-readably", &print_readably /*
1729 If non-nil, then all objects will be printed in a readable form.
1730 If an object has no readable representation, then an error is signalled.
1731 When print-readably is true, compiled-function objects will be written in
1732  #[...] form instead of in #<compiled-function [...]> form, and two-element
1733  lists of the form (quote object) will be written as the equivalent 'object.
1734 Do not SET this variable; bind it instead.
1735 */ );
1736   print_readably = 0;
1737
1738   /* #### I think this should default to t.  But we'd better wait
1739      until we see that it works out.  */
1740   DEFVAR_LISP ("print-gensym", &Vprint_gensym /*
1741 If non-nil, then uninterned symbols will be printed specially.
1742 Uninterned symbols are those which are not present in `obarray', that is,
1743 those which were made with `make-symbol' or by calling `intern' with a
1744 second argument.
1745
1746 When print-gensym is true, such symbols will be preceded by "#:",
1747 which causes the reader to create a new symbol instead of interning
1748 and returning an existing one.  Beware: the #: syntax creates a new
1749 symbol each time it is seen, so if you print an object which contains
1750 two pointers to the same uninterned symbol, `read' will not duplicate
1751 that structure.
1752
1753 If the value of `print-gensym' is a cons cell, then in addition
1754 refrain from clearing `print-gensym-alist' on entry to and exit from
1755 printing functions, so that the use of #...# and #...= can carry over
1756 for several separately printed objects.
1757 */ );
1758   Vprint_gensym = Qnil;
1759
1760   DEFVAR_LISP ("print-gensym-alist", &Vprint_gensym_alist /*
1761 Association list of elements (GENSYM . N) to guide use of #N# and #N=.
1762 In each element, GENSYM is an uninterned symbol that has been associated
1763 with #N= for the specified value of N.
1764 */ );
1765   Vprint_gensym_alist = Qnil;
1766
1767   DEFVAR_LISP ("print-message-label", &Vprint_message_label /*
1768 Label for minibuffer messages created with `print'.  This should
1769 generally be bound with `let' rather than set.  (See `display-message'.)
1770 */ );
1771   Vprint_message_label = Qprint;
1772 }