]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
[lilypond-book] Fix indentation in LaTeX mode.
[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     (include-settings #f
108 "Include file for global settings, included before the score is processed.")
109     (job-count #f
110 "Process in parallel, using the given number of
111 jobs.")
112     (log-file #f
113 "If string FOO is given as argument, redirect
114 output to log file `FOO.log'.")
115     (midi-extension ,(if (eq? PLATFORM 'windows)
116                          "mid"
117                          "midi")
118 "Set the default file extension for MIDI output
119 file to given string.")
120     (music-strings-to-paths #f
121 "Convert text strings to paths when glyphs belong
122 to a music font.")
123     (old-relative #f
124 "Make \\relative mode for simultaneous music work
125 similar to chord syntax.")
126     (point-and-click #t
127 "Add point & click links to PDF output.")
128     (paper-size "a4"
129 "Set default paper size.")
130     (pixmap-format "png16m"
131 "Set GhostScript's output format for pixel images.")
132     (preview #f
133 "Create preview images also.")
134     (print-pages #t
135 "Print pages in the normal way.")
136     (protected-scheme-parsing #t
137 "Continue when errors in inline scheme are caught
138 in the parser.  If #f, halt on errors and print
139 a stack trace.")
140     (profile-property-accesses #f
141 "Keep statistics of get_property() calls.")
142     (resolution 101
143 "Set resolution for generating PNG pixmaps to
144 given value (in dpi).")
145     (read-file-list #f
146 "Specify name of a file which contains a list of
147 input files to be processed.")
148     (relative-includes #f
149 "When processing an \\include command, look for
150 the included file relative to the current file
151 (instead of the root file)")
152     (safe #f
153 "Run in safer mode.")
154     (separate-log-files #f
155 "For input files `FILE1.ly', `FILE2.ly', ...
156 output log data to files `FILE1.log',
157 `FILE2.log', ...")
158     (show-available-fonts #f
159 "List available font names.")
160     (strict-infinity-checking #f
161 "Force a crash on encountering Inf and NaN
162 floating point exceptions.")
163     (strip-output-dir #t
164 "Don't use directories from input files while
165 constructing output file names.")
166     (svg-woff #f
167 "Use woff font files in SVG backend.")
168     (trace-memory-frequency #f
169 "Record Scheme cell usage this many times per
170 second.  Dump results to `FILE.stacks' and
171 `FILE.graph'.")
172     (trace-scheme-coverage #f
173 "Record coverage of Scheme files in `FILE.cov'.")
174     (verbose ,(ly:command-line-verbose?)
175 "Value of the --verbose flag (read-only).")
176     (warning-as-error #f
177 "Change all warning and programming_error
178 messages into errors.")
179     ))
180
181 ;; Need to do this in the beginning.  Other parts of the Scheme
182 ;; initialization depend on these options.
183
184 (for-each (lambda (x)
185             (ly:add-option (car x) (cadr x) (caddr x)))
186           scheme-options-definitions)
187
188 (for-each (lambda (x)
189             (ly:set-option (car x) (cdr x)))
190           (eval-string (ly:command-line-options)))
191
192 (debug-set! stack 0)
193
194 (if (defined? 'set-debug-cell-accesses!)
195     (set-debug-cell-accesses! #f))
196
197 ;;(set-debug-cell-accesses! 1000)
198
199 ;;; Boolean thunk - are we integrating Guile V2.0 or higher with LilyPond?
200 (define-public (guile-v2)
201   (string>? (version) "1.9.10"))
202
203 (use-modules (ice-9 regex)
204              (ice-9 safe)
205              (ice-9 format)
206              (ice-9 rdelim)
207              (ice-9 optargs)
208              (oop goops)
209              (srfi srfi-1)
210              (srfi srfi-13)
211              (srfi srfi-14)
212              (scm clip-region)
213              (scm memory-trace)
214              (scm coverage))
215
216 (define-public _ gettext)
217 ;;; TODO:
218 ;;  There are new modules defined in Guile V2.0 which we need to use, e.g.
219 ;;  the modules and scheme files loaded by lily.scm use currying.
220 ;;  In Guile V2 this needs (ice-9 curried-definitions) which is not
221 ;;  present in Guile V1.8
222 ;;
223 ;; TODO add in modules for V1.8,7 deprecated in V2.0 and integrated
224 ;; into Guile base code, like (ice-9 syncase).
225 ;;
226
227 (define-public fancy-format
228   format)
229
230 (define-public (ergonomic-simple-format dest . rest)
231   "Like ice-9 format, but without the memory consumption."
232   (if (string? dest)
233       (apply simple-format (cons #f (cons dest rest)))
234       (apply simple-format (cons dest rest))))
235
236 (define format
237   ergonomic-simple-format)
238
239 ;; my display
240 (define-public (myd k v)
241   (display k)
242   (display ": ")
243   (display v)
244   (display ", ")
245   v)
246
247 (define-public (print . args)
248   (apply format (cons (current-output-port) args)))
249
250
251 ;;; General settings.
252 ;;;
253 ;;; Debugging evaluator is slower.  This should have a more sensible
254 ;;; default.
255
256 (if (or (ly:get-option 'verbose)
257         (ly:get-option 'trace-memory-frequency)
258         (ly:get-option 'trace-scheme-coverage))
259     (begin
260       (ly:set-option 'protected-scheme-parsing #f)
261       (debug-enable 'debug)
262       (debug-enable 'backtrace)
263       (read-enable 'positions)))
264
265 (if (ly:get-option 'trace-scheme-coverage)
266     (coverage:enable))
267
268 (define-public parser #f)
269
270 (define music-string-to-path-backends
271   '(svg))
272
273 (if (memq (ly:get-option 'backend) music-string-to-path-backends)
274     (ly:set-option 'music-strings-to-paths #t))
275
276
277 (define-public (ly:load x)
278   (let* ((file-name (%search-load-path x)))
279     (if (ly:get-option 'verbose)
280         (ly:progress "[~A" file-name))
281     (if (not file-name)
282         (ly:error (_ "cannot find: ~A") x))
283     (primitive-load file-name)
284     (if (ly:get-option 'verbose)
285         (ly:progress "]\n"))))
286
287 (define-public DOS
288   (let ((platform (string-tokenize
289                    (vector-ref (uname) 0) char-set:letter+digit)))
290     (if (null? (cdr platform)) #f
291         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
292
293 (define (slashify x)
294   (if (string-index x #\\)
295       x
296       (string-regexp-substitute
297         "//*" "/"
298         (string-regexp-substitute "\\\\" "/" x))))
299
300 (define-public (ly-getcwd)
301   (if (eq? PLATFORM 'windows)
302       (slashify (getcwd))
303       (getcwd)))
304
305 (define-public (is-absolute? file-name)
306   (let ((file-name-length (string-length file-name)))
307     (if (= file-name-length 0)
308         #f
309         (or (eq? (string-ref file-name 0) #\/)
310             (and (eq? PLATFORM 'windows)
311                  (> file-name-length 2)
312                  (eq? (string-ref file-name 1) #\:)
313                  (eq? (string-ref file-name 2) #\/))))))
314
315 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
316 ;;; If necessary, emulate Guile V2 module_export_all! for Guile V1.8.n
317 (cond-expand
318  ((not guile-v2)
319   (define (module-export-all! mod)
320     (define (fresh-interface!)
321       (let ((iface (make-module)))
322         (set-module-name! iface (module-name mod))
323         ;; for guile 2: (set-module-version! iface (module-version mod))
324         (set-module-kind! iface 'interface)
325         (set-module-public-interface! mod iface)
326         iface))
327     (let ((iface (or (module-public-interface mod)
328                      (fresh-interface!))))
329       (set-module-obarray! iface (module-obarray mod))))))
330
331 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
332 (define (type-check-list location signature arguments)
333   "Typecheck a list of arguments against a list of type predicates.
334 Print a message at LOCATION if any predicate failed."
335   (define (recursion-helper signature arguments count)
336     (define (helper pred? arg count)
337       (if (not (pred? arg))
338           (begin
339             (ly:input-message
340              location
341              (format
342               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
343               count (type-name pred?) arg))
344             #f)
345           #t))
346
347     (if (null? signature)
348         #t
349         (and (helper (car signature) (car arguments) count)
350              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
351   (recursion-helper signature arguments 1))
352
353
354 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
355 ;; Safe definitions utility
356
357 (define safe-objects
358   (list))
359
360 (define-macro (define-safe-public arglist . body)
361   "Define a variable, export it, and mark it as safe, i.e. usable in
362 LilyPond safe mode.  The syntax is the same as `define*-public'."
363   (define (get-symbol arg)
364     (if (pair? arg)
365         (get-symbol (car arg))
366         arg))
367
368   (let ((safe-symbol (get-symbol arglist)))
369     `(begin
370        (define*-public ,arglist
371          ,@body)
372        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
373                                 safe-objects))
374        ,safe-symbol)))
375
376 (define-safe-public (lilypond-version)
377   (string-join
378    (map (lambda (x) (if (symbol? x)
379                         (symbol->string x)
380                         (number->string x)))
381         (ly:version))
382    "."))
383
384 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
385 ;; init pitch system
386
387 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
388
389 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
390 ;; other files.
391
392 (define init-scheme-files
393   '("lily-library.scm"
394     "file-cache.scm"
395     "define-event-classes.scm"
396     "define-music-callbacks.scm"
397     "define-music-types.scm"
398     "output-lib.scm"
399     "c++.scm"
400     "chord-ignatzek-names.scm"
401     "chord-entry.scm"
402     "chord-generic-names.scm"
403     "stencil.scm"
404     "markup.scm"
405     "music-functions.scm"
406     "part-combiner.scm"
407     "autochange.scm"
408     "define-music-properties.scm"
409     "time-signature-settings.scm"
410     "auto-beam.scm"
411     "chord-name.scm"
412     "bezier-tools.scm"
413     "parser-ly-from-scheme.scm"
414     "ly-syntax-constructors.scm"
415
416     "define-context-properties.scm"
417     "translation-functions.scm"
418     "script.scm"
419     "midi.scm"
420     "layout-beam.scm"
421     "parser-clef.scm"
422     "layout-slur.scm"
423     "font.scm"
424     "encoding.scm"
425
426     "flag-styles.scm"
427     "fret-diagrams.scm"
428     "harp-pedals.scm"
429     "define-woodwind-diagrams.scm"
430     "display-woodwind-diagrams.scm"
431     "predefined-fretboards.scm"
432     "define-markup-commands.scm"
433     "define-grob-properties.scm"
434     "define-grobs.scm"
435     "define-grob-interfaces.scm"
436     "define-stencil-commands.scm"
437     "titling.scm"
438
439     "paper.scm"
440     "backend-library.scm"
441     "x11-color.scm"
442     "tablature.scm"
443
444     ;; must be after everything has been defined
445     "safe-lily.scm"))
446
447 (for-each ly:load init-scheme-files)
448
449 (define-public r5rs-primary-predicates
450   `((,boolean? . "boolean")
451     (,char? . "character")
452     (,number? . "number")
453     (,pair? . "pair")
454     (,port? . "port")
455     (,procedure? . "procedure")
456     (,string? . "string")
457     (,symbol? . "symbol")
458     (,vector? . "vector")))
459
460 (define-public r5rs-secondary-predicates
461   `((,char-alphabetic? . "alphabetic character")
462     (,char-lower-case? . "lower-case character")
463     (,char-numeric? . "numeric character")
464     (,char-upper-case? . "upper-case character")
465     (,char-whitespace? . "whitespace character")
466
467     (,complex? . "complex number")
468     (,even? . "even number")
469     (,exact? . "exact number")
470     (,inexact? . "inexact number")
471     (,integer? . "integer")
472     (,negative? . "negative number")
473     (,odd? . "odd number")
474     (,positive? . "positive number")
475     (,rational? . "rational number")
476     (,real? . "real number")
477     (,zero? . "zero")
478
479     (,list? . "list")
480     (,null? . "null")
481
482     (,input-port? . "input port")
483     (,output-port? . "output port")
484
485     ;; would this ever be used?
486     (,eof-object? . "end-of-file object")
487     ))
488
489 (define-public guile-predicates
490   `((,hash-table? . "hash table")
491   ))
492
493 (define-public lilypond-scheme-predicates
494   `((,boolean-or-symbol? . "boolean or symbol")
495     (,color? . "color")
496     (,cheap-list? . "list")
497     (,grob-list? . "list of grobs")
498     ;; this is built on cheap-list
499     (,list-or-symbol? . "list or symbol")
500     (,markup? . "markup")
501     (,markup-command-list? . "markup command list")
502     (,markup-list? . "markup list")
503     (,moment-pair? . "pair of moment objects")
504     (,number-or-grob? . "number or grob")
505     (,number-or-string? . "number or string")
506     (,number-pair? . "pair of numbers")
507     (,rhythmic-location? . "rhythmic location")
508     (,scheme? . "any type")
509     (,string-or-pair? . "string or pair")
510     (,string-or-symbol? . "string or symbol")
511     ))
512
513 (define-public lilypond-exported-predicates
514   `((,ly:box? . "box")
515     (,ly:context? . "context")
516     (,ly:dimension? . "dimension, in staff space")
517     (,ly:dir? . "direction")
518     (,ly:dispatcher? . "dispatcher")
519     (,ly:duration? . "duration")
520     (,ly:font-metric? . "font metric")
521     (,ly:grob? . "graphical (layout) object")
522     (,ly:grob-array? . "array of grobs")
523     (,ly:input-location? . "input location")
524     (,ly:item? . "item")
525     (,ly:iterator? . "iterator")
526     (,ly:lily-lexer? . "lily-lexer")
527     (,ly:lily-parser? . "lily-parser")
528     (,ly:listener? . "listener")
529     (,ly:moment? . "moment")
530     (,ly:music? . "music")
531     (,ly:music-function? . "music function")
532     (,ly:music-list? . "list of music objects")
533     (,ly:music-output? . "music output")
534     (,ly:otf-font? . "OpenType font")
535     (,ly:output-def? . "output definition")
536     (,ly:page-marker? . "page marker")
537     (,ly:pango-font? . "pango font")
538     (,ly:paper-book? . "paper book")
539     (,ly:paper-system? . "paper-system Prob")
540     (,ly:pitch? . "pitch")
541     (,ly:prob? . "property object")
542     (,ly:score? . "score")
543     (,ly:simple-closure? . "simple closure")
544     (,ly:skyline? . "skyline")
545     (,ly:skyline-pair? . "pair of skylines")
546     (,ly:source-file? . "source file")
547     (,ly:spanner? . "spanner")
548     (,ly:stencil? . "stencil")
549     (,ly:stream-event? . "stream event")
550     (,ly:translator? . "translator")
551     (,ly:translator-group? . "translator group")
552     ))
553
554
555 (set! type-p-name-alist
556       (append r5rs-primary-predicates
557               r5rs-secondary-predicates
558               guile-predicates
559               lilypond-scheme-predicates
560               lilypond-exported-predicates))
561
562
563 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
564 ;; timing
565
566 (define (profile-measurements)
567   (let* ((t (times))
568          (stats (gc-stats)))
569     (list (- (+ (tms:cutime t)
570                 (tms:utime t))
571              (assoc-get 'gc-time-taken stats))
572           (assoc-get 'total-cells-allocated  stats 0))))
573
574 (define (dump-profile base last this)
575   (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
576          (diff (map (lambda (y) (apply - y)) (zip this last))))
577     (ly:progress "\nWriting timing to ~a..." outname)
578     (format (open-file outname "w")
579             "time: ~a\ncells: ~a\n"
580             (if (ly:get-option 'dump-cpu-profile)
581                 (car diff)
582                 0)
583             (cadr diff))))
584
585 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
586 ;; debug memory leaks
587
588 (define gc-dumping
589   #f)
590
591 (define gc-protect-stat-count
592   0)
593
594 (define-public (dump-live-object-stats outfile)
595   (for-each (lambda (x)
596               (format outfile "~a: ~a\n" (car x) (cdr x)))
597             (sort (gc-live-object-stats)
598                   (lambda (x y)
599                     (string<? (car x) (car y))))))
600
601 (define-public (dump-gc-protects)
602   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
603   (let* ((protects (sort (hash-table->alist (ly:protects))
604                          (lambda (a b)
605                            (< (object-address (car a))
606                               (object-address (car b))))))
607          (out-file-name (string-append
608                          "gcstat-" (number->string gc-protect-stat-count)
609                          ".scm"))
610          (outfile (open-file out-file-name "w")))
611     (set! gc-dumping #t)
612     (display (format "Dumping GC statistics ~a...\n" out-file-name))
613     (display (map (lambda (y)
614                     (let ((x (car y))
615                           (c (cdr y)))
616                       (display
617                        (format "~a (~a) = ~a\n" (object-address x) c x)
618                        outfile)))
619                   (filter
620                    (lambda (x)
621                      (not (symbol? (car x))))
622                    protects))
623              outfile)
624     (format outfile "\nprotected symbols: ~a\n"
625             (apply + (map (lambda (obj-count)
626                             (if (symbol? (car obj-count))
627                                 (cdr obj-count)
628                                 0))
629                           protects)))
630
631     ;; (display (ly:smob-protects))
632     (newline outfile)
633     (if (defined? 'gc-live-object-stats)
634         (let* ((stats #f))
635           (display "Live object statistics: GC'ing\n")
636           (ly:reset-all-fonts)
637           (gc)
638           (gc)
639           (display "Asserting dead objects\n")
640           (ly:set-option 'debug-gc-assert-parsed-dead #t)
641           (gc)
642           (ly:set-option 'debug-gc-assert-parsed-dead #f)
643           (set! stats (gc-live-object-stats))
644           (display "Dumping live object statistics.\n")
645           (dump-live-object-stats outfile)))
646     (newline outfile)
647     (let* ((stats (gc-stats)))
648       (for-each (lambda (sym)
649                   (display
650                    (format "~a ~a ~a\n"
651                            gc-protect-stat-count
652                            sym
653                            (assoc-get sym stats "?"))
654
655                    outfile))
656                 '(protected-objects bytes-malloced cell-heap-size)))
657     (set! gc-dumping #f)
658     (close-port outfile)))
659
660 (define (check-memory)
661   "Read `/proc/self' to check up on memory use."
662   (define (gulp-file name)
663     (let* ((file (open-input-file name))
664            (text (read-delimited "" file)))
665       (close file)
666       text))
667
668   (let* ((stat (gulp-file "/proc/self/status"))
669          (lines (string-split stat #\newline))
670          (interesting (filter identity
671                               (map
672                                (lambda (l)
673                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
674                                lines)))
675          (mem (string->number (match:substring (car interesting) 1))))
676     (display (format  "VMDATA: ~a\n" mem))
677     (display (gc-stats))
678     (if (> mem 100000)
679         (begin (dump-gc-protects)
680                (raise 1)))))
681
682 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
683
684 (define (multi-fork count)
685   "Split this process into COUNT helpers.  Returns either a list of
686 PIDs or the number of the process."
687   (define (helper count acc)
688     (if (> count 0)
689         (let* ((pid (primitive-fork)))
690           (if (= pid 0)
691               (1- count)
692               (helper (1- count) (cons pid acc))))
693         acc))
694
695   (helper count '()))
696
697 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
698
699 (define* (ly:exit status #:optional (silently #f))
700   "Exit function for lilypond"
701   (if (not silently)
702       (case status
703         ((0) (ly:success (_ "Compilation successfully completed")))
704         ((1) (ly:warning (_ "Compilation completed with warnings or errors")))
705         (else (ly:message ""))))
706   (exit status))
707
708 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
709
710 (define-public (lilypond-main files)
711   "Entry point for LilyPond."
712   (eval-string (ly:command-line-code))
713   (if (ly:get-option 'help)
714       (begin (ly:option-usage)
715              (ly:exit 0 #t)))
716   (if (ly:get-option 'show-available-fonts)
717       (begin (ly:font-config-display-fonts)
718              (ly:exit 0 #t)))
719   (if (ly:get-option 'gui)
720       (gui-main files))
721   (if (null? files)
722       (begin (ly:usage)
723              (ly:exit 2 #t)))
724   (if (ly:get-option 'read-file-list)
725       (set! files
726             (filter (lambda (s)
727                       (> (string-length s) 0))
728                     (apply append
729                            (map (lambda (f)
730                                   (string-split (ly:gulp-file f) #\nl))
731                                 files)))))
732   (if (and (number? (ly:get-option 'job-count))
733            (>= (length files) (ly:get-option 'job-count)))
734       (let* ((count (ly:get-option 'job-count))
735              (split-todo (split-list files count))
736              (joblist (multi-fork count))
737              (errors '()))
738         (if (not (string-or-symbol? (ly:get-option 'log-file)))
739             (ly:set-option 'log-file "lilypond-multi-run"))
740         (if (number? joblist)
741             (begin (ly:set-option
742                     'log-file (format "~a-~a"
743                                       (ly:get-option 'log-file) joblist))
744                    (set! files (vector-ref split-todo joblist)))
745             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
746                    (for-each
747                     (lambda (pid)
748                       (let* ((stat (cdr (waitpid pid))))
749                         (if (not (= stat 0))
750                             (set! errors
751                                   (acons (list-element-index joblist pid)
752                                          stat errors)))))
753                     joblist)
754                    (for-each
755                     (lambda (x)
756                       (let* ((job (car x))
757                              (state (cdr x))
758                              (logfile (format "~a-~a.log"
759                                               (ly:get-option 'log-file) job))
760                              (log (ly:gulp-file logfile))
761                              (len (string-length log))
762                              (tail (substring  log (max 0 (- len 1024)))))
763                         (if (status:term-sig state)
764                             (ly:message
765                              "\n\n~a\n"
766                              (format (_ "job ~a terminated with signal: ~a")
767                                      job (status:term-sig state)))
768                             (ly:message
769                              (_ "logfile ~a (exit ~a):\n~a")
770                              logfile (status:exit-val state) tail))))
771                     errors)
772                    (if (pair? errors)
773                        (ly:error "Children ~a exited with errors."
774                                  (map car errors)))
775                    ;; must overwrite individual entries
776                    (if (ly:get-option 'dump-profile)
777                        (dump-profile "lily-run-total"
778                                      '(0 0) (profile-measurements)))
779                    (if (null? errors)
780                        (ly:exit 0 #f)
781                        (ly:exit 1 #f))))))
782
783   (if (string-or-symbol? (ly:get-option 'log-file))
784       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
785   (let ((failed (lilypond-all files)))
786     (if (ly:get-option 'trace-scheme-coverage)
787         (begin
788           (coverage:show-all (lambda (f)
789                                (string-contains f "lilypond")))))
790     (if (pair? failed)
791         (begin (ly:error (_ "failed files: ~S") (string-join failed))
792                (ly:exit 1 #f))
793         (begin
794           (ly:exit 0 #f)))))
795
796
797 (define-public (lilypond-all files)
798   (let* ((failed '())
799          (separate-logs (ly:get-option 'separate-log-files))
800          (ping-log
801           (if separate-logs
802               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
803                              (format "~a.log" (ly:get-option 'log-file))
804                              "/dev/tty") "a") #f))
805          (do-measurements (ly:get-option 'dump-profile))
806          (handler (lambda (key failed-file)
807                     (set! failed (append (list failed-file) failed)))))
808     (gc)
809     (for-each
810      (lambda (x)
811        (let* ((start-measurements (if do-measurements
812                                       (profile-measurements)
813                                       #f))
814               (base (dir-basename x ".ly"))
815               (all-settings (ly:all-options)))
816          (if separate-logs
817              (ly:stderr-redirect (format "~a.log" base) "w"))
818          (if ping-log
819              (format ping-log "Processing ~a\n" base))
820          (if (ly:get-option 'trace-memory-frequency)
821              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
822          (lilypond-file handler x)
823          (if start-measurements
824              (dump-profile x start-measurements (profile-measurements)))
825          (if (ly:get-option 'trace-memory-frequency)
826              (begin (mtrace:stop-trace)
827                     (mtrace:dump-results base)))
828          (for-each (lambda (s)
829                      (ly:set-option (car s) (cdr s)))
830                    all-settings)
831          (ly:set-option 'debug-gc-assert-parsed-dead #t)
832          (gc)
833          (ly:set-option 'debug-gc-assert-parsed-dead #f)
834          (if (ly:get-option 'debug-gc)
835              (dump-gc-protects)
836              (ly:reset-all-fonts))))
837      files)
838
839     ;; Ensure a notice re failed files is written to aggregate logfile.
840     (if ping-log
841         (format ping-log "Failed files: ~a\n" failed))
842     (if (ly:get-option 'dump-profile)
843         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
844     failed))
845
846 (define (lilypond-file handler file-name)
847   (catch 'ly-file-failed
848          (lambda () (ly:parse-file file-name))
849          (lambda (x . args) (handler x file-name))))
850
851 (use-modules (scm editor))
852
853 (define-public (gui-main files)
854   (if (null? files)
855       (gui-no-files-handler))
856   (if (not (string? (ly:get-option 'log-file)))
857       (let* ((base (dir-basename (car files) ".ly"))
858              (log-name (string-append base ".log")))
859         (if (not (ly:get-option 'gui))
860             (ly:message (_ "Redirecting output to ~a...") log-name))
861         (ly:stderr-redirect log-name "w")
862         (ly:message "# -*-compilation-*-"))
863       (let ((failed (lilypond-all files)))
864         (if (pair? failed)
865             (begin
866               ;; ugh
867               (ly:stderr-redirect "foo" "r")
868               (system (get-editor-command log-name 0 0 0))
869               (ly:error (_ "failed files: ~S") (string-join failed))
870               ;; not reached?
871               (exit 1))
872             (ly:exit 0 #f)))))
873
874 (define (gui-no-files-handler)
875   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
876          ;; FIXME: soft-code, localize
877          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
878          (cmd (get-editor-command welcome-ly 0 0 0)))
879     (ly:message (_ "Invoking `~a'...\n") cmd)
880     (system cmd)
881     (ly:exit 1 #f)))