Using Guile Interactively
=========================

When you start up Guile by typing just guile, without a -c argument or the name of a script to execute, you get an interactive interpreter where you can enter Scheme expressions, and Guile will evaluate them and print the results for you.  Here are some simple examples.

     scheme@(guile-user)> (+ 3 4 5)
     $1 = 12
     scheme@(guile-user)> (display "Hello world!\n")
     Hello world!
     scheme@(guile-user)> (values 'a 'b)
     $2 = a
     $3 = b

This mode of use is called a REPL, which is short for ``Read-Eval-Print Loop'', because the Guile interpreter first reads the expression that you have typed, then evaluates it, and then prints the result.

The prompt shows you what language and module you are in. In this case, the current language is scheme, and the current module is (guile-user). See Other Languages, for more information on Guile's support for languages other than Scheme.

The Init File, ~/.guile
-----------------------

When run interactively, Guile will load a local initialization file from ~/.guile.  This file should contain Scheme expressions for evaluation.

This facility lets the user customize their interactive Guile environment, pulling in extra modules or parameterizing the REPL implementation.

To run Guile without loading the init file, use the -q command-line option.

Readline
--------

To make it easier for you to repeat and vary previously entered expressions, or to edit the expression that you're typing in, Guile can use the GNU Readline library.  This is not enabled by default because of licensing reasons, but all you need to activate Readline is the following pair of lines.

     scheme@(guile-user)> (use-modules (ice-9 readline))
     scheme@(guile-user)> (activate-readline)

It's a good idea to put these two lines (without the scheme@(guile-user)> prompts) in your .guile file. See Init File, for more on .guile.

Value History
-------------

Just as Readline helps you to reuse a previous input line, value history allows you to use the result of a previous evaluation in a new expression.  When value history is enabled, each evaluation result is automatically assigned to the next in the sequence of variables $1, $2, ....  You can then use these variables in subsequent expressions.

     scheme@(guile-user)> (iota 10)
     $1 = (0 1 2 3 4 5 6 7 8 9)
     scheme@(guile-user)> (apply * (cdr $1))
     $2 = 362880
     scheme@(guile-user)> (sqrt $2)
     $3 = 602.3952191045344
     scheme@(guile-user)> (cons $2 $1)
     $4 = (362880 0 1 2 3 4 5 6 7 8 9)

Value history is enabled by default, because Guile's REPL imports the (ice-9 history) module. Value history may be turned off or on within the repl, using the options interface:

     scheme@(guile-user)> ,option value-history #f
     scheme@(guile-user)> 'foo
     foo
     scheme@(guile-user)> ,option value-history #t
     scheme@(guile-user)> 'bar
     $5 = bar

Note that previously recorded values are still accessible, even if value history is off. In rare cases, these references to past computations can cause Guile to use too much memory. One may clear these values, possibly enabling garbage collection, via the clear-value-history! procedure, described below.

The programmatic interface to value history is in a module:

     (use-modules (ice-9 history))

 -- Scheme Procedure: value-history-enabled?
     Return true iff value history is enabled.

 -- Scheme Procedure: enable-value-history!
     Turn on value history, if it was off.

 -- Scheme Procedure: disable-value-history!
     Turn off value history, if it was on.

 -- Scheme Procedure: clear-value-history!
     Clear the value history. If the stored values are not captured by some other data structure or closure, they may then be reclaimed by the garbage collector.

REPL Commands
-------------

The REPL exists to read expressions, evaluate them, and then print their results. But sometimes one wants to tell the REPL to evaluate an expression in a different way, or to do something else altogether. A user can affect the way the REPL works with a REPL command.

The previous section had an example of a command, in the form of ,option.

     scheme@(guile-user)> ,option value-history #t

Commands are distinguished from expressions by their initial comma (,). Since a comma cannot begin an expression in most languages, it is an effective indicator to the REPL that the following text forms a command, not an expression.

REPL commands are convenient because they are always there. Even if the current module doesn't have a binding for pretty-print, one can always ,pretty-print.

The following sections document the various commands, grouped together by functionality. Many of the commands have abbreviations; see the online help (,help) for more information.

Help Commands
.............

When Guile starts interactively, it notifies the user that help can be had by typing ,help. Indeed, help is a command, and a particularly useful one, as it allows the user to discover the rest of the commands.

 -- REPL Command: help [all | group | [-c] command]
     Show help.

     With one argument, tries to look up the argument as a group name, giving help on that group if successful. Otherwise tries to look up the argument as a command, giving help on the command.

     If there is a command whose name is also a group name, use the -c COMMAND form to give help on the command instead of the group.

     Without any argument, a list of help commands and command groups are displayed.

 -- REPL Command: show [topic]
     Gives information about Guile.

     With one argument, tries to show a particular piece of information; currently supported topics are `warranty' (or `w'), `copying' (or `c'), and `version' (or `v').

     Without any argument, a list of topics is displayed.

 -- REPL Command: apropos regexp
     Find bindings/modules/packages.

 -- REPL Command: describe obj
     Show description/documentation.

Module Commands
...............

 -- REPL Command: module [module]
     Change modules / Show current module.

 -- REPL Command: import module ...
     Import modules / List those imported.

 -- REPL Command: load file
     Load a file in the current module.

 -- REPL Command: reload [module]
     Reload the given module, or the current module if none was given.

 -- REPL Command: binding
     List current bindings.

 -- REPL Command: in module expression
 -- REPL Command: in module command arg ...
     Evaluate an expression, or alternatively, execute another meta-command in the context of a module.  For example, ,in (foo bar) ,binding will show the bindings in the module (foo bar).

Language Commands
.................

 -- REPL Command: language language
     Change languages.

Compile Commands
................

 -- REPL Command: compile exp
     Generate compiled code.

 -- REPL Command: compile-file file
     Compile a file.

 -- REPL Command: expand exp
     Expand any macros in a form.

 -- REPL Command: optimize exp
     Run the optimizer on a piece of code and print the result.

 -- REPL Command: disassemble exp
     Disassemble a compiled procedure.

 -- REPL Command: disassemble-file file
     Disassemble a file.

Profile Commands
................

 -- REPL Command: time exp
     Time execution.

 -- REPL Command: profile exp
     Profile execution.

 -- REPL Command: trace exp
     Trace execution.

Debug Commands
..............

These debugging commands are only available within a recursive REPL; they do not work at the top level.

 -- REPL Command: backtrace [count] [#:width w] [#:full? f]
     Print a backtrace.

     Print a backtrace of all stack frames, or innermost COUNT frames. If COUNT is negative, the last COUNT frames will be shown.

 -- REPL Command: up [count]
     Select a calling stack frame.

     Select and print stack frames that called this one. An argument says how many frames up to go.

 -- REPL Command: down [count]
     Select a called stack frame.

     Select and print stack frames called by this one. An argument says how many frames down to go.

 -- REPL Command: frame [idx]
     Show a frame.

     Show the selected frame.  With an argument, select a frame by index, then show it.

 -- REPL Command: procedure
     Print the procedure for the selected frame.

 -- REPL Command: locals
     Show local variables.

     Show locally-bound variables in the selected frame.

 -- REPL Command: error-message
 -- REPL Command: error
     Show error message.

     Display the message associated with the error that started the current debugging REPL.

 -- REPL Command: registers
     Show the VM registers associated with the current frame.

     See Stack Layout, for more information on VM stack frames.

 -- REPL Command: width [cols]
     Sets the number of display columns in the output of ,backtrace and ,locals to COLS.  If COLS is not given, the width of the terminal is used.

The next 3 commands work at any REPL.

 -- REPL Command: break proc
     Set a breakpoint at PROC.

 -- REPL Command: break-at-source file line
     Set a breakpoint at the given source location.

 -- REPL Command: tracepoint proc
     Set a tracepoint on the given procedure. This will cause all calls to the procedure to print out a tracing message. See Tracing Traps, for more information.

The rest of the commands in this subsection all apply only when the stack is continuable --- in other words when it makes sense for the program that the stack comes from to continue running.  Usually this means that the program stopped because of a trap or a breakpoint.

 -- REPL Command: step
     Tell the debugged program to step to the next source location.

 -- REPL Command: next
     Tell the debugged program to step to the next source location in the same frame.  (See Traps for the details of how this works.)

 -- REPL Command: finish
     Tell the program being debugged to continue running until the completion of the current stack frame, and at that time to print the result and reenter the REPL.

Inspect Commands
................

 -- REPL Command: inspect exp
     Inspect the result(s) of evaluating EXP.

 -- REPL Command: pretty-print exp
     Pretty-print the result(s) of evaluating EXP.

System Commands
...............

 -- REPL Command: gc
     Garbage collection.

 -- REPL Command: statistics
     Display statistics.

 -- REPL Command: option [key value]
     List/show/set options.

 -- REPL Command: quit
     Quit this session.

Current REPL options include:

compile-options
     The options used when compiling expressions entered at the REPL. See Compilation, for more on compilation options.

interp
     Whether to interpret or compile expressions given at the REPL, if such a choice is available.  Off by default (indicating compilation).

prompt
     A customized REPL prompt.  #f by default, indicating the default prompt.

value-history
     Whether value history is on or not.  See Value History.

on-error
     What to do when an error happens.  By default, debug, meaning to enter the debugger.  Other values include backtrace, to show a backtrace without entering the debugger, or report, to simply show a short error printout.

Default values for REPL options may be set using repl-default-option-set! from (system repl common):

 -- Scheme Procedure: repl-set-default-option! key value
     Set the default value of a REPL option.  This function is particularly useful in a user's init file.  See Init File.

Error Handling
--------------

When code being evaluated from the REPL hits an error, Guile enters a new prompt, allowing you to inspect the context of the error.

     scheme@(guile-user)> (map string-append '("a" "b") '("c" #\d))
     ERROR: In procedure string-append:
     ERROR: Wrong type (expecting string): #\d
     Entering a new prompt.  Type `,bt' for a backtrace or `,q' to continue.
     scheme@(guile-user) [1]>

The new prompt runs inside the old one, in the dynamic context of the error.  It is a recursive REPL, augmented with a reified representation of the stack, ready for debugging.

,backtrace (abbreviated ,bt) displays the Scheme call stack at the point where the error occurred:

     scheme@(guile-user) [1]> ,bt
                1 (map #<procedure string-append _> ("a" "b") ("c" #\d))
                0 (string-append "b" #\d)

In the above example, the backtrace doesn't have much source information, as map and string-append are both primitives. But in the general case, the space on the left of the backtrace indicates the line and column in which a given procedure calls another.

You can exit a recursive REPL in the same way that you exit any REPL: via (quit), ,quit (abbreviated ,q), or C-d, among other options.

Interactive Debugging
---------------------

A recursive debugging REPL exposes a number of other meta-commands that inspect the state of the computation at the time of the error. These commands allow you to

  * display the Scheme call stack at the point where the error occurred;

  * move up and down the call stack, to see in detail the expression being evaluated, or the procedure being applied, in each frame; and

  * examine the values of variables and expressions in the context of each frame.

See Debug Commands, for documentation of the individual commands. This section aims to give more of a walkthrough of a typical debugging session.

First, we're going to need a good error. Let's try to macroexpand the expression (unquote foo), outside of a quasiquote form, and see how the macroexpander reports this error.

     scheme@(guile-user)> (macroexpand '(unquote foo))
     ERROR: In procedure macroexpand:
     ERROR: unquote: expression not valid outside of quasiquote in (unquote foo)
     Entering a new prompt.  Type `,bt' for a backtrace or `,q' to continue.
     scheme@(guile-user) [1]>

The backtrace command, which can also be invoked as bt, displays the call stack (aka backtrace) at the point where the debugger was entered:

     scheme@(guile-user) [1]> ,bt
     In ice-9/psyntax.scm:
       1130:21  3 (chi-top (unquote foo) () ((top)) e (eval) (hygiene #))
       1071:30  2 (syntax-type (unquote foo) () ((top)) #f #f (# #) #f)
       1368:28  1 (chi-macro #<procedure de9360 at ice-9/psyntax.scm...> ...)
     In unknown file:
                0 (scm-error syntax-error macroexpand "~a: ~a in ~a" # #f)

A call stack consists of a sequence of stack frames, with each frame describing one procedure which is waiting to do something with the values returned by another. Here we see that there are four frames on the stack.

Note that macroexpand is not on the stack -- it must have made a tail call to chi-top, as indeed we would find if we searched ice-9/psyntax.scm for its definition.

When you enter the debugger, the innermost frame is selected, which means that the commands for getting information about the ``current'' frame, or for evaluating expressions in the context of the current frame, will do so by default with respect to the innermost frame.  To select a different frame, so that these operations will apply to it instead, use the up, down and frame commands like this:

     scheme@(guile-user) [1]> ,up
     In ice-9/psyntax.scm:
       1368:28  1 (chi-macro #<procedure de9360 at ice-9/psyntax.scm...> ...)
     scheme@(guile-user) [1]> ,frame 3
     In ice-9/psyntax.scm:
       1130:21  3 (chi-top (unquote foo) () ((top)) e (eval) (hygiene #))
     scheme@(guile-user) [1]> ,down
     In ice-9/psyntax.scm:
       1071:30  2 (syntax-type (unquote foo) () ((top)) #f #f (# #) #f)

Perhaps we're interested in what's going on in frame 2, so we take a look at its local variables:

     scheme@(guile-user) [1]> ,locals
       Local variables:
       $1 = e = (unquote foo)
       $2 = r = ()
       $3 = w = ((top))
       $4 = s = #f
       $5 = rib = #f
       $6 = mod = (hygiene guile-user)
       $7 = for-car? = #f
       $8 = first = unquote
       $9 = ftype = macro
       $10 = fval = #<procedure de9360 at ice-9/psyntax.scm:2817:2 (x)>
       $11 = fe = unquote
       $12 = fw = ((top))
       $13 = fs = #f
       $14 = fmod = (hygiene guile-user)

All of the values are accessible by their value-history names ($N):

     scheme@(guile-user) [1]> $10
     $15 = #<procedure de9360 at ice-9/psyntax.scm:2817:2 (x)>

We can even invoke the procedure at the REPL directly:

     scheme@(guile-user) [1]> ($10 'not-going-to-work)
     ERROR: In procedure macroexpand:
     ERROR: source expression failed to match any pattern in not-going-to-work
     Entering a new prompt.  Type `,bt' for a backtrace or `,q' to continue.

Well at this point we've caused an error within an error. Let's just quit back to the top level:

     scheme@(guile-user) [2]> ,q
     scheme@(guile-user) [1]> ,q
     scheme@(guile-user)>

Finally, as a word to the wise: hackers close their REPL prompts with C-d.

Using Guile in Emacs
====================

Any text editor can edit Scheme, but some are better than others.  Emacs is the best, of course, and not just because it is a fine text editor. Emacs has good support for Scheme out of the box, with sensible indentation rules, parenthesis-matching, syntax highlighting, and even a set of keybindings for structural editing, allowing navigation, cut-and-paste, and transposition operations that work on balanced S-expressions.

As good as it is, though, two things will vastly improve your experience with Emacs and Guile.

The first is Taylor Campbell's Paredit (http://www.emacswiki.org/emacs/ParEdit).  You should not code in any dialect of Lisp without Paredit.  (They say that unopinionated writing is boring---hence this tone---but it's the truth, regardless.)  Paredit is the bee's knees.

The second is José Antonio Ortega Ruiz's Geiser (http://www.nongnu.org/geiser/).  Geiser complements Emacs' scheme-mode with tight integration to running Guile processes via a comint-mode REPL buffer.

Of course there are keybindings to switch to the REPL, and a good REPL environment, but Geiser goes beyond that, providing:

  * Form evaluation in the context of the current file's module.

  * Macro expansion.

  * File/module loading and/or compilation.

  * Namespace-aware identifier completion (including local bindings, names visible in the current module, and module names).

  * Autodoc: the echo area shows information about the signature of the procedure/macro around point automatically.

  * Jump to definition of identifier at point.

  * Access to documentation (including docstrings when the implementation provides it).

  * Listings of identifiers exported by a given module.

  * Listings of callers/callees of procedures.

  * Rudimentary support for debugging and error navigation.

  * Support for multiple, simultaneous REPLs.

See Geiser's web page at http://www.nongnu.org/geiser/, for more information.

Using Guile Tools
=================

Guile also comes with a growing number of command-line utilities: a compiler, a disassembler, some module inspectors, and in the future, a system to install Guile packages from the internet.  These tools may be invoked using the guild program.

     $ guild compile -o foo.go foo.scm
     wrote `foo.go'

This program used to be called guile-tools up to Guile version 2.0.1, and for backward compatibility it still may be called as such.  However we changed the name to guild, not only because it is pleasantly shorter and easier to read, but also because this tool will serve to bind Guile wizards together, by allowing hackers to share code with each other using a CPAN-like system.

See Compilation, for more on guild compile.

A complete list of guild scripts can be had by invoking guild list, or simply guild.

Installing Site Packages
========================

At some point, you will probably want to share your code with other people.  To do so effectively, it is important to follow a set of common conventions, to make it easy for the user to install and use your package.

The first thing to do is to install your Scheme files where Guile can find them.  When Guile goes to find a Scheme file, it will search a load path to find the file: first in Guile's own path, then in paths for site packages.  A site package is any Scheme code that is installed and not part of Guile itself.  See Load Paths, for more on load paths.

There are several site paths, for historical reasons, but the one that should generally be used can be obtained by invoking the %site-dir procedure.  See Build Config.  If Guile EFFECTIVE-VERSION is installed on your system in /usr/, then (%site-dir) will be /usr/share/guile/site/EFFECTIVE-VERSION.  Scheme files should be installed there.

If you do not install compiled .go files, Guile will compile your modules and programs when they are first used, and cache them in the user's home directory.  See Compilation, for more on auto-compilation.  However, it is better to compile the files before they are installed, and to just copy the files to a place that Guile can find them.

As with Scheme files, Guile searches a path to find compiled .go files, the %load-compiled-path.  By default, this path has two entries: a path for Guile's files, and a path for site packages.  You should install your .go files into the latter.  Currently there is no procedure to get at this path, which is probably a bug.  As in the previous example, if Guile EFFECTIVE-VERSION is installed on your system in /usr/, then the place to put compiled files for site packages will be /usr/lib/guile/EFFECTIVE-VERSION/site-ccache.

Note that a .go file will only be loaded in preference to a .scm file if it is newer.  For that reason, you should install your Scheme files first, and your compiled files second.  Load Paths, for more on the loading process.

Finally, although this section is only about Scheme, sometimes you need to install C extensions too.  Shared libraries should be installed in the extensions dir.  This value can be had from the build config (see Build Config).  Again, if Guile EFFECTIVE-VERSION is installed on your system in /usr/, then the extensions dir will be /usr/lib/guile/EFFECTIVE-VERSION/extensions.