]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
Fix alphabetic order of options definitions
[lilypond.git] / scm / lily.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2010 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
5 ;;;;
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.
10 ;;;;
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.
15 ;;;;
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/>.
18
19 ;; Internationalisation: (_i "to be translated") gets an entry in the
20 ;; POT file; (gettext ...) must be invoked explicitly to do the actual
21 ;; "translation".
22 ;;
23 ;; (define-macro (_i x) x)
24 ;; (define-macro-public _i (x) x)
25 ;; (define-public-macro _i (x) x)
26 ;; Abbrv-PWR!
27
28 (defmacro-public _i (x) x)
29
30 (read-enable 'positions)
31 (debug-enable 'debug)
32
33 (define-public PLATFORM
34   (string->symbol
35    (string-downcase
36     (car (string-tokenize (utsname:sysname (uname)))))))
37
38 (define scheme-options-definitions
39   `(
40     ;; NAMING: either
41
42     ;; - [subject-]object-object-verb +"ing"
43     ;; - [subject-]-verb-object-object
44
45     ;; Avoid overlong lines in `lilypond -dhelp'!  Strings should not
46     ;; be longer than 48 characters per line.
47
48     (anti-alias-factor 1
49 "Render at higher resolution (using given factor)
50 and scale down result to prevent jaggies in
51 PNG images.")
52     (aux-files #t
53 "Create .tex, .texi, .count files in the
54 EPS backend.")
55     (backend ps
56 "Select backend.  Possible values: 'eps, 'null,
57 'ps, 'scm, 'socket, 'svg.")
58     (check-internal-types #f
59 "Check every property assignment for types.")
60     (clip-systems #f
61 "Generate cut-out snippets of a score.")
62     (datadir #f
63 "LilyPond prefix for data files (read-only).")
64     (debug-gc #f
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'.")
71     (debug-lexer #f
72 "Debug the flex lexer.")
73     (debug-page-breaking-scoring #f
74 "Dump scores for many different page breaking
75 configurations.")
76     (debug-parser #f
77 "Debug the bison parser.")
78     (debug-property-callbacks #f
79 "Debug cyclic callback chains.")
80     (debug-skylines #f
81 "Debug skylines.")
82     (delete-intermediate-files #t
83 "Delete unusable, intermediate PostScript files.")
84     (dump-profile #f
85 "Dump memory and time information for each file.")
86     (dump-cpu-profile #f
87 "Dump timing information (system-dependent).")
88     (dump-signatures #f
89 "Dump output signatures of each system.  Used for
90 regression testing.")
91     (eps-box-padding #f
92 "Pad left edge of the output EPS bounding box by
93 given amount (in mm).")
94     (gs-load-fonts #f
95 "Load fonts via Ghostscript.")
96     (gs-load-lily-fonts #f
97 "Load only LilyPond fonts via Ghostscript.")
98     (gui #f
99 "Run LilyPond from a GUI and redirect stderr to
100 a log file.")
101     (help #f
102 "Show this help.")
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.")
107     (job-count #f
108 "Process in parallel, using the given number of
109 jobs.")
110     (log-file #f
111 "If string FOO is given as argument, redirect
112 output to log file `FOO.log'.")
113     (midi-extension ,(if (eq? PLATFORM 'windows)
114                          "mid"
115                          "midi")
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
120 to a music font.")
121     (old-relative #f
122 "Make \\relative mode for simultaneous music work
123 similar to chord syntax.")
124     (point-and-click #t
125 "Add point & click links to PDF output.")
126     (paper-size "a4"
127 "Set default paper size.")
128     (pixmap-format "png16m"
129 "Set GhostScript's output format for pixel images.")
130     (preview #f
131 "Create preview images also.")
132     (print-pages #t
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
137 a stack trace.")
138     (profile-property-accesses #f
139 "Keep statistics of get_property() calls.")
140     (resolution 101
141 "Set resolution for generating PNG pixmaps to
142 given value (in dpi).")
143     (read-file-list #f
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)")
150     (safe #f
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',
155 `FILE2.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.")
161     (strip-output-dir #t
162 "Don't use directories from input files while
163 constructing output file names.")
164     (svg-woff #f
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
169 `FILE.graph'.")
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).")
174     (warning-as-error #f
175 "Change all warning and programming_error
176 messages into errors.")
177     ))
178
179 ;; Need to do this in the beginning.  Other parts of the Scheme
180 ;; initialization depend on these options.
181
182 (for-each (lambda (x)
183             (ly:add-option (car x) (cadr x) (caddr x)))
184           scheme-options-definitions)
185
186 (for-each (lambda (x)
187             (ly:set-option (car x) (cdr x)))
188           (eval-string (ly:command-line-options)))
189
190 (debug-set! stack 0)
191
192 (if (defined? 'set-debug-cell-accesses!)
193     (set-debug-cell-accesses! #f))
194
195                                         ;(set-debug-cell-accesses! 1000)
196
197 (use-modules (ice-9 regex)
198               (ice-9 safe)
199               (ice-9 format)
200               (ice-9 rdelim)
201               (ice-9 optargs)
202               (oop goops)
203               (srfi srfi-1)
204               (srfi srfi-13)
205               (srfi srfi-14)
206               (scm clip-region)
207               (scm memory-trace)
208               (scm coverage))
209
210 (define-public fancy-format
211   format)
212
213 (define-public (ergonomic-simple-format dest . rest)
214   "Like ice-9 format, but without the memory consumption."
215   (if (string? dest)
216       (apply simple-format (cons #f (cons dest rest)))
217       (apply simple-format (cons dest rest))))
218
219 (define format
220   ergonomic-simple-format)
221
222 ;; my display
223 (define-public (myd k v)
224   (display k)
225   (display ": ")
226   (display v)
227   (display ", ")
228   v)
229
230 (define-public (print . args)
231   (apply format (cons (current-output-port) args)))
232
233
234 ;;; General settings.
235 ;;;
236 ;;; Debugging evaluator is slower.  This should have a more sensible
237 ;;; default.
238
239 (if (or (ly:get-option 'verbose)
240         (ly:get-option 'trace-memory-frequency)
241         (ly:get-option 'trace-scheme-coverage))
242     (begin
243       (ly:set-option 'protected-scheme-parsing #f)
244       (debug-enable 'debug)
245       (debug-enable 'backtrace)
246       (read-enable 'positions)))
247
248 (if (ly:get-option 'trace-scheme-coverage)
249     (coverage:enable))
250
251 (define-public parser #f)
252
253 (define music-string-to-path-backends
254   '(svg))
255
256 (if (memq (ly:get-option 'backend) music-string-to-path-backends)
257     (ly:set-option 'music-strings-to-paths #t))
258
259 (define-public _ gettext)
260
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))
265     (if (not file-name)
266         (ly:error (_ "cannot find: ~A") x))
267     (primitive-load file-name)
268     (if (ly:get-option 'verbose)
269         (ly:progress "]\n"))))
270
271 (define-public DOS
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")))))
276
277 (define (slashify x)
278   (if (string-index x #\\)
279       x
280       (string-regexp-substitute
281         "//*" "/"
282         (string-regexp-substitute "\\\\" "/" x))))
283
284 (define-public (ly-getcwd)
285   (if (eq? PLATFORM 'windows)
286       (slashify (getcwd))
287       (getcwd)))
288
289 (define-public (is-absolute? file-name)
290   (let ((file-name-length (string-length file-name)))
291     (if (= file-name-length 0)
292         #f
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) #\/))))))
298
299 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
300
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))
307           (begin
308             (ly:input-message
309              location
310              (format
311               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
312               count (type-name pred?) arg))
313             #f)
314           #t))
315
316     (if (null? signature)
317         #t
318         (and (helper (car signature) (car arguments) count)
319              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
320   (recursion-helper signature arguments 1))
321
322
323 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
324 ;; Safe definitions utility
325
326 (define safe-objects
327   (list))
328
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)
333     (if (pair? arg)
334         (get-symbol (car arg))
335         arg))
336
337   (let ((safe-symbol (get-symbol arglist)))
338     `(begin
339        (define*-public ,arglist
340          ,@body)
341        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
342                                 safe-objects))
343        ,safe-symbol)))
344
345 (define-safe-public (lilypond-version)
346   (string-join
347    (map (lambda (x) (if (symbol? x)
348                         (symbol->string x)
349                         (number->string x)))
350         (ly:version))
351    "."))
352
353 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
354 ;; init pitch system
355
356 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
357
358 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
359 ;; other files.
360
361 (define init-scheme-files
362   '("lily-library.scm"
363     "file-cache.scm"
364     "define-event-classes.scm"
365     "define-music-types.scm"
366     "output-lib.scm"
367     "c++.scm"
368     "chord-ignatzek-names.scm"
369     "chord-entry.scm"
370     "chord-generic-names.scm"
371     "stencil.scm"
372     "markup.scm"
373     "music-functions.scm"
374     "part-combiner.scm"
375     "autochange.scm"
376     "define-music-properties.scm"
377     "time-signature-settings.scm"
378     "auto-beam.scm"
379     "chord-name.scm"
380     "bezier-tools.scm"
381     "parser-ly-from-scheme.scm"
382     "ly-syntax-constructors.scm"
383
384     "define-context-properties.scm"
385     "translation-functions.scm"
386     "script.scm"
387     "midi.scm"
388     "layout-beam.scm"
389     "parser-clef.scm"
390     "layout-slur.scm"
391     "font.scm"
392     "encoding.scm"
393
394     "flag-styles.scm"
395     "fret-diagrams.scm"
396     "harp-pedals.scm"
397     "define-woodwind-diagrams.scm"
398     "display-woodwind-diagrams.scm"
399     "predefined-fretboards.scm"
400     "define-markup-commands.scm"
401     "define-grob-properties.scm"
402     "define-grobs.scm"
403     "define-grob-interfaces.scm"
404     "define-stencil-commands.scm"
405     "titling.scm"
406
407     "paper.scm"
408     "backend-library.scm"
409     "x11-color.scm"
410     "tablature.scm"
411
412     ;; must be after everything has been defined
413     "safe-lily.scm"))
414
415 (for-each ly:load init-scheme-files)
416
417 (define-public r5rs-primary-predicates
418   `((,boolean? . "boolean")
419     (,char? . "character")
420     (,number? . "number")
421     (,pair? . "pair")
422     (,port? . "port")
423     (,procedure? . "procedure")
424     (,string? . "string")
425     (,symbol? . "symbol")
426     (,vector? . "vector")))
427
428 (define-public r5rs-secondary-predicates
429   `((,char-alphabetic? . "alphabetic character")
430     (,char-lower-case? . "lower-case character")
431     (,char-numeric? . "numeric character")
432     (,char-upper-case? . "upper-case character")
433     (,char-whitespace? . "whitespace character")
434
435     (,complex? . "complex number")
436     (,even? . "even number")
437     (,exact? . "exact number")
438     (,inexact? . "inexact number")
439     (,integer? . "integer")
440     (,negative? . "negative number")
441     (,odd? . "odd number")
442     (,positive? . "positive number")
443     (,rational? . "rational number")
444     (,real? . "real number")
445     (,zero? . "zero")
446
447     (,list? . "list")
448     (,null? . "null")
449
450     (,input-port? . "input port")
451     (,output-port? . "output port")
452
453     ;; would this ever be used?
454     (,eof-object? . "end-of-file object")
455     ))
456
457 (define-public guile-predicates
458   `((,hash-table? . "hash table")
459   ))
460
461 (define-public lilypond-scheme-predicates
462   `((,boolean-or-symbol? . "boolean or symbol")
463     (,color? . "color")
464     (,cheap-list? . "list")
465     (,grob-list? . "list of grobs")
466     ;; this is built on cheap-list
467     (,list-or-symbol? . "list or symbol")
468     (,markup? . "markup")
469     (,markup-command-list? . "markup command list")
470     (,markup-list? . "markup list")
471     (,moment-pair? . "pair of moment objects")
472     (,number-or-grob? . "number or grob")
473     (,number-or-string? . "number or string")
474     (,number-pair? . "pair of numbers")
475     (,rhythmic-location? . "rhythmic location")
476     (,scheme? . "any type")
477     (,string-or-pair? . "string or pair")
478     (,string-or-symbol? . "string or symbol")
479     ))
480
481 (define-public lilypond-exported-predicates
482   `((,ly:box? . "box")
483     (,ly:context? . "context")
484     (,ly:dimension? . "dimension, in staff space")
485     (,ly:dir? . "direction")
486     (,ly:dispatcher? . "dispatcher")
487     (,ly:duration? . "duration")
488     (,ly:font-metric? . "font metric")
489     (,ly:grob? . "graphical (layout) object")
490     (,ly:grob-array? . "array of grobs")
491     (,ly:input-location? . "input location")
492     (,ly:item? . "item")
493     (,ly:iterator? . "iterator")
494     (,ly:lily-lexer? . "lily-lexer")
495     (,ly:lily-parser? . "lily-parser")
496     (,ly:listener? . "listener")
497     (,ly:moment? . "moment")
498     (,ly:music? . "music")
499     (,ly:music-function? . "music function")
500     (,ly:music-list? . "list of music objects")
501     (,ly:music-output? . "music output")
502     (,ly:otf-font? . "OpenType font")
503     (,ly:output-def? . "output definition")
504     (,ly:page-marker? . "page marker")
505     (,ly:pango-font? . "pango font")
506     (,ly:paper-book? . "paper book")
507     (,ly:paper-system? . "paper-system Prob")
508     (,ly:pitch? . "pitch")
509     (,ly:prob? . "property object")
510     (,ly:score? . "score")
511     (,ly:simple-closure? . "simple closure")
512     (,ly:skyline? . "skyline")
513     (,ly:skyline-pair? . "pair of skylines")
514     (,ly:source-file? . "source file")
515     (,ly:spanner? . "spanner")
516     (,ly:stencil? . "stencil")
517     (,ly:stream-event? . "stream event")
518     (,ly:translator? . "translator")
519     (,ly:translator-group? . "translator group")
520     ))
521
522
523 (set! type-p-name-alist
524       (append r5rs-primary-predicates
525               r5rs-secondary-predicates
526               guile-predicates
527               lilypond-scheme-predicates
528               lilypond-exported-predicates))
529
530
531 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
532 ;; timing
533
534 (define (profile-measurements)
535   (let* ((t (times))
536          (stats (gc-stats)))
537     (list (- (+ (tms:cutime t)
538                 (tms:utime t))
539              (assoc-get 'gc-time-taken stats))
540           (assoc-get 'total-cells-allocated  stats 0))))
541
542 (define (dump-profile base last this)
543   (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
544          (diff (map (lambda (y) (apply - y)) (zip this last))))
545     (ly:progress "\nWriting timing to ~a..." outname)
546     (format (open-file outname "w")
547             "time: ~a\ncells: ~a\n"
548             (if (ly:get-option 'dump-cpu-profile)
549                 (car diff)
550                 0)
551             (cadr diff))))
552
553 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
554 ;; debug memory leaks
555
556 (define gc-dumping
557   #f)
558
559 (define gc-protect-stat-count
560   0)
561
562 (define-public (dump-live-object-stats outfile)
563   (for-each (lambda (x)
564               (format outfile "~a: ~a\n" (car x) (cdr x)))
565             (sort (gc-live-object-stats)
566                   (lambda (x y)
567                     (string<? (car x) (car y))))))
568
569 (define-public (dump-gc-protects)
570   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
571   (let* ((protects (sort (hash-table->alist (ly:protects))
572                          (lambda (a b)
573                            (< (object-address (car a))
574                               (object-address (car b))))))
575          (out-file-name (string-append
576                          "gcstat-" (number->string gc-protect-stat-count)
577                          ".scm"))
578          (outfile (open-file out-file-name "w")))
579     (set! gc-dumping #t)
580     (display (format "Dumping GC statistics ~a...\n" out-file-name))
581     (display (map (lambda (y)
582                     (let ((x (car y))
583                           (c (cdr y)))
584                       (display
585                        (format "~a (~a) = ~a\n" (object-address x) c x)
586                        outfile)))
587                   (filter
588                    (lambda (x)
589                      (not (symbol? (car x))))
590                    protects))
591              outfile)
592     (format outfile "\nprotected symbols: ~a\n"
593             (apply + (map (lambda (obj-count)
594                             (if (symbol? (car obj-count))
595                                 (cdr obj-count)
596                                 0))
597                           protects)))
598
599     ;; (display (ly:smob-protects))
600     (newline outfile)
601     (if (defined? 'gc-live-object-stats)
602         (let* ((stats #f))
603           (display "Live object statistics: GC'ing\n")
604           (ly:reset-all-fonts)
605           (gc)
606           (gc)
607           (display "Asserting dead objects\n")
608           (ly:set-option 'debug-gc-assert-parsed-dead #t)
609           (gc)
610           (ly:set-option 'debug-gc-assert-parsed-dead #f)
611           (set! stats (gc-live-object-stats))
612           (display "Dumping live object statistics.\n")
613           (dump-live-object-stats outfile)))
614     (newline outfile)
615     (let* ((stats (gc-stats)))
616       (for-each (lambda (sym)
617                   (display
618                    (format "~a ~a ~a\n"
619                            gc-protect-stat-count
620                            sym
621                            (assoc-get sym stats "?"))
622
623                    outfile))
624                 '(protected-objects bytes-malloced cell-heap-size)))
625     (set! gc-dumping #f)
626     (close-port outfile)))
627
628 (define (check-memory)
629   "Read `/proc/self' to check up on memory use."
630   (define (gulp-file name)
631     (let* ((file (open-input-file name))
632            (text (read-delimited "" file)))
633       (close file)
634       text))
635
636   (let* ((stat (gulp-file "/proc/self/status"))
637          (lines (string-split stat #\newline))
638          (interesting (filter identity
639                               (map
640                                (lambda (l)
641                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
642                                lines)))
643          (mem (string->number (match:substring (car interesting) 1))))
644     (display (format  "VMDATA: ~a\n" mem))
645     (display (gc-stats))
646     (if (> mem 100000)
647         (begin (dump-gc-protects)
648                (raise 1)))))
649
650 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
651
652 (define (multi-fork count)
653   "Split this process into COUNT helpers.  Returns either a list of
654 PIDs or the number of the process."
655   (define (helper count acc)
656     (if (> count 0)
657         (let* ((pid (primitive-fork)))
658           (if (= pid 0)
659               (1- count)
660               (helper (1- count) (cons pid acc))))
661         acc))
662
663   (helper count '()))
664
665 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
666
667 (define* (ly:exit status #:optional (silently #f) )
668     "Exit function for lilypond"
669     (if (not silently)
670         (case status
671             ((0) (ly:success "Compilation successfully completed"))
672             ((1) (ly:warning "Compilation completed with warnings or errors"))
673             (else (ly:message "")))
674         )
675     (exit status)
676     )
677 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
678
679 (define-public (lilypond-main files)
680   "Entry point for LilyPond."
681   (eval-string (ly:command-line-code))
682   (if (ly:get-option 'help)
683       (begin (ly:option-usage)
684              (ly:exit 0 #t)))
685   (if (ly:get-option 'show-available-fonts)
686       (begin (ly:font-config-display-fonts)
687              (ly:exit 0 #t)))
688   (if (ly:get-option 'gui)
689       (gui-main files))
690   (if (null? files)
691       (begin (ly:usage)
692              (ly:exit 2 #t)))
693   (if (ly:get-option 'read-file-list)
694       (set! files
695             (filter (lambda (s)
696                       (> (string-length s) 0))
697                     (apply append
698                            (map (lambda (f)
699                                   (string-split (ly:gulp-file f) #\nl))
700                                 files)))))
701   (if (and (number? (ly:get-option 'job-count))
702            (>= (length files) (ly:get-option 'job-count)))
703       (let* ((count (ly:get-option 'job-count))
704              (split-todo (split-list files count))
705              (joblist (multi-fork count))
706              (errors '()))
707         (if (not (string-or-symbol? (ly:get-option 'log-file)))
708             (ly:set-option 'log-file "lilypond-multi-run"))
709         (if (number? joblist)
710             (begin (ly:set-option
711                     'log-file (format "~a-~a"
712                                       (ly:get-option 'log-file) joblist))
713                    (set! files (vector-ref split-todo joblist)))
714             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
715                    (for-each
716                     (lambda (pid)
717                       (let* ((stat (cdr (waitpid pid))))
718                         (if (not (= stat 0))
719                             (set! errors
720                                   (acons (list-element-index joblist pid)
721                                          stat errors)))))
722                     joblist)
723                    (for-each
724                     (lambda (x)
725                       (let* ((job (car x))
726                              (state (cdr x))
727                              (logfile (format "~a-~a.log"
728                                               (ly:get-option 'log-file) job))
729                              (log (ly:gulp-file logfile))
730                              (len (string-length log))
731                              (tail (substring  log (max 0 (- len 1024)))))
732                         (if (status:term-sig state)
733                             (ly:message
734                              "\n\n~a\n"
735                              (format (_ "job ~a terminated with signal: ~a")
736                                      job (status:term-sig state)))
737                             (ly:message
738                              (_ "logfile ~a (exit ~a):\n~a")
739                              logfile (status:exit-val state) tail))))
740                     errors)
741                    (if (pair? errors)
742                        (ly:error "Children ~a exited with errors."
743                                  (map car errors)))
744                    ;; must overwrite individual entries
745                    (if (ly:get-option 'dump-profile)
746                        (dump-profile "lily-run-total"
747                                      '(0 0) (profile-measurements)))
748                    (if (null? errors)
749                        (ly:exit 0 #f)
750                        (ly:exit 1 #f))))))
751
752   (if (string-or-symbol? (ly:get-option 'log-file))
753       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
754   (let ((failed (lilypond-all files)))
755     (if (ly:get-option 'trace-scheme-coverage)
756         (begin
757           (coverage:show-all (lambda (f)
758                                (string-contains f "lilypond")))))
759     (if (pair? failed)
760         (begin (ly:error (_ "failed files: ~S") (string-join failed))
761                (ly:exit 1 #f))
762         (begin
763           (ly:exit 0 #f)))))
764
765
766 (define-public (lilypond-all files)
767   (let* ((failed '())
768          (separate-logs (ly:get-option 'separate-log-files))
769          (ping-log
770           (if separate-logs
771               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
772                              (format "~a.log" (ly:get-option 'log-file))
773                              "/dev/tty") "a") #f))
774          (do-measurements (ly:get-option 'dump-profile))
775          (handler (lambda (key failed-file)
776                     (set! failed (append (list failed-file) failed)))))
777     (gc)
778     (for-each
779      (lambda (x)
780        (let* ((start-measurements (if do-measurements
781                                       (profile-measurements)
782                                       #f))
783               (base (dir-basename x ".ly"))
784               (all-settings (ly:all-options)))
785          (if separate-logs
786              (ly:stderr-redirect (format "~a.log" base) "w"))
787          (if ping-log
788              (format ping-log "Processing ~a\n" base))
789          (if (ly:get-option 'trace-memory-frequency)
790              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
791          (lilypond-file handler x)
792          (if start-measurements
793              (dump-profile x start-measurements (profile-measurements)))
794          (if (ly:get-option 'trace-memory-frequency)
795              (begin (mtrace:stop-trace)
796                     (mtrace:dump-results base)))
797          (for-each (lambda (s)
798                      (ly:set-option (car s) (cdr s)))
799                    all-settings)
800          (ly:set-option 'debug-gc-assert-parsed-dead #t)
801          (gc)
802          (ly:set-option 'debug-gc-assert-parsed-dead #f)
803          (if (ly:get-option 'debug-gc)
804              (dump-gc-protects)
805              (ly:reset-all-fonts))))
806      files)
807
808     ;; we want the failed-files notice in the aggregrate logfile.
809     (if ping-log
810         (format ping-log "Failed files: ~a\n" failed))
811     (if (ly:get-option 'dump-profile)
812         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
813     failed))
814
815 (define (lilypond-file handler file-name)
816   (catch 'ly-file-failed
817          (lambda () (ly:parse-file file-name))
818          (lambda (x . args) (handler x file-name))))
819
820 (use-modules (scm editor))
821
822 (define-public (gui-main files)
823   (if (null? files)
824       (gui-no-files-handler))
825   (if (not (string? (ly:get-option 'log-file)))
826       (let* ((base (dir-basename (car files) ".ly"))
827              (log-name (string-append base ".log")))
828         (if (not (ly:get-option 'gui))
829             (ly:message (_ "Redirecting output to ~a...") log-name))
830         (ly:stderr-redirect log-name "w")
831         (ly:message "# -*-compilation-*-"))
832       (let ((failed (lilypond-all files)))
833         (if (pair? failed)
834             (begin
835               ;; ugh
836               (ly:stderr-redirect "foo" "r")
837               (system (get-editor-command log-name 0 0 0))
838               (ly:error (_ "failed files: ~S") (string-join failed))
839               ;; not reached?
840               (exit 1))
841             (ly:exit 0 #f)))))
842
843 (define (gui-no-files-handler)
844   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
845          ;; FIXME: soft-code, localize
846          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
847          (cmd (get-editor-command welcome-ly 0 0 0)))
848     (ly:message (_ "Invoking `~a'...\n") cmd)
849     (system cmd)
850     (ly:exit 1 #f)))