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