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