1 ;;;; This file is part of LilyPond, the GNU music typesetter.
3 ;;;; Copyright (C) 1998--2010 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
6 ;;;; LilyPond is free software: you can redistribute it and/or modify
7 ;;;; it under the terms of the GNU General Public License as published by
8 ;;;; the Free Software Foundation, either version 3 of the License, or
9 ;;;; (at your option) any later version.
11 ;;;; LilyPond is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;;;; GNU General Public License for more details.
16 ;;;; You should have received a copy of the GNU General Public License
17 ;;;; along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
19 ;; Internationalisation: (_i "to be translated") gets an entry in the
20 ;; POT file; (gettext ...) must be invoked explicitly to do the actual
23 ;; (define-macro (_i x) x)
24 ;; (define-macro-public _i (x) x)
25 ;; (define-public-macro _i (x) x)
28 (defmacro-public _i (x) x)
30 (read-enable 'positions)
33 (define-public PLATFORM
36 (car (string-tokenize (utsname:sysname (uname)))))))
38 (define scheme-options-definitions
42 ;; - [subject-]object-object-verb +"ing"
43 ;; - [subject-]-verb-object-object
45 ;; Avoid overlong lines in `lilypond -dhelp'! Strings should not
46 ;; be longer than 48 characters per line.
49 "Render at higher resolution (using given factor)
50 and scale down result to prevent jaggies in
53 "Create .tex, .texi, .count files in the
56 "Select backend. Possible values: 'eps, 'null,
57 'ps, 'scm, 'socket, 'svg.")
58 (check-internal-types #f
59 "Check every property assignment for types.")
61 "Generate cut-out snippets of a score.")
63 "LilyPond prefix for data files (read-only).")
65 "Dump memory debugging statistics.")
66 (debug-gc-assert-parsed-dead #f
67 "For memory debugging: Ensure that all
68 references to parsed objects are dead. This is
69 an internal option, and is switched on
70 automatically for `-ddebug-gc'.")
72 "Debug the flex lexer.")
73 (debug-page-breaking-scoring #f
74 "Dump scores for many different page breaking
77 "Debug the bison parser.")
78 (debug-property-callbacks #f
79 "Debug cyclic callback chains.")
82 (delete-intermediate-files #t
83 "Delete unusable, intermediate PostScript files.")
85 "Dump memory and time information for each file.")
87 "Dump timing information (system-dependent).")
89 "Dump output signatures of each system. Used for
92 "Pad left edge of the output EPS bounding box by
93 given amount (in mm).")
95 "Load fonts via Ghostscript.")
96 (gs-load-lily-fonts #f
97 "Load only LilyPond fonts via Ghostscript.")
99 "Run LilyPond from a GUI and redirect stderr to
103 (include-book-title-preview #t
104 "Include book titles in preview images.")
105 (include-eps-fonts #t
106 "Include fonts in separate-system EPS files.")
108 "Process in parallel, using the given number of
111 "If string FOO is given as argument, redirect
112 output to log file `FOO.log'.")
113 (midi-extension ,(if (eq? PLATFORM 'windows)
116 "Set the default file extension for MIDI output
117 file to given string.")
118 (music-strings-to-paths #f
119 "Convert text strings to paths when glyphs belong
122 "Make \\relative mode for simultaneous music work
123 similar to chord syntax.")
125 "Add point & click links to PDF output.")
127 "Set default paper size.")
128 (pixmap-format "png16m"
129 "Set GhostScript's output format for pixel images.")
131 "Create preview images also.")
133 "Print pages in the normal way.")
134 (protected-scheme-parsing #t
135 "Continue when errors in inline scheme are caught
136 in the parser. If #f, halt on errors and print
138 (profile-property-accesses #f
139 "Keep statistics of get_property() calls.")
141 "Set resolution for generating PNG pixmaps to
142 given value (in dpi).")
144 "Specify name of a file which contains a list of
145 input files to be processed.")
146 (relative-includes #f
147 "When processing an \\include command, look for
148 the included file relative to the current file
149 (instead of the root file)")
151 "Run in safer mode.")
152 (separate-log-files #f
153 "For input files `FILE1.ly', `FILE2.ly', ...
154 output log data to files `FILE1.log',
156 (show-available-fonts #f
157 "List available font names.")
158 (strict-infinity-checking #f
159 "Force a crash on encountering Inf and NaN
160 floating point exceptions.")
162 "Don't use directories from input files while
163 constructing output file names.")
165 "Use woff font files in SVG backend.")
166 (trace-memory-frequency #f
167 "Record Scheme cell usage this many times per
168 second. Dump results to `FILE.stacks' and
170 (trace-scheme-coverage #f
171 "Record coverage of Scheme files in `FILE.cov'.")
172 (verbose ,(ly:command-line-verbose?)
173 "Value of the --verbose flag (read-only).")
175 "Change all warning and programming_error
176 messages into errors.")
179 ;; Need to do this in the beginning. Other parts of the Scheme
180 ;; initialization depend on these options.
182 (for-each (lambda (x)
183 (ly:add-option (car x) (cadr x) (caddr x)))
184 scheme-options-definitions)
186 (for-each (lambda (x)
187 (ly:set-option (car x) (cdr x)))
188 (eval-string (ly:command-line-options)))
192 (if (defined? 'set-debug-cell-accesses!)
193 (set-debug-cell-accesses! #f))
195 ;(set-debug-cell-accesses! 1000)
197 (use-modules (ice-9 regex)
210 (define-public fancy-format
213 (define-public (ergonomic-simple-format dest . rest)
214 "Like ice-9 format, but without the memory consumption."
216 (apply simple-format (cons #f (cons dest rest)))
217 (apply simple-format (cons dest rest))))
220 ergonomic-simple-format)
223 (define-public (myd k v)
230 (define-public (print . args)
231 (apply format (cons (current-output-port) args)))
234 ;;; General settings.
236 ;;; Debugging evaluator is slower. This should have a more sensible
239 (if (or (ly:get-option 'verbose)
240 (ly:get-option 'trace-memory-frequency)
241 (ly:get-option 'trace-scheme-coverage))
243 (ly:set-option 'protected-scheme-parsing #f)
244 (debug-enable 'debug)
245 (debug-enable 'backtrace)
246 (read-enable 'positions)))
248 (if (ly:get-option 'trace-scheme-coverage)
251 (define-public parser #f)
253 (define music-string-to-path-backends
256 (if (memq (ly:get-option 'backend) music-string-to-path-backends)
257 (ly:set-option 'music-strings-to-paths #t))
259 (define-public _ gettext)
261 (define-public (ly:load x)
262 (let* ((file-name (%search-load-path x)))
263 (if (ly:get-option 'verbose)
264 (ly:progress "[~A" file-name))
266 (ly:error (_ "cannot find: ~A") x))
267 (primitive-load file-name)
268 (if (ly:get-option 'verbose)
269 (ly:progress "]\n"))))
272 (let ((platform (string-tokenize
273 (vector-ref (uname) 0) char-set:letter+digit)))
274 (if (null? (cdr platform)) #f
275 (member (string-downcase (cadr platform)) '("95" "98" "me")))))
278 (if (string-index x #\\)
280 (string-regexp-substitute
282 (string-regexp-substitute "\\\\" "/" x))))
284 (define-public (ly-getcwd)
285 (if (eq? PLATFORM 'windows)
289 (define-public (is-absolute? file-name)
290 (let ((file-name-length (string-length file-name)))
291 (if (= file-name-length 0)
293 (or (eq? (string-ref file-name 0) #\/)
294 (and (eq? PLATFORM 'windows)
295 (> file-name-length 2)
296 (eq? (string-ref file-name 1) #\:)
297 (eq? (string-ref file-name 2) #\/))))))
299 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
301 (define (type-check-list location signature arguments)
302 "Typecheck a list of arguments against a list of type predicates.
303 Print a message at LOCATION if any predicate failed."
304 (define (recursion-helper signature arguments count)
305 (define (helper pred? arg count)
306 (if (not (pred? arg))
311 #f (_ "wrong type for argument ~a. Expecting ~a, found ~s")
312 count (type-name pred?) arg))
316 (if (null? signature)
318 (and (helper (car signature) (car arguments) count)
319 (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
320 (recursion-helper signature arguments 1))
323 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
324 ;; Safe definitions utility
329 (define-macro (define-safe-public arglist . body)
330 "Define a variable, export it, and mark it as safe, i.e. usable in
331 LilyPond safe mode. The syntax is the same as `define*-public'."
332 (define (get-symbol arg)
334 (get-symbol (car arg))
337 (let ((safe-symbol (get-symbol arglist)))
339 (define*-public ,arglist
341 (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
345 (define-safe-public (lilypond-version)
347 (map (lambda (x) (if (symbol? x)
353 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
356 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
358 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
361 (define init-scheme-files
364 "define-event-classes.scm"
365 "define-music-callbacks.scm"
366 "define-music-types.scm"
369 "chord-ignatzek-names.scm"
371 "chord-generic-names.scm"
374 "music-functions.scm"
377 "define-music-properties.scm"
378 "time-signature-settings.scm"
382 "parser-ly-from-scheme.scm"
383 "ly-syntax-constructors.scm"
385 "define-context-properties.scm"
386 "translation-functions.scm"
398 "define-woodwind-diagrams.scm"
399 "display-woodwind-diagrams.scm"
400 "predefined-fretboards.scm"
401 "define-markup-commands.scm"
402 "define-grob-properties.scm"
404 "define-grob-interfaces.scm"
405 "define-stencil-commands.scm"
409 "backend-library.scm"
413 ;; must be after everything has been defined
416 (for-each ly:load init-scheme-files)
418 (define-public r5rs-primary-predicates
419 `((,boolean? . "boolean")
420 (,char? . "character")
421 (,number? . "number")
424 (,procedure? . "procedure")
425 (,string? . "string")
426 (,symbol? . "symbol")
427 (,vector? . "vector")))
429 (define-public r5rs-secondary-predicates
430 `((,char-alphabetic? . "alphabetic character")
431 (,char-lower-case? . "lower-case character")
432 (,char-numeric? . "numeric character")
433 (,char-upper-case? . "upper-case character")
434 (,char-whitespace? . "whitespace character")
436 (,complex? . "complex number")
437 (,even? . "even number")
438 (,exact? . "exact number")
439 (,inexact? . "inexact number")
440 (,integer? . "integer")
441 (,negative? . "negative number")
442 (,odd? . "odd number")
443 (,positive? . "positive number")
444 (,rational? . "rational number")
445 (,real? . "real number")
451 (,input-port? . "input port")
452 (,output-port? . "output port")
454 ;; would this ever be used?
455 (,eof-object? . "end-of-file object")
458 (define-public guile-predicates
459 `((,hash-table? . "hash table")
462 (define-public lilypond-scheme-predicates
463 `((,boolean-or-symbol? . "boolean or symbol")
465 (,cheap-list? . "list")
466 (,grob-list? . "list of grobs")
467 ;; this is built on cheap-list
468 (,list-or-symbol? . "list or symbol")
469 (,markup? . "markup")
470 (,markup-command-list? . "markup command list")
471 (,markup-list? . "markup list")
472 (,moment-pair? . "pair of moment objects")
473 (,number-or-grob? . "number or grob")
474 (,number-or-string? . "number or string")
475 (,number-pair? . "pair of numbers")
476 (,rhythmic-location? . "rhythmic location")
477 (,scheme? . "any type")
478 (,string-or-pair? . "string or pair")
479 (,string-or-symbol? . "string or symbol")
482 (define-public lilypond-exported-predicates
484 (,ly:context? . "context")
485 (,ly:dimension? . "dimension, in staff space")
486 (,ly:dir? . "direction")
487 (,ly:dispatcher? . "dispatcher")
488 (,ly:duration? . "duration")
489 (,ly:font-metric? . "font metric")
490 (,ly:grob? . "graphical (layout) object")
491 (,ly:grob-array? . "array of grobs")
492 (,ly:input-location? . "input location")
494 (,ly:iterator? . "iterator")
495 (,ly:lily-lexer? . "lily-lexer")
496 (,ly:lily-parser? . "lily-parser")
497 (,ly:listener? . "listener")
498 (,ly:moment? . "moment")
499 (,ly:music? . "music")
500 (,ly:music-function? . "music function")
501 (,ly:music-list? . "list of music objects")
502 (,ly:music-output? . "music output")
503 (,ly:otf-font? . "OpenType font")
504 (,ly:output-def? . "output definition")
505 (,ly:page-marker? . "page marker")
506 (,ly:pango-font? . "pango font")
507 (,ly:paper-book? . "paper book")
508 (,ly:paper-system? . "paper-system Prob")
509 (,ly:pitch? . "pitch")
510 (,ly:prob? . "property object")
511 (,ly:score? . "score")
512 (,ly:simple-closure? . "simple closure")
513 (,ly:skyline? . "skyline")
514 (,ly:skyline-pair? . "pair of skylines")
515 (,ly:source-file? . "source file")
516 (,ly:spanner? . "spanner")
517 (,ly:stencil? . "stencil")
518 (,ly:stream-event? . "stream event")
519 (,ly:translator? . "translator")
520 (,ly:translator-group? . "translator group")
524 (set! type-p-name-alist
525 (append r5rs-primary-predicates
526 r5rs-secondary-predicates
528 lilypond-scheme-predicates
529 lilypond-exported-predicates))
532 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
535 (define (profile-measurements)
538 (list (- (+ (tms:cutime t)
540 (assoc-get 'gc-time-taken stats))
541 (assoc-get 'total-cells-allocated stats 0))))
543 (define (dump-profile base last this)
544 (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
545 (diff (map (lambda (y) (apply - y)) (zip this last))))
546 (ly:progress "\nWriting timing to ~a..." outname)
547 (format (open-file outname "w")
548 "time: ~a\ncells: ~a\n"
549 (if (ly:get-option 'dump-cpu-profile)
554 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
555 ;; debug memory leaks
560 (define gc-protect-stat-count
563 (define-public (dump-live-object-stats outfile)
564 (for-each (lambda (x)
565 (format outfile "~a: ~a\n" (car x) (cdr x)))
566 (sort (gc-live-object-stats)
568 (string<? (car x) (car y))))))
570 (define-public (dump-gc-protects)
571 (set! gc-protect-stat-count (1+ gc-protect-stat-count))
572 (let* ((protects (sort (hash-table->alist (ly:protects))
574 (< (object-address (car a))
575 (object-address (car b))))))
576 (out-file-name (string-append
577 "gcstat-" (number->string gc-protect-stat-count)
579 (outfile (open-file out-file-name "w")))
581 (display (format "Dumping GC statistics ~a...\n" out-file-name))
582 (display (map (lambda (y)
586 (format "~a (~a) = ~a\n" (object-address x) c x)
590 (not (symbol? (car x))))
593 (format outfile "\nprotected symbols: ~a\n"
594 (apply + (map (lambda (obj-count)
595 (if (symbol? (car obj-count))
600 ;; (display (ly:smob-protects))
602 (if (defined? 'gc-live-object-stats)
604 (display "Live object statistics: GC'ing\n")
608 (display "Asserting dead objects\n")
609 (ly:set-option 'debug-gc-assert-parsed-dead #t)
611 (ly:set-option 'debug-gc-assert-parsed-dead #f)
612 (set! stats (gc-live-object-stats))
613 (display "Dumping live object statistics.\n")
614 (dump-live-object-stats outfile)))
616 (let* ((stats (gc-stats)))
617 (for-each (lambda (sym)
620 gc-protect-stat-count
622 (assoc-get sym stats "?"))
625 '(protected-objects bytes-malloced cell-heap-size)))
627 (close-port outfile)))
629 (define (check-memory)
630 "Read `/proc/self' to check up on memory use."
631 (define (gulp-file name)
632 (let* ((file (open-input-file name))
633 (text (read-delimited "" file)))
637 (let* ((stat (gulp-file "/proc/self/status"))
638 (lines (string-split stat #\newline))
639 (interesting (filter identity
642 (string-match "^VmData:[ \t]*([0-9]*) kB" l))
644 (mem (string->number (match:substring (car interesting) 1))))
645 (display (format "VMDATA: ~a\n" mem))
648 (begin (dump-gc-protects)
651 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
653 (define (multi-fork count)
654 "Split this process into COUNT helpers. Returns either a list of
655 PIDs or the number of the process."
656 (define (helper count acc)
658 (let* ((pid (primitive-fork)))
661 (helper (1- count) (cons pid acc))))
666 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
668 (define* (ly:exit status #:optional (silently #f) )
669 "Exit function for lilypond"
672 ((0) (ly:success "Compilation successfully completed"))
673 ((1) (ly:warning "Compilation completed with warnings or errors"))
674 (else (ly:message "")))
678 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
680 (define-public (lilypond-main files)
681 "Entry point for LilyPond."
682 (eval-string (ly:command-line-code))
683 (if (ly:get-option 'help)
684 (begin (ly:option-usage)
686 (if (ly:get-option 'show-available-fonts)
687 (begin (ly:font-config-display-fonts)
689 (if (ly:get-option 'gui)
694 (if (ly:get-option 'read-file-list)
697 (> (string-length s) 0))
700 (string-split (ly:gulp-file f) #\nl))
702 (if (and (number? (ly:get-option 'job-count))
703 (>= (length files) (ly:get-option 'job-count)))
704 (let* ((count (ly:get-option 'job-count))
705 (split-todo (split-list files count))
706 (joblist (multi-fork count))
708 (if (not (string-or-symbol? (ly:get-option 'log-file)))
709 (ly:set-option 'log-file "lilypond-multi-run"))
710 (if (number? joblist)
711 (begin (ly:set-option
712 'log-file (format "~a-~a"
713 (ly:get-option 'log-file) joblist))
714 (set! files (vector-ref split-todo joblist)))
715 (begin (ly:progress "\nForking into jobs: ~a\n" joblist)
718 (let* ((stat (cdr (waitpid pid))))
721 (acons (list-element-index joblist pid)
728 (logfile (format "~a-~a.log"
729 (ly:get-option 'log-file) job))
730 (log (ly:gulp-file logfile))
731 (len (string-length log))
732 (tail (substring log (max 0 (- len 1024)))))
733 (if (status:term-sig state)
736 (format (_ "job ~a terminated with signal: ~a")
737 job (status:term-sig state)))
739 (_ "logfile ~a (exit ~a):\n~a")
740 logfile (status:exit-val state) tail))))
743 (ly:error "Children ~a exited with errors."
745 ;; must overwrite individual entries
746 (if (ly:get-option 'dump-profile)
747 (dump-profile "lily-run-total"
748 '(0 0) (profile-measurements)))
753 (if (string-or-symbol? (ly:get-option 'log-file))
754 (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
755 (let ((failed (lilypond-all files)))
756 (if (ly:get-option 'trace-scheme-coverage)
758 (coverage:show-all (lambda (f)
759 (string-contains f "lilypond")))))
761 (begin (ly:error (_ "failed files: ~S") (string-join failed))
767 (define-public (lilypond-all files)
769 (separate-logs (ly:get-option 'separate-log-files))
772 (open-file (if (string-or-symbol? (ly:get-option 'log-file))
773 (format "~a.log" (ly:get-option 'log-file))
774 "/dev/tty") "a") #f))
775 (do-measurements (ly:get-option 'dump-profile))
776 (handler (lambda (key failed-file)
777 (set! failed (append (list failed-file) failed)))))
781 (let* ((start-measurements (if do-measurements
782 (profile-measurements)
784 (base (dir-basename x ".ly"))
785 (all-settings (ly:all-options)))
787 (ly:stderr-redirect (format "~a.log" base) "w"))
789 (format ping-log "Processing ~a\n" base))
790 (if (ly:get-option 'trace-memory-frequency)
791 (mtrace:start-trace (ly:get-option 'trace-memory-frequency)))
792 (lilypond-file handler x)
793 (if start-measurements
794 (dump-profile x start-measurements (profile-measurements)))
795 (if (ly:get-option 'trace-memory-frequency)
796 (begin (mtrace:stop-trace)
797 (mtrace:dump-results base)))
798 (for-each (lambda (s)
799 (ly:set-option (car s) (cdr s)))
801 (ly:set-option 'debug-gc-assert-parsed-dead #t)
803 (ly:set-option 'debug-gc-assert-parsed-dead #f)
804 (if (ly:get-option 'debug-gc)
806 (ly:reset-all-fonts))))
809 ;; we want the failed-files notice in the aggregrate logfile.
811 (format ping-log "Failed files: ~a\n" failed))
812 (if (ly:get-option 'dump-profile)
813 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
816 (define (lilypond-file handler file-name)
817 (catch 'ly-file-failed
818 (lambda () (ly:parse-file file-name))
819 (lambda (x . args) (handler x file-name))))
821 (use-modules (scm editor))
823 (define-public (gui-main files)
825 (gui-no-files-handler))
826 (if (not (string? (ly:get-option 'log-file)))
827 (let* ((base (dir-basename (car files) ".ly"))
828 (log-name (string-append base ".log")))
829 (if (not (ly:get-option 'gui))
830 (ly:message (_ "Redirecting output to ~a...") log-name))
831 (ly:stderr-redirect log-name "w")
832 (ly:message "# -*-compilation-*-"))
833 (let ((failed (lilypond-all files)))
837 (ly:stderr-redirect "foo" "r")
838 (system (get-editor-command log-name 0 0 0))
839 (ly:error (_ "failed files: ~S") (string-join failed))
844 (define (gui-no-files-handler)
845 (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
846 ;; FIXME: soft-code, localize
847 (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
848 (cmd (get-editor-command welcome-ly 0 0 0)))
849 (ly:message (_ "Invoking `~a'...\n") cmd)