`load' is a macro (!) that resolves paths relative to source file dir
[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}
91a60e57
NJ
221
222@item --autocompile
223Compile source files automatically (default behavior).
224
225@vnew{2.0}
226
227@item --no-autocompile
228Disable automatic source file compilation.
229
230@vnew{2.0}
231
07d83abe
MV
232@item -h@r{, }--help
233Display help on invoking Guile, and then exit.
234
235@item -v@r{, }--version
236Display the current version of Guile, and then exit.
237
238@end table
239
240
241@node The Meta Switch
242@subsection The Meta Switch
243
244Guile's command-line switches allow the programmer to describe
245reasonably complicated actions in scripts. Unfortunately, the POSIX
246script invocation mechanism only allows one argument to appear on the
247@samp{#!} line after the path to the Guile executable, and imposes
248arbitrary limits on that argument's length. Suppose you wrote a script
249starting like this:
250@example
251#!/usr/local/bin/guile -e main -s
252!#
253(define (main args)
254 (map (lambda (arg) (display arg) (display " "))
255 (cdr args))
256 (newline))
257@end example
258The intended meaning is clear: load the file, and then call @code{main}
259on the command-line arguments. However, the system will treat
260everything after the Guile path as a single argument --- the string
261@code{"-e main -s"} --- which is not what we want.
262
263As a workaround, the meta switch @code{\} allows the Guile programmer to
264specify an arbitrary number of options without patching the kernel. If
265the first argument to Guile is @code{\}, Guile will open the script file
266whose name follows the @code{\}, parse arguments starting from the
267file's second line (according to rules described below), and substitute
268them for the @code{\} switch.
269
270Working in concert with the meta switch, Guile treats the characters
271@samp{#!} as the beginning of a comment which extends through the next
272line containing only the characters @samp{!#}. This sort of comment may
273appear anywhere in a Guile program, but it is most useful at the top of
274a file, meshing magically with the POSIX script invocation mechanism.
275
276Thus, consider a script named @file{/u/jimb/ekko} which starts like this:
277@example
278#!/usr/local/bin/guile \
279-e main -s
280!#
281(define (main args)
282 (map (lambda (arg) (display arg) (display " "))
283 (cdr args))
284 (newline))
285@end example
286
287Suppose a user invokes this script as follows:
288@example
289$ /u/jimb/ekko a b c
290@end example
291
292Here's what happens:
293@itemize @bullet
294
295@item
296the operating system recognizes the @samp{#!} token at the top of the
297file, and rewrites the command line to:
298@example
299/usr/local/bin/guile \ /u/jimb/ekko a b c
300@end example
301This is the usual behavior, prescribed by POSIX.
302
303@item
304When Guile sees the first two arguments, @code{\ /u/jimb/ekko}, it opens
305@file{/u/jimb/ekko}, parses the three arguments @code{-e}, @code{main},
306and @code{-s} from it, and substitutes them for the @code{\} switch.
307Thus, Guile's command line now reads:
308@example
309/usr/local/bin/guile -e main -s /u/jimb/ekko a b c
310@end example
311
312@item
313Guile then processes these switches: it loads @file{/u/jimb/ekko} as a
314file of Scheme code (treating the first three lines as a comment), and
315then performs the application @code{(main "/u/jimb/ekko" "a" "b" "c")}.
316
317@end itemize
318
319
320When Guile sees the meta switch @code{\}, it parses command-line
321argument from the script file according to the following rules:
322@itemize @bullet
323
324@item
325Each space character terminates an argument. This means that two
326spaces in a row introduce an argument @code{""}.
327
328@item
329The tab character is not permitted (unless you quote it with the
330backslash character, as described below), to avoid confusion.
331
332@item
333The newline character terminates the sequence of arguments, and will
334also terminate a final non-empty argument. (However, a newline
335following a space will not introduce a final empty-string argument;
336it only terminates the argument list.)
337
338@item
339The backslash character is the escape character. It escapes backslash,
340space, tab, and newline. The ANSI C escape sequences like @code{\n} and
341@code{\t} are also supported. These produce argument constituents; the
342two-character combination @code{\n} doesn't act like a terminating
343newline. The escape sequence @code{\@var{NNN}} for exactly three octal
344digits reads as the character whose ASCII code is @var{NNN}. As above,
345characters produced this way are argument constituents. Backslash
346followed by other characters is not allowed.
347
348@end itemize
349
350
351@node Command Line Handling
352@subsection Command Line Handling
353
354@c This section was written and contributed by Martin Grabmueller.
355
356The ability to accept and handle command line arguments is very
357important when writing Guile scripts to solve particular problems, such
358as extracting information from text files or interfacing with existing
359command line applications. This chapter describes how Guile makes
360command line arguments available to a Guile script, and the utilities
361that Guile provides to help with the processing of command line
362arguments.
363
364When a Guile script is invoked, Guile makes the command line arguments
365accessible via the procedure @code{command-line}, which returns the
366arguments as a list of strings.
367
368For example, if the script
369
370@example
371#! /usr/local/bin/guile -s
372!#
373(write (command-line))
374(newline)
375@end example
376
377@noindent
378is saved in a file @file{cmdline-test.scm} and invoked using the command
379line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}, the output
380is
381
382@example
383("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")
384@end example
385
386If the script invocation includes a @code{-e} option, specifying a
387procedure to call after loading the script, Guile will call that
388procedure with @code{(command-line)} as its argument. So a script that
389uses @code{-e} doesn't need to refer explicitly to @code{command-line}
390in its code. For example, the script above would have identical
391behaviour if it was written instead like this:
392
393@example
394#! /usr/local/bin/guile \
395-e main -s
396!#
397(define (main args)
398 (write args)
399 (newline))
400@end example
401
402(Note the use of the meta switch @code{\} so that the script invocation
403can include more than one Guile option: @xref{The Meta Switch}.)
404
405These scripts use the @code{#!} POSIX convention so that they can be
406executed using their own file names directly, as in the example command
407line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}. But they
408can also be executed by typing out the implied Guile command line in
409full, as in:
410
411@example
412$ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob
413@end example
414
415@noindent
416or
417
418@example
419$ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob
420@end example
421
422Even when a script is invoked using this longer form, the arguments that
423the script receives are the same as if it had been invoked using the
424short form. Guile ensures that the @code{(command-line)} or @code{-e}
425arguments are independent of how the script is invoked, by stripping off
426the arguments that Guile itself processes.
427
428A script is free to parse and handle its command line arguments in any
429way that it chooses. Where the set of possible options and arguments is
430complex, however, it can get tricky to extract all the options, check
431the validity of given arguments, and so on. This task can be greatly
432simplified by taking advantage of the module @code{(ice-9 getopt-long)},
433which is distributed with Guile, @xref{getopt-long}.
434
435
436@node Scripting Examples
437@subsection Scripting Examples
438
439To start with, here are some examples of invoking Guile directly:
440
441@table @code
442
443@item guile -- a b c
444Run Guile interactively; @code{(command-line)} will return @*
445@code{("/usr/local/bin/guile" "a" "b" "c")}.
446
447@item guile -s /u/jimb/ex2 a b c
448Load the file @file{/u/jimb/ex2}; @code{(command-line)} will return @*
449@code{("/u/jimb/ex2" "a" "b" "c")}.
450
451@item guile -c '(write %load-path) (newline)'
452Write the value of the variable @code{%load-path}, print a newline,
453and exit.
454
455@item guile -e main -s /u/jimb/ex4 foo
456Load the file @file{/u/jimb/ex4}, and then call the function
457@code{main}, passing it the list @code{("/u/jimb/ex4" "foo")}.
458
459@item guile -l first -ds -l last -s script
460Load the files @file{first}, @file{script}, and @file{last}, in that
461order. The @code{-ds} switch says when to process the @code{-s}
462switch. For a more motivated example, see the scripts below.
463
464@end table
465
466
467Here is a very simple Guile script:
468@example
469#!/usr/local/bin/guile -s
470!#
471(display "Hello, world!")
472(newline)
473@end example
474The first line marks the file as a Guile script. When the user invokes
475it, the system runs @file{/usr/local/bin/guile} to interpret the script,
476passing @code{-s}, the script's filename, and any arguments given to the
477script as command-line arguments. When Guile sees @code{-s
478@var{script}}, it loads @var{script}. Thus, running this program
479produces the output:
480@example
481Hello, world!
482@end example
483
484Here is a script which prints the factorial of its argument:
485@example
486#!/usr/local/bin/guile -s
487!#
488(define (fact n)
489 (if (zero? n) 1
490 (* n (fact (- n 1)))))
491
492(display (fact (string->number (cadr (command-line)))))
493(newline)
494@end example
495In action:
496@example
e03d9636 497$ ./fact 5
07d83abe
MV
498120
499$
500@end example
501
502However, suppose we want to use the definition of @code{fact} in this
503file from another script. We can't simply @code{load} the script file,
504and then use @code{fact}'s definition, because the script will try to
505compute and display a factorial when we load it. To avoid this problem,
506we might write the script this way:
507
508@example
509#!/usr/local/bin/guile \
510-e main -s
511!#
512(define (fact n)
513 (if (zero? n) 1
514 (* n (fact (- n 1)))))
515
516(define (main args)
517 (display (fact (string->number (cadr args))))
518 (newline))
519@end example
520This version packages the actions the script should perform in a
521function, @code{main}. This allows us to load the file purely for its
522definitions, without any extraneous computation taking place. Then we
523used the meta switch @code{\} and the entry point switch @code{-e} to
524tell Guile to call @code{main} after loading the script.
525@example
e03d9636 526$ ./fact 50
07d83abe
MV
52730414093201713378043612608166064768844377641568960512000000000000
528@end example
529
530Suppose that we now want to write a script which computes the
531@code{choose} function: given a set of @var{m} distinct objects,
532@code{(choose @var{n} @var{m})} is the number of distinct subsets
533containing @var{n} objects each. It's easy to write @code{choose} given
534@code{fact}, so we might write the script this way:
535@example
536#!/usr/local/bin/guile \
537-l fact -e main -s
538!#
539(define (choose n m)
540 (/ (fact m) (* (fact (- m n)) (fact n))))
541
542(define (main args)
543 (let ((n (string->number (cadr args)))
544 (m (string->number (caddr args))))
545 (display (choose n m))
546 (newline)))
547@end example
548
549The command-line arguments here tell Guile to first load the file
550@file{fact}, and then run the script, with @code{main} as the entry
551point. In other words, the @code{choose} script can use definitions
552made in the @code{fact} script. Here are some sample runs:
553@example
e03d9636 554$ ./choose 0 4
07d83abe 5551
e03d9636 556$ ./choose 1 4
07d83abe 5574
e03d9636 558$ ./choose 2 4
07d83abe 5596
e03d9636 560$ ./choose 3 4
07d83abe 5614
e03d9636 562$ ./choose 4 4
07d83abe 5631
e03d9636 564$ ./choose 50 100
07d83abe
MV
565100891344545564193334812497256
566@end example
567
44fd0a72
KR
568
569@c Local Variables:
570@c TeX-master: "guile.texi"
571@c End: