]> git.donarmstrong.com Git - lilypond.git/blob - input/new/transposing-pitches-with-minimum-accidentals-smart-transpose.ly
1ff8444f55d09245840be2912d5a2addecc70331
[lilypond.git] / input / new / transposing-pitches-with-minimum-accidentals-smart-transpose.ly
1 \version "2.12.0"
2 \header {
3   lsrtags = "pitches"
4   texidoc = "This example uses some Scheme code to enforce enharmonic
5 modifications for notes in order to have the minimum number of
6 accidentals.  In this case, the following rules apply:
7
8 @itemize
9 @item
10 Double accidentals should be removed
11
12 @item
13 B sharp -> C
14
15 @item
16 E sharp -> F
17
18 @item
19 C flat -> B
20
21 @item
22 F flat -> E
23
24 @end itemize
25
26 In this manner, the most natural enharmonic notes are chosen.
27 "
28   doctitle = "Transposing music with minimum accidentals"
29 }
30
31 #(define  (naturalize-pitch p)
32   (let* ((o (ly:pitch-octave p))
33          (a (* 4 (ly:pitch-alteration p)))
34          ; alteration, a, in quarter tone steps,
35          ; for historical reasons
36          (n (ly:pitch-notename p)))
37     (cond
38      ((and (> a 1) (or (eq? n 6) (eq? n 2)))
39       (set! a (- a 2))
40       (set! n (+ n 1)))
41      ((and (< a -1) (or (eq? n 0) (eq? n 3)))
42       (set! a (+ a 2))
43       (set! n (- n 1))))
44     (cond
45      ((> a 2) (set! a (- a 4)) (set! n (+ n 1)))
46      ((< a -2) (set! a (+ a 4)) (set! n (- n 1))))
47     (if (< n 0) (begin (set! o (- o 1)) (set! n (+ n 7))))
48     (if (> n 6) (begin (set! o (+ o 1)) (set! n (- n 7))))
49     (ly:make-pitch o n (/ a 4))))
50
51 #(define (naturalize music)
52   (let* ((es (ly:music-property music 'elements))
53          (e (ly:music-property music 'element))
54          (p (ly:music-property music 'pitch)))
55     (if (pair? es)
56        (ly:music-set-property!
57          music 'elements
58          (map (lambda (x) (naturalize x)) es)))
59     (if (ly:music? e)
60        (ly:music-set-property!
61          music 'element
62          (naturalize e)))
63     (if (ly:pitch? p)
64        (begin
65          (set! p (naturalize-pitch p))
66          (ly:music-set-property! music 'pitch p)))
67     music))
68
69 naturalizeMusic =
70 #(define-music-function (parser location m)
71   (ly:music?)
72   (naturalize m))
73
74 music = \relative c' { c4 d e g }
75
76 \score {
77   \new Staff {
78     \transpose c ais { \music }
79     \naturalizeMusic \transpose c ais { \music }
80     \transpose c deses { \music }
81     \naturalizeMusic \transpose c deses { \music }
82   }
83   \layout { }
84 }