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(,,,). 74 75:- multifile 76 el_setup/1, % +Input 77 el_wcwidth/2, % +Code, -Columns 78 prolog:complete_input/4.
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(_)).
user_input
is connected to a terminal. This is the high level predicate used
for most purposes. The remainder of the library interface deals with
low level predicates that allows for applying and programming
libedit in non-standard situations.
The library is registered with ProgName set to swipl (see
el_wrap/4).
Options processed:
history or 100 if this flag is not defined.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, _).
-v or -e.
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 ).ESC[1;5D and ESC[1;5C
for these key combinations (see packages/xpce/src/txt/terminal.c);
most xterm-compatible terminals use the same sequences. In vi
mode the binding is installed in both the insert keymap and the
command (alternative) keymap. Called after the el_setup/1 hooks
since those may switch editor.
This complements the readline emulation, which already binds these sequences in its initialisation.
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 ).^Z to send end-of-file on Windows, matching the platform
convention (compare with ^D on Unix). Routed through libedit's
built-in em-delete-or-list (emacs) or vi-list-or-eof (vi), both
of which return EOF on an empty line.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(_).
262el_wrap(ProgName, In, Out, Error) :-
263 el_wrap(ProgName, In, Out, Error, []).forall(el_setup(Input), true) after the
input stream has been wrapped, the default Prolog commands have been
added and the default user setup file has been sourced using
el_source/2. It can be used to define and bind additional commands.$HOME/.editrcbind command with the given arguments. The
example below lists the current key bindings.
?- el_bind(user_input, ['-a']).
The predicate el_bind/2 is typically used to bind commands defined using el_addfn/4. Note that the C proxy function has only the last character of the command as context to find the Prolog binding. This implies we cannot both bind e.g., "^[?" and "?" to a Prolog function.
bind -a (see el_bind/2) and Goal is called of the
associated key-binding is activated. Goal is called as
call(:Goal, +Input, +Char, -Continue)
where Input is the input stream providing access to the editor, Char
the activating character and Continue must be instantated with one
of the known continuation codes as defined by libedit: norm,
newline, eof, arghack, refresh, refresh_beep, cursor,
redisplay, error or fatal. In addition, the following Continue
code is provided.
The registered Goal typically used el_line/2 to fetch the input line and el_cursor/2, el_insertstr/2 and/or el_deletestr/2 to manipulate the input line.
Normally el_bind/2 is used to associate the defined command with a keyboard sequence.
el_set() and el_wset(). Currently provided values for
Action are:
el_wsey() EL_WORDCHARS, which is only provided
in some recent versions of libedit.ESC[200~ /
ESC[201~ before each prompt, which the default bindings
route through bracketed_paste/3. Disabling sends the matching
ESC[?2004l sequence immediately. enable_bracketed_paste/1
manages this based on the current editor; you normally do not
need to set it directly.This predicate fails silently of Action is not implemented. Illegal input raises in an exception.
el_get(). Currently supported Property terms:
emacs or vi, reflecting the current
keymap selected via el_bind/2 with -e / -v.
Any other Property raises a domain_error(editline_property, _).
line(Before,
After), where Before is a string holding the text before the
cursor and After is a string holding the text after the cursor.history() from libedit. Supported actions are:
el_history() using H_GETSIZE,
which returns the number of currently saved events. The number
of saved events may be computed from first and last or
using el_history_events/2.first is the most recent event and
last the oldest.history() API, retrieving a numbered event without changing
the current notion.Num-String, where
Num is the event number and String is the associated string
without terminating newline.LIBEDIT_MAJOR*10000 + LIBEDIT_MINOR*100.
The version is generated from the include file histedit.h,
which implies that the actual version of the shared library may be
different.473:- multifile 474 prolog:history/2. 475 476prologhistory(Input, enabled) :- 477 !, 478 el_wrapped(Input), 479 el_history(Input, getsize(Size)), 480 Size > 0. 481prologhistory(Input, add(Line)) :- 482 !, 483 el_add_history(Input, Line). 484prologhistory(Input, load(File)) :- 485 !, 486 compat_read_history(Input, File). 487prologhistory(Input, save(File)) :- 488 !, 489 el_write_history(Input, File). 490prologhistory(Input, events(Events)) :- 491 !, 492 el_history_events(Input, Events). 493prologhistory(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).
swipl-win.exe before migrating to SDL.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 *******************************/
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]).
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 *******************************/
complete editline function. The
predicate is called with three arguments, the first being the input
stream used to access the libedit functions and the second the
activating character. The last argument tells libedit what to do.
Consult el_set(3), EL_ADDFN for details.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.
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.input in effect while the user is typing (see
decorate_prompt/2 in boot/toplevel.pl). Erasing part of the screen
paints it with the current background colour, so libedit must switch
these attributes off before it erases the rows the line no longer
uses, e.g. after unwrapping a long line or moving from a multi-line
history entry to a shorter one. See EL_ATTRS in libedit.
The toplevel calls this each time it builds a prompt, so a theme loaded at run time is picked up. Does nothing if libedit is too old to support this.
750prologline_editor_attributes(Off, On) :-
751 el_wrapped(user_input),
752 ignore(el_set(user_input, attrs(Off, On))).
The toplevel decorates the input line by leaving the attributes of
the colour class input in effect while the user is typing (see
decorate_prompt/2 in boot/toplevel.pl). Without this reset that
decoration also applies to the text below, and if the class has a
background colour it paints whatever we erase with `\e[K` as well.
The commands that write this text end with redisplay, which makes
libedit redraw the line from scratch and thus re-install the style.
769plain_style :- 770 format(user_error, '\e[0m', []). 771 772complete_text(Text-_Comment, Text) :- !. 773complete_text(Text, Text).
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).
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).
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(_, _, []).
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 *******************************/
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(,,). 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(_).
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 *******************************/
The terminal is asked to enable bracketed paste mode (ESC[?2004h) from the C layer each time a prompt is issued.
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.
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 ).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 1100prologerror_message(editline(Msg)) --> 1101 [ 'editline: ~s'-[Msg] ]
BSD libedit based command line editing
This library wraps the BSD libedit command line editor. The binding provides a high level API to enable command line editing on the Prolog user streams and low level predicates to apply the library on other streams and program the library.
While reading a line, the binding surrounds the prompt and the input with the OSC 133 semantic prompt marks of FinalTerm:
ESC]133;Abefore the prompt,ESC]133;Bbefore the input,ESC]133;Cafter the line was entered andESC]133;Dwhere its output ends, which is just before the next line is asked for. A term that takes more than one line is read a line at a time; the prompt of each line after the first is markedESC]133;A;k=s, which says it continues an input rather than starting one, so that a terminal can keep the whole term together. A terminal that understands them (Epilog, iTerm2, kitty, WezTerm, VS Code) can tell prompt, input and output apart, which is what lets it jump between prompts, act on the output of one command or, in Epilog, move the caret to a click in the line being edited. A read that asks for a single character, as get_single_char/1 and the debugger do, is not marked: there is no line being edited there. A terminal that does not know the marks ignores them; one that prints them instead can be spared them with el_set/2 usingprompt_marks(false).