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