Go to the first, previous, next, last section, table of contents.


How to Run Prolog

SICStus Prolog offers the user an interactive programming environment with tools for incrementally building programs, debugging programs by following their executions, and modifying parts of programs without having to start again from scratch.

The text of a Prolog program is normally created in a file or a number of files using one of the standard text editors. The Prolog interpreter can then be instructed to read in programs from these files; this is called consulting the file. Alternatively, the Prolog compiler can be used for compiling the file.

Getting Started

Under UNIX, SICStus Prolog is normally started from one of the shells. On other platforms, it is normally started by clicking on an icon. However, it is often convenient to run SICStus Prolog under GNU Emacs instead. A GNU Emacs interface for SICStus Prolog is described later (see section Emacs Interface). From a shell, SICStus Prolog is started by typing:

% sicstus [-f] [-i] [-m] [-B[abspath]] [-R[abspath]] [-p boot-path] 
    [-base executable] [-r restorefile] [-l prologfile]  
    [-P[T] [num]] [-F num] [-a argument...]

where the flags have the following meaning:

-f
Fast start. Don't read any initialization file (`~/.sicstusrc' or `~/.sicstus.ini') on startup. If the flag is omitted, SICStus Prolog will consult this file on startup if it exists.
-i
Forced interactive. Prompt for user input, even if the standard input does not appear to be a terminal.
-m
Use malloc()/free() in the memory manager's bottom layer.
-l prolog-file
Ensure that the file prolog-file is loaded on startup.
-r saved-state
Restore the saved state saved-state on startup. This is done before any initialization file or prolog-file is loaded.
-a argument...
where the arguments can be retrieved from Prolog by prolog_flag(argv, Args), which will unify Args with argument... represented as a list of atoms.
-p boot-path
Overrides the default path for the Runtime Library, from which the value of the user:library_directory/1 fact is derived. This option is only relevant for statically linked Development Systems (see section Development Systems) as an alternative to setting the SP_PATH variable (see section Environment Variables). The use of this flag is discouraged. Use the -base option instead.
-base executable
Unix platforms only. Override the binary used when executing SICStus from within the start-script. Useful, for example, for statically linked Development Systems (see section Development Systems) to avoid having to set environment variables such as SP_PATH (see section Environment Variables) which are set by the start-script.
-P [num]
-PT [num]
The uninstrumented (-P) or trace (-PT) version of Muse is started. As an option, num specifies the initial number of workers used (defaults to 1). See section The Muse Model. Only available if Muse has been installed.
-F num
Only useful for the Sequent Symmetry version of Muse. Its purpose is to preallocate shared memory for num workers. If the `-F' argument is not used, num is assumed to be equal to the default number of workers.
-B[abspath]
Creates a saved state for a development system. This option is not needed for normal use. If abspath is given, it specifies the absolute pathname for the saved state. Note: There must not be a space before the path, or it will be interpreted as a separate option.
-R[abspath]
Equivalent to the -B option, except that it builds a saved state for a runtime system instead.

Under Unix, a saved state file can be executed directly by typing:

% file argument...

This is equivalent to:

% sicstus -r file [-a argument...]

Note: Beginning with SICStus version 3.7, saved-states do not store the complete path of the binary sp.exe. Instead, they call the start-script sicstus, which is assumed to be found in the shell's path. If there are several versions of SICStus installed, it is up to the user to make sure that the correct start-script is found.

Notice that the flags are not available when executing saved states--all the command line arguments are treated as Prolog arguments.

The Development System responds with a message of identification and the prompt `| ?- ' as soon as it is ready to accept input, thus:

SICStus 3.7: Mon Mar  2 19:22:44 MET 1998
| ?- 

At this point the top-level is expecting input of a directive, i.e. a query or command. See section Directives: Queries and Commands. You cannot type in clauses immediately (see section Inserting Clauses at the Terminal). While typing in a directive, the prompt (on following lines) becomes ` '. That is, the `| ?- ' appears only for the first line of the directive, and subsequent lines are indented.

Finding Libraries at Runtime

As of SICStus Prolog 3.7, development systems and runtime systems have been reorganized around a common runtime kernel. This kernel is delivered as a shared object/DLL, which means that the runtime linker must be able to locate it at runtime. Under Windows, the runtime linker usually has no problem locating the correct DLLs. The rest of this section is therefore Unix-specific.

Most Unix systems rely partly on the so called runtime linker search path which tells the runtime linker where it should look for shared objects in addition to the default paths (such as `/lib', `/usr/lib', `/usr/local/lib', and so on).

SICStus' start-script fixes this by setting the runtime linker search path variable together with SP_PATH (See section Environment Variables) to their correct values. There is also a flag -base to the start-script which forces it to use a different executable. This is very useful when bulding statically linked Development Systems (see section Development Systems). By using the -base flag, the start-script can be used also for these. For example, to execute a statically linked Development System called myapp:

% sicstus -base myapp

However, this is only possible to do with Development Systems. Runtime Systems cannot be started using the SICStus start-script and therefore may have to set the runtime linker search path variable explicitly. The following is how a typical error looks like when the runtime linker cannot find the SICStus runtime kernel:

ld.so.1: /home/bob/mysicstus/lib/sicstus37beta/bin/sp.exe: fatal: \
   libsprt37.so: can't open file: errno=2
Killed

The cure for this is to explicitly set the runtime linker search path variable to contain the path to `libsprt37.so'. For sh, bash, etc. this is done by:

% export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/home/bob/mysicstus/lib

and for csh, tcsh, etc. by:

% setenv LD_LIBRARY_PATH ${LD_LIBRARY_PATH}:/home/bob/mysicstus/lib

The runtime linker search path variable is not always called LD_LIBRARY_PATH; this depends on which runtime linker the system uses and how it is configured. Other possible names are LD_RUN_PATH, LIBRARY_PATH, and SHLIB_PATH. The latter is mostly used under IRIX. Check your system documentation or ask your system administrator for details.

Environment Variables

The following environment variables can be set before starting SICStus Prolog. Some of these override the default sizes of certain areas. The sizes are given in bytes, but may be followed by K or M meaning kilobytes or megabytes respectively.

SP_CTYPE
Selects the appropriate character set standard: The supported values are euc (for EUC) and iso_8859_1 (for ISO 8859/1). The latter is the default.
SP_PATH
This environment variable is used to determine the location of the Runtime Library. It is normally not necessary to set this environment variable; under UNIX it is hard-coded into the start-up script and under Windows it is stored in the repository. However, under some circumstances it is necessary to set this variable explicitly, for example when executing Runtime System which do not specify a path in the third argument to SP_initialize().
TMPDIR
If set, indicates the pathname where temporary files should be created. Defaults to `/usr/tmp'.
GLOBALSTKSIZE
Governs the initial size of the global stack.
LOCALSTKSIZE
Governs the initial size of the local stack.
CHOICESTKSIZE
Governs the initial size of the choicepoint stack.
TRAILSTKSIZE
Governs the initial size of the trail stack.
PROLOGINITSIZE
Governs the size of Prolog's initial memory allocation.
PROLOGMAXSIZE
Defines a limit on the amount of data space which Prolog will use.
PROLOGINCSIZE
Governs the amount of space Prolog asks the operating system for in any given memory expansion.
PROLOGKEEPSIZE
Governs the size of space Prolog retains after performing some computation. By default, Prolog gets memory from the operating system as the user program executes and returns all free memory back to the operating system when the user program does not need any more. If the programmer knows that her program, once it has grown to a certain size, is likely to need as much memory for future computations, then she can advise Prolog not to return all the free memory back to the operating system by setting this variable. Only memory that is allocated above and beyond PROLOGKEEPSIZE is returned to the OS; the rest will be kept.

Send bug reports to <sicstus-support@sics.se>. Bugs tend actually to be fixed if they can be isolated, so it is in your interest to report them in such a way that they can be easily reproduced.

The mailing list <sicstus-users@sics.se> is a mailing list for communication among users and implementors. To [un]subscribe, write to <sicstus-users-request@sics.se>.

Reading in Programs

A program is made up of a sequence of clauses, possibly interspersed with directives to the system. The clauses of a predicate do not have to be immediately consecutive, but remember that their relative order may be important (see section Procedural Semantics).

To input a program from a file file, just type the filename inside list brackets (followed by . and RET), thus:

| ?- [file].

This instructs the interpreter to read in (consult) the program. Note that it may be necessary to surround the whole file specification file with single quotes to make it a legal Prolog atom; e.g.

| ?- ['myfile.pl'].

| ?- ['/usr/prolog/somefile'].

The specified file is then read in. Clauses in the file are stored so that they can later be interpreted, while any directives are obeyed as they are encountered. When the end of the file is found, the interpreter displays on the standard error stream the time spent for read-in. This indicates the completion of the directive.

Predicates that expect the name of a Prolog source file as an argument use
absolute_file_name/2 (see section Stream I/O) to look up the file. This predicate will first search for a file with the suffix `.pl' added to the name given as an argument. If this fails it will look for a file with no extra suffix added. There is also support for libraries.

In general, this directive can be any list of filenames, such as:

| ?- [myprog,extras,tests].

In this case all three files would be consulted.

The clauses for all the predicates in the consulted files will replace any existing clauses for those predicates, i.e. any such previously existing clauses in the database will be deleted.

Note that consult/1 in SICStus Prolog behaves like reconsult/1 in DEC-10 Prolog.

Inserting Clauses at the Terminal

Clauses may also be typed in directly at the terminal, although this is only recommended if the clauses will not be needed permanently, and are few in number. To enter clauses at the terminal, you must give the special directive:

| ?- [user].
|

and the new prompt `| ' shows that the system is now in a state where it expects input of clauses or directives. To return to top level, type ^D. The system responds thus:

{user consulted, 20 msec 200 bytes}

Directives: Queries and Commands

Directives are either queries or commands. Both are ways of directing the system to execute some goal or goals.

In the following, suppose that list membership has been defined by loading the following clauses from a file:

member(X, [X|_]).
member(X, [_|L]) :- member(X, L).

(Notice the use of anonymous variables written `_'.)

Queries

The full syntax of a query is `?-' followed by a sequence of goals. The top level expects queries. This is signaled by the initial prompt `| ?- '. Thus a query at top level looks like:

| ?- member(b, [a,b,c]).

Remember that Prolog terms must terminate with a full stop (., possibly followed by layout text), and that therefore Prolog will not execute anything until you have typed the full stop (and then RET) at the end of the query.

If the goal(s) specified in a query can be satisfied, and if there are no variables as in this example, then the system answers

yes

and execution of the query terminates.

If variables are included in the query, then the final value of each variable is displayed (except for variables whose names begin with _). Thus the query

| ?- member(X, [a,b,c]).

would be answered by

X = a

At this point the system is waiting for input of either just a RET or else a ; followed by RET. Simply typing RET terminates the query; the system responds with `yes'. However, typing ; causes the system to backtrack (see section Procedural Semantics) looking for alternative solutions. If no further solutions can be found it outputs `no'.

The outcome of some queries is shown below, where a number preceded by _ is a system-generated name for a variable.

| ?- member(X, [tom,dick,harry]).

X = tom ;
X = dick ;
X = harry ;

no
| ?- member(X, [a,b,f(Y,c)]), member(X, [f(b,Z),d]).

X = f(b,c),
Y = b,
Z = c

yes
| ?- member(X, [f(_),g]).

X = f(_A)

yes
| ?-

Commands are like queries except that

  1. Variable bindings are not displayed if and when the command succeeds.
  2. You are not given the chance to backtrack through other solutions.

Commands

Commands start with the symbol `:-'. Any required output must be programmed explicitly; e.g. the command:

:- member(3, [1,2,3]), write(ok).

directs the system to check whether 3 belongs to the list [1,2,3]. Execution of a command terminates when all the goals in the command have been successfully executed. Other alternative solutions are not sought. If no solution can be found, the system prints:

{Warning: Goal - goal failed}

as a warning.

The principal use for commands (as opposed to queries) is to allow files to contain directives which call various predicates, but for which you do not want to have the answers printed out. In such cases you only want to call the predicates for their effect, i.e. you don't want terminal interaction in the middle of consulting the file. A useful example would be the use of a directive in a file which consults a whole list of other files, e.g.

:- [ bits, bobs, main, tests, data, junk ].

If a command like this were contained in the file `myprog' then typing the following at top-level would be a quick way of reading in your entire program:

| ?- [myprog].

When simply interacting with the top-level this distinction between queries and commands is not normally very important. At top-level you should just type queries normally. In a file, queries are in fact treated as commands, i.e. if you wish to execute some goals then the directive in the file must be preceded by `:-' or `?-', otherwise it would be treated as a clause.

Syntax Errors

Syntax errors are detected during reading. Each clause, directive or in general any term read in by the built-in predicate read/1 that fails to comply with syntax requirements is displayed on the standard error stream as soon as it is read, along with its position in the input stream and a mark indicating the point in the string of symbols where the parser has failed to continue analysis, e.g.:

| member(X, X$L).
{SYNTAX ERROR: in line 5 (within 5-6)}
** , or ) expected in arguments **
member ( X , X 
** here **
$ L ) . 

if $ has not been declared as an infix operator.

Note that any comments in the faulty line are not displayed with the error message. If you are in doubt about which clause was wrong you can use the listing/1 predicate to list all the clauses which were successfully read-in, e.g.

| ?- listing(member/2).

Note: The built in predicates read/(1-2) normaly raise an exception on syntax errors (see section Error and Exception Handling). The behavior is controlled by the flag syntax_errors (see prolog_flag/3).

Undefined Predicates

There is a difference between predicates that have no definition and predicates that have no clauses. The latter case is meaningful e.g. for dynamic predicates (see section Declarations) that clauses are being added to or removed from. There are good reasons for treating calls to undefined predicates as errors, as such calls easily arise from typing errors.

The system can optionally catch calls to predicates that have no definition. First the user defined predicate user:unknown_predicate_handler/3 (see section Error and Exception Handling) is called. If undefined or if the call fails the action is governed by the state of the unknown/2 flag which can be:

trace
which causes calls to undefined predicates to be reported and the debugger to be entered at the earliest opportunity.
error
which causes calls to such predicates to raise an exception (the default state). See section Error and Exception Handling.
fail
which causes calls to such predicates to fail.

Calls to predicates that have no clauses are not caught.

The built-in predicate unknown(?OldState, ?NewState) unifies OldState with the current state and sets the state to NewState. The built-in predicate debugging/0 prints the value of this state along with its other information. This state is also controlled by the flag unknown (see prolog_flag/3).

Program Execution And Interruption

Execution of a program is started by giving the system a directive which contains a call to one of the program's predicates.

Only when execution of one directive is complete does the system become ready for another directive. However, one may interrupt the normal execution of a directive by typing ^C. This ^C interruption has the effect of suspending the execution, and the following message is displayed:

Prolog interruption (h or ? for help) ?

At this point, the Development System accepts one-letter commands corresponding to certain actions. To execute an action simply type the corresponding character (lower or upper case) followed by RET. The available commands in both Development Systems are:

a
aborts the current computation.
c
continues the execution.
e
exits from SICStus Prolog, closing all files.
h
?
lists available commands.

The following commands are also available in the sequential Development System only:

b
invokes a recursive top-level.
d
z
t
switch on the debugger. See section Debugging.

If the standard input stream is not connected to the terminal, e.g. by redirecting standard input to a file or a pipe, the above ^C interrupt options are not available. Instead, typing ^C causes SICStus Prolog to exit, and no terminal prompts are printed.

Exiting From The Top-Level

To exit from the top-level and return to the shell, either type ^D at the top-level, or call the built-in predicate halt/0, or use the e (exit) command following a ^C interruption.

Nested Executions--Break and Abort

The Prolog system provides a way to suspend the execution of your program and to enter a new incarnation of the top level where you can issue directives to solve goals etc. This is achieved by issuing the directive (see section Program Execution And Interruption):

| ?- break.

This invokes a recursive top-level, indicated by the message:

{ Break level 1 }

You can now type queries just as if you were at top-level.

If another call of break/0 is encountered, it moves up to level 2, and so on. To close the break and resume the execution which was suspended, type ^D. The debugger state and current input and output streams will be restored, and execution will be resumed at the predicate call where it had been suspended after printing the message:

{ End break }

Alternatively, the suspended execution can be aborted by calling the built-in predicate abort/0.

A suspended execution can be aborted by issuing the directive:

| ?- abort.

within a break. In this case no ^D is needed to close the break; all break levels are discarded and the system returns right back to top-level. I/O streams remain open, but the debugger is switched off. abort/0 may also be called from within a program.

Saving and Restoring Program States

Once a program has been read, the system will have available all the information necessary for its execution. This information is called a program state.

The state of a program may be saved on disk for future execution. The state consists of all predicates and modules except built-in predicates and clauses of volatile predicates, the current operator declarations, the values of all writable Prolog flags except debugging, source_info, and the user_* stream aliases (see section Information about the State of the Program), any blackboard data (see section Blackboard Primitives), internal database data (see section Internal Database), and profiling data (see section Execution Profiling), but no information for source-linked debugging.

To save a program into a file File, type the following directive. On UNIX platforms, the file becomes executable:

| ?- save_program(File).

You can also specify a goal to be run when a saved program is restored. This is done by:

| ?- save_program(File, start).

where start/0 is the predicate to be called.

Once a program has been saved into a file File, the following directive will restore the system to the saved state:

| ?- restore(File).

If a saved state has been moved or copied to another machine, the path names of foreign resources and other files needed upon restore are typically different at restore time from their save time values. To solve this problem, certain atoms will be relocated during restore as follows:

The purpose of this procedure is to be able to build and deploy an application consisting of a saved state and other files as a directory tree with the saved state at the root: as long as the other files maintain their relative position in the deployed copy, they can still be found upon restore.

Note: Foreign resources, see section Calling C from Prolog, are unloaded by save_program/(1,2). The names and paths of the resources, typically `$SP_PATH/library' relative, are however included in the saved state. After the save, and after restoring a saved state, this information is used to reload the foreign resources again. The state of the foreign resource in terms of global C variables and allocated memory is thus not preserved. Foreign resources may define init and deinit functions to take special action upon loading and unloading, see section Init and Deinit Functions.

In the Muse Development System, the above predicates may only be called when the system has been adjusted to one worker; see section The Muse Model.

Emacs Interface

This section explains how to use the GNU Emacs interface for SICStus Prolog, and how to customize your GNU Emacs environment for it.

The advantages of using SICStus in the Emacs environment are source-linked debugging, auto indentation, syntax highlighting, help on predefined predicates (requires the SICStus info files to be installed), loading code from inside Emacs, auto-fill mode, and more.

The mode was developed for GNU Emacs 19.34 but it works well for versions 19.31 through 20.2. Earlier versions may not be able to provide syntax highlighting. The mode has also been reported to work with XEmacs (version 19 and 20) but it will probably not work with GNU Emacs 18 or earlier.

The Emacs interface is not part of SICStus Prolog proper, but is included in the distribution for convenience. It was written by Emil Åström and Milan Zamazal, based on an earlier version of the mode written by Masanobu Umeda. Contributions has also been made by Johan Andersson, Peter Olin, Mats Carlsson, Johan Bevemyr, Stefan Andersson, and Per Danielsson (all at SICS), and Henrik Båkman at Uppsala University, Sweden. Some ideas and also a few lines of code have been borrowed (with permission) from Oz.el by Ralf Scheidhauer and Michael Mehl, the Emacs major mode for the Oz programming language. More ideas and code have been taken from the SICStus debugger mode by Per Mildner.

Customizing Emacs

Assuming the GNU Emacs interface for SICStus Prolog has been installed, inserting the following lines in your `~/.emacs' (or `_emacs' in case of Windows/DOS) will make Emacs use this mode automatically when editing files with a `.pl' extension:

(setq load-path (cons "/usr/local/lib/sicstus37" load-path))
(autoload 'run-prolog "prolog" "Start a Prolog sub-process." t)
(autoload 'prolog-mode "prolog" "Major mode for editing Prolog programs." t)
(setq prolog-use-sicstus-sd t)
(setq auto-mode-alist (cons '("\\.pl$" . prolog-mode) auto-mode-alist))

where the path in the first line is the file system path to `prolog.el' (the Emacs interface) and `pltrace.el' (the process output filter for source-linked debugging). For example, `~/site-lisp' means that the file is in the user's home directory, under site-lisp. MSDOS paths can be written like `C:/Program Files/emacs-19.34/site-lisp'.

The last line above makes sure that files ending with `.pl' are assumed to be Prolog files and not Perl, which is the default Emacs setting. If this is undesirable, remove that line. It is then necessary for the user to manually switch to prolog mode by typing M-x prolog-mode after opening a prolog file.

If the shell command sicstus is not available in the default path, then it is necessary to set the value of the environment variable EPROLOG to a shell command to invoke SICStus Prolog. This is an example for C Shell:

setenv EPROLOG /usr/local/bin/sicstus

Basic Configuration

If the following lines are not present in `~/.emacs', we suggest they are added, so that the font-lock mode (syntax coloring support) is enabled for all major modes in Emacs that support it.

(global-font-lock-mode t)
(setq font-lock-maximum-decoration t)

If one wants to add font-locking only to the prolog mode, the two lines above could be replaced by:

(add-hook 'prolog-mode-hook 'turn-on-font-lock)

If the background color of Emacs is dark and it is difficult to read the code because of the chosen colors, then it might be useful to add

(setq font-lock-background-mode 'dark)

Usage

A prolog process can be started by choosing Run Prolog from the Prolog menu, by typing C-c RET, or by typing M-x run-prolog. It is however not strictly necessary to start a prolog process manually since it is automatically done when consulting or compiling, if needed. The process can be restarted (i.e. the old one is killed and a new one is created) by typing C-u C-c RET.

Programs are run and debugged in the normal way, with terminal I/O via the *prolog* buffer. The most common debugging predicates are available from the menu or via key-bindings.

A particularly useful feature under the Emacs interface is source-linked debugging. This is enabled or disabled using the Prolog/Source level debugging menu entry. It can also be enabled by setting the Emacs variable prolog-use-sicstus-sd to t in `~/.emacs'. Both these methods set the Prolog flag source_info to on. The flag should be on while loading the code to be debugged and while debugging. If so, the debugger will display the source code location of the current goal when it prompts for a debugger command, by overlaying the beginning of the current line of code with an arrow. If source_info was off when the code was loaded, or if it was asserted or loaded from user, the current goal will still be shown but out of context.

Note that if the code has been modified since it was last loaded, Prolog's line number information may be invalid. If this happens, just reload the relevant buffer.

Consultation and compilation is either done via the menu or with the following key-bindings:

C-c C-f
Consult file.
C-c C-b
Consult buffer.
C-c C-r
Consult region.
C-c C-p
Consult predicate.
C-c C-c f
Compile file.
C-c C-c b
Compile buffer.
C-c C-c r
Compile region.
C-c C-c p
Compile predicate.

The boundaries used when consulting and compiling predicates are the first and last clauses of the predicate the cursor is currently in.

Other useful key-bindings are:

M-n
Go to the next clause.
M-p
Go to the previous clause.
M-a
Go to beginning of clause.
M-e
Go to end of clause.
M-C-c
Mark clause.
M-C-a
Go to beginning of predicate.
M-C-e
Go to end of predicate.
M-C-h
Mark predicate.
M-{
Go to the previous paragraph (i.e. empty line).
M-}
Go to the next paragraph (i.e. empty line).
M-h
Mark paragraph.
M-C-n
Go to matching right parenthesis.
M-C-p
Go to matching left parenthesis.
M-;
Creates a comment at comment-column. This comment will always stay at this position when the line is indented, regardless of changes in the text earlier on the line, provided that prolog-align-comments-flag is set to t.
C-c C-t, C-u C-c C-t
Enable and disable tracing, respectively.
C-c C-d, C-u C-c C-d
Enable and disable debugging, respectively.
C-c C-z, C-u C-c C-z
Enable and disable zipping, respectively.
C-c C-s
Insert the PredSpec of the current predicate into the code.
C-c C-n
Insert the name of the current predicate into the code. This can be useful when writing recursive predicates or predicates with several clauses. See also the prolog-electric-dot-flag variable below.
C-c C-v a
Convert all variables in a region to anonymous variables. This can also be done using the Prolog/Transform/All variables to '_' menu entry. See also the prolog-electric-underscore-flag Emacs variable.
C-c ?
Help on predicate (requires the SICStus info files to be installed), and the Emacs variable prolog-info-predicate-index to be set to the predicate index of the info files (defaults to "(sicstus)Predicate Index").

Mode Line

If working with an application split into several modules, it is recommended to let the source files begin with a "mode line":

%%% -*- Module: ModuleName; -*-

The Emacs interface will look for the mode line and notify the SICStus Prolog module system that the predicates being incrementally reconsulted or recompiled belong to the module ModuleName. If SICStus Prolog recognizes the file as one being loaded before, it will remember what module it belongs to. If the mode line is missing, and the file has not been loaded before, the predicates will go into the type-in module. Even if the file has been loaded earlier, its filename may have a slightly different appearance to Prolog via the Emacs interface, so it is safest to always include the mode line. A mode line can be inserted by choosing Insert/Module modeline in the Prolog menu.

Configuration

The behavior of the Emacs interface can be controlled by a set of user-configurable settings. Some of these can be changed on the fly, while some require Emacs to be restarted. To set a variable on the fly, type M-x set-variable RET VariableName RET Value RET. Note that variable names can be completed by typing a few characters and then pressing TAB.

To set a variable so that the setting is used every time Emacs is started, add lines of the following format to `~/.emacs':

(setq VariableName Value)

The available settings are:

prolog-system
The Prolog system to use. Available settings are 'mercury, 'sicstus, and 'swi. Defaults to 'sicstus.
prolog-system-version
The version of SICStus that is used. Defaults to '((sicstus (3 . 7))). Note that the spaces are significant!
prolog-use-sicstus-sd
Set to t to enable the source-linked debugging extensions by default. Defaults to nil. The debugging can be enabled via the Prolog menu even if this variable is nil. Note that the source-linked debugging only works if prolog-system-version is set correctly.
pltrace-port-arrow-assoc
Only relevant for source-linked debugging, this controls how the various ports of invocation boxes (see section The Procedure Box Control Flow Model) map to arrows that point into the current line of code in source code buffers. Initialized as:
'(("call" . ">>>") ("exit" . "+++") ("ndexit" . "?++") ("redo" . "<<<") 
  ("fail" . "---") ("exception" . "==>"))
where ndexit is the non-deterministic variant of the Exit port.
prolog-indent-width
How many positions to indent the body of a clause. Defaults to tab-width, normally 8.
prolog-paren-indent
The number of positions to indent code inside grouping parentheses. Defaults to 4, which gives the following indentation.
p :-
        (   q1
        ;   q2,
            q3
        ).
Note that the spaces between the parentheses and the code are automatically inserted when TAB is pressed at those positions.
prolog-align-comments-flag
Set to nil to prevent single %-comments to be automatically aligned. Defaults to t. Note that comments with one % are indented to comment-column, comments with two % to the code level, and that comments with three % are never changed when indenting.
prolog-indent-mline-comments-flag
Set to nil to prevent indentation of text inside /* ... */ comments. Defaults t.
prolog-object-end-to-0-flag
Set to nil to indent the closing } of an object definition to prolog-indent-width. Defaults to t.
prolog-keywords
This is a list with keywords that are highlighted in a special color when used as commands (i.e. as :- keyword). Defaults to
'((sicstus ("block" "dynamic" "mode" "module" "multifile"
   "meta_predicate" "parallel" "public" "sequential" "volatile")))
prolog-electric-newline-flag
Set to nil to prevent Emacs from automatically indenting the next line when pressing RET. Defaults to t.
prolog-hungry-delete-key-flag
Set to t to enable deletion of all white space before the cursor when pressing the delete key (unless inside a comment, string, or quoted atom). Defaults to nil.
prolog-electric-dot-flag
Set to t to enable the electric dot function. If enabled, pressing . at the end of a non-empty line inserts a dot and a newline. When pressed at the beginning of a line, a new head of the last predicate is inserted. When pressed at the end of a line with only whitespace, a recursive call to the current predicate is inserted. The function respects the arity of the predicate and inserts parentheses and the correct number of commas for separation of the arguments. Defaults to nil.
prolog-electric-underscore-flag
Set to t to enable the electric underscore function. When enabled, pressing underscore (_) when the cursor is on a variable, replaces the variable with the anynomous variable. Defaults to nil.
prolog-old-sicstus-keys-flag
Set to t to enable the key-bindings of the old Emacs interface. These bindings are not used by default since they violate GNU Emacs recommendations. Defaults to nil.
prolog-use-prolog-tokenizer-flag
Set to nil to use built-in functions of Emacs for parsing the source code when indenting. This is faster than the default but does not handle some of the syntax peculiarities of Prolog. Defaults to t.
prolog-parse-mode
What position the parsing is done from when indenting code. Two possible settings: 'beg-of-line and 'beg-of-clause. The first is faster but may result in erroneous indentation in /* ... */ comments. The default is 'beg-of-line.
prolog-imenu-flag
Set to t to enable a new Predicate menu which contains all predicates of the current file. Choosing an entry in the menu moves the cursor to the start of that predicate. Defaults to nil.
prolog-info-predicate-index
The info node for the SICStus predicate index. This is important if the online help function is to be used (by pressing C-c ?, or choosing the Prolog/Help on predicate menu entry). The default setting is "(sicstus)Predicate Index".
prolog-underscore-wordchar-flag
Set to nil to not make underscore (_) a word-constituent character. Defaults to t.

Tips

Some general tips and tricks for using the SICStus mode and Emacs in general are given here.

Font-locking

When editing large files, it might happen that font-locking is not done because the file is too large. Typing M-x lazy-lock-mode results in only the visible parts of the buffer being highlighted, which is much faster.

If the font-locking seems to be incorrect then choose Fontify Buffer from the Prolog menu.

Auto-fill mode

Auto-fill mode is enabled by typing M-x auto-fill-mode. This enables automatic line breaking with some features. For example, the following multiline comment was created by typing M-; followed by the text. The second line was indented and a % was added automatically.

dynamics([]).       % A list of pit furnace
                    % dynamic instances

Speed

There are several things to do if the speed of the Emacs environment is a problem:

Changing Colors

The prolog mode uses the default Emacs colors for font-locking as far as possible. The only custom settings are in the prolog process buffer. The default settings of the colors may not agree with your preferences, so here is how to change them.

First of all, list all available faces (a face is a combined setting of foreground and background colors, font, boldness, etc.) by typing M-x list-faces-display.

There are several functions that change the appearance of a face, the ones you will most likely need are:

set-face-foreground
set-face-background
set-face-underline-p
make-face-bold
make-face-bold-italic
make-face-italic
make-face-unbold
make-face-unitalic

These can be tested interactively by typing M-x function-name. You will then be asked for the name of the face to change and a value. If the buffers are not updated according to the new settings, then refontify the buffer using the Fontify Buffer menu entry in the Prolog menu.

Colors are specified by a name or by RGB values. Available color names can be listed with M-x list-colors-display.

To store the settings of the faces, a few lines must be added to `~/.emacs'. For example:

;; Customize font-lock faces
(add-hook 'font-lock-mode-hook 
          '(lambda ()
             (set-face-foreground font-lock-variable-name-face "#00a000")
             (make-face-bold font-lock-keyword-face)
             (set-face-foreground font-lock-reference-face "Blue")
             ))


Go to the first, previous, next, last section, table of contents.