This manual is for Sweep (version 0.27.6), an Emacs package providing an embedded SWI-Prolog runtime inside of Emacs along with an advanced SWI-Prolog development environment.
Next: Installation, Previous: Sweep: SWI-Prolog Embedded in Emacs, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Sweep is an embedding of SWI-Prolog in Emacs. It provides an interface for executing Prolog queries and consuming their results from Emacs Lisp (see Querying Prolog). Sweep further builds on top of this interface and on top of the standard Emacs facilities to provide advanced features for developing SWI-Prolog programs in Emacs.
Next: High-level Architecture, Up: Overview [Contents][Index]
Some of the main benefits that Sweep brings to working with Prolog code in Emacs are:
These features and others are documented in the rest of this manual, along with many options that Sweep provides for you to customize its behavior.
Next: Comparison with Emacs’s built-in Prolog mode, Previous: Main Features, Up: Overview [Contents][Index]
Sweep uses the C interfaces of both SWI-Prolog and Emacs Lisp to create a dynamically loaded Emacs module that contains the SWI-Prolog runtime. As such, Sweep has parts written in C, in Prolog and in Emacs Lisp.
The different parts of Sweep are structured as follows:
sweep-module
. This module is linked against the
SWI-Prolog runtime library (libswipl) and exposes a subset of
the SWI-Prolog C interface to Emacs in the form of Elisp functions
(see Querying Prolog). Notably, sweep-module
is
responsible for translating Elisp objects to Prolog terms and vice
versa.
sweep-module
to provide user-facing commands and functionality.
It is also responsible for loading sweep-module
the first time
you do something that involves interacting with Prolog.
sweep
) which is by default arranged by sweeprolog.el to
be loaded when the embedded Prolog runtime is initialized. It
contains predicates that sweeprolog.el invokes through
sweep-module
to facilitate its different commands.
Previous: High-level Architecture, Up: Overview [Contents][Index]
Emacs has a built-in mode for Prolog code, defined in the library prolog.el that comes bundled with Emacs. prolog.el aims to work with a wide variety of Prolog systems and dialects, unlike Sweep that is very tightly integrated with SWI-Prolog specifically.
If you are working with SWI-Prolog, you’ll find Sweep to be far more powerful than the built-in prolog.el. This is because Sweep leverages the Prolog parser and other analysis tools that SWI-Prolog itself uses, which give it access to highly accurate and rich information about SWI-Prolog code. If you’re using another Prolog implementation, you should stick to prolog.el as Sweep only supports SWI-Prolog.
Next: Getting Started, Previous: Overview, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Installing Sweep requires:
Sweep is available from NonGNU ELPA, to install it simply type in Emacs M-x package-install RET sweeprolog RET.
Note that in Emacs prior to version 28, you need to explicitly enable NonGNU ELPA by adding something like the following to your Emacs configuration:
(with-eval-after-load 'package (add-to-list 'package-archives '("nongnu" . "https://elpa.nongnu.org/nongnu/")))
To upgrade Sweep to a newer version, do M-x package-upgrade RET sweeprolog RET.
For straight.el users, use the following form to install Sweep:
(straight-use-package '(sweeprolog :files (:defaults "*.pl")))
Next: Discovering Sweep, Previous: Installation, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
After installing the sweeprolog
Elisp library, load it into
Emacs:
(require 'sweeprolog)
Sweep tries to find SWI-Prolog by looking for the swipl
executable in the directories listed in the Emacs variable
exec-path
. When Emacs is started from a shell, it initializes
exec-path
from the shell’s PATH
environment variable
which normally includes the location of swipl
in common
SWI-Prolog installations. If Emacs doesn’t find the swipl
executable via exec-path
, you can tell Sweep where to find it
by setting the variable sweeprolog-swipl-path
to point to it:
(setq sweeprolog-swipl-path "/path/to/swipl")
All set! You can now use Sweep for Prolog development (see Editing Prolog code) and for integrating Prolog into your Emacs Lisp code (see Querying Prolog). In the next section (see Discovering Sweep) you’ll find some useful tips for learning to work with Sweep.
Important note for Linux users: prior to version 29, Emacs
would load dynamic modules in a way that is not fully compatible with
the way the SWI-Prolog native library, libswipl, loads its own
native extensions. This may lead to Sweep failing after loading
sweep-module
(see High-level Architecture).
If you’re running Emacs 28 or earlier on Linux, you can workaround
this issue by starting Emacs with libswipl loaded upfront via
LD_PRELOAD
, for example:
LD_PRELOAD=/usr/local/lib/libswipl.so emacs
Next: Prolog Initialization and Cleanup, Previous: Getting Started, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Sweep comes with many useful commands and features for working with SWI-Prolog. This section lists suggested ways for you to get to know the provided commands and make the most out of Sweep.
The main documentation resource for Sweep is this very manual. It describes almost every command and customization option that Sweep provides. Since Sweep includes many features, describing all them makes this manual longer then you’d probably want to read upfront. Instead it’s recommended that you skim this manual to get an idea of the available features, and then return to it as a reference during your work with Sweep.
To open this manual from within Emacs, type C-h i (info
)
to open the Info reader, followed by d m sweep RET to go
to the top Info directory and select the Sweep manual. Sweep also
provides a convenient command for opening the manual:
Display the Sweep manual in Info.
To open the relevant part of the manual for a specific command that you want to learn more about, type C-h F followed by the name of that command. For example, typing C-h F sweeprolog-info-manual RET brings up this manual section in Info. If the command you’re interested in is bound to a key sequence, you can go to its Info node by typing C-h K followed by the key sequence that invokes it.
Other than the text in this manual, Sweep commands and user options
have Elisp documentation strings that describe them individually. The
various Emacs Help commands (C-h k, C-h f, C-h v,
etc.) display these documentation strings in a dedicated Help buffer
(see (emacs)Help). From the Help buffer, you can jump to the
relevant Info node typing i (help-goto-info
) to read more
about related commands and customization options.
You can also view an HTML version of this manual online at https://eshelyaron.com/sweep.html.
To learn about recent changes and new features in Sweep, check out the
NEWS file that comes with Sweep. You can open it with the command
sweeprolog-view-news
:
View the Sweep NEWS file.
Next: Querying Prolog, Previous: Discovering Sweep, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
The embedded SWI-Prolog runtime must be initialized before it can start executing queries. Normally, Sweep takes care of initializing Prolog for you the first time you use a command that requires running some Prolog code. This section elaborates about Prolog initialization and its customization options in Sweep:
List of strings used as initialization arguments for Prolog. Sweep
uses these as the args argument of sweeprolog-initialize
when it initializes Prolog on-demand.
Sweep loads and initializes Prolog on-demand at the first invocation
of a command that requires the embedded Prolog. The user option
sweeprolog-init-args
says which arguments to pass to Prolog
initialization. Its value is a list of strings that you can extend if
you want to pass specific command line flags SWI-Prolog. For example,
to limit the embedded Prolog stack to 512 MB, add the following to
your Emacs configuration:
(with-eval-after-load 'sweeprolog (push "--stack-limit=512m" sweeprolog-init-args))
Sweep initializes Prolog from Elisp by calling function
sweeprolog-initialize
.
Initialize the embedded Prolog runtime. prog should be the path
to the swipl
executable, and args should be a list of
command line arguments for swipl
. Sweep initializes Prolog
as if it was started from the command line as prog
args
.
The function sweeprolog-initialize
takes one or more string
arguments and initializes the embedded Prolog as if it were invoked
externally in a command line with the given strings as command line
arguments, where the first argument to sweeprolog-initialize
corresponds to argv[0]
. This function is implemented in C in
sweep-module
(see High-level Architecture).
The default value of sweeprolog-init-args
is set to load the
Prolog helper library sweep.pl and to create a boolean Prolog
flag called sweep
with value true
. You can check for
this flag in Prolog code to detect at runtime that you’re running
under Sweep.
It is also possible to specify initialization arguments to SWI-Prolog
by passing them as command line arguments to Emacs, which can be
convenient when using Emacs and Sweep as an alternative for the common
shell-based interaction with SWI-Prolog. This is achieved by adding
the flag --swipl-args followed by any number of arguments
intended for SWI-Prolog, with a single semicolon (;
) argument
marking the end of the SWI-Prolog arguments, after which further
arguments are processed by Emacs as usual (see (emacs)Emacs
Invocation for more information about Emacs’s command line
options), for example:
emacs --some-emacs-option --swipl-args -l foobar.pl \; --more-emacs-options
In order for Sweep to be able to handle Emacs’s command line
arguments, you must call sweeprolog-handle-command-line-args
before Emacs processes the --swipl-args argument.
Enable support for the Sweep-specific --swipl-args Emacs command line flag. This flag can be used to specify additional Prolog initialization arguments for Sweep to use when initializing Prolog on-demand, directly from Emacs’s command line invocation.
This function makes Emacs recognize the --swipl-args command
line flag by adding a dedicated handler function to
command-line-functions
(see (elisp)Command-Line
Arguments). If you want to use --swipl-args, you
should arrange for command-line-functions
to run before Emacs
processes --swipl-args. To do that, either place a call
sweeprolog-handle-command-line-args
in your Emacs
configuration, or call it from the command line right before
--swipl-args:
emacs -f sweeprolog-handle-command-line-args --swipl-args -l foobar.pl \;
You can shut down or restart the embedded Prolog runtime using the following commands:
Shut down the embedded Prolog runtime.
Restart the embedded Prolog runtime.
The command sweeprolog-shutdown
shuts down the Prolog runtime
and frees up resources Prolog allocated. You cannot shut down Prolog
with running top-levels (see The Prolog Top-level)—if you invoke
sweeprolog-shutdown
while you have running top-levels, this
command suggests killing them, and if you refuse it complains and
keeps Prolog running. The command sweeprolog-restart
is
similar to sweeprolog-shutdown
, expect it starts the embedded
Prolog runtime anew after shutting it down. When you invoke
sweeprolog-restart
with a prefix argument (C-u M-x
sweeprolog-restart RET), this command prompts for additional
initialization arguments to pass to the embedded Prolog runtime when
restarting it.
Next: Editing Prolog code, Previous: Prolog Initialization and Cleanup, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
This section describes a set of Elisp functions that let you invoke Prolog queries and interact with the embedded Prolog runtime:
Query the Prolog predicate mod:functor/2
in the
context of the module cxt. Convert input to a Prolog
term and use it as the first argument, unless reverse is
non-nil
, in which can use input as the second argument.
The other argument is called the output argument of the query,
it is expected to be unified with some output that the query wants to
return to Elisp. The output argument can be retrieved with
sweeprolog-next-solution
. This function always returns
t
when its arguments are valid, otherwise it returns
nil
.
Return the next solution of the last Prolog query. Return a cons cell
(det . output)
if the query succeeded, where
det is the symbol !
if no choice points remain and
t
otherwise, and output is the output argument of the
query converted to an Elisp S-expression. If there are no more
solutions, return nil
instead. If a Prolog exception was
thrown, return a cons cell (exception . exp)
where
exp is the exception term converted to Elisp.
Cut the last Prolog query. This releases any resources reserved for
it and makes further calls to sweeprolog-next-solution
invalid
until you open a new query.
Close the last Prolog query. Similar to sweeprolog-cut-query
expect that any unifications created by the last query are dropped.
Sweep provides the Elisp function sweeprolog-open-query
for
invoking Prolog predicates. The predicate you invoke via this
function must be of arity two, and it will be called in mode
p(+In, -Out)
—the predicate should treat the first argument as
input and expect a variable as the second argument, which it should
unify with some output. This restriction is placed in order to
facilitate a natural calling convention between Elisp, a functional
language, and Prolog, a logical one.
The sweeprolog-open-query
function takes five arguments, the
first three are strings which denote:
The fourth argument to sweeprolog-open-query
is converted into
a Prolog term and used as the first argument of the predicate
(see Conversion of Elisp objects to Prolog terms). The fifth argument is an optional
reverse flag—when this flag is set to non-nil
, the
order of the arguments is reversed such that the predicate is called
in mode p(-Out, +In)
rather than p(+In, -Out)
.
To examine th results of a Prolog query, use the function
sweeprolog-next-solution
. If the query succeeded,
sweeprolog-next-solution
returns a cons cell whose car
is either the symbol !
when the success was deterministic or
t
otherwise, and the cdr
is the current value of the
second (output) Prolog argument converted to an Elisp object
(see Conversion of Prolog terms to Elisp objects). If the query failed,
sweeprolog-next-solution
returns nil.
Sweep only executes one Prolog query at a given time, so you need to
close close queries that you open with sweeprolog-open-query
before opening new ones. When no more solutions are available for the
current query (sweeprolog-next-solution
returns nil
), or
when you’re otherwise not interested in more solutions, you must close
the query with either sweeprolog-cut-query
or
sweeprolog-close-query
. Both of these functions close the
current query, but sweeprolog-close-query
also destroys any
Prolog bindings that it created.
Sweep converts Elisp objects into Prolog terms to allow the Elisp programmers to specify arguments for Prolog predicates invocations (see Definition of sweeprolog-open-query). Seeing as some Elisp objects, like Elisp compiled functions, wouldn’t be as useful for passing to Prolog as others, Sweep only converts Elisp objects of certain types to Prolog, namely Sweep currently converts trees of strings and numbers:
[]
.
car
and the cdr
of the cons.
Next: Counting solutions for a Prolog predicate in Elisp, Previous: Conversion of Elisp objects to Prolog terms, Up: Querying Prolog [Contents][Index]
Sweep converts Prolog terms into Elisp object to allow efficient processing of Prolog query results in Elisp (see Definition of sweeprolog-next-solution).
foo
is converted to a cons cell (atom . "foo")
.
[]
is converted to the Elisp nil
object.
car
and cdr
are
the representations of the head and the tail of the list.
compound
. The second element is a string denoting the
functor name of the compound, and the rest of the elements are the
arguments of the compound in their Elisp representation.
variable
,
blob
, and
dict
.
Next: Calling Elisp function inside Prolog queries, Previous: Conversion of Prolog terms to Elisp objects, Up: Querying Prolog [Contents][Index]
Below is an example usage of the Sweep interface for calling Prolog.
It shows an invocation of the non-deterministic predicate
lists:permutation/2
directly from an function Elisp that counts
the number of different permutations of the list (1 2 3 4 5)
:
(sweeprolog-open-query "user" "lists" "permutation" '(1 2 3 4 5)) (let ((num 0) (sol (sweeprolog-next-solution))) (while sol (setq num (1+ num)) (setq sol (sweeprolog-next-solution))) (sweeprolog-close-query) num)
Previous: Counting solutions for a Prolog predicate in Elisp, Up: Querying Prolog [Contents][Index]
Sweep defines the foreign Prolog predicates sweep_funcall/2
and
sweep_funcall/3
, that you can use for calling Elisp functions
from Prolog code. You can only call these predicates in the context
of a Prolog query initiated by sweeprolog-open-query
, meaning
that they only work in the main Prolog thread (which is also Emacs’s
main thread). The first argument to these predicates is a Prolog
string holding the name of the Elisp function to call. The last
argument to these predicates is unified with the return value of the
Elisp function, represented as a Prolog term (see Conversion of Elisp objects to Prolog terms). sweep_funcall/3
converts its second argument to an
Elisp object (see Conversion of Prolog terms to Elisp objects) and passes it as a sole
argument to the Elisp function it invokes. The sweep_funcall/2
variant invokes the Elisp function without any arguments.
Next: Prolog Help, Previous: Querying Prolog, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Sweep includes a dedicated major mode for reading and editing Prolog
code—Sweep Prolog mode, or simply sweeprolog-mode
.
Enable the Sweep Prolog major mode for reading and editing SWI-Prolog code in the current buffer.
Hook run after entering Sweep Prolog mode. See (emacs)Hooks, for more information about major mode hooks in Emacs.
To activate this mode in a buffer, type M-x sweeprolog-mode
RET. To instruct Emacs to always open Prolog files in Sweep
Prolog mode, modify the Emacs variable auto-mode-alist
accordingly:
(add-to-list 'auto-mode-alist '("\\.plt?\\'" . sweeprolog-mode))
See (emacs)Choosing Modes, for more information about how Emacs chooses a major mode to use when you visit a file.
To list all of the commands available in a Sweep Prolog mode buffer,
type C-h m (describe-mode
). When Menu Bar mode is
enabled, you can run many of these commands via the Sweep menu. For
more information about Menu Bar mode, see (emacs)Menu Bars.
Next: Semantic Highlighting, Up: Editing Prolog code [Contents][Index]
Sweep Prolog mode uses a bespoke indentation engine to determine the appropriate indentation of each line of Prolog code. The indentation engine analyses the syntactic context of a given line and decides how far it should be indented based on a set of indentation rules.
Indent the current line. If the region is active, indent all the
lines within it (indent-for-tab-command
).
Indent the current line according to SWI-Prolog conventions. This
function is used as the value of indent-line-function
in Sweep
Prolog mode buffers.
Infer the indentation style of the current buffer from its contents.
Number of columns to indent nested code to in Sweep Prolog mode buffers.
The entry point of the indentation engine is the function
sweeprolog-indent-line
which takes no arguments and indents the
line at point. Sweep Prolog mode cooperates with the standard Emacs
interface for indentation by arranging for
sweeprolog-indent-line
to be called whenever a line should be
indented, notably when you press TAB
. For a full description
of the available commands and options that pertain to indentation,
See (emacs)Indentation.
The user option sweeprolog-indent-offset
specifies how many
columns Sweep keeps empty between every level of indentation. The
standard Emacs variable indent-tabs-mode
determines if
indentation can use tabs or only spaces. You may sometimes want to
adjust these options to match the indentation style used in an
existing Prolog codebase. The command
sweeprolog-infer-indent-style
can do that for you by analyzing
the contents of the current buffer and updating the buffer-local
values of sweeprolog-indent-offset
and indent-tabs-mode
accordingly. Consider adding sweeprolog-infer-indent-style
to
sweeprolog-mode-hook
to have it set up the indentation style
automatically in all Sweep Prolog mode buffers:
(add-hook 'sweeprolog-mode-hook #'sweeprolog-infer-indent-style)
Up: Indentation [Contents][Index]
Sweep Prolog mode indents lines according to the following rules:
This rule yields the following layouts:
some_functor( some_arg ). some_functor( some_arg ).
sweeprolog-indent-offset
(by default, four extra
columns).
As an example, this rule yields the following layouts when
sweeprolog-indent-offset
is set to the default value of four
columns:
some_functor(arg1, arg2) :- body_term. asserta( some_functor(arg1, arg2) :- body_term ).
This rule yields the following layouts:
head :- body1, body2, body3, body4, body5. A is 1 * 2 ^ 3 * 4 * 5. A is 1 * 2 + 3 * 4 * 5.
sweeprolog-indent-offset
.
This rule yields the following layout:
some_functor( arg1, ...
sweeprolog-indent-offset
.
This rule yields the following layout:
:- multifile predicate/3.
Next: Hover for Help, Previous: Indentation, Up: Editing Prolog code [Contents][Index]
Sweep Prolog mode highlights Prolog code through the standard Emacs
font-lock
system (see (emacs)Font Lock). Sweep Prolog
mode highlights different tokens in Prolog code according to their
semantics, determined through static analysis that Sweep performs on
demand. When you first open a buffer in Sweep Prolog mode, its entire
contents are analyzed to collect and cache cross reference data, and
Sweep highlight all of the code in the buffer accordingly. In
contrast, while you edit and move around the buffer, Sweep uses a
faster, local analysis for updating the semantic highlighting in
response to changes in the buffer.
Analyze the current buffer and update cross-references
(sweeprolog-analyze-buffer
).
Whether to analyze sweeprolog-mode
buffers on idle. Defaults
to t
.
Maximum number of characters in a Sweep Prolog mode buffer to analyze on idle. Larger buffers are not analyzed on idle. Defaults to 100,000 characters.
Minimum number of idle seconds to wait before analyzing a
sweeprolog-mode
buffer. Defaults to 1.5.
At any point in a sweeprolog-mode
buffer, you can use the
command C-c C-c (M-x sweeprolog-analyze-buffer) to update
the cross reference cache and highlight the buffer accordingly. When
Sweep’s Flymake integration is enabled, this command also updates the
diagnostics for the current buffer (see Examining Diagnostics). This may
be useful, for example, after defining a new predicate.
If the user option sweeprolog-analyze-buffer-on-idle
is set to
non-nil
(as it is by default), Sweep also updates semantic
highlighting in the buffer whenever Emacs is idle for a reasonable
amount of time, unless the buffer is larger than the value of the
sweeprolog-analyze-buffer-max-size
user option. You can
specify a minimum idle time for Sweep to wait before updating
reanalyzing the buffer highlighting is controlled by customizing the
user option sweeprolog-analyze-buffer-min-interval
.
To view and customize the various faces that Sweep defines and uses for semantic highlighting, type M-x customize-group RET sweeprolog-faces RET. See (emacs)Faces, for more information about text faces in Emacs.
Sweep comes with a custom theme called sweeprolog-pce
, that
emulates the Prolog code highlighting provided by PceEmacs, the
SWI-Prolog built-in Emacs-like editor (see
Using the
PceEmacs built-in editor in the SWI-Prolog manual). If you are
starting out with Sweep after coming from PceEmacs, enabling this
theme may soften your landing by providing a more familiar experience.
The sweeprolog-pce
theme only affects faces that Sweep itself
defines, so you can use it along other themes that you may have
enabled. To enable this theme or the current Emacs session, type
M-x load-theme RET sweeprolog-pce RET. To enable it
for future sessions, add the following to your Emacs configuration:
(load-theme 'sweeprolog-pce t)
For more information about custom themes in Emacs, See (emacs)Custom Themes.
In versions up to and including 0.20.0, Sweep used to provide a
different mechanism for emulating the highlighting of PceEmacs that
involved customizing the user option sweeprolog-faces-style
.
When that option was set to light
or dark
, Sweep would
use different sets of faces that mimic the highlighting of PceEmacs.
sweeprolog-faces-style
is now deprecated, and you should
instead use the sweeprolog-pce
theme. Still, in benefit of
users that have sweeprolog-faces-style
set and expect Sweep to
use PceEmacs highlighting, Sweep checks if
sweeprolog-faces-style
is either light
or dark
when you first open a Prolog buffer, and if so it simply enables the
sweeprolog-pce
theme to get the same effect.
Next: Quasi-quotation highlighting, Previous: PceEmacs Highlighting Emulation, Up: Semantic Highlighting [Contents][Index]
Sweep Prolog mode can highlight all occurrences of a given Prolog
variable in the clause in which it appears. By default, occurrences
of the variable at point are highlighted automatically whenever you
move the cursor into a variable. To achieve this, Sweep uses the
Emacs minor mode cursor-sensor-mode
which allows for running
hooks when the cursor enters or leaves certain text regions
(see (elisp)Special Properties in the Elisp
manual).
Highlight occurrences of a Prolog variable in the clause at point. With a prefix argument, clear variable highlighting in the clause at point instead.
Whether to use cursor-sensor-mode
to highlight occurrences of
the Prolog variable across the current clause. Defaults to t
.
To disable automatic variable highlighting based on the variable at
point, customize sweeprolog-enable-cursor-sensor
to nil.
To manually highlight occurrences of a variable in the current clause,
use the command M-x sweeprolog-highlight-variable
. This
command prompts for variable to highlight, defaulting to the variable
at point, if any. If you call it with a prefix argument (C-u M-x
sweeprolog-highlight-variable RET), it clears all variable
highlighting in the current clause instead.
Previous: Highlighting occurrences of a variable, Up: Semantic Highlighting [Contents][Index]
SWI-Prolog supports quasi-quotations, which allow you to incorporate different languages as part of your Prolog code. Sweep recognizes quasi-quotations and highlights their contents according to the Emacs mode corresponding to the quoted language.
Alist of (type . mode)
pairs, where type is a
Prolog quasi-quotation type, and mode is a symbol specifying the
major mode to use for highlighting quasi-quoted text of type
type.
The user option sweeprolog-qq-mode-alist
specifies the
association between SWI-Prolog quasi-quotation types and Emacs major
modes. By default, Sweep defines associations for HTML and JavaScript
quasi-quotation types. You can change the default choice of mode for
these highlighting languages and add associations for other languages
by customizing sweeprolog-qq-mode-alist
.
If a quasi-quotation type does not have a matching mode in
sweeprolog-qq-mode-alist
, Sweep highlights the quoted content
with the sweeprolog-qq-content
face.
For more information about quasi-quotations in SWI-Prolog, see library(quasi_quotations) in the SWI-Prolog manual.
Next: Maintaining Code Layout, Previous: Semantic Highlighting, Up: Editing Prolog code [Contents][Index]
In See Semantic Highlighting, we talked about how Sweep performs semantic analysis to determine the meaning of different terms in different contexts and highlight them accordingly. Beyond highlighting, Sweep can also tell you exactly what different tokens in Prolog code mean by annotating them with a textual description that’s displayed when you hover over them with the mouse.
Whether to annotate Prolog tokens with help text via the
help-echo
text property. Defaults to t
.
Display the help-echo
text of the token at point in the echo
area (display-local-help
).
If the user option sweeprolog-enable-help-echo
is
non-nil
, as it is by default, Sweep annotates Prolog tokens
with a short description of their meaning in that specific context.
This is done by adding the help-echo
text property to different
parts of the buffer based on semantic analysis. The help-echo
text is automatically displayed at the mouse tooltip when you hover
over different tokens in the buffer.
Alternatively, you can display the help-echo
text for the token
at point in the echo area by typing C-h . (C-h followed by
a dot).
The help-echo
description of file specification in import
directives is especially useful as it tells you which predicates that
the current buffer uses actually come from the imported file. For
example, if we have a Prolog file with the following contents:
:- use_module(library(lists)). foo(Foo, Bar) :- flatten(Bar, Baz), member(Foo, Baz).
Then hovering over library(lists)
shows:
Dependency on /usr/local/lib/swipl/library/lists.pl, resolves calls to flatten/2, member/2
Next: Term-based editing and motion commands, Previous: Hover for Help, Up: Editing Prolog code [Contents][Index]
Some Prolog constructs, such as if-then-else constructs, have a conventional layout in which each goal starts at the fourth column after the beginning of the opening parenthesis or operator. For example:
( if -> then ; else *-> elif ; true )
To help you in maintaining the desired layout without having to
manually count spaces, Sweep provides the command
sweeprolog-align-spaces
that updates the whitespace around
point such that the next token is aligned to a (multiple of) four
columns from the start of the previous token. Sweep also provides a
dedicated minor mode sweeprolog-electric-layout-mode
that
adjusts whitespace around point automatically as you type
(Electric Layout mode).
Next: Electric Layout mode, Up: Maintaining Code Layout [Contents][Index]
Insert or remove spaces around point to such that the next Prolog token starts at a column distanced from the beginning of the previous token by a multiple of four columns.
Whether to add sweeprolog-align-spaces
as the first element of
cycle-spacing-actions
in Sweep Prolog mode buffers. Defaults
to t
.
To insert or update whitespace around point, use the command M-x
sweeprolog-align-spaces
. As an example, consider a Sweep Prolog mode
buffer with the following contents, where ∗ designates the
location of the cursor:
foo :- ( if ;∗
Calling M-x sweeprolog-align-spaces
inserts three spaces, to
yield the expected layout:
foo :- ( if ; ∗
In Emacs 29, you can extend the command M-x cycle-spacing
via a
list of callback functions specified by the variable
cycle-spacing-actions
. Sweep leverages this facility and adds
sweeprolog-align-spaces
as the first action of
cycle-spacing
. To inhibit sweeprolog-mode
from doing
so, set the user option sweeprolog-enable-cycle-spacing
to nil.
Moreover, in Emacs 29 cycle-spacing
is bound by default to
M-SPC, which means that all you need to do to align
if-then-else and similar constructs is to type M-SPC after
the first token.
In Emacs prior to version 29, you can bind
sweeprolog-align-spaces
to M-SPC directly by adding
the following lines to Emacs’s initialization file (see (emacs)Init
File).
(eval-after-load 'sweeprolog '(define-key sweeprolog-mode-map (kbd "M-SPC") #'sweeprolog-align-spaces))
Previous: Inserting the Right Number of Spaces, Up: Maintaining Code Layout [Contents][Index]
The minor mode sweeprolog-electric-layout-mode
adjusts
whitespace around point automatically as you type:
Toggle automatic whitespace adjustment according to SWI-Prolog conventions.
It works by examining the context of point whenever a character is inserted in the current buffer, and applying the following layout rules:
Insert two consecutive spaces after the %!
or %%
starting a ‘PlDoc’ predicate documentation structured comment.
Insert spaces after a part of an if-then-else
constructs such that point is positioned four columns after its
beginning. The specific tokens that trigger this rule are the
opening parenthesis (
and the operators ;
, ->
and *->
, and only if
they are inserted in a callable context, where an if-then-else
construct would normally appear.
To enable this mode in a Sweep Prolog mode buffer, type M-x
sweeprolog-electric-layout-mode RET. You can automate this
step by adding sweeprolog-electric-layout-mode
to
sweeprolog-mode-hook
in your Emacs configuration:
(add-hook 'sweeprolog-mode-hook #'sweeprolog-electric-layout-mode)
Next: Holes, Previous: Maintaining Code Layout, Up: Editing Prolog code [Contents][Index]
Emacs includes many useful features for operating on syntactic units in source code buffer, such as marking, transposing and moving over expressions. By default, these features are geared towards working with Lisp expressions, or S-expressions. Sweep extends Emacs’s notion of syntactic expressions to accommodate for Prolog terms, which allows the standard S-expression based commands to operate on Prolog terms seamlessly.
The Emacs manual covers the most important commands that operate on S-expressions, and by extension on Prolog terms. See (emacs)Expressions. Another useful command for Prolog programmers is M-x kill-backward-up-list, bound by default to C-M-^ in Sweep Prolog mode buffers.
Kill the Prolog term containing the current term, leaving the current
term itself (kill-backward-up-list
).
This command replaces the parent term containing the term at point with the term itself. To illustrate the utility of this command, consider the following clause:
head :- goal1, setup_call_cleanup(setup, goal2, cleanup).
Now with point anywhere inside goal2
, calling
kill-backward-up-list
removes the setup_call_cleanup/3
term leaving goal2
to be called directly:
head :- goal1, goal2.
Next: Definitions and References, Previous: Term-based editing and motion commands, Up: Editing Prolog code [Contents][Index]
Holes are Prolog variables that some Sweep commands use as placeholder for other terms.
When writing Prolog code in the usual way of typing in one character at a time, the buffer text is often found in a syntactically incorrect state while you edit it. This happens for example right after you insert an infix operator, before typing its expected right-hand side argument. Sweep provides an alternative method for inserting Prolog terms in a way that maintains the syntactic correctness of the buffer text while allowing the user to incrementally refine it by using placeholder terms, called simply holes. Holes indicate the location of missing terms that the user can later fill in, essentially they represent source-level unknown terms and their presence satisfies the Prolog parser. Holes are written in the buffer as regular Prolog variables, but they are annotated with a special text property that allows Sweep to recognize them as holes needed to be filled.
See Inserting Terms with Holes, for a command that uses holes to let you write syntactically correct Prolog terms incrementally. Several other Sweep commands insert holes in place of unknown terms, including C-M-i (see Code Completion), C-M-m (see Context-Based Term Insertion) and M-x sweeprolog-plunit-testset-skeleton (see Writing Tests).
Next: Jumping to Holes, Up: Holes [Contents][Index]
Use the command C-c RET to add a term to the buffer at point while keeping it syntactically correct. You don’t need to give the entire term at once, only its functor and arity. Sweep automatically inserts holes for the arguments (if any), which you can incrementally fill one after the other.
Insert a Prolog term with a given functor and arity at point, using
holes for arguments (sweeprolog-insert-term-with-holes
).
The main command for inserting terms with holes is
sweeprolog-insert-term-with-holes
. This command, bound by
default to C-c C-m (or C-c RET) in Sweep Prolog mode
buffers, prompts for a functor and an arity and inserts a
corresponding term with holes in place of the term’s arguments. It
leaves point right after the first hole, sets the mark to its start
and activates the region such that the hole is marked. Call
sweeprolog-insert-term-with-holes
again to replace the active
region, which now covers the first hole, with another term, that may
again contain further holes. That way you can incrementally write a
Prolog term, including whole clauses, by working down the syntactic
structure of the term and maintaining its correctness all the while.
Without a prefix argument, sweeprolog-insert-term-with-holes
prompts for the functor and the arity to use. A non-negative prefix
argument, such as C-2 C-c C-m or C-u C-c C-m, is taken to
be the inserted term’s arity and in this case
sweeprolog-insert-term-with-holes
only prompts for the functor
to insert. A negative prefix argument, C-- C-c C-m, inserts
only a single hole without prompting for a functor. To further help
with keeping the buffer syntactically correct, this command adds a
comma (,
) before or after the inserted term when needed
according to the surrounding tokens. If you call it at the end of a
term that doesn’t have a closing fullstop, it adds the fullstop after
the inserted term.
Next: Filling Holes, Previous: Inserting Terms with Holes, Up: Holes [Contents][Index]
Use these commands to move between holes in the current Prolog buffer:
Move point to the next hole in the buffer and select it as the region.
With numeric prefix argument n, move forward over n - 1
holes and select the next one (sweeprolog-forward-hole
).
Move point to the previous hole in the buffer and select it as the
region. With numeric prefix argument n, move backward over
n - 1 holes and select the next one
(sweeprolog-backward-hole
).
Display the number of holes that are present in the buffer
(sweeprolog-count-holes
).
Toggle moving to the next hole in the buffer with TAB
if the
current line is already properly indented.
To jump to the next hole in a Sweep Prolog mode buffer, use the
command sweeprolog-forward-hole
, bound by default to C-c
TAB (or C-c C-i). This command sets up the region to
cover the next hole after point leaving the cursor at right after the
hole. To jump to the previous hole use C-c S-TAB
(sweeprolog-backward-hole
), or call
sweeprolog-forward-hole
with a negative prefix argument
(C-- C-c TAB).
You can also call sweeprolog-forward-hole
and
sweeprolog-backward-hole
with a numeric prefix argument to jump
over the specified number of holes. For example, typing C-3 C-c
TAB skips the next two holes in the buffer and selects the
third as the region. As a special case, if you call these commands
with a zero prefix argument (C-0 C-c TAB), they invoke the
command sweeprolog-count-holes
instead of jumping. This
command counts how many holes are left in the current buffer and
reports its finding via a message in the echo area.
When the minor mode sweeprolog-forward-hole-on-tab-mode
is
enabled, the TAB key is bound to a command moves to the
next hole when called in a properly indented line (otherwise it
indents the line). This makes moving between holes in the buffer
easier since you can use TAB instead of C-c
TAB in most cases. To enable this mode in a, type M-x
sweeprolog-forward-hole-on-tab-mode-map RET. You can automate
this step by adding sweeprolog-forward-hole-on-tab-mode
to
sweeprolog-mode-hook
in your Emacs configuration:
(add-hook 'sweeprolog-mode-hook #'sweeprolog-forward-hole-on-tab-mode)
Next: Highlighting Holes, Previous: Jumping to Holes, Up: Holes [Contents][Index]
Filling a hole means replacing it in the buffer with a Prolog term. The simplest way to fill a hole is how you would replace any other piece of text in Emacs—select it as the region, kill it (for example, with C-w) and insert another Prolog term in its place. For more information about the region, (emacs)Mark in the Emacs manual.
Yanking a hole with C-y (yank
) after you kill it removes
the special hole property and inserts it as a plain variable. This
can be useful if you want to keep the variable name that Sweep chose
for the hole—simply press C-w C-y with the hole marked. You
can also use the command sweeprolog-fill-holes
, which turns all
holes in the current region to plain variables.
As an alternative to manually killing the region with C-w, if
you enable Delete Selection mode (delete-selection-mode
), the
hole is automatically removed as soon as you start typing while its
marked. See (emacs)Using Region, for more information about
Delete Selection mode.
Most Sweep commands that insert holes also move to the first hole they insert and select it as the region for you to fill it. Similarly, jumping to the next hole in the buffer with C-c TAB also selects it. The command C-c RET is specifically designed for filling holes by deleting the selected hole and inserting a Prolog term at once (see Inserting Terms with Holes).
Previous: Filling Holes, Up: Holes [Contents][Index]
Sweep highlights holes in Prolog buffer by default so you can easily identify missing terms.
Whether to highlight holes in Sweep Prolog mode buffers with a
dedicated face. By default, this is set to t
.
When the user option sweeprolog-highlight-holes
is set to
non-nil
, Sweep highlights holes in Prolog buffers with a
dedicated face to make them easily distinguishable from regular Prolog
variables. Hole highlighting is enabled by default, to disable it
customize sweeprolog-highlight-holes
to nil
.
Next: Predicate Definition Boundaries, Previous: Holes, Up: Editing Prolog code [Contents][Index]
Sweep Prolog mode integrates with the Emacs xref
API to
facilitate quick access to predicate definitions and references in
Prolog code buffers. This enables the many commands that the
xref
interface provides, like M-.
(xref-find-definitions
) for jumping to the definition of the
predicate at point. See (emacs)Find Identifiers, for an overview
of the available commands.
Sweep Prolog mode also integrates with Emacs’s imenu
, which
provides a simple facility for looking up and jumping to definitions
in the current buffer. To jump to a definition in the current buffer,
type M-x imenu RET (bound by default to M-g i in
Emacs version 29 or later). For information about customizing
imenu
, (emacs)Imenu.
You can use the command sweeprolog-xref-project-source-files
to
update Sweep’s cross reference data for all Prolog source files in the
current project. To determine the set of source files in the current
project, Sweep consults the functions project-current
and
project-files
(see (emacs)Projects). When you search for
references to Prolog predicates with M-?
(xref-find-references
), Sweep implicitly invokes
sweeprolog-xref-project-source-files
to bring you up-to-date
references from across the current project.
Next: Following File Specifications, Previous: Definitions and References, Up: Editing Prolog code [Contents][Index]
The following commands act on entire Prolog predicate definitions as a single unit:
Move forward from point to the next predicate definition in the
current buffer (sweeprolog-forward-predicate
).
Move backward from point to the previous predicate definition
(sweeprolog-backward-predicate
).
Select the current predicate as the active region, put point at the
its beginning, and the mark at the end
(sweeprolog-mark-predicate
).
In Sweep Prolog mode, the commands M-n
(sweeprolog-forward-predicate
) and M-p
(sweeprolog-backward-predicate
) are available for quickly
jumping to the first line of the next or previous predicate definition
in the current buffer.
The command M-h (sweeprolog-mark-predicate
) marks the
entire predicate definition at point, along with its ‘PlDoc’
comments if there are any. As an example, you can use this command to
move an entire predicate definition typing M-h C-w and then
yanking it elsewhere with C-y.
Next: Loading Buffers, Previous: Predicate Definition Boundaries, Up: Editing Prolog code [Contents][Index]
In SWI-Prolog, one often refers to source file paths using file
specifications, special Prolog terms that act as path aliases, such
as library(lists)
which refers to a file lists.pl in any
of the Prolog library directories.
Resolve file specification at point and visit the specified file
(sweeprolog-find-file-at-point
).
Return the file name specified by the Prolog file specification at point.
You can follow file specifications that occur in Sweep Prolog mode
buffers with C-c C-o (or M-x sweeprolog-find-file-at-point
RET) whenever point is over a valid file specification. For
example, consider a Prolog file buffer with the common directive
use_module/1
:
:- use_module(library(lists)).
With point anywhere inside library(lists)
, type C-c C-o
to open the lists.pl file in the Prolog library.
Sweep also extends Emacs’s file-name-at-point-functions
hook
with the function sweeprolog-file-at-point
that returns the
resolved Prolog file specification at point, if any. Emacs uses this
hook to populate the “future history” of minibuffer prompts that
read file names, such as the one you get when you type C-x C-f
(find-file
). In particular this means that if point is in a
Prolog file specification, you can type M-n after C-x C-f
to populate the minibuffer with the corresponding file name. You can
then go ahead and visit the file by typing RET, or you can
edit the minibuffer contents and visit a nearby file instead.
For more information about file specifications in SWI-Prolog, see
absolute_file_name/3
in the SWI-Prolog manual.
Next: Setting Breakpoints, Previous: Following File Specifications, Up: Editing Prolog code [Contents][Index]
You can load a buffer of SWI-Prolog code with the following command:
Load the current buffer into the embedded SWI-Prolog runtime
(sweeprolog-load-buffer
).
Use the command sweeprolog-load-buffer
to load the contents of
a Sweep Prolog mode buffer into the embedded SWI-Prolog runtime.
After a buffer is loaded, you can query the predicates it defines from
Elisp (see Querying Prolog) and from the Sweep top-level
(see The Prolog Top-level). In Sweep Prolog mode buffers,
sweeprolog-load-buffer
is bound to C-c C-l. By default
this command loads the current buffer if its major mode is
sweeprolog-mode
, and prompts for an appropriate buffer
otherwise. To choose a different buffer to load while visiting a
sweeprolog-mode
buffer, invoke sweeprolog-load-buffer
with a prefix argument (C-u C-c C-l).
The mode line displays the word ‘Loaded’ next to the ‘Sweep’ major mode indicator if the current buffer has been loaded and hasn’t been modified since. See (emacs)Mode Line, for more information about the mode line.
More relevant information about loading code in SWI-Prolog can be found in Loading Prolog source files in the SWI-Prolog manual.
Next: Creating New Modules, Previous: Loading Buffers, Up: Editing Prolog code [Contents][Index]
You can set breakpoints in Sweep Prolog mode buffers to have SWI-Prolog break before specific goals in the code (see Breakpoints in the SWI-Prolog manual).
Set a breakpoint (sweeprolog-set-breakpoint
).
Whether to highlight breakpoints in Sweep Prolog mode buffers.
Defaults to t
.
The command sweeprolog-set-breakpoint
, bound to C-c C-b,
sets a breakpoint at the position of the cursor. If you call it with
a positive prefix argument (for example, C-u C-c C-b), it
creates a conditional breakpoint with a condition goal that you insert
in the minibuffer. If you call it with a non-positive prefix argument
(for example, C-0 C-c C-b), it deletes the breakpoint at point
instead.
When Context Menu mode is enabled, you can also create and delete
breakpoints in sweeprolog-mode
buffers through right-click
context menus (see Context Menu).
By default, Sweep highlights terms with active breakpoints in Sweep
Prolog mode buffers. To inhibit breakpoint highlighting, customize
the user option sweeprolog-highlight-breakpoints
to nil
.
Up: Setting Breakpoints [Contents][Index]
Sweep provides a breakpoint menu that lets you manage breakpoints across your codebase.
Display a list of active breakpoints.
To open the breakpoint menu, type M-x sweeprolog-list-breakpoints RET. This command opens the breakpoint menu in the *Sweep Breakpoints* buffer. The major mode of this buffer is Sweep Breakpoint Menu, which is a special mode that includes useful commands for managing Prolog breakpoints:
Go to the position of the breakpoint corresponding to the breakpoint menu entry at point.
Show the position of the breakpoint corresponding to the breakpoint
menu entry at point, in another window
(sweeprolog-breakpoint-menu-find-other-window
).
Set the condition goal for the breakpoint corresponding to the
breakpoint menu entry at point
(sweeprolog-breakpoint-menu-set-condition
).
Next: Documenting Predicates, Previous: Setting Breakpoints, Up: Editing Prolog code [Contents][Index]
Sweep integrates with the Emacs auto-insert
command to assist
you with creating of new SWI-Prolog modules. You can use
auto-insert
to populate new Prolog files with module template.
Additional content to put in the topmost comment in Prolog module headers.
The command auto-insert
in Sweep Prolog mode inserts a Prolog
module skeleton that begins with a module header multi-line
comment. By default, this header includes your name and email address
(user-full-name
and user-mail-address
respectively). If
you want the header to contain more information, you can extend it to
suite yours needs by customizing
sweeprolog-module-header-comment-skeleton
. This can be useful,
for example, for including copyright text in the header.
After the header, the module skeleton inserts a module/2
directive with the module name set to the base name of the file.
Lastly the skeleton includes a ‘PlDoc’ module comment for you to fill with the module’s documentation (see File comments in the SWI-Prolog manual).
As an example, open a new Prolog file and call it foo.pl by typing C-x C-f foo.pl RET, and insert the module skeleton with M-x auto-insert RET. The buffer contents should now be as follows:
/* Author: John Doe Email: john.doe@example.com */ :- module(foo, []). /** <module> */
To automatically insert the module skeleton whenever you open a new
Prolog file, enable the minor mode auto-insert-mode
.
See (autotype)Autoinserting in the Autotyping
manual, for detailed information about auto-insert
and its customization options.
Next: Example Usage Comments, Previous: Creating New Modules, Up: Editing Prolog code [Contents][Index]
SWI-Prolog predicates can be documented with specially structured comments placed above the predicate definition, which are processed by the ‘PlDoc’ source documentation system. Emacs comes with many useful commands specifically intended for working with comments in programming languages, which apply also to writing ‘PlDoc’ comments for Prolog predicates. For an overview of the relevant standard Emacs commands, see (emacs)Comment Commands.
Insert ‘PlDoc’ documentation comment for the predicate at or
above point (sweeprolog-document-predicate-at-point
).
Function to use for determining the initial contents of documentation
comments that you insert with
sweeprolog-document-predicate-at-point
.
Prompt and read from the minibuffer the argument modes, determinism specification and initial summary of the given predicate.
Use holes for the initial documentation of the given predicate.
Sweep also includes a dedicated command called
sweeprolog-document-predicate-at-point
for interactively
creating ‘PlDoc’ comments for predicates in
sweeprolog-mode
buffers. This command, bound by default to
C-c C-d, finds the beginning of the predicate definition under
or right above the current cursor location, and inserts a formatted
‘PlDoc’ comment. This command fills in initial argument modes,
determinism specification, and optionally a summary line for the
documented predicate. There are different ways in which
sweeprolog-document-predicate-at-point
can obtain the needed
initial documentation information, depending on the value of the user
option sweeprolog-read-predicate-documentation-function
which
specifies a function to retrieve this information. The default
function prompts you to insert the parameters one by one via the
minibuffer. Alternatively, you can use holes (see Holes) for the
predicate’s argument modes and determinism specifiers by setting this
option to sweeprolog-read-predicate-documentation-with-holes
,
as follows:
(setq sweeprolog-read-predicate-documentation-function #'sweeprolog-read-predicate-documentation-with-holes)
sweeprolog-document-predicate-at-point
leaves the cursor at the
end of the newly inserted documentation comment for you to extend or
edit it as you see fit. To add another comment line, use M-j
(default-indent-new-line
) which starts a new line with the
comment prefix filled in. Emacs has other powerful built-in features
for working with comments in code buffers that you can leverage to
edit ‘PlDoc’ comments—See (emacs)Comments, for the full
details. Furthermore you can make use of the rich support Emacs
provides for editing natural language text when working on
‘PlDoc’ comments. For example, to nicely format a paragraph of
text, use M-q (fill-paragraph
). Many useful commands for
editing text are documented in (emacs)Text, which see.
For more information about ‘PlDoc’ and source documentation in SWI-Prolog, see the PlDoc manual.
Next: Displaying Predicate Documentation, Previous: Documenting Predicates, Up: Editing Prolog code [Contents][Index]
Beyond documenting your code with ‘PlDoc’ comments as described in Documenting Predicates, you may want to have comments in your source code that demonstrate example usage of some predicate or another. Creating such comments usually involves posting queries in a Prolog top-level, copying the queries and their results into the relevant source code buffer, and formatting them as comments. Sweep provides the following command to streamline this process:
Start a new top-level for recording example usage. When you finish
interacting with the top-level its contents are formatted as a comment
in the buffer and position where you invoked this command
(sweeprolog-make-example-usage-comment
).
The command sweeprolog-make-example-usage-comment
, bound to
C-c C-% in Sweep Prolog mode buffers, creates and switches to a
new top-level buffer for recording example usage that you want to
demonstrate. The example usage top-level is a regular top-level
buffer (see The Prolog Top-level), except that it’s tied to the
specific position in the source buffer where you invoke this command.
You can post queries in the example usage top-level and edit it
freely, then type C-c C-q in to quit the top-level buffer and
format its contents as a comment in the source buffer.
You can have multiple example usage top-levels for different parts of your code at the same time. To display the source position where you created a certain usage example top-level buffer by, type C-c C-b in that buffer.
Next: Examining Diagnostics, Previous: Example Usage Comments, Up: Editing Prolog code [Contents][Index]
Sweep integrates with the Emacs minor mode ElDoc, which automatically displays documentation for the predicate at point. Whenever you move the cursor into a predicate definition or invocation, ElDoc displays the signature and summary of that predicate in the echo area at the bottom of the frame.
Whether to enable ElDoc support in sweeprolog-mode
buffers.
Defaults to t
.
To disable the ElDoc integration in Sweep Prolog mode buffers,
customize the user option sweeprolog-enable-eldoc
to
nil
.
See (emacs)Programming Language Doc, for more information about ElDoc and its customization options.
Next: Exporting Predicates, Previous: Displaying Predicate Documentation, Up: Editing Prolog code [Contents][Index]
Sweep can diagnose problems in Prolog code and report them to the user by integrating with Flymake, a powerful interface for on-the-fly diagnostics built into Emacs.
Whether to enable Flymake support in Sweep Prolog mode buffers.
Defaults to t
.
List diagnostics for the current buffer or project in a dedicated
buffer (sweeprolog-show-diagnostics
).
Flymake integration is enabled by default, to disable it customize the
user option sweeprolog-enable-flymake
to nil
.
When this integration is enabled, several Flymake commands are available for listing and jumping between found errors. see (flymake)Finding diagnostics, for a full description of these commands. Additionally, Sweep Prolog mode configures the standard command M-x next-error to operate on Flymake diagnostics. This allows for moving to the next (or previous) error location with the common M-g n (or M-g p) keybinding. See (emacs)Compilation Mode, for more information about these commands.
The command sweeprolog-show-diagnostics
shows a list of Flymake
diagnostics for the current buffer. It is bound by default to
C-c C-` in Sweep Prolog mode buffers with Flymake integration
enabled. When you call it with a prefix argument (C-u C-c C-`),
it shows a list of diagnostics for all buffers in the current project.
Next: Code Completion, Previous: Examining Diagnostics, Up: Editing Prolog code [Contents][Index]
When you define a predicate in a Prolog mode, by default it is only
visible inside that module, unless you export it by including
the predicate in the export list of the defining module (the export
list of a module is the second argument of the module/2
directive).
Add the predicate predicate at point to the export list of the current
Prolog module (sweeprolog-export-predicate
).
Sweep provides a convenient command for exporting predicates that you
define in Sweep Prolog mode buffers. To add the predicate near point
to the export list of the current module, use the command C-c
C-e (sweeprolog-export-predicate
). If the current predicate
is documented with a ‘PlDoc’ comment, this command adds a comment
with the predicate’s mode after its name in the export list. If point
is not near a predicate definition, calling
sweeprolog-export-predicate
prompts for a predicate to export
with completion for non-exported predicates in the current buffer. To
force sweeprolog-export-predicate
to prompt even when point is
on a predicate definition, invoke it with a prefix argument (C-u
C-c C-e).
Next: Context-Based Term Insertion, Previous: Exporting Predicates, Up: Editing Prolog code [Contents][Index]
In Emacs, major modes for different programming languages provide
in-buffer code completion via a standard generic command called
completion-at-point
(see (emacs)Symbol Completion). This
command is normally bound to C-M-i and M-TAB. Sweep
extends completion-at-point
with context-aware completion for
Prolog code in Prolog buffers.
When providing candidates for in-buffer completion, Sweep takes into account the code surrounding the cursor to determine what kind of completion makes most sense:
If the text before point can be completed to one or more variable
names that appear elsewhere in the current clause,
completion-at-point
suggests matching variable names as
completion candidates.
If point is at a callable position, completion-at-point
suggests matching predicate calls. If the predicate you choose takes
arguments, Sweep inserts holes in their places, and moves point to the
first argument (see Holes).
If point is inside a predicate options list,
completion-at-point
suggests matching options or option values
for the appropriate predicate.
If point is at a position where a source file specification should
appear (such as the argument of use_module/1
),
completion-at-point
suggests matching source file
specifications.
If point is inside an arithmetic expression,
completion-at-point
suggests matching arithmetic functions.
If point is at a position where a Prolog flag should appear (such as
the first argument of set_prolog_flag/2
),
completion-at-point
suggests matching flags.
If point is at a non-callable position, completion-at-point
suggests matching atoms and functors.
Next: Writing Tests, Previous: Code Completion, Up: Editing Prolog code [Contents][Index]
As a means of automating common Prolog code editing tasks, such as
adding new clauses to an existing predicate, Sweep Prolog mode
provides the “do what I mean” command
sweeprolog-insert-term-dwim
, bound by default to C-M-m
(or equivalently, M-RET). This command inserts a new term in
the current buffer according to the context in which you invoke it.
Insert an appropriate Prolog term in the current buffer, based on the
current context (sweeprolog-insert-term-dwim
).
List of functions for sweeprolog-insert-term-dwim
to try for
inserting a Prolog term based on the current context.
To determine which term to insert and exactly where, the command
sweeprolog-insert-term-dwim
calls the functions in the list
sweeprolog-insert-term-functions
one after the other until one
of them succeeds. The functions on this list are called term
insertion functions, each insertion function takes two
arguments—the position where you invoke
sweeprolog-insert-term-dwim
and the prefix argument you give
it, if any—and returns non-nil
after performing its specific
insertion if it is applicable in the current context.
By default, sweeprolog-insert-term-functions
contains the
following insertion functions:
If the region is active and selects a goal, extract the selected goal into a separate predicate. With a prefix argument, also suggest replacing other goals in the buffer that the selected goal subsumes with invocations of the new predicate that this function creates. See Extracting Goals to Separate Predicates.
If the last token before point is a fullstop ending a predicate clause, insert a new clause below it.
If point is over a call to an undefined predicate, insert a definition
for that predicate. By default, the new predicate definition is
inserted right below the last clause of the current predicate
definition. You can customize the user option
sweeprolog-new-predicate-location-function
to control where in
the buffer this function inserts new predicate definitions.
This command inserts holes as placeholders for the body term and the head’s arguments, if any. See Holes.
Next: Managing Dependencies, Previous: Context-Based Term Insertion, Up: Editing Prolog code [Contents][Index]
SWI-Prolog includes the ‘PlUnit’ unit testing
framework1, in which you write unit
tests in special blocks of Prolog code enclosed within the directives
begin_tests/1
and end_tests/1
. To insert a new block of
unit tests (also known as a test-set) in a Prolog buffer, use
the command M-x sweeprolog-plunit-testset-skeleton RET.
Insert a ‘PlUnit’ test-set skeleton at point.
This command prompts for a name to give the new test-set and inserts a template such as the following:
:- begin_tests(foo_regression_tests). test() :- TestBody. :- end_tests(foo_regression_tests).
The cursor is left between the parentheses of the test()
head
term, and the TestBody
variable is marked as a hole
(see Holes). To insert another unit test, place point after a
complete test case and type C-M-m (or M-RET) to invoke
sweeprolog-insert-term-dwim
(see Context-Based Term Insertion).
Next: Term Search, Previous: Writing Tests, Up: Editing Prolog code [Contents][Index]
It is considered good practice to explicitly list the dependencies of
your SWI-Prolog source files on predicates defined in other files by
using autoload/2
and use_module/2
directives, rather
than relying on implicit autoloads. To find all implicitly autoloaded
predicates in the current sweeprolog-mode
buffer and make the
dependencies on them explicit, use the command
sweeprolog-update-dependencies
bound to C-c C-u.
Add explicit dependencies for implicitly autoloaded predicates in the
current buffer (sweeprolog-update-dependencies
).
Determines which Prolog directive to use in
sweeprolog-update-dependencies
when adding new directives. The
value of this user option is one of the symbols use-module
,
autoload
or infer
. If it is use-module
,
sweeprolog-update-dependencies
adds use_module/2
directives, a value of autoload
means to add autoload/2
directives, and infer
says to infer which directive to use
based on the existing dependency directives in the buffer, if any.
Defaults to infer
.
Whether Flymake should complain about implicitly autoloaded predicates in Sweep Prolog mode buffers.
The command sweeprolog-update-dependencies
, bound to C-c
C-u, analyzes the current buffer and adds or updates
autoload/2
and use_module/2
directives as needed.
When this command adds a new directive, rather than updating an
existing one, it can use either autoload/2
or
use_module/2
to declare the new dependency based on the value
of the user option sweeprolog-dependency-directive
. If you set
this option is to use-module
, new dependencies use the
use_module/2
directive. If it’s autoload
, new
dependencies use autoload/2
. If it’s infer
, as it is by
default, new dependencies use autoload/2
unless the buffer
already contains dependency directives and they are all
use_module/2
directives, in which case they also use
use_module/2
.
By default, when Flymake integration is enabled (see Examining Diagnostics), Sweep highlights calls to implicitly autoloaded predicates
and reports them as Flymake diagnostics. To inhibit Flymake from
diagnosing implicit autoloads, customize the user option
sweeprolog-note-implicit-autoloads
to nil
.
Next: Query Replace Term, Previous: Managing Dependencies, Up: Editing Prolog code [Contents][Index]
You can search for Prolog terms matching a given search term with the
command sweeprolog-term-search
.
Search for Prolog terms matching a given search term in the current
buffer (sweeprolog-term-search
).
The command sweeprolog-term-search
, bound by default to
C-c C-s in Sweep Prolog mode buffers, prompts for a Prolog term
to search for and finds terms in the current buffer that the search
term subsumes. It highlights all matching terms in the buffer and
moves the cursor to the end of the next match after point. For
example, to find if-then-else constructs in the current buffer do
C-c C-s _ -> _ ; _ RET.
This command highlights the current match with the
sweeprolog-term-search-current
face, and all other matches with
the sweeprolog-term-search-match
face. See (emacs)Face
Customization for information about customizing faces.
While prompting for a search term in the minibuffer, this command populates the “future history” with the Prolog terms at point, with the most nested term at point on top. Typing M-n once in the minibuffer fills in the innermost term at point, typing M-n again cycles up the syntax tree at point filling the minibuffer with larger terms, up until the top-term at point. See (emacs)Minibuffer History, for more information about minibuffer history commands.
If you invoke sweeprolog-term-search
with a prefix argument
(C-u C-c C-s), you can further refine the search with an
arbitrary Prolog goal. The given goal runs for each matching term,
and if the goal fails sweeprolog-term-search
disregards the
corresponding match. You can use variables from the search term in
the goal to refer to the corresponding subterms of the matching
term—for example, you can find all places in your code where you
have a call to sub_string/5
with either the first or the last
argument being a literal atom by typing C-u C-c C-s
sub_string(Str, _, _, _, Sub) RET atom(Str) ; atom(Sub)
RET.
If you call this command with a double prefix argument (C-u C-u C-c C-s), it also prompts you to specify the class of term to search for. This can be one of the following symbols:
clause
Matches whole clauses.
head
Matches head terms.
goal
Matches goal terms.
data
Matches data terms.
_
Matches any term.
You can specify multiple classes in the minibuffer by delimiting them
with ‘,’, in which case sweeprolog-term-search
matches
terms that match any of the these classes.
If you call sweeprolog-term-search
with a negative prefix
argument (C-- C-c C-s), it searches backward and moves to
beginning of the first match that starts before point.
After invoking sweeprolog-term-search
, use C-s to move to
the next matching term and C-r to move backward to the previous
match. To exit term search, type C-m (or RET).
Similarly to Isearch, sweeprolog-term-search
sets the mark to
the original point so you can easily return to where you were before
beginning the search. See (emacs)Basic Isearch.
Next: Context Menu, Previous: Term Search, Up: Editing Prolog code [Contents][Index]
Sweep includes a powerful search and replace mechanism called
Term Replace, that allows you to quickly and consistently
transform some terms across a Prolog buffer. Term Replace searches
for terms with the same flexibility and precision of Term Search
(see Term Search), while letting you interactively transform and
replace matching terms in place. You can use Term Replace to refactor
your code in many ways, such as extending a predicate with another
argument, or replacing all calls to a predicate with another one while
transposing some of the arguments. If you’re familiar with Emacs’s
Query Replace commands, you can think of Term Replace as a
Prolog-specific superpowered version of query-replace-regexp
(see (emacs)Query Replace). To initiate Term Replace, use the
following command:
Replace some terms after point matching a given template with a given
replacement (sweeprolog-query-replace-term
).
The command sweeprolog-query-replace-term
(bound to C-c
C-S) prompts for two Prolog terms, the template term and the
replacement term, and then asks for each term in the buffer that
matches the template if you want to replace it. You can use variables
in the template term to capture sub-terms of the matching term, and
use them in the replacement term. For example, if you want to
transpose the two arguments in a bunch of calls to =/2
, you can
specify R=L
as the template term and L=R
as the
replacement.
This command uses the same underlying term search as C-c C-s
(sweeprolog-term-search
) does for finding matches, expect that
sweeprolog-query-replace-term
only searches from point to the
end of buffer. If you invoke sweeprolog-query-replace-term
with an active region, it limits the operation to matching terms in
the region. sweeprolog-query-replace-term
highlights the
current match with the sweeprolog-query-replace-term-current
face, and all other matches with the
sweeprolog-query-replace-term-match
face. By default, these
faces inherit from sweeprolog-term-search-current
and
sweeprolog-term-search-match
, respectively. Furthermore,
similarly to C-c C-s, you can invoke
sweeprolog-query-replace-term
with a prefix argument to refine
the search with an arbitrary Prolog goal that matching terms must
satisfy, or with two prefix arguments to target only terms in certain
contexts. See Term Search for full details about prefix arguments
and search refinement.
sweeprolog-query-replace-term
goes over the matching terms in
turn and asks you what to do with each. The available answers are:
Replace the current match and move to the next one.
Skip the current match without replacing it.
Replace the current match, show the result, and suggest reverting back before moving to the next match.
Quit without replacing the current match.
Replace the current match, and exit right away asking about further matches.
Replace the current match and all remaining matches without asking.
Edit the replacement term for the current match in the minibuffer, and then perform the replacement.
Enter recursive edit. This allows you to pause the current Term Replace session, perform some edits, or otherwise use Emacs however you please, an then resume Term Replace from the same point by typing C-M-c. See (emacs)Recursive Edit.
If you include a new variable in the replacement term
that does not appear in the template term,
sweeprolog-query-replace-term
uses that variable as-is in each
replacement, expect if the matching term happens to contain a variable
with that name already, in which case this command adds the suffix
‘Fresh’ to the name of the new variable from the replacement.
Including a new variable in the replacement term is useful, for
example, for introducing a new argument to a predicate.
Next: Renaming Variables, Previous: Query Replace Term, Up: Editing Prolog code [Contents][Index]
In addition to the keybindings that Sweep provides for invoking its commands, it integrates with Emacs’s standard Context Menu minor mode to provide contextual menus that you interact with using the mouse.
Toggle Context Menu mode. When enabled, clicking the mouse button
down-mouse-3
(meaning “right-click”) activates a menu whose
contents depend on its surrounding context.
List of functions that create Context Menu entries for Prolog tokens. Each function should receive as its arguments the menu that is being created, the Prolog token’s description, its start position, its end position, and the position of the mouse click. It should alter the menu according to that context.
To enable Context Menu mode, type M-x context-menu-mode
RET. To have Context Menu mode enabled automatically when
Emacs starts, place a call to (context-menu-mode)
in your Emacs
initialization file. You can access the context menu by
right-clicking anywhere in Emacs. If you do it in a Sweep Prolog mode
buffer, you can invoke several Prolog-specific commands based on where
you click in the buffer.
If you right-click on a Prolog file specification or module name, Sweep suggests visiting it either in the current window or in another. If you right-click on a predicate, it lets you view its documentation in a dedicated buffer (see Prolog Help). For variables, it enables the ‘Rename Variable’ menu entry that you can use to rename the variable you click on across its containing clause (see Renaming Variables).
You can further extend and customize the context menu that Sweep
Prolog mode provides by adding functions to the variable
sweeprolog-context-menu-functions
. Each function on this list
receives the menu that is being created and a description of the
clicked Prolog token, and it can extend the menu with entries before
Emacs displays the menu.
Next: Numbered Variables, Previous: Context Menu, Up: Editing Prolog code [Contents][Index]
You can rename a Prolog variable across the current top-term with the following command:
Rename a variable across the topmost Prolog term at point
(sweeprolog-rename-variable
).
If non-nil
, allow selecting an existing variable name as the
new name of a variable being renamed with
sweeprolog-rename-variable
. If it is the symbol
confirm
, allow but ask for confirmation first. Defaults to
confirm
.
The command sweeprolog-rename-variable
, bound to C-c C-r,
prompts for two variable names and replaces all occurrences of the
first variable in the term at point with the second. The prompt for
the first (old) variable name provides completion based on the
existing variable names in the current term, and it uses the variable
at point as its default.
The user option sweeprolog-rename-variable-allow-existing
controls what happens if the second (new) variable name that you
insert in the minibuffer already occurs in the current clause. By
default it is set to confirm
, which says to ask for
confirmation before selecting an existing variable name as the new
name. This is because renaming a variable to another existing
variable name potentially alters the semantics of the term by merging
the two variables. Other alternatives for this user option are
t
for allowing such merges without confirmation, and nil
for refusing them altogether.
If Context Menu mode is enabled, you can also rename variables by right-clicking on them with the mouse and selecting ‘Rename Variable’ from the top of the context menu. See Context Menu, for more information about context menus in Sweep.
Next: Macro Expansion, Previous: Renaming Variables, Up: Editing Prolog code [Contents][Index]
A widespread convention in Prolog is using a common prefix with a
numeric suffix to name related variables, such as Foo0
,
Foo1
, etc. Sweep provides convenient commands for managing
such numbered variable sequences consistently:
Prompt for a numbered variable and increment it and all numbered
variables with the same base name and a greater number in the current
clause (sweeprolog-increment-numbered-variables
).
Prompt for a numbered variable and decrement it and all numbered
variables with the same base name and a greater number in the current
clause (sweeprolog-decrement-numbered-variables
).
Numbering variables is often used to convey the order in which they are bound. For example:
%! process(+State0, -State) is det. process(State0, State) :- foo(State0, State1), bar(State2, State1), baz(State2, State).
Here State0
and State
are respectively the input and
output arguments of process/2
, and State1
and
State2
represent intermediary stages between them.
The command C-c C-+
(sweeprolog-increment-numbered-variables
) prompts you for a
numbered variable in the current clause, and increments the number of
that variable along with all other numbered variables with the same
base name and a greater number. You can use it to “make room” for
another intermediary variable between two sequentially numbered
variables. If you call this command with point on a numeric variable,
it suggests that variable as the default choice. If you call this
command with a prefix argument, it increments by the numeric value of
the prefix argument, otherwise it increments by one.
For instance, typing C-c C-+ State1 RET with point anywhere in
the definition of process/2
from the above example results in
the following code:
process(State0, State) :- foo(State0, State2), bar(State3, State2), baz(State3, State).
Note how sweeprolog-increment-numbered-variables
replaced all
occurrences of State1
with State2
, while the original
occurrences of State2
are replaced with State3
. The
overall semantics of the clause doesn’t change, but you can now
replace the call to foo/2
with two goals and reintroduce
State1
as an intermediary result between them while keeping
your numbering consistent, e.g.:
process(State0, State) :- one(State0, State1), two(State1, State2), bar(State3, State2), baz(State3, State).
If Context Menu mode is enabled, you can also invoke
sweeprolog-increment-numbered-variables
by right-clicking on a
numbered variables and selecting ‘Increment Variable Numbers’
from the context menu. See Context Menu.
The command C-c C--
(sweeprolog-decrement-numbered-variables
) is similar to
C-c C-+ except it decrements all numbered variables starting
with a given numbered variable rather than incrementing them. When
you delete an intermediary numbered variable and end with a gap in the
variable numbering sequence, you can use this command to close the gap
by decrementing the following numbered variables.
After invoking either C-c C-- or C-c C-+, you can continue
to decrement or increment the same set of numbered variables by
repeating with -
and +
.
Next: Extracting Goals to Separate Predicates, Previous: Numbered Variables, Up: Editing Prolog code [Contents][Index]
Recent versions of SWI-Prolog include a pre-processing mechanism
called Prolog macros, implemented in library(macros)
. It
provides a convenient way for computing terms at compile time and
using them in code.
Macros are defined using special rules with #define(Macro, Replacement)
head terms. Then, when SWI-Prolog reads a term of the form #(Macro)
during compilation, it invokes the macro replacement rule and uses the
expanded term instead.
Sweep can replace macro invocations with their expansions. To expand a macro in your source code, use the following command:
Replace the Prolog macro invocation starting at point with its expansion.
You can call this command with point on the #
macro indicator
to expand the macro inline. To undo the expansion, use C-/
(undo
).
With Context Menu mode enabled, you can also expand macros by
right-clicking on the #
and selecting ‘Expand Macro’ from
the context menu. See Context Menu.
Previous: Macro Expansion, Up: Editing Prolog code [Contents][Index]
Sweep can help you extract a part of the body of a Prolog clause into a separate predicate, so you can reuse it in other places.
Extract the goal between point and mark into a new predicate.
This command extracts the selected goal into a separate predicate. It prompts you for the name of the new predicate and inserts a definition for that predicate in the current buffer, while replacing the current region with a call to this new predicate. The body of the new predicate is the goal in the current region, and this command determines the arguments of the new predicate based on the variables that the goal to extract shares with the containing clause.
If the selected goal contains a cut whose scope would change as a
result of being extracted from the current clause,
sweeprolog-extract-region-to-predicate
warns you about it and
asks you to confirm before continuing. If your code already includes
a definition for the predicate that
sweeprolog-extract-region-to-predicate
would define, this
command similarly warns you and asks for confirmation.
If you call sweeprolog-extract-region-to-predicate
when the
region does not contain a valid Prolog term, this command complains
and refuses to extract the invalid term.
By default, sweeprolog-extract-region-to-predicate
is not bound
directly to any key in Sweep Prolog mode; instead, you can invoke it
by typing M-RET (sweeprolog-insert-term-dwim
) when
the region is active. See Context-Based Term Insertion.
If you invoke sweeprolog-extract-region-to-predicate
with a
prefix argument—either directly or via
sweeprolog-insert-term-dwim
by typing C-u M-RET
with an active region—then after extracting the selected goal to a
new predicate, this command searches the current buffer for other
goals that the selected goal subsumes, and suggests replacing them
with invocations of the newly defined predicate. See Query Replace Term.
With Context Menu mode enabled, you can also invoke this command by right-clicking on an active region and selecting ‘Extract to New Predicate’.
Next: The Prolog Top-level, Previous: Editing Prolog code, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Sweep provides a way to read SWI-Prolog documentation via the standard
Emacs help
user interface, akin to Emacs’s built-in
describe-function
(C-h f) and describe-variable
(C-h v). For more information about Emacs help
and its
special major mode, help-mode
, (emacs)Help Mode.
Prompt for a Prolog module and display its full documentation in a help buffer.
Prompt for a Prolog predicate and display its full documentation in a help buffer.
The command sweeprolog-describe-module
prompts for the name of
a Prolog module and displays its documentation in the *Help*
buffer. To jump to the source code from the documentation, press
s (help-view-source
).
Similarly, you can use M-x sweeprolog-describe-predicate RET to display the documentation of a Prolog predicate. This commands prompts for a predicate with completion. When the cursor is over a predicate definition or invocation in a Sweep Prolog mode, that predicate is set as the default selection and can be described by simply typing RET in response to the prompt.
Next: Executing Prolog Asynchronously, Previous: Prolog Help, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Sweep provides a classic Prolog top-level interface for interacting with the embedded Prolog runtime. To start the top-level, use M-x sweeprolog-top-level RET. This command opens a buffer with an interactive Prolog top-level.
Run an interactive Prolog top-level in a buffer.
sweeprolog-top-level
creates a buffer named
*sweeprolog-top-level*, and connects it to a Prolog top-level.
If the *sweeprolog-top-level* buffer already exists, this
command simply displays the existing buffer. See Multiple Top-levels to learn about using multiple top-level buffers at the
same time.
The top-level buffer uses the Sweep Top-level major mode
(sweeprolog-top-level-mode
). This mode derives from
comint-mode
, which is the common mode used in Emacs
REPL (Read Evaluate Print Loop) interfaces. As a result, the
top-level buffer inherits the features present in other
comint-mode
derivatives, most of which are described in
(emacs)Shell Mode.
Top-level buffers are backed by Prolog threads that run in the same
process as Emacs and the main Prolog runtime. On Unix systems,
top-levels communicate with their corresponding threads via a
pseudo-terminal device (pty). Alternatively, Sweep top-level
buffers can communicate with their threads via a local TCP connection.
You can force Sweep to use TCP instead of a pty on Unix systems by
customizing the user option sweeprolog-top-level-use-pty
to
nil
.
Whether to use pty for top-level communication. If this is
non-nil
, Sweep top-level buffers communicate with their
top-level threads via a pty, otherwise they use a local TCP
connection.
sweeprolog-top-level-use-pty
is on by default on systems where
Emacs can use a pty. On other systems, such as MS Windows, or when
otherwise sweeprolog-top-level-use-pty
is set to nil
,
Sweep creates a TCP server socket bound to a random port to accept
incoming connections from top-level buffers. Sweep only starts this
TCP server socket when you first invoke of
sweeprolog-top-level
, so there are no listening sockets before
you actually use the top-level. The TCP server only accepts
connections from the local machine, but note that other users on the
same host might be able to connect to the TCP server socket and get a
Prolog top-level. This may be a security concern if you are sharing a
host with untrusted users, so you should be careful about using
sweeprolog-top-level
with sweeprolog-top-level-use-pty
set to nil
on shared machines.
When Emacs connects to a top-level via a pty, the top-level uses
ANSI escape sequences to add colored output and other features.
Emacs interprets these escape sequences by default and turns them into
text properties for the top-level output. If you want Emacs to filter
out ANSI escape sequences and disable output coloring, set the user
option ansi-color-for-comint-mode
to the symbol filter
.
Next: Multiple Top-levels, Up: The Prolog Top-level [Contents][Index]
When you start a new top-level, it prompts you to enter a Prolog query
by displaying the query prompt, which is usually ‘?- ’.
You post your query by typing it at the prompt, and pressing
RET (comint-send-input
) to send it. If the query
succeeds with a choicepoint, the top-level lets you to perform one of
several actions by typing a single character, such as ; to get
the next answer. Sweep Top-level mode detects that the top-level
expects a single character input, and sends the character you type to
the top-level immediately. After the top-level is done with answering
your query, it prompts you again to post a new one.
The Sweep top-level provides input completion at the query prompt, which works similarly to the in-buffer completion you get in Sweep Prolog mode buffers (see Code Completion). Namely, to complete a partial predicate name or other input in the top-level prompt, type C-M-i (or M-TAB).
Next: The Top-level Menu buffer, Previous: Interacting with the Top-level, Up: The Prolog Top-level [Contents][Index]
You can create and use any number of top-levels at the same time, each
top-level with its own buffer. If a top-level buffer already exists,
sweeprolog-top-level
simply opens it by default. To create
another one or more top-level buffers, run sweeprolog-top-level
with a prefix argument (C-u M-x sweeprolog-top-level RET)
to choose a different buffer name. Alternatively, run the command
C-x x u (rename-uniquely
) in the buffer called
*sweeprolog-top-level* and then do M-x
sweeprolog-top-level RET again. This changes the name of the
original top-level buffer to something like
*sweeprolog-top-level*<2> and allows the new top-level to claim
the buffer name *sweeprolog-top-level*.
Next: Sending signals to running top-levels, Previous: Multiple Top-levels, Up: The Prolog Top-level [Contents][Index]
Sweep provides a convenient interface for listing the active Prolog top-levels and operating on them, called the Top-level Menu buffer. This buffer shows the list of active Sweep top-level buffers in a table that includes information and statistics for each top-level.
Display a list of running Prolog top-levels.
To open the Top-level Menu buffer, use the command M-x sweeprolog-list-top-levels RET. By default, the buffer is called *Sweep Top-levels*.
The Top-level Menu buffer uses a special major mode named
sweeprolog-top-level-menu-mode
. This mode provides several
commands that operate on the top-level corresponding to the table row
at point. The available commands are:
Open the specified top-level buffer (sweeprolog-top-level-menu-go-to
).
Kill the specified top-level buffer
(sweeprolog-top-level-menu-kill
).
Signal the specified top-level buffer
(sweeprolog-top-level-menu-signal
). See Sending signals to running top-levels.
Create a new top-level buffer (sweeprolog-top-level-menu-new
).
Update the Top-level Menu contents (revert-buffer
).
Next: Top-level History, Previous: The Top-level Menu buffer, Up: The Prolog Top-level [Contents][Index]
When executing long running Prolog queries in the top-level, there may
arise a need to interrupt the query, either to inspect the state of
the top-level or to free it for running other queries. To signal a
Sweep top-level that it should stop executing the current query and do
something else instead, use the command
sweeprolog-top-level-signal
.
Prompt for a Prolog goal and signal a top-level buffer to execute it.
This command prompts for an active Sweep top-level buffer followed by a Prolog goal, and interrupts the top-level causing it to run the specified goal.
Interrupt the current Prolog top-level.
In a top-level buffer, you can use the command
sweeprolog-top-level-signal-current
to signal the current
top-level. It is bound by default to C-c C-c. This command
uses the value of the user option
sweeprolog-top-level-signal-default-goal
as the goal to signal,
this is set by default to a goal that interrupts the top-level thread
returns control of the top-level to the user. If you call
sweeprolog-top-level-signal-current
with a prefix argument
(C-u C-c C-c), it prompts for the goal to signal.
You can also signal top-levels from the Sweep Top-level Menu buffer
with the command sweeprolog-top-level-menu-signal
with point at
the entry corresponding to the wanted top-level (see The Top-level Menu buffer).
For more information about interrupting threads in SWI-Prolog, see Signaling threads in the SWI-Prolog manual.
Next: Following Error Messages, Previous: Sending signals to running top-levels, Up: The Prolog Top-level [Contents][Index]
Sweep top-level buffers provide a history of previous user inputs,
similarly to other comint-mode
derivatives such as
shell-mode
. To insert the last input from the history at the
prompt, use M-p (comint-previous-input
). See (emacs)Shell
History, for a full description of history related commands.
Minimum input length to record in the history of Sweep top-levels.
How to persist input history for top-levels across Emacs sessions.
The Sweep top-level history only records inputs whose length is at
least sweeprolog-top-level-min-history-length
characters. This
user option is set to 3 by default, and should generally be set to at
least 2 to keep the history from being clobbered with single-character
inputs, which are common in the top-level interaction, for example
;
as used to invoke backtracking.
Sweep can optionally persist top-level input history. The user option
sweeprolog-top-level-persistent-history
controls if and where
top-levels store their persistent history: when this option is
non-nil
, Sweep top-level buffers that you create read their
input history from a persistent history file, and write their history
back to it when you delete them. If this option is a string, it is
treated as a file name, and top-level buffers use that file to
persistent their input history. If it’s a function, it is called with
no arguments and should return either a file name for the persistent
history, or nil
to disable persistent history for that
top-level buffer. The file name that this user option specifies can
be either absolute or relative, in which case it is expanded relative
to the default directory of the top-level buffer (see (emacs)File
Names). This option can also be a list of the form
(project rel def)
, in which case the persistent
history file that a top-level buffer uses depends on the current
project of the of that buffer (see (emacs)Projects). If there
is no current project, the top-level persistent history file is
def. Otherwise, the history file is rel relative to the
project’s root directory. You can leave def nil
or omit
it entirely to disable persistent history for top-levels that are not
associated with any project. By default, this option is set to
nil
which says not to keep persistent top-level history.
Next: Sending Goals to the Top-level, Previous: Top-level History, Up: The Prolog Top-level [Contents][Index]
Many standard SWI-Prolog facilities generate messages that refer to
specific source code locations. For example, loading a Prolog file
that contains singleton variables into the top-level produces warning
messages pointing to the starting line of the clauses where the
singleton variables occur. If you enable
compilation-shell-minor-mode
in the top-level buffer, Emacs
recognizes the Prolog messages that refer to source locations and
provides convenient commands for visiting such source locations from
the top-level buffer. See (emacs)Compilation Mode, For more
information about compilation-shell-minor-mode
.
To use compilation-shell-minor-mode
automatically in all
top-level buffers, you can arrange for the
sweeprolog-top-level-mode
hook to enable it as follows:
(add-hook 'sweeprolog-top-level-mode-hook #'compilation-shell-minor-mode)
Previous: Following Error Messages, Up: The Prolog Top-level [Contents][Index]
You can send a goal to execute in a Prolog top-level from any buffer with the command M-x sweeprolog-top-level-send-goal RET.
Execute a Prolog goal in a top-level buffer and display that buffer
(sweeprolog-top-level-send-goal
).
This command prompts for a Prolog goal in the minibuffer, executes it in a top-level buffer and displays that buffer if it’s not already visible. While inserting the goal in the minibuffer, you can use TAB (or C-i) to get completion suggestions.
In Sweep Prolog mode buffers, you can invoke
sweeprolog-top-level-send-goal
by typing C-c C-q. It
also uses the goal at point (if any) as the “future history” for the
goal prompt, which you can access with M-n in the minibuffer.
Next: Finding Prolog Code, Previous: The Prolog Top-level, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Sweep provides a facility for executing Prolog goals in separate threads and capturing their output in Emacs buffers as it is produced. You can use this for running queries without blocking Emacs.
Execute a Prolog goal asynchronously and display its output in a
dedicated buffer (sweeprolog-async-goal
).
The command sweeprolog-async-goal
, bound to C-c C-& in
Sweep Prolog mode buffers, prompts for a Prolog goal and executes it
in a new Prolog thread, redirecting its output and error streams to an
Emacs buffer that gets updated asynchronously.
This is similar in nature to running asynchronous shell commands with
the standard M-& (async-shell-command
) or M-x
compile commands, expect that sweeprolog-async-goal
runs a
Prolog goal instead of a shell command. For more information about
the aforementioned commands, see (emacs)Single Shell and
(emacs)Compilation.
The output buffer that sweeprolog-async-goal
creates uses a
dedicated mode called Sweep Async Output mode. This mode is
derived from the standard Compilation mode, and it provides all of the
usual commands documented in (emacs)Compilation Mode.
Notably, you can run the same query again by typing g
(sweeprolog-async-goal-restart
) in the output buffer. To
interrupt the goal running in the current output buffer, press
C-c C-k (kill-compilation
).
Compatibility note: asynchronous queries use pipe processes that require Emacs 28 or later and SWI-Prolog 9.1.4 or later.
Next: Quick Access to Sweep Commands, Previous: Executing Prolog Asynchronously, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
The following commands let you jump to a piece of Prolog code from anywhere in Emacs:
Prompt for a known Prolog module and find its source code.
Prompt for a known Prolog predicate and find its source code.
sweeprolog-find-module
and sweeprolog-find-predicate
prompt you for a Prolog identifier (respectively, a module name or a
predicate indicator), and jump to its source definition. Sweep
integrates with Emacs’s standard completion API to annotate candidate
modules in the completion UI with a summary line derived from their
documentation, when available.
By default, these commands use the current window to display the selected module or predicate. To have it in another window instead, invoke these commands with a prefix argument (C-u M-x sweeprolog-find-predicate RET).
The command sweeprolog-find-predicate
uses the function
sweeprolog-read-predicate
for prompting you to insert a
predicate indicator in the minibuffer. This is the standard function
that Sweep commands use for this purpose. It provides completion
candidates based on known predicates, and it uses the predicate at
point, if any, as the default minibuffer argument. By default,
sweeprolog-read-predicate
includes all predicates that Sweep
knows about as completion candidates, except for predicates whose
functor name begins with $
, because that’s the convention in
SWI-Prolog for internal predicates that are usually of little interest
to users. To include also these predicates as completion candidates,
customize the user option
sweeprolog-predicate-visible-p-function
to nil
.
Next: Built-in Native Predicates, Up: Finding Prolog Code [Contents][Index]
Sweep defines a handler for the Emacs function expand-file-name
that recognizes Prolog file specifications, such as
library(lists)
, and expands them to their corresponding
absolute paths. This means that you can use Prolog file
specifications with Emacs’s standard find-file
(C-x C-f)
to locate Prolog resources directly.
For example, typing C-x C-f library(pldoc/doc_man) RET
opens the source of the pldoc_man
module from the Prolog
library, and C-x C-f pack(.) RET opens the Prolog packages
directory.
Previous: Prolog file specification expansion, Up: Finding Prolog Code [Contents][Index]
Some of the built-in predicates provided by SWI-Prolog, such as
is/2
, are implemented in C and included as native functions in
the SWI-Prolog runtime. It is sometimes useful to examine the
implementation of such native built-in predicates by reading its
definition in the SWI-Prolog C sources. Sweep knows about SWI-Prolog
native built-ins, and can find and jump to their definitions in C when
the user has the SWI-Prolog sources checked out locally.
Location of the SWI-Prolog source code root directory.
The way Sweep locates the SWI-Prolog sources depends on the user
option sweeprolog-swipl-sources
. Setting it to nil
disables searching for definitions of native built-ins altogether. To
point Sweep to the root directory of the SWI-Prolog source code, set
sweeprolog-swipl-sources
to the name of that directory. Any
non-nil
non-string value says to try and locate a checkout of
the SWI-Prolog sources among known project root directories (Sweep
consults Emacs’s built-in project-known-project-roots
to find
your project roots, see (emacs)Projects).
With sweeprolog-swipl-sources
set, the provided commands for
finding predicate definitions operate seamlessly on native built-ins
to display their C definitions. These commands include:
xref-find-definitions
) in Sweep Prolog mode buffers
(see Definitions and References), and
help-view-source
) in the *Help* buffer produced
by M-x sweeprolog-describe-predicate (see Prolog Help).
Next: Examining Prolog Messages, Previous: Finding Prolog Code, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Sweep defines a keymap called sweeprolog-prefix-map
that
provides global keybindings for several useful Sweep commands. By
default, sweeprolog-prefix-map
itself is not bound to any key.
To bind it to C-c p, add the following to your Emacs
configuration:
(keymap-global-set "C-c p" 'sweeprolog-prefix-map)
C-c p is the recommended binding for
sweeprolog-prefix-map
, but you’re free to pick any key sequence
you like. As an example, with the above binding you can access the
Sweep top-level from anywhere with C-c p t.
The full list of keybindings in sweeprolog-prefix-map
, assuming
the recommended key binding, is given below:
sweeprolog-find-module
(see Finding Prolog Code).
sweeprolog-find-predicate
(see Finding Prolog Code).
sweeprolog-top-level
(see The Prolog Top-level).
sweeprolog-top-level-send-goal
(see Sending Goals to the Top-level).
sweeprolog-load-buffer
(see Loading Buffers).
sweeprolog-async-goal
(see Executing Prolog Asynchronously).
sweeprolog-list-breakpoints
(see Breakpoint Menu).
sweeprolog-pack-install
(see Installing Prolog Packages).
sweeprolog-restart
(see Prolog Initialization and Cleanup).
sweeprolog-set-prolog-flag
(see Setting Prolog Flags).
sweeprolog-list-top-levels
(see The Top-level Menu buffer).
sweeprolog-xref-project-source-files
(see Definitions and References).
sweeprolog-describe-module
(see Prolog Help).
sweeprolog-describe-predicate
(see Prolog Help).
sweeprolog-view-messages
(see Examining Prolog Messages).
sweeprolog-view-news
(see Discovering Sweep).
Next: Setting Prolog Flags, Previous: Quick Access to Sweep Commands, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Sweep redirects messages that the embedded Prolog runtime emits to a
dedicated Emacs buffer. By default, the Sweep messages buffer is
named *Sweep Messages*. To instruct Sweep to use another
buffer name instead, customize the user option
sweeprolog-messages-buffer-name
to a suitable value.
The *Sweep Messages* buffer enables the minor mode
compilation-minor-mode
, which let’s you jump to source
locations that appear in errors and warning by clicking on them.
Display the Sweep messages buffer.
You can use the command M-x sweeprolog-view-messages RET
to display the Sweep messages buffer. This command is bound to h
e in sweeprolog-prefix-map
(see Quick Access to Sweep Commands).
Next: Installing Prolog Packages, Previous: Examining Prolog Messages, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
SWI-Prolog has a set of flags that let you examine and configure the Prolog execution runtime. You can set Prolog flags from Emacs directly with the following command:
Set the value of a Prolog flag.
This command let’s you interactively configure the embedded Prolog execution environment by changing the values of Prolog flags. It prompts you for a Prolog flag, with completion candidates annotated with their current values. Then, it prompts again for a Prolog term and sets the flag’s value to that term.
For more information about Prolog flags in SWI-Prolog, see Environment Control in the SWI-Prolog manual.
As an example, the Prolog flag double_quotes
controls the
interpretation of double quotes in Prolog code. By default,
double_quotes
is set to string
, so for instance
"foo"
is read as a SWI-Prolog string. You can easily validate
this in the Sweep top-level:
?- A = "foo". A = "foo".
You can change the interpretation of double quotes to denote lists of
character codes, by setting the value the double_quotes
flag to
codes
with M-x sweeprolog-set-prolog-flag RET
double_quotes RET codes RET. Evaluating A = "foo"
again exhibits the different interpretation:
?- A = "foo". A = [102, 111, 111].
Note that some flags have a thread-local value, and
sweeprolog-set-prolog-flag
always operates only on the main
thread. To set flags in an existing top-level thread, use the
predicate set_prolog_flag/2
directly in that top-level.
Next: Contributing, Previous: Setting Prolog Flags, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
You can install SWI-Prolog add-ons, also known as packs, with the following command:
Install or upgrade a Prolog pack.
This command prompts from a pack name, with completion, and installs it or upgrades it to the latest available version. (See also Packs in the SWI-Prolog manual.)
Next: Things to do, Previous: Installing Prolog Packages, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
We highly appreciate all contributions, including bug reports, patches, improvement suggestions, and general feedback.
For a list of known areas where Sweep could use some work, see Things to do.
Next: Submitting patches and bug reports, Up: Contributing [Contents][Index]
Since the Prolog and C parts of Sweep are distributed and installed
along with SWI-Prolog (see Installation), the easiest way to set
up Sweep for development is to start with a SWI-Prolog development
setup. Clone the swipl-devel
Git repository, go the
subdirectory packages/sweep that contains Sweep as a Git
submodule, and update it to the latest development version:
git clone --recursive https://github.com/SWI-Prolog/swipl-devel.git cd swipl-devel/packages/sweep git checkout master git pull
The directory packages/sweep in the swipl-devel
repository now contains the development version of Sweep. You can
hack on Sweep’s source files and then (re)build SWI-Prolog to test
your changes. See
Building SWI-Prolog using cmake for more information about building
SWI-Prolog from source.
If you only modify the Elisp library sweeprolog.el, you do not need to rebuild SWI-Prolog. You can simply evaluate and test your changes directly inside Emacs (see (emacs)Lisp Eval).
If you change sweep.c or otherwise want to rebuild SWI-Prolog, you can do that from the packages/sweep subdirectory by running the following command:
ninja -C ../../build
Previous: Setting up Sweep for local development, Up: Contributing [Contents][Index]
The best way to get in touch with the Sweep maintainers is via the Sweep mailing list.
Report a bug in Sweep to the maintainers via mail.
You can use the command M-x sweeprolog-submit-bug-report to easily contact the Sweep maintainers from within Emacs. This command opens a new buffer with a message template ready to be sent to the Sweep mailing list.
Next: Indices, Previous: Contributing, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
The following sections list potential improvement for Sweep in different areas:
Next: General improvements, Up: Things to do [Contents][Index]
font-lock-maximum-decoration
We should take into account the value of
font-lock-maximum-decoration
while highlighting
sweeprolog-mode
buffers. This variable conveys the user’s
preferred degree of highlighting. A possible approach would be
changing sweeprolog-analyze-fragment-to-faces
such that each
color fragment in the returned list states the minimum decoration
level (1, 2 or 3) for which it should apply.
sweeprolog-analyze-fragment-font-lock
would then compare this
target to the value of (font-lock-value-in-major-mode
font-lock-maximum-decoration)
and decide whether or not to apply the
fragment.
Sweep Prolog mode should integrate with align.el such that
M-x align aligns arguments of consecutive predicate calls.
Concretely, we need to locally set align-mode-rules-list
to a
suitable value in sweeprolog-mode
.
Sweep Prolog mode should define a fill-paragraph-function
, and
perhaps also a normal-auto-fill-function
, for code filling that
takes into account Prolog-specific conventions.
Previous: Improvements around editing Prolog, Up: Things to do [Contents][Index]
Sweep should facilitate interactive debugging of SWI-Prolog code.
This is a big topic that we don’t clearly address. Perhaps this
should be handled through a Debug Adapter Protocol integration similar
to dap-swi-prolog
(Debug Adapter Protocol for SWI-Prolog).
It would be nice if Sweep would “teach” project.el to detect directories containing SWI-Prolog pack.pl package definitions as root project directories.
Currently, the Elisp interface that Sweep provides for querying Prolog only allows calling directly to predicates of arity 2 (see Querying Prolog), ideally we should provide a (backward-compatible) way for executing arbitrary Prolog queries.
Previous: Things to do, Up: Sweep: SWI-Prolog Embedded in Emacs [Contents][Index]
Next: Variable index, Up: Indices [Contents][Index]
Jump to: | C D I K N S |
---|
Jump to: | C D I K N S |
---|
Next: Keystroke index, Previous: Function index, Up: Indices [Contents][Index]
Jump to: | I S |
---|
Jump to: | I S |
---|
Next: Concept index, Previous: Variable index, Up: Indices [Contents][Index]
Jump to: | C M O R S T |
---|
Jump to: | C M O R S T |
---|
Previous: Keystroke index, Up: Indices [Contents][Index]
Jump to: | A B C D E F G H I J K L M N P Q R S T U V W X |
---|
Jump to: | A B C D E F G H I J K L M N P Q R S T U V W X |
---|