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