Two very small edits
[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
07d83abe
MV
119@item -l @var{file}
120Load Scheme source code from @var{file}, and continue processing the
121command line.
122
123@item -e @var{function}
124Make @var{function} the @dfn{entry point} of the script. After loading
125the script file (with @code{-s}) or evaluating the expression (with
126@code{-c}), apply @var{function} to a list containing the program name
127and the command-line arguments --- the list provided by the
128@code{command-line} function.
129
130A @code{-e} switch can appear anywhere in the argument list, but Guile
131always invokes the @var{function} as the @emph{last} action it performs.
132This is weird, but because of the way script invocation works under
133POSIX, the @code{-s} option must always come last in the list.
134
135The @var{function} is most often a simple symbol that names a function
136that is defined in the script. It can also be of the form @code{(@@
137@var{module-name} @var{symbol})} and in that case, the symbol is
138looked up in the module named @var{module-name}.
139
e70c841f
MV
140For compatibility with some versions of Guile 1.4, you can also use the
141form @code{(symbol ...)} (that is, a list of only symbols that doesn't
142start with @code{@@}), which is equivalent to @code{(@@ (symbol ...)
143main)}, or @code{(symbol ...) symbol} (that is, a list of only symbols
144followed by a symbol), which is equivalent to @code{(@@ (symbol ...)
145symbol)}. We recommend to use the equivalent forms directly since they
72b3aa56 146correspond to the @code{(@@ ...)} read syntax that can be used in
e70c841f
MV
147normal code, @xref{Using Guile Modules}.
148
07d83abe
MV
149@xref{Scripting Examples}.
150
151@item -ds
152Treat a final @code{-s} option as if it occurred at this point in the
153command line; load the script here.
154
155This switch is necessary because, although the POSIX script invocation
156mechanism effectively requires the @code{-s} option to appear last, the
157programmer may well want to run the script before other actions
158requested on the command line. For examples, see @ref{Scripting
159Examples}.
160
161@item \
162Read more command-line arguments, starting from the second line of the
163script file. @xref{The Meta Switch}.
164
07d83abe
MV
165@item --use-srfi=@var{list}
166The option @code{--use-srfi} expects a comma-separated list of numbers,
167each representing a SRFI number to be loaded into the interpreter
168before starting evaluating a script file or the REPL. Additionally,
169the feature identifier for the loaded SRFIs is recognized by
170`cond-expand' when using this option.
171
172@example
173guile --use-srfi=8,13
174@end example
175
176@item --debug
a43b4d6e
AW
177Start with the debugging virtual machine engine. Using the debugging VM
178will enable support for VM hooks, which are needed for tracing,
179breakpoints, and accurate call counts when profiling. The debugging VM
180is slower than the regular VM, though, by about 10 percent. @xref{VM
181Hooks}, for more information.
182
183By default, the debugging VM engine is only used when entering an
184interactive session. When executing a script with @code{-s} or
185@code{-c}, the normal, faster VM is used by default.
07d83abe
MV
186
187@vnew{1.8}
188@item --no-debug
a43b4d6e 189Do not use the debugging VM engine, even when entering an interactive
07d83abe
MV
190session.
191
f88dae81
AW
192@item --listen[=@var{p}]
193While this program runs, listen on a local port or a path for REPL
194clients. If @var{p} starts with a number, it is assumed to be a local
195port on which to listen. If it starts with a forward slash, it is
196assumed to be a path to a UNIX domain socket on which to listen.
197
198If @var{p} is not given, the default is local port 37146. If you look
199at it upside down, it almost spells ``Guile''. If you have netcat
200installed, you should be able to @kbd{nc localhost 37146} and get a
201Guile prompt. Alternately you can fire up Emacs and connect to the
ced9917e 202process; see @ref{Using Guile in Emacs} for more details.
f88dae81
AW
203
204Note that opening a port allows anyone who can connect to that port---in
205the TCP case, any local user---to do anything Guile can do, as the user
206that the Guile process is running as. Don't use @option{--listen} on
ced9917e
AW
207multi-user machines. Of course, if you don't pass @option{--listen} to
208Guile, no port will be opened.
f88dae81
AW
209
210That said, @code{--listen} is great for interactive debugging and
211development.
212
213@vnew{2.0}
07d83abe
MV
214@item -h@r{, }--help
215Display help on invoking Guile, and then exit.
216
217@item -v@r{, }--version
218Display the current version of Guile, and then exit.
219
220@end table
221
222
223@node The Meta Switch
224@subsection The Meta Switch
225
226Guile's command-line switches allow the programmer to describe
227reasonably complicated actions in scripts. Unfortunately, the POSIX
228script invocation mechanism only allows one argument to appear on the
229@samp{#!} line after the path to the Guile executable, and imposes
230arbitrary limits on that argument's length. Suppose you wrote a script
231starting like this:
232@example
233#!/usr/local/bin/guile -e main -s
234!#
235(define (main args)
236 (map (lambda (arg) (display arg) (display " "))
237 (cdr args))
238 (newline))
239@end example
240The intended meaning is clear: load the file, and then call @code{main}
241on the command-line arguments. However, the system will treat
242everything after the Guile path as a single argument --- the string
243@code{"-e main -s"} --- which is not what we want.
244
245As a workaround, the meta switch @code{\} allows the Guile programmer to
246specify an arbitrary number of options without patching the kernel. If
247the first argument to Guile is @code{\}, Guile will open the script file
248whose name follows the @code{\}, parse arguments starting from the
249file's second line (according to rules described below), and substitute
250them for the @code{\} switch.
251
252Working in concert with the meta switch, Guile treats the characters
253@samp{#!} as the beginning of a comment which extends through the next
254line containing only the characters @samp{!#}. This sort of comment may
255appear anywhere in a Guile program, but it is most useful at the top of
256a file, meshing magically with the POSIX script invocation mechanism.
257
258Thus, consider a script named @file{/u/jimb/ekko} which starts like this:
259@example
260#!/usr/local/bin/guile \
261-e main -s
262!#
263(define (main args)
264 (map (lambda (arg) (display arg) (display " "))
265 (cdr args))
266 (newline))
267@end example
268
269Suppose a user invokes this script as follows:
270@example
271$ /u/jimb/ekko a b c
272@end example
273
274Here's what happens:
275@itemize @bullet
276
277@item
278the operating system recognizes the @samp{#!} token at the top of the
279file, and rewrites the command line to:
280@example
281/usr/local/bin/guile \ /u/jimb/ekko a b c
282@end example
283This is the usual behavior, prescribed by POSIX.
284
285@item
286When Guile sees the first two arguments, @code{\ /u/jimb/ekko}, it opens
287@file{/u/jimb/ekko}, parses the three arguments @code{-e}, @code{main},
288and @code{-s} from it, and substitutes them for the @code{\} switch.
289Thus, Guile's command line now reads:
290@example
291/usr/local/bin/guile -e main -s /u/jimb/ekko a b c
292@end example
293
294@item
295Guile then processes these switches: it loads @file{/u/jimb/ekko} as a
296file of Scheme code (treating the first three lines as a comment), and
297then performs the application @code{(main "/u/jimb/ekko" "a" "b" "c")}.
298
299@end itemize
300
301
302When Guile sees the meta switch @code{\}, it parses command-line
303argument from the script file according to the following rules:
304@itemize @bullet
305
306@item
307Each space character terminates an argument. This means that two
308spaces in a row introduce an argument @code{""}.
309
310@item
311The tab character is not permitted (unless you quote it with the
312backslash character, as described below), to avoid confusion.
313
314@item
315The newline character terminates the sequence of arguments, and will
316also terminate a final non-empty argument. (However, a newline
317following a space will not introduce a final empty-string argument;
318it only terminates the argument list.)
319
320@item
321The backslash character is the escape character. It escapes backslash,
322space, tab, and newline. The ANSI C escape sequences like @code{\n} and
323@code{\t} are also supported. These produce argument constituents; the
324two-character combination @code{\n} doesn't act like a terminating
325newline. The escape sequence @code{\@var{NNN}} for exactly three octal
326digits reads as the character whose ASCII code is @var{NNN}. As above,
327characters produced this way are argument constituents. Backslash
328followed by other characters is not allowed.
329
330@end itemize
331
332
333@node Command Line Handling
334@subsection Command Line Handling
335
336@c This section was written and contributed by Martin Grabmueller.
337
338The ability to accept and handle command line arguments is very
339important when writing Guile scripts to solve particular problems, such
340as extracting information from text files or interfacing with existing
341command line applications. This chapter describes how Guile makes
342command line arguments available to a Guile script, and the utilities
343that Guile provides to help with the processing of command line
344arguments.
345
346When a Guile script is invoked, Guile makes the command line arguments
347accessible via the procedure @code{command-line}, which returns the
348arguments as a list of strings.
349
350For example, if the script
351
352@example
353#! /usr/local/bin/guile -s
354!#
355(write (command-line))
356(newline)
357@end example
358
359@noindent
360is saved in a file @file{cmdline-test.scm} and invoked using the command
361line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}, the output
362is
363
364@example
365("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")
366@end example
367
368If the script invocation includes a @code{-e} option, specifying a
369procedure to call after loading the script, Guile will call that
370procedure with @code{(command-line)} as its argument. So a script that
371uses @code{-e} doesn't need to refer explicitly to @code{command-line}
372in its code. For example, the script above would have identical
373behaviour if it was written instead like this:
374
375@example
376#! /usr/local/bin/guile \
377-e main -s
378!#
379(define (main args)
380 (write args)
381 (newline))
382@end example
383
384(Note the use of the meta switch @code{\} so that the script invocation
385can include more than one Guile option: @xref{The Meta Switch}.)
386
387These scripts use the @code{#!} POSIX convention so that they can be
388executed using their own file names directly, as in the example command
389line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}. But they
390can also be executed by typing out the implied Guile command line in
391full, as in:
392
393@example
394$ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob
395@end example
396
397@noindent
398or
399
400@example
401$ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob
402@end example
403
404Even when a script is invoked using this longer form, the arguments that
405the script receives are the same as if it had been invoked using the
406short form. Guile ensures that the @code{(command-line)} or @code{-e}
407arguments are independent of how the script is invoked, by stripping off
408the arguments that Guile itself processes.
409
410A script is free to parse and handle its command line arguments in any
411way that it chooses. Where the set of possible options and arguments is
412complex, however, it can get tricky to extract all the options, check
413the validity of given arguments, and so on. This task can be greatly
414simplified by taking advantage of the module @code{(ice-9 getopt-long)},
415which is distributed with Guile, @xref{getopt-long}.
416
417
418@node Scripting Examples
419@subsection Scripting Examples
420
421To start with, here are some examples of invoking Guile directly:
422
423@table @code
424
425@item guile -- a b c
426Run Guile interactively; @code{(command-line)} will return @*
427@code{("/usr/local/bin/guile" "a" "b" "c")}.
428
429@item guile -s /u/jimb/ex2 a b c
430Load the file @file{/u/jimb/ex2}; @code{(command-line)} will return @*
431@code{("/u/jimb/ex2" "a" "b" "c")}.
432
433@item guile -c '(write %load-path) (newline)'
434Write the value of the variable @code{%load-path}, print a newline,
435and exit.
436
437@item guile -e main -s /u/jimb/ex4 foo
438Load the file @file{/u/jimb/ex4}, and then call the function
439@code{main}, passing it the list @code{("/u/jimb/ex4" "foo")}.
440
441@item guile -l first -ds -l last -s script
442Load the files @file{first}, @file{script}, and @file{last}, in that
443order. The @code{-ds} switch says when to process the @code{-s}
444switch. For a more motivated example, see the scripts below.
445
446@end table
447
448
449Here is a very simple Guile script:
450@example
451#!/usr/local/bin/guile -s
452!#
453(display "Hello, world!")
454(newline)
455@end example
456The first line marks the file as a Guile script. When the user invokes
457it, the system runs @file{/usr/local/bin/guile} to interpret the script,
458passing @code{-s}, the script's filename, and any arguments given to the
459script as command-line arguments. When Guile sees @code{-s
460@var{script}}, it loads @var{script}. Thus, running this program
461produces the output:
462@example
463Hello, world!
464@end example
465
466Here is a script which prints the factorial of its argument:
467@example
468#!/usr/local/bin/guile -s
469!#
470(define (fact n)
471 (if (zero? n) 1
472 (* n (fact (- n 1)))))
473
474(display (fact (string->number (cadr (command-line)))))
475(newline)
476@end example
477In action:
478@example
e03d9636 479$ ./fact 5
07d83abe
MV
480120
481$
482@end example
483
484However, suppose we want to use the definition of @code{fact} in this
485file from another script. We can't simply @code{load} the script file,
486and then use @code{fact}'s definition, because the script will try to
487compute and display a factorial when we load it. To avoid this problem,
488we might write the script this way:
489
490@example
491#!/usr/local/bin/guile \
492-e main -s
493!#
494(define (fact n)
495 (if (zero? n) 1
496 (* n (fact (- n 1)))))
497
498(define (main args)
499 (display (fact (string->number (cadr args))))
500 (newline))
501@end example
502This version packages the actions the script should perform in a
503function, @code{main}. This allows us to load the file purely for its
504definitions, without any extraneous computation taking place. Then we
505used the meta switch @code{\} and the entry point switch @code{-e} to
506tell Guile to call @code{main} after loading the script.
507@example
e03d9636 508$ ./fact 50
07d83abe
MV
50930414093201713378043612608166064768844377641568960512000000000000
510@end example
511
512Suppose that we now want to write a script which computes the
513@code{choose} function: given a set of @var{m} distinct objects,
514@code{(choose @var{n} @var{m})} is the number of distinct subsets
515containing @var{n} objects each. It's easy to write @code{choose} given
516@code{fact}, so we might write the script this way:
517@example
518#!/usr/local/bin/guile \
519-l fact -e main -s
520!#
521(define (choose n m)
522 (/ (fact m) (* (fact (- m n)) (fact n))))
523
524(define (main args)
525 (let ((n (string->number (cadr args)))
526 (m (string->number (caddr args))))
527 (display (choose n m))
528 (newline)))
529@end example
530
531The command-line arguments here tell Guile to first load the file
532@file{fact}, and then run the script, with @code{main} as the entry
533point. In other words, the @code{choose} script can use definitions
534made in the @code{fact} script. Here are some sample runs:
535@example
e03d9636 536$ ./choose 0 4
07d83abe 5371
e03d9636 538$ ./choose 1 4
07d83abe 5394
e03d9636 540$ ./choose 2 4
07d83abe 5416
e03d9636 542$ ./choose 3 4
07d83abe 5434
e03d9636 544$ ./choose 4 4
07d83abe 5451
e03d9636 546$ ./choose 50 100
07d83abe
MV
547100891344545564193334812497256
548@end example
549
44fd0a72
KR
550
551@c Local Variables:
552@c TeX-master: "guile.texi"
553@c End: