@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 2006, 2010, 2011, 2012
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node Using Guile Interactively
@section Using Guile Interactively

When you start up Guile by typing just @code{guile}, without a
@code{-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.

@lisp
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
@end lisp

@noindent
This mode of use is called a @dfn{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 @code{scheme}, and the current module is
@code{(guile-user)}. @xref{Other Languages}, for more information on Guile's
support for languages other than Scheme.

@menu
* Init File::
* Readline::                    
* Value History::              
* REPL Commands::               
* Error Handling::              
* Interactive Debugging::       
@end menu


@node Init File
@subsection The Init File, @file{~/.guile}

@cindex .guile
When run interactively, Guile will load a local initialization file from
@file{~/.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 @code{-q}
command-line option.


@node Readline
@subsection 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.

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

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


@node Value History
@subsection Value History

Just as Readline helps you to reuse a previous input line, @dfn{value
history} allows you to use the @emph{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
@code{$1}, @code{$2}, @dots{}.  You can then use these variables in
subsequent expressions.

@lisp
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)
@end lisp

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

@lisp
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
@end lisp

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 @code{clear-value-history!} procedure, described below.

The programmatic interface to value history is in a module:

@lisp
(use-modules (ice-9 history))
@end lisp

@deffn {Scheme Procedure} value-history-enabled?
Return true iff value history is enabled.
@end deffn

@deffn {Scheme Procedure} enable-value-history!
Turn on value history, if it was off.
@end deffn

@deffn {Scheme Procedure} disable-value-history!
Turn off value history, if it was on.
@end deffn

@deffn {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.
@end deffn


@node REPL Commands
@subsection REPL Commands

@cindex 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 @dfn{REPL command}.

The previous section had an example of a command, in the form of
@code{,option}.

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

@noindent
Commands are distinguished from expressions by their initial comma
(@samp{,}). 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 @code{pretty-print}, one can
always @code{,pretty-print}.

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

@menu
* Help Commands::               
* Module Commands::             
* Language Commands::           
* Compile Commands::            
* Profile Commands::            
* Debug Commands::              
* Inspect Commands::            
* System Commands::             
@end menu

@node Help Commands
@subsubsection Help Commands

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

@deffn {REPL Command} help [@code{all} | group | @code{[-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 @samp{-c
@var{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.
@end deffn

@deffn {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.
@end deffn

@deffn {REPL Command} apropos regexp
Find bindings/modules/packages.
@end deffn

@deffn {REPL Command} describe obj
Show description/documentation.
@end deffn

@node Module Commands
@subsubsection Module Commands

@deffn {REPL Command} module [module]
Change modules / Show current module.
@end deffn

@deffn {REPL Command} import module @dots{}
Import modules / List those imported.
@end deffn

@deffn {REPL Command} load file
Load a file in the current module.
@end deffn

@deffn {REPL Command} reload [module]
Reload the given module, or the current module if none was given.
@end deffn

@deffn {REPL Command} binding
List current bindings.
@end deffn

@deffn {REPL Command} in module expression
@deffnx {REPL Command} in module command arg @dots{}
Evaluate an expression, or alternatively, execute another meta-command
in the context of a module.  For example, @samp{,in (foo bar) ,binding}
will show the bindings in the module @code{(foo bar)}.
@end deffn

@node Language Commands
@subsubsection Language Commands

@deffn {REPL Command} language language
Change languages.
@end deffn

@node Compile Commands
@subsubsection Compile Commands

@deffn {REPL Command} compile exp
Generate compiled code.
@end deffn

@deffn {REPL Command} compile-file file
Compile a file.
@end deffn

@deffn {REPL Command} expand exp
Expand any macros in a form.
@end deffn

@deffn {REPL Command} optimize exp
Run the optimizer on a piece of code and print the result.
@end deffn

@deffn {REPL Command} disassemble exp
Disassemble a compiled procedure.
@end deffn

@deffn {REPL Command} disassemble-file file
Disassemble a file.
@end deffn

@node Profile Commands
@subsubsection Profile Commands

@deffn {REPL Command} time exp
Time execution.
@end deffn

@deffn {REPL Command} profile exp
Profile execution.
@end deffn

@deffn {REPL Command} trace exp
Trace execution.
@end deffn

@node Debug Commands
@subsubsection Debug Commands

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

@deffn {REPL Command} backtrace [count] [#:width w] [#:full? f]
Print a backtrace.

Print a backtrace of all stack frames, or innermost @var{count} frames.
If @var{count} is negative, the last @var{count} frames will be shown.
@end deffn

@deffn {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.
@end deffn

@deffn {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.
@end deffn

@deffn {REPL Command} frame [idx]
Show a frame.

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

@deffn {REPL Command} procedure
Print the procedure for the selected frame.
@end deffn

@deffn {REPL Command} locals
Show local variables.

Show locally-bound variables in the selected frame.
@end deffn

@deffn {REPL Command} error-message
@deffnx {REPL Command} error
Show error message.

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

@deffn {REPL Command} registers
Show the VM registers associated with the current frame.

@xref{Stack Layout}, for more information on VM stack frames.
@end deffn

@deffn {REPL Command} width [cols]
Sets the number of display columns in the output of @code{,backtrace}
and @code{,locals} to @var{cols}.  If @var{cols} is not given, the width
of the terminal is used.
@end deffn

The next 3 commands work at any REPL.

@deffn {REPL Command} break proc
Set a breakpoint at @var{proc}.
@end deffn

@deffn {REPL Command} break-at-source file line
Set a breakpoint at the given source location.
@end deffn

@deffn {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. @xref{Tracing Traps}, for
more information.
@end deffn

The rest of the commands in this subsection all apply only when the
stack is @dfn{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.

@deffn {REPL Command} step
Tell the debugged program to step to the next source location.
@end deffn

@deffn {REPL Command} next
Tell the debugged program to step to the next source location in the
same frame.  (See @ref{Traps} for the details of how this works.)
@end deffn

@deffn {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.
@end deffn


@node Inspect Commands
@subsubsection Inspect Commands

@deffn {REPL Command} inspect exp
Inspect the result(s) of evaluating @var{exp}.
@end deffn

@deffn {REPL Command} pretty-print exp
Pretty-print the result(s) of evaluating @var{exp}.
@end deffn

@node System Commands
@subsubsection System Commands

@deffn {REPL Command} gc
Garbage collection.
@end deffn

@deffn {REPL Command} statistics
Display statistics.
@end deffn

@deffn {REPL Command} option [key value]
List/show/set options.
@end deffn

@deffn {REPL Command} quit
Quit this session.
@end deffn

Current REPL options include:

@table @code
@item compile-options
The options used when compiling expressions entered at the REPL.
@xref{Compilation}, for more on compilation options.
@item interp
Whether to interpret or compile expressions given at the REPL, if such a
choice is available.  Off by default (indicating compilation).
@item prompt
A customized REPL prompt.  @code{#f} by default, indicating the default
prompt.
@item value-history
Whether value history is on or not.  @xref{Value History}.
@item on-error
What to do when an error happens.  By default, @code{debug}, meaning to
enter the debugger.  Other values include @code{backtrace}, to show a
backtrace without entering the debugger, or @code{report}, to simply
show a short error printout.
@end table

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

@deffn {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.  @xref{Init File}.
@end deffn


@node Error Handling
@subsection 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.

@lisp
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]>
@end lisp

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.

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

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

In the above example, the backtrace doesn't have much source
information, as @code{map} and @code{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 @samp{(quit)}, @samp{,quit} (abbreviated @samp{,q}), or
@kbd{C-d}, among other options.


@node Interactive Debugging
@subsection 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

@itemize @bullet
@item
display the Scheme call stack at the point where the error occurred;

@item
move up and down the call stack, to see in detail the expression being
evaluated, or the procedure being applied, in each @dfn{frame}; and

@item
examine the values of variables and expressions in the context of each
frame.
@end itemize

@noindent
@xref{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 @code{(unquote foo)}, outside of a @code{quasiquote} form,
and see how the macroexpander reports this error.

@lisp
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]>
@end lisp

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

@lisp
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)
@end lisp

A call stack consists of a sequence of stack @dfn{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 @code{macroexpand} is not on the stack -- it must have made a
tail call to @code{chi-top}, as indeed we would find if we searched
@code{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 @code{up}, @code{down} and @code{frame} commands like
this:

@lisp
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)
@end lisp

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

@lisp
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)
@end lisp

All of the values are accessible by their value-history names
(@code{$@var{n}}):

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

We can even invoke the procedure at the REPL directly:

@lisp
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.
@end lisp

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

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

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


@node Using Guile in Emacs
@section Using Guile in Emacs

@cindex 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.

@cindex Paredit
The first is Taylor Campbell's
@uref{http://www.emacswiki.org/emacs/ParEdit, 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.

@cindex Geiser
The second is
@iftex
Jos@'e
@end iftex
@ifnottex
José
@end ifnottex
Antonio Ortega Ruiz's
@uref{http://www.nongnu.org/geiser/, Geiser}.  Geiser complements Emacs'
@code{scheme-mode} with tight integration to running Guile processes via
a @code{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:

@itemize @bullet
@item
Form evaluation in the context of the current file's module.
@item
Macro expansion.
@item
File/module loading and/or compilation.
@item
Namespace-aware identifier completion (including local bindings, names
visible in the current module, and module names).
@item
Autodoc: the echo area shows information about the signature of the
procedure/macro around point automatically.
@item
Jump to definition of identifier at point.
@item
Access to documentation (including docstrings when the implementation
provides it).
@item
Listings of identifiers exported by a given module.
@item
Listings of callers/callees of procedures.
@item
Rudimentary support for debugging and error navigation.
@item
Support for multiple, simultaneous REPLs.
@end itemize

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


@node Using Guile Tools
@section Using Guile Tools

@cindex guild
@cindex guile-tools
@cindex wizards
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 @code{guild} program.

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

This program used to be called @code{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 @code{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.

@xref{Compilation}, for more on @code{guild compile}.

A complete list of guild scripts can be had by invoking @code{guild
list}, or simply @code{guild}.


@node Installing Site Packages
@section Installing Site Packages

@cindex site
@cindex site path
@cindex load path
@findex %site-dir

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
@dfn{load path} to find the file: first in Guile's own path, then in
paths for @dfn{site packages}.  A site package is any Scheme code that
is installed and not part of Guile itself.  @xref{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
@code{%site-dir} procedure.  @xref{Build Config}.  If Guile
@value{EFFECTIVE-VERSION} is installed on your system in @code{/usr/},
then @code{(%site-dir)} will be
@code{/usr/share/guile/site/@value{EFFECTIVE-VERSION}}.  Scheme files
should be installed there.

If you do not install compiled @code{.go} files, Guile will compile your
modules and programs when they are first used, and cache them in the
user's home directory.  @xref{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 @code{.go}
files, the @code{%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 @code{.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 @value{EFFECTIVE-VERSION} is installed on
your system in @code{/usr/}, then the place to put compiled files for
site packages will be
@code{/usr/lib/guile/@value{EFFECTIVE-VERSION}/site-ccache}.

Note that a @code{.go} file will only be loaded in preference to a
@code{.scm} file if it is newer.  For that reason, you should install
your Scheme files first, and your compiled files second.  @code{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 @dfn{extensions dir}.  This value can be had from the build config
(@pxref{Build Config}).  Again, if Guile @value{EFFECTIVE-VERSION} is
installed on your system in @code{/usr/}, then the extensions dir will
be @code{/usr/lib/guile/@value{EFFECTIVE-VERSION}/extensions}.


@c Local Variables:
@c TeX-master: "guile.texi"
@c End:
