View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  1985-2017, University of Amsterdam
    7                              VU University Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module('$toplevel',
   37          [ '$initialise'/0,            % start Prolog
   38            '$toplevel'/0,              % Prolog top-level (re-entrant)
   39            '$compile'/0,               % `-c' toplevel
   40            '$config'/0,                % --dump-runtime-variables toplevel
   41            initialize/0,               % Run program initialization
   42            version/0,                  % Write initial banner
   43            version/1,                  % Add message to the banner
   44            prolog/0,                   % user toplevel predicate
   45            '$query_loop'/0,            % toplevel predicate
   46            residual_goals/1,           % +Callable
   47            (initialization)/1,         % initialization goal (directive)
   48            '$thread_init'/0,           % initialise thread
   49            (thread_initialization)/1   % thread initialization goal
   50            ]).   51
   52
   53                 /*******************************
   54                 *       FILE_SEARCH_PATH       *
   55                 *******************************/
   56
   57:- multifile user:file_search_path/2.   58
   59user:file_search_path(app_data, PrologAppData) :-
   60    (   current_prolog_flag(windows, true)
   61    ->  catch(win_folder(appdata, AppData), _, fail),
   62        atom_concat(AppData, '/SWI-Prolog', PrologAppData),
   63        (   exists_directory(PrologAppData)
   64        ->  true
   65        ;   catch(make_directory(PrologAppData), _, fail)
   66        )
   67    ;   catch(expand_file_name('~/lib/swipl', [PrologAppData]), _, fail)
   68    ).
   69user:file_search_path(app_preferences, Preferences) :-
   70    (   current_prolog_flag(windows, true)
   71    ->  Preferences = app_data('.')
   72    ;   catch(expand_file_name(~, [UserHome]), _, fail)
   73    ->  Preferences = UserHome
   74    ).
   75user:file_search_path(user_profile, app_preferences('.')).
   76
   77
   78                 /*******************************
   79                 *         VERSION BANNER       *
   80                 *******************************/
   81
   82:- dynamic
   83    prolog:version_msg/1.
 version is det
Print the Prolog banner message and messages registered using version/1.
   90version :-
   91    print_message(banner, welcome).
 version(+Message) is det
Add message to version/0
   97:- multifile
   98    system:term_expansion/2.   99
  100system:term_expansion((:- version(Message)),
  101                      prolog:version_msg(Message)).
  102
  103version(Message) :-
  104    (   prolog:version_msg(Message)
  105    ->  true
  106    ;   assertz(prolog:version_msg(Message))
  107    ).
  108
  109
  110                /********************************
  111                *         INITIALISATION        *
  112                *********************************/
  113
  114%       note: loaded_init_file/2 is used by prolog_load_context/2 to
  115%       confirm we are loading a script.
  116
  117:- dynamic
  118    loaded_init_file/2.             % already loaded init files
  119
  120'$load_init_file'(none) :- !.
  121'$load_init_file'(Base) :-
  122    loaded_init_file(Base, _),
  123    !.
  124'$load_init_file'(InitFile) :-
  125    exists_file(InitFile),
  126    !,
  127    ensure_loaded(user:InitFile).
  128'$load_init_file'(Base) :-
  129    absolute_file_name(user_profile(Base), InitFile,
  130                       [ access(read),
  131                         file_errors(fail)
  132                       ]),
  133    asserta(loaded_init_file(Base, InitFile)),
  134    load_files(user:InitFile,
  135               [ scope_settings(false)
  136               ]).
  137'$load_init_file'(_).
  138
  139'$load_system_init_file' :-
  140    loaded_init_file(system, _),
  141    !.
  142'$load_system_init_file' :-
  143    '$cmd_option_val'(system_init_file, Base),
  144    Base \== none,
  145    current_prolog_flag(home, Home),
  146    file_name_extension(Base, rc, Name),
  147    atomic_list_concat([Home, '/', Name], File),
  148    absolute_file_name(File, Path,
  149                       [ file_type(prolog),
  150                         access(read),
  151                         file_errors(fail)
  152                       ]),
  153    asserta(loaded_init_file(system, Path)),
  154    load_files(user:Path,
  155               [ silent(true),
  156                 scope_settings(false)
  157               ]),
  158    !.
  159'$load_system_init_file'.
  160
  161'$load_script_file' :-
  162    loaded_init_file(script, _),
  163    !.
  164'$load_script_file' :-
  165    '$cmd_option_val'(script_file, OsFiles),
  166    load_script_files(OsFiles).
  167
  168load_script_files([]).
  169load_script_files([OsFile|More]) :-
  170    prolog_to_os_filename(File, OsFile),
  171    (   absolute_file_name(File, Path,
  172                           [ file_type(prolog),
  173                             access(read),
  174                             file_errors(fail)
  175                           ])
  176    ->  asserta(loaded_init_file(script, Path)),
  177        load_files(user:Path, []),
  178        load_files(More)
  179    ;   throw(error(existence_error(script_file, File), _))
  180    ).
  181
  182
  183                 /*******************************
  184                 *       AT_INITIALISATION      *
  185                 *******************************/
  186
  187:- meta_predicate
  188    initialization(0).  189
  190:- '$iso'((initialization)/1).
 initialization :Goal
Runs Goal after loading the file in which this directive appears as well as after restoring a saved state.
See also
- initialization/2
  199initialization(Goal) :-
  200    Goal = _:G,
  201    prolog:initialize_now(G, Use),
  202    !,
  203    print_message(warning, initialize_now(G, Use)),
  204    initialization(Goal, now).
  205initialization(Goal) :-
  206    initialization(Goal, after_load).
  207
  208:- multifile
  209    prolog:initialize_now/2,
  210    prolog:message//1.  211
  212prolog:initialize_now(load_foreign_library(_),
  213                      'use :- use_foreign_library/1 instead').
  214prolog:initialize_now(load_foreign_library(_,_),
  215                      'use :- use_foreign_library/2 instead').
  216
  217prolog:message(initialize_now(Goal, Use)) -->
  218    [ 'Initialization goal ~p will be executed'-[Goal],nl,
  219      'immediately for backward compatibility reasons', nl,
  220      '~w'-[Use]
  221    ].
  222
  223'$run_initialization' :-
  224    '$run_initialization'(_, []),
  225    '$thread_init'.
 initialize
Run goals registered with :- initialization(Goal, program).. Stop with an exception if a goal fails or raises an exception.
  232initialize :-
  233    forall('$init_goal'(when(program), Goal, Ctx),
  234           run_initialize(Goal, Ctx)).
  235
  236run_initialize(Goal, Ctx) :-
  237    (   catch(Goal, E, true),
  238        (   var(E)
  239        ->  true
  240        ;   throw(error(initialization_error(E, Goal, Ctx), _))
  241        )
  242    ;   throw(error(initialization_error(failed, Goal, Ctx), _))
  243    ).
  244
  245
  246                 /*******************************
  247                 *     THREAD INITIALIZATION    *
  248                 *******************************/
  249
  250:- meta_predicate
  251    thread_initialization(0).  252:- dynamic
  253    '$at_thread_initialization'/1.
 thread_initialization :Goal
Run Goal now and everytime a new thread is created.
  259thread_initialization(Goal) :-
  260    assert('$at_thread_initialization'(Goal)),
  261    call(Goal),
  262    !.
  263
  264'$thread_init' :-
  265    (   '$at_thread_initialization'(Goal),
  266        (   call(Goal)
  267        ->  fail
  268        ;   fail
  269        )
  270    ;   true
  271    ).
  272
  273
  274                 /*******************************
  275                 *     FILE SEARCH PATH (-p)    *
  276                 *******************************/
 $set_file_search_paths is det
Process -p PathSpec options.
  282'$set_file_search_paths' :-
  283    '$cmd_option_val'(search_paths, Paths),
  284    (   '$member'(Path, Paths),
  285        atom_chars(Path, Chars),
  286        (   phrase('$search_path'(Name, Aliases), Chars)
  287        ->  '$reverse'(Aliases, Aliases1),
  288            forall('$member'(Alias, Aliases1),
  289                   asserta(user:file_search_path(Name, Alias)))
  290        ;   print_message(error, commandline_arg_type(p, Path))
  291        ),
  292        fail ; true
  293    ).
  294
  295'$search_path'(Name, Aliases) -->
  296    '$string'(NameChars),
  297    [=],
  298    !,
  299    {atom_chars(Name, NameChars)},
  300    '$search_aliases'(Aliases).
  301
  302'$search_aliases'([Alias|More]) -->
  303    '$string'(AliasChars),
  304    path_sep,
  305    !,
  306    { '$make_alias'(AliasChars, Alias) },
  307    '$search_aliases'(More).
  308'$search_aliases'([Alias]) -->
  309    '$string'(AliasChars),
  310    '$eos',
  311    !,
  312    { '$make_alias'(AliasChars, Alias) }.
  313
  314path_sep -->
  315    { current_prolog_flag(windows, true)
  316    },
  317    !,
  318    [;].
  319path_sep -->
  320    [:].
  321
  322'$string'([]) --> [].
  323'$string'([H|T]) --> [H], '$string'(T).
  324
  325'$eos'([], []).
  326
  327'$make_alias'(Chars, Alias) :-
  328    catch(term_to_atom(Alias, Chars), _, fail),
  329    (   atom(Alias)
  330    ;   functor(Alias, F, 1),
  331        F \== /
  332    ),
  333    !.
  334'$make_alias'(Chars, Alias) :-
  335    atom_chars(Alias, Chars).
  336
  337
  338                 /*******************************
  339                 *   LOADING ASSIOCIATED FILES  *
  340                 *******************************/
 argv_files(-Files) is det
Update the Prolog flag argv, extracting the leading directory and files.
  347argv_files(Files) :-
  348    current_prolog_flag(argv, Argv),
  349    no_option_files(Argv, Argv1, Files),
  350    (   Argv1 \== Argv
  351    ->  set_prolog_flag(argv, Argv1)
  352    ;   true
  353    ).
  354
  355no_option_files([--|Argv], Argv, []) :- !.
  356no_option_files([OsScript|Argv], Argv, [Script]) :-
  357    prolog_to_os_filename(Script, OsScript),
  358    access_file(Script, read),
  359    catch(setup_call_cleanup(
  360              open(Script, read, In),
  361              ( get_char(In, '#'),
  362                get_char(In, '!')
  363              ),
  364              close(In)),
  365          _, fail),
  366    !.
  367no_option_files([OsFile|Argv0], Argv, [File|T]) :-
  368    file_name_extension(_, Ext, OsFile),
  369    user:prolog_file_type(Ext, prolog),
  370    !,
  371    prolog_to_os_filename(File, OsFile),
  372    no_option_files(Argv0, Argv, T).
  373no_option_files(Argv, Argv, []).
  374
  375clean_argv :-
  376    (   current_prolog_flag(argv, [--|Argv])
  377    ->  set_prolog_flag(argv, Argv)
  378    ;   true
  379    ).
 associated_files(-Files)
If SWI-Prolog is started as <exe> <file>.<ext>, where <ext> is the extension registered for associated files, set the Prolog flag associated_file, switch to the directory holding the file and -if possible- adjust the window title.
  388associated_files([]) :-
  389    current_prolog_flag(saved_program_class, runtime),
  390    !,
  391    clean_argv.
  392associated_files(Files) :-
  393    '$set_prolog_file_extension',
  394    argv_files(Files),
  395    (   Files = [File|_]
  396    ->  absolute_file_name(File, AbsFile),
  397        set_prolog_flag(associated_file, AbsFile),
  398        set_working_directory(File),
  399        set_window_title(Files)
  400    ;   true
  401    ).
 set_working_directory(+File)
When opening as a GUI application, e.g., by opening a file from the Finder/Explorer/..., we typically want to change working directory to the location of the primary file. We currently detect that we are a GUI app by the Prolog flag console_menu, which is set by swipl-win[.exe].
  411set_working_directory(File) :-
  412    current_prolog_flag(console_menu, true),
  413    access_file(File, read),
  414    !,
  415    file_directory_name(File, Dir),
  416    working_directory(_, Dir).
  417set_working_directory(_).
  418
  419set_window_title([File|More]) :-
  420    current_predicate(system:window_title/2),
  421    !,
  422    (   More == []
  423    ->  Extra = []
  424    ;   Extra = ['...']
  425    ),
  426    atomic_list_concat(['SWI-Prolog --', File | Extra], ' ', Title),
  427    system:window_title(_, Title).
  428set_window_title(_).
 start_pldoc
If the option --pldoc[=port] is given, load the PlDoc system.
  436start_pldoc :-
  437    '$cmd_option_val'(pldoc_server, Server),
  438    (   Server == ''
  439    ->  call((doc_server(_), doc_browser))
  440    ;   catch(atom_number(Server, Port), _, fail)
  441    ->  call(doc_server(Port))
  442    ;   print_message(error, option_usage(pldoc)),
  443        halt(1)
  444    ).
  445start_pldoc.
 load_associated_files(+Files)
Load Prolog files specified from the commandline.
  452load_associated_files(Files) :-
  453    (   '$member'(File, Files),
  454        load_files(user:File, [expand(false)]),
  455        fail
  456    ;   true
  457    ).
  458
  459hkey('HKEY_CURRENT_USER/Software/SWI/Prolog').
  460hkey('HKEY_LOCAL_MACHINE/Software/SWI/Prolog').
  461
  462'$set_prolog_file_extension' :-
  463    current_prolog_flag(windows, true),
  464    hkey(Key),
  465    catch(win_registry_get_value(Key, fileExtension, Ext0),
  466          _, fail),
  467    !,
  468    (   atom_concat('.', Ext, Ext0)
  469    ->  true
  470    ;   Ext = Ext0
  471    ),
  472    (   user:prolog_file_type(Ext, prolog)
  473    ->  true
  474    ;   asserta(user:prolog_file_type(Ext, prolog))
  475    ).
  476'$set_prolog_file_extension'.
  477
  478
  479                /********************************
  480                *        TOPLEVEL GOALS         *
  481                *********************************/
 $initialise is semidet
Called from PL_initialise() to do the Prolog part of the initialization. If an exception occurs, this is printed and '$initialise' fails.
  489'$initialise' :-
  490    catch(initialise_prolog, E, initialise_error(E)).
  491
  492initialise_error('$aborted') :- !.
  493initialise_error(E) :-
  494    print_message(error, initialization_exception(E)),
  495    fail.
  496
  497initialise_prolog :-
  498    '$clean_history',
  499    '$run_initialization',
  500    '$load_system_init_file',
  501    set_toplevel,
  502    associated_files(Files),
  503    '$set_file_search_paths',
  504    init_debug_flags,
  505    start_pldoc,
  506    attach_packs,
  507    '$cmd_option_val'(init_file, OsFile),
  508    prolog_to_os_filename(File, OsFile),
  509    '$load_init_file'(File),
  510    catch(setup_colors, E, print_message(warning, E)),
  511    '$load_script_file',
  512    load_associated_files(Files),
  513    '$cmd_option_val'(goals, Goals),
  514    (   Goals == [],
  515        \+ '$init_goal'(when(_), _, _)
  516    ->  version                                 % default interactive run
  517    ;   run_init_goals(Goals),
  518        (   load_only
  519        ->  version
  520        ;   run_program_init,
  521            run_main_init
  522        )
  523    ).
  524
  525set_toplevel :-
  526    '$cmd_option_val'(toplevel, TopLevelAtom),
  527    catch(term_to_atom(TopLevel, TopLevelAtom), E,
  528          (print_message(error, E),
  529           halt(1))),
  530    create_prolog_flag(toplevel_goal, TopLevel, [type(term)]).
  531
  532load_only :-
  533    current_prolog_flag(os_argv, OSArgv),
  534    memberchk('-l', OSArgv),
  535    current_prolog_flag(argv, Argv),
  536    \+ memberchk('-l', Argv).
 run_init_goals(+Goals) is det
Run registered initialization goals on order. If a goal fails, execution is halted.
  543run_init_goals([]).
  544run_init_goals([H|T]) :-
  545    run_init_goal(H),
  546    run_init_goals(T).
  547
  548run_init_goal(Text) :-
  549    catch(term_to_atom(Goal, Text), E,
  550          (   print_message(error, init_goal_syntax(E, Text)),
  551              halt(2)
  552          )),
  553    run_init_goal(Goal, Text).
 run_program_init is det
Run goals registered using
  559run_program_init :-
  560    forall('$init_goal'(when(program), Goal, Ctx),
  561           run_init_goal(Goal, @(Goal,Ctx))).
  562
  563run_main_init :-
  564    findall(Goal-Ctx, '$init_goal'(when(main), Goal, Ctx), Pairs),
  565    '$last'(Pairs, Goal-Ctx),
  566    !,
  567    (   current_prolog_flag(toplevel_goal, default)
  568    ->  set_prolog_flag(toplevel_goal, halt)
  569    ;   true
  570    ),
  571    run_init_goal(Goal, @(Goal,Ctx)).
  572run_main_init.
  573
  574run_init_goal(Goal, Ctx) :-
  575    (   catch_with_backtrace(user:Goal, E, true)
  576    ->  (   var(E)
  577        ->  true
  578        ;   print_message(error, init_goal_failed(E, Ctx)),
  579            halt(2)
  580        )
  581    ;   (   current_prolog_flag(verbose, silent)
  582        ->  Level = silent
  583        ;   Level = error
  584        ),
  585        print_message(Level, init_goal_failed(failed, Ctx)),
  586        halt(1)
  587    ).
 init_debug_flags is det
Initialize the various Prolog flags that control the debugger and toplevel.
  594init_debug_flags :-
  595    once(print_predicate(_, [print], PrintOptions)),
  596    create_prolog_flag(answer_write_options, PrintOptions, []),
  597    create_prolog_flag(prompt_alternatives_on, determinism, []),
  598    create_prolog_flag(toplevel_extra_white_line, true, []),
  599    create_prolog_flag(toplevel_print_factorized, false, []),
  600    create_prolog_flag(print_write_options,
  601                       [ portray(true), quoted(true), numbervars(true) ],
  602                       []),
  603    create_prolog_flag(toplevel_residue_vars, false, []),
  604    '$set_debugger_write_options'(print).
 setup_backtrace
Initialise printing a backtrace.
  610setup_backtrace :-
  611    (   \+ current_prolog_flag(backtrace, false),
  612        load_setup_file(library(prolog_stack))
  613    ->  true
  614    ;   true
  615    ).
 setup_colors is det
Setup interactive usage by enabling colored output.
  621setup_colors :-
  622    (   \+ current_prolog_flag(color_term, false),
  623        stream_property(user_input, tty(true)),
  624        stream_property(user_error, tty(true)),
  625        stream_property(user_output, tty(true)),
  626        load_setup_file(user:library(ansi_term))
  627    ->  true
  628    ;   true
  629    ).
 setup_history
Enable per-directory persistent history.
  635setup_history :-
  636    (   \+ current_prolog_flag(save_history, false),
  637        stream_property(user_input, tty(true)),
  638        \+ current_prolog_flag(readline, false),
  639        load_setup_file(library(prolog_history))
  640    ->  prolog_history(enable)
  641    ;   true
  642    ),
  643    set_default_history,
  644    '$load_history'.
 setup_readline
Setup line editing.
  650setup_readline :-
  651    (   current_prolog_flag(readline, swipl_win)
  652    ->  true
  653    ;   stream_property(user_input, tty(true)),
  654        current_prolog_flag(tty_control, true),
  655        \+ getenv('TERM', dumb),
  656        (   current_prolog_flag(readline, ReadLine)
  657        ->  true
  658        ;   ReadLine = true
  659        ),
  660        readline_library(ReadLine, Library),
  661        load_setup_file(library(Library))
  662    ->  set_prolog_flag(readline, Library)
  663    ;   set_prolog_flag(readline, false)
  664    ).
  665
  666readline_library(true, Library) :-
  667    !,
  668    preferred_readline(Library).
  669readline_library(false, _) :-
  670    !,
  671    fail.
  672readline_library(Library, Library).
  673
  674preferred_readline(editline).
  675preferred_readline(readline).
 load_setup_file(+File) is semidet
Load a file and fail silently if the file does not exist.
  681load_setup_file(File) :-
  682    catch(load_files(File,
  683                     [ silent(true),
  684                       if(not_loaded)
  685                     ]), _, fail).
  686
  687
  688:- '$hide'('$toplevel'/0).              % avoid in the GUI stacktrace
 $toplevel
Called from PL_toplevel()
  694'$toplevel' :-
  695    '$runtoplevel',
  696    print_message(informational, halt).
 $runtoplevel
Actually run the toplevel. The values default and prolog both start the interactive toplevel, where prolog implies the user gave -t prolog.
See also
- prolog/0 is the default interactive toplevel
  706'$runtoplevel' :-
  707    current_prolog_flag(toplevel_goal, TopLevel0),
  708    toplevel_goal(TopLevel0, TopLevel),
  709    user:TopLevel.
  710
  711:- dynamic  setup_done/0.  712:- volatile setup_done/0.  713
  714toplevel_goal(default, '$query_loop') :-
  715    !,
  716    setup_interactive.
  717toplevel_goal(prolog, '$query_loop') :-
  718    !,
  719    setup_interactive.
  720toplevel_goal(Goal, Goal).
  721
  722setup_interactive :-
  723    setup_done,
  724    !.
  725setup_interactive :-
  726    asserta(setup_done),
  727    catch(setup_backtrace, E, print_message(warning, E)),
  728    catch(setup_readline,  E, print_message(warning, E)),
  729    catch(setup_history,   E, print_message(warning, E)).
 $compile
Toplevel called when invoked with -c option.
  735'$compile' :-
  736    (   catch('$compile_', E, (print_message(error, E), halt(1)))
  737    ->  true
  738    ;   print_message(error, error(goal_failed('$compile'), _)),
  739        halt(1)
  740    ).
  741
  742'$compile_' :-
  743    '$load_system_init_file',
  744    '$set_file_search_paths',
  745    init_debug_flags,
  746    '$run_initialization',
  747    attach_packs,
  748    use_module(library(qsave)),
  749    qsave:qsave_toplevel.
 $config
Toplevel when invoked with --dump-runtime-variables
  755'$config' :-
  756    '$load_system_init_file',
  757    '$set_file_search_paths',
  758    init_debug_flags,
  759    '$run_initialization',
  760    load_files(library(prolog_config)),
  761    (   catch(prolog_dump_runtime_variables, E,
  762              (print_message(error, E), halt(1)))
  763    ->  true
  764    ;   print_message(error, error(goal_failed(prolog_dump_runtime_variables),_))
  765    ).
  766
  767
  768                /********************************
  769                *    USER INTERACTIVE LOOP      *
  770                *********************************/
 prolog
Run the Prolog toplevel. This is now the same as break/0, which pretends to be in a break-level if there is a parent environment.
  778prolog :-
  779    break.
  780
  781:- create_prolog_flag(toplevel_mode, backtracking, []).
 $query_loop
Run the normal Prolog query loop. Note that the query is not protected by catch/3. Dealing with unhandled exceptions is done by the C-function query_loop(). This ensures that unhandled exceptions are really unhandled (in Prolog).
  790'$query_loop' :-
  791    current_prolog_flag(toplevel_mode, recursive),
  792    !,
  793    break_level(Level),
  794    read_expanded_query(Level, Query, Bindings),
  795    (   Query == end_of_file
  796    ->  print_message(query, query(eof))
  797    ;   '$call_no_catch'('$execute'(Query, Bindings)),
  798        (   current_prolog_flag(toplevel_mode, recursive)
  799        ->  '$query_loop'
  800        ;   '$switch_toplevel_mode'(backtracking),
  801            '$query_loop'           % Maybe throw('$switch_toplevel_mode')?
  802        )
  803    ).
  804'$query_loop' :-
  805    break_level(BreakLev),
  806    repeat,
  807        read_expanded_query(BreakLev, Query, Bindings),
  808        (   Query == end_of_file
  809        ->  !, print_message(query, query(eof))
  810        ;   '$execute'(Query, Bindings),
  811            (   current_prolog_flag(toplevel_mode, recursive)
  812            ->  !,
  813                '$switch_toplevel_mode'(recursive),
  814                '$query_loop'
  815            ;   fail
  816            )
  817        ).
  818
  819break_level(BreakLev) :-
  820    (   current_prolog_flag(break_level, BreakLev)
  821    ->  true
  822    ;   BreakLev = -1
  823    ).
  824
  825read_expanded_query(BreakLev, ExpandedQuery, ExpandedBindings) :-
  826    '$current_typein_module'(TypeIn),
  827    (   stream_property(user_input, tty(true))
  828    ->  '$system_prompt'(TypeIn, BreakLev, Prompt),
  829        prompt(Old, '|    ')
  830    ;   Prompt = '',
  831        prompt(Old, '')
  832    ),
  833    trim_stacks,
  834    repeat,
  835      read_query(Prompt, Query, Bindings),
  836      prompt(_, Old),
  837      catch(call_expand_query(Query, ExpandedQuery,
  838                              Bindings, ExpandedBindings),
  839            Error,
  840            (print_message(error, Error), fail)),
  841    !.
 read_query(+Prompt, -Goal, -Bindings) is det
Read the next query. The first clause deals with the case where !-based history is enabled. The second is used if we have command line editing.
  850read_query(Prompt, Goal, Bindings) :-
  851    current_prolog_flag(history, N),
  852    integer(N), N > 0,
  853    !,
  854    read_history(h, '!h',
  855                 [trace, end_of_file],
  856                 Prompt, Goal, Bindings).
  857read_query(Prompt, Goal, Bindings) :-
  858    remove_history_prompt(Prompt, Prompt1),
  859    repeat,                                 % over syntax errors
  860    prompt1(Prompt1),
  861    read_query_line(user_input, Line),
  862    '$save_history_line'(Line),             % save raw line (edit syntax errors)
  863    '$current_typein_module'(TypeIn),
  864    catch(read_term_from_atom(Line, Goal,
  865                              [ variable_names(Bindings),
  866                                module(TypeIn)
  867                              ]), E,
  868          (   print_message(error, E),
  869              fail
  870          )),
  871    !,
  872    '$save_history_event'(Line).            % save event (no syntax errors)
 read_query_line(+Input, -Line) is det
  876read_query_line(Input, Line) :-
  877    catch(read_term_as_atom(Input, Line), Error, true),
  878    save_debug_after_read,
  879    (   var(Error)
  880    ->  true
  881    ;   Error = error(syntax_error(_),_)
  882    ->  print_message(error, Error),
  883        fail
  884    ;   print_message(error, Error),
  885        throw(Error)
  886    ).
 read_term_as_atom(+Input, -Line)
Read the next term as an atom and skip to the newline or a non-space character.
  893read_term_as_atom(In, Line) :-
  894    '$raw_read'(In, Line),
  895    (   Line == end_of_file
  896    ->  true
  897    ;   skip_to_nl(In)
  898    ).
 skip_to_nl(+Input) is det
Read input after the term. Skips white space and %... comment until the end of the line or a non-blank character.
  905skip_to_nl(In) :-
  906    repeat,
  907    peek_char(In, C),
  908    (   C == '%'
  909    ->  skip(In, '\n')
  910    ;   char_type(C, space)
  911    ->  get_char(In, _),
  912        C == '\n'
  913    ;   true
  914    ),
  915    !.
  916
  917remove_history_prompt('', '') :- !.
  918remove_history_prompt(Prompt0, Prompt) :-
  919    atom_chars(Prompt0, Chars0),
  920    clean_history_prompt_chars(Chars0, Chars1),
  921    delete_leading_blanks(Chars1, Chars),
  922    atom_chars(Prompt, Chars).
  923
  924clean_history_prompt_chars([], []).
  925clean_history_prompt_chars(['~', !|T], T) :- !.
  926clean_history_prompt_chars([H|T0], [H|T]) :-
  927    clean_history_prompt_chars(T0, T).
  928
  929delete_leading_blanks([' '|T0], T) :-
  930    !,
  931    delete_leading_blanks(T0, T).
  932delete_leading_blanks(L, L).
 set_default_history
Enable !-based numbered command history. This is enabled by default if we are not running under GNU-emacs and we do not have our own line editing.
  941set_default_history :-
  942    current_prolog_flag(history, _),
  943    !.
  944set_default_history :-
  945    (   (   \+ current_prolog_flag(readline, false)
  946        ;   current_prolog_flag(emacs_inferior_process, true)
  947        )
  948    ->  create_prolog_flag(history, 0, [])
  949    ;   create_prolog_flag(history, 25, [])
  950    ).
  951
  952
  953                 /*******************************
  954                 *        TOPLEVEL DEBUG        *
  955                 *******************************/
 save_debug_after_read
Called right after the toplevel read to save the debug status if it was modified from the GUI thread using e.g.
thread_signal(main, gdebug)
bug
- Ideally, the prompt would change if debug mode is enabled. That is hard to realise with all the different console interfaces supported by SWI-Prolog.
  970save_debug_after_read :-
  971    current_prolog_flag(debug, true),
  972    !,
  973    save_debug.
  974save_debug_after_read.
  975
  976save_debug :-
  977    (   tracing,
  978        notrace
  979    ->  Tracing = true
  980    ;   Tracing = false
  981    ),
  982    current_prolog_flag(debug, Debugging),
  983    set_prolog_flag(debug, false),
  984    create_prolog_flag(query_debug_settings,
  985                       debug(Debugging, Tracing), []).
  986
  987restore_debug :-
  988    current_prolog_flag(query_debug_settings, debug(Debugging, Tracing)),
  989    set_prolog_flag(debug, Debugging),
  990    (   Tracing == true
  991    ->  trace
  992    ;   true
  993    ).
  994
  995:- initialization
  996    create_prolog_flag(query_debug_settings, debug(false, false), []).  997
  998
  999                /********************************
 1000                *            PROMPTING          *
 1001                ********************************/
 1002
 1003'$system_prompt'(Module, BrekLev, Prompt) :-
 1004    current_prolog_flag(toplevel_prompt, PAtom),
 1005    atom_codes(PAtom, P0),
 1006    (    Module \== user
 1007    ->   '$substitute'('~m', [Module, ': '], P0, P1)
 1008    ;    '$substitute'('~m', [], P0, P1)
 1009    ),
 1010    (    BrekLev > 0
 1011    ->   '$substitute'('~l', ['[', BrekLev, '] '], P1, P2)
 1012    ;    '$substitute'('~l', [], P1, P2)
 1013    ),
 1014    current_prolog_flag(query_debug_settings, debug(Debugging, Tracing)),
 1015    (    Tracing == true
 1016    ->   '$substitute'('~d', ['[trace] '], P2, P3)
 1017    ;    Debugging == true
 1018    ->   '$substitute'('~d', ['[debug] '], P2, P3)
 1019    ;    '$substitute'('~d', [], P2, P3)
 1020    ),
 1021    atom_chars(Prompt, P3).
 1022
 1023'$substitute'(From, T, Old, New) :-
 1024    atom_codes(From, FromCodes),
 1025    phrase(subst_chars(T), T0),
 1026    '$append'(Pre, S0, Old),
 1027    '$append'(FromCodes, Post, S0) ->
 1028    '$append'(Pre, T0, S1),
 1029    '$append'(S1, Post, New),
 1030    !.
 1031'$substitute'(_, _, Old, Old).
 1032
 1033subst_chars([]) -->
 1034    [].
 1035subst_chars([H|T]) -->
 1036    { atomic(H),
 1037      !,
 1038      atom_codes(H, Codes)
 1039    },
 1040    Codes,
 1041    subst_chars(T).
 1042subst_chars([H|T]) -->
 1043    H,
 1044    subst_chars(T).
 1045
 1046
 1047                /********************************
 1048                *           EXECUTION           *
 1049                ********************************/
 $execute(Goal, Bindings) is det
Execute Goal using Bindings.
 1055'$execute'(Var, _) :-
 1056    var(Var),
 1057    !,
 1058    print_message(informational, var_query(Var)).
 1059'$execute'(Goal, Bindings) :-
 1060    '$current_typein_module'(TypeIn),
 1061    '$dwim_correct_goal'(TypeIn:Goal, Bindings, Corrected),
 1062    !,
 1063    setup_call_cleanup(
 1064        '$set_source_module'(M0, TypeIn),
 1065        expand_goal(Corrected, Expanded),
 1066        '$set_source_module'(M0)),
 1067    print_message(silent, toplevel_goal(Expanded, Bindings)),
 1068    '$execute_goal2'(Expanded, Bindings).
 1069'$execute'(_, _) :-
 1070    notrace,
 1071    print_message(query, query(no)).
 1072
 1073'$execute_goal2'(Goal, Bindings) :-
 1074    restore_debug,
 1075    residue_vars(Goal, Vars),
 1076    deterministic(Det),
 1077    (   save_debug
 1078    ;   restore_debug, fail
 1079    ),
 1080    flush_output(user_output),
 1081    call_expand_answer(Bindings, NewBindings),
 1082    (    \+ \+ write_bindings(NewBindings, Vars, Det)
 1083    ->   !
 1084    ).
 1085'$execute_goal2'(_, _) :-
 1086    save_debug,
 1087    print_message(query, query(no)).
 1088
 1089residue_vars(Goal, Vars) :-
 1090    current_prolog_flag(toplevel_residue_vars, true),
 1091    !,
 1092    call_residue_vars(Goal, Vars).
 1093residue_vars(Goal, []) :-
 1094    toplevel_call(Goal).
 1095
 1096toplevel_call(Goal) :-
 1097    call(Goal),
 1098    no_lco.
 1099
 1100no_lco.
 write_bindings(+Bindings, +ResidueVars, +Deterministic) is semidet
Write bindings resulting from a query. The flag prompt_alternatives_on determines whether the user is prompted for alternatives. groundness gives the classical behaviour, determinism is considered more adequate and informative.

Succeeds if the user accepts the answer and fails otherwise.

Arguments:
ResidueVars- are the residual constraints and provided if the prolog flag toplevel_residue_vars is set to project.
 1115write_bindings(Bindings, ResidueVars, Det) :-
 1116    '$current_typein_module'(TypeIn),
 1117    translate_bindings(Bindings, Bindings1, ResidueVars, TypeIn:Residuals),
 1118    write_bindings2(Bindings1, Residuals, Det).
 1119
 1120write_bindings2([], Residuals, _) :-
 1121    current_prolog_flag(prompt_alternatives_on, groundness),
 1122    !,
 1123    print_message(query, query(yes(Residuals))).
 1124write_bindings2(Bindings, Residuals, true) :-
 1125    current_prolog_flag(prompt_alternatives_on, determinism),
 1126    !,
 1127    print_message(query, query(yes(Bindings, Residuals))).
 1128write_bindings2(Bindings, Residuals, _Det) :-
 1129    repeat,
 1130        print_message(query, query(more(Bindings, Residuals))),
 1131        get_respons(Action),
 1132    (   Action == redo
 1133    ->  !, fail
 1134    ;   Action == show_again
 1135    ->  fail
 1136    ;   !,
 1137        print_message(query, query(done))
 1138    ).
 residual_goals(:NonTerminal)
Directive that registers NonTerminal as a collector for residual goals.
 1145:- multifile
 1146    residual_goal_collector/1. 1147
 1148:- meta_predicate
 1149    residual_goals(2). 1150
 1151residual_goals(NonTerminal) :-
 1152    throw(error(context_error(nodirective, residual_goals(NonTerminal)), _)).
 1153
 1154system:term_expansion((:- residual_goals(NonTerminal)),
 1155                      '$toplevel':residual_goal_collector(M2:Head)) :-
 1156    prolog_load_context(module, M),
 1157    strip_module(M:NonTerminal, M2, Head),
 1158    '$must_be'(callable, Head).
 prolog:residual_goals// is det
DCG that collects residual goals that are not associated with the answer through attributed variables.
 1165:- public prolog:residual_goals//0. 1166
 1167prolog:residual_goals -->
 1168    { findall(NT, residual_goal_collector(NT), NTL) },
 1169    collect_residual_goals(NTL).
 1170
 1171collect_residual_goals([]) --> [].
 1172collect_residual_goals([H|T]) -->
 1173    ( call(H) -> [] ; [] ),
 1174    collect_residual_goals(T).
 prolog:translate_bindings(+Bindings0, -Bindings, +ResidueVars, +ResidualGoals, -Residuals) is det
Translate the raw variable bindings resulting from successfully completing a query into a binding list and list of residual goals suitable for human consumption.
Arguments:
Bindings- is a list of binding(Vars,Value,Substitutions), where Vars is a list of variable names. E.g. binding(['A','B'],42,[])` means that both the variable A and B have the value 42. Values may contain terms '$VAR'(Name) to indicate sharing with a given variable. Value is always an acyclic term. If cycles appear in the answer, Substitutions contains a list of substitutions that restore the original term.
Residuals- is a pair of two lists representing residual goals. The first element of the pair are residuals related to the query variables and the second are related that are disconnected from the query.
 1199:- public
 1200    prolog:translate_bindings/5. 1201:- meta_predicate
 1202    prolog:translate_bindings(+, -, +, +, :). 1203
 1204prolog:translate_bindings(Bindings0, Bindings, ResVars, ResGoals, Residuals) :-
 1205    translate_bindings(Bindings0, Bindings, ResVars, ResGoals, Residuals).
 1206
 1207translate_bindings(Bindings0, Bindings, ResidueVars, Residuals) :-
 1208    prolog:residual_goals(ResidueGoals, []),
 1209    translate_bindings(Bindings0, Bindings, ResidueVars, ResidueGoals,
 1210                       Residuals).
 1211
 1212translate_bindings(Bindings0, Bindings, [], [], _:[]-[]) :-
 1213    term_attvars(Bindings0, []),
 1214    !,
 1215    join_same_bindings(Bindings0, Bindings1),
 1216    factorize_bindings(Bindings1, Bindings2),
 1217    bind_vars(Bindings2, Bindings3),
 1218    filter_bindings(Bindings3, Bindings).
 1219translate_bindings(Bindings0, Bindings, ResidueVars, ResGoals0,
 1220                   TypeIn:Residuals-HiddenResiduals) :-
 1221    project_constraints(Bindings0, ResidueVars),
 1222    hidden_residuals(ResidueVars, Bindings0, HiddenResiduals0),
 1223    omit_qualifiers(HiddenResiduals0, TypeIn, HiddenResiduals),
 1224    copy_term(Bindings0+ResGoals0, Bindings1+ResGoals1, Residuals0),
 1225    '$append'(ResGoals1, Residuals0, Residuals1),
 1226    omit_qualifiers(Residuals1, TypeIn, Residuals),
 1227    join_same_bindings(Bindings1, Bindings2),
 1228    factorize_bindings(Bindings2, Bindings3),
 1229    bind_vars(Bindings3, Bindings4),
 1230    filter_bindings(Bindings4, Bindings).
 1231
 1232hidden_residuals(ResidueVars, Bindings, Goal) :-
 1233    term_attvars(ResidueVars, Remaining),
 1234    term_attvars(Bindings, QueryVars),
 1235    subtract_vars(Remaining, QueryVars, HiddenVars),
 1236    copy_term(HiddenVars, _, Goal).
 1237
 1238subtract_vars(All, Subtract, Remaining) :-
 1239    sort(All, AllSorted),
 1240    sort(Subtract, SubtractSorted),
 1241    ord_subtract(AllSorted, SubtractSorted, Remaining).
 1242
 1243ord_subtract([], _Not, []).
 1244ord_subtract([H1|T1], L2, Diff) :-
 1245    diff21(L2, H1, T1, Diff).
 1246
 1247diff21([], H1, T1, [H1|T1]).
 1248diff21([H2|T2], H1, T1, Diff) :-
 1249    compare(Order, H1, H2),
 1250    diff3(Order, H1, T1, H2, T2, Diff).
 1251
 1252diff12([], _H2, _T2, []).
 1253diff12([H1|T1], H2, T2, Diff) :-
 1254    compare(Order, H1, H2),
 1255    diff3(Order, H1, T1, H2, T2, Diff).
 1256
 1257diff3(<,  H1, T1,  H2, T2, [H1|Diff]) :-
 1258    diff12(T1, H2, T2, Diff).
 1259diff3(=, _H1, T1, _H2, T2, Diff) :-
 1260    ord_subtract(T1, T2, Diff).
 1261diff3(>,  H1, T1, _H2, T2, Diff) :-
 1262    diff21(T2, H1, T1, Diff).
 project_constraints(+Bindings, +ResidueVars) is det
Call <module>:project_attributes/2 if the Prolog flag toplevel_residue_vars is set to project.
 1270project_constraints(Bindings, ResidueVars) :-
 1271    !,
 1272    term_attvars(Bindings, AttVars),
 1273    phrase(attribute_modules(AttVars), Modules0),
 1274    sort(Modules0, Modules),
 1275    term_variables(Bindings, QueryVars),
 1276    project_attributes(Modules, QueryVars, ResidueVars).
 1277project_constraints(_, _).
 1278
 1279project_attributes([], _, _).
 1280project_attributes([M|T], QueryVars, ResidueVars) :-
 1281    (   current_predicate(M:project_attributes/2),
 1282        catch(M:project_attributes(QueryVars, ResidueVars), E,
 1283              print_message(error, E))
 1284    ->  true
 1285    ;   true
 1286    ),
 1287    project_attributes(T, QueryVars, ResidueVars).
 1288
 1289attribute_modules([]) --> [].
 1290attribute_modules([H|T]) -->
 1291    { get_attrs(H, Attrs) },
 1292    attrs_modules(Attrs),
 1293    attribute_modules(T).
 1294
 1295attrs_modules([]) --> [].
 1296attrs_modules(att(Module, _, More)) -->
 1297    [Module],
 1298    attrs_modules(More).
 join_same_bindings(Bindings0, Bindings)
Join variables that are bound to the same value. Note that we return the last value. This is because the factorization may be different and ultimately the names will be printed as V1 = V2, ... VN = Value. Using the last, Value has the factorization of VN.
 1309join_same_bindings([], []).
 1310join_same_bindings([Name=V0|T0], [[Name|Names]=V|T]) :-
 1311    take_same_bindings(T0, V0, V, Names, T1),
 1312    join_same_bindings(T1, T).
 1313
 1314take_same_bindings([], Val, Val, [], []).
 1315take_same_bindings([Name=V1|T0], V0, V, [Name|Names], T) :-
 1316    V0 == V1,
 1317    !,
 1318    take_same_bindings(T0, V1, V, Names, T).
 1319take_same_bindings([Pair|T0], V0, V, Names, [Pair|T]) :-
 1320    take_same_bindings(T0, V0, V, Names, T).
 omit_qualifiers(+QGoals, +TypeIn, -Goals) is det
Omit unneeded module qualifiers from QGoals relative to the given module TypeIn.
 1329omit_qualifiers([], _, []).
 1330omit_qualifiers([Goal0|Goals0], TypeIn, [Goal|Goals]) :-
 1331    omit_qualifier(Goal0, TypeIn, Goal),
 1332    omit_qualifiers(Goals0, TypeIn, Goals).
 1333
 1334omit_qualifier(M:G0, TypeIn, G) :-
 1335    M == TypeIn,
 1336    !,
 1337    omit_meta_qualifiers(G0, TypeIn, G).
 1338omit_qualifier(M:G0, TypeIn, G) :-
 1339    predicate_property(TypeIn:G0, imported_from(M)),
 1340    \+ predicate_property(G0, transparent),
 1341    !,
 1342    G0 = G.
 1343omit_qualifier(_:G0, _, G) :-
 1344    predicate_property(G0, built_in),
 1345    \+ predicate_property(G0, transparent),
 1346    !,
 1347    G0 = G.
 1348omit_qualifier(M:G0, _, M:G) :-
 1349    atom(M),
 1350    !,
 1351    omit_meta_qualifiers(G0, M, G).
 1352omit_qualifier(G0, TypeIn, G) :-
 1353    omit_meta_qualifiers(G0, TypeIn, G).
 1354
 1355omit_meta_qualifiers(V, _, V) :-
 1356    var(V),
 1357    !.
 1358omit_meta_qualifiers((QA,QB), TypeIn, (A,B)) :-
 1359    !,
 1360    omit_qualifier(QA, TypeIn, A),
 1361    omit_qualifier(QB, TypeIn, B).
 1362omit_meta_qualifiers(freeze(V, QGoal), TypeIn, freeze(V, Goal)) :-
 1363    callable(QGoal),
 1364    !,
 1365    omit_qualifier(QGoal, TypeIn, Goal).
 1366omit_meta_qualifiers(when(Cond, QGoal), TypeIn, when(Cond, Goal)) :-
 1367    callable(QGoal),
 1368    !,
 1369    omit_qualifier(QGoal, TypeIn, Goal).
 1370omit_meta_qualifiers(G, _, G).
 bind_vars(+BindingsIn, -Bindings)
Bind variables to '$VAR'(Name), so they are printed by the names used in the query. Note that by binding in the reverse order, variables bound to one another come out in the natural order.
 1379bind_vars(Bindings0, Bindings) :-
 1380    bind_query_vars(Bindings0, Bindings, SNames),
 1381    bind_skel_vars(Bindings, Bindings, SNames, 1, _).
 1382
 1383bind_query_vars([], [], []).
 1384bind_query_vars([binding(Names,Var,[Var2=Cycle])|T0],
 1385                [binding(Names,Cycle,[])|T], [Name|SNames]) :-
 1386    Var == Var2,                   % also implies var(Var)
 1387    !,
 1388    '$last'(Names, Name),
 1389    Var = '$VAR'(Name),
 1390    bind_query_vars(T0, T, SNames).
 1391bind_query_vars([B|T0], [B|T], AllNames) :-
 1392    B = binding(Names,Var,Skel),
 1393    bind_query_vars(T0, T, SNames),
 1394    (   var(Var), \+ attvar(Var), Skel == []
 1395    ->  AllNames = [Name|SNames],
 1396        '$last'(Names, Name),
 1397        Var = '$VAR'(Name)
 1398    ;   AllNames = SNames
 1399    ).
 1400
 1401
 1402
 1403bind_skel_vars([], _, _, N, N).
 1404bind_skel_vars([binding(_,_,Skel)|T], Bindings, SNames, N0, N) :-
 1405    bind_one_skel_vars(Skel, Bindings, SNames, N0, N1),
 1406    bind_skel_vars(T, Bindings, SNames, N1, N).
 bind_one_skel_vars(+Subst, +Bindings, +VarName, +N0, -N)
Give names to the factorized variables that do not have a name yet. This introduces names _S<N>, avoiding duplicates. If a factorized variable shares with another binding, use the name of that variable.
To be done
- Consider the call below. We could remove either of the A = x(1). Which is best?
?- A = x(1), B = a(A,A).
A = x(1),
B = a(A, A), % where
    A = x(1).
 1425bind_one_skel_vars([], _, _, N, N).
 1426bind_one_skel_vars([Var=Value|T], Bindings, Names, N0, N) :-
 1427    (   var(Var)
 1428    ->  (   '$member'(binding(Names, VVal, []), Bindings),
 1429            same_term(Value, VVal)
 1430        ->  '$last'(Names, VName),
 1431            Var = '$VAR'(VName),
 1432            N2 = N0
 1433        ;   between(N0, infinite, N1),
 1434            atom_concat('_S', N1, Name),
 1435            \+ memberchk(Name, Names),
 1436            !,
 1437            Var = '$VAR'(Name),
 1438            N2 is N1 + 1
 1439        )
 1440    ;   N2 = N0
 1441    ),
 1442    bind_one_skel_vars(T, Bindings, Names, N2, N).
 factorize_bindings(+Bindings0, -Factorized)
Factorize cycles and sharing in the bindings.
 1449factorize_bindings([], []).
 1450factorize_bindings([Name=Value|T0], [binding(Name, Skel, Subst)|T]) :-
 1451    '$factorize_term'(Value, Skel, Subst0),
 1452    (   current_prolog_flag(toplevel_print_factorized, true)
 1453    ->  Subst = Subst0
 1454    ;   only_cycles(Subst0, Subst)
 1455    ),
 1456    factorize_bindings(T0, T).
 1457
 1458
 1459only_cycles([], []).
 1460only_cycles([B|T0], List) :-
 1461    (   B = (Var=Value),
 1462        Var = Value,
 1463        acyclic_term(Var)
 1464    ->  only_cycles(T0, List)
 1465    ;   List = [B|T],
 1466        only_cycles(T0, T)
 1467    ).
 filter_bindings(+Bindings0, -Bindings)
Remove bindings that must not be printed. There are two of them: Variables whose name start with '_' and variables that are only bound to themselves (or, unbound).
 1476filter_bindings([], []).
 1477filter_bindings([H0|T0], T) :-
 1478    hide_vars(H0, H),
 1479    (   (   arg(1, H, [])
 1480        ;   self_bounded(H)
 1481        )
 1482    ->  filter_bindings(T0, T)
 1483    ;   T = [H|T1],
 1484        filter_bindings(T0, T1)
 1485    ).
 1486
 1487hide_vars(binding(Names0, Skel, Subst), binding(Names, Skel, Subst)) :-
 1488    hide_names(Names0, Skel, Subst, Names).
 1489
 1490hide_names([], _, _, []).
 1491hide_names([Name|T0], Skel, Subst, T) :-
 1492    (   sub_atom(Name, 0, _, _, '_'),
 1493        current_prolog_flag(toplevel_print_anon, false),
 1494        sub_atom(Name, 1, 1, _, Next),
 1495        char_type(Next, prolog_var_start)
 1496    ->  true
 1497    ;   Subst == [],
 1498        Skel == '$VAR'(Name)
 1499    ),
 1500    !,
 1501    hide_names(T0, Skel, Subst, T).
 1502hide_names([Name|T0], Skel, Subst, [Name|T]) :-
 1503    hide_names(T0, Skel, Subst, T).
 1504
 1505self_bounded(binding([Name], Value, [])) :-
 1506    Value == '$VAR'(Name).
 get_respons(-Action)
Read the continuation entered by the user.
 1512get_respons(Action) :-
 1513    repeat,
 1514        flush_output(user_output),
 1515        get_single_char(Char),
 1516        answer_respons(Char, Action),
 1517        (   Action == again
 1518        ->  print_message(query, query(action)),
 1519            fail
 1520        ;   !
 1521        ).
 1522
 1523answer_respons(Char, again) :-
 1524    '$in_reply'(Char, '?h'),
 1525    !,
 1526    print_message(help, query(help)).
 1527answer_respons(Char, redo) :-
 1528    '$in_reply'(Char, ';nrNR \t'),
 1529    !,
 1530    print_message(query, if_tty([ansi(bold, ';', [])])).
 1531answer_respons(Char, redo) :-
 1532    '$in_reply'(Char, 'tT'),
 1533    !,
 1534    trace,
 1535    save_debug,
 1536    print_message(query, if_tty([ansi(bold, '; [trace]', [])])).
 1537answer_respons(Char, continue) :-
 1538    '$in_reply'(Char, 'ca\n\ryY.'),
 1539    !,
 1540    print_message(query, if_tty([ansi(bold, '.', [])])).
 1541answer_respons(0'b, show_again) :-
 1542    !,
 1543    break.
 1544answer_respons(Char, show_again) :-
 1545    print_predicate(Char, Pred, Options),
 1546    !,
 1547    print_message(query, if_tty(['~w'-[Pred]])),
 1548    set_prolog_flag(answer_write_options, Options).
 1549answer_respons(-1, show_again) :-
 1550    !,
 1551    print_message(query, halt('EOF')),
 1552    halt(0).
 1553answer_respons(Char, again) :-
 1554    print_message(query, no_action(Char)).
 1555
 1556print_predicate(0'w, [write], [ quoted(true),
 1557                                spacing(next_argument)
 1558                              ]).
 1559print_predicate(0'p, [print], [ quoted(true),
 1560                                portray(true),
 1561                                max_depth(10),
 1562                                spacing(next_argument)
 1563                              ]).
 1564
 1565
 1566                 /*******************************
 1567                 *          EXPANSION           *
 1568                 *******************************/
 1569
 1570:- user:dynamic(expand_query/4). 1571:- user:multifile(expand_query/4). 1572
 1573call_expand_query(Goal, Expanded, Bindings, ExpandedBindings) :-
 1574    user:expand_query(Goal, Expanded, Bindings, ExpandedBindings),
 1575    !.
 1576call_expand_query(Goal, Expanded, Bindings, ExpandedBindings) :-
 1577    toplevel_variables:expand_query(Goal, Expanded, Bindings, ExpandedBindings),
 1578    !.
 1579call_expand_query(Goal, Goal, Bindings, Bindings).
 1580
 1581
 1582:- user:dynamic(expand_answer/2). 1583:- user:multifile(expand_answer/2). 1584
 1585call_expand_answer(Goal, Expanded) :-
 1586    user:expand_answer(Goal, Expanded),
 1587    !.
 1588call_expand_answer(Goal, Expanded) :-
 1589    toplevel_variables:expand_answer(Goal, Expanded),
 1590    !.
 1591call_expand_answer(Goal, Goal)