update URI documentation
[bpt/guile.git] / doc / ref / scheme-scripts.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
049ec202 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2010
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
07d83abe
MV
7@node Guile Scripting
8@section Guile Scripting
9
10Like AWK, Perl, or any shell, Guile can interpret script files. A Guile
11script is simply a file of Scheme code with some extra information at
12the beginning which tells the operating system how to invoke Guile, and
13then tells Guile how to handle the Scheme code.
14
15@menu
16* The Top of a Script File:: How to start a Guile script.
17* Invoking Guile:: Command line options understood by Guile.
18* The Meta Switch:: Passing complex argument lists to Guile
19 from shell scripts.
20* Command Line Handling:: Accessing the command line from a script.
21* Scripting Examples::
22@end menu
23
24
25@node The Top of a Script File
26@subsection The Top of a Script File
27
28The first line of a Guile script must tell the operating system to use
29Guile to evaluate the script, and then tell Guile how to go about doing
30that. Here is the simplest case:
31
32@itemize @bullet
33
34@item
35The first two characters of the file must be @samp{#!}.
36
37The operating system interprets this to mean that the rest of the line
38is the name of an executable that can interpret the script. Guile,
39however, interprets these characters as the beginning of a multi-line
40comment, terminated by the characters @samp{!#} on a line by themselves.
41(This is an extension to the syntax described in R5RS, added to support
42shell scripts.)
43
44@item
45Immediately after those two characters must come the full pathname to
46the Guile interpreter. On most systems, this would be
47@samp{/usr/local/bin/guile}.
48
49@item
50Then must come a space, followed by a command-line argument to pass to
51Guile; this should be @samp{-s}. This switch tells Guile to run a
52script, instead of soliciting the user for input from the terminal.
53There are more elaborate things one can do here; see @ref{The Meta
54Switch}.
55
56@item
57Follow this with a newline.
58
59@item
60The second line of the script should contain only the characters
61@samp{!#} --- just like the top of the file, but reversed. The
62operating system never reads this far, but Guile treats this as the end
63of the comment begun on the first line by the @samp{#!} characters.
64
8748ffea
MG
65@item
66If this source code file is not ASCII or ISO-8859-1 encoded, a coding
67declaration such as @code{coding: utf-8} should appear in a comment
68somewhere in the first five lines of the file: see @ref{Character
69Encoding of Source Files}.
70
07d83abe
MV
71@item
72The rest of the file should be a Scheme program.
73
74@end itemize
75
76Guile reads the program, evaluating expressions in the order that they
77appear. Upon reaching the end of the file, Guile exits.
78
79
80@node Invoking Guile
81@subsection Invoking Guile
44fd0a72 82@cindex invocation
07d83abe
MV
83
84Here we describe Guile's command-line processing in detail. Guile
85processes its arguments from left to right, recognizing the switches
86described below. For examples, see @ref{Scripting Examples}.
87
88@table @code
89
90@item -s @var{script} @var{arg...}
91Read and evaluate Scheme source code from the file @var{script}, as the
92@code{load} function would. After loading @var{script}, exit. Any
93command-line arguments @var{arg...} following @var{script} become the
94script's arguments; the @code{command-line} function returns a list of
95strings of the form @code{(@var{script} @var{arg...})}.
96
97@item -c @var{expr} @var{arg...}
98Evaluate @var{expr} as Scheme code, and then exit. Any command-line
99arguments @var{arg...} following @var{expr} become command-line arguments; the
100@code{command-line} function returns a list of strings of the form
101@code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
102Guile executable.
103
104@item -- @var{arg...}
105Run interactively, prompting the user for expressions and evaluating
106them. Any command-line arguments @var{arg...} following the @code{--}
107become command-line arguments for the interactive session; the
108@code{command-line} function returns a list of strings of the form
109@code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
110Guile executable.
111
fcb8ba8c
MV
112@item -L @var{directory}
113Add @var{directory} to the front of Guile's module load path. The
114given directories are searched in the order given on the command line
115and before any directories in the GUILE_LOAD_PATH environment
116variable. Paths added here are @emph{not} in effect during execution
117of the user's @file{.guile} file.
118
b710608c
AR
119@item -x @var{extension}
120Add @var{extension} to the front of Guile's load extension list
121(@pxref{Loading, @code{%load-extensions}}). The specified extensions
122are tried in the order given on the command line, and before the default
123load extensions. Extensions added here are @emph{not} in effect during
124execution of the user's @file{.guile} file.
125
07d83abe
MV
126@item -l @var{file}
127Load Scheme source code from @var{file}, and continue processing the
128command line.
129
130@item -e @var{function}
131Make @var{function} the @dfn{entry point} of the script. After loading
132the script file (with @code{-s}) or evaluating the expression (with
133@code{-c}), apply @var{function} to a list containing the program name
134and the command-line arguments --- the list provided by the
135@code{command-line} function.
136
137A @code{-e} switch can appear anywhere in the argument list, but Guile
138always invokes the @var{function} as the @emph{last} action it performs.
139This is weird, but because of the way script invocation works under
140POSIX, the @code{-s} option must always come last in the list.
141
142The @var{function} is most often a simple symbol that names a function
143that is defined in the script. It can also be of the form @code{(@@
144@var{module-name} @var{symbol})} and in that case, the symbol is
145looked up in the module named @var{module-name}.
146
e70c841f
MV
147For compatibility with some versions of Guile 1.4, you can also use the
148form @code{(symbol ...)} (that is, a list of only symbols that doesn't
149start with @code{@@}), which is equivalent to @code{(@@ (symbol ...)
150main)}, or @code{(symbol ...) symbol} (that is, a list of only symbols
151followed by a symbol), which is equivalent to @code{(@@ (symbol ...)
152symbol)}. We recommend to use the equivalent forms directly since they
72b3aa56 153correspond to the @code{(@@ ...)} read syntax that can be used in
e70c841f
MV
154normal code, @xref{Using Guile Modules}.
155
07d83abe
MV
156@xref{Scripting Examples}.
157
158@item -ds
159Treat a final @code{-s} option as if it occurred at this point in the
160command line; load the script here.
161
162This switch is necessary because, although the POSIX script invocation
163mechanism effectively requires the @code{-s} option to appear last, the
164programmer may well want to run the script before other actions
165requested on the command line. For examples, see @ref{Scripting
166Examples}.
167
168@item \
169Read more command-line arguments, starting from the second line of the
170script file. @xref{The Meta Switch}.
171
07d83abe
MV
172@item --use-srfi=@var{list}
173The option @code{--use-srfi} expects a comma-separated list of numbers,
174each representing a SRFI number to be loaded into the interpreter
175before starting evaluating a script file or the REPL. Additionally,
176the feature identifier for the loaded SRFIs is recognized by
177`cond-expand' when using this option.
178
179@example
180guile --use-srfi=8,13
181@end example
182
183@item --debug
a43b4d6e
AW
184Start with the debugging virtual machine engine. Using the debugging VM
185will enable support for VM hooks, which are needed for tracing,
186breakpoints, and accurate call counts when profiling. The debugging VM
187is slower than the regular VM, though, by about 10 percent. @xref{VM
188Hooks}, for more information.
189
190By default, the debugging VM engine is only used when entering an
191interactive session. When executing a script with @code{-s} or
192@code{-c}, the normal, faster VM is used by default.
07d83abe
MV
193
194@vnew{1.8}
195@item --no-debug
a43b4d6e 196Do not use the debugging VM engine, even when entering an interactive
07d83abe
MV
197session.
198
f88dae81
AW
199@item --listen[=@var{p}]
200While this program runs, listen on a local port or a path for REPL
201clients. If @var{p} starts with a number, it is assumed to be a local
202port on which to listen. If it starts with a forward slash, it is
203assumed to be a path to a UNIX domain socket on which to listen.
204
205If @var{p} is not given, the default is local port 37146. If you look
206at it upside down, it almost spells ``Guile''. If you have netcat
207installed, you should be able to @kbd{nc localhost 37146} and get a
208Guile prompt. Alternately you can fire up Emacs and connect to the
ced9917e 209process; see @ref{Using Guile in Emacs} for more details.
f88dae81
AW
210
211Note that opening a port allows anyone who can connect to that port---in
212the TCP case, any local user---to do anything Guile can do, as the user
213that the Guile process is running as. Don't use @option{--listen} on
ced9917e
AW
214multi-user machines. Of course, if you don't pass @option{--listen} to
215Guile, no port will be opened.
f88dae81
AW
216
217That said, @code{--listen} is great for interactive debugging and
218development.
219
220@vnew{2.0}
07d83abe
MV
221@item -h@r{, }--help
222Display help on invoking Guile, and then exit.
223
224@item -v@r{, }--version
225Display the current version of Guile, and then exit.
226
227@end table
228
229
230@node The Meta Switch
231@subsection The Meta Switch
232
233Guile's command-line switches allow the programmer to describe
234reasonably complicated actions in scripts. Unfortunately, the POSIX
235script invocation mechanism only allows one argument to appear on the
236@samp{#!} line after the path to the Guile executable, and imposes
237arbitrary limits on that argument's length. Suppose you wrote a script
238starting like this:
239@example
240#!/usr/local/bin/guile -e main -s
241!#
242(define (main args)
243 (map (lambda (arg) (display arg) (display " "))
244 (cdr args))
245 (newline))
246@end example
247The intended meaning is clear: load the file, and then call @code{main}
248on the command-line arguments. However, the system will treat
249everything after the Guile path as a single argument --- the string
250@code{"-e main -s"} --- which is not what we want.
251
252As a workaround, the meta switch @code{\} allows the Guile programmer to
253specify an arbitrary number of options without patching the kernel. If
254the first argument to Guile is @code{\}, Guile will open the script file
255whose name follows the @code{\}, parse arguments starting from the
256file's second line (according to rules described below), and substitute
257them for the @code{\} switch.
258
259Working in concert with the meta switch, Guile treats the characters
260@samp{#!} as the beginning of a comment which extends through the next
261line containing only the characters @samp{!#}. This sort of comment may
262appear anywhere in a Guile program, but it is most useful at the top of
263a file, meshing magically with the POSIX script invocation mechanism.
264
265Thus, consider a script named @file{/u/jimb/ekko} which starts like this:
266@example
267#!/usr/local/bin/guile \
268-e main -s
269!#
270(define (main args)
271 (map (lambda (arg) (display arg) (display " "))
272 (cdr args))
273 (newline))
274@end example
275
276Suppose a user invokes this script as follows:
277@example
278$ /u/jimb/ekko a b c
279@end example
280
281Here's what happens:
282@itemize @bullet
283
284@item
285the operating system recognizes the @samp{#!} token at the top of the
286file, and rewrites the command line to:
287@example
288/usr/local/bin/guile \ /u/jimb/ekko a b c
289@end example
290This is the usual behavior, prescribed by POSIX.
291
292@item
293When Guile sees the first two arguments, @code{\ /u/jimb/ekko}, it opens
294@file{/u/jimb/ekko}, parses the three arguments @code{-e}, @code{main},
295and @code{-s} from it, and substitutes them for the @code{\} switch.
296Thus, Guile's command line now reads:
297@example
298/usr/local/bin/guile -e main -s /u/jimb/ekko a b c
299@end example
300
301@item
302Guile then processes these switches: it loads @file{/u/jimb/ekko} as a
303file of Scheme code (treating the first three lines as a comment), and
304then performs the application @code{(main "/u/jimb/ekko" "a" "b" "c")}.
305
306@end itemize
307
308
309When Guile sees the meta switch @code{\}, it parses command-line
310argument from the script file according to the following rules:
311@itemize @bullet
312
313@item
314Each space character terminates an argument. This means that two
315spaces in a row introduce an argument @code{""}.
316
317@item
318The tab character is not permitted (unless you quote it with the
319backslash character, as described below), to avoid confusion.
320
321@item
322The newline character terminates the sequence of arguments, and will
323also terminate a final non-empty argument. (However, a newline
324following a space will not introduce a final empty-string argument;
325it only terminates the argument list.)
326
327@item
328The backslash character is the escape character. It escapes backslash,
329space, tab, and newline. The ANSI C escape sequences like @code{\n} and
330@code{\t} are also supported. These produce argument constituents; the
331two-character combination @code{\n} doesn't act like a terminating
332newline. The escape sequence @code{\@var{NNN}} for exactly three octal
333digits reads as the character whose ASCII code is @var{NNN}. As above,
334characters produced this way are argument constituents. Backslash
335followed by other characters is not allowed.
336
337@end itemize
338
339
340@node Command Line Handling
341@subsection Command Line Handling
342
343@c This section was written and contributed by Martin Grabmueller.
344
345The ability to accept and handle command line arguments is very
346important when writing Guile scripts to solve particular problems, such
347as extracting information from text files or interfacing with existing
348command line applications. This chapter describes how Guile makes
349command line arguments available to a Guile script, and the utilities
350that Guile provides to help with the processing of command line
351arguments.
352
353When a Guile script is invoked, Guile makes the command line arguments
354accessible via the procedure @code{command-line}, which returns the
355arguments as a list of strings.
356
357For example, if the script
358
359@example
360#! /usr/local/bin/guile -s
361!#
362(write (command-line))
363(newline)
364@end example
365
366@noindent
367is saved in a file @file{cmdline-test.scm} and invoked using the command
368line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}, the output
369is
370
371@example
372("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")
373@end example
374
375If the script invocation includes a @code{-e} option, specifying a
376procedure to call after loading the script, Guile will call that
377procedure with @code{(command-line)} as its argument. So a script that
378uses @code{-e} doesn't need to refer explicitly to @code{command-line}
379in its code. For example, the script above would have identical
380behaviour if it was written instead like this:
381
382@example
383#! /usr/local/bin/guile \
384-e main -s
385!#
386(define (main args)
387 (write args)
388 (newline))
389@end example
390
391(Note the use of the meta switch @code{\} so that the script invocation
392can include more than one Guile option: @xref{The Meta Switch}.)
393
394These scripts use the @code{#!} POSIX convention so that they can be
395executed using their own file names directly, as in the example command
396line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}. But they
397can also be executed by typing out the implied Guile command line in
398full, as in:
399
400@example
401$ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob
402@end example
403
404@noindent
405or
406
407@example
408$ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob
409@end example
410
411Even when a script is invoked using this longer form, the arguments that
412the script receives are the same as if it had been invoked using the
413short form. Guile ensures that the @code{(command-line)} or @code{-e}
414arguments are independent of how the script is invoked, by stripping off
415the arguments that Guile itself processes.
416
417A script is free to parse and handle its command line arguments in any
418way that it chooses. Where the set of possible options and arguments is
419complex, however, it can get tricky to extract all the options, check
420the validity of given arguments, and so on. This task can be greatly
421simplified by taking advantage of the module @code{(ice-9 getopt-long)},
422which is distributed with Guile, @xref{getopt-long}.
423
424
425@node Scripting Examples
426@subsection Scripting Examples
427
428To start with, here are some examples of invoking Guile directly:
429
430@table @code
431
432@item guile -- a b c
433Run Guile interactively; @code{(command-line)} will return @*
434@code{("/usr/local/bin/guile" "a" "b" "c")}.
435
436@item guile -s /u/jimb/ex2 a b c
437Load the file @file{/u/jimb/ex2}; @code{(command-line)} will return @*
438@code{("/u/jimb/ex2" "a" "b" "c")}.
439
440@item guile -c '(write %load-path) (newline)'
441Write the value of the variable @code{%load-path}, print a newline,
442and exit.
443
444@item guile -e main -s /u/jimb/ex4 foo
445Load the file @file{/u/jimb/ex4}, and then call the function
446@code{main}, passing it the list @code{("/u/jimb/ex4" "foo")}.
447
448@item guile -l first -ds -l last -s script
449Load the files @file{first}, @file{script}, and @file{last}, in that
450order. The @code{-ds} switch says when to process the @code{-s}
451switch. For a more motivated example, see the scripts below.
452
453@end table
454
455
456Here is a very simple Guile script:
457@example
458#!/usr/local/bin/guile -s
459!#
460(display "Hello, world!")
461(newline)
462@end example
463The first line marks the file as a Guile script. When the user invokes
464it, the system runs @file{/usr/local/bin/guile} to interpret the script,
465passing @code{-s}, the script's filename, and any arguments given to the
466script as command-line arguments. When Guile sees @code{-s
467@var{script}}, it loads @var{script}. Thus, running this program
468produces the output:
469@example
470Hello, world!
471@end example
472
473Here is a script which prints the factorial of its argument:
474@example
475#!/usr/local/bin/guile -s
476!#
477(define (fact n)
478 (if (zero? n) 1
479 (* n (fact (- n 1)))))
480
481(display (fact (string->number (cadr (command-line)))))
482(newline)
483@end example
484In action:
485@example
e03d9636 486$ ./fact 5
07d83abe
MV
487120
488$
489@end example
490
491However, suppose we want to use the definition of @code{fact} in this
492file from another script. We can't simply @code{load} the script file,
493and then use @code{fact}'s definition, because the script will try to
494compute and display a factorial when we load it. To avoid this problem,
495we might write the script this way:
496
497@example
498#!/usr/local/bin/guile \
499-e main -s
500!#
501(define (fact n)
502 (if (zero? n) 1
503 (* n (fact (- n 1)))))
504
505(define (main args)
506 (display (fact (string->number (cadr args))))
507 (newline))
508@end example
509This version packages the actions the script should perform in a
510function, @code{main}. This allows us to load the file purely for its
511definitions, without any extraneous computation taking place. Then we
512used the meta switch @code{\} and the entry point switch @code{-e} to
513tell Guile to call @code{main} after loading the script.
514@example
e03d9636 515$ ./fact 50
07d83abe
MV
51630414093201713378043612608166064768844377641568960512000000000000
517@end example
518
519Suppose that we now want to write a script which computes the
520@code{choose} function: given a set of @var{m} distinct objects,
521@code{(choose @var{n} @var{m})} is the number of distinct subsets
522containing @var{n} objects each. It's easy to write @code{choose} given
523@code{fact}, so we might write the script this way:
524@example
525#!/usr/local/bin/guile \
526-l fact -e main -s
527!#
528(define (choose n m)
529 (/ (fact m) (* (fact (- m n)) (fact n))))
530
531(define (main args)
532 (let ((n (string->number (cadr args)))
533 (m (string->number (caddr args))))
534 (display (choose n m))
535 (newline)))
536@end example
537
538The command-line arguments here tell Guile to first load the file
539@file{fact}, and then run the script, with @code{main} as the entry
540point. In other words, the @code{choose} script can use definitions
541made in the @code{fact} script. Here are some sample runs:
542@example
e03d9636 543$ ./choose 0 4
07d83abe 5441
e03d9636 545$ ./choose 1 4
07d83abe 5464
e03d9636 547$ ./choose 2 4
07d83abe 5486
e03d9636 549$ ./choose 3 4
07d83abe 5504
e03d9636 551$ ./choose 4 4
07d83abe 5521
e03d9636 553$ ./choose 50 100
07d83abe
MV
554100891344545564193334812497256
555@end example
556
44fd0a72
KR
557
558@c Local Variables:
559@c TeX-master: "guile.texi"
560@c End: