]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily-library.scm
Simplify hash-table->alist, alist->hash-table, functional-or, functional-and, list...
[lilypond.git] / scm / lily-library.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2012 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 ; for take, drop, take-while, list-index, and find-tail:
20 (use-modules (srfi srfi-1))
21
22 ; for define-safe-public when byte-compiling using Guile V2
23 (use-modules (scm safe-utility-defs))
24
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;; constants.
27
28 (define-public X 0)
29 (define-public Y 1)
30 (define-safe-public START -1)
31 (define-safe-public STOP 1)
32 (define-public LEFT -1)
33 (define-public RIGHT 1)
34 (define-public UP 1)
35 (define-public DOWN -1)
36 (define-public CENTER 0)
37
38 (define-safe-public DOUBLE-FLAT-QTS -4)
39 (define-safe-public THREE-Q-FLAT-QTS -3)
40 (define-safe-public FLAT-QTS -2)
41 (define-safe-public SEMI-FLAT-QTS -1)
42 (define-safe-public NATURAL-QTS 0)
43 (define-safe-public SEMI-SHARP-QTS 1)
44 (define-safe-public SHARP-QTS 2)
45 (define-safe-public THREE-Q-SHARP-QTS 3)
46 (define-safe-public DOUBLE-SHARP-QTS 4)
47 (define-safe-public SEMI-TONE-QTS 2)
48
49 (define-safe-public DOUBLE-FLAT  -1)
50 (define-safe-public THREE-Q-FLAT -3/4)
51 (define-safe-public FLAT -1/2)
52 (define-safe-public SEMI-FLAT -1/4)
53 (define-safe-public NATURAL 0)
54 (define-safe-public SEMI-SHARP 1/4)
55 (define-safe-public SHARP 1/2)
56 (define-safe-public THREE-Q-SHARP 3/4)
57 (define-safe-public DOUBLE-SHARP 1)
58 (define-safe-public SEMI-TONE 1/2)
59
60 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
61 ;; moments
62
63 (define-public ZERO-MOMENT (ly:make-moment 0 1))
64
65 (define-public (moment-min a b)
66   (if (ly:moment<? a b) a b))
67
68 (define-public (moment<=? a b)
69   (or (equal? a b)
70       (ly:moment<? a b)))
71
72 (define-public (fraction->moment fraction)
73   (if (null? fraction)
74       ZERO-MOMENT
75       (ly:make-moment (car fraction) (cdr fraction))))
76
77 (define-public (moment->fraction moment)
78   (cons (ly:moment-main-numerator moment)
79         (ly:moment-main-denominator moment)))
80
81 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
82 ;; arithmetic
83 (define-public (average x . lst)
84   (/ (+ x (apply + lst)) (1+ (length lst))))
85
86 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
87 ;; parser <-> output hooks.
88
89 (define-public (collect-bookpart-for-book parser book-part)
90   "Toplevel book-part handler."
91   (define (add-bookpart book-part)
92     (ly:parser-define!
93        parser 'toplevel-bookparts
94        (cons book-part (ly:parser-lookup parser 'toplevel-bookparts))))
95   ;; If toplevel scores have been found before this \bookpart,
96   ;; add them first to a dedicated bookpart
97   (if (pair? (ly:parser-lookup parser 'toplevel-scores))
98       (begin
99         (add-bookpart (ly:make-book-part
100                        (ly:parser-lookup parser 'toplevel-scores)))
101         (ly:parser-define! parser 'toplevel-scores (list))))
102   (add-bookpart book-part))
103
104 (define-public (collect-scores-for-book parser score)
105   (ly:parser-define!
106    parser 'toplevel-scores
107    (cons score (ly:parser-lookup parser 'toplevel-scores))))
108
109 (define-public (collect-music-aux score-handler parser music)
110   (define (music-property symbol)
111     (let ((value (ly:music-property music symbol)))
112       (if (not (null? value))
113           value
114           #f)))
115   (cond ((music-property 'page-marker)
116          ;; a page marker: set page break/turn permissions or label
117          (begin
118            (let ((label (music-property 'page-label)))
119              (if (symbol? label)
120                  (score-handler (ly:make-page-label-marker label))))
121            (for-each (lambda (symbol)
122                        (let ((permission (music-property symbol)))
123                          (if (symbol? permission)
124                              (score-handler
125                               (ly:make-page-permission-marker symbol
126                                                               (if (eqv? 'forbid permission)
127                                                                   '()
128                                                                   permission))))))
129                      (list 'line-break-permission 'page-break-permission
130                            'page-turn-permission))))
131         ((not (music-property 'void))
132          ;; a regular music expression: make a score with this music
133          ;; void music is discarded
134          (score-handler (scorify-music music parser)))))
135
136 (define-public (collect-music-for-book parser music)
137   "Top-level music handler."
138   (collect-music-aux (lambda (score)
139                        (collect-scores-for-book parser score))
140                      parser
141                      music))
142
143 (define-public (collect-book-music-for-book parser book music)
144   "Book music handler."
145   (collect-music-aux (lambda (score)
146                        (ly:book-add-score! book score))
147                      parser
148                      music))
149
150 (define-public (scorify-music music parser)
151   "Preprocess @var{music}."
152
153   (for-each (lambda (func)
154               (set! music (func music parser)))
155             toplevel-music-functions)
156
157   (ly:make-score music))
158
159
160 (define (get-current-filename parser book)
161   "return any suffix value for output filename allowing for settings by
162 calls to bookOutputName function"
163   (let ((book-filename (paper-variable parser book 'output-filename)))
164     (if (not book-filename)
165         (ly:parser-output-name parser)
166         book-filename)))
167
168 (define (get-current-suffix parser book)
169   "return any suffix value for output filename allowing for settings by calls to
170 bookoutput function"
171   (let ((book-output-suffix (paper-variable parser book 'output-suffix)))
172     (if (not (string? book-output-suffix))
173         (ly:parser-lookup parser 'output-suffix)
174         book-output-suffix)))
175
176 (define-public current-outfile-name #f)  ; for use by regression tests
177
178 (define (get-outfile-name parser book)
179   "return current filename for generating backend output files"
180   ;; user can now override the base file name, so we have to use
181   ;; the file-name concatenated with any potential output-suffix value
182   ;; as the key to out internal a-list
183   (let* ((base-name (get-current-filename parser book))
184          (output-suffix (get-current-suffix parser book))
185          (alist-key (format #f "~a~a" base-name output-suffix))
186          (counter-alist (ly:parser-lookup parser 'counter-alist))
187          (output-count (assoc-get alist-key counter-alist 0))
188          (result base-name))
189     ;; Allow all ASCII alphanumerics, including accents
190     (if (string? output-suffix)
191         (set! result
192               (format #f "~a-~a"
193                       result
194                       (string-regexp-substitute
195                        "[^-[:alnum:]]"
196                        "_"
197                        output-suffix))))
198
199     ;; assoc-get call will always have returned a number
200     (if (> output-count 0)
201         (set! result (format #f "~a-~a" result output-count)))
202
203     (ly:parser-define!
204      parser 'counter-alist
205      (assoc-set! counter-alist alist-key (1+ output-count)))
206     (set! current-outfile-name result)
207     result))
208
209 (define (print-book-with parser book process-procedure)
210   (let* ((paper (ly:parser-lookup parser '$defaultpaper))
211          (layout (ly:parser-lookup parser '$defaultlayout))
212          (outfile-name (get-outfile-name parser book)))
213     (process-procedure book paper layout outfile-name)))
214
215 (define-public (print-book-with-defaults parser book)
216   (print-book-with parser book ly:book-process))
217
218 (define-public (print-book-with-defaults-as-systems parser book)
219   (print-book-with parser book ly:book-process-to-systems))
220
221 ;; Add a score to the current bookpart, book or toplevel
222 (define-public (add-score parser score)
223     (cond
224       ((ly:parser-lookup parser '$current-bookpart)
225           ((ly:parser-lookup parser 'bookpart-score-handler)
226                 (ly:parser-lookup parser '$current-bookpart) score))
227       ((ly:parser-lookup parser '$current-book)
228           ((ly:parser-lookup parser 'book-score-handler)
229                 (ly:parser-lookup parser '$current-book) score))
230       (else
231           ((ly:parser-lookup parser 'toplevel-score-handler) parser score))))
232
233 (define-public paper-variable
234   (let
235       ((get-papers
236         (lambda (parser book)
237           (append (if (and book (ly:output-def? (ly:book-paper book)))
238                       (list (ly:book-paper book))
239                       '())
240                   (ly:parser-lookup parser '$papers)
241                   (list (ly:parser-lookup parser '$defaultpaper))))))
242     (make-procedure-with-setter
243      (lambda (parser book symbol)
244        (any (lambda (p) (ly:output-def-lookup p symbol #f))
245             (get-papers parser book)))
246      (lambda (parser book symbol value)
247        (ly:output-def-set-variable!
248         (car (get-papers parser book))
249         symbol value)))))
250
251 (define-public (add-text parser text)
252   (add-score parser (list text)))
253
254 (define-public (add-music parser music)
255   (collect-music-aux (lambda (score)
256                        (add-score parser score))
257                      parser
258                      music))
259
260 (define-public (context-mod-from-music parser music)
261   (let ((warn #t) (mods (ly:make-context-mod)))
262     (let loop ((m music))
263       (if (music-is-of-type? m 'layout-instruction-event)
264           (let ((symbol (ly:music-property m 'symbol)))
265             (ly:add-context-mod
266              mods
267              (case (ly:music-property m 'name)
268                ((PropertySet)
269                 (list 'assign
270                       symbol
271                       (ly:music-property m 'value)))
272                ((PropertyUnset)
273                 (list 'unset symbol))
274                ((OverrideProperty)
275                 (cons* 'push
276                        symbol
277                        (ly:music-property m 'grob-value)
278                        (cond
279                         ((ly:music-property m 'grob-property #f) => list)
280                         (else
281                          (ly:music-property m 'grob-property-path)))))
282                ((RevertProperty)
283                 (cons* 'pop
284                        symbol
285                        (cond
286                         ((ly:music-property m 'grob-property #f) => list)
287                         (else
288                          (ly:music-property m 'grob-property-path))))))))
289           (case (ly:music-property m 'name)
290             ((ApplyContext)
291              (ly:add-context-mod mods
292                                  (list 'apply
293                                        (ly:music-property m 'procedure))))
294             ((ContextSpeccedMusic)
295              (loop (ly:music-property m 'element)))
296             (else
297              (let ((callback (ly:music-property m 'elements-callback)))
298                (if (procedure? callback)
299                    (for-each loop (callback m))
300                    (if (and warn (ly:duration? (ly:music-property m 'duration)))
301                        (begin
302                          (ly:music-warning
303                           music
304                           (_ "Music unsuitable for context-mod"))
305                          (set! warn #f)))))))))
306     mods))
307
308 (define-public (context-defs-from-music parser output-def music)
309   (let ((warn #t))
310     (let loop ((m music) (mods #f))
311       ;; The parser turns all sets, overrides etc into something
312       ;; wrapped in ContextSpeccedMusic.  If we ever get a set,
313       ;; override etc that is not wrapped in ContextSpeccedMusic, the
314       ;; user has created it in Scheme himself without providing the
315       ;; required wrapping.  In that case, using #f in the place of a
316       ;; context modification results in a reasonably recognizable
317       ;; error.
318       (if (music-is-of-type? m 'layout-instruction-event)
319           (ly:add-context-mod
320            mods
321            (case (ly:music-property m 'name)
322              ((PropertySet)
323               (list 'assign
324                     (ly:music-property m 'symbol)
325                     (ly:music-property m 'value)))
326              ((PropertyUnset)
327               (list 'unset
328                     (ly:music-property m 'symbol)))
329              ((OverrideProperty)
330               (cons* 'push
331                      (ly:music-property m 'symbol)
332                      (ly:music-property m 'grob-value)
333                      (cond
334                       ((ly:music-property m 'grob-property #f) => list)
335                       (else
336                        (ly:music-property m 'grob-property-path)))))
337              ((RevertProperty)
338               (cons* 'pop
339                      (ly:music-property m 'symbol)
340                      (cond
341                       ((ly:music-property m 'grob-property #f) => list)
342                       (else
343                        (ly:music-property m 'grob-property-path)))))))
344           (case (ly:music-property m 'name)
345             ((ApplyContext)
346              (ly:add-context-mod mods
347                                  (list 'apply
348                                        (ly:music-property m 'procedure))))
349             ((ContextSpeccedMusic)
350              ;; Use let* here to let defs catch up with modifications
351              ;; to the context defs made in the recursion
352              (let* ((mods (loop (ly:music-property m 'element)
353                                 (ly:make-context-mod)))
354                     (defs (ly:output-find-context-def
355                            output-def (ly:music-property m 'context-type))))
356                (if (null? defs)
357                    (ly:music-warning
358                     music
359                     (ly:format (_ "Cannot find context-def \\~a")
360                                (ly:music-property m 'context-type)))
361                    (for-each
362                     (lambda (entry)
363                       (ly:output-def-set-variable!
364                        output-def (car entry)
365                        (ly:context-def-modify (cdr entry) mods)))
366                     defs))))
367             (else
368              (let ((callback (ly:music-property m 'elements-callback)))
369                (if (procedure? callback)
370                    (fold loop mods (callback m))
371                    (if (and warn (ly:duration? (ly:music-property m 'duration)))
372                        (begin
373                          (ly:music-warning
374                           music
375                           (_ "Music unsuitable for output-def"))
376                          (set! warn #f))))))))
377       mods)))
378
379
380 ;;;;;;;;;;;;;;;;
381 ;; alist
382
383 (define-public assoc-get ly:assoc-get)
384
385 (define-public chain-assoc-get ly:chain-assoc-get)
386
387 (define-public (uniqued-alist alist acc)
388   (if (null? alist) acc
389       (if (assoc (caar alist) acc)
390           (uniqued-alist (cdr alist) acc)
391           (uniqued-alist (cdr alist) (cons (car alist) acc)))))
392
393 (define-public (alist<? x y)
394   (string<? (symbol->string (car x))
395             (symbol->string (car y))))
396
397 (define (map-alist-vals func list)
398   "map FUNC over the vals of  LIST, leaving the keys."
399   (if (null?  list)
400       '()
401       (cons (cons  (caar list) (func (cdar list)))
402             (map-alist-vals func (cdr list)))))
403
404 (define (map-alist-keys func list)
405   "map FUNC over the keys of an alist LIST, leaving the vals."
406   (if (null?  list)
407       '()
408       (cons (cons (func (caar list)) (cdar list))
409             (map-alist-keys func (cdr list)))))
410
411 (define-public (first-member members lst)
412   "Return first successful member (of member) from @var{members} in
413 @var{lst}."
414   (any (lambda (m) (member m lst)) members))
415
416 (define-public (first-assoc keys lst)
417   "Return first successful assoc of key from @var{keys} in @var{lst}."
418   (any (lambda (k) (assoc k lst)) keys))
419
420 (define-public (flatten-alist alist)
421   (if (null? alist)
422       '()
423       (cons (caar alist)
424             (cons (cdar alist)
425                   (flatten-alist (cdr alist))))))
426
427 (define (assoc-remove key alist)
428   "Remove key (and its corresponding value) from an alist.
429    Different than assoc-remove! because it is non-destructive."
430   (define (assoc-crawler key l r)
431     (if (null? r)
432         l
433         (if (equal? (caar r) key)
434             (append l (cdr r))
435             (assoc-crawler key (append l `(,(car r))) (cdr r)))))
436   (assoc-crawler key '() alist))
437
438 (define-public (map-selected-alist-keys function keys alist)
439   "Return @var{alist} with @var{function} applied to all of the values
440 in list @var{keys}.
441
442 For example:
443 @example
444 @code{guile> (map-selected-alist-keys - '(a b) '((a . 1) (b . -2) (c . 3) (d . 4)))}
445 @code{((a . -1) (b . 2) (c . 3) (d . 4)}
446 @end example"
447    (define (map-selected-alist-keys-helper function key alist)
448      (map
449      (lambda (pair)
450        (if (equal? key (car pair))
451            (cons key (function (cdr pair)))
452            pair))
453      alist))
454    (if (null? keys)
455        alist
456        (map-selected-alist-keys
457          function
458          (cdr keys)
459          (map-selected-alist-keys-helper function (car keys) alist))))
460
461 ;;;;;;;;;;;;;;;;
462 ;; vector
463
464 (define-public (vector-for-each proc vec)
465   (do
466       ((i 0 (1+ i)))
467       ((>= i (vector-length vec)) vec)
468     (vector-set! vec i (proc (vector-ref vec i)))))
469
470 ;;;;;;;;;;;;;;;;
471 ;; hash
472
473 (define-public (hash-table->alist t)
474   (hash-fold acons '() t))
475
476 ;; todo: code dup with C++.
477 (define-safe-public (alist->hash-table lst)
478   "Convert alist to table"
479   (let ((m (make-hash-table (length lst))))
480     (for-each (lambda (k-v) (hashq-set! m (car k-v) (cdr k-v))) lst)
481     m))
482
483 ;;;;;;;;;;;;;;;;
484 ;; list
485
486 (define (functional-or . rest)
487   (any identity rest))
488
489 (define (functional-and . rest)
490   (every identity rest))
491
492 (define (split-list lst n)
493   "Split LST in N equal sized parts"
494
495   (define (helper todo acc-vector k)
496     (if (null? todo)
497         acc-vector
498         (begin
499           (if (< k 0)
500               (set! k (+ n k)))
501
502           (vector-set! acc-vector k (cons (car todo) (vector-ref acc-vector k)))
503           (helper (cdr todo) acc-vector (1- k)))))
504
505   (helper lst (make-vector n '()) (1- n)))
506
507 (define (list-element-index lst x)
508   (list-index (lambda (m) (equal? m x))))
509
510 (define-public (count-list lst)
511   "Given @var{lst} as @code{(E1 E2 .. )}, return
512 @code{((E1 . 1) (E2 . 2) ... )}."
513
514   (define (helper l acc count)
515     (if (pair? l)
516         (helper (cdr l) (cons (cons (car l) count) acc) (1+ count))
517         acc))
518
519
520   (reverse (helper lst '() 1)))
521
522 (define-public (list-join lst intermediate)
523   "Put @var{intermediate} between all elts of @var{lst}."
524
525   (fold-right
526    (lambda (elem prev)
527             (if (pair? prev)
528                 (cons  elem (cons intermediate prev))
529                 (list elem)))
530           '() lst))
531
532 (define-public (filtered-map proc lst)
533   (filter
534    (lambda (x) x)
535    (map proc lst)))
536
537 (define-public (flatten-list x)
538   "Unnest list."
539   (cond ((null? x) '())
540         ((not (pair? x)) (list x))
541         (else (append (flatten-list (car x))
542                       (flatten-list (cdr x))))))
543
544 (define (list-minus a b)
545   "Return list of elements in A that are not in B."
546   (lset-difference eq? a b))
547
548 (define-public (uniq-list lst)
549   "Uniq @var{lst}, assuming that it is sorted.  Uses @code{equal?}
550 for comparisons."
551
552   (reverse!
553    (fold (lambda (x acc)
554            (if (null? acc)
555                (list x)
556                (if (equal? x (car acc))
557                    acc
558                    (cons x acc))))
559          '() lst) '()))
560
561 (define (split-at-predicate pred lst)
562   "Split LST into two lists at the first element that returns #f for
563   (PRED previous_element element).  Return the two parts as a pair.
564   Example: (split-at-predicate < '(1 2 3 2 1)) ==> ((1 2 3) . (2 1))"
565   (if (null? lst)
566       (list lst)
567       (let ((i (list-index (lambda (x y) (not (pred x y)))
568                            lst
569                            (cdr lst))))
570         (if i
571             (cons (take lst (1+ i)) (drop lst (1+ i)))
572             (list lst)))))
573
574 (define-public (split-list-by-separator lst pred)
575   "Split @var{lst} at each element that satisfies @var{pred}, and return
576 the parts (with the separators removed) as a list of lists.  For example,
577 executing @samp{(split-list-by-separator '(a 0 b c 1 d) number?)} returns
578 @samp{((a) (b c) (d))}."
579   (let loop ((result '()) (lst lst))
580     (if (and lst (not (null? lst)))
581         (loop
582           (append result
583                   (list (take-while (lambda (x) (not (pred x))) lst)))
584           (let ((tail (find-tail pred lst)))
585             (if tail (cdr tail) #f)))
586        result)))
587
588 (define-public (offset-add a b)
589   (cons (+ (car a) (car b))
590         (+ (cdr a) (cdr b))))
591
592 (define-public (offset-flip-y o)
593   (cons (car o) (- (cdr o))))
594
595 (define-public (offset-scale o scale)
596   (cons (* (car o) scale)
597         (* (cdr o) scale)))
598
599 (define-public (ly:list->offsets accum coords)
600   (if (null? coords)
601       accum
602       (cons (cons (car coords) (cadr coords))
603             (ly:list->offsets accum (cddr coords)))))
604
605 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
606 ;; intervals
607
608 (define-public empty-interval '(+inf.0 . -inf.0))
609
610 (define-public (symmetric-interval expr)
611   (cons (- expr) expr))
612
613 (define-public (interval-length x)
614   "Length of the number-pair @var{x}, if an interval."
615   (max 0 (- (cdr x) (car x))))
616
617 (define-public (ordered-cons a b)
618   (cons (min a b)
619         (max a b)))
620
621 (define-public (interval-bound interval dir)
622   ((if (= dir RIGHT) cdr car) interval))
623
624 (define-public (interval-index interval dir)
625   "Interpolate @var{interval} between between left (@var{dir}=-1) and
626 right (@var{dir}=+1)."
627
628   (* (+  (interval-start interval) (interval-end interval)
629          (* dir (- (interval-end interval) (interval-start interval))))
630      0.5))
631
632 (define-public (interval-center x)
633   "Center the number-pair @var{x}, if an interval."
634   (if (interval-empty? x)
635       0.0
636       (/ (+ (car x) (cdr x)) 2)))
637
638 (define-public interval-start car)
639
640 (define-public interval-end cdr)
641
642 (define (other-axis a)
643   (remainder (+ a 1) 2))
644
645 (define-public (interval-scale iv factor)
646   (cons (* (car iv) factor)
647     (* (cdr iv) factor)))
648
649 (define-public (interval-widen iv amount)
650   (cons (- (car iv) amount)
651     (+ (cdr iv) amount)))
652
653 (define-public (interval-empty? iv)
654    (> (car iv) (cdr iv)))
655
656 (define-public (interval-union i1 i2)
657   (cons
658     (min (car i1) (car i2))
659     (max (cdr i1) (cdr i2))))
660
661 (define-public (interval-intersection i1 i2)
662    (cons
663      (max (car i1) (car i2))
664      (min (cdr i1) (cdr i2))))
665
666 (define-public (interval-sane? i)
667   (not (or  (nan? (car i))
668             (inf? (car i))
669             (nan? (cdr i))
670             (inf? (cdr i))
671             (> (car i) (cdr i)))))
672
673 (define-public (add-point interval p)
674   (cons (min (interval-start interval) p)
675         (max (interval-end interval) p)))
676
677 (define-public (reverse-interval iv)
678   (cons (cdr iv) (car iv)))
679
680 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
681 ;; coordinates
682
683 (define coord-x car)
684 (define coord-y cdr)
685
686 (define (coord-operation operator operand coordinate)
687   (if (pair? operand)
688     (cons (operator (coord-x operand) (coord-x coordinate))
689           (operator (coord-y operand) (coord-y coordinate)))
690     (cons (operator operand (coord-x coordinate))
691           (operator operand (coord-y coordinate)))))
692
693 (define (coord-apply function coordinate)
694   (if (pair? function)
695     (cons
696       ((coord-x function) (coord-x coordinate))
697       ((coord-y function) (coord-y coordinate)))
698     (cons
699       (function (coord-x coordinate))
700       (function (coord-y coordinate)))))
701
702 (define-public (coord-translate coordinate amount)
703   (coord-operation + amount coordinate))
704
705 (define-public (coord-scale coordinate amount)
706   (coord-operation * amount coordinate))
707
708 (define-public (coord-rotate coordinate degrees-in-radians)
709   (let*
710     ((coordinate
711       (cons
712         (exact->inexact (coord-x coordinate))
713         (exact->inexact (coord-y coordinate))))
714      (radius
715       (sqrt
716         (+ (* (coord-x coordinate) (coord-x coordinate))
717            (* (coord-y coordinate) (coord-y coordinate)))))
718     (angle (angle-0-2pi (atan (coord-y coordinate) (coord-x coordinate)))))
719    (cons
720      (* radius (cos (+ angle degrees-in-radians)))
721      (* radius (sin (+ angle degrees-in-radians))))))
722
723 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
724 ;; trig
725
726 (define-public PI (* 4 (atan 1)))
727
728 (define-public TWO-PI (* 2 PI))
729
730 (define-public PI-OVER-TWO (/ PI 2))
731
732 (define-public THREE-PI-OVER-TWO (* 3 PI-OVER-TWO))
733
734 (define-public (cyclic-base-value value cycle)
735   "Take @var{value} and modulo-maps it between 0 and base @var{cycle}."
736   (if (< value 0)
737       (cyclic-base-value (+ value cycle) cycle)
738       (if (>= value cycle)
739           (cyclic-base-value (- value cycle) cycle)
740           value)))
741
742 (define-public (angle-0-2pi angle)
743   "Take @var{angle} (in radians) and maps it between 0 and 2pi."
744   (cyclic-base-value angle TWO-PI))
745
746 (define-public (angle-0-360 angle)
747   "Take @var{angle} (in degrees) and maps it between 0 and 360 degrees."
748   (cyclic-base-value angle 360.0))
749
750 (define-public PI-OVER-180  (/ PI 180))
751
752 (define-public (degrees->radians angle-degrees)
753   "Convert the given angle from degrees to radians."
754   (* angle-degrees PI-OVER-180))
755
756 (define-public (ellipse-radius x-radius y-radius angle)
757   (/
758     (* x-radius y-radius)
759     (sqrt
760       (+ (* (expt y-radius 2)
761             (* (cos angle) (cos angle)))
762         (* (expt x-radius 2)
763            (* (sin angle) (sin angle)))))))
764
765 (define-public (polar->rectangular radius angle-in-degrees)
766   "Return polar coordinates (@var{radius}, @var{angle-in-degrees})
767 as rectangular coordinates @ode{(x-length . y-length)}."
768
769   (let ((complex (make-polar
770                     radius
771                     (degrees->radians angle-in-degrees))))
772      (cons
773        (real-part complex)
774        (imag-part complex))))
775
776 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
777 ;; string
778
779 (define-public (string-endswith s suffix)
780   (equal? suffix (substring s
781                             (max 0 (- (string-length s) (string-length suffix)))
782                             (string-length s))))
783
784 (define-public (string-startswith s prefix)
785   (equal? prefix (substring s 0 (min (string-length s) (string-length prefix)))))
786
787 (define-public (string-encode-integer i)
788   (cond
789    ((= i  0) "o")
790    ((< i 0)   (string-append "n" (string-encode-integer (- i))))
791    (else (string-append
792           (make-string 1 (integer->char (+ 65 (modulo i 26))))
793           (string-encode-integer (quotient i 26))))))
794
795 (define (number->octal-string x)
796   (let* ((n (inexact->exact x))
797          (n64 (quotient n 64))
798          (n8 (quotient (- n (* n64 64)) 8)))
799     (string-append
800      (number->string n64)
801      (number->string n8)
802      (number->string (remainder (- n (+ (* n64 64) (* n8 8))) 8)))))
803
804 (define-public (ly:inexact->string x radix)
805   (let ((n (inexact->exact x)))
806     (number->string n radix)))
807
808 (define-public (ly:number-pair->string c)
809   (string-append (ly:number->string (car c)) " "
810                  (ly:number->string (cdr c))))
811
812 (define-public (dir-basename file . rest)
813   "Strip suffixes in @var{rest}, but leave directory component for
814 @var{file}."
815   (define (inverse-basename x y) (basename y x))
816   (simple-format #f "~a/~a" (dirname file)
817                  (fold inverse-basename file rest)))
818
819 (define-public (write-me message x)
820   "Return @var{x}.  Display @var{message} and write @var{x}.
821 Handy for debugging, possibly turned off."
822   (display message) (write x) (newline) x)
823 ;;  x)
824
825 (define-public (stderr string . rest)
826   (apply format (cons (current-error-port) (cons string rest)))
827   (force-output (current-error-port)))
828
829 (define-public (debugf string . rest)
830   (if #f
831       (apply stderr (cons string rest))))
832
833 (define (index-cell cell dir)
834   (if (equal? dir 1)
835       (cdr cell)
836       (car cell)))
837
838 (define (cons-map f x)
839   "map F to contents of X"
840   (cons (f (car x)) (f (cdr x))))
841
842 (define-public (list-insert-separator lst between)
843   "Create new list, inserting @var{between} between elements of @var{lst}."
844   (define (conc x y )
845     (if (eq? y #f)
846         (list x)
847         (cons x  (cons between y))))
848   (fold-right conc #f lst))
849
850 (define-public (string-regexp-substitute a b str)
851   (regexp-substitute/global #f a str 'pre b 'post))
852
853 (define (regexp-split str regex)
854   (define matches '())
855   (define end-of-prev-match 0)
856   (define (notice match)
857
858     (set! matches (cons (substring (match:string match)
859                                    end-of-prev-match
860                                    (match:start match))
861                         matches))
862     (set! end-of-prev-match (match:end match)))
863
864   (regexp-substitute/global #f regex str notice 'post)
865
866   (if (< end-of-prev-match (string-length str))
867       (set!
868        matches
869        (cons (substring str end-of-prev-match (string-length str)) matches)))
870
871    (reverse matches))
872
873 ;;;;;;;;;;;;;;;;
874 ;; other
875
876 (define (sign x)
877   (if (= x 0)
878       0
879       (if (< x 0) -1 1)))
880
881 (define-public (binary-search start end getter target-val)
882   (_i "Find the index between @var{start} and @var{end} (an integer)
883 which produces the closest match to @var{target-val} if
884 applied to function @var{getter}.")
885   (if (<= end start)
886       start
887       (let* ((compare (quotient (+ start end) 2))
888              (get-val (getter compare)))
889         (cond
890          ((< target-val get-val)
891           (set! end (1- compare)))
892          ((< get-val target-val)
893           (set! start (1+ compare))))
894         (binary-search start end getter target-val))))
895
896 (define-public (car< a b)
897   (< (car a) (car b)))
898
899 (define-public (car<= a b)
900   (<= (car a) (car b)))
901
902 (define-public (symbol<? lst r)
903   (string<? (symbol->string lst) (symbol->string r)))
904
905 (define-public (symbol-key<? lst r)
906   (string<? (symbol->string (car lst)) (symbol->string (car r))))
907
908 (define-public (eval-carefully symbol module . default)
909   "Check whether all symbols in expr @var{symbol} are reachable
910 in module @var{module}.  In that case evaluate, otherwise
911 print a warning and set an optional @var{default}."
912   (let* ((unavailable? (lambda (sym)
913                          (not (module-defined? module sym))))
914          (sym-unavailable (if (pair? symbol)
915                               (filter
916                                 unavailable?
917                                 (filter symbol? (flatten-list symbol)))
918                               (if (unavailable? symbol)
919                                    #t
920                                    '()))))
921     (if (null? sym-unavailable)
922         (eval symbol module)
923         (let* ((def (and (pair? default) (car default))))
924           (ly:programming-error
925             "cannot evaluate ~S in module ~S, setting to ~S"
926             (object->string symbol)
927             (object->string module)
928             (object->string def))
929           def))))
930
931 ;;
932 ;; don't confuse users with #<procedure .. > syntax.
933 ;;
934 (define-public (scm->string val)
935   (if (and (procedure? val)
936            (symbol? (procedure-name val)))
937       (symbol->string (procedure-name val))
938       (string-append
939        (if (self-evaluating? val)
940            (if (string? val)
941                "\""
942                "")
943            "'")
944        (call-with-output-string (lambda (port) (display val port)))
945        (if (string? val)
946            "\""
947            ""))))
948
949 (define-public (!= lst r)
950   (not (= lst r)))
951
952 (define-public lily-unit->bigpoint-factor
953   (cond
954    ((equal? (ly:unit) "mm") (/ 72.0 25.4))
955    ((equal? (ly:unit) "pt") (/ 72.0 72.27))
956    (else (ly:error (_ "unknown unit: ~S") (ly:unit)))))
957
958 (define-public lily-unit->mm-factor
959   (* 25.4 (/ lily-unit->bigpoint-factor 72)))
960
961 ;;; FONT may be font smob, or pango font string...
962 (define-public (font-name-style font)
963   (if (string? font)
964       (string-downcase font)
965       (let* ((font-name (ly:font-name font))
966              (full-name (if font-name font-name (ly:font-file-name font))))
967           (string-downcase full-name))))
968
969 (define-public (modified-font-metric-font-scaling font)
970   (let* ((designsize (ly:font-design-size font))
971          (magnification (* (ly:font-magnification font)))
972          (scaling (* magnification designsize)))
973     (debugf "scaling:~S\n" scaling)
974     (debugf "magnification:~S\n" magnification)
975     (debugf "design:~S\n" designsize)
976     scaling))
977
978 (define-public (version-not-seen-message input-file-name)
979   (ly:warning-located
980     (ly:format "~a:1" input-file-name)
981     (_ "no \\version statement found, please add~afor future compatibility")
982     (format #f "\n\n\\version ~s\n\n" (lilypond-version))))
983
984 (define-public (old-relative-not-used-message input-file-name)
985   (ly:warning-located
986     (ly:format "~a:1" input-file-name)
987     (_ "old relative compatibility not used")))