* stepmake/GNUmakefile.in: remove nested stepmake packaging stuff.
[lilypond.git] / scripts / abc2ly.py
blobbde1e8cfe553a89982ab2ad3cc1af47ed1ceca09
1 #!@PYTHON@
3 # once upon a rainy monday afternoon.
5 # ...
7 # (not finished.)
8 # ABC standard v1.6: http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt
10 # Enhancements (Roy R. Rankin)
12 # Header section moved to top of lilypond file
13 # handle treble, treble-8, alto, and bass clef
14 # Handle voices (V: headers) with clef and part names, multiple voices
15 # Handle w: lyrics with multiple verses
16 # Handle key mode names for minor, major, phrygian, ionian, locrian, aeolian,
17 # mixolydian, lydian, dorian
18 # Handle part names from V: header
19 # Tuplets handling fixed up
20 # Lines starting with |: not discarded as header lines
21 # Multiple T: and C: header entries handled
22 # Accidental maintained until next bar check
23 # Silent rests supported
24 # articulations fermata, upbow, downbow, ltoe, accent, tenuto supported
25 # Chord strings([-^]"string") can contain a '#'
26 # Header fields enclosed by [] in notes string processed
27 # W: words output after tune as abc2ps does it (they failed before)
29 # Enhancements (Laura Conrad)
31 # Barring now preserved between ABC and lilypond
32 # the default placement for text in abc is above the staff.
33 # %%LY now supported.
34 # \breve and \longa supported.
35 # M:none doesn't crash lily.
37 # Limitations
39 # Multiple tunes in single file not supported
40 # Blank T: header lines should write score and open a new score
41 # Not all header fields supported
42 # ABC line breaks are ignored
43 # Block comments generate error and are ignored
44 # Postscript commands are ignored
45 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
46 # %%LY slyrics can't be directly before a w: line.
47 # ???
51 #TODO:
53 # Convert to new chord styles.
55 # UNDEF -> None
59 program_name = 'abc2ly'
60 version = '@TOPLEVEL_VERSION@'
61 if version == '@' + 'TOPLEVEL_VERSION' + '@':
62 version = '(unknown version)' # uGUHGUHGHGUGH
64 import __main__
65 import getopt
66 import sys
67 import re
68 import string
69 import os
72 UNDEF = 255
73 state = UNDEF
74 strict = 0
75 voice_idx_dict = {}
76 header = {}
77 header['footnotes'] = ''
78 lyrics = []
79 slyrics = []
80 voices = []
81 state_list = []
82 repeat_state = [0] * 8
83 current_voice_idx = -1
84 current_lyric_idx = -1
85 lyric_idx = -1
86 part_names = 0
87 default_len = 8
88 length_specified = 0
89 nobarlines = 0
90 global_key = [0] * 7 # UGH
91 names = ["One", "Two", "Three"]
92 DIGITS='0123456789'
93 alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
94 HSPACE=' \t'
95 midi_specs = ''
98 def error (msg):
99 sys.stderr.write (msg)
100 if strict:
101 sys.exit (1)
104 def check_clef(s):
105 if not s:
106 return ''
107 if re.match('-8va', s) or re.match('treble8', s):
108 # treble8 is used by abctab2ps; -8va is used by barfly,
109 # and by my patch to abc2ps. If there's ever a standard
110 # about this we'll support that.
111 s = s[4:]
112 state.base_octave = -1
113 voices_append("\\clef \"G_8\"\n")
114 elif re.match('^treble', s):
115 s = s[6:]
116 if re.match ('^-8', s):
117 s = s[2:]
118 state.base_octave = -2
119 voices_append("\\clef \"G_8\"\n")
120 else:
121 state.base_octave = 0
122 voices_append("\\clef treble\n")
123 elif re.match('^alto', s):
124 s = s[4:]
125 state.base_octave = -1
126 voices_append ("\\clef alto\n" )
127 elif re.match('^bass',s ):
128 s = s[4:]
129 state.base_octave = -2
130 voices_append ("\\clef bass\n" )
131 return s
133 def select_voice (name, rol):
134 if not voice_idx_dict.has_key (name):
135 state_list.append(Parser_state())
136 voices.append ('')
137 slyrics.append ([])
138 voice_idx_dict[name] = len (voices) -1
139 __main__.current_voice_idx = voice_idx_dict[name]
140 __main__.state = state_list[current_voice_idx]
141 while rol != '':
142 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
143 if m:
144 keyword = m.group(1)
145 rol = m.group (2)
146 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
147 if a:
148 value = a.group (1)
149 rol = a.group ( 2)
150 if keyword == 'clef':
151 check_clef(value)
152 elif keyword == "name":
153 value = re.sub ('\\\\','\\\\\\\\', value)
154 voices_append ("\\property Staff.instrument = %s\n" % value )
155 __main__.part_names = 1
156 elif keyword == "sname" or keyword == "snm":
157 voices_append ("\\property Staff.instr = %s\n" % value )
159 else:
160 break
162 return
165 def dump_header (outf,hdr):
166 outf.write ('\\header {\n')
167 ks = hdr.keys ()
168 ks.sort ()
169 for k in ks:
170 hdr[k] = re.sub('"', '\\"', hdr[k])
171 outf.write ('\t%s = "%s"\n'% (k,hdr[k]))
172 outf.write ('}')
174 def dump_lyrics (outf):
175 if (len(lyrics)):
176 outf.write("\n\\score\n{\n \\context Lyrics\n <<\n")
177 for i in range (len (lyrics)):
178 outf.write ( lyrics [i])
179 outf.write ("\n")
180 outf.write(" >>\n \\paper{}\n}\n")
182 def dump_default_bar (outf):
184 Nowadays abc2ly outputs explicits barlines (?)
186 outf.write ("\n\\property Score.defaultBarType=\"empty\"\n")
189 def dump_slyrics (outf):
190 ks = voice_idx_dict.keys()
191 ks.sort ()
192 for k in ks:
193 if re.match('[1-9]', k):
194 m = alphabet[string.atoi(k)]
195 else:
196 m = k
197 for i in range (len(slyrics[voice_idx_dict[k]])):
198 l=alphabet[i]
199 outf.write ("\nwords%sV%s = \\lyrics {" % (m, l))
200 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
201 outf.write ("\n}")
203 def dump_voices (outf):
204 global doing_alternative, in_repeat
205 ks = voice_idx_dict.keys()
206 ks.sort ()
207 for k in ks:
208 if re.match ('[1-9]', k):
209 m = alphabet[string.atoi(k)]
210 else:
211 m = k
212 outf.write ("\nvoice%s = \\notes {" % m)
213 dump_default_bar(outf)
214 if repeat_state[voice_idx_dict[k]]:
215 outf.write("\n\\repeat volta 2 {")
216 outf.write ("\n" + voices [voice_idx_dict[k]])
217 if not using_old:
218 if doing_alternative[voice_idx_dict[k]]:
219 outf.write("}")
220 if in_repeat[voice_idx_dict[k]]:
221 outf.write("}")
222 outf.write ("\n}")
224 def try_parse_q(a):
225 global midi_specs
226 #assume that Q takes the form "Q:1/4=120"
227 #There are other possibilities, but they are deprecated
228 if string.count(a, '/') == 1:
229 array=string.split(a,'/')
230 numerator=array[0]
231 if numerator != 1:
232 sys.stderr.write("abc2ly: Warning, unable to translate a Q specification with a numerator of %s: %s\n" % (numerator, a))
233 array2=string.split(array[1],'=')
234 denominator=array2[0]
235 perminute=array2[1]
236 duration=str(string.atoi(denominator)/string.atoi(numerator))
237 midi_specs=string.join(["\\tempo", duration, "=", perminute])
238 else:
239 sys.stderr.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a)
241 def dump_score (outf):
242 outf.write (r"""\score{
243 \notes <<
244 """)
246 ks = voice_idx_dict.keys ();
247 ks.sort ()
248 for k in ks:
249 if re.match('[1-9]', k):
250 m = alphabet[string.atoi(k)]
251 else:
252 m = k
253 if k == 'default' and len (voice_idx_dict) > 1:
254 break
255 if len ( slyrics [voice_idx_dict[k]] ):
256 outf.write ("\n \\addlyrics")
257 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
258 if k != 'default':
259 outf.write ("\t \\voicedefault\n")
260 outf.write ("\t \\voice%s " % m)
261 outf.write ("\n\t}\n")
262 if len ( slyrics [voice_idx_dict[k]] ):
263 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<<\t" % k)
264 if re.match('[1-9]',k):
265 m = alphabet[string.atoi(k)]
266 else:
267 m = k
268 for i in range (len(slyrics[voice_idx_dict[k]])):
269 l=alphabet[i]
270 outf.write("\n\t { \\words%sV%s }" % ( m, l) )
271 outf.write ( "\n\t>>\n" )
272 outf.write ("\n >>")
273 outf.write ("\n\t\\paper {\n")
274 if part_names:
275 outf.write ("\t \\translator \n\t {\n")
276 outf.write ("\t\t\\StaffContext\n")
277 # outf.write ("\t\t\\consists Staff_margin_engraver\n")
278 outf.write ("\t }\n")
279 outf.write ("\t}\n\t\\midi {%s}\n}\n" % midi_specs)
283 def set_default_length (s):
284 global length_specified
285 m = re.search ('1/([0-9]+)', s)
286 if m:
287 __main__.default_len = string.atoi ( m.group (1))
288 length_specified = 1
290 def set_default_len_from_time_sig (s):
291 m = re.search ('([0-9]+)/([0-9]+)', s)
292 if m:
293 n = string.atoi (m.group (1))
294 d = string.atoi (m.group (2))
295 if (n * 1.0 )/(d * 1.0) < 0.75:
296 __main__.default_len = 16
297 else:
298 __main__.default_len = 8
300 def gulp_file(f):
301 try:
302 i = open(f)
303 i.seek (0, 2)
304 n = i.tell ()
305 i.seek (0,0)
306 except:
307 sys.stderr.write ("can't open file: `%s'\n" % f)
308 return ''
309 s = i.read (n)
310 if len (s) <= 0:
311 sys.stderr.write ("gulped empty file: `%s'\n" % f)
312 i.close ()
313 return s
316 # pitch manipulation. Tuples are (name, alteration).
317 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
318 # pitch in semitones.
319 def semitone_pitch (tup):
320 p =0
322 t = tup[0]
323 p = p + 12 * (t / 7)
324 t = t % 7
326 if t > 2:
327 p = p- 1
329 p = p + t* 2 + tup[1]
330 return p
332 def fifth_above_pitch (tup):
333 (n, a) = (tup[0] + 4, tup[1])
335 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
336 a = a + difference
338 return (n,a)
340 def sharp_keys ():
341 p = (0,0)
342 l = []
343 k = 0
344 while 1:
345 l.append (p)
346 (t,a) = fifth_above_pitch (p)
347 if semitone_pitch((t,a)) % 12 == 0:
348 break
350 p = (t % 7, a)
351 return l
353 def flat_keys ():
354 p = (0,0)
355 l = []
356 k = 0
357 while 1:
358 l.append (p)
359 (t,a) = quart_above_pitch (p)
360 if semitone_pitch((t,a)) % 12 == 0:
361 break
363 p = (t % 7, a)
364 return l
366 def quart_above_pitch (tup):
367 (n, a) = (tup[0] + 3, tup[1])
369 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
370 a = a + difference
372 return (n,a)
374 key_lookup = { # abc to lilypond key mode names
375 'm' : 'minor',
376 'min' : 'minor',
377 'maj' : 'major',
378 'major' : 'major',
379 'phr' : 'phrygian',
380 'ion' : 'ionian',
381 'loc' : 'locrian',
382 'aeo' : 'aeolian',
383 'mix' : 'mixolydian',
384 'mixolydian' : 'mixolydian',
385 'lyd' : 'lydian',
386 'dor' : 'dorian',
387 'dorian' : 'dorian'
390 def lily_key (k):
391 k = string.lower (k)
392 key = k[0]
393 k = k[1:]
394 if k and k[0] == '#':
395 key = key + 'is'
396 k = k[1:]
397 elif k and k[0] == 'b':
398 key = key + 'es'
399 k = k[1:]
400 if not k:
401 return '%s \\major' % key
403 type = k[0:3]
404 if key_lookup.has_key(type):
405 return("%s \\%s" % ( key, key_lookup[type]))
406 sys.stderr.write("Unknown key type `%s' ignored\n" % type)
407 return key
409 def shift_key (note, acc , shift):
410 s = semitone_pitch((note, acc))
411 s = (s + shift + 12) % 12
412 if s <= 4:
413 n = s / 2
414 a = s % 2
415 else:
416 n = (s + 1) / 2
417 a = (s + 1) % 2
418 if a:
419 n = n + 1
420 a = -1
421 return (n,a)
423 key_shift = { # semitone shifts for key mode names
424 'm' : 3,
425 'min' : 3,
426 'minor' : 3,
427 'maj' : 0,
428 'major' : 0,
429 'phr' : -4,
430 'phrygian' : -4,
431 'ion' : 0,
432 'ionian' : 0,
433 'loc' : 1,
434 'locrian' : 1,
435 'aeo' : 3,
436 'aeolian' : 3,
437 'mix' : 5,
438 'mixolydian' : 5,
439 'lyd' : -5,
440 'lydian' : -5,
441 'dor' : -2,
442 'dorian' : -2
444 def compute_key (k):
445 k = string.lower (k)
446 intkey = (ord (k[0]) - ord('a') + 5) % 7
447 intkeyacc =0
448 k = k[1:]
450 if k and k[0] == 'b':
451 intkeyacc = -1
452 k = k[1:]
453 elif k and k[0] == '#':
454 intkeyacc = 1
455 k = k[1:]
456 k = k[0:3]
457 if k and key_shift.has_key(k):
458 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
459 keytup = (intkey, intkeyacc)
461 sharp_key_seq = sharp_keys ()
462 flat_key_seq = flat_keys ()
464 accseq = None
465 accsign = 0
466 if keytup in sharp_key_seq:
467 accsign = 1
468 key_count = sharp_key_seq.index (keytup)
469 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
471 elif keytup in flat_key_seq:
472 accsign = -1
473 key_count = flat_key_seq.index (keytup)
474 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
475 else:
476 error ("Huh?")
477 raise "Huh"
479 key_table = [0] * 7
480 for a in accseq:
481 key_table[a] = key_table[a] + accsign
483 return key_table
485 tup_lookup = {
486 '2' : '3/2',
487 '3' : '2/3',
488 '4' : '4/3',
489 '5' : '4/5',
490 '6' : '4/6',
491 '7' : '6/7',
492 '9' : '8/9',
496 def try_parse_tuplet_begin (str, state):
497 if re.match ('\([2-9]', str):
498 dig = str[1]
499 str = str[2:]
500 prev_tuplet_state = state.parsing_tuplet
501 state.parsing_tuplet = string.atoi (dig[0])
502 if prev_tuplet_state:
503 voices_append ("}")
504 voices_append ("\\times %s {" % tup_lookup[dig])
505 return str
507 def try_parse_group_end (str, state):
508 if str and str[0] in HSPACE:
509 str = str[1:]
510 return str
512 def header_append (key, a):
513 s = ''
514 if header.has_key (key):
515 s = header[key] + "\n"
516 header [key] = s + a
518 def wordwrap(a, v):
519 linelen = len (v) - string.rfind(v, '\n')
520 if linelen + len (a) > 80:
521 v = v + '\n'
522 return v + a + ' '
524 def stuff_append (stuff, idx, a):
525 if not stuff:
526 stuff.append (a)
527 else:
528 stuff [idx] = wordwrap(a, stuff[idx])
532 def voices_append(a):
533 if current_voice_idx < 0:
534 select_voice ('default', '')
535 stuff_append (voices, current_voice_idx, a)
537 def repeat_prepend():
538 global repeat_state
539 if current_voice_idx < 0:
540 select_voice ('default', '')
541 if not using_old:
542 repeat_state[current_voice_idx] = 't'
545 def lyrics_append(a):
546 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
547 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
548 a = '\t{ \\lyrics "' + a + '" }\n'
549 stuff_append (lyrics, current_lyric_idx, a)
551 # break lyrics to words and put "'s around words containing numbers and '"'s
552 def fix_lyric(str):
553 ret = ''
554 while str != '':
555 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
556 if m:
557 word = m.group(1)
558 str = m.group(2)
559 word = re.sub('"', '\\"', word) # escape "
560 if re.match('.*[0-9"\(]', word):
561 word = re.sub('_', ' ', word) # _ causes probs inside ""
562 ret = ret + '\"' + word + '\" '
563 else:
564 ret = ret + word + ' '
565 else:
566 return (ret)
567 return (ret)
569 def slyrics_append(a):
570 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
571 a = re.sub ( '-', '- ', a) # split words with -
572 a = re.sub ( '\\\\- ', '-', a) # unless \-
573 a = re.sub ( '~', '_', a) # ~ to space('_')
574 a = re.sub ( '\*', '_ ', a) # * to to space
575 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
576 if re.match('.*[0-9"\(]', a): # put numbers and " and ( into quoted string
577 a = fix_lyric(a)
578 a = re.sub ( '$', ' ', a) # insure space between lines
579 __main__.lyric_idx = lyric_idx + 1
580 if len(slyrics[current_voice_idx]) <= lyric_idx:
581 slyrics[current_voice_idx].append(a)
582 else:
583 v = slyrics[current_voice_idx][lyric_idx]
584 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
587 def try_parse_header_line (ln, state):
588 global length_specified
589 m = re.match ('^([A-Za-z]): *(.*)$', ln)
591 if m:
592 g =m.group (1)
593 a = m.group (2)
594 if g == 'T': #title
595 a = re.sub('[ \t]*$','', a) #strip trailing blanks
596 if header.has_key('title'):
597 if a:
598 if len(header['title']):
599 header['title'] = header['title'] + '\\\\\\\\' + a
600 else:
601 header['subtitle'] = a
602 else:
603 header['title'] = a
604 if g == 'M': # Meter
605 if a == 'C':
606 if not state.common_time:
607 state.common_time = 1
608 voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
609 a = '4/4'
610 if a == 'C|':
611 if not state.common_time:
612 state.common_time = 1
613 voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
614 a = '2/2'
615 if not length_specified:
616 set_default_len_from_time_sig (a)
617 else:
618 length_specified = 0
619 if not a == 'none':
620 voices_append ('\\time %s' % a)
621 state.next_bar = ''
622 if g == 'K': # KEY
623 a = check_clef(a)
624 if a:
625 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
626 if m:
627 # there may or may not be a space
628 # between the key letter and the mode
629 if key_lookup.has_key(m.group(2)[0:3]):
630 key_info = m.group(1) + m.group(2)[0:3]
631 clef_info = m.group(2)[4:]
632 else:
633 key_info = m.group(1)
634 clef_info = m.group(2)
635 __main__.global_key = compute_key (key_info)# ugh.
636 voices_append ('\\key %s' % lily_key(key_info))
637 check_clef(clef_info)
638 else:
639 __main__.global_key = compute_key (a)# ugh.
640 voices_append ('\\key %s \\major' % lily_key(a))
641 if g == 'N': # Notes
642 header ['footnotes'] = header['footnotes'] + '\\\\\\\\' + a
643 if g == 'O': # Origin
644 header ['origin'] = a
645 if g == 'X': # Reference Number
646 header ['crossRefNumber'] = a
647 if g == 'A': # Area
648 header ['area'] = a
649 if g == 'H': # History
650 header_append ('history', a)
651 if g == 'B': # Book
652 header ['book'] = a
653 if g == 'C': # Composer
654 if header.has_key('composer'):
655 if a:
656 header['composer'] = header['composer'] + '\\\\\\\\' + a
657 else:
658 header['composer'] = a
659 if g == 'S':
660 header ['subtitle'] = a
661 if g == 'L': # Default note length
662 set_default_length (ln)
663 if g == 'V': # Voice
664 voice = re.sub (' .*$', '', a)
665 rest = re.sub ('^[^ \t]* *', '', a)
666 if state.next_bar:
667 voices_append(state.next_bar)
668 state.next_bar = ''
669 select_voice (voice, rest)
670 if g == 'W': # Words
671 lyrics_append(a)
672 if g == 'w': # vocals
673 slyrics_append (a)
674 if g == 'Q': #tempo
675 try_parse_q (a)
676 return ''
677 return ln
679 # we use in this order specified accidental, active accidental for bar,
680 # active accidental for key
681 def pitch_to_lilypond_name (name, acc, bar_acc, key):
682 s = ''
683 if acc == UNDEF:
684 if not nobarlines:
685 acc = bar_acc
686 if acc == UNDEF:
687 acc = key
688 if acc == -1:
689 s = 'es'
690 elif acc == 1:
691 s = 'is'
693 if name > 4:
694 name = name -7
695 return(chr (name + ord('c')) + s)
698 def octave_to_lilypond_quotes (o):
699 o = o + 2
700 s =''
701 if o < 0:
702 o = -o
703 s=','
704 else:
705 s ='\''
707 return s * o
709 def parse_num (str):
710 durstr = ''
711 while str and str[0] in DIGITS:
712 durstr = durstr + str[0]
713 str = str[1:]
715 n = None
716 if durstr:
717 n =string.atoi (durstr)
718 return (str,n)
721 def duration_to_lilypond_duration (multiply_tup, defaultlen, dots):
722 base = 1
723 # (num / den) / defaultlen < 1/base
724 while base * multiply_tup[0] < multiply_tup[1]:
725 base = base * 2
726 if base == 1:
727 if (multiply_tup[0] / multiply_tup[1]) == 2:
728 base = '\\breve'
729 if (multiply_tup[0] / multiply_tup[1]) == 3:
730 base = '\\breve'
731 dots = 1
732 if (multiply_tup[0] / multiply_tup[1]) == 4:
733 base = '\longa'
734 return '%s%s' % ( base, '.'* dots)
736 class Parser_state:
737 def __init__ (self):
738 self.in_acc = {}
739 self.next_articulation = ''
740 self.next_bar = ''
741 self.next_dots = 0
742 self.next_den = 1
743 self.parsing_tuplet = 0
744 self.plus_chord = 0
745 self.base_octave = 0
746 self.common_time = 0
750 # return (str, num,den,dots)
751 def parse_duration (str, parser_state):
752 num = 0
753 den = parser_state.next_den
754 parser_state.next_den = 1
756 (str, num) = parse_num (str)
757 if not num:
758 num = 1
759 if len(str):
760 if str[0] == '/':
761 if len(str[0]):
762 while str[:1] == '/':
763 str= str[1:]
764 d = 2
765 if str[0] in DIGITS:
766 (str, d) =parse_num (str)
768 den = den * d
770 den = den * default_len
772 current_dots = parser_state.next_dots
773 parser_state.next_dots = 0
774 if re.match ('[ \t]*[<>]', str):
775 while str[0] in HSPACE:
776 str = str[1:]
777 while str[0] == '>':
778 str = str [1:]
779 current_dots = current_dots + 1
780 parser_state.next_den = parser_state.next_den * 2
782 while str[0] == '<':
783 str = str [1:]
784 den = den * 2
785 parser_state.next_dots = parser_state.next_dots + 1
789 try_dots = [3, 2, 1]
790 for d in try_dots:
791 f = 1 << d
792 multiplier = (2*f-1)
793 if num % multiplier == 0 and den % f == 0:
794 num = num / multiplier
795 den = den / f
796 current_dots = current_dots + d
798 return (str, num,den,current_dots)
801 def try_parse_rest (str, parser_state):
802 if not str or str[0] <> 'z' and str[0] <> 'x':
803 return str
805 __main__.lyric_idx = -1
807 if parser_state.next_bar:
808 voices_append(parser_state.next_bar)
809 parser_state.next_bar = ''
811 if str[0] == 'z':
812 rest = 'r'
813 else:
814 rest = 's'
815 str = str[1:]
817 (str, num,den,d) = parse_duration (str, parser_state)
818 voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
819 if parser_state.next_articulation:
820 voices_append (parser_state.next_articulation)
821 parser_state.next_articulation = ''
823 return str
825 artic_tbl = {
826 '.' : '-.',
827 'T' : '^\\trill',
828 'H' : '^\\fermata',
829 'u' : '^\\upbow',
830 'K' : '^\\ltoe',
831 'k' : '^\\accent',
832 'M' : '^\\tenuto',
833 '~' : '^"~" ',
834 'J' : '', # ignore slide
835 'R' : '', # ignore roll
836 'v' : '^\\downbow'
839 def try_parse_articulation (str, state):
840 while str and artic_tbl.has_key(str[:1]):
841 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
842 if not artic_tbl[str[:1]]:
843 sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
845 str = str[1:]
849 # s7m2 input doesnt care about spaces
850 if re.match('[ \t]*\(', str):
851 str = string.lstrip (str)
853 slur_begin =0
854 while str[:1] =='(' and str[1] not in DIGITS:
855 slur_begin = slur_begin + 1
856 state.next_articulation = state.next_articulation + '('
857 str = str[1:]
859 return str
862 # remember accidental for rest of bar
864 def set_bar_acc(note, octave, acc, state):
865 if acc == UNDEF:
866 return
867 n_oct = note + octave * 7
868 state.in_acc[n_oct] = acc
870 # get accidental set in this bar or UNDEF if not set
871 def get_bar_acc(note, octave, state):
872 n_oct = note + octave * 7
873 if state.in_acc.has_key(n_oct):
874 return(state.in_acc[n_oct])
875 else:
876 return(UNDEF)
878 def clear_bar_acc(state):
879 for k in state.in_acc.keys():
880 del state.in_acc[k]
884 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
885 def try_parse_note (str, parser_state):
886 mud = ''
888 slur_begin =0
889 if not str:
890 return str
892 articulation =''
893 acc = UNDEF
894 if str[0] in '^=_':
895 c = str[0]
896 str = str[1:]
897 if c == '^':
898 acc = 1
899 if c == '=':
900 acc = 0
901 if c == '_':
902 acc = -1
904 octave = parser_state.base_octave
905 if str[0] in "ABCDEFG":
906 str = string.lower (str[0]) + str[1:]
907 octave = octave - 1
910 notename = 0
911 if str[0] in "abcdefg":
912 notename = (ord(str[0]) - ord('a') + 5)%7
913 str = str[1:]
914 else:
915 return str # failed; not a note!
918 __main__.lyric_idx = -1
920 if parser_state.next_bar:
921 voices_append(parser_state.next_bar)
922 parser_state.next_bar = ''
924 while str[0] == ',':
925 octave = octave - 1
926 str = str[1:]
927 while str[0] == '\'':
928 octave = octave + 1
929 str = str[1:]
931 (str, num,den,current_dots) = parse_duration (str, parser_state)
933 if re.match('[ \t]*\)', str):
934 str = string.lstrip (str)
936 slur_end =0
937 while str[:1] ==')':
938 slur_end = slur_end + 1
939 str = str[1:]
942 bar_acc = get_bar_acc(notename, octave, parser_state)
943 pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
944 oct = octave_to_lilypond_quotes (octave)
945 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
946 mod='!'
947 else:
948 mod = ''
949 voices_append ("%s%s%s%s" %
950 (pit, oct, mod,
951 duration_to_lilypond_duration ((num,den), default_len, current_dots)))
953 set_bar_acc(notename, octave, acc, parser_state)
954 if parser_state.next_articulation:
955 articulation = articulation + parser_state.next_articulation
956 parser_state.next_articulation = ''
958 voices_append (articulation)
960 if parser_state.parsing_tuplet:
961 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
962 if not parser_state.parsing_tuplet:
963 voices_append ("}")
964 if slur_begin:
965 voices_append ('-(' * slur_begin )
966 if slur_end:
967 voices_append ('-)' *slur_end )
971 return str
973 def junk_space (str):
974 while str and str[0] in '\t\n ':
975 str = str[1:]
977 return str
980 def try_parse_guitar_chord (str, state):
981 if str[:1] =='"':
982 str = str[1:]
983 gc = ''
984 if str[0] == '_' or (str[0] == '^'):
985 position = str[0]
986 str = str[1:]
987 else:
988 position = '^'
989 while str and str[0] != '"':
990 gc = gc + str[0]
991 str = str[1:]
993 if str:
994 str = str[1:]
995 gc = re.sub('#', '\\#', gc) # escape '#'s
996 state.next_articulation = ("%c\"%s\"" % (position ,gc)) + state.next_articulation
997 return str
999 def try_parse_escape (str):
1000 if not str or str [0] != '\\':
1001 return str
1003 str = str[1:]
1004 if str[:1] =='K':
1005 key_table = compute_key ()
1006 return str
1009 # |] thin-thick double bar line
1010 # || thin-thin double bar line
1011 # [| thick-thin double bar line
1012 # :| left repeat
1013 # |: right repeat
1014 # :: left-right repeat
1015 # |1 volta 1
1016 # |2 volta 2
1017 old_bar_dict = {
1018 '|]' : '|.',
1019 '||' : '||',
1020 '[|' : '||',
1021 ':|' : ':|',
1022 '|:' : '|:',
1023 '::' : ':|:',
1024 '|1' : '|',
1025 '|2' : '|',
1026 ':|2' : ':|',
1027 '|' : '|'
1029 bar_dict = {
1030 '|]' : '\\bar "|."',
1031 '||' : '\\bar "||"',
1032 '[|' : '\\bar "||"',
1033 ':|' : '}',
1034 '|:' : '\\repeat volta 2 {',
1035 '::' : '} \\repeat volta 2 {',
1036 '|1' : '} \\alternative{{',
1037 '|2' : '} {',
1038 ':|2' : '} {',
1039 '|' : '\\bar "|"'
1043 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1044 alternative_opener = ['|1', '|2', ':|2']
1045 repeat_ender = ['::', ':|']
1046 repeat_opener = ['::', '|:']
1047 in_repeat = [''] * 8
1048 doing_alternative = [''] * 8
1049 using_old = ''
1051 def try_parse_bar (str,state):
1052 global in_repeat, doing_alternative, using_old
1053 do_curly = ''
1054 bs = None
1055 if current_voice_idx < 0:
1056 select_voice ('default', '')
1057 # first try the longer one
1058 for trylen in [3,2,1]:
1059 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1060 s = str[:trylen]
1061 if using_old:
1062 bs = "\\bar \"%s\"" % old_bar_dict[s]
1063 else:
1064 bs = "%s" % bar_dict[s]
1065 str = str[trylen:]
1066 if s in alternative_opener:
1067 if not in_repeat[current_voice_idx]:
1068 using_old = 't'
1069 bs = "\\bar \"%s\"" % old_bar_dict[s]
1070 else:
1071 doing_alternative[current_voice_idx] = 't'
1073 if s in repeat_ender:
1074 if not in_repeat[current_voice_idx]:
1075 sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1076 repeat_prepend()
1077 in_repeat[current_voice_idx] = ''
1078 else:
1079 if doing_alternative[current_voice_idx]:
1080 do_curly = 't'
1081 if using_old:
1082 bs = "\\bar \"%s\"" % old_bar_dict[s]
1083 else:
1084 bs = bar_dict[s]
1085 doing_alternative[current_voice_idx] = ''
1086 in_repeat[current_voice_idx] = ''
1087 if s in repeat_opener:
1088 in_repeat[current_voice_idx] = 't'
1089 if using_old:
1090 bs = "\\bar \"%s\"" % old_bar_dict[s]
1091 else:
1092 bs = bar_dict[s]
1093 break
1094 if str[:1] == '|':
1095 state.next_bar = '|\n'
1096 str = str[1:]
1097 clear_bar_acc(state)
1099 if bs <> None or state.next_bar != '':
1100 if state.parsing_tuplet:
1101 state.parsing_tuplet =0
1102 voices_append ('} ')
1104 if bs <> None:
1105 clear_bar_acc(state)
1106 voices_append (bs)
1107 if do_curly != '':
1108 voices_append("} }")
1109 do_curly = ''
1110 return str
1112 def try_parse_tie (str):
1113 if str[:1] =='-':
1114 str = str[1:]
1115 voices_append (' ~ ')
1116 return str
1118 def bracket_escape (str, state):
1119 m = re.match ( '^([^\]]*)] *(.*)$', str)
1120 if m:
1121 cmd = m.group (1)
1122 str = m.group (2)
1123 try_parse_header_line (cmd, state)
1124 return str
1126 def try_parse_chord_delims (str, state):
1127 if str[:1] =='[':
1128 str = str[1:]
1129 if re.match('[A-Z]:', str): # bracket escape
1130 return bracket_escape(str, state)
1131 if state.next_bar:
1132 voices_append(state.next_bar)
1133 state.next_bar = ''
1134 voices_append ('<')
1136 if str[:1] == '+':
1137 str = str[1:]
1138 if state.plus_chord:
1139 voices_append ('>')
1140 state.plus_chord = 0
1141 else:
1142 if state.next_bar:
1143 voices_append(state.next_bar)
1144 state.next_bar = ''
1145 voices_append ('<')
1146 state.plus_chord = 1
1148 ch = ''
1149 if str[:1] ==']':
1150 str = str[1:]
1151 ch = '>'
1153 end = 0
1154 while str[:1] ==')':
1155 end = end + 1
1156 str = str[1:]
1159 voices_append ("\\spanrequest \\stop \"slur\"" * end)
1160 voices_append (ch)
1161 return str
1163 def try_parse_grace_delims (str, state):
1164 if str[:1] =='{':
1165 if state.next_bar:
1166 voices_append(state.next_bar)
1167 state.next_bar = ''
1168 str = str[1:]
1169 voices_append ('\\grace { ')
1171 if str[:1] =='}':
1172 str = str[1:]
1173 voices_append ('}')
1175 return str
1177 def try_parse_comment (str):
1178 global nobarlines
1179 if (str[0] == '%'):
1180 if str[0:5] == '%MIDI':
1181 #the nobarlines option is necessary for an abc to lilypond translator for
1182 #exactly the same reason abc2midi needs it: abc requires the user to enter
1183 #the note that will be printed, and MIDI and lilypond expect entry of the
1184 #pitch that will be played.
1186 #In standard 19th century musical notation, the algorithm for translating
1187 #between printed note and pitch involves using the barlines to determine
1188 #the scope of the accidentals.
1190 #Since ABC is frequently used for music in styles that do not use this
1191 #convention, such as most music written before 1700, or ethnic music in
1192 #non-western scales, it is necessary to be able to tell a translator that
1193 #the barlines should not affect its interpretation of the pitch.
1194 if (string.find(str,'nobarlines') > 0):
1195 nobarlines = 1
1196 elif str[0:3] == '%LY':
1197 p = string.find(str, 'voices')
1198 if (p > -1):
1199 voices_append(str[p+7:])
1200 voices_append("\n")
1201 p = string.find(str, 'slyrics')
1202 if (p > -1):
1203 slyrics_append(str[p+8:])
1205 #write other kinds of appending if we ever need them.
1206 return str
1208 happy_count = 100
1209 def parse_file (fn):
1210 f = open (fn)
1211 ls = f.readlines ()
1213 select_voice('default', '')
1214 lineno = 0
1215 sys.stderr.write ("Line ... ")
1216 sys.stderr.flush ()
1217 __main__.state = state_list[current_voice_idx]
1219 for ln in ls:
1220 lineno = lineno + 1
1222 if not (lineno % happy_count):
1223 sys.stderr.write ('[%d]'% lineno)
1224 sys.stderr.flush ()
1225 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1226 if m:
1227 if m.group(2):
1228 try_parse_comment(m.group(2))
1229 voices_append ('%% %s\n' % m.group(2))
1230 ln = m.group (1)
1232 orig_ln = ln
1234 ln = try_parse_header_line (ln, state)
1236 # Try nibbling characters off until the line doesn't change.
1237 prev_ln = ''
1238 while ln != prev_ln:
1239 prev_ln = ln
1240 ln = try_parse_chord_delims (ln, state)
1241 ln = try_parse_rest (ln, state)
1242 ln = try_parse_articulation (ln,state)
1243 ln = try_parse_note (ln, state)
1244 ln = try_parse_bar (ln, state)
1245 ln = try_parse_tie (ln)
1246 ln = try_parse_escape (ln)
1247 ln = try_parse_guitar_chord (ln, state)
1248 ln = try_parse_tuplet_begin (ln, state)
1249 ln = try_parse_group_end (ln, state)
1250 ln = try_parse_grace_delims (ln, state)
1251 ln = junk_space (ln)
1253 if ln:
1254 error ("%s: %d: Huh? Don't understand\n" % (fn, lineno))
1255 left = orig_ln[0:-len (ln)]
1256 sys.stderr.write (left + '\n')
1257 sys.stderr.write (' ' * len (left) + ln + '\n')
1260 def identify():
1261 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1263 def help ():
1264 print r"""
1265 Convert ABC to lilypond.
1267 Usage: abc2ly [OPTIONS]... ABC-FILE
1269 Options:
1270 -h, --help print this help
1271 -o, --output=FILE set output filename to FILE
1272 -v, --version show version information
1273 -s, --strict be strict about succes
1275 This program converts ABC music files (see
1276 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) to LilyPond input.
1279 Report bugs to bug-lilypond@gnu.org.
1281 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>, Laura Conrad
1282 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1285 def print_version ():
1286 print r"""abc2ly (GNU lilypond) %s""" % version
1290 (options, files) = getopt.getopt (sys.argv[1:], 'vo:hs', ['help','version', 'output=', 'strict'])
1291 out_filename = ''
1293 for opt in options:
1294 o = opt[0]
1295 a = opt[1]
1296 if o== '--help' or o == '-h':
1297 help ()
1298 sys.exit (0)
1299 elif o == '--version' or o == '-v':
1300 print_version ()
1301 sys.exit(0)
1302 elif o == '--strict' or o == '-s':
1303 strict = 1
1304 elif o == '--output' or o == '-o':
1305 out_filename = a
1306 else:
1307 print o
1308 raise getopt.error
1310 identify()
1312 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1313 for f in files:
1314 if f == '-':
1315 f = ''
1317 sys.stderr.write ('Parsing `%s\'...\n' % f)
1318 parse_file (f)
1320 if not out_filename:
1321 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1322 sys.stderr.write ('lilypond output to: `%s\'...' % out_filename)
1323 outf = open (out_filename, 'w')
1325 # dump_global (outf)
1326 dump_header (outf ,header)
1327 dump_slyrics (outf)
1328 dump_voices (outf)
1329 dump_score (outf)
1330 dump_lyrics (outf)
1331 sys.stderr.write ('\n')