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