1\input texinfo @c -*-texinfo-*- 2@c %**start of header 3@setfilename guile-library.info 4@settitle Guile Library 5@c %**end of header 6 7@copying 8This manual is for Guile Library (version 0.2.6.1, updated July 2018) 9 10Copyright 2003,2007,2010,2011,2016,2017,2018 Andy Wingo, Richard Todd 11 12@quotation 13Permission is granted to copy, distribute and/or modify this document 14under the terms of the GNU Free Documentation License, Version 1.2 or 15any later version published y the Free Software Foundation; with no 16Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A 17copy of the license is included in the section entitled "GNU Free 18Documentation License". 19 20@end quotation 21 22@end copying 23 24@dircategory The Algorithmic Language Scheme 25@direntry 26* Guile Library: (guile-library.info). Common modules for Guile Scheme. 27@end direntry 28 29@titlepage 30@title Guile Library 31@subtitle version 0.2.6.1, updated July 2018 32@author Andy Wingo (@email{wingo at pobox.com}) 33@author Richard Todd (@email{richardt at vzavenue.net}) 34@page 35@vskip 0pt plus 1filll 36@insertcopying 37@end titlepage 38 39@ifnottex 40@node Top 41@top Guile Library 42@insertcopying 43@menu 44* apicheck:: Describe and verify library programming interfaces 45* config load:: Loading configuration files 46* container async-queue:: A thread-safe message queue 47* container nodal-tree:: A tree consisting of nodes with attributes 48* container delay-tree:: A nodal tree with lazily evaluated fields 49* debugging assert:: Helpful assert macro 50* debugging time:: A simple macro to time the execution of an expression 51* graph topological-sort:: Routines to perform topological sorts 52* htmlprag:: Neil Van Dyke's permissive ("pragmatic") HTML parser 53* io string:: SLIB's IO routines dealing with strings 54* logging logger:: A flexible logging system 55* logging port-log:: A logger that outputs to a port 56* logging rotating-log:: A logger that rotates its output files 57* match-bind:: Nifty and concise regular expression routines 58* math minima:: A golden-section minimum finder 59* math primes:: Functions related to prime numbers and factorization 60* os process:: Spawning processes and capturing their output 61* scheme documentation:: Macros to define different kinds of variables with documentation 62* scheme kwargs:: Defining functions with flexible keyword arguments 63* search basic:: Classic search functions 64* string completion:: Building blocks for tab completion 65* string soundex:: The SOUNDEX string categorization algorithm 66* string transform:: Beyond SRFI-13 67* string wrap:: A versatile string formatter 68* term ansi-color:: Generate ANSI color escape sequences 69* unit-test:: A JUnit-style unit testing framework 70 71* Copying This Manual:: 72* Concept Index:: 73* Function Index:: 74@end menu 75 76@end ifnottex 77 78@iftex 79@shortcontents 80@end iftex 81 82@node apicheck 83@chapter (apicheck) 84@section Overview 85@code{(apicheck)} exports two routines. @code{apicheck-generate} 86produces a description of the Scheme API exported by a set of modules as 87an S-expression. @code{apicheck-validate} verifies that the API 88exported by a set of modules is compatible with an API description 89generated by @code{apicheck-generate}. 90 91It would be nice to have Makefile.am fragments here, but for now, see 92the Guile-Library source distribution for information on how to 93integrate apicheck with your module's unit test suite. 94 95@section Usage 96@anchor{apicheck apicheck-generate}@defun apicheck-generate module-names 97Generate a description of the API exported by the set of modules 98@var{module-names}. 99 100@end defun 101 102@anchor{apicheck apicheck-validate}@defun apicheck-validate api module-names 103Validate that the API exported by the set of modules @var{module-names} 104is compatible with the recorded API description @var{api}. Raises an 105exception if the interface is incompatible. 106 107@end defun 108 109@node config load 110@chapter (config load) 111@section Overview 112@verbatim 113 This module needs to be documented. 114@end verbatim 115 116@section Usage 117@anchor{config load <configuration>}@deftp Class <configuration> 118@end deftp 119 120@anchor{config load load-config!}@deffn Generic load-config! 121@end deffn 122 123@deffn Method load-config! (@var{cfg} @code{<configuration>}) (@var{commands} @code{<list>}) (@var{file-name} @code{<string>}) 124@end deffn 125 126@anchor{config load &config-error}@defvar &config-error 127@end defvar 128 129@anchor{config load config-error-arguments}@defun config-error-arguments c 130@end defun 131 132@node container async-queue 133@chapter (container async-queue) 134@section Overview 135A asynchronous queue can be used to safely send messages from one thread 136to another. 137 138@section Usage 139@anchor{container async-queue make-async-queue}@defun make-async-queue 140Create a new asynchronous queue. 141 142@end defun 143 144@anchor{container async-queue async-enqueue!}@defun async-enqueue! q elt 145Enqueue @var{elt} into @var{q}. 146 147@end defun 148 149@anchor{container async-queue async-dequeue!}@defun async-dequeue! q 150Dequeue a single element from @var{q}. If the queue is empty, the 151calling thread is blocked until an element is enqueued by another 152thread. 153 154@end defun 155 156@node container nodal-tree 157@chapter (container nodal-tree) 158@section Overview 159A nodal tree is a tree composed of nodes, each of which may have 160children. Nodes are represented as alists. The only alist entry that 161is specified is @code{children}, which must hold a list of child nodes. 162Other entries are intentionally left unspecified, so as to allow for 163extensibility. 164 165@section Usage 166@anchor{container nodal-tree nodal-tree?}@defun nodal-tree? x 167Predicate to determine if @var{x} is a nodal tree. Not particularly 168efficient: intended for debugging purposes. 169 170@end defun 171 172@anchor{container nodal-tree make-node}@defun make-node . attributes 173@end defun 174 175@anchor{container nodal-tree node-ref}@defun node-ref node name 176@end defun 177 178@anchor{container nodal-tree node-set!}@defun node-set! node name val 179@end defun 180 181@anchor{container nodal-tree node-children}@defun node-children node 182@end defun 183 184@node container delay-tree 185@chapter (container delay-tree) 186@section Overview 187A delay tree is a superset of a nodal tree (see (container nodal-tree)). 188It extends nodal trees to allow any entry of the node to be a promise 189created with the @code{delay} operator. 190 191@section Usage 192@anchor{container delay-tree force-ref}@defun force-ref node field 193Access a field in a node of a delay tree. If the value of the field is 194a promise, the promise will be forced, and the value will be replaced 195with the forced value. 196 197@end defun 198 199@node debugging assert 200@chapter (debugging assert) 201@section Overview 202Defines an @code{assert} macro, and the @code{cout} and @code{cerr} 203utility functions. 204 205@section Usage 206@anchor{debugging assert assert}@defspec assert doit (expr ...) (r-exp ...) 207@defspecx assert collect (expr ...) 208@defspecx assert collect (expr ...) report: r-exp ... 209@defspecx assert collect (expr ...) expr1 stuff ... 210@defspecx assert stuff ... 211Assert the truth of an expression (or of a sequence of expressions). 212 213syntax: @code{assert @var{?expr} @var{?expr} ... [report: @var{?r-exp} 214@var{?r-exp} ...]} 215 216If @code{(and @var{?expr} @var{?expr} ...)} evaluates to anything but 217@code{#f}, the result is the value of that expression. Otherwise, an 218error is reported. 219 220The error message will show the failed expressions, as well as the 221values of selected variables (or expressions, in general). The user may 222explicitly specify the expressions whose values are to be printed upon 223assertion failure -- as @var{?r-exp} that follow the identifier 224@code{report:}. 225 226Typically, @var{?r-exp} is either a variable or a string constant. If 227the user specified no @var{?r-exp}, the values of variables that are 228referenced in @var{?expr} will be printed upon the assertion failure. 229 230@end defspec 231 232@anchor{debugging assert cout}@defun cout . args 233Similar to @code{cout << arguments << args}, where @var{argument} can be 234any Scheme object. If it's a procedure (e.g. @code{newline}), it's 235called without args rather than printed. 236 237@end defun 238 239@anchor{debugging assert cerr}@defun cerr . args 240Similar to @code{cerr << arguments << args}, where @var{argument} can be 241any Scheme object. If it's a procedure (e.g. @code{newline}), it's 242called without args rather than printed. 243 244@end defun 245 246@node debugging time 247@chapter (debugging time) 248@section Overview 249@c it's really texinfo 250Defines a macro to time execution of a body of expressions. Each 251element is timed individually. 252 253@section Usage 254@anchor{debugging time time}@defspec time args 255syntax: @code{(time @var{expr1} @var{expr2}...)} 256 257Times the execution of a list of expressions, in milliseconds. The 258resolution is limited to guile's @code{internal-time-units-per-second}. 259Disregards the expressions' return value(s) (FIXME). 260 261@end defspec 262 263@node graph topological-sort 264@chapter (graph topological-sort) 265@section Overview 266@verbatim 267 The algorithm is inspired by Cormen, Leiserson and Rivest (1990) 268 ``Introduction to Algorithms'', chapter 23. 269@end verbatim 270 271@section Usage 272@anchor{graph topological-sort topological-sort}@defun topological-sort dag 273Returns a list of the objects in the directed acyclic graph, @var{dag}, 274topologically sorted. Objects are compared using @code{equal?}. The 275graph has the form: 276 277@lisp 278 (list (obj1 . (dependents-of-obj1)) 279 (obj2 . (dependents-of-obj2)) ...) 280@end lisp 281 282...specifying, for example, that @code{obj1} must come before all the 283objects in @code{(dependents-of-obj1)} in the sort. 284 285@end defun 286 287@anchor{graph topological-sort topological-sortq}@defun topological-sortq dag 288Returns a list of the objects in the directed acyclic graph, @var{dag}, 289topologically sorted. Objects are compared using @code{eq?}. The graph 290has the form: 291 292@lisp 293 (list (obj1 . (dependents-of-obj1)) 294 (obj2 . (dependents-of-obj2)) ...) 295@end lisp 296 297...specifying, for example, that @code{obj1} must come before all the 298objects in @code{(dependents-of-obj1)} in the sort. 299 300@end defun 301 302@anchor{graph topological-sort topological-sortv}@defun topological-sortv dag 303Returns a list of the objects in the directed acyclic graph, @var{dag}, 304topologically sorted. Objects are compared using @code{eqv?}. The 305graph has the form: 306 307@lisp 308 (list (obj1 . (dependents-of-obj1)) 309 (obj2 . (dependents-of-obj2)) ...) 310@end lisp 311 312...specifying, for example, that @code{obj1} must come before all the 313objects in @code{(dependents-of-obj1)} in the sort. 314 315@end defun 316 317@node htmlprag 318@chapter (htmlprag) 319@section Overview 320HtmlPrag provides permissive HTML parsing capability to Scheme programs, 321which is useful for software agent extraction of information from Web 322pages, for programmatically transforming HTML files, and for 323implementing interactive Web browsers. HtmlPrag emits ``SHTML,'' which 324is an encoding of HTML in [SXML], so that conventional HTML may be 325processed with XML tools such as [SXPath] and [SXML-Tools]. Like 326[SSAX-HTML], HtmlPrag provides a permissive tokenizer, but also attempts 327to recover structure. HtmlPrag also includes procedures for encoding 328SHTML in HTML syntax. 329 330The HtmlPrag parsing behavior is permissive in that it accepts erroneous 331HTML, handling several classes of HTML syntax errors gracefully, without 332yielding a parse error. This is crucial for parsing arbitrary 333real-world Web pages, since many pages actually contain syntax errors 334that would defeat a strict or validating parser. HtmlPrag's handling of 335errors is intended to generally emulate popular Web browsers' 336interpretation of the structure of erroneous HTML. We euphemistically 337term this kind of parse ``pragmatic.'' 338 339HtmlPrag also has some support for [XHTML], although XML namespace 340qualifiers [XML-Names] are currently accepted but stripped from the 341resulting SHTML. Note that valid XHTML input is of course better 342handled by a validating XML parser like [SSAX]. 343 344To receive notification of new versions of HtmlPrag, and to be polled 345for input on changes to HtmlPrag being considered, ask the author to add 346you to the moderated, announce-only email list, 347@code{htmlprag-announce}. 348 349Thanks to Oleg Kiselyov and Kirill Lisovsky for their help with SXML. 350 351@section Usage 352@anchor{htmlprag shtml-comment-symbol}@defvar shtml-comment-symbol 353@end defvar 354 355@anchor{htmlprag shtml-decl-symbol}@defvar shtml-decl-symbol 356@end defvar 357 358@anchor{htmlprag shtml-empty-symbol}@defvar shtml-empty-symbol 359@end defvar 360 361@anchor{htmlprag shtml-end-symbol}@defvar shtml-end-symbol 362@end defvar 363 364@anchor{htmlprag shtml-entity-symbol}@defvar shtml-entity-symbol 365@end defvar 366 367@anchor{htmlprag shtml-named-char-id}@defvar shtml-named-char-id 368@end defvar 369 370@anchor{htmlprag shtml-numeric-char-id}@defvar shtml-numeric-char-id 371@end defvar 372 373@anchor{htmlprag shtml-pi-symbol}@defvar shtml-pi-symbol 374@end defvar 375 376@anchor{htmlprag shtml-start-symbol}@defvar shtml-start-symbol 377@end defvar 378 379@anchor{htmlprag shtml-text-symbol}@defvar shtml-text-symbol 380@end defvar 381 382@anchor{htmlprag shtml-top-symbol}@defvar shtml-top-symbol 383@end defvar 384 385@anchor{htmlprag html->shtml}@defun html->shtml input 386@end defun 387 388@anchor{htmlprag html->sxml}@defun html->sxml input 389@end defun 390 391@anchor{htmlprag html->sxml-0nf}@defun html->sxml-0nf input 392@end defun 393 394@anchor{htmlprag html->sxml-1nf}@defun html->sxml-1nf input 395@end defun 396 397@anchor{htmlprag html->sxml-2nf}@defun html->sxml-2nf input 398@end defun 399 400@anchor{htmlprag make-html-tokenizer}@defun make-html-tokenizer in normalized? 401@end defun 402 403@anchor{htmlprag parse-html/tokenizer}@defun parse-html/tokenizer tokenizer normalized? 404@end defun 405 406@anchor{htmlprag shtml->html}@defun shtml->html shtml 407@end defun 408 409@anchor{htmlprag shtml-entity-value}@defun shtml-entity-value entity 410@end defun 411 412@anchor{htmlprag shtml-token-kind}@defun shtml-token-kind token 413@end defun 414 415@anchor{htmlprag sxml->html}@defun sxml->html shtml 416@end defun 417 418@anchor{htmlprag test-htmlprag}@defun test-htmlprag 419@end defun 420 421@anchor{htmlprag tokenize-html}@defun tokenize-html in normalized? 422@end defun 423 424@anchor{htmlprag write-shtml-as-html}@defun write-shtml-as-html shtml out 425@end defun 426 427@anchor{htmlprag write-sxml-html}@defun write-sxml-html shtml out 428@end defun 429 430@node io string 431@chapter (io string) 432@section Overview 433@c really, texinfo 434Procedures that do io with strings. 435 436@section Usage 437@anchor{io string find-string-from-port?}@defun find-string-from-port? str <input-port> . max-no-char 438Looks for @var{str} in @var{<input-port>}, optionally within the first 439@var{max-no-char} characters. 440 441@end defun 442 443@node logging logger 444@chapter (logging logger) 445@section Overview 446@anchor{cindex-logging}@cindex logging 447@anchor{cindex-loggers relationship with handlers}@cindex loggers, relationship with handlers 448@anchor{cindex-handlers relationship with loggers}@cindex handlers, relationship with loggers 449@anchor{cindex-log levels}@cindex log levels 450This is a logging subsystem similar to the one in the python standard 451library. There are two main concepts to understand when working with 452the logging modules. These are loggers and log handlers. 453 454@table @asis 455@item Loggers 456Loggers are the front end interfaces for program logging. They can be 457registered by name so that no part of a program needs to be concerned 458with passing around loggers. In addition, a default logger can be 459designated so that, for most applications, the program does not need to 460be concerned with logger instances at all beyond the initial setup. 461 462Log messages all flow through a logger. Messages carry with them a 463level (for example: 'WARNING, 'ERROR, 'CRITICAL), and loggers can filter 464out messages on a level basis at runtime. This way, the amount of 465logging can be turned up during development and bug investigation, but 466turned back down on stable releases. 467 468Loggers depend on Log Handlers to actually get text to the log's 469destination (for example, a disk file). A single Logger can send 470messages through multiple Log Handlers, effectively multicasting logs to 471multiple destinations. 472 473@item Log Handlers 474Log Handlers actually route text to a destination. One or more handlers 475must be attached to a logger for any text to actually appear in a log. 476 477Handlers apply a configurable transformation to the text so that it is 478formatted properly for the destination (for instance: syslogs, or a text 479file). Like the loggers, they can filter out messages based on log 480levels. By using filters on both the Logger and the Handlers, precise 481controls can be put on which log messages go where, even within a single 482logger. 483 484@end table 485 486@section Example use of logger 487Here is an example program that sets up a logger with two handlers. One 488handler sends the log messages to a text log that rotates its logs. The 489other handler sends logs to standard error, and has its levels set so 490that INFO and WARN-level logs don't get through. 491 492@lisp 493(use-modules (logging logger) 494 (logging rotating-log) 495 (logging port-log) 496 (scheme documentation) 497 (oop goops)) 498 499 ---------------------------------------------------------------------- 500 Support functions 501 ---------------------------------------------------------------------- 502(define (setup-logging) 503 (let ((lgr (make <logger>)) 504 (rotating (make <rotating-log> 505 #:num-files 3 506 #:size-limit 1024 507 #:file-name "test-log-file")) 508 (err (make <port-log> #:port (current-error-port)))) 509 510 ;; don't want to see warnings or info on the screen!! 511 (disable-log-level! err 'WARN) 512 (disable-log-level! err 'INFO) 513 514 ;; add the handlers to our logger 515 (add-handler! lgr rotating) 516 (add-handler! lgr err) 517 518 ;; make this the application's default logger 519 (set-default-logger! lgr) 520 (open-log! lgr))) 521 522 523(define (shutdown-logging) 524 (flush-log) ;; since no args, it uses the default 525 (close-log!) ;; since no args, it uses the default 526 (set-default-logger! #f)) 527 528 ---------------------------------------------------------------------- 529 Main code 530 ---------------------------------------------------------------------- 531(setup-logging) 532 533 Due to log levels, this will get to file, 534 but not to stderr 535(log-msg 'WARN "This is a warning.") 536 537 This will get to file AND stderr 538(log-msg 'CRITICAL "ERROR message!!!") 539 540(shutdown-logging) 541@end lisp 542 543@section Usage 544@anchor{logging logger <log-handler>}@deftp Class <log-handler> 545This is the base class for all of the log handlers, and encompasses the 546basic functionality that all handlers are expected to have. Keyword 547arguments recognized by the @code{<log-handler>} at creation time are: 548 549@table @code 550@item #:formatter 551This optional parameter must be a function that takes three arguments: 552the log level, the time (as from @code{current-time}), and the log 553string itself. The function must return a string representing the 554formatted log. 555 556Here is an example invokation of the default formatter, and what it's 557output looks like: 558 559@lisp 560 (default-log-formatter 'CRITICAL 561 (current-time) 562 "The servers are melting!") 563==> "2003/12/29 14:53:02 (CRITICAL): The servers are melting!" 564@end lisp 565 566@end table 567 568@end deftp 569 570@anchor{logging logger emit-log}@deffn Generic emit-log 571@code{emit-log handler str}. This method should be implemented for all 572the handlers. This sends a string to their output media. All level 573checking and formatting has already been done by @code{accept-log}. 574 575@end deffn 576 577@anchor{logging logger accept-log}@deffn Generic accept-log 578@code{accept-log handler lvl time str}. If @var{lvl} is enabled for 579@var{handler}, then @var{str} will be formatted and sent to the log via 580the @code{emit-log} method. Formatting is done via the formatting 581function given at @var{handler}'s creation time, or by the default if 582none was given. 583 584This method should not normally need to be overridden by subclasses. 585This method should not normally be called by users of the logging 586system. It is only exported so that writers of log handlers can 587override this behavior. 588 589@end deffn 590 591@deffn Method accept-log (@var{self} @code{<log-handler>}) (@var{level} @code{<top>}) (@var{time} @code{<top>}) (@var{str} @code{<top>}) 592@end deffn 593 594@anchor{logging logger <logger>}@deftp Class <logger> 595This is the class that aggregates and manages log handlers. It also 596maintains the global information about which levels of log messages are 597enabled, and which have been suppressed. Keyword arguments accepted on 598creation are: 599 600@table @code 601@item #:handlers 602This optional parameter must be a list of objects derived from 603@code{<log-handler>}. Handlers can always be added later via 604@code{add-handler!} calls. 605 606@end table 607 608@end deftp 609 610@anchor{logging logger add-handler!}@deffn Generic add-handler! 611@code{add-handler! lgr handler}. Adds @var{handler} to @var{lgr}'s list 612of handlers. All subsequent logs will be sent through the new handler, 613as well as any previously registered handlers. 614 615@end deffn 616 617@deffn Method add-handler! (@var{lgr} @code{<logger>}) (@var{handler} @code{<log-handler>}) 618@end deffn 619 620@anchor{logging logger log-msg}@deffn Generic log-msg 621@code{log-msg [lgr] lvl arg1 arg2 ...}. Send a log message made up of 622the @code{display}'ed representation of the given arguments. The log is 623generated at level @var{lvl}, which should be a symbol. If the 624@var{lvl} is disabled, the log message is not generated. Generated log 625messages are sent through each of @var{lgr}'s handlers. 626 627If the @var{lgr} parameter is omitted, then the default logger is used, 628if one is set. 629 630As the args are @code{display}'ed, a large string is built up. Then, 631the string is split at newlines and sent through the log handlers as 632independent log messages. The reason for this behavior is to make 633output nicer for log handlers that prepend information like pid and 634timestamps to log statements. 635 636@lisp 637;; logging to default logger, level of WARN 638 (log-msg 'WARN "Warning! " x " is bigger than " y "!!!") 639 640;; looking up a logger and logging to it 641 (let ((l (lookup-logger "main"))) 642 (log-msg l 'CRITICAL "FAILURE TO COMMUNICATE!") 643 (log-msg l 'CRITICAL "ABORTING NOW")) 644@end lisp 645 646@end deffn 647 648@deffn Method log-msg (@var{lgr} @code{<logger>}) (@var{lvl} @code{<top>}) (@var{objs} @code{<top>})... 649@end deffn 650 651@deffn Method log-msg (@var{lvl} @code{<symbol>}) (@var{objs} @code{<top>})... 652@end deffn 653 654@anchor{logging logger set-default-logger!}@defun set-default-logger! lgr 655Sets the given logger, @var{lgr}, as the default for logging methods 656where a logger is not given. @var{lgr} can be an instance of 657@code{<logger>}, a string that has been registered via 658@code{register-logger!}, or @code{#f} to remove the default logger. 659 660With this mechanism, most applications will never need to worry about 661logger registration or lookup. 662 663@lisp 664;; example 1 665 (set-default-logger! "main") ;; look up "main" logger and make it the default 666 667;; example 2 668 (define lgr (make <logger>)) 669 (add-handler! lgr 670 (make <port-handler> 671 #:port (current-error-port))) 672 (set-default-logger! lgr) 673 (log-msg 'CRITICAL "This is a message to the default logger!!!") 674 (log-msg lgr 'CRITICAL "This is a message to a specific logger!!!") 675@end lisp 676 677@end defun 678 679@anchor{logging logger register-logger!}@defun register-logger! str lgr 680Makes @var{lgr} accessible from other parts of the program by a name 681given in @var{str}. @var{str} should be a string, and @var{lgr} should 682be an instance of class @code{<logger>}. 683 684@lisp 685 (define main-log (make <logger>)) 686 (define corba-log (make <logger>)) 687 (register-logger! "main" main-log) 688 (register-logger! "corba" corba-log) 689 690;; in a completely different part of the program.... 691 (log-msg (lookup-logger "corba") 'WARNING "This is a corba warning.") 692@end lisp 693 694@end defun 695 696@anchor{logging logger lookup-logger}@defun lookup-logger str 697Looks up an instance of class @code{<logger>} by the name given in 698@var{str}. The string should have already been registered via a call to 699@code{register-logger!}. 700 701@end defun 702 703@anchor{logging logger enable-log-level!}@defun enable-log-level! lgr lvl 704Enables a specific logging level given by the symbol @var{lvl}, such 705that messages at that level will be sent to the log handlers. @var{lgr} 706can be of type @code{<logger>} or @code{<log-handler>}. 707 708Note that any levels that are neither enabled or disabled are treated as 709enabled by the logging system. This is so that misspelt level names do 710not cause a logging blackout. 711 712@end defun 713 714@anchor{logging logger disable-log-level!}@defun disable-log-level! lgr lvl 715Disables a specific logging level, such that messages at that level will 716not be sent to the log handlers. @var{lgr} can be of type 717@code{<logger>} or @code{<log-handler>}. 718 719Note that any levels that are neither enabled or disabled are treated as 720enabled by the logging system. This is so that misspelt level names do 721not cause a logging blackout. 722 723@end defun 724 725@anchor{logging logger flush-log}@deffn Generic flush-log 726@code{flush-log handler}. Tells the @code{handler} to output any log 727statements it may have buffered up. Handlers for which a flush 728operation doesn't make sense can choose not to implement this method. 729The default implementation just returns @code{#t}. 730 731@end deffn 732 733@deffn Method flush-log (@var{lgr} @code{<logger>}) 734@end deffn 735 736@deffn Method flush-log 737@end deffn 738 739@deffn Method flush-log (@var{lh} @code{<log-handler>}) 740@end deffn 741 742@anchor{logging logger open-log!}@deffn Generic open-log! 743@code{open-log! handler}. Tells the @code{handler} to open its log. 744Handlers for which an open operation doesn't make sense can choose not 745to implement this method. The default implementation just returns 746@code{#t}. 747 748@end deffn 749 750@deffn Method open-log! 751@end deffn 752 753@deffn Method open-log! (@var{lgr} @code{<logger>}) 754@end deffn 755 756@deffn Method open-log! (@var{lh} @code{<log-handler>}) 757@end deffn 758 759@anchor{logging logger close-log!}@deffn Generic close-log! 760@code{open-log! handler}. Tells the @code{handler} to close its log. 761Handlers for which a close operation doesn't make sense can choose not 762to implement this method. The default implementation just returns 763@code{#t}. 764 765@end deffn 766 767@deffn Method close-log! 768@end deffn 769 770@deffn Method close-log! (@var{lgr} @code{<logger>}) 771@end deffn 772 773@deffn Method close-log! (@var{lh} @code{<log-handler>}) 774@end deffn 775 776@node logging port-log 777@chapter (logging port-log) 778@section Overview 779@anchor{cindex-logs through ports}@cindex logs, through ports 780@anchor{cindex-ports for logging}@cindex ports, for logging 781This module defines a log handler that writes to an arbitrary port of 782the user's choice. Uses of this handler could include: 783 784@itemize @bullet 785@item 786Sending logs across a socket to a network log collector. 787 788@item 789Sending logs to the screen 790 791@item 792Sending logs to a file 793 794@item 795Collecting logs in memory in a string port for later use 796 797@end itemize 798 799@section Usage 800@anchor{logging port-log <port-log>}@deftp Class <port-log> 801This is a log handler which writes logs to a user-provided port. 802 803Keywords recognized by @code{<port-log>} on creation are: 804 805@table @code 806@item #:port 807This is the port to which the log handler will write. 808 809@item #:formatter 810Allows the user to provide a function to use as the log formatter for 811this handler. @xref{logging logger <log-handler>}, for details. 812 813@end table 814 815Example of creating a @code{<port-log>}: 816 817@lisp 818 (make <port-log> #:port (current-error-port)) 819@end lisp 820 821@end deftp 822 823@node logging rotating-log 824@chapter (logging rotating-log) 825@section Overview 826@anchor{cindex-logs rotating}@cindex logs, rotating 827This module defines a log handler for text logs that rotate when they 828get to be a user-defined size. This is similar to the behavior of many 829UNIX standard log files. @xref{logging logger}, for more information in 830general on log handlers. 831 832@section Usage 833@anchor{logging rotating-log <rotating-log>}@deftp Class <rotating-log> 834This is a log handler which writes text logs that rotate when they reach 835a configurable size limit. 836 837Keywords recognized by @code{<rotating-log>} on creation are: 838 839@table @code 840@item #:num-files 841This is the number of log files you want the logger to use. Default is 8424. 843 844@item #:size-limit 845This is the size, in bytes, a log file must get before the logs get 846rotated. Default is 1MB (104876 bytes). 847 848@item #:file-name 849This is the base of the log file name. Default is ``logfile''. Numbers 850will be appended to the file name representing the log number. The 851newest log file is always ``@var{NAME}.1''. 852 853@item #:formatter 854Allows the user to provide a function to use as the log formatter for 855this handler. @xref{logging logger <log-handler>}, for details. 856 857@end table 858 859Example of creating a @code{<rotating-log>}: 860 861@lisp 862 (make <rotating-log> 863 #:num-files 3 864 #:size-limit 1024 865 #:file-name "test-log-file")) 866@end lisp 867 868@end deftp 869 870@node match-bind 871@chapter (match-bind) 872@section Overview 873@c 874Utility functions and syntax constructs for dealing with regular 875expressions in a concise manner. Will be submitted to Guile for 876inclusion. 877 878@section Usage 879@anchor{match-bind match-bind}@defspec match-bind 880Match a string against a regular expression, binding lexical variables 881to the various parts of the match. 882 883@var{vars} is a list of names to which to bind the parts of the match. 884The first variable of the list will be bound to the entire match, so the 885number of variables needed will be equal to the number of open 886parentheses (`(') in the pattern, plus one for the whole match. 887 888@var{consequent} is executed if the given expression @var{str} matches 889@var{regex}. If the string does not match, @var{alternate} will be 890executed if present. If @var{alternate} is not present, the result of 891@code{match-bind} is unspecified. 892 893Here is a short example: 894 895@example 896 (define (star-indent line) 897 "Returns the number of spaces until the first 898 star (`*') in the input, or #f if the first 899 non-space character is not a star." 900 (match-bind "^( *)\*.*$" line (_ spaces) 901 (string-length spaces) 902 #f)) 903@end example 904 905@code{match-bind} compiles the regular expression @var{regex} at macro 906expansion time. For this reason, @var{regex} must be a string literal, 907not an arbitrary expression. 908 909@end defspec 910 911@anchor{match-bind s///}@defun s/// pat subst 912Make a procedure that performs perl-like regular expression 913search-and-replace on an input string. 914 915The regular expression pattern @var{pat} is in the standard regular 916expression syntax accepted by @code{make-regexp}. The substitution 917string is very similar to perl's @code{s///} operator. Backreferences 918are indicated with a dollar sign (@samp{$}), and characters can be 919escaped with the backslash. 920 921@code{s///} returns a procedure of one argument, the input string to be 922matched. If the string matches the pattern, it will be returned with 923the first matching segment replaced as per the substitution string. 924Otherwise the string will be returned unmodified. 925 926Here are some examples: 927 928@example 929 ((s/// "foo" "bar") "foo bar baz qux foo") 930 @result{} "bar bar baz qux foo" 931 932 ((s/// "zag" "bar") "foo bar baz qux foo") 933 @result{} "foo bar baz qux foo" 934 935 ((s/// "(f(o+)) (zag)?" "$1 $2 $3") 936 "foo bar baz qux foo") 937 @result{} "foo oo bar baz qux foo" 938@end example 939 940@end defun 941 942@anchor{match-bind s///g}@defun s///g pat subst 943Make a procedure that performs perl-like global search-and-replace on an 944input string. 945 946The @var{pat} and @var{subst} arguments are as in the non-global 947@code{s///}. @xref{match-bind s///,,s///}, for more information. 948 949@code{s///g} differs from @code{s///} in that it does a global search 950and replace, not stopping at the first match. 951 952@end defun 953 954@node math minima 955@chapter (math minima) 956@section Overview 957@anchor{cindex-golden section}@cindex golden section 958@anchor{cindex-section golden}@cindex section, golden 959@anchor{cindex-minimum of a mathematical function}@cindex minimum, of a mathematical function 960This module contains functions for computing the minimum values of 961mathematical expressions on an interval. 962 963@section Usage 964@anchor{math minima golden-section-search}@defun golden-section-search f x0 x1 prec 965The Golden Section Search algorithm finds minima of functions which are 966expensive to compute or for which derivatives are not available. 967Although optimum for the general case, convergence is slow, requiring 968nearly 100 iterations for the example (x^3-2x-5). 969 970If the derivative is available, Newton-Raphson is probably a better 971choice. If the function is inexpensive to compute, consider 972approximating the derivative. 973 974@var{x0} and @var{x1} are real numbers. The (single argument) procedure 975@var{func} is unimodal over the open interval (@var{x0}, @var{x1}). That 976is, there is exactly one point in the interval for which the derivative 977of @var{func} is zero. 978 979It returns a pair (@var{x} . @var{func}(@var{x})) where 980@var{func}(@var{x}) is the minimum. The @var{prec} parameter is the 981stop criterion. If @var{prec} is a positive number, then the iteration 982continues until @var{x} is within @var{prec} from the true value. If 983@var{prec} is a negative integer, then the procedure will iterate 984@var{-prec} times or until convergence. If @var{prec} is a procedure of 985seven arguments, @var{x0}, @var{x1}, @var{a}, @var{b}, @var{fa}, 986@var{fb}, and @var{count}, then the iterations will stop when the 987procedure returns @code{#t}. 988 989Analytically, the minimum of x^3-2x-5 is 0.816497. 990 991@example 992 (define func (lambda (x) (+ (* x (+ (* x x) -2)) -5))) 993 (golden-section-search func 0 1 (/ 10000)) 994 ==> (816.4883855245578e-3 . -6.0886621077391165) 995 (golden-section-search func 0 1 -5) 996 ==> (819.6601125010515e-3 . -6.088637561916407) 997 (golden-section-search func 0 1 998 (lambda (a b c d e f g ) (= g 500))) 999 ==> (816.4965933140557e-3 . -6.088662107903635) 1000@end example 1001 1002@end defun 1003 1004@node math primes 1005@chapter (math primes) 1006@section Overview 1007@anchor{cindex-prime number}@cindex prime number 1008@anchor{cindex-numbers prime}@cindex numbers, prime 1009@anchor{cindex-numbers prime factors of}@cindex numbers, prime factors of 1010@anchor{cindex-prime factors}@cindex prime factors 1011@anchor{cindex-factors prime}@cindex factors, prime 1012This module defines functions related to prime numbers, and prime 1013factorization. 1014 1015@section Usage 1016@anchor{math primes prime:trials}@defvar prime:trials 1017This is the maximum number of iterations of Solovay-Strassen that will 1018be done to test a number for primality. The chance of error (a 1019composite being labelled prime) is @code{(expt 2 (- prime:trials))}. 1020 1021@end defvar 1022 1023@anchor{math primes prime?}@defun prime? n 1024Returns @code{#f} if @var{n} is composite, and @code{t} if it is prime. 1025There is a slight chance, @code{(expt 2 (- prime:trials))}, that a 1026composite will return @code{#t}. 1027 1028@end defun 1029 1030@anchor{math primes prime>}@defun prime> start 1031Return the first prime number greater than @var{start}. It doesn't 1032matter if @var{start} is prime or composite. 1033 1034@end defun 1035 1036@anchor{math primes primes>}@defun primes> start count 1037Returns a list of the first @var{count} prime numbers greater than 1038@var{start}. 1039 1040@end defun 1041 1042@anchor{math primes prime<}@defun prime< start 1043Return the first prime number less than @var{start}. It doesn't matter 1044if @var{start} is prime or composite. If no primes are less than 1045@var{start}, @code{#f} will be returned. 1046 1047@end defun 1048 1049@anchor{math primes primes<}@defun primes< start count 1050Returns a list of the first @var{count} prime numbers less than 1051@var{start}. If there are fewer than @var{count} prime numbers less 1052than @var{start}, then the returned list will have fewer than 1053@var{start} elements. 1054 1055@end defun 1056 1057@anchor{math primes factor}@defun factor k 1058Returns a list of the prime factors of @var{k}. The order of the 1059factors is unspecified. In order to obtain a sorted list do 1060@code{(sort! (factor @var{k}) <)}. 1061 1062@end defun 1063 1064@node os process 1065@chapter (os process) 1066@section Overview 1067@anchor{cindex-Goosh module}@cindex Goosh module 1068@anchor{cindex-process Operating System}@cindex process, Operating System 1069@anchor{cindex-process chain}@cindex process chain 1070@anchor{cindex-pipeline process}@cindex pipeline, process 1071This is a library for execution of other programs from Guile. It also 1072allows communication using pipes (or a pseudo terminal device, but 1073that's not currently implemented). This code originates in the 1074@code{(goosh)} modules, which itself was part of goonix in one of 1075Guile's past lives. 1076 1077The following will hold when starting programs: 1078 1079@enumerate 1080@item 1081If the name of the program does not contain a @code{/} then the 1082directories listed in the current @code{PATH} environment variable are 1083searched to locate the program. 1084 1085@item 1086Unlike for the corresponding primitive exec procedures, e.g., 1087@code{execlp}, the name of the program can not be set independently of 1088the path to execute: the zeroth and first members of the argument vector 1089are combined into one. 1090 1091@end enumerate 1092 1093All symbols exported with the prefix @code{os:process:} are there in 1094support of macros that use them. They should be ignored by users of 1095this module. 1096 1097@section Usage 1098@anchor{os process os:process:pipe-fork-child}@defspec os:process:pipe-fork-child 1099@end defspec 1100 1101@anchor{os process run+}@defspec run+ args 1102Evaluate an expression in a new foreground process and wait for its 1103completion. If no connection terms are specified, then all ports except 1104@code{current-input-port}, @code{current-output-port} and 1105@code{current-error-port} will be closed in the new process. The file 1106descriptors underlying these ports will not be changed. 1107 1108The value returned is the exit status from the new process as returned 1109by the @code{waitpid} procedure. 1110 1111The @var{keywords} and @var{connections} arguments are optional: see 1112@code{run-concurrently+}, which is documented below. The 1113@code{#:foreground} keyword is implied. 1114 1115@example 1116 (run+ (begin (write (+ 2 2)) (newline) (quit 0))) 1117@end example 1118 1119@example 1120 (run+ (tail-call-program "cat" "/etc/passwd")) 1121@end example 1122 1123@end defspec 1124 1125@anchor{os process run-concurrently+}@defspec run-concurrently+ args 1126Evaluate an expression in a new background process. If no connection 1127terms are specified, then all ports except @code{current-input-port}, 1128@code{current-output-port} and @code{current-error-port} will be closed 1129in the new process. The file descriptors underlying these ports will 1130not be changed. 1131 1132The value returned in the parent is the pid of the new process. 1133 1134When the process terminates its exit status can be collected using the 1135@code{waitpid} procedure. 1136 1137Keywords can be specified before the connection list: 1138 1139@code{#:slave} causes the new process to be put into a new session. If 1140@code{current-input-port} (after redirections) is a tty it will be 1141assigned as the controlling terminal. This option is used when 1142controlling a process via a pty. 1143 1144@code{#:no-auto-close} prevents the usual closing of ports which occurs 1145by default. 1146 1147@code{#:foreground} makes the new process the foreground job of the 1148controlling terminal, if the current process is using job control. (not 1149currently implemented). The default is to place it into the background 1150 1151The optional connection list can take several forms: 1152 1153@code{(port)} usually specifies that a given port not be closed. However 1154if @code{#:no-auto-close} is present it specifies instead a port which 1155should be closed. 1156 1157@code{(port 0)} specifies that a port be moved to a given file 1158descriptor (e.g., 0) in the new process. The order of the two 1159components is not significant, but one must be a number and the other 1160must evaluate to a port. If the file descriptor is one of the standard 1161set @code{(0, 1, 2)} then the corresponding standard port (e.g., 1162@code{current-input-port}) will be set to the specified port. 1163 1164Example: 1165 1166@example 1167 (let ((p (open-input-file "/etc/passwd"))) 1168 (run-concurrently+ (tail-call-program "cat") (p 0))) 1169@end example 1170 1171@end defspec 1172 1173@anchor{os process tail-call-pipeline}@defspec tail-call-pipeline args 1174Replace the current process image with a pipeline of connected 1175processes. 1176 1177The expressions in the pipeline are run in new background processes. The 1178foreground process waits for them all to terminate. The exit status is 1179derived from the status of the process at the tail of the pipeline: its 1180exit status if it terminates normally, otherwise 128 plus the number of 1181the signal that caused it to terminate. 1182 1183The signal handlers will be reset and file descriptors set up as for 1184@code{tail-call-program}. Like @code{tail-call-program} it does not 1185close open ports or flush buffers. 1186 1187Example: 1188 1189@example 1190 (tail-call-pipeline ("ls" "/etc") ("grep" "passwd")) 1191@end example 1192 1193@end defspec 1194 1195@anchor{os process tail-call-pipeline+}@defspec tail-call-pipeline+ args 1196Replace the current process image with a pipeline of connected 1197processes. 1198 1199Each process is specified by an expression and each pair of processes 1200has a connection list with pairs of file descriptors. E.g., @code{((1 12010) (2 0))} specifies that file descriptors 1 and 2 are to be connected 1202to file descriptor 0. This may also be written as @code{((1 2 0))}. 1203 1204The expressions in the pipeline are run in new background processes. The 1205foreground process waits for them all to terminate. The exit status is 1206derived from the status of the process at the tail of the pipeline: its 1207exit status if it terminates normally, otherwise 128 plus the number of 1208the signal that caused it to terminate. 1209 1210The signal handlers will be reset and file descriptors set up as for 1211@code{tail-call-program}. Like @code{tail-call-program} it does not 1212close open ports or flush buffers. 1213 1214Example: 1215 1216@example 1217 (tail-call-pipeline+ (tail-call-program "ls" "/etc") ((1 0)) 1218 (tail-call-program "grep" "passwd")) 1219@end example 1220 1221@end defspec 1222 1223@anchor{os process os:process:new-comm-pipes}@defun os:process:new-comm-pipes old-pipes out-conns 1224@end defun 1225 1226@anchor{os process os:process:pipe-make-commands}@defun os:process:pipe-make-commands fdes port portvar 1227@end defun 1228 1229@anchor{os process os:process:pipe-make-redir-commands}@defun os:process:pipe-make-redir-commands connections portvar 1230@end defun 1231 1232@anchor{os process os:process:setup-redirected-port}@defun os:process:setup-redirected-port port fdes 1233@end defun 1234 1235@anchor{os process run}@defun run prog . args 1236Execute @var{prog} in a new foreground process and wait for its 1237completion. The value returned is the exit status of the new process as 1238returned by the @code{waitpid} procedure. 1239 1240Example: 1241 1242@example 1243 (run "cat" "/etc/passwd") 1244@end example 1245 1246@end defun 1247 1248@anchor{os process run-concurrently}@defun run-concurrently . args 1249Start a program running in a new background process. The value returned 1250is the pid of the new process. 1251 1252When the process terminates its exit status can be collected using the 1253@code{waitpid} procedure. 1254 1255Example: 1256 1257@example 1258 (run-concurrently "cat" "/etc/passwd") 1259@end example 1260 1261@end defun 1262 1263@anchor{os process run-with-pipe}@defun run-with-pipe mode prog . args 1264Start @var{prog} running in a new background process. The value 1265returned is a pair: the CAR is the pid of the new process and the CDR is 1266either a port or a pair of ports (with the CAR containing the input port 1267and the CDR the output port). The port(s) can be used to read from the 1268standard output of the process and/or write to its standard input, 1269depending on the @var{mode} setting. The value of @var{mode} should be 1270one of "r", "w" or "r+". 1271 1272When the process terminates its exit status can be collected using the 1273@code{waitpid} procedure. 1274 1275Example: 1276 1277@example 1278 (use-modules (ice-9 rdelim)) ; needed by read-line 1279 (define catport (cdr (run-with-pipe "r" "cat" "/etc/passwd"))) 1280 (read-line catport) 1281@end example 1282 1283@end defun 1284 1285@anchor{os process tail-call-program}@defun tail-call-program prog . args 1286Replace the current process image by executing @var{prog} with the 1287supplied list of arguments, @var{args}. 1288 1289This procedure will reset the signal handlers and attempt to set up file 1290descriptors as follows: 1291 1292@enumerate 1293@item 1294File descriptor 0 is set from (current-input-port). 1295 1296@item 1297File descriptor 1 is set from (current-output-port). 1298 1299@item 1300File descriptor 2 is set from (current-error-port). 1301 1302@end enumerate 1303 1304If a port can not be used (e.g., because it's closed or it's a string 1305port) then the file descriptor is opened on the file specified by 1306@code{*null-device*} instead. 1307 1308Note that this procedure does not close any ports or flush output 1309buffers. Successfully executing @var{prog} will prevent the normal 1310flushing of buffers that occurs when Guile terminates. Doing otherwise 1311would be incorrect after forking a child process, since the buffers 1312would be flushed in both parent and child. 1313 1314Examples: 1315 1316@example 1317 (tail-call-program "cat" "/etc/passwd") 1318@end example 1319 1320@example 1321 (with-input-from-file "/etc/passwd" 1322 (lambda () 1323 (tail-call-program "cat"))) 1324@end example 1325 1326@end defun 1327 1328@node scheme documentation 1329@chapter (scheme documentation) 1330@section Overview 1331@c texinfo commentary 1332Defines some macros to help in documenting macros, variables, generic 1333functions, and classes. 1334 1335@section Usage 1336@anchor{scheme documentation define-macro-with-docs}@defspec define-macro-with-docs args 1337Define a macro with documentation. 1338 1339@end defspec 1340 1341@anchor{scheme documentation define-with-docs}@defspec define-with-docs args 1342Define a variable with documentation. 1343 1344@end defspec 1345 1346@anchor{scheme documentation define-generic-with-docs}@defspec define-generic-with-docs args 1347Define a generic function with documentation. 1348 1349@end defspec 1350 1351@anchor{scheme documentation define-class-with-docs}@defspec define-class-with-docs args 1352Define a class with documentation. 1353 1354@end defspec 1355 1356@node scheme kwargs 1357@chapter (scheme kwargs) 1358@section Overview 1359@c 1360Support for defining functions that take python-like keyword arguments. 1361In one of his early talks, Paul Graham wrote about a large system called 1362"Rtml": 1363 1364@quotation 1365Most of the operators in Rtml were designed to take keyword parameters, 1366and what a help that turned out to be. If I wanted to add another 1367dimension to the behavior of one of the operators, I could just add a 1368new keyword parameter, and everyone's existing templates would continue 1369to work. A few of the Rtml operators didn't take keyword parameters, 1370because I didn't think I'd ever need to change them, and almost every 1371one I ended up kicking myself about later. If I could go back and start 1372over from scratch, one of the things I'd change would be that I'd make 1373every Rtml operator take keyword parameters. 1374 1375@end quotation 1376 1377@xref{scheme kwargs lambda/kwargs,,lambda/kwargs}, for documentation and 1378examples. 1379 1380@xref{Optional Arguments,,,guile,Guile Reference Manual}, for more 1381information on Guile's standard support for optional and keyword 1382arguments. Quote taken from 1383@uref{http://lib.store.yahoo.net/lib/paulgraham/bbnexcerpts.txt}. 1384 1385@section Usage 1386@anchor{scheme kwargs define/kwargs}@defspec define/kwargs args 1387Defines a function that takes kwargs. @xref{scheme kwargs 1388lambda/kwargs}, for more information. 1389 1390@end defspec 1391 1392@anchor{scheme kwargs lambda/kwargs}@defspec lambda/kwargs args 1393Defines a function that takes keyword arguments. 1394 1395@var{bindings} is a list of bindings, each of which may either be a 1396symbol or a two-element symbol-and-default-value list. Symbols without 1397specified default values will default to @code{#f}. 1398 1399For example: 1400 1401@example 1402 (define frobulate (lambda/kwargs (foo (bar 13) (baz 42)) 1403 (list foo bar baz))) 1404 (frobulate) @result{} (#f 13 42) 1405 (frobulate #:baz 3) @result{} (#f 13 3) 1406 (frobulate #:foo 3) @result{} (3 13 42) 1407 (frobulate 3 4) @result{} (3 4 42) 1408 (frobulate 1 2 3) @result{} (1 2 3) 1409 (frobulate #:baz 2 #:bar 1) @result{} (#f 1 2) 1410 (frobulate 10 20 #:foo 3) @result{} (3 20 42) 1411@end example 1412 1413This function differs from the standard @code{lambda*} provided by Guile 1414in that invoking the function will accept positional arguments. As an 1415example, the @code{lambda/kwargs} behaves more intuitively in the 1416following case: 1417 1418@example 1419 ((lambda* (#:optional (bar 42) #:key (baz 73)) 1420 (list bar baz)) 1421 1 2) @result{} (1 73) 1422 ((lambda/kwargs ((bar 42) (baz 73)) 1423 (list bar baz)) 1424 1 2) @result{} (1 2) 1425@end example 1426 1427The fact that @code{lambda*} accepts the extra @samp{2} argument is 1428probably just a bug. In any case, @code{lambda/kwargs} does the right 1429thing. 1430 1431@end defspec 1432 1433@node search basic 1434@chapter (search basic) 1435@section Overview 1436@verbatim 1437 This module has the classic search functions in it. 1438@end verbatim 1439 1440@section Usage 1441@anchor{search basic depth-first-search}@defun depth-first-search init done? expander 1442Performs a depth-first search from initial state @var{init}. It will 1443return the first state it sees for which predicate @var{done?} returns 1444@code{#t}. It will use function @var{expander} to get a list of all 1445states reacheable from a given state. 1446 1447@var{init} can take any form the user wishes. This function treats it 1448as opaque data to pass to @var{done?} and @var{expander}. 1449 1450@var{done?} takes one argument, of the same type as @var{init}, and 1451returns either @code{#t} or @code{#f}. 1452 1453@var{expander} takes one argument, of the same type as @var{init}, and 1454returns a list of states that can be reached from there. 1455 1456@end defun 1457 1458@anchor{search basic breadth-first-search}@defun breadth-first-search init done? expander 1459Performs a breadth-first search from initial state @var{init}. It will 1460return the first state it sees for which predicate @var{done?} returns 1461@code{#t}. It will use function @var{expander} to get a list of all 1462states reacheable from a given state. 1463 1464@var{init} can take any form the user wishes. This function treats it 1465as opaque data to pass to @var{done?} and @var{expander}. 1466 1467@var{done?} takes one argument, of the same type as @var{init}, and 1468returns either @code{#t} or @code{#f}. 1469 1470@var{expander} takes one argument, of the same type as @var{init}, and 1471returns a list of states that can be reached from there. 1472 1473@end defun 1474 1475@anchor{search basic binary-search-sorted-vector}@defun binary-search-sorted-vector vec target [cmp] [default] 1476Searches a sorted vector @var{vec} for item @var{target}. A binary 1477search is employed which should find an item in O(log n) time if it is 1478present. If @var{target} is found, the index into @var{vec} is 1479returned. 1480 1481As part of the search, the function @var{cmp} is applied to determine 1482whether a vector item is less than, greater than, or equal to the 1483@var{target}. If @var{target} cannot be found in the vector, then 1484@var{default} is returned. 1485 1486@var{cmp} defaults to @code{-}, which gives a correct comparison for 1487vectors of numbers. @var{default} will be @code{#f} if another value is 1488not given. 1489 1490@lisp 1491 (binary-search-sorted-vector #(10 20 30) 20) @result{} 1 1492@end lisp 1493 1494@end defun 1495 1496@node string completion 1497@chapter (string completion) 1498@section Overview 1499This module provides a facility that can be used to implement features 1500such as TAB-completion in programs. A class @code{<string-completer>} 1501tracks all the potential complete strings. Here is an example usage. 1502 1503@lisp 1504(use-modules (string completion) 1505 (oop goops) 1506 (srfi srfi-11)) ;; for the (let-values) 1507 1508(define c (make <string-completer>)) 1509(add-strings! c "you your yourself yourselves") 1510 1511(let-values (((completions expansion exact? unique?) (complete c "yours"))) 1512 (display completions)(newline) 1513 (display expansion) (newline) 1514 (display exact?)(newline) 1515 (display unique?)(newline)) 1516 1517==> ("yourself" "yourselves") 1518 "yoursel" 1519 #f 1520 #f 1521@end lisp 1522 1523There are several more options for usage, which are detailed in the 1524class and method documentation. 1525 1526@section Usage 1527@anchor{string completion <string-completer>}@deftp Class <string-completer> 1528This is the class that knows what the possible expansions are, and can 1529determine the completions of given partial strings. The following are 1530the recognized keywords on the call to @code{make}: 1531 1532@table @code 1533@item #:strings 1534This gives the completer an initial set of strings. It is optional, and 1535the @code{add-strings!} method can add strings to the completer later, 1536whether these initial strings were given or not. The strings that 1537follow this keyword can take any form that the @code{add-strings!} 1538method can take (see below). 1539 1540@item #:case-sensitive? 1541This is a boolean that directs the completer to do its comparisons in a 1542case sensiteve way or not. The default value is @code{#t}, for 1543case-sensitive behavior. 1544 1545@end table 1546 1547@end deftp 1548 1549@anchor{string completion case-sensitive-completion?}@deffn Generic case-sensitive-completion? 1550@code{case-sensitive-completion? completer}. Returns @code{#t} if the 1551completer is case-sensitive, and @code{#f} otherwise. 1552 1553@end deffn 1554 1555@deffn Method case-sensitive-completion? 1556@end deffn 1557 1558@anchor{string completion add-strings!}@deffn Generic add-strings! 1559@code{add-strings! completer strings}. Adds the given strings to the 1560set of possible comletions known to @var{completer}. @var{strings} can 1561either be a list of strings, or a single string of words separated by 1562spaces. The order of the words given is not important. 1563 1564@end deffn 1565 1566@deffn Method add-strings! (@var{sc} @code{<string-completer>}) (@var{strings} @code{<top>}) 1567@end deffn 1568 1569@anchor{string completion all-completions}@defun all-completions completer str 1570Returns a list of all possible completions for the given string 1571@var{str}. The returned list will be in alphabetical order. 1572 1573Note that users wanting to customize the completion algorithm can 1574subclass @code{<string-completer>} and override this method. 1575 1576@end defun 1577 1578@anchor{string completion complete}@deffn Generic complete 1579@code{complete completer str}. Accepts a string, @var{str}, and returns 1580four values via a @code{values} call. These are: 1581 1582@table @var 1583@item completions 1584This is the same list that would be returned from a call to 1585@code{all-completions}. 1586 1587@item expansion 1588This is the longest string that would have returned identical results. 1589In other words, this is what most programs replace your string with when 1590you press TAB once. This value will be equal to @var{str} if there were 1591no known completionss. 1592 1593@example 1594 ("wonders" "wonderment" "wondering") 1595completed against "won" yields an expansion 1596of "wonder" 1597@end example 1598 1599@item exact? 1600This will be @code{#t} if the returned @var{expansion} is an exact match 1601of one of the possible completions. 1602 1603@item unique? 1604This will be #t if there is only one possible completion. Note that 1605when @var{unique?} is @code{#t}, then @var{exact?} will also be 1606@code{#t}. 1607 1608@end table 1609 1610@end deffn 1611 1612@deffn Method complete (@var{sc} @code{<string-completer>}) (@var{str} @code{<top>}) 1613@end deffn 1614 1615@node string soundex 1616@chapter (string soundex) 1617@section Overview 1618Soundex algorithm, taken from Knuth, Vol. 3 ``Sorting and searching'', 1619pp 391--2 1620 1621@section Usage 1622@anchor{string soundex soundex}@defun soundex name 1623Performs the original soundex algorithm on the input @var{name}. Returns 1624the encoded string. The idea is for similar sounding sames to end up 1625with the same encoding. 1626 1627@lisp 1628 (soundex "Aiza") 1629=> "A200" 1630 (soundex "Aisa") 1631=> "A200" 1632 (soundex "Aesha") 1633=> "A200" 1634@end lisp 1635 1636@end defun 1637 1638@node string transform 1639@chapter (string transform) 1640@section Overview 1641Module @samp{(string transform)} provides functions for modifying 1642strings beyond that which is provided in the guile core and @samp{(srfi 1643srfi-13)}. 1644 1645@section Usage 1646@anchor{string transform escape-special-chars}@defun escape-special-chars str special-chars escape-char 1647Returns a copy of @var{str} with all given special characters preceded 1648by the given @var{escape-char}. 1649 1650@var{special-chars} can either be a single character, or a string 1651consisting of all the special characters. 1652 1653@lisp 1654;; make a string regexp-safe... 1655 (escape-special-chars "***(Example String)***" 1656 "[]()/*." 1657 #\\) 1658=> "\\*\\*\\*\\(Example String\\)\\*\\*\\*" 1659 1660;; also can escape a singe char... 1661 (escape-special-chars "richardt@@vzavenue.net" 1662 #\@@ 1663 #\@@) 1664=> "richardt@@@@vzavenue.net" 1665@end lisp 1666 1667@end defun 1668 1669@anchor{string transform transform-string}@defun transform-string str match? replace [start] [end] 1670Uses @var{match?} against each character in @var{str}, and performs a 1671replacement on each character for which matches are found. 1672 1673@var{match?} may either be a function, a character, a string, or 1674@code{#t}. If @var{match?} is a function, then it takes a single 1675character as input, and should return @samp{#t} for matches. 1676@var{match?} is a character, it is compared to each string character 1677using @code{char=?}. If @var{match?} is a string, then any character in 1678that string will be considered a match. @code{#t} will cause every 1679character to be a match. 1680 1681If @var{replace} is a function, it is called with the matched character 1682as an argument, and the returned value is sent to the output string via 1683@samp{display}. If @var{replace} is anything else, it is sent through 1684the output string via @samp{display}. 1685 1686Note that te replacement for the matched characters does not need to be 1687a single character. That is what differentiates this function from 1688@samp{string-map}, and what makes it useful for applications such as 1689converting @samp{#\&} to @samp{"&"} in web page text. Some other 1690functions in this module are just wrappers around common uses of 1691@samp{transform-string}. Transformations not possible with this 1692function should probably be done with regular expressions. 1693 1694If @var{start} and @var{end} are given, they control which portion of 1695the string undergoes transformation. The entire input string is still 1696output, though. So, if @var{start} is @samp{5}, then the first five 1697characters of @var{str} will still appear in the returned string. 1698 1699@lisp 1700; these two are equivalent... 1701 (transform-string str #\space #\-) ; change all spaces to -'s 1702 (transform-string str (lambda (c) (char=? #\space c)) #\-) 1703@end lisp 1704 1705@end defun 1706 1707@anchor{string transform expand-tabs}@defun expand-tabs str [tab-size] 1708Returns a copy of @var{str} with all tabs expanded to spaces. 1709@var{tab-size} defaults to 8. 1710 1711Assuming tab size of 8, this is equivalent to: 1712 1713@lisp 1714 (transform-string str #\tab " ") 1715@end lisp 1716 1717@end defun 1718 1719@anchor{string transform center-string}@defun center-string str [width] [chr] [rchr] 1720Returns a copy of @var{str} centered in a field of @var{width} 1721characters. Any needed padding is done by character @var{chr}, which 1722defaults to @samp{#\space}. If @var{rchr} is provided, then the padding 1723to the right will use it instead. See the examples below. left and 1724@var{rchr} on the right. The default @var{width} is 80. The default 1725@var{lchr} and @var{rchr} is @samp{#\space}. The string is never 1726truncated. 1727 1728@lisp 1729 (center-string "Richard Todd" 24) 1730=> " Richard Todd " 1731 1732 (center-string " Richard Todd " 24 #\=) 1733=> "===== Richard Todd =====" 1734 1735 (center-string " Richard Todd " 24 #\< #\>) 1736=> "<<<<< Richard Todd >>>>>" 1737@end lisp 1738 1739@end defun 1740 1741@anchor{string transform left-justify-string}@defun left-justify-string str [width] [chr] 1742@code{left-justify-string str [width chr]}. Returns a copy of @var{str} 1743padded with @var{chr} such that it is left justified in a field of 1744@var{width} characters. The default @var{width} is 80. Unlike 1745@samp{string-pad} from srfi-13, the string is never truncated. 1746 1747@end defun 1748 1749@anchor{string transform right-justify-string}@defun right-justify-string str [width] [chr] 1750Returns a copy of @var{str} padded with @var{chr} such that it is right 1751justified in a field of @var{width} characters. The default @var{width} 1752is 80. The default @var{chr} is @samp{#\space}. Unlike 1753@samp{string-pad} from srfi-13, the string is never truncated. 1754 1755@end defun 1756 1757@anchor{string transform collapse-repeated-chars}@defun collapse-repeated-chars str [chr] [num] 1758Returns a copy of @var{str} with all repeated instances of @var{chr} 1759collapsed down to at most @var{num} instances. The default value for 1760@var{chr} is @samp{#\space}, and the default value for @var{num} is 1. 1761 1762@lisp 1763 (collapse-repeated-chars "H e l l o") 1764=> "H e l l o" 1765 (collapse-repeated-chars "H--e--l--l--o" #\-) 1766=> "H-e-l-l-o" 1767 (collapse-repeated-chars "H-e--l---l----o" #\- 2) 1768=> "H-e--l--l--o" 1769@end lisp 1770 1771@end defun 1772 1773@node string wrap 1774@chapter (string wrap) 1775@section Overview 1776Module @samp{(string wrap)} provides functions for formatting text 1777strings such that they fill a given width field. A class, 1778@code{<text-wrapper>}, does the work, but two convenience methods create 1779instances of it for one-shot use, and in the process make for a more 1780``schemey'' interface. If many strings will be formatted with the same 1781parameters, it might be better performance-wise to create and use a 1782single @code{<text-wrapper>}. 1783 1784@section Usage 1785@anchor{string wrap <text-wrapper>}@deftp Class <text-wrapper> 1786This class encapsulates the parameters needing to be fed to the text 1787wrapping algorithm. The following are the recognized keywords on the 1788call to @code{make}: 1789 1790@table @code 1791@item #:line-width 1792This is the target length used when deciding where to wrap lines. 1793Default is 80. 1794 1795@item #:expand-tabs? 1796Boolean describing whether tabs in the input should be expanded. Default 1797is #t. 1798 1799@item #:tab-width 1800If tabs are expanded, this will be the number of spaces to which they 1801expand. Default is 8. 1802 1803@item #:collapse-whitespace? 1804Boolean describing whether the whitespace inside the existing text 1805should be removed or not. Default is #t. 1806 1807If text is already well-formatted, and is just being wrapped to fit in a 1808different width, then setting this to @samp{#f}. This way, many common 1809text conventions (such as two spaces between sentences) can be preserved 1810if in the original text. If the input text spacing cannot be trusted, 1811then leave this setting at the default, and all repeated whitespace will 1812be collapsed down to a single space. 1813 1814@item #:initial-indent 1815Defines a string that will be put in front of the first line of wrapped 1816text. Default is the empty string, ``''. 1817 1818@item #:subsequent-indent 1819Defines a string that will be put in front of all lines of wrapped text, 1820except the first one. Default is the empty string, ``''. 1821 1822@item #:break-long-words? 1823If a single word is too big to fit on a line, this setting tells the 1824wrapper what to do. Defaults to #t, which will break up long words. 1825When set to #f, the line will be allowed, even though it is longer than 1826the defined @code{#:line-width}. 1827 1828@end table 1829 1830Here's an example of creating a @code{<text-wrapper>}: 1831 1832@lisp 1833 (make <text-wrapper> #:line-width 48 #:break-long-words? #f) 1834@end lisp 1835 1836@end deftp 1837 1838@anchor{string wrap fill-string}@deffn Generic fill-string 1839@code{fill-string str keywds ...}. Wraps the text given in string 1840@var{str} according to the parameters provided in @var{keywds}, or the 1841default setting if they are not given. Returns a single string with the 1842wrapped text. Valid keyword arguments are discussed with the 1843@code{<text-wrapper>} class. 1844 1845@code{fill-string tw str}. fills @var{str} using the instance of 1846@code{<text-wrapper>} given as @var{tw}. 1847 1848@end deffn 1849 1850@deffn Method fill-string (@var{tw} @code{<text-wrapper>}) (@var{str} @code{<top>}) 1851@end deffn 1852 1853@deffn Method fill-string (@var{str} @code{<top>}) (@var{keywds} @code{<top>})... 1854@end deffn 1855 1856@anchor{string wrap string->wrapped-lines}@deffn Generic string->wrapped-lines 1857@code{string->wrapped-lines str keywds ...}. Wraps the text given in 1858string @var{str} according to the parameters provided in @var{keywds}, 1859or the default setting if they are not given. Returns a list of strings 1860representing the formatted lines. Valid keyword arguments are discussed 1861with the @code{<text-wrapper>} class. 1862 1863@code{string->wrapped-lines tw str}. Wraps the text given in string 1864@var{str} according to the given @code{<text-wrapper>} @var{tw}. Returns 1865a list of strings representing the formatted lines. Valid keyword 1866arguments are discussed with the @code{<text-wrapper>} class. 1867 1868@end deffn 1869 1870@deffn Method string->wrapped-lines (@var{tw} @code{<text-wrapper>}) (@var{str} @code{<top>}) 1871@end deffn 1872 1873@deffn Method string->wrapped-lines (@var{str} @code{<top>}) (@var{keywds} @code{<top>})... 1874@end deffn 1875 1876@node term ansi-color 1877@chapter (term ansi-color) 1878@section Overview 1879@anchor{cindex-terminals ANSI color codes for}@cindex terminals, ANSI color codes for 1880@anchor{cindex-ANSI color codes}@cindex ANSI color codes 1881@anchor{cindex-color codes ANSI}@cindex color codes, ANSI 1882The @samp{(term ansi-color)} module generates ANSI escape sequences for 1883colors. Here is an example of the module's use: 1884 1885@lisp 1886 method one: safer, since you know the colors 1887 will get reset 1888(display (colorize-string "Hello!\n" 'RED 'BOLD 'ON-BLUE)) 1889 1890 method two: insert the colors by hand 1891(for-each display 1892 (list (color 'RED 'BOLD 'ON-BLUE) 1893 "Hello!" 1894 (color 'RESET))) 1895@end lisp 1896 1897@section Usage 1898@anchor{term ansi-color color}@defun color . lst 1899Returns a string containing the ANSI escape sequence for producing the 1900requested set of attributes. 1901 1902The allowed values for the attributes are listed below. Unknown 1903attributes are ignored. 1904 1905@table @asis 1906@item Reset Attributes 1907@samp{CLEAR} and @samp{RESET} are allowed and equivalent. 1908 1909@item Non-Color Attributes 1910@samp{BOLD} makes text bold, and @samp{DARK} reverses this. 1911@samp{UNDERLINE} and @samp{UNDERSCORE} are equivalent. @samp{BLINK} 1912makes the text blink. @samp{REVERSE} invokes reverse video. 1913@samp{CONCEALED} hides output (as for getting passwords, etc.). 1914 1915@item Foregrond Color Attributes 1916@samp{BLACK}, @samp{RED}, @samp{GREEN}, @samp{YELLOW}, @samp{BLUE}, 1917@samp{MAGENTA}, @samp{CYAN}, @samp{WHITE} 1918 1919@item Background Color Attributes 1920@samp{ON-BLACK}, @samp{ON-RED}, @samp{ON-GREEN}, @samp{ON-YELLOW}, 1921@samp{ON-BLUE}, @samp{ON-MAGENTA}, @samp{ON-CYAN}, @samp{ON-WHITE} 1922 1923@end table 1924 1925@end defun 1926 1927@anchor{term ansi-color colorize-string}@defun colorize-string str . color-list 1928Returns a copy of @var{str} colorized using ANSI escape sequences 1929according to the attributes specified in @var{color-list}. At the end 1930of the returned string, the color attributes will be reset such that 1931subsequent output will not have any colors in effect. 1932 1933The allowed values for the attributes are listed in the documentation 1934for the @code{color} function. 1935 1936@end defun 1937 1938@node unit-test 1939@chapter (unit-test) 1940@section Overview 1941@section Usage 1942@anchor{unit-test assert-equal}@defun assert-equal expected got 1943@end defun 1944 1945@anchor{unit-test assert-true}@defun assert-true got 1946@end defun 1947 1948@anchor{unit-test assert-false}@defun assert-false got 1949@end defun 1950 1951@anchor{unit-test assert-numeric-=}@defun assert-numeric-= expected got precision 1952@end defun 1953 1954@anchor{unit-test <test-result>}@deftp Class <test-result> 1955@end deftp 1956 1957@anchor{unit-test tests-run}@deffn Generic tests-run 1958@end deffn 1959 1960@deffn Method tests-run 1961@end deffn 1962 1963@anchor{unit-test tests-failed}@deffn Generic tests-failed 1964@end deffn 1965 1966@deffn Method tests-failed 1967@end deffn 1968 1969@anchor{unit-test tests-log}@deffn Generic tests-log 1970@end deffn 1971 1972@deffn Method tests-log 1973@end deffn 1974 1975@anchor{unit-test failure-messages}@deffn Generic failure-messages 1976@end deffn 1977 1978@deffn Method failure-messages 1979@end deffn 1980 1981@anchor{unit-test test-started}@deffn Generic test-started 1982@end deffn 1983 1984@deffn Method test-started (@var{self} @code{<test-result>}) (@var{description} @code{<string>}) 1985@end deffn 1986 1987@anchor{unit-test test-failed}@deffn Generic test-failed 1988@end deffn 1989 1990@deffn Method test-failed (@var{self} @code{<test-result>}) (@var{description} @code{<string>}) 1991@end deffn 1992 1993@anchor{unit-test summary}@deffn Generic summary 1994@end deffn 1995 1996@deffn Method summary (@var{self} @code{<test-result>}) 1997@end deffn 1998 1999@anchor{unit-test <test-case>}@deftp Class <test-case> 2000@end deftp 2001 2002@anchor{unit-test name}@deffn Generic name 2003@end deffn 2004 2005@deffn Method name 2006@end deffn 2007 2008@deffn Method name 2009@end deffn 2010 2011@anchor{unit-test set-up-test}@deffn Generic set-up-test 2012@end deffn 2013 2014@deffn Method set-up-test (@var{self} @code{<test-case>}) 2015@end deffn 2016 2017@anchor{unit-test tear-down-test}@deffn Generic tear-down-test 2018@end deffn 2019 2020@deffn Method tear-down-test (@var{self} @code{<test-case>}) 2021@end deffn 2022 2023@anchor{unit-test run}@deffn Generic run 2024@end deffn 2025 2026@deffn Method run (@var{self} @code{<test-suite>}) (@var{result} @code{<test-result>}) 2027@end deffn 2028 2029@deffn Method run (@var{self} @code{<test-case>}) (@var{result} @code{<test-result>}) 2030@end deffn 2031 2032@anchor{unit-test <test-suite>}@deftp Class <test-suite> 2033@end deftp 2034 2035@anchor{unit-test tests}@deffn Generic tests 2036@end deffn 2037 2038@deffn Method tests 2039@end deffn 2040 2041@anchor{unit-test add}@deffn Generic add 2042@end deffn 2043 2044@deffn Method add (@var{self} @code{<test-suite>}) (@var{suite} @code{<test-suite>}) 2045@end deffn 2046 2047@deffn Method add (@var{self} @code{<test-suite>}) (@var{test} @code{<test-case>}) 2048@end deffn 2049 2050@anchor{unit-test run-all-defined-test-cases}@defun run-all-defined-test-cases 2051@end defun 2052 2053@anchor{unit-test exit-with-summary}@defun exit-with-summary result 2054@end defun 2055 2056@anchor{unit-test assert}@defspec assert 2057@end defspec 2058 2059@anchor{unit-test assert-exception}@defspec assert-exception 2060@end defspec 2061 2062@node Copying This Manual 2063@appendix Copying This Manual 2064This manual is covered under the GNU Free Documentation License. A copy of the FDL is provided here.@menu 2065* GNU Free Documentation License:: License for copying this manual 2066@end menu 2067 2068@include fdl.texi 2069@node Concept Index 2070@unnumbered Concept Index 2071@printindex cp 2072@node Function Index 2073@unnumbered Function Index 2074@printindex fn 2075@bye 2076