Subject: Re: bug#18652: 25.0.50; [PATCH] Add fresh-line

From: Leo Liu <[email-masked]>
Date: Wed, 08 Oct 2014 13:08:57 +0800

On 2014-10-08 09:54 +0800, Leo Liu wrote:
> How about something like this? Thanks, Leo.

This is the full patch (documentation, tests etc.) without the changelog
entries. Also improved to support print to stdout in noninteractive
mode. Comments?

Thanks, Leo

=== modified file 'doc/lispref/streams.texi'
--- doc/lispref/streams.texi	2014-03-18 01:19:03 +0000
+++ doc/lispref/streams.texi	2014-10-08 02:36:52 +0000
@@ -621,6 +621,13 @@
 for ``terminate print''.
 @end defun
 
+@defun fresh-line &optional stream
+@cindex fresh line in print
+This function outputs a newline to @var{stream} unless already at the
+beginning of a line. Return @code{t} if a newline is printed. Signal
+an error if @var{stream} is a function.
+@end defun
+
 @defun write-char character &optional stream
 This function outputs @var{character} to @var{stream}.  It returns
 @var{character}.

=== modified file 'src/print.c'
--- src/print.c	2014-09-11 06:21:55 +0000
+++ src/print.c	2014-10-08 04:58:12 +0000
@@ -58,6 +58,9 @@
 #define PRINT_CIRCLE 200
 static Lisp_Object being_printed[PRINT_CIRCLE];
 
+/* Last char printed to stdout by printchar.  */
+static unsigned int printchar_stdout_last;
+
 /* When printing into a buffer, first we put the text in this
    block, then insert it all at once.  */
 static char *print_buffer;
@@ -238,6 +241,7 @@
 	}
       else if (noninteractive)
 	{
+	  printchar_stdout_last = ch;
 	  fwrite (str, 1, len, stdout);
 	  noninteractive_need_newline = 1;
 	}
@@ -530,6 +534,32 @@
   return Qt;
 }
 
+DEFUN ("fresh-line", Ffresh_line, Sfresh_line, 0, 1, 0,
+       doc: /* Output a newline unless already at the beginning of a line.
+Value is non-nil if a newline is printed.
+Signal an error if PRINTCHARFUN is a function.  */)
+  (Lisp_Object printcharfun)
+{
+  Lisp_Object val = Qnil;
+
+  PRINTDECLARE;
+  if (NILP (printcharfun))
+    printcharfun = Vstandard_output;
+  PRINTPREPARE;
+
+  if (FUNCTIONP (printcharfun))
+    signal_error ("Unsupported function argument", printcharfun);
+
+  if (noninteractive && !NILP (printcharfun))
+    val = printchar_stdout_last == 10 ? Qnil : Qt;
+  else if (NILP (Fbolp ()))
+    val = Qt;
+
+  if (!NILP (val)) PRINTCHAR ('\n');
+  PRINTFINISH;
+  return val;
+}
+
 DEFUN ("prin1", Fprin1, Sprin1, 1, 2, 0,
        doc: /* Output the printed representation of OBJECT, any Lisp object.
 Quoting characters are printed when needed to make output that `read'
@@ -2334,6 +2364,7 @@
   defsubr (&Sprinc);
   defsubr (&Sprint);
   defsubr (&Sterpri);
+  defsubr (&Sfresh_line);
   defsubr (&Swrite_char);
 #ifdef WITH_REDIRECT_DEBUGGING_OUTPUT
   defsubr (&Sredirect_debugging_output);