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