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:           https://www.swi-prolog.org
    6    Copyright (c)  1998-2026, University of Amsterdam
    7                              VU University 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(prolog_edit,
   38          [ edit/1,                     % +Spec
   39            edit/0
   40          ]).   41:- autoload(library(lists), [member/2, append/3, select/3, append/2]).   42:- autoload(library(error), [domain_error/2]).   43:- autoload(library(make), [make/0]).   44:- autoload(library(prolog_breakpoints), [breakpoint_property/2]).   45:- autoload(library(apply), [foldl/5, maplist/3, maplist/2]).   46:- use_module(library(dcg/high_order), [sequence/5]).   47:- autoload(library(readutil), [read_line_to_string/2]).   48:- autoload(library(solution_sequences), [distinct/2]).   49:- if(exists_source(library(editline))).   50:- autoload(library(editline), [el_history_events/2]).   51:- endif.   52
   53% :- set_prolog_flag(generate_debug_info, false).

Editor interface

This module implements the generic editor interface. It consists of two extensible parts with little in between. The first part deals with translating the input into source-location, and the second with starting an editor.

   63:- multifile
   64    locate/3,                       % +Partial, -FullSpec, -Location
   65    locate/2,                       % +FullSpec, -Location
   66    select_location/3,              % +Pairs, +Spec, -Location
   67    exists_location/1,              % +Location
   68    user_select/2,                  % +Max, -I
   69    edit_source/1,                  % +Location
   70    edit_command/2,                 % +Editor, -Command
   71    load/0.                         % provides load-hooks
   72
   73:- public
   74    locations/2,                    % +Spec, -Locations
   75    predicate_location/2,           % :Pred, -Location
   76    addr2location/3.                % +Address, -File, -Line
 edit(+Spec)
Edit indicated object. Spec is a predicate indicator, a file specification or a source location File:Line or File:Line:Col. Both Line and Col count from 1, as in the messages we print, the hyperlinks we emit (see ansi_hyperlink/2) and the messages of e.g., the C compiler. Note that the line_position of a stream (see stream_position_data/3) counts from 0.
   87edit(Spec) :-
   88    notrace(edit_no_trace(Spec)).
   89
   90edit_no_trace(Spec) :-
   91    var(Spec),
   92    !,
   93    throw(error(instantiation_error, _)).
   94edit_no_trace(Spec) :-
   95    locations(Spec, Pairs),
   96    do_select_location(Pairs, Spec, Location),
   97    do_edit_source(Location).
 edit
Edit associated or script file. This is the Prolog file opened by double-clicking, the initial file loaded from the commandline using e.g., the command below or the last file loaded into the current session using ?- [file]., ?- consult(file). or ?- use_module(file).
% swipl [-s] file.pl
  111edit :-
  112    current_prolog_flag(associated_file, File),
  113    !,
  114    edit(file(File)).
  115edit :-
  116    '$cmd_option_val'(script_file, OsFiles),
  117    OsFiles = [OsFile],
  118    !,
  119    prolog_to_os_filename(File, OsFile),
  120    edit(file(File)).
  121:- if(exists_source(library(editline))).  122edit :-
  123    session_loaded_file(File),
  124    !,
  125    edit(file(File)).
  126:- endif.  127edit :-
  128    throw(error(context_error(edit, no_default_file), _)).
  129
  130:- if(exists_source(library(editline))).  131session_loaded_file(File) :-
  132    catch(el_history_events(user_input, Events),
  133          error(_,_), fail),
  134    member(_-Event, Events),
  135    catch(term_string(Command, Event), error(_,_), fail),
  136    load_command(Command, File0),
  137    (   is_list(File0)
  138    ->  member(File1, File0)
  139    ;   File1 = File0
  140    ),
  141    catch(absolute_file_name(File1, File,
  142                             [ file_type(source),
  143                               file_errors(fail)
  144                             ]),
  145          error(_,_), fail),
  146    source_file(File),
  147    !.
  148
  149load_command([File|T], [File|T]).
  150load_command(consult(File), File).
  151load_command(use_module(File), File).
  152:- endif.
 locations(+Spec, -Locations) is det
Locate entities matching Spec. Locations is a list of pairs Location-FullSpec, where Location is a dict holding a file, optional line and optional linepos keys. FullSpec is the disambiguated specification, e.g., member expands to member/2 for the predicate.
  162locations(Spec, Locations) :-
  163    load_extensions,
  164    findall(Location-FullSpec,
  165            locate(Spec, FullSpec, Location),
  166            Pairs0),
  167    sort(Pairs0, Pairs1),
  168    merge_locations(Pairs1, Locations).
  169
  170
  171                 /*******************************
  172                 *            LOCATE            *
  173                 *******************************/
 locate(+Spec, -FullSpec, -Location:dict)
  177locate(FileSpec:Line, file(Path, line(Line)), #{file:Path, line:Line}) :-
  178    integer(Line), Line >= 1,
  179    ground(FileSpec),                      % so specific; do not try alts
  180    !,
  181    locate(FileSpec, _, #{file:Path}).
  182locate(FileSpec:Line:LinePos,
  183       file(Path, line(Line), linepos(LinePos)),
  184       #{file:Path, line:Line, linepos:LinePos}) :-
  185    integer(Line), Line >= 1,
  186    integer(LinePos), LinePos >= 1,
  187    ground(FileSpec),                      % so specific; do not try alts
  188    !,
  189    locate(FileSpec, _, #{file:Path}).
  190locate(Path, file(Path), #{file:Path}) :-
  191    atom(Path),
  192    exists_file(Path).
  193locate(Pattern, file(Path), #{file:Path}) :-
  194    atom(Pattern),
  195    catch(expand_file_name(Pattern, Files), error(_,_), fail),
  196    member(Path, Files),
  197    exists_file(Path).
  198locate(FileBase, file(File), #{file:File}) :-
  199    atom(FileBase),
  200    find_source(FileBase, File).
  201locate(FileSpec, file(File), #{file:File}) :-
  202    is_file_search_spec(FileSpec),
  203    find_source(FileSpec, File).
  204locate(FileBase, source_file(Path),  #{file:Path}) :-
  205    atom(FileBase),
  206    source_file(Path),
  207    file_base_name(Path, File),
  208    (   File == FileBase
  209    ->  true
  210    ;   file_name_extension(FileBase, _, File)
  211    ).
  212locate(FileBase, include_file(Path),  #{file:Path}) :-
  213    atom(FileBase),
  214    setof(Path, include_file(Path), Paths),
  215    member(Path, Paths),
  216    file_base_name(Path, File),
  217    (   File == FileBase
  218    ->  true
  219    ;   file_name_extension(FileBase, _, File)
  220    ).
  221locate(Name, FullSpec, Location) :-
  222    atom(Name),
  223    locate(Name/_, FullSpec, Location).
  224locate(Name/Arity, Module:Name/Arity, Location) :-
  225    locate(Module:Name/Arity, Location).
  226locate(Name//DCGArity, FullSpec, Location) :-
  227    (   integer(DCGArity)
  228    ->  Arity is DCGArity+2,
  229        locate(Name/Arity, FullSpec, Location)
  230    ;   locate(Name/_, FullSpec, Location) % demand arity >= 2
  231    ).
  232locate(Name/Arity, library(File),  #{file:PlPath}) :-
  233    atom(Name),
  234    '$in_library'(Name, Arity, Path),
  235    (   absolute_file_name(library(.), Dir,
  236                           [ file_type(directory),
  237                             solutions(all)
  238                           ]),
  239        atom_concat(Dir, File0, Path),
  240        atom_concat(/, File, File0)
  241    ->  find_source(Path, PlPath)
  242    ;   fail
  243    ).
  244locate(Module:Name, Module:Name/Arity, Location) :-
  245    locate(Module:Name/Arity, Location).
  246locate(Module:Head, Module:Name/Arity, Location) :-
  247    callable(Head),
  248    \+ ( Head = (PName/_),
  249         atom(PName)
  250       ),
  251    functor(Head, Name, Arity),
  252    locate(Module:Name/Arity, Location).
  253locate(Spec, module(Spec), Location) :-
  254    locate(module(Spec), Location).
  255locate(Spec, Spec, Location) :-
  256    locate(Spec, Location).
  257
  258include_file(Path) :-
  259    source_file_property(Path, included_in(_,_)).
 is_file_search_spec(@Spec) is semidet
True if Spec is valid pattern for absolute_file_name/3.
  265is_file_search_spec(Spec) :-
  266    compound(Spec),
  267    compound_name_arguments(Spec, Alias, [Arg]),
  268    is_file_spec(Arg),
  269    user:file_search_path(Alias, _),
  270    !.
  271
  272is_file_spec(Name), atom(Name) => true.
  273is_file_spec(Name), string(Name) => true.
  274is_file_spec(Term), cyclic_term(Term) => fail.
  275is_file_spec(A/B) => is_file_spec(A), is_file_spec(B).
  276is_file_spec(_) => fail.
 find_source(++FileSpec, =File) is semidet
Find a source file from FileSpec. If FileSpec resolves to a .qlf file, File is the embedded `.pl` file (which may not exist).
  283find_source(FileSpec, File) :-
  284    catch(absolute_file_name(FileSpec, File0,
  285                             [ file_type(prolog),
  286                               access(read),
  287                               file_errors(fail)
  288                             ]),
  289          error(_,_), fail),
  290    prolog_source(File0, File).
  291
  292prolog_source(File0, File) :-
  293    file_name_extension(_, Ext, File0),
  294    user:prolog_file_type(Ext, qlf),
  295    !,
  296    '$qlf_module'(File0, Info),
  297    File = Info.get(file).
  298prolog_source(File, File).
 locate(+Spec, -Location)
Locate object from the specified location.
  305locate(file(File, line(Line)), #{file:File, line:Line}).
  306locate(file(File), #{file:File}).
  307locate(Module:Name/Arity, Location) :-
  308    (   atom(Name), integer(Arity)
  309    ->  functor(Head, Name, Arity)
  310    ;   Head = _                    % leave unbound
  311    ),
  312    (   (   var(Module)
  313        ;   var(Name)
  314        )
  315    ->  NonImport = true
  316    ;   NonImport = false
  317    ),
  318    current_predicate(Name, Module:Head),
  319    \+ (   NonImport == true,
  320           Module \== system,
  321           predicate_property(Module:Head, imported_from(_))
  322       ),
  323    functor(Head, Name, Arity),     % bind arity
  324    predicate_location(Module:Head, Location).
  325locate(module(Module), Location) :-
  326    atom(Module),
  327    module_property(Module, file(Path)),
  328    (   module_property(Module, line_count(Line))
  329    ->  Location = #{file:Path, line:Line}
  330    ;   Location = #{file:Path}
  331    ).
  332locate(breakpoint(Id), Location) :-
  333    integer(Id),
  334    breakpoint_property(Id, clause(Ref)),
  335    (   breakpoint_property(Id, file(File)),
  336        breakpoint_property(Id, line_count(Line))
  337    ->  Location =  #{file:File, line:Line}
  338    ;   locate(clause(Ref), Location)
  339    ).
  340locate(clause(Ref), #{file:File, line:Line}) :-
  341    clause_property(Ref, file(File)),
  342    clause_property(Ref, line_count(Line)).
  343locate(clause(Ref, _PC), #{file:File, line:Line}) :- % TBD: use clause
  344    clause_property(Ref, file(File)),
  345    clause_property(Ref, line_count(Line)).
 predicate_location(:Predicate, -Location) is nondet
Find the source location of a predicate.
Arguments:
Predicate- is a qualified head. The module may be unbound at entry. It will be bound to the actual implementation module.
  354predicate_location(Pred, #{file:File, line:Line}) :-
  355    copy_term(Pred, Pred2),
  356    distinct(Primary, primary_predicate(Pred2, Primary)),
  357    ignore(Pred = Primary),
  358    '$predicate_source_location'(Primary, File:Line).
  359
  360primary_predicate(Pred, Primary) :-
  361    (   predicate_property(Pred, imported_from(Source))
  362    ->  strip_module(Pred, _, Head),
  363        Primary = Source:Head
  364    ;   Primary = Pred
  365    ).
 addr2location(+Address, -File, -Line) is semidet
Get the File and Line for a C address.
  372addr2location(Address, File, Line) :-
  373    '$addr2line'(Address, Source),
  374    '$addr2line_location'(Source, File, Line).
  375
  376
  377                 /*******************************
  378                 *             EDIT             *
  379                 *******************************/
 do_edit_source(+Location)
Actually call the editor to edit Location, a list of Name(Value) that contains file(File) and may contain line(Line). First the multifile hook edit_source/1 is called. If this fails the system checks for XPCE and the prolog-flag editor. If the latter is built_in or pce_emacs, it will start PceEmacs.

Finally, it will get the editor to use from the prolog-flag editor and use edit_command/2 to determine how this editor should be called.

  393do_edit_source(Location) :-             % hook
  394    edit_source(Location),
  395    !.
  396do_edit_source(Location) :-             % PceEmacs
  397    current_prolog_flag(editor, Editor),
  398    is_pceemacs(Editor),
  399    current_prolog_flag(gui, true),
  400    !,
  401    location_url(Location, URL),        % File[:Line[:LinePos]]
  402    run_pce_emacs(URL).
  403do_edit_source(Location) :-             % External editor
  404    external_edit_command(Location, Command),
  405    print_message(informational, edit(waiting_for_editor)),
  406    (   catch(shell(Command), E,
  407              (print_message(warning, E),
  408               fail))
  409    ->  print_message(informational, edit(make)),
  410        make
  411    ;   print_message(informational, edit(canceled))
  412    ).
  413
  414external_edit_command(Location, Command) :-
  415    #{file:File, line:Line} :< Location,
  416    editor(Editor),
  417    file_base_name(Editor, EditorFile),
  418    file_name_extension(Base, _, EditorFile),
  419    edit_command(Base, Cmd),
  420    prolog_to_os_filename(File, OsFile),
  421    shell_safe_file(File, OsFile),
  422    atom_codes(Cmd, S0),
  423    substitute('%e', Editor, S0, S1),
  424    substitute('%f', OsFile, S1, S2),
  425    substitute('%d', Line,   S2, S),
  426    !,
  427    atom_codes(Command, S).
  428external_edit_command(Location, Command) :-
  429    #{file:File} :< Location,
  430    editor(Editor),
  431    file_base_name(Editor, EditorFile),
  432    file_name_extension(Base, _, EditorFile),
  433    edit_command(Base, Cmd),
  434    prolog_to_os_filename(File, OsFile),
  435    shell_safe_file(File, OsFile),
  436    atom_codes(Cmd, S0),
  437    substitute('%e', Editor, S0, S1),
  438    substitute('%f', OsFile, S1, S),
  439    \+ substitute('%d', 1, S, _),
  440    !,
  441    atom_codes(Command, S).
  442external_edit_command(Location, Command) :-
  443    #{file:File} :< Location,
  444    editor(Editor),
  445    shell_safe_file(File, File),
  446    format(string(Command), '"~w" "~w"', [Editor, File]).
 shell_safe_file(+File, +OsFile) is det
The editor command is run using shell/1, where the file name appears inside quotes of the edit_command/2 template. Refuse file names with characters that may end the quoted text or are expanded by the shell.
Errors
- domain_error(shell_safe_file_name, File)
  457shell_safe_file(File, OsFile) :-
  458    atom_codes(OsFile, Codes),
  459    (   member(C, Codes),
  460        unsafe_file_char(C)
  461    ->  domain_error(shell_safe_file_name, File)
  462    ;   true
  463    ).
  464
  465unsafe_file_char(C) :-
  466    C < 0' .
  467unsafe_file_char(C) :-
  468    memberchk(C, `'"\`$`).
  469unsafe_file_char(C) :-
  470    current_prolog_flag(windows, true),
  471    !,
  472    memberchk(C, `%!^&|<>`).
  473unsafe_file_char(0'\\).
  474
  475is_pceemacs(pce_emacs).
  476is_pceemacs(built_in).
 run_pce_emacs(+URL) is semidet
Dynamically load and run emacs/1.
  482run_pce_emacs(URL) :-
  483    autoload_call(in_pce_thread(autoload_call(emacs(URL)))).
 editor(-Editor)
Determine the external editor to run.
  489editor(Editor) :-                       % $EDITOR
  490    current_prolog_flag(editor, Editor),
  491    (   sub_atom(Editor, 0, _, _, $)
  492    ->  sub_atom(Editor, 1, _, 0, Var),
  493        catch(getenv(Var, Editor), _, fail), !
  494    ;   Editor == default
  495    ->  catch(getenv('EDITOR', Editor), _, fail), !
  496    ;   \+ is_pceemacs(Editor)
  497    ->  !
  498    ).
  499editor(Editor) :-                       % User defaults
  500    getenv('EDITOR', Editor),
  501    !.
  502editor(vi) :-                           % Platform defaults
  503    current_prolog_flag(unix, true),
  504    !.
  505editor(notepad) :-
  506    current_prolog_flag(windows, true),
  507    !.
  508editor(_) :-                            % No luck
  509    throw(error(existence_error(editor), _)).
 edit_command(+Editor, -Command)
This predicate should specify the shell-command called to invoke the user's editor. The following substitutions will be made:
%ePath name of the editor
%fPath name of the file to be edited
%dLine number of the target
  521edit_command(vi,          '%e +%d \'%f\'').
  522edit_command(vi,          '%e \'%f\'').
  523edit_command(emacs,       '%e +%d \'%f\'').
  524edit_command(emacs,       '%e \'%f\'').
  525edit_command(notepad,     '"%e" "%f"').
  526edit_command(wordpad,     '"%e" "%f"').
  527edit_command(uedit32,     '%e "%f/%d/0"').      % ultraedit (www.ultraedit.com)
  528edit_command(jedit,       '%e -wait \'%f\' +line:%d').
  529edit_command(jedit,       '%e -wait \'%f\'').
  530edit_command(edit,        '%e %f:%d').          % PceEmacs client script
  531edit_command(edit,        '%e %f').
  532
  533edit_command(emacsclient, Command) :- edit_command(emacs, Command).
  534edit_command(vim,         Command) :- edit_command(vi,    Command).
  535edit_command(nvim,        Command) :- edit_command(vi,    Command).
  536
  537substitute(FromAtom, ToAtom, Old, New) :-
  538    atom_codes(FromAtom, From),
  539    (   atom(ToAtom)
  540    ->  atom_codes(ToAtom, To)
  541    ;   number_codes(ToAtom, To)
  542    ),
  543    append(Pre, S0, Old),
  544    append(From, Post, S0) ->
  545    append(Pre, To, S1),
  546    append(S1, Post, New),
  547    !.
  548substitute(_, _, Old, Old).
  549
  550
  551                 /*******************************
  552                 *            SELECT            *
  553                 *******************************/
  554
  555merge_locations(Locations0, Locations) :-
  556    append(Before, [L1|Rest], Locations0),
  557    select(L2, Rest, Rest1),
  558    merge_location(L1, L2, Loc),
  559    !,
  560    append([Before, [Loc], Rest1], Locations1),
  561    merge_locations(Locations1, Locations).
  562merge_locations(Locations, Locations).
  563
  564merge_location(Loc1-Spec1, Loc2-Spec2, Loc1-Spec1) :-
  565    same_file_location(Loc1,Loc2),
  566    better_spec(Spec1, Spec2).
  567merge_location(Loc1-Spec1, Loc2-Spec2, Loc-Spec) :-
  568    same_location(Loc1, Loc2, Loc),
  569    merge_specs(Spec1, Spec2, Spec).
  570
  571same_file_location(L1, L2) :-
  572    #{file:File} :< L1,
  573    #{file:File} :< L2.
  574
  575same_location(L, L, L).
  576same_location(#{file:F1}, #{file:F2}, #{file:F}) :-
  577    best_same_file(F1, F2, F).
  578same_location(#{file:F1, line:Line}, #{file:F2}, #{file:F, line:Line}) :-
  579    best_same_file(F1, F2, F).
  580same_location(#{file:F1}, #{file:F2, line:Line}, #{file:F, line:Line}) :-
  581    best_same_file(F1, F2, F).
  582
  583best_same_file(F1, F2, F) :-
  584    catch(same_file(F1, F2), _, fail),
  585    !,
  586    atom_length(F1, L1),
  587    atom_length(F2, L2),
  588    (   L1 < L2
  589    ->  F = F1
  590    ;   F = F2
  591    ).
  592
  593merge_specs(Spec, Spec, Spec) :-
  594    !.
  595merge_specs(file(F1), file(F2), file(F)) :-
  596    best_same_file(F1, F2, F),
  597    !.
  598merge_specs(Spec1, Spec2, Spec) :-
  599    merge_specs_(Spec1, Spec2, Spec),
  600    !.
  601merge_specs(Spec1, Spec2, Spec) :-
  602    merge_specs_(Spec2, Spec1, Spec),
  603    !.
  604
  605merge_specs_(FileSpec, Spec, Spec) :-
  606    is_filespec(FileSpec).
  607
  608is_filespec(file(_)) => true.
  609is_filespec(source_file(_)) => true.
  610is_filespec(Term),
  611    compound(Term),
  612    compound_name_arguments(Term, Alias, [_Arg]),
  613    user:file_search_path(Alias, _) => true.
  614is_filespec(_) =>
  615    fail.
  616
  617better_spec(class(_), module(_)).
  618better_spec(_, FileSpec) :-
  619    is_filespec(FileSpec).
 select_location(+Pairs, +UserSpec, -Location) is semidet
Arguments:
Pairs- is a list of Location-Spec pairs
Location- is a list of properties
  626do_select_location(Pairs, Spec, Location) :-
  627    select_location(Pairs, Spec, Location),                % HOOK
  628    !,
  629    Location \== [].
  630do_select_location([], Spec, _) :-
  631    !,
  632    print_message(warning, edit(not_found(Spec))),
  633    fail.
  634do_select_location([#{file:File}-file(File)], _, Location) :-
  635    !,
  636    Location = #{file:File}.
  637do_select_location([Location-_Spec], _, Location) :-
  638    existing_location(Location),
  639    !.
  640do_select_location(Pairs, _, Location) :-
  641    foldl(number_location, Pairs, NPairs, 1, End),
  642    print_message(help, edit(select(NPairs))),
  643    (   End == 1
  644    ->  fail
  645    ;   Max is End - 1,
  646        user_selection(Max, I),
  647        memberchk(I-(Location-_Spec), NPairs)
  648    ).
 existing_location(+Location) is semidet
True when Location can be edited. By default that means that the file exists. This facility is hooked to allow for alternative ways to reach the source, e.g., by lazily downloading it.
  656existing_location(Location) :-
  657    exists_location(Location),
  658    !.
  659existing_location(Location) :-
  660    #{file:File} :< Location,
  661    access_file(File, read).
  662
  663number_location(Pair, N-Pair, N, N1) :-
  664    Pair = Location-_Spec,
  665    existing_location(Location),
  666    !,
  667    N1 is N+1.
  668number_location(Pair, 0-Pair, N, N).
  669
  670user_selection(Max, I) :-
  671    user_select(Max, I),
  672    !.
  673user_selection(Max, I) :-
  674    print_message(help, edit(choose(Max))),
  675    read_number(Max, I).
 read_number(+Max, -X) is semidet
Read a number between 1 and Max. If Max < 10, use get_single_char/1.
  681read_number(Max, X) :-
  682    Max < 10,
  683    !,
  684    get_single_char(C),
  685    put_code(user_error, C),
  686    between(0'0, 0'9, C),
  687    X is C - 0'0.
  688read_number(_, X) :-
  689    read_line_to_string(user_input, String),
  690    number_string(X, String).
  691
  692
  693                 /*******************************
  694                 *             MESSAGES         *
  695                 *******************************/
  696
  697:- multifile
  698    prolog:message/3.  699
  700prolog:message(edit(Msg)) -->
  701    message(Msg).
  702
  703message(not_found(Spec)) -->
  704    [ 'Cannot find anything to edit from "~p"'-[Spec] ],
  705    (   { atom(Spec) }
  706    ->  [ nl, '    Use edit(file(~q)) to create a new file'-[Spec] ]
  707    ;   []
  708    ).
  709message(select(NPairs)) -->
  710    { \+ (member(N-_, NPairs), N > 0) },
  711    !,
  712    [ 'Found the following locations:', nl ],
  713    sequence(target, [nl], NPairs).
  714message(select(NPairs)) -->
  715    [ 'Please select item to edit:', nl ],
  716    sequence(target, [nl], NPairs).
  717message(target(Location-Spec, N)) -->
  718    ['~t~d~3| '-[N]],
  719    edit_specifier(Spec),
  720    [ '\t' ],
  721    edit_location(Location, true).
  722message(choose(_Max)) -->
  723    [ nl, 'Your choice? ', flush ].
  724message(waiting_for_editor) -->
  725    [ 'Waiting for editor ... ', flush ].
  726message(make) -->
  727    [ 'Running make to reload modified files' ].
  728message(canceled) -->
  729    [ 'Editor returned failure; skipped make/0 to reload files' ].
  730
  731target(0-(Location-Spec)) ==>
  732    [ ansi(warning, '~t*~3| ', [])],
  733    edit_specifier(Spec),
  734    [ '~t~32|' ],
  735    edit_location(Location, false),
  736    [ ansi(warning, ' (no source available)', [])].
  737target(N-(Location-Spec)) ==>
  738    [ ansi(bold, '~t~d~3| ', [N])],
  739    edit_specifier(Spec),
  740    [ '~t~32|' ],
  741    edit_location(Location, true).
  742
  743edit_specifier(Module:Name/Arity) ==>
  744    [ '~w:'-[Module],
  745      ansi(code, '~w/~w', [Name, Arity]) ].
  746edit_specifier(file(_Path)) ==>
  747    [ '<file>' ].
  748edit_specifier(source_file(_Path)) ==>
  749    [ '<loaded file>' ].
  750edit_specifier(include_file(_Path)) ==>
  751    [ '<included file>' ].
  752edit_specifier(Term) ==>
  753    [ '~p'-[Term] ].
  754
  755edit_location(Location, false) ==>
  756    { location_label(Location, Label) },
  757    [ ansi(warning, '~s', [Label]) ].
  758edit_location(Location, true) ==>
  759    { location_label(Location, Label),
  760      location_url(Location, URL)
  761    },
  762    [ url(URL, Label) ].
  763
  764location_label(Location, Label) :-
  765    #{file:File, line:Line} :< Location,
  766    !,
  767    short_filename(File, ShortFile),
  768    format(string(Label), '~w:~d', [ShortFile, Line]).
  769location_label(Location, Label) :-
  770    #{file:File} :< Location,
  771    !,
  772    short_filename(File, ShortFile),
  773    format(string(Label), '~w', [ShortFile]).
  774
  775location_url(Location, File:Line:LinePos) :-
  776    #{file:File, line:Line, linepos:LinePos} :< Location,
  777    !.
  778location_url(Location, File:Line) :-
  779    #{file:File, line:Line} :< Location,
  780    !.
  781location_url(Location, File) :-
  782    #{file:File} :< Location.
 short_filename(+Path, -Spec) is det
Spec is a way to refer to the file Path that is shorter. The path is shortened by either taking it relative to the current working directory or use one of the Prolog path aliases.
  790short_filename(Path, Spec) :-
  791    working_directory(Here, Here),
  792    atom_concat(Here, Local0, Path),
  793    !,
  794    remove_leading_slash(Local0, Spec).
  795short_filename(Path, Spec) :-
  796    findall(LenAlias, aliased_path(Path, LenAlias), Keyed),
  797    keysort(Keyed, [_-Spec|_]).
  798short_filename(Path, Path).
  799
  800aliased_path(Path, Len-Spec) :-
  801    setof(Alias, file_alias_path(Alias), Aliases),
  802    member(Alias, Aliases),
  803    Alias \== autoload,             % confusing and covered by something else
  804    Term =.. [Alias, '.'],
  805    absolute_file_name(Term, Prefix,
  806                       [ file_type(directory),
  807                         file_errors(fail),
  808                         solutions(all)
  809                       ]),
  810    atom_concat(Prefix, Local0, Path),
  811    remove_leading_slash(Local0, Local1),
  812    remove_extension(Local1, Local2),
  813    unquote_segments(Local2, Local),
  814    atom_length(Local2, Len),
  815    Spec =.. [Alias, Local].
  816
  817file_alias_path(Alias) :-
  818    user:file_search_path(Alias, _).
  819
  820remove_leading_slash(Path, Local) :-
  821    atom_concat(/, Local, Path),
  822    !.
  823remove_leading_slash(Path, Path).
  824
  825remove_extension(File0, File) :-
  826    file_name_extension(File, Ext, File0),
  827    user:prolog_file_type(Ext, source),
  828    !.
  829remove_extension(File, File).
  830
  831unquote_segments(File, Segments) :-
  832    split_string(File, "/", "/", SegmentStrings),
  833    maplist(atom_string, SegmentList, SegmentStrings),
  834    maplist(no_quote_needed, SegmentList),
  835    !,
  836    segments(SegmentList, Segments).
  837unquote_segments(File, File).
  838
  839
  840no_quote_needed(A) :-
  841    format(atom(Q), '~q', [A]),
  842    Q == A.
  843
  844segments([Segment], Segment) :-
  845    !.
  846segments(List, A/Segment) :-
  847    append(L1, [Segment], List),
  848    !,
  849    segments(L1, A).
  850
  851
  852                 /*******************************
  853                 *        LOAD EXTENSIONS       *
  854                 *******************************/
  855
  856load_extensions :-
  857    load,
  858    fail.
  859load_extensions.
  860
  861:- load_extensions.