-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmusicexp.py
2753 lines (2238 loc) · 84.5 KB
/
musicexp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import inspect
import sys
import re
import math
import lilylib as ly
import warnings
import utilities
from pprint import pprint
from rational import Rational
# Store previously converted pitch for \relative conversion as a global state variable
previous_pitch = None
relative_pitches = False
whatOrnament = ""
ly_dur = None # stores lilypond durations
def escape_instrument_string(input_string):
retstring = input_string.replace("\"", "\\\"")
if re.match('.*[\r\n]+.*', retstring):
rx = re.compile(r'[\n\r]+')
strings = rx.split(retstring)
retstring = "\\markup { \\center-column { "
for s in strings:
retstring += "\\line {\"" + s + "\"} "
retstring += "} }"
else:
retstring = "\"" + retstring + "\""
return retstring
class Output_stack_element:
def __init__(self):
self.factor = Rational(1)
def copy(self):
o = Output_stack_element()
o.factor = self.factor
return o
class Output_printer(object):
"""
A class that takes care of formatting (eg.: indenting) a
Music expression as a .ly file.
"""
def __init__(self):
self._line = ''
self._indent = 4
self._nesting = 0
self._file = sys.stdout
self._line_len = 72
self._output_state_stack = [Output_stack_element()]
self._skipspace = False
self._last_duration = None
def set_file(self, file):
self._file = file
def dump_version(self, version):
self.print_verbatim('\\version "' + version + '"')
self.newline()
def get_indent(self):
return self._nesting * self._indent
def override(self):
last = self._output_state_stack[-1]
self._output_state_stack.append(last.copy())
def add_factor(self, factor):
self.override()
self._output_state_stack[-1].factor *= factor
def revert(self):
del self._output_state_stack[-1]
if not self._output_state_stack:
raise RuntimeError('empty stack')
def duration_factor(self):
return self._output_state_stack[-1].factor
def print_verbatim(self, str):
self._line += str
def unformatted_output(self, str):
# don't indent on \< and indent only once on <<
self._nesting += (str.count('<')
- str.count('\<') - str.count('<<')
+ str.count('{'))
self._nesting -= (str.count('>') - str.count('\>') - str.count('>>')
- str.count('->') - str.count('_>')
- str.count('^>')
+ str.count('}'))
self.print_verbatim(str)
def print_duration_string(self, str):
if self._last_duration == str:
return
self.unformatted_output(str)
def print_invisible_tied_to_note_style(self):
str = ("\\once\\hideNotes")
self.newline()
self.add_word(str)
self.newline()
def print_note_color(self, object, rgb=None):
if rgb:
str = ("\\once\\override %s.color = #(rgb-color %s %s %s)" %
(object, rgb[0], rgb[1], rgb[2]))
self.newline()
self.add_word(str)
self.newline()
else:
str = "\\revert %s.color" % object
self.newline()
self.add_word(str)
self.newline()
def add_word(self, str):
if (len(str) + 1 + len(self._line) > self._line_len):
self.newline()
self._skipspace = True
if not self._skipspace:
self._line += ' '
self.unformatted_output(str)
self._skipspace = False
def newline(self):
self._file.write(self._line + '\n')
self._line = ' ' * self._indent * self._nesting
self._skipspace = True
def skipspace(self):
self._skipspace = True
def __call__(self, arg):
self.dump(arg)
def dump(self, str):
if self._skipspace:
self._skipspace = False
self.unformatted_output(str)
else:
# Avoid splitting quoted strings (e.g. "1. Wie") when indenting.
words = utilities.split_string_and_preserve_doublequoted_substrings(
str)
for w in words:
self.add_word(w)
def close(self):
self.newline()
self._file.close()
self._file = None
class Duration:
def __init__(self):
self.duration_log = 0
self.dots = 0
self.factor = Rational(1)
def lisp_expression(self):
return '(ly:make-duration %d %d %d %d)' % (self.duration_log,
self.dots,
self.factor.numerator(),
self.factor.denominator())
def ly_expression(self, factor=None, scheme_mode=False):
global ly_dur # stores lilypond durations
if not factor:
factor = self.factor
if self.duration_log < 0:
if scheme_mode:
longer_dict = {-1: "breve", -2: "longa"}
else:
longer_dict = {-1: "\\breve", -2: "\\longa"}
dur_str = longer_dict.get(self.duration_log, "1")
else:
dur_str = '%d' % (1 << self.duration_log)
dur_str += '.' * self.dots
if factor != Rational(1, 1):
if factor.denominator() != 1:
dur_str += '*%d/%d' % (factor.numerator(),
factor.denominator())
else:
dur_str += '*%d' % factor.numerator()
if dur_str.isdigit():
ly_dur = int(dur_str)
# TODO: We need to deal with dotted notes and scaled durations
# otherwise ly_dur won't work in combination with tremolos.
return dur_str
def print_ly(self, outputter):
dur_str = self.ly_expression(self.factor / outputter.duration_factor())
outputter.print_duration_string(dur_str)
def __repr__(self):
return self.ly_expression()
def copy(self):
d = Duration()
d.dots = self.dots
d.duration_log = self.duration_log
d.factor = self.factor
return d
def get_length(self):
dot_fact = Rational((1 << (1 + self.dots)) - 1,
1 << self.dots)
log = abs(self.duration_log)
dur = 1 << log
if self.duration_log < 0:
base = Rational(dur)
else:
base = Rational(1, dur)
return base * dot_fact * self.factor
def set_create_midi(option):
"""
Implement the midi command line option '-m' and '--midi'.
If True, add midi-block to .ly file (see L{musicexp.Score.print_ly}).
@param option: Indicates whether the midi-block has to be added or not.
@type option: boolean
"""
global midi_option
midi_option = option
def get_create_midi():
"""
Return, if exists the state of the midi-option.
@return: The state of the midi-option.
@rtype: boolean
"""
try:
return midi_option
except:
return False
# implement the command line option '--transpose'
def set_transpose(option):
global transpose_option
transpose_option = option
def get_transpose(optType):
try:
if(optType == "string"):
return '\\transpose c %s' % transpose_option
elif(optType == "integer"):
p = generic_tone_to_pitch(transpose_option)
return p.semitones()
except:
if(optType == "string"):
return ""
elif(optType == "integer"):
return 0
# implement the command line option '--tab-clef'
def set_tab_clef(option):
global tab_clef_option
tab_clef_option = option
def get_tab_clef():
try:
return ("tab", tab_clef_option)[tab_clef_option == "tab" or tab_clef_option == "moderntab"]
except:
return "tab"
# definitions of the command line option '--string-numbers'
def set_string_numbers(option):
global string_numbers_option
string_numbers_option = option
def get_string_numbers():
try:
return ("t", string_numbers_option)[string_numbers_option == "t" or string_numbers_option == "f"]
except:
return "t"
def generic_tone_to_pitch(tone):
accidentals_dict = {
"": 0,
"es": -1,
"s": -1,
"eses": -2,
"ses": -2,
"is": 1,
"isis": 2
}
p = Pitch()
tone_ = tone.strip().lower()
p.octave = tone_.count("'") - tone_.count(",")
tone_ = tone_.replace(",", "").replace("'", "")
p.step = ((ord(tone_[0]) - ord('a') + 5) % 7)
p.alteration = accidentals_dict.get(tone_[1:], 0)
return p
# Implement the different note names for the various languages
def pitch_generic(pitch, notenames, accidentals):
str = notenames[pitch.step]
halftones = int(pitch.alteration)
if halftones < 0:
str += accidentals[0] * (-halftones)
elif pitch.alteration > 0:
str += accidentals[3] * (halftones)
# Handle remaining fraction to pitch.alteration (for microtones)
if (halftones != pitch.alteration):
if None in accidentals[1:3]:
ly.warning(
_("Language does not support microtones contained in the piece"))
else:
try:
str += {-0.5: accidentals[1], 0.5: accidentals[2]
}[pitch.alteration - halftones]
except KeyError:
ly.warning(
_("Language does not support microtones contained in the piece"))
return str
def pitch_general(pitch):
str = pitch_generic(pitch, ['c', 'd', 'e', 'f', 'g', 'a', 'b'], [
'es', 'eh', 'ih', 'is'])
if "h" in str: # no short forms for quarter tones
return str
return str.replace('aes', 'as').replace('ees', 'es')
def pitch_nederlands(pitch):
return pitch_general(pitch)
def pitch_catalan(pitch):
str = pitch_generic(pitch, ['do', 're', 'mi', 'fa', 'sol', 'la', 'si'], [
'b', 'qb', 'qd', 'd'])
return str.replace('bq', 'tq').replace('dq', 'tq').replace('bt', 'c').replace('dt', 'c')
def pitch_deutsch(pitch):
str = pitch_generic(pitch, ['c', 'd', 'e', 'f', 'g', 'a', 'h'], [
'es', 'eh', 'ih', 'is'])
if str == 'hes':
return 'b'
if str[0] == "a":
return str.replace('e', 'a').replace('aa', 'a')
return str.replace('ee', 'e')
def pitch_english(pitch):
str = pitch_generic(pitch, ['c', 'd', 'e', 'f', 'g', 'a', 'b'], [
'f', 'qf', 'qs', 's'])
return str[0] + str[1:].replace('fq', 'tq').replace('sq', 'tq')
def pitch_espanol(pitch):
str = pitch_generic(pitch, ['do', 're', 'mi', 'fa', 'sol', 'la', 'si'], [
'b', 'cb', 'cs', 's'])
return str.replace('bc', 'tc').replace('sc', 'tc')
def pitch_francais(pitch):
str = pitch_generic(pitch, ['do', 'ré', 'mi', 'fa', 'sol', 'la', 'si'], [
'b', 'sb', 'sd', 'd'])
return str
def pitch_italiano(pitch):
str = pitch_generic(pitch, ['do', 're', 'mi', 'fa', 'sol', 'la', 'si'], [
'b', 'sb', 'sd', 'd'])
return str
def pitch_norsk(pitch):
str = pitch_generic(pitch, ['c', 'd', 'e', 'f', 'g', 'a', 'h'], [
'ess', 'eh', 'ih', 'iss'])
return str.replace('hess', 'b')
def pitch_portugues(pitch):
str = pitch_generic(pitch, ['do', 're', 'mi', 'fa', 'sol', 'la', 'si'], [
'b', 'bqt', 'sqt', 's'])
return str.replace('bbq', 'btq').replace('ssq', 'stq')
def pitch_suomi(pitch):
str = pitch_generic(pitch, ['c', 'd', 'e', 'f', 'g', 'a', 'h'], [
'es', 'eh', 'ih', 'is'])
if str == 'hes':
return 'b'
return str.replace('aes', 'as').replace('ees', 'es')
def pitch_svenska(pitch):
str = pitch_generic(pitch, ['c', 'd', 'e', 'f', 'g', 'a', 'h'], [
'ess', 'eh', 'ih', 'iss'])
if str == 'hess':
return 'b'
return str.replace('aes', 'as').replace('ees', 'es')
def pitch_vlaams(pitch):
str = pitch_generic(pitch, ['do', 're', 'mi', 'fa', 'sol', 'la', 'si'], [
'b', 'hb', 'hk', 'k'])
return str
def set_pitch_language(language):
global pitch_generating_function
function_dict = {
"nederlands": pitch_nederlands,
"català": pitch_catalan,
"deutsch": pitch_deutsch,
"english": pitch_english,
"español": pitch_espanol,
"français": pitch_francais,
"italiano": pitch_italiano,
"norsk": pitch_norsk,
"português": pitch_portugues,
"suomi": pitch_suomi,
"svenska": pitch_svenska,
"vlaams": pitch_vlaams}
pitch_generating_function = function_dict.get(language, pitch_general)
# global variable to hold the formatting function.
pitch_generating_function = pitch_general
class Pitch:
def __init__(self):
self.alteration = 0
self.step = 0
self.octave = 0
self._force_absolute_pitch = False
def __repr__(self):
return self.ly_expression()
def transposed(self, interval):
c = self.copy()
c.alteration += interval.alteration
c.step += interval.step
c.octave += interval.octave
c.normalize()
target_st = self.semitones() + interval.semitones()
c.alteration += target_st - c.semitones()
return c
def normalize(c):
while c.step < 0:
c.step += 7
c.octave -= 1
c.octave += c.step // 7
c.step = c.step % 7
def lisp_expression(self):
return '(ly:make-pitch %d %d %d)' % (self.octave,
self.step,
self.alteration)
def copy(self):
p = Pitch()
p.alteration = self.alteration
p.step = self.step
p.octave = self.octave
p._force_absolute_pitch = self._force_absolute_pitch
return p
def steps(self):
return self.step + self.octave * 7
def semitones(self):
return self.octave * 12 + [0, 2, 4, 5, 7, 9, 11][self.step] + self.alteration
def normalize_alteration(c):
if(c.alteration < 0 and [True, False, False, True, False, False, False][c.step]):
c.alteration += 1
c.step -= 1
elif(c.alteration > 0 and [False, False, True, False, False, False, True][c.step]):
c.alteration -= 1
c.step += 1
c.normalize()
def add_semitones(self, number):
semi = number + self.alteration
self.alteration = 0
if(semi == 0):
return
sign = (1, -1)[semi < 0]
prev = self.semitones()
while abs((prev + semi) - self.semitones()) > 1:
self.step += sign
self.normalize()
self.alteration += (prev + semi) - self.semitones()
self.normalize_alteration()
def ly_step_expression(self):
return pitch_generating_function(self)
def absolute_pitch(self):
if self.octave >= 0:
return "'" * (self.octave + 1)
elif self.octave < -1:
return "," * (-self.octave - 1)
else:
return ''
def relative_pitch(self):
global previous_pitch
if not previous_pitch:
previous_pitch = self
return self.absolute_pitch()
previous_pitch_steps = previous_pitch.octave * 7 + previous_pitch.step
this_pitch_steps = self.octave * 7 + self.step
pitch_diff = (this_pitch_steps - previous_pitch_steps)
previous_pitch = self
if pitch_diff > 3:
return "'" * ((pitch_diff + 3) // 7)
elif pitch_diff < -3:
return "," * ((-pitch_diff + 3) // 7)
else:
return ""
def ly_expression(self):
str = self.ly_step_expression()
if relative_pitches and not self._force_absolute_pitch:
str += self.relative_pitch()
else:
str += self.absolute_pitch()
return str
def print_ly(self, outputter):
outputter(self.ly_expression())
class Music:
def __init__(self):
self.parent = None
self.start = Rational(0)
self.comment = ''
self.identifier = None
def get_length(self):
return Rational(0)
def get_properties(self):
return ''
def has_children(self):
return False
def get_index(self):
if self.parent:
return self.parent.elements.index(self)
else:
return None
def name(self):
return self.__class__.__name__
def lisp_expression(self):
name = self.name()
props = self.get_properties()
return "(make-music '%s %s)" % (name, props)
def set_start(self, start):
self.start = start
def find_first(self, predicate):
if predicate(self):
return self
return None
def print_comment(self, printer, text=None):
if not text:
text = self.comment
if not text:
return
if text == '\n':
printer.newline()
return
lines = text.split('\n')
for l in lines:
if l:
printer.unformatted_output('% ' + l)
printer.newline()
def print_with_identifier(self, printer):
if self.identifier:
printer("\\%s" % self.identifier)
else:
self.print_ly(printer)
def print_ly(self, printer):
printer(self.ly_expression())
class MusicWrapper (Music):
def __init__(self):
Music.__init__(self)
self.element = None
def print_ly(self, func):
self.element.print_ly(func)
class ModeChangingMusicWrapper (MusicWrapper):
def __init__(self):
MusicWrapper.__init__(self)
self.mode = 'notemode'
def print_ly(self, func):
func('\\%s' % self.mode)
MusicWrapper.print_ly(self, func)
class RelativeMusic (MusicWrapper):
def __init__(self):
MusicWrapper.__init__(self)
self.basepitch = None
def print_ly(self, func):
global previous_pitch
global relative_pitches
prev_relative_pitches = relative_pitches
relative_pitches = True
previous_pitch = self.basepitch
if not previous_pitch:
previous_pitch = Pitch()
func('\\relative %s%s' % (pitch_generating_function(previous_pitch),
previous_pitch.absolute_pitch()))
MusicWrapper.print_ly(self, func)
relative_pitches = prev_relative_pitches
class TimeScaledMusic (MusicWrapper):
def __init__(self):
MusicWrapper.__init__(self)
self.numerator = 1
self.denominator = 1
self.display_number = "actual" # valid values "actual" | "both" | None
# Display the basic note length for the tuplet:
self.display_type = None # value values "actual" | "both" | None
self.display_bracket = "bracket" # valid values "bracket" | "curved" | None
self.actual_type = None # The actually played unit of the scaling
self.normal_type = None # The basic unit of the scaling
self.display_numerator = None
self.display_denominator = None
def print_ly(self, func):
if self.display_bracket == None:
func("\\once \\omit TupletBracket")
func.newline()
elif self.display_bracket == "curved":
ly.warning(
_("Tuplet brackets of curved shape are not correctly implemented"))
func("\\once \\override TupletBracket.stencil = #ly:slur::print")
func.newline()
base_number_function = {None: "#f",
"actual": "tuplet-number::calc-denominator-text",
"both": "tuplet-number::calc-fraction-text"}.get(self.display_number, None)
# If we have non-standard numerator/denominator, use our custom function
if self.display_number == "actual" and self.display_denominator:
base_number_function = "(tuplet-number::non-default-tuplet-denominator-text %s)" % self.display_denominator
elif self.display_number == "both" and (self.display_denominator or self.display_numerator):
if self.display_numerator:
num = self.display_numerator
else:
num = "#f"
if self.display_denominator:
den = self.display_denominator
else:
den = "#f"
base_number_function = "(tuplet-number::non-default-tuplet-fraction-text %s %s)" % (
den, num)
if self.display_type == "actual" and self.normal_type:
base_duration = self.normal_type.lisp_expression()
func("\\once \\override TupletNumber.text = #(tuplet-number::append-note-wrapper %s %s)" %
(base_number_function, base_duration))
func.newline()
elif self.display_type == "both": # TODO: Implement this using actual_type and normal_type!
if self.display_number == None:
func("\\once \\omit TupletNumber")
func.newline()
elif self.display_number == "both":
den_duration = self.normal_type.lisp_expression()
# If we don't have an actual type set, use the normal duration!
if self.actual_type:
num_duration = self.actual_type.lisp_expression()
else:
num_duration = den_duration
if (self.display_denominator or self.display_numerator):
func("\\once \\override TupletNumber.text = #(tuplet-number::non-default-fraction-with-notes %s %s %s %s)" %
(self.display_denominator, den_duration,
self.display_numerator, num_duration))
func.newline()
else:
func("\\once \\override TupletNumber.text = #(tuplet-number::fraction-with-notes %s %s)" %
(den_duration, num_duration))
func.newline()
else:
if self.display_number == None:
func("\\once \\omit TupletNumber")
func.newline()
elif self.display_number == "both":
func("\\once \\override TupletNumber.text = #%s" %
base_number_function)
func.newline()
func('\\times %d/%d ' %
(self.numerator, self.denominator))
func.add_factor(Rational(self.numerator, self.denominator))
MusicWrapper.print_ly(self, func)
func.revert()
class NestedMusic(Music):
def __init__(self):
Music.__init__(self)
self.elements = []
def append(self, what):
if what:
self.elements.append(what)
def has_children(self):
return self.elements
def insert_around(self, succ, elt, dir):
assert elt.parent == None
assert succ == None or succ in self.elements
idx = 0
if succ:
idx = self.elements.index(succ)
if dir > 0:
idx += 1
else:
if dir < 0:
idx = 0
elif dir > 0:
idx = len(self.elements)
self.elements.insert(idx, elt)
elt.parent = self
def get_properties(self):
return ("'elements (list %s)"
% " ".join([x.lisp_expression() for x in self.elements]))
def get_subset_properties(self, predicate):
return ("'elements (list %s)"
% " ".join([x.lisp_expression() for x in list(filter(predicate, self.elements))]))
def get_neighbor(self, music, dir):
assert music.parent == self
idx = self.elements.index(music)
idx += dir
idx = min(idx, len(self.elements) - 1)
idx = max(idx, 0)
return self.elements[idx]
def delete_element(self, element):
assert element in self.elements
self.elements.remove(element)
element.parent = None
def set_start(self, start):
self.start = start
for e in self.elements:
e.set_start(start)
def find_first(self, predicate):
r = Music.find_first(self, predicate)
if r:
return r
for e in self.elements:
r = e.find_first(predicate)
if r:
return r
return None
class SequentialMusic (NestedMusic):
def get_last_event_chord(self):
value = None
at = len(self.elements) - 1
while (at >= 0 and
not isinstance(self.elements[at], ChordEvent) and
not isinstance(self.elements[at], BarLine)):
at -= 1
if (at >= 0 and isinstance(self.elements[at], ChordEvent)):
value = self.elements[at]
return value
def print_ly(self, printer, newline=True):
printer('{')
if self.comment:
self.print_comment(printer)
if newline:
printer.newline()
for e in self.elements:
e.print_ly(printer)
printer('}')
if newline:
printer.newline()
def lisp_sub_expression(self, pred):
name = self.name()
props = self.get_subset_properties(pred)
return "(make-music '%s %s)" % (name, props)
def set_start(self, start):
for e in self.elements:
e.set_start(start)
start += e.get_length()
class RepeatedMusic:
def __init__(self):
self.repeat_type = "volta"
self.repeat_count = 2
self.endings = []
self.music = None
def set_music(self, music):
if isinstance(music, Music):
self.music = music
elif isinstance(music, list):
self.music = SequentialMusic()
self.music.elements = music
else:
ly.warning(_("unable to set the music %(music)s for the repeat %(repeat)s") %
{'music': music, 'repeat': self})
def add_ending(self, music):
self.endings.append(music)
def print_ly(self, printer):
printer.dump('\\repeat %s %s' % (self.repeat_type, self.repeat_count))
if self.music:
self.music.print_ly(printer)
else:
ly.warning(_("encountered repeat without body"))
printer.dump('{}')
if self.endings:
printer.dump('\\alternative {')
for e in self.endings:
e.print_ly(printer)
printer.dump('}')
class Lyrics:
def __init__(self):
self.lyrics_syllables = []
def print_ly(self, printer):
printer.dump(self.ly_expression())
printer.newline()
printer.dump('}')
printer.newline()
def ly_expression(self):
lstr = "\lyricmode {\set ignoreMelismata = ##t"
for l in self.lyrics_syllables:
lstr += l
# lstr += "\n}"
return lstr
class Header:
def __init__(self):
self.header_fields = {}
def set_field(self, field, value):
self.header_fields[field] = value
def format_header_strings(self, key, value, printer):
printer.dump(key + ' = ')
# If a header item contains a line break, it is segmented. The
# substrings are formatted with the help of \markup, using
# \column and \line. An exception, however, are texidoc items,
# which should not contain LilyPond formatting commands.
if (key != 'texidoc') and ('\n' in value):
value = value.replace('"', '')
printer.dump(r'\markup \column {')
substrings = value.split('\n')
for s in substrings:
printer.newline()
printer.dump(r'\line { "' + s + '"}')
printer.dump('}')
printer.newline()
else:
printer.dump(value)
printer.newline()
def print_ly(self, printer):
printer.dump("\header {")
printer.newline()
for (k, v) in list(self.header_fields.items()):
if v:
self.format_header_strings(k, v, printer)
# printer.newline()
printer.dump("}")
printer.newline()
printer.newline()
class Paper:
def __init__(self):
self.global_staff_size = -1
# page size
self.page_width = -1
self.page_height = -1
# page margins
self.top_margin = -1
self.bottom_margin = -1
self.left_margin = -1
self.right_margin = -1
self.system_left_margin = -1
self.system_right_margin = -1
self.system_distance = -1
self.top_system_distance = -1
self.indent = 0
self.short_indent = 0
self.instrument_names = []
def print_length_field(self, printer, field, value):
if value >= 0:
printer.dump("%s = %s\\cm" % (field, value))
printer.newline()
def get_longest_instrument_name(self):
result = ''
for name in self.instrument_names:
lines = name.split('\n')
for line in lines:
if len(line) > len(result):
result = line
return result
def print_ly(self, printer):
if self.global_staff_size > 0:
printer.dump('#(set-global-staff-size %s)' %
self.global_staff_size)
printer.newline()
printer.dump('\\paper {')
printer.newline()
printer.newline()
self.print_length_field(printer, "paper-width", self.page_width)
self.print_length_field(printer, "paper-height", self.page_height)
self.print_length_field(printer, "top-margin", self.top_margin)
self.print_length_field(printer, "bottom-margin", self.bottom_margin)
self.print_length_field(printer, "left-margin", self.left_margin)