]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/snippets/transposing-pitches-with-minimum-accidentals-smart-transpose.ly
df6ce9d6c098260ec418a76c1ce22337da923153
[lilypond.git] / Documentation / snippets / transposing-pitches-with-minimum-accidentals-smart-transpose.ly
1 %% DO NOT EDIT this file manually; it is automatically
2 %% generated from LSR http://lsr.di.unimi.it
3 %% Make any changes in LSR itself, or in Documentation/snippets/new/ ,
4 %% and then run scripts/auxiliar/makelsr.py
5 %%
6 %% This file is in the public domain.
7 \version "2.19.22"
8
9 \header {
10   lsrtags = "pitches, scheme-language, workaround"
11
12   texidoc = "
13 This example uses some Scheme code to enforce enharmonic modifications
14 for notes in order to have the minimum number of accidentals.  In this
15 case, the following rules apply:
16
17 Double accidentals should be removed
18
19
20 B sharp -> C
21
22
23 E sharp -> F
24
25
26 C flat -> B
27
28
29 F flat -> E
30
31
32 In this manner, the most natural enharmonic notes are chosen.
33
34 "
35   doctitle = "Transposing pitches with minimum accidentals (\"Smart\" transpose)"
36 } % begin verbatim
37
38 #(define (naturalize-pitch p)
39    (let ((o (ly:pitch-octave p))
40          (a (* 4 (ly:pitch-alteration p)))
41          ;; alteration, a, in quarter tone steps,
42          ;; for historical reasons
43          (n (ly:pitch-notename p)))
44      (cond
45       ((and (> a 1) (or (eq? n 6) (eq? n 2)))
46        (set! a (- a 2))
47        (set! n (+ n 1)))
48       ((and (< a -1) (or (eq? n 0) (eq? n 3)))
49        (set! a (+ a 2))
50        (set! n (- n 1))))
51      (cond
52       ((> a 2) (set! a (- a 4)) (set! n (+ n 1)))
53       ((< a -2) (set! a (+ a 4)) (set! n (- n 1))))
54      (if (< n 0) (begin (set! o (- o 1)) (set! n (+ n 7))))
55      (if (> n 6) (begin (set! o (+ o 1)) (set! n (- n 7))))
56      (ly:make-pitch o n (/ a 4))))
57
58 #(define (naturalize music)
59    (let ((es (ly:music-property music 'elements))
60          (e (ly:music-property music 'element))
61          (p (ly:music-property music 'pitch)))
62      (if (pair? es)
63          (ly:music-set-property!
64           music 'elements
65           (map naturalize es)))
66      (if (ly:music? e)
67          (ly:music-set-property!
68           music 'element
69           (naturalize e)))
70      (if (ly:pitch? p)
71          (begin
72            (set! p (naturalize-pitch p))
73            (ly:music-set-property! music 'pitch p)))
74      music))
75
76 naturalizeMusic =
77 #(define-music-function (m)
78    (ly:music?)
79    (naturalize m))
80
81 music = \relative c' { c4 d e g }
82
83 \score {
84   \new Staff {
85     \transpose c ais { \music }
86     \naturalizeMusic \transpose c ais { \music }
87     \transpose c deses { \music }
88     \naturalizeMusic \transpose c deses { \music }
89   }
90   \layout { }
91 }