View source with formatted 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)  2017-2025, VU University Amsterdam
    7                              CWI Amsterdam
    8                              SWI-Prolog Solutions b.v.
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(editline,
   38          [ el_wrap/0,                          % wrap user_input, etc.
   39            el_wrap/1,                          % +Options
   40            el_wrap/4,                          % +Prog, +Input, +Output, +Error
   41            el_wrap/5,                          % +Prog, +Input, +Output, +Error, +Options
   42            el_wrapped/1,                       % +Input
   43            el_unwrap/1,                        % +Input
   44
   45            el_source/2,                        % +Input, +File
   46            el_bind/2,                          % +Input, +Args
   47            el_set/2,                           % +Input, +Action
   48            el_get/2,                           % +Input, ?Property
   49            el_addfn/4,                         % +Input, +Name, +Help, :Goal
   50            el_cursor/2,                        % +Input, +Move
   51            el_line/2,                          % +Input, -Line
   52            el_insertstr/2,                     % +Input, +Text
   53            el_deletestr/2,                     % +Input, +Count
   54
   55            el_history/2,                       % +Input, ?Action
   56            el_history_events/2,                % +Input, -Events
   57            el_add_history/2,                   % +Input, +Line
   58            el_write_history/2,                 % +Input, +FileName
   59            el_read_history/2,                  % +Input, +FileName
   60
   61	    el_version/1			% -Version:integer
   62          ]).   63:- autoload(library(apply),[maplist/2,maplist/3]).   64:- autoload(library(lists),[reverse/2,max_list/2,append/3,member/2]).   65:- autoload(library(solution_sequences),[call_nth/2]).   66:- autoload(library(option), [merge_options/3]).   67
   68:- use_foreign_library(foreign(libedit4pl)).   69
   70:- initialization el_wrap_if_ok.   71
   72:- meta_predicate
   73    el_addfn(+,+,+,3).   74
   75:- multifile
   76    el_setup/1,                         % +Input
   77    el_wcwidth/2,                       % +Code, -Columns
   78    prolog:complete_input/4.   79
   80
   81/** <module> BSD libedit based command line editing
   82
   83This library wraps the BSD  libedit   command  line  editor. The binding
   84provides a high level API to enable   command line editing on the Prolog
   85user streams and low level predicates  to   apply  the  library on other
   86streams and program the library.
   87
   88While reading a line, the binding  surrounds   the  prompt and the input
   89with the OSC 133 _semantic  prompt_   marks  of FinalTerm: ``ESC]133;A``
   90before the prompt, ``ESC]133;B`` before   the input, ``ESC]133;C`` after
   91the line was entered and ``ESC]133;D`` where   its output ends, which is
   92just before the next line is asked for.  A term that takes more than one
   93line is read a line at a time; the   prompt of each line after the first
   94is marked ``ESC]133;A;k=s``, which says  it   continues  an input rather
   95than starting one, so that a terminal  can keep the whole term together.
   96A terminal that understands them  (Epilog,   iTerm2,  kitty, WezTerm, VS
   97Code) can tell prompt, input and  output   apart,  which is what lets it
   98jump between prompts, act on the output   of  one command or, in Epilog,
   99move the caret to a click in the line being edited. A read that asks for
  100a single character, as get_single_char/1  and   the  debugger do, is not
  101marked: there is no line being edited   there.  A terminal that does not
  102know the marks ignores them; one that  prints them instead can be spared
  103them with el_set/2 using `prompt_marks(false)`.
  104*/
  105
  106el_wrap_if_ok :-
  107    stream_property(user_input, tty(true)),
  108    os_stream(user_output),
  109    os_stream(user_error),
  110    !,
  111    el_wrap.
  112el_wrap_if_ok.
  113
  114%   The output streams must be OS files for el_wrap/5.  They are not
  115%   if the library is loaded by a thread that was created while the
  116%   output was captured, e.g., by with_output_to/3 or a unit test: the
  117%   thread inherits the memory streams, while user_input is still the
  118%   terminal.
  119
  120os_stream(Stream) :-
  121    stream_property(Stream, file_no(_)).
  122
  123%!  el_wrap is det.
  124%!  el_wrap(+Options) is det.
  125%
  126%   Enable using editline on the standard   user streams if `user_input`
  127%   is connected to a terminal. This is   the  high level predicate used
  128%   for most purposes. The remainder of the library interface deals with
  129%   low level predicates  that  allows   for  applying  and  programming
  130%   libedit in non-standard situations.
  131%
  132%   The library is registered  with  _ProgName_   set  to  `swipl`  (see
  133%   el_wrap/4).
  134%
  135%   Options processed:
  136%
  137%     - pipes(+Boolean)
  138%       Used by Epilog windows to indicate we are reading from a Windows
  139%       named pipe in _overlapped_ mode.  Ignored on other platforms.
  140%     - history(+Size)
  141%       Size of the history.  Default is defined by the Prolog flag
  142%       `history` or `100` if this flag is not defined.
  143%     - alert_signo(+Integer)
  144%       Signal used for making thread_signal/2 work while the thread
  145%       is in a blocking system call.
  146
  147el_wrap :-
  148    el_wrap([]).
  149
  150el_wrap(_) :-
  151    el_wrapped(user_input),
  152    !.
  153el_wrap(Options) :-
  154    stream_property(user_input, tty(true)), !,
  155    findall(Opt, el_default(Opt), Defaults),
  156    merge_options(Options, Defaults, Options1),
  157    el_wrap(swipl, user_input, user_output, user_error, Options1),
  158    add_prolog_commands(user_input),
  159    ignore(el_set(user_input, wordchars("_"))),
  160    forall(el_setup(user_input), true),
  161    enable_bracketed_paste(user_input),
  162    enable_word_motion(user_input),
  163    enable_windows_eof(user_input).
  164el_wrap(_).
  165
  166el_default(history(Size)) :-
  167    current_prolog_flag(history, Value),
  168    (   integer(Value),
  169        Value >= 0
  170    ->  Size = Value
  171    ;   Value == false
  172    ->  Size = 0
  173    ).
  174:- if(current_predicate(prolog_alert_signal/2)).  175el_default(alert_signo(SigNo)) :-
  176    prolog_alert_signal(SigName, SigName),
  177    current_signal(SigName, SigNo, _Handler).
  178:- endif.  179
  180add_prolog_commands(Input) :-
  181    el_addfn(Input, complete, 'Complete atoms and files', complete),
  182    el_addfn(Input, show_completions, 'List completions', show_completions),
  183    el_addfn(Input, electric, 'Indicate matching bracket', electric),
  184    el_addfn(Input, isearch_history, 'Incremental search in history',
  185             isearch_history),
  186    el_addfn(Input, bracketed_paste, 'Handle bracketed paste', bracketed_paste),
  187    el_bind(Input, ["^I",  complete]),
  188    el_bind(Input, ["^[?", show_completions]),
  189    el_bind(Input, ["^R",  isearch_history]),
  190    bind_electric(Input),
  191    add_paste_quoted(Input),
  192    el_source(Input, _).
  193
  194%!  enable_bracketed_paste(+Input) is det.
  195%
  196%   Sync bracketed paste mode with the current editor: bind ESC[200~
  197%   to bracketed_paste/3 and enable the mode in emacs, unbind and
  198%   disable it in vi.  In vi mode ESC leaves insert mode, so the
  199%   ESC[200~ start marker cannot be dispatched as a key binding.
  200%   Called from el_wrap/1 after the el_setup/1 hook, since that hook
  201%   may switch editor with el_bind/2 `-v` or `-e`.
  202
  203enable_bracketed_paste(Input) :-
  204    (   el_get(Input, editor(vi))
  205    ->  el_bind(Input, ['-r', "\e[200~"]),
  206        el_set(Input, bracketed_paste(false))
  207    ;   el_bind(Input, ["\e[200~", bracketed_paste]),
  208        el_set(Input, bracketed_paste(true))
  209    ).
  210
  211%!  enable_word_motion(+Input) is det.
  212%
  213%   Bind the xterm Ctrl+Left/Ctrl+Right escape sequences to word
  214%   motion.  The Epilog terminal sends ``ESC[1;5D`` and ``ESC[1;5C``
  215%   for these key combinations (see packages/xpce/src/txt/terminal.c);
  216%   most xterm-compatible terminals use the same sequences.  In vi
  217%   mode the binding is installed in both the insert keymap and the
  218%   command (alternative) keymap.  Called after the el_setup/1 hooks
  219%   since those may switch editor.
  220%
  221%   This complements the readline emulation, which already binds
  222%   these sequences in its initialisation.
  223
  224enable_word_motion(Input) :-
  225    el_bind(Input, ["\e[1;5D", 'ed-prev-word']),
  226    el_bind(Input, ["\e[1;5C", 'em-next-word']),
  227    (   el_get(Input, editor(vi))
  228    ->  el_bind(Input, ['-a', "\e[1;5D", 'vi-prev-word']),
  229        el_bind(Input, ['-a', "\e[1;5C", 'vi-next-word'])
  230    ;   true
  231    ).
  232
  233%!  enable_windows_eof(+Input) is det.
  234%
  235%   Bind ``^Z`` to send end-of-file on Windows, matching the platform
  236%   convention (compare with ``^D`` on Unix).  Routed through libedit's
  237%   built-in `em-delete-or-list` (emacs) or `vi-list-or-eof` (vi), both
  238%   of which return EOF on an empty line.
  239
  240enable_windows_eof(Input) :-
  241    current_prolog_flag(windows, true),
  242    !,
  243    (   el_get(Input, editor(vi))
  244    ->  el_bind(Input, ["^Z", 'vi-list-or-eof'])
  245    ;   el_bind(Input, ["^Z", 'em-delete-or-list'])
  246    ).
  247enable_windows_eof(_).
  248
  249%!  el_wrap(+ProgName:atom, +In:stream, +Out:stream, +Error:stream) is det.
  250%!  el_wrap(+ProgName:atom, +In:stream, +Out:stream, +Error:stream, +Options) is det.
  251%
  252%   Enable editline on  the  stream-triple   <In,Out,Error>.  From  this
  253%   moment on In is a handle to the command line editor.  Options:
  254%
  255%     - pipes(true)
  256%       Windows only. Assume the I/O is using pipes rather than a
  257%       console.  This is used for the Epilog terminal.
  258%
  259%   @arg ProgName is the name of the invoking program, used when reading
  260%   the editrc(5) file to determine which settings to use.
  261
  262el_wrap(ProgName, In, Out, Error) :-
  263    el_wrap(ProgName, In, Out, Error, []).
  264
  265%!  el_setup(+In:stream) is nondet.
  266%
  267%   This hooks is called as   forall(el_setup(Input),  true) _after_ the
  268%   input stream has been wrapped, the default Prolog commands have been
  269%   added and the  default  user  setup   file  has  been  sourced using
  270%   el_source/2. It can be used to define and bind additional commands.
  271
  272%!  el_wrapped(+In:stream) is semidet.
  273%
  274%   True if In is a stream wrapped by el_wrap/3.
  275
  276%!  el_unwrap(+In:stream) is det.
  277%
  278%   Remove the libedit wrapper for In and   the related output and error
  279%   streams.
  280%
  281%   @bug The wrapper creates =|FILE*|= handles that cannot be closed and
  282%   thus wrapping and unwrapping implies a (modest) memory leak.
  283
  284%!  el_source(+In:stream, +File) is det.
  285%
  286%   Initialise editline by reading the contents of File.  If File is
  287%   unbound try =|$HOME/.editrc|=
  288
  289
  290%!  el_bind(+In:stream, +Args) is det.
  291%
  292%   Invoke the libedit `bind` command  with   the  given  arguments. The
  293%   example below lists the current key bindings.
  294%
  295%   ```
  296%   ?- el_bind(user_input, ['-a']).
  297%   ```
  298%
  299%   The predicate el_bind/2 is typically used   to bind commands defined
  300%   using el_addfn/4. Note that the C proxy   function has only the last
  301%   character of the command as context to find the Prolog binding. This
  302%   implies we cannot both bind  e.g.,  "^[?"   _and_  "?"  to  a Prolog
  303%   function.
  304%
  305%   @see editrc(5) for more information.
  306
  307%!  el_addfn(+Input:stream, +Command, +Help, :Goal) is det.
  308%
  309%   Add a new command to the command  line editor associated with Input.
  310%   Command is the name of the command,  Help is the help string printed
  311%   with e.g. =|bind -a|= (see el_bind/2)  and   Goal  is  called of the
  312%   associated key-binding is activated.  Goal is called as
  313%
  314%       call(:Goal, +Input, +Char, -Continue)
  315%
  316%   where Input is the input stream providing access to the editor, Char
  317%   the activating character and Continue must   be instantated with one
  318%   of the known continuation  codes  as   defined  by  libedit: `norm`,
  319%   `newline`, `eof`, `arghack`, `refresh`,   `refresh_beep`,  `cursor`,
  320%   `redisplay`, `error` or `fatal`. In addition, the following Continue
  321%   code is provided.
  322%
  323%     * electric(Move, TimeOut, Continue)
  324%     Show _electric caret_ at Move positions to the left of the normal
  325%     cursor positions for the given TimeOut.  Continue as defined by
  326%     the Continue value.
  327%
  328%   The registered Goal typically used el_line/2 to fetch the input line
  329%   and el_cursor/2, el_insertstr/2 and/or  el_deletestr/2 to manipulate
  330%   the input line.
  331%
  332%   Normally el_bind/2 is used to associate   the defined command with a
  333%   keyboard sequence.
  334%
  335%   @see el_set(3) =EL_ADDFN= for details.
  336
  337%!  el_set(+Input:stream, +Action) is semidet.
  338%
  339%   Interface to el_set() and el_wset().   Currently provided values for
  340%   Action are:
  341%
  342%     - wordchars(+Text)
  343%       Set the characters considered part of a _word_.  This feature
  344%       depends on el_wsey() ``EL_WORDCHARS``, which is only provided
  345%       in some recent versions of `libedit`.
  346%     - bracketed_paste(+Boolean)
  347%       Enable or disable bracketed paste mode.  When enabled, the
  348%       terminal is asked to bracket pasted text with ``ESC[200~`` /
  349%       ``ESC[201~`` before each prompt, which the default bindings
  350%       route through bracketed_paste/3.  Disabling sends the matching
  351%       ``ESC[?2004l`` sequence immediately.  enable_bracketed_paste/1
  352%       manages this based on the current editor; you normally do not
  353%       need to set it directly.
  354%     - prompt_marks(+Boolean)
  355%       Enable or disable the OSC 133 prompt marks described with this
  356%       module.  They are enabled by default and are ignored by a
  357%       terminal that does not know them; disable them for a terminal
  358%       that prints them instead.  Note that Epilog then has neither
  359%       mark nor bracketed paste to tell it that a line is being
  360%       edited if bracketed paste is disabled as well, and a click no
  361%       longer moves the caret.
  362%
  363%   This predicate fails silently of Action  is not implemented. Illegal
  364%   input raises in an exception.
  365
  366%!  el_get(+Input:stream, ?Property) is semidet.
  367%
  368%   Interface to el_get().  Currently supported Property terms:
  369%
  370%     - editor(-Editor)
  371%       Editor is unified with `emacs` or `vi`, reflecting the current
  372%       keymap selected via el_bind/2 with `-e` / `-v`.
  373%     - bracketed_paste(-Boolean)
  374%       Whether bracketed paste mode is currently enabled; see
  375%       el_set/2.
  376%     - prompt_marks(-Boolean)
  377%       Whether the prompt and the input are marked with OSC 133; see
  378%       el_set/2.
  379%
  380%   Any other Property raises a `domain_error(editline_property, _)`.
  381
  382%!  el_line(+Input:stream, -Line) is det.
  383%
  384%   Fetch the currently buffered input line. Line is a term line(Before,
  385%   After), where `Before` is  a  string   holding  the  text before the
  386%   cursor and `After` is a string holding the text after the cursor.
  387
  388%!  el_cursor(+Input:stream, +Move:integer) is det.
  389%
  390%   Move the cursor Move  character   forwards  (positive)  or backwards
  391%   (negative).
  392
  393%!  el_insertstr(+Input:stream, +Text) is det.
  394%
  395%   Insert Text at the cursor.
  396
  397%!  el_deletestr(+Input:stream, +Count) is det.
  398%
  399%   Delete Count characters before the cursor.
  400
  401%!  el_history(+In:stream, ?Action) is det.
  402%
  403%   Perform a generic action on the history. This provides an incomplete
  404%   interface to history() from libedit.  Supported actions are:
  405%
  406%     - clear
  407%       Clear the history.
  408%     - setsize(+Integer)
  409%       Set size of history to size elements.
  410%     - getsize(-Integer)
  411%       Unify Integer with the maximum size of the history.  Note that
  412%       this is _not_ the same as el_history() using ``H_GETSIZE``,
  413%       which returns the number of currently saved events. The number
  414%       of saved events may be computed from `first` and `last` or
  415%       using el_history_events/2.
  416%     - setunique(+Boolean)
  417%       Set flag that adjacent identical event strings should not be
  418%       entered into the history.
  419%     - first(-Num, -String)
  420%     - last(-Num, -String)
  421%     - curr(-Num, -String)
  422%     - prev(-Num, -String)
  423%     - next(-Num, -String)
  424%       Retrieve an event.  Num is the event number and String is the
  425%       event string.  Note that `first` is the most recent event and
  426%       `last` the oldest.
  427%     - set(Num)
  428%       Set the notion of _current_ to Num.
  429%     - prev_str(+Search, -Num, -String)
  430%     - next_str(+Search, -Num, -String)
  431%       Retrieve the previous or next event whose String starts with
  432%       Search.
  433%     - event(+Num, -String)
  434%       True when String represents event Num.   This is an extension to
  435%       the history() API, retrieving a numbered event without changing
  436%       the current notion.
  437
  438%!  el_history_events(+In:stream, -Events:list(pair)) is det.
  439%
  440%   Unify Events with a list of pairs   of  the form `Num-String`, where
  441%   `Num` is the event number  and   `String`  is  the associated string
  442%   without terminating newline.
  443
  444%!  el_add_history(+In:stream, +Line:text) is det.
  445%
  446%   Add a line to the command line history.
  447
  448%!  el_read_history(+In:stream, +File:file) is det.
  449%
  450%   Read the history saved using el_write_history/2.
  451%
  452%   @arg File is a file specification for absolute_file_name/3.
  453
  454%!  el_write_history(+In:stream, +File:file) is det.
  455%
  456%   Save editline history to File.  The   history  may be reloaded using
  457%   el_read_history/2.
  458%
  459%   @arg File is a file specification for absolute_file_name/3.
  460
  461%!  el_version(-Version)
  462%
  463%   True when Version  is ``LIBEDIT_MAJOR*10000 + LIBEDIT_MINOR*100``.
  464%   The  version is  generated from  the include  file ``histedit.h``,
  465%   which implies that the actual version of the shared library may be
  466%   different.
  467
  468%!  prolog:history(+Input, ?Action) is semidet.
  469%
  470%   Provide  the  plugable  interface  into   the  system  command  line
  471%   management.
  472
  473:- multifile
  474    prolog:history/2.  475
  476prolog:history(Input, enabled) :-
  477    !,
  478    el_wrapped(Input),
  479    el_history(Input, getsize(Size)),
  480    Size > 0.
  481prolog:history(Input, add(Line)) :-
  482    !,
  483    el_add_history(Input, Line).
  484prolog:history(Input, load(File)) :-
  485    !,
  486    compat_read_history(Input, File).
  487prolog:history(Input, save(File)) :-
  488    !,
  489    el_write_history(Input, File).
  490prolog:history(Input, events(Events)) :-
  491    !,
  492    el_history_events(Input, Events).
  493prolog:history(Input, Command) :-
  494    public_command(Command),
  495    !,
  496    el_history(Input, Command).
  497
  498public_command(first(_Num, _String)).
  499public_command(curr(_Num, _String)).
  500public_command(event(_Num, _String)).
  501public_command(prev_str(_Search, _Num, _String)).
  502public_command(clear).
  503
  504%!  compat_read_history(+Input, +File) is det.
  505%
  506%   Read the saved history. This loads both  the LibEdit and old history
  507%   format used by `swipl-win.exe` before migrating to SDL.
  508
  509compat_read_history(Input, File) :-
  510    catch(el_read_history(Input, File), error(editline(_),_), fail),
  511    !.
  512compat_read_history(Input, File) :-
  513    access_file(File, read),
  514    setup_call_cleanup(
  515        open(File, read, In, [encoding(utf8)]),
  516        read_old_history(Input, In),
  517        close(In)),
  518    !.
  519compat_read_history(_, _).
  520
  521read_old_history(Input, From) :-
  522    catch('$raw_read'(From, Line), error(_,_), fail),
  523    (   Line == end_of_file
  524    ->  true
  525    ;   string_concat(Line, '.', Event),
  526        el_add_history(Input, Event),
  527        read_old_history(Input, From)
  528    ).
  529
  530		 /*******************************
  531		 *        ELECTRIC CARET	*
  532		 *******************************/
  533
  534%!  bind_electric(+Input) is det.
  535%
  536%   Bind known close statements for electric input
  537
  538bind_electric(Input) :-
  539    forall(bracket(_Open, Close), bind_code(Input, Close, electric)),
  540    forall(quote(Close), bind_code(Input, Close, electric)).
  541
  542bind_code(Input, Code, Command) :-
  543    string_codes(Key, [Code]),
  544    el_bind(Input, [Key, Command]).
  545
  546
  547%!  electric(+Input, +Char, -Continue) is det.
  548
  549electric(Input, Char, Continue) :-
  550    string_codes(Str, [Char]),
  551    el_insertstr(Input, Str),
  552    el_line(Input, line(Before, _)),
  553    (   string_codes(Before, Codes),
  554        nesting(Codes, 0, Nesting),
  555        reverse(Nesting, [Close|RevNesting])
  556    ->  (   Close = open(_,_)                   % open quote
  557        ->  Continue = refresh
  558        ;   matching_open(RevNesting, Close, _, Index)
  559        ->  string_length(Before, Len),         % Proper match
  560            Move is Index-Len,
  561            Continue = electric(Move, 500, refresh)
  562        ;   Continue = refresh_beep             % Not properly nested
  563        )
  564    ;   Continue = refresh_beep
  565    ).
  566
  567matching_open_index(String, Index) :-
  568    string_codes(String, Codes),
  569    nesting(Codes, 0, Nesting),
  570    reverse(Nesting, [Close|RevNesting]),
  571    matching_open(RevNesting, Close, _, Index).
  572
  573matching_open([Open|Rest], Close, Rest, Index) :-
  574    Open = open(Index,_),
  575    match(Open, Close),
  576    !.
  577matching_open([Close1|Rest1], Close, Rest, Index) :-
  578    Close1 = close(_,_),
  579    matching_open(Rest1, Close1, Rest2, _),
  580    matching_open(Rest2, Close, Rest, Index).
  581
  582match(open(_,Open),close(_,Close)) :-
  583    (   bracket(Open, Close)
  584    ->  true
  585    ;   Open == Close,
  586        quote(Open)
  587    ).
  588
  589bracket(0'(, 0')).
  590bracket(0'[, 0']).
  591bracket(0'{, 0'}).
  592
  593quote(0'\').
  594quote(0'\").
  595quote(0'\`).
  596
  597nesting([], _, []).
  598nesting([H|T], I, Nesting) :-
  599    (   bracket(H, _Close)
  600    ->  Nesting = [open(I,H)|Nest]
  601    ;   bracket(_Open, H)
  602    ->  Nesting = [close(I,H)|Nest]
  603    ),
  604    !,
  605    I2 is I+1,
  606    nesting(T, I2, Nest).
  607nesting([0'0, 0'\'|T], I, Nesting) :-
  608    !,
  609    phrase(skip_code, T, T1),
  610    difflist_length(T, T1, Len),
  611    I2 is I+Len+2,
  612    nesting(T1, I2, Nesting).
  613nesting([H|T], I, Nesting) :-
  614    quote(H),
  615    !,
  616    (   phrase(skip_quoted(H), T, T1)
  617    ->  difflist_length(T, T1, Len),
  618        I2 is I+Len+1,
  619        Nesting = [open(I,H),close(I2,H)|Nest],
  620        nesting(T1, I2, Nest)
  621    ;   Nesting = [open(I,H)]                   % Open quote
  622    ).
  623nesting([_|T], I, Nesting) :-
  624    I2 is I+1,
  625    nesting(T, I2, Nesting).
  626
  627difflist_length(List, Tail, Len) :-
  628    difflist_length(List, Tail, 0, Len).
  629
  630difflist_length(List, Tail, Len0, Len) :-
  631    List == Tail,
  632    !,
  633    Len = Len0.
  634difflist_length([_|List], Tail, Len0, Len) :-
  635    Len1 is Len0+1,
  636    difflist_length(List, Tail, Len1, Len).
  637
  638skip_quoted(H) -->
  639    [H],
  640    !.
  641skip_quoted(H) -->
  642    "\\", [H],
  643    !,
  644    skip_quoted(H).
  645skip_quoted(H) -->
  646    [_],
  647    skip_quoted(H).
  648
  649skip_code -->
  650    "\\", [_],
  651    !.
  652skip_code -->
  653    [_].
  654
  655
  656		 /*******************************
  657		 *           COMPLETION		*
  658		 *******************************/
  659
  660%!  complete(+Input, +Char, -Continue) is det.
  661%
  662%   Implementation of the registered `complete`   editline function. The
  663%   predicate is called with three arguments,  the first being the input
  664%   stream used to access  the  libedit   functions  and  the second the
  665%   activating character. The last argument tells   libedit  what to do.
  666%   Consult el_set(3), =EL_ADDFN= for details.
  667
  668
  669:- dynamic
  670    last_complete/2.  671
  672complete(Input, _Char, Continue) :-
  673    el_line(Input, line(Before, After)),
  674    ensure_input_completion,
  675    prolog:complete_input(Before, After, Delete, Completions),
  676    (   Completions = [One]
  677    ->  string_length(Delete, Len),
  678        el_deletestr(Input, Len),
  679        complete_text(One, Text),
  680        el_insertstr(Input, Text),
  681        Continue = refresh
  682    ;   Completions == []
  683    ->  Continue = refresh_beep
  684    ;   get_time(Now),
  685        retract(last_complete(TLast, Before)),
  686        Now - TLast < 2
  687    ->  plain_style,
  688        nl(user_error),
  689        list_alternatives(Completions),
  690        Continue = redisplay
  691    ;   retractall(last_complete(_,_)),
  692        get_time(Now),
  693        asserta(last_complete(Now, Before)),
  694        common_competion(Completions, Extend),
  695        (   Delete == Extend
  696        ->  Continue = refresh_beep
  697        ;   string_length(Delete, Len),
  698            el_deletestr(Input, Len),
  699            el_insertstr(Input, Extend),
  700            Continue = refresh
  701        )
  702    ).
  703
  704:- dynamic
  705    input_completion_loaded/0.  706
  707ensure_input_completion :-
  708    input_completion_loaded,
  709    !.
  710ensure_input_completion :-
  711    predicate_property(prolog:complete_input(_,_,_,_),
  712                       number_of_clauses(N)),
  713    N > 0,
  714    !.
  715ensure_input_completion :-
  716    exists_source(library(console_input)),
  717    !,
  718    use_module(library(console_input), []),
  719    asserta(input_completion_loaded).
  720ensure_input_completion.
  721
  722
  723%!  show_completions(+Input, +Char, -Continue) is det.
  724%
  725%   Editline command to show possible completions.
  726
  727show_completions(Input, _Char, Continue) :-
  728    el_line(Input, line(Before, After)),
  729    prolog:complete_input(Before, After, _Delete, Completions),
  730    plain_style,
  731    nl(user_error),
  732    list_alternatives(Completions),
  733    Continue = redisplay.
  734
  735%!  prolog:line_editor_attributes(+Off, +On) is det.
  736%
  737%   Tell libedit how to switch the  decoration of the line being edited
  738%   off and on again.  The toplevel leaves the attributes of the colour
  739%   class `input` in effect while the  user is typing (see
  740%   decorate_prompt/2 in `boot/toplevel.pl`).  Erasing part of the screen
  741%   paints it with the current background colour, so libedit must switch
  742%   these attributes off before it erases  the rows the line no longer
  743%   uses, e.g. after unwrapping a long line or moving from a multi-line
  744%   history entry to a shorter one.  See EL_ATTRS in libedit.
  745%
  746%   The toplevel calls this each time it builds a prompt, so a theme
  747%   loaded at run time is picked up.  Does nothing if libedit is too old
  748%   to support this.
  749
  750prolog:line_editor_attributes(Off, On) :-
  751    el_wrapped(user_input),
  752    ignore(el_set(user_input, attrs(Off, On))).
  753
  754%!  plain_style is det.
  755%
  756%   Reset the terminal attributes before writing text that is not part of
  757%   the line being edited, such  as   the  completion alternatives or the
  758%   incremental search prompt.
  759%
  760%   The toplevel decorates the input line   by leaving the attributes of
  761%   the colour class `input` in effect while the user is typing (see
  762%   decorate_prompt/2 in `boot/toplevel.pl`).  Without this reset that
  763%   decoration also applies to the text below, and if the class has a
  764%   background colour it paints whatever we erase with `\e[K` as well.
  765%
  766%   The commands that write this text end with `redisplay`, which makes
  767%   libedit redraw the line from scratch and thus re-install the style.
  768
  769plain_style :-
  770    format(user_error, '\e[0m', []).
  771
  772complete_text(Text-_Comment, Text) :- !.
  773complete_text(Text, Text).
  774
  775%!  common_competion(+Alternatives, -Common) is det.
  776%
  777%   True when Common is the common prefix of all candidate Alternatives.
  778
  779common_competion(Alternatives, Common) :-
  780    maplist(atomic, Alternatives),
  781    !,
  782    common_prefix(Alternatives, Common).
  783common_competion(Alternatives, Common) :-
  784    maplist(complete_text, Alternatives, AltText),
  785    !,
  786    common_prefix(AltText, Common).
  787
  788%!  common_prefix(+Atoms, -Common) is det.
  789%
  790%   True when Common is the common prefix of all Atoms.
  791
  792common_prefix([A1|T], Common) :-
  793    common_prefix_(T, A1, Common).
  794
  795common_prefix_([], Common, Common).
  796common_prefix_([H|T], Common0, Common) :-
  797    common_prefix(H, Common0, Common1),
  798    common_prefix_(T, Common1, Common).
  799
  800%!  common_prefix(+A1, +A2, -Prefix:string) is det.
  801%
  802%   True when Prefix is the common prefix of the atoms A1 and A2
  803
  804common_prefix(A1, A2, Prefix) :-
  805    sub_atom(A1, 0, _, _, A2),
  806    !,
  807    Prefix = A2.
  808common_prefix(A1, A2, Prefix) :-
  809    sub_atom(A2, 0, _, _, A1),
  810    !,
  811    Prefix = A1.
  812common_prefix(A1, A2, Prefix) :-
  813    atom_codes(A1, C1),
  814    atom_codes(A2, C2),
  815    list_common_prefix(C1, C2, C),
  816    string_codes(Prefix, C).
  817
  818list_common_prefix([H|T0], [H|T1], [H|T]) :-
  819    !,
  820    list_common_prefix(T0, T1, T).
  821list_common_prefix(_, _, []).
  822
  823
  824
  825%!  list_alternatives(+Alternatives)
  826%
  827%   List possible completions at the current point.
  828%
  829%   @tbd currently ignores the Comment in Text-Comment alternatives.
  830
  831list_alternatives(Alternatives) :-
  832    maplist(atomic, Alternatives),
  833    !,
  834    length(Alternatives, Count),
  835    maplist(atom_length, Alternatives, Lengths),
  836    max_list(Lengths, Max),
  837    tty_size(_, Cols),
  838    ColW is Max+2,
  839    Columns is max(1, Cols // ColW),
  840    RowCount is (Count+Columns-1)//Columns,
  841    length(Rows, RowCount),
  842    to_matrix(Alternatives, Rows, Rows),
  843    (   RowCount > 11
  844    ->  length(First, 10),
  845        Skipped is RowCount - 10,
  846        append(First, _, Rows),
  847        maplist(write_row(ColW), First),
  848        format(user_error, '... skipped ~D rows~n', [Skipped])
  849    ;   maplist(write_row(ColW), Rows)
  850    ).
  851list_alternatives(Alternatives) :-
  852    maplist(complete_text, Alternatives, AltText),
  853    list_alternatives(AltText).
  854
  855to_matrix([], _, Rows) :-
  856    !,
  857    maplist(close_list, Rows).
  858to_matrix([H|T], [RH|RT], Rows) :-
  859    !,
  860    add_list(RH, H),
  861    to_matrix(T, RT, Rows).
  862to_matrix(List, [], Rows) :-
  863    to_matrix(List, Rows, Rows).
  864
  865add_list(Var, Elem) :-
  866    var(Var), !,
  867    Var = [Elem|_].
  868add_list([_|T], Elem) :-
  869    add_list(T, Elem).
  870
  871close_list(List) :-
  872    append(List, [], _),
  873    !.
  874
  875write_row(ColW, Row) :-
  876    length(Row, Columns),
  877    make_format(Columns, ColW, Format),
  878    format(user_error, Format, Row).
  879
  880make_format(N, ColW, Format) :-
  881    format(string(PerCol), '~~w~~t~~~d+', [ColW]),
  882    Front is N - 1,
  883    length(LF, Front),
  884    maplist(=(PerCol), LF),
  885    append(LF, ['~w~n'], Parts),
  886    atomics_to_string(Parts, Format).
  887
  888
  889		 /*******************************
  890		 *             SEARCH		*
  891		 *******************************/
  892
  893%!  isearch_history(+Input, +Char, -Continue) is det.
  894%
  895%   Incremental search through the history.  The behavior is based
  896%   on GNU readline.
  897
  898isearch_history(Input, _Char, Continue) :-
  899    el_line(Input, line(Before, After)),
  900    string_concat(Before, After, Current),
  901    string_length(Current, Len),
  902    search_print('', "", Current),
  903    search(Input, "", Current, 1, Line),
  904    el_deletestr(Input, Len),
  905    el_insertstr(Input, Line),
  906    Continue = redisplay.
  907
  908search(Input, For, Current, Nth, Line) :-
  909    el_getc(Input, Next),
  910    Next \== -1,
  911    !,
  912    search(Next, Input, For, Current, Nth, Line).
  913search(_Input, _For, _Current, _Nth, "").
  914
  915search(7, _Input, _, Current, _, Current) :-    % C-g: abort
  916    !,
  917    clear_line.
  918search(18, Input, For, Current, Nth, Line) :-   % C-r: search previous
  919    !,
  920    N2 is Nth+1,
  921    search_(Input, For, Current, N2, Line).
  922search(19, Input, For, Current, Nth, Line) :-   % C-s: search next
  923    !,
  924    N2 is max(1,Nth-1),
  925    search_(Input, For, Current, N2, Line).
  926search(127, Input, For, Current, _Nth, Line) :- % DEL/BS: shorten search
  927    sub_string(For, 0, _, 1, For1),
  928    !,
  929    search_(Input, For1, Current, 1, Line).
  930search(Char, Input, For, Current, Nth, Line) :-
  931    code_type(Char, cntrl),
  932    !,
  933    search_end(Input, For, Current, Nth, Line),
  934    el_push(Input, Char).
  935search(Char, Input, For, Current, _Nth, Line) :-
  936    format(string(For1), '~w~c', [For,Char]),
  937    search_(Input, For1, Current, 1, Line).
  938
  939search_(Input, For1, Current, Nth, Line) :-
  940    (   find_in_history(Input, For1, Current, Nth, Candidate)
  941    ->  search_print('', For1, Candidate)
  942    ;   search_print('failed ', For1, Current)
  943    ),
  944    search(Input, For1, Current, Nth, Line).
  945
  946search_end(Input, For, Current, Nth, Line) :-
  947    (   find_in_history(Input, For, Current, Nth, Line)
  948    ->  true
  949    ;   Line = Current
  950    ),
  951    clear_line.
  952
  953find_in_history(_, "", Current, _, Current) :-
  954    !.
  955find_in_history(Input, For, _, Nth, Line) :-
  956    el_history_events(Input, History),
  957    call_nth(( member(_N-Line, History),
  958               sub_string(Line, _, _, _, For)
  959             ),
  960             Nth),
  961    !.
  962
  963%   Note that we reset the attributes  (see   plain_style/0):  the search
  964%   prompt is not the line being edited and, more importantly, `\e[0K'
  965%   erases using the current background colour.
  966
  967search_print(State, Search, Current) :-
  968    format(user_error, '\r\e[0m(~wreverse-i-search)`~w\': ~w\e[0K',
  969           [State, Search, Current]).
  970
  971clear_line :-
  972    format(user_error, '\r\e[0m\e[0K', []).
  973
  974
  975                /*******************************
  976                *         PASTE QUOTED         *
  977                *******************************/
  978
  979:- meta_predicate
  980    with_quote_flags(+,+,0).  981
  982add_paste_quoted(Input) :-
  983    current_prolog_flag(gui, true),
  984    !,
  985    el_addfn(Input, paste_quoted, 'Paste as quoted atom', paste_quoted),
  986    el_bind(Input, ["^Y",  paste_quoted]).
  987add_paste_quoted(_).
  988
  989%!  paste_quoted(+Input, +Char, -Continue) is det.
  990%
  991%   Paste the selection as quoted Prolog value.   The quoting type
  992%   depends on the quote before the caret.  If there is no quote
  993%   before the caret we paste as an atom.
  994
  995paste_quoted(Input, _Char, Continue) :-
  996    clipboard_content(String),
  997    quote_text(Input, String, Quoted),
  998    el_insertstr(Input, Quoted),
  999    Continue = refresh.
 1000
 1001quote_text(Input, String, Value) :-
 1002    el_line(Input, line(Before, _After)),
 1003    (   sub_string(Before, _, 1, 0, Quote)
 1004    ->  true
 1005    ;   Quote = "'"
 1006    ),
 1007    quote_text(Input, Quote, String, Value).
 1008
 1009quote_text(Input, "'", Text, Quoted) =>
 1010    format(string(Quoted), '~q', [Text]),
 1011    el_deletestr(Input, 1).
 1012quote_text(Input, "\"", Text, Quoted) =>
 1013    atom_string(Text, String),
 1014    with_quote_flags(
 1015        string, codes,
 1016        format(string(Quoted), '~q', [String])),
 1017    el_deletestr(Input, 1).
 1018quote_text(Input, "`", Text, Quoted) =>
 1019    atom_string(Text, String),
 1020    with_quote_flags(
 1021        codes, string,
 1022        format(string(Quoted), '~q', [String])),
 1023    el_deletestr(Input, 1).
 1024quote_text(_, _, Text, Quoted) =>
 1025    format(string(Quoted), '~q', [Text]).
 1026
 1027with_quote_flags(Double, Back, Goal) :-
 1028    setup_call_cleanup(
 1029        ( push_prolog_flag(double_quotes, Double),
 1030          push_prolog_flag(back_quotes, Back) ),
 1031        Goal,
 1032        ( pop_prolog_flag(back_quotes),
 1033          pop_prolog_flag(double_quotes) )).
 1034
 1035clipboard_content(Text) :-
 1036    current_prolog_flag(gui, true),
 1037    !,
 1038    autoload_call(in_pce_thread_sync(
 1039                      autoload_call(
 1040                          get(@(display), paste, primary, string(Text))))).
 1041clipboard_content("").
 1042
 1043
 1044                /*******************************
 1045                *       BRACKETED PASTE        *
 1046                *******************************/
 1047
 1048%!  bracketed_paste(+Input, +Char, -Continue) is det.
 1049%
 1050%   Handler for the bracketed paste start sequence ESC[200~.  Reads
 1051%   characters until the end sequence ESC[201~ is received and inserts
 1052%   the collected text literally, bypassing per-character key dispatch.
 1053%
 1054%   The terminal is asked to enable bracketed paste mode (ESC[?2004h)
 1055%   from the C layer each time a prompt is issued.
 1056
 1057bracketed_paste(Input, _Char, Continue) :-
 1058    collect_paste(Input, [], RevCodes),
 1059    reverse(RevCodes, Codes),
 1060    string_codes(Text, Codes),
 1061    el_insertstr(Input, Text),
 1062    Continue = refresh.
 1063
 1064%!  collect_paste(+Input, +RevAcc, -RevResult) is det.
 1065%
 1066%   Read characters one at a time, accumulating them in reverse order.
 1067%   Stop when the reversed accumulator starts with the end sequence
 1068%   ESC[201~ (27,91,50,48,49,126) and return the reversed content that
 1069%   precedes it.
 1070
 1071collect_paste(Input, RevCodes, Result) :-
 1072    el_getc(Input, Char),
 1073    (   Char == -1                          % EOF / error
 1074    ->  Result = RevCodes
 1075    ;   paste_char(Char, Char1),
 1076        RevCodes1 = [Char1|RevCodes],
 1077        (   RevCodes1 = [0'~,0'1,0'0,0'2,0'[,0'\e|Rest]  % ESC[201~ reversed
 1078        ->  Result = Rest
 1079        ;   collect_paste(Input, RevCodes1, Result)
 1080        )
 1081    ).
 1082
 1083%!  paste_char(+Raw, -Char) is det.
 1084%
 1085%   Translate a raw character code from bracketed paste to the intended
 1086%   code.  The tty line discipline in edit mode has INLCR set, which maps
 1087%   LF (10) to CR (13) before libedit reads it.  We reverse that here so
 1088%   pasted newlines are inserted as actual newlines.
 1089
 1090paste_char(0'\r, 0'\n) :- !.               % CR → LF (INLCR maps \n to \r in edit mode)
 1091paste_char(C,   C).
 1092
 1093
 1094                /*******************************
 1095                *           MESSAGE            *
 1096                *******************************/
 1097
 1098:- multifile prolog:error_message//1. 1099
 1100prolog:error_message(editline(Msg)) -->
 1101    [ 'editline: ~s'-[Msg] ]