]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily-library.scm
(PATCH_FILES): remove darwin.patch.
[lilypond.git] / scm / lily-library.scm
1 ;;;;
2 ;;;; lily-library.scm -- utilities
3 ;;;;
4 ;;;;  source file of the GNU LilyPond music typesetter
5 ;;;; 
6 ;;;; (c) 1998--2006 Jan Nieuwenhuizen <janneke@gnu.org>
7 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
8
9
10 (define-public X 0)
11 (define-public Y 1)
12 (define-safe-public START -1)
13 (define-safe-public STOP 1)
14 (define-public LEFT -1)
15 (define-public RIGHT 1)
16 (define-public UP 1)
17 (define-public DOWN -1)
18 (define-public CENTER 0)
19
20 (define-safe-public DOUBLE-FLAT -4)
21 (define-safe-public THREE-Q-FLAT -3)
22 (define-safe-public FLAT -2)
23 (define-safe-public SEMI-FLAT -1)
24 (define-safe-public NATURAL 0)
25 (define-safe-public SEMI-SHARP 1)
26 (define-safe-public SHARP 2)
27 (define-safe-public THREE-Q-SHARP 3)
28 (define-safe-public DOUBLE-SHARP 4)
29 (define-safe-public SEMI-TONE 2)
30
31 (define-public ZERO-MOMENT (ly:make-moment 0 1)) 
32
33 (define-public (moment-min a b)
34   (if (ly:moment<? a b) a b))
35
36 (define-public (average x . lst)
37   (/ (+ x (apply + lst)) (1+ (length lst))))
38
39 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
40 ;; lily specific variables.
41
42 (define-public default-script-alist '())
43
44
45 ;; parser stuff.
46 (define-public (print-music-as-book parser music)
47   (let* ((head (ly:parser-lookup parser '$defaultheader))
48          (book (ly:make-book (ly:parser-lookup parser '$defaultpaper)
49                              head (scorify-music music parser))))
50     (print-book-with-defaults parser book)))
51
52 (define-public (print-score-as-book parser score)
53   (let* ((head (ly:parser-lookup parser '$defaultheader))
54          (book (ly:make-book (ly:parser-lookup parser '$defaultpaper)
55                              head score)))
56     (print-book-with-defaults parser book)))
57
58 (define-public (print-score parser score)
59   (let* ((head (ly:parser-lookup parser '$defaultheader))
60          (book (ly:make-book (ly:parser-lookup parser '$defaultpaper)
61                              head score)))
62     (ly:parser-print-score parser book)))
63                 
64 (define-public (collect-scores-for-book parser score)
65   (ly:parser-define!
66    parser 'toplevel-scores
67    (cons score (ly:parser-lookup parser 'toplevel-scores))))
68
69
70 (define-public (scorify-music music parser)
71   
72   (for-each (lambda (func)
73               (set! music (func music parser)))
74             toplevel-music-functions)
75
76   (ly:make-score music))
77
78 (define-public (collect-music-for-book parser music)
79   ;; discard music if its 'void property is true.
80   (let ((void-music (ly:music-property music 'void)))
81     (if (or (null? void-music) (not void-music))
82         (collect-scores-for-book parser (scorify-music music parser)))))
83
84
85 (define-public (print-book-with-defaults parser book)
86   (let*
87       ((paper (ly:parser-lookup parser '$defaultpaper))
88        (layout (ly:parser-lookup parser '$defaultlayout))
89        (count (ly:parser-lookup parser 'output-count))
90        (base (ly:parser-output-name parser)))
91
92     (if (not (integer? count))
93         (set! count 0))
94
95     (if (> count 0)
96         (set! base (format #f "~a-~a" base count)))
97
98     (ly:parser-define! parser 'output-count (1+ count))
99     (ly:book-process book paper layout base)
100     ))
101
102 (define-public (print-score-with-defaults parser score)
103   (let*
104       ((paper (ly:parser-lookup parser '$defaultpaper))
105        (layout (ly:parser-lookup parser '$defaultlayout))
106        (header (ly:parser-lookup parser '$defaultheader))
107        (count (ly:parser-lookup parser 'output-count))
108        (base (ly:parser-output-name parser)))
109
110     (if (not (integer? count))
111         (set! count 0))
112
113     (if (> count 0)
114         (set! base (format #f "~a-~a" base count)))
115
116     (ly:parser-define! parser 'output-count (1+ count))
117     (ly:score-process score header paper layout base)
118     ))
119
120
121 ;;;;;;;;;;;;;;;;
122 ;; alist
123 (define-public assoc-get ly:assoc-get)
124
125 (define-public (uniqued-alist alist acc)
126   (if (null? alist) acc
127       (if (assoc (caar alist) acc)
128           (uniqued-alist (cdr alist) acc)
129           (uniqued-alist (cdr alist) (cons (car alist) acc)))))
130
131 (define-public (alist<? x y)
132   (string<? (symbol->string (car x))
133             (symbol->string (car y))))
134
135 (define-public (chain-assoc x alist-list)
136   (if (null? alist-list)
137       #f
138       (let* ((handle (assoc x (car alist-list))))
139         (if (pair? handle)
140             handle
141             (chain-assoc x (cdr alist-list))))))
142
143 (define-public (chain-assoc-get x alist-list . default)
144   "Return ALIST entry for X. Return DEFAULT (optional, else #f) if not
145 found."
146
147   (define (helper x alist-list default)
148     (if (null? alist-list)
149         default
150         (let* ((handle (assoc x (car alist-list))))
151           (if (pair? handle)
152               (cdr handle)
153               (helper x (cdr alist-list) default)))))
154
155   (helper x alist-list
156           (if (pair? default) (car default) #f)))
157
158 (define (map-alist-vals func list)
159   "map FUNC over the vals of  LIST, leaving the keys."
160   (if (null?  list)
161       '()
162       (cons (cons  (caar list) (func (cdar list)))
163             (map-alist-vals func (cdr list)))))
164
165 (define (map-alist-keys func list)
166   "map FUNC over the keys of an alist LIST, leaving the vals. "
167   (if (null?  list)
168       '()
169       (cons (cons (func (caar list)) (cdar list))
170             (map-alist-keys func (cdr list)))))
171
172 (define-public (first-member members lst)
173   "Return first successful MEMBER of member from MEMBERS in LST."
174   (if (null? members)
175       #f
176       (let ((m (member (car members) lst)))
177         (if m m (first-member (cdr members) lst)))))
178
179 (define-public (first-assoc keys lst)
180   "Return first successful ASSOC of key from KEYS in LST."
181   (if (null? keys)
182       #f
183       (let ((k (assoc (car keys) lst)))
184         (if k k (first-assoc (cdr keys) lst)))))
185
186 (define-public (flatten-alist alist)
187   (if (null? alist)
188       '()
189       (cons (caar alist)
190             (cons (cdar alist)
191                   (flatten-alist (cdr alist))))))
192
193 ;;;;;;;;;;;;;;;;
194 ;; vector
195 (define-public (vector-for-each proc vec)
196   (do
197       ((i 0 (1+ i)))
198       ((>= i (vector-length vec)) vec)
199     (vector-set! vec i (proc (vector-ref vec i)))))
200
201 ;;;;;;;;;;;;;;;;
202 ;; hash
203
204 (if (not (defined? 'hash-table?)) ;; guile 1.6 compat
205     (begin
206       (define hash-table? vector?)
207       (define-public (hash-for-each proc tab)
208         (hash-fold (lambda (k v prior)
209                      (proc k v)
210                      #f)
211                    #f
212                    tab))
213       (define-public (hash-table->alist t)
214         "Convert table t to list"
215         (apply append (vector->list t))))
216
217     ;; native hashtabs.
218     (begin
219       (define-public (hash-table->alist t)
220         (hash-fold (lambda (k v acc) (acons  k v  acc))
221                    '() t))))
222
223 ;; todo: code dup with C++. 
224 (define-safe-public (alist->hash-table lst)
225   "Convert alist to table"
226   (let ((m (make-hash-table (length lst))))
227     (map (lambda (k-v) (hashq-set! m (car k-v) (cdr k-v))) lst)
228     m))
229
230 ;;;;;;;;;;;;;;;;
231 ;; list
232
233
234 (define-public (list-join lst intermediate)
235   "put INTERMEDIATE  between all elts of LST."
236   
237   (reduce (lambda (elt prev)
238             (if (pair? prev)
239                 (cons  elt (cons intermediate prev))
240                 (list elt intermediate prev)))
241           '() lst))
242
243
244 (define-public (filtered-map proc lst)
245   (filter
246    (lambda (x) x)
247    (map proc lst)))
248
249
250 (define (flatten-list lst)
251   "Unnest LST" 
252   (if (null? lst)
253       '()
254       (if (pair? (car lst))
255           (append (flatten-list (car lst)) (flatten-list  (cdr lst)))
256           (cons (car lst) (flatten-list (cdr lst))))))
257
258 (define (list-minus a b)
259   "Return list of elements in A that are not in B."
260   (lset-difference eq? a b))
261
262 ;; TODO: use the srfi-1 partition function.
263 (define-public (uniq-list lst)
264   
265   "Uniq LST, assuming that it is sorted"
266   (define (helper acc lst) 
267     (if (null? lst)
268         acc
269         (if (null? (cdr lst))
270             (cons (car lst) acc)
271             (if (equal? (car lst) (cadr lst))
272                 (helper acc (cdr lst))
273                 (helper (cons (car lst) acc)  (cdr lst))))))
274   (reverse! (helper '() lst) '()))
275
276 (define (split-at-predicate predicate lst)
277  "Split LST = (a_1 a_2 ... a_k b_1 ... b_k)
278   into L1 = (a_1 ... a_k ) and L2 =(b_1 .. b_k) 
279   Such that (PREDICATE a_i a_{i+1}) and not (PREDICATE a_k b_1).
280   L1 is copied, L2 not.
281
282   (split-at-predicate (lambda (x y) (= (- y x) 2)) '(1 3 5 9 11) (cons '() '()))"
283  ;; " Emacs is broken
284
285  (define (inner-split predicate lst acc)
286    (cond
287     ((null? lst) acc)
288     ((null? (cdr lst))
289      (set-car! acc (cons (car lst) (car acc)))
290      acc)
291     ((predicate (car lst) (cadr lst))
292      (set-car! acc (cons (car lst) (car acc)))
293      (inner-split predicate (cdr lst) acc))
294     (else
295      (set-car! acc (cons (car lst) (car acc)))
296      (set-cdr! acc (cdr lst))
297      acc)))
298  
299  (let* ((c (cons '() '())))
300    (inner-split predicate lst  c)
301    (set-car! c (reverse! (car c)))
302    c))
303
304 (define-public (split-list lst sep?)
305    "(display (split-list '(a b c / d e f / g) (lambda (x) (equal? x '/))))
306    =>
307    ((a b c) (d e f) (g))
308   "
309    ;; " Emacs is broken
310    (define (split-one sep?  lst acc)
311      "Split off the first parts before separator and return both parts."
312      (if (null? lst)
313          (cons acc '())
314          (if (sep? (car lst))
315              (cons acc (cdr lst))
316              (split-one sep? (cdr lst) (cons (car lst) acc)))))
317    
318    (if (null? lst)
319        '()
320        (let* ((c (split-one sep? lst '())))
321          (cons (reverse! (car c) '()) (split-list (cdr c) sep?)))))
322
323 (define-public (offset-add a b)
324   (cons (+ (car a) (car b))
325         (+ (cdr a) (cdr b)))) 
326
327 (define-public (offset-flip-y o)
328   (cons (car o) (- (cdr o))))
329
330 (define-public (offset-scale o scale)
331   (cons (* (car o) scale)
332         (* (cdr o) scale)))
333
334 (define-public (ly:list->offsets accum coords)
335   (if (null? coords)
336       accum
337       (cons (cons (car coords) (cadr coords))
338             (ly:list->offsets accum (cddr coords)))))
339
340 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
341 ;; numbers
342
343 (if (not (defined? 'nan?)) ;; guile 1.6 compat
344     (define-public (nan? x) (not (or (< 0.0 x)
345                                      (> 0.0 x)
346                                      (= 0.0 x)))))
347
348 (if (not (defined? 'inf?))
349     (define-public (inf? x) (= (/ 1.0 x) 0.0)))
350
351 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
352 ;; intervals
353
354 (define-public (interval-length x)
355   "Length of the number-pair X, when an interval"
356   (max 0 (- (cdr x) (car x))))
357
358 (define-public interval-start car)
359 (define-public (ordered-cons a b)
360   (cons (min a b)
361         (max a b)))
362
363 (define-public interval-end cdr)
364
365 (define-public (interval-index interval dir)
366   "Interpolate INTERVAL between between left (DIR=-1) and right (DIR=+1)"
367   
368   (* (+  (interval-start interval) (interval-end interval)
369          (* dir (- (interval-end interval) (interval-start interval))))
370      0.5))
371
372 (define-public (interval-center x)
373   "Center the number-pair X, when an interval"
374   (if (interval-empty? x)
375       0.0
376       (/ (+ (car x) (cdr x)) 2)))
377
378 (define-public interval-start car)
379 (define-public interval-end cdr)
380 (define-public (interval-translate iv amount)
381   (cons (+ amount (car iv))
382         (+ amount (cdr iv))))
383
384 (define (other-axis a)
385   (remainder (+ a 1) 2))
386
387 (define-public (interval-widen iv amount)
388    (cons (- (car iv) amount)
389          (+ (cdr iv) amount)))
390
391
392 (define-public (interval-empty? iv)
393    (> (car iv) (cdr iv)))
394
395 (define-public (interval-union i1 i2)
396    (cons (min (car i1) (car i2))
397          (max (cdr i1) (cdr i2))))
398
399 (define-public (interval-sane? i)
400   (not (or  (nan? (car i))
401             (inf? (car i))
402             (nan? (cdr i))
403             (inf? (cdr i))
404             (> (car i) (cdr i)))))
405
406
407 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
408 ;;
409
410
411 (define-public (string-encode-integer i)
412   (cond
413    ((= i  0) "o")
414    ((< i 0)   (string-append "n" (string-encode-integer (- i))))
415    (else (string-append
416           (make-string 1 (integer->char (+ 65 (modulo i 26))))
417           (string-encode-integer (quotient i 26))))))
418
419 (define-public (ly:numbers->string lst)
420   (string-join (map ly:number->string lst) " "))
421
422 (define (number->octal-string x)
423   (let* ((n (inexact->exact x))
424          (n64 (quotient n 64))
425          (n8 (quotient (- n (* n64 64)) 8)))
426     (string-append
427      (number->string n64)
428      (number->string n8)
429      (number->string (remainder (- n (+ (* n64 64) (* n8 8))) 8)))))
430
431 (define-public (ly:inexact->string x radix)
432   (let ((n (inexact->exact x)))
433     (number->string n radix)))
434
435 (define-public (ly:number-pair->string c)
436   (string-append (ly:number->string (car c)) " "
437                  (ly:number->string (cdr c))))
438
439
440 (define-public (write-me message x)
441   "Return X.  Display MESSAGE and write X.  Handy for debugging,
442 possibly turned off."
443   (display message) (write x) (newline) x)
444 ;;  x)
445
446 (define-public (stderr string . rest)
447   (apply format (cons (current-error-port) (cons string rest)))
448   (force-output (current-error-port)))
449
450 (define-public (debugf string . rest)
451   (if #f
452       (apply stderr (cons string rest))))
453
454 (define (index-cell cell dir)
455   (if (equal? dir 1)
456       (cdr cell)
457       (car cell)))
458
459 (define (cons-map f x)
460   "map F to contents of X"
461   (cons (f (car x)) (f (cdr x))))
462
463 (define-public (list-insert-separator lst between)
464   "Create new list, inserting BETWEEN between elements of LIST"
465   (define (conc x y )
466     (if (eq? y #f)
467         (list x)
468         (cons x  (cons between y))))
469   (fold-right conc #f lst))
470
471 (define-public (string-regexp-substitute a b str)
472   (regexp-substitute/global #f a str 'pre b 'post)) 
473
474 (define (regexp-split str regex)
475   (define matches '())
476   (define end-of-prev-match 0)
477   (define (notice match)
478
479     (set! matches (cons (substring (match:string match)
480                                    end-of-prev-match
481                                    (match:start match))
482                         matches))
483     (set! end-of-prev-match (match:end match)))
484
485   (regexp-substitute/global #f regex str notice 'post)
486
487   (if (< end-of-prev-match (string-length str))
488       (set!
489        matches
490        (cons (substring str end-of-prev-match (string-length str)) matches)))
491
492    (reverse matches))
493
494 ;;;;;;;;;;;;;;;;
495 ; other
496 (define (sign x)
497   (if (= x 0)
498       0
499       (if (< x 0) -1 1)))
500
501 (define-public (car< a b) (< (car a) (car b)))
502
503
504 (define-public (symbol<? lst r)
505   (string<? (symbol->string lst) (symbol->string r)))
506
507 (define-public (symbol-key<? lst r)
508   (string<? (symbol->string (car lst)) (symbol->string (car r))))
509
510 ;;
511 ;; don't confuse users with #<procedure .. > syntax. 
512 ;; 
513 (define-public (scm->string val)
514   (if (and (procedure? val) (symbol? (procedure-name val)))
515       (symbol->string (procedure-name val))
516       (string-append
517        (if (self-evaluating? val) "" "'")
518        (call-with-output-string (lambda (port) (display val port))))))
519
520 (define-public (!= lst r)
521   (not (= lst r)))
522
523 (define-public lily-unit->bigpoint-factor
524   (cond
525    ((equal? (ly:unit) "mm") (/ 72.0 25.4))
526    ((equal? (ly:unit) "pt") (/ 72.0 72.27))
527    (else (ly:error (_ "unknown unit: ~S") (ly:unit)))))
528
529 (define-public lily-unit->mm-factor
530   (* 25.4 (/ lily-unit->bigpoint-factor 72)))
531
532 ;;; FONT may be font smob, or pango font string...
533 (define-public (font-name-style font)
534       ;; FIXME: ughr, (ly:font-name) sometimes also has Style appended.
535       (let* ((font-name (ly:font-name font))
536              (full-name (if font-name font-name (ly:font-file-name font)))
537              (name-style (string-split full-name #\-)))
538         ;; FIXME: ughr, barf: feta-alphabet is actually emmentaler
539         (if (string-prefix? "feta-alphabet" full-name)
540             (list "emmentaler"
541                   (substring  full-name (string-length "feta-alphabet")))
542             (if (not (null? (cdr name-style)))
543             name-style
544             (append name-style '("Regular"))))))
545
546 (define-public (modified-font-metric-font-scaling font)
547   (let* ((designsize (ly:font-design-size font))
548          (magnification (* (ly:font-magnification font)))
549          (scaling (* magnification designsize)))
550     (debugf "scaling:~S\n" scaling)
551     (debugf "magnification:~S\n" magnification)
552     (debugf "design:~S\n" designsize)
553     scaling))
554
555 (define-public (version-not-seen-message input-file-name)
556   (ly:message
557    (string-append
558     input-file-name ": 0: " (_ "warning: ")
559    (format #f
560            (_ "no \\version statement found, please add~afor future compatibility")
561            (format #f "\n\n\\version ~s\n\n" (lilypond-version))))))
562
563 (define-public (old-relative-not-used-message input-file-name)
564   (ly:message
565    (string-append
566     input-file-name ": 0: " (_ "warning: ")
567     (_ "old relative compatibility not used"))))