View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2022, SWI-Prolog Solutions b.v.
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(streams,
   36	  [ with_output_to/3		% ?Output, :Goal, +Options
   37	  ]).   38:- autoload(library(error), [must_be/2]).   39:- autoload(library(option), [option/2, option/3]).   40:- autoload(library(apply), [maplist/2, maplist/3]).   41
   42:- meta_predicate with_output_to(?, 0, +).   43
   44/** <module> Manage Prolog streams
   45
   46This library provides high level primitives for stream operations.  It
   47is related  to the  charsio.pl and codesio.pl  libraries.  Considering
   48these are de-facto standard Prolog  libraries we prefer to leave these
   49untouched.
   50
   51*/
   52
   53%!  with_output_to(?Output, :Goal, +Options) is det.
   54%
   55%   Run  Goal and  once/1 while  capturing all  output to  all streams
   56%   (`current_output`, `user_output`  and `user_error`) in  the string
   57%   Output.  Options processed:
   58%
   59%     - capture(ListOfStreams)
   60%       List of streams to capture.  Default is `[]`, causing the
   61%       predicate to call with_output_to/2.  The only admissible
   62%       list elements are the alias names for the Prolog standard
   63%       streams.  As `current_output` is always captured, the only
   64%       two values are `user_output` and `user_error`
   65%     - color(Boolean)
   66%       When `true`, pretend the output is a terminal, causing messages
   67%       to use ANSI term escape sequences for color.
   68%
   69%   For example, the  following captures an error  message.  Note that
   70%   we must catch and print the message  inside Goal.  If we do not do
   71%   so the exception of Goal is simply propagated into the environment
   72%   without binding Output.
   73%
   74%   ```
   75%   ?- with_output_to(string(Out),
   76%                     catch(A is log(-1), E, print_message(error, E)),
   77%                     [capture([user_error]), color(true)]).
   78%   Out = "\u001B[1;31mERROR: is/2: Arithmetic: \c
   79%          evaluation error: `undefined'\n\u001B[0m",
   80%   E = error(evaluation_error(undefined), context(system:(is)/2, _)).
   81%   ```
   82
   83with_output_to(Output, Goal, []) =>
   84    with_output_to(Output, Goal).
   85with_output_to(Output, Goal, Options) =>
   86    option(capture(Streams), Options, []),
   87    must_be(list(oneof([user_output,user_error])), Streams),
   88    with_output_to(
   89	Output,
   90	setup_call_cleanup(
   91	    output_state(State, Streams),
   92	    capture(Goal, Streams, Options),
   93	    restore_output(State, Streams))).
   94
   95capture(Goal, Streams, Options) :-
   96    current_output(S),
   97    (   option(color(true), Options)
   98    ->  set_stream(S, tty(true))
   99    ;   true
  100    ),
  101    maplist(capture_output(S), Streams),
  102    once(Goal),
  103    maplist(flush_output, [current_output|Streams]).
  104
  105output_state(State, Streams) :-
  106    maplist(stream_id, Streams, State).
  107
  108stream_id(Alias, Stream) :-
  109    stream_property(Stream, alias(Alias)).
  110
  111restore_output(State, Streams) :-
  112    maplist(restore_stream, Streams, State).
  113
  114restore_stream(Alias, Stream) :-
  115    set_stream(Stream, alias(Alias)).
  116
  117capture_output(S, Alias) :-
  118    set_stream(S, alias(Alias))