1 ;;;; lily.scm -- toplevel Scheme stuff
3 ;;;; source file of the GNU LilyPond music typesetter
5 ;;;; (c) 1998--2007 Jan Nieuwenhuizen <janneke@gnu.org>
6 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
8 ;; Internationalisation: (_i "to be translated") gets an entry in the
9 ;; POT file (gettext ) must be invoked explicitely to do the actual
11 ;;(define-macro (_i x) x)
12 ;;(define-macro-public _i (x) x)
13 ;;(define-public-macro _i (x) x)
15 (defmacro-public _i (x) x)
17 (read-enable 'positions)
20 (define-public PLATFORM
23 (car (string-tokenize (utsname:sysname (uname)))))))
25 (define scheme-options-definitions
30 ;; - [subject-]object-object-verb +"ing"
31 ;; - [subject-]-verb-object-object
33 (anti-alias-factor 1 "render at higher resolution and scale down result\nto prevent jaggies in PNG")
34 (backend ps "which backend to use by default; Options: eps, ps [default], scm, svg, tex, texstr)")
35 (check-internal-types #f "check every property assignment for types")
36 (clip-systems #f "Generate cut-out snippets of a score")
37 (datadir #f "LilyPond prefix for data files (Readonly).")
38 (debug-gc #f "dump memory debugging statistics")
39 (debug-gc-assert-parsed-dead #f "for memory debugging:
40 ensure that all refs to parsed objects are dead. This is an internal option, and is switched on automatically for -ddebug-gc.")
41 (debug-lexer #f "debug the flex lexer")
42 (debug-page-breaking-scoring #f "dump scores for many different page breaking configurations")
43 (debug-parser #f "debug the bison parser")
44 (debug-property-callbacks #f "debug cyclic callback chains")
45 (debug-skylines #f "debug skylines")
46 (delete-intermediate-files #f
47 "delete unusable PostScript files")
48 (dump-profile #f "dump memory and time information for each file")
49 (dump-cpu-profile #f "dump timing information (system-dependent)")
50 (dump-signatures #f "dump output signatures of each system. Used for regression testing.")
52 (eps-box-padding #f "Pad EPS bounding box left edge. Guarantee alignment between systems in LaTeX.")
54 "load fonts via Ghostscript.")
55 (gs-load-lily-fonts #f
56 "load only lilypond fonts via Ghostscript.")
57 (gui #f "running from gui; redirect stderr to log file")
58 (help #f "show this help.")
59 (include-book-title-preview #t "include book-titles in preview images.")
60 (include-eps-fonts #t "Include fonts in separate-system EPS files.")
61 (job-count #f "Process in parallel")
62 (log-file #f "redirect output to log FILE.log")
63 (midi-extension ,(if (eq? PLATFORM 'windows)
66 "set the default file extension for MIDI")
69 "relative for simultaneous music works
70 similar to chord syntax")
71 (point-and-click #t "use point & click")
72 (paper-size "a4" "the default paper size")
73 (pixmap-format "png16m" "GS format to use for pixel images")
74 (preview #f "make a incipit image. ")
75 (print-pages #t "print pages normally. ")
76 (protected-scheme-parsing #t "continue when finding errors in inline
77 scheme are caught in the parser. If off, halt
78 on errors, and print a stack trace.")
79 (profile-property-accesses #f "keep statistics of get_property() calls.")
81 (resolution 101 "resolution for generating PNG bitmaps")
82 (read-file-list #f "Read files to be processed from command line arguments")
84 (safe #f "Run safely")
85 (strict-infinity-checking #f "If yes, crash on encountering Inf/NaN.")
86 (strip-output-dir #t "If yes, strip directories from input files.")
87 (separate-log-files #f "Output to FILE.log per file.")
88 (trace-memory-frequency #f "Record Scheme cell usage this many times per second, and dump to file.")
89 (trace-scheme-coverage #f "Record coverage of Scheme files")
91 "how much verbosity for TTF font embedding?")
92 (show-available-fonts #f
93 "List font names available.")
94 (verbose ,(ly:command-line-verbose?) "value for the --verbose flag")
97 ;; need to do this in the beginning. Other parts of the
98 ;; Scheme init depend on these options.
102 (ly:add-option (car x) (cadr x) (caddr x)))
103 scheme-options-definitions)
107 (ly:set-option (car x) (cdr x)))
108 (eval-string (ly:command-line-options)))
112 (if (defined? 'set-debug-cell-accesses!)
113 (set-debug-cell-accesses! #f))
115 ;(set-debug-cell-accesses! 1000)
117 (use-modules (ice-9 regex)
130 (define-public fancy-format format)
131 (define-public (ergonomic-simple-format dest . rest)
132 "Like ice-9 format, but without the memory consumption."
135 (apply simple-format (cons #f (cons dest rest)))
136 (apply simple-format (cons dest rest))))
138 (define format ergonomic-simple-format)
141 (define-public (myd k v) (display k) (display ": ") (display v) (display ", ")
144 (define-public (print . args)
145 (apply format (cons (current-output-port) args)))
149 ;;; debugging evaluator is slower. This should
150 ;;; have a more sensible default.
152 (if (or (ly:get-option 'verbose)
153 (ly:get-option 'trace-memory-frequency)
154 (ly:get-option 'trace-scheme-coverage)
157 (ly:set-option 'protected-scheme-parsing #f)
158 (debug-enable 'debug)
159 (debug-enable 'backtrace)
160 (read-enable 'positions)))
163 (if (ly:get-option 'trace-scheme-coverage)
166 (define-public tex-backend?
167 (member (ly:get-option 'backend) '(texstr tex)))
169 (define-public parser #f)
172 ;; TeX C++ code actually hooks into TEX_STRING_HASHLIMIT
173 (define-public TEX_STRING_HASHLIMIT 10000000)
177 ;; gettext wrapper for guile < 1.7.2
178 (if (defined? 'gettext)
179 (define-public _ gettext)
180 (define-public _ ly:gettext))
182 (define-public (ly:load x)
183 (let* ((file-name (%search-load-path x)))
184 (if (ly:get-option 'verbose)
185 (ly:progress "[~A" file-name))
187 (ly:error (_ "cannot find: ~A") x))
188 (primitive-load file-name)
189 (if (ly:get-option 'verbose)
193 (let ((platform (string-tokenize
194 (vector-ref (uname) 0) char-set:letter+digit)))
195 (if (null? (cdr platform)) #f
196 (member (string-downcase (cadr platform)) '("95" "98" "me")))))
200 (define native-getcwd getcwd)
202 (if (string-index x #\\)
204 (string-regexp-substitute
206 (string-regexp-substitute "\\\\" "/" x))))
207 ;; FIXME: this prints a warning.
208 (define-public (ly-getcwd)
209 (slashify (native-getcwd))))
210 (else (define-public ly-getcwd getcwd)))
212 (define-public (is-absolute? file-name)
213 (let ((file-name-length (string-length file-name)))
214 (if (= file-name-length 0)
216 (or (eq? (string-ref file-name 0) #\/)
217 (and (eq? PLATFORM 'windows)
218 (> file-name-length 2)
219 (eq? (string-ref file-name 1) #\:)
220 (eq? (string-ref file-name 2) #\/))))))
222 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
224 (define (type-check-list location signature arguments)
225 "Typecheck a list of arguments against a list of type
226 predicates. Print a message at LOCATION if any predicate failed."
228 (define (recursion-helper signature arguments count)
229 (define (helper pred? arg count)
230 (if (not (pred? arg))
236 #f (_ "wrong type for argument ~a. Expecting ~a, found ~s")
237 count (type-name pred?) arg))
241 (if (null? signature)
243 (and (helper (car signature) (car arguments) count)
244 (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
246 (recursion-helper signature arguments 1))
248 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
252 ;;(define-public (output-framework) (write "hello\n"))
254 (define output-tex-module
255 (make-module 1021 (list (resolve-interface '(scm output-tex)))))
256 (define output-ps-module
257 (make-module 1021 (list (resolve-interface '(scm output-ps)))))
259 (define-public (ps-output-expression expr port)
260 (display (eval expr output-ps-module) port))
262 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
263 ;; Safe definitions utility
264 (define safe-objects (list))
266 (define-macro (define-safe-public arglist . body)
267 "Define a variable, export it, and mark it as safe, ie usable in LilyPond safe mode.
268 The syntax is the same as `define*-public'."
269 (define (get-symbol arg)
271 (get-symbol (car arg))
273 (let ((safe-symbol (get-symbol arglist)))
275 (define*-public ,arglist
277 (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
281 (define-safe-public (lilypond-version)
283 (map (lambda (x) (if (symbol? x)
289 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
292 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
296 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
304 "define-event-classes.scm"
305 "define-music-types.scm"
308 "chord-ignatzek-names.scm"
310 "chord-generic-names.scm"
313 "music-functions.scm"
316 "define-music-properties.scm"
320 "parser-ly-from-scheme.scm"
321 "ly-syntax-constructors.scm"
323 "define-context-properties.scm"
324 "translation-functions.scm"
336 "predefined-fretboards.scm"
337 "define-markup-commands.scm"
338 "define-grob-properties.scm"
340 "define-grob-interfaces.scm"
341 "define-stencil-commands.scm"
345 "backend-library.scm"
348 ;; must be after everything has been defined
352 (for-each ly:load init-scheme-files)
355 (set! type-p-name-alist
357 (,boolean-or-symbol? . "boolean or symbol")
358 (,boolean? . "boolean")
360 (,grob-list? . "list of grobs")
361 (,hash-table? . "hash table")
362 (,input-port? . "input port")
363 (,integer? . "integer")
365 (,ly:context? . "context")
366 (,ly:dimension? . "dimension, in staff space")
367 (,ly:dir? . "direction")
368 (,ly:duration? . "duration")
369 (,ly:grob? . "layout object")
370 (,ly:input-location? . "input location")
371 (,ly:moment? . "moment")
372 (,ly:music? . "music")
373 (,ly:pitch? . "pitch")
374 (,ly:translator? . "translator")
375 (,ly:font-metric? . "font metric")
376 (,ly:simple-closure? . "simple closure")
377 (,markup-list? . "list of markups")
378 (,markup? . "markup")
379 (,ly:music-list? . "list of music")
380 (,number-or-grob? . "number or grob")
381 (,number-or-string? . "number or string")
382 (,number-pair? . "pair of numbers")
383 (,number? . "number")
384 (,output-port? . "output port")
386 (,procedure? . "procedure")
387 (,rhythmic-location? . "rhythmic location")
388 (,scheme? . "any type")
389 (,string? . "string")
390 (,symbol? . "symbol")
391 (,vector? . "vector")))
393 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
396 (define (profile-measurements)
403 (ly:assoc-get 'gc-time-taken stats))
405 (ly:assoc-get 'total-cells-allocated stats 0)
408 (define (dump-profile base last this)
410 ((outname (format "~a.profile" (dir-basename base ".ly")))
411 (diff (map (lambda (y) (apply - y)) (zip this last))))
413 (ly:progress "\nWriting timing to ~a..." outname)
414 (format (open-file outname "w")
415 "time: ~a\ncells: ~a\n"
416 (if (ly:get-option 'dump-cpu-profile)
423 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
426 (define gc-dumping #f)
427 (define gc-protect-stat-count 0)
429 (define-public (dump-live-object-stats outfile)
432 (format outfile "~a: ~a\n" (car x) (cdr x)))
433 (sort (gc-live-object-stats)
435 (string<? (car x) (car y))))))
437 (define-public (dump-gc-protects)
438 (set! gc-protect-stat-count (1+ gc-protect-stat-count))
439 (let* ((protects (sort
440 (hash-table->alist (ly:protects))
442 (< (object-address (car a))
443 (object-address (car b))))))
445 (out-file-name (string-append
446 "gcstat-" (number->string gc-protect-stat-count)
448 (outfile (open-file out-file-name "w")))
451 (display (format "Dumping GC statistics ~a...\n" out-file-name))
457 (format "~a (~a) = ~a\n" (object-address x) c x)
461 (not (symbol? (car x))))
465 (format outfile "\nprotected symbols: ~a\n"
466 (apply + (map (lambda (obj-count) (if (symbol? (car obj-count))
471 ;; (display (ly:smob-protects))
473 (if (defined? 'gc-live-object-stats)
475 (display "Live object statistics: GC'ing\n")
479 (display "Asserting dead objects\n")
480 (ly:set-option 'debug-gc-assert-parsed-dead #t)
482 (ly:set-option 'debug-gc-assert-parsed-dead #f)
484 (set! stats (gc-live-object-stats))
485 (display "Dumping live object statistics.\n")
486 (dump-live-object-stats outfile)))
496 gc-protect-stat-count
498 (let ((sym-stat (assoc sym stats)))
503 '(protected-objects bytes-malloced cell-heap-size
513 (define (check-memory)
514 "read /proc/self to check up on memory use."
515 (define (gulp-file name)
516 (let* ((file (open-input-file name))
517 (text (read-delimited "" file)))
521 ((stat (gulp-file "/proc/self/status"))
522 (lines (string-split stat #\newline))
523 (interesting (filter identity
526 (string-match "^VmData:[ \t]*([0-9]*) kB" l))
528 (mem (string->number (match:substring (car interesting) 1)))
532 (display (format "VMDATA: ~a\n" mem))
541 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
544 (define (multi-fork count)
545 "Split this process in COUNT helpers. Returns either a list of pids,
546 or the number of the process."
547 (define (helper count acc)
550 ((pid (primitive-fork)))
553 (helper (1- count) (cons pid acc))))
558 (define-public (lilypond-main files)
559 "Entry point for LilyPond."
561 (eval-string (ly:command-line-code))
563 (if (ly:get-option 'help)
568 (if (ly:get-option 'show-available-fonts)
570 (ly:font-config-display-fonts)
575 (if (ly:get-option 'gui)
583 (if (ly:get-option 'read-file-list)
586 (> (string-length s) 0))
588 (map (lambda (f) (string-split (ly:gulp-file f) #\nl))
592 (if (and (number? (ly:get-option 'job-count))
593 (>= (length files) (ly:get-option 'job-count)))
595 ((count (ly:get-option 'job-count))
596 (split-todo (split-list files count))
597 (joblist (multi-fork count))
600 (if (not (string-or-symbol? (ly:get-option 'log-file)))
601 (ly:set-option 'log-file "lilypond-multi-run"))
603 (if (number? joblist)
606 'log-file (format "~a-~a"
607 (ly:get-option 'log-file) joblist))
608 (set! files (vector-ref split-todo joblist)))
611 (ly:progress "\nForking into jobs: ~a\n" joblist)
614 (let* ((stat (cdr (waitpid pid))))
618 (acons (list-element-index joblist pid)
626 (logfile (format "~a-~a.log"
627 (ly:get-option 'log-file) job))
628 (log (ly:gulp-file logfile))
629 (len (string-length log))
630 (tail (substring log (max 0 (- len 1024)))))
632 (if (status:term-sig state)
635 (format (_ "job ~a terminated with signal: ~a")
636 job (status:term-sig state)))
638 (_ "logfile ~a (exit ~a):\n~a")
639 logfile (status:exit-val state) tail))))
644 (ly:error "Children ~a exited with errors." (map car errors)))
646 ;; must overwrite individual entries
647 (if (ly:get-option 'dump-profile)
648 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
650 (exit (if (null? errors) 0 1))))))
652 (if (string-or-symbol? (ly:get-option 'log-file))
653 (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
655 (let ((failed (lilypond-all files)))
656 (if (ly:get-option 'trace-scheme-coverage)
658 (coverage:show-all (lambda (f) (string-contains f "lilypond"))
663 (ly:error (_ "failed files: ~S") (string-join failed))
666 ;; HACK: be sure to exit with single newline
670 (define-public (lilypond-all files)
672 (separate-logs (ly:get-option 'separate-log-files))
675 (open-file (if (string-or-symbol? (ly:get-option 'log-file))
676 (format "~a.log" (ly:get-option 'log-file))
677 "/dev/tty") "a") #f))
678 (do-measurements (ly:get-option 'dump-profile))
679 (handler (lambda (key failed-file)
680 (set! failed (append (list failed-file) failed)))))
686 ((start-measurements (if do-measurements
687 (profile-measurements)
689 (base (dir-basename x ".ly"))
690 (all-settings (ly:all-options)))
693 (ly:stderr-redirect (format "~a.log" base) "w"))
695 (format ping-log "Procesing ~a\n" base))
697 (if (ly:get-option 'trace-memory-frequency)
698 (mtrace:start-trace (ly:get-option 'trace-memory-frequency)))
700 (lilypond-file handler x)
701 (if start-measurements
702 (dump-profile x start-measurements (profile-measurements)))
704 (if (ly:get-option 'trace-memory-frequency)
707 (mtrace:dump-results base)))
711 (ly:set-option (car s) (cdr s)))
714 (ly:clear-anonymous-modules)
715 (ly:set-option 'debug-gc-assert-parsed-dead #t)
717 (ly:set-option 'debug-gc-assert-parsed-dead #f)
720 (if (ly:get-option 'debug-gc)
722 (if (= (random 40) 1)
723 (ly:reset-all-fonts)))))
727 ;; we want the failed-files notice in the aggregrate logfile.
729 (format ping-log "Failed files: ~a\n" failed))
731 (if (ly:get-option 'dump-profile)
732 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
736 (define (lilypond-file handler file-name)
737 (catch 'ly-file-failed
738 (lambda () (ly:parse-file file-name))
739 (lambda (x . args) (handler x file-name))))
741 (use-modules (scm editor))
743 (define-public (gui-main files)
745 (gui-no-files-handler))
747 (if (not (string? (ly:get-option 'log-file)))
748 (let* ((base (dir-basename (car files) ".ly"))
749 (log-name (string-append base ".log")))
750 (if (not (ly:get-option 'gui))
751 (ly:message (_ "Redirecting output to ~a...") log-name))
752 (ly:stderr-redirect log-name "w")
753 (ly:message "# -*-compilation-*-"))
755 (let ((failed (lilypond-all files)))
759 (ly:stderr-redirect "foo" "r")
760 (system (get-editor-command log-name 0 0 0))
761 (ly:error (_ "failed files: ~S") (string-join failed))
766 (define (gui-no-files-handler)
767 (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
768 ;; FIXME: soft-code, localize
769 (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
770 (cmd (get-editor-command welcome-ly 0 0 0)))
771 (ly:message (_ "Invoking `~a'...") cmd)