]> git.donarmstrong.com Git - lilypond.git/blob - scripts/abc2ly.py
* scripts/musedata2ly.py (): idem
[lilypond.git] / scripts / abc2ly.py
1 #!@PYTHON@
2
3 # once upon a rainy monday afternoon.
4 #
5 #   ...
6 #
7 # (not finished.)
8 # ABC standard v1.6:  http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt
9 #
10 # Enhancements  (Roy R. Rankin)
11 #
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)
28
29 # Enhancements (Laura Conrad)
30 #
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.
36
37 # Limitations
38 #
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 # ???
48
49
50
51 #TODO:
52 #
53 # Convert to new chord styles.
54 #
55 # UNDEF -> None
56 #
57   
58   
59 program_name = 'abc2ly'
60 version = '@TOPLEVEL_VERSION@'
61 if version == '@' + 'TOPLEVEL_VERSION' + '@':
62         version = '(unknown version)'           # uGUHGUHGHGUGH
63   
64 import __main__
65 import getopt
66 import sys
67 import re
68 import string
69 import os
70
71
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 = ''
96
97
98 def error (msg):
99         sys.stderr.write (msg)
100         if strict:
101                 sys.exit (1)
102         
103         
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
132
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 )
158
159               else:
160                       break
161
162         return
163
164
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 ('}')
173
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")
181
182 def dump_default_bar (outf):
183         outf.write ("\n\\property Score.defaultBarType=\"empty\"\n")
184
185
186 def dump_slyrics (outf):
187         ks = voice_idx_dict.keys()
188         ks.sort ()
189         for k in ks:
190                 if re.match('[1-9]', k):
191                         m = alphabet[string.atoi(k)]
192                 else:
193                         m = k
194                 for i in range (len(slyrics[voice_idx_dict[k]])):
195                         l=alphabet[i]
196                         outf.write ("\nwords%sV%s = \\lyrics  {" % (m, l))
197                         outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
198                         outf.write ("\n}")
199
200 def dump_voices (outf):
201         global doing_alternative, in_repeat
202         ks = voice_idx_dict.keys()
203         ks.sort ()
204         for k in ks:
205                 if re.match ('[1-9]', k):
206                         m = alphabet[string.atoi(k)]
207                 else:
208                         m = k
209                 outf.write ("\nvoice%s = \\notes {" % m)
210                 dump_default_bar(outf)
211                 if repeat_state[voice_idx_dict[k]]:
212                         outf.write("\n\\repeat volta 2 {")
213                 outf.write ("\n" + voices [voice_idx_dict[k]])
214                 if not using_old:
215                         if doing_alternative[voice_idx_dict[k]]:
216                                 outf.write("}")
217                         if in_repeat[voice_idx_dict[k]]:
218                                 outf.write("}")
219                 outf.write ("\n}")
220
221 def try_parse_q(a):
222         global midi_specs
223         #assume that Q takes the form "Q:1/4=120"
224         #There are other possibilities, but they are deprecated
225         if string.count(a, '/') == 1:
226                 array=string.split(a,'/')
227                 numerator=array[0]
228                 if numerator != 1:
229                         sys.stderr.write("abc2ly: Warning, unable to translate a Q specification with a numerator of %s: %s\n" % (numerator, a))
230                 array2=string.split(array[1],'=')
231                 denominator=array2[0]
232                 perminute=array2[1]
233                 duration=str(string.atoi(denominator)/string.atoi(numerator))
234                 midi_specs=string.join(["\\tempo", duration, "=", perminute])
235         else:
236                 sys.stderr.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a)
237         
238 def dump_score (outf):
239         outf.write (r"""\score{
240         \notes <
241 """)
242
243         ks  = voice_idx_dict.keys ();
244         ks.sort ()
245         for k in  ks:
246                 if re.match('[1-9]', k):
247                         m = alphabet[string.atoi(k)]
248                 else:
249                         m = k
250                 if k == 'default' and len (voice_idx_dict) > 1:
251                         break
252                 if len ( slyrics [voice_idx_dict[k]] ):
253                         outf.write ("\n        \\addlyrics")
254                 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k ) 
255                 if k != 'default':
256                         outf.write ("\t    \\voicedefault\n")
257                 outf.write ("\t    \\voice%s " % m)
258                 outf.write ("\n\t}\n")
259                 if len ( slyrics [voice_idx_dict[k]] ):
260                         outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<\t" % k)
261                         if re.match('[1-9]',k):
262                                 m = alphabet[string.atoi(k)]
263                         else:
264                                 m = k
265                         for i in range (len(slyrics[voice_idx_dict[k]])):
266                                 l=alphabet[i]
267                                 outf.write("\n\t  { \\words%sV%s }" % ( m, l) )
268                         outf.write ( "\n\t>\n" )
269         outf.write ("\n    >")
270         outf.write ("\n\t\\paper {\n")
271         if part_names:
272                 outf.write ("\t    \\translator \n\t    {\n")
273                 outf.write ("\t\t\\StaffContext\n")
274 #               outf.write ("\t\t\\consists Staff_margin_engraver\n")
275                 outf.write ("\t    }\n")
276         outf.write ("\t}\n\t\\midi {%s}\n}\n" % midi_specs)
277
278
279
280 def set_default_length (s):
281         global length_specified
282         m =  re.search ('1/([0-9]+)', s)
283         if m:
284                 __main__.default_len = string.atoi ( m.group (1))
285                 length_specified = 1
286
287 def set_default_len_from_time_sig (s):
288         m =  re.search ('([0-9]+)/([0-9]+)', s)
289         if m:
290                 n = string.atoi (m.group (1))
291                 d = string.atoi (m.group (2))
292                 if (n * 1.0 )/(d * 1.0) <  0.75:
293                         __main__.default_len =  16
294                 else:
295                         __main__.default_len = 8
296
297 def gulp_file(f):
298         try:
299                 i = open(f)
300                 i.seek (0, 2)
301                 n = i.tell ()
302                 i.seek (0,0)
303         except:
304                 sys.stderr.write ("can't open file: `%s'\n" % f)
305                 return ''
306         s = i.read (n)
307         if len (s) <= 0:
308                 sys.stderr.write ("gulped empty file: `%s'\n" % f)
309         i.close ()
310         return s
311
312
313 # pitch manipulation. Tuples are (name, alteration).
314 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
315 # pitch in semitones. 
316 def semitone_pitch  (tup):
317         p =0
318
319         t = tup[0]
320         p = p + 12 * (t / 7)
321         t = t % 7
322         
323         if t > 2:
324                 p = p- 1
325                 
326         p = p + t* 2 + tup[1]
327         return p
328
329 def fifth_above_pitch (tup):
330         (n, a)  = (tup[0] + 4, tup[1])
331
332         difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
333         a = a + difference
334         
335         return (n,a)
336
337 def sharp_keys ():
338         p = (0,0)
339         l = []
340         k = 0
341         while 1:
342                 l.append (p)
343                 (t,a) = fifth_above_pitch (p)
344                 if semitone_pitch((t,a)) % 12 == 0:
345                         break
346
347                 p = (t % 7, a)
348         return l
349
350 def flat_keys ():
351         p = (0,0)
352         l = []
353         k = 0
354         while 1:
355                 l.append (p)
356                 (t,a) = quart_above_pitch (p)
357                 if semitone_pitch((t,a)) % 12 == 0:
358                         break
359
360                 p = (t % 7, a)
361         return l
362
363 def quart_above_pitch (tup):
364         (n, a)  = (tup[0] + 3, tup[1])
365
366         difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
367         a = a + difference
368         
369         return (n,a)
370
371 key_lookup = {  # abc to lilypond key mode names
372         'm'   : 'minor',
373         'min' : 'minor',
374         'maj' : 'major',
375         'major' : 'major',      
376         'phr' : 'phrygian',
377         'ion' : 'ionian',
378         'loc' : 'locrian',
379         'aeo' : 'aeolian',
380         'mix' : 'mixolydian',
381         'mixolydian' : 'mixolydian',    
382         'lyd' : 'lydian',
383         'dor' : 'dorian',
384         'dorian' : 'dorian'     
385 }
386
387 def lily_key (k):
388         k = string.lower (k)
389         key = k[0]
390         k = k[1:]
391         if k and k[0] == '#':
392                 key = key + 'is'
393                 k = k[1:]
394         elif k and k[0] == 'b':
395                 key = key + 'es'
396                 k = k[1:]
397         if not k:
398                 return '%s \\major' % key
399
400         type = k[0:3]
401         if key_lookup.has_key(type):
402                 return("%s \\%s" % ( key, key_lookup[type]))
403         sys.stderr.write("Unknown key type `%s' ignored\n" % type)
404         return key
405
406 def shift_key (note, acc , shift):
407         s = semitone_pitch((note, acc))
408         s = (s + shift + 12) % 12
409         if s <= 4:
410                 n = s / 2
411                 a = s % 2
412         else:
413                 n = (s + 1) / 2
414                 a = (s + 1) % 2
415         if a:
416                 n = n + 1
417                 a = -1
418         return (n,a)
419
420 key_shift = { # semitone shifts for key mode names
421         'm'   : 3,
422         'min' : 3,
423         'minor' : 3,
424         'maj' : 0,
425         'major' : 0,    
426         'phr' : -4,
427         'phrygian' : -4,
428         'ion' : 0,
429         'ionian' : 0,
430         'loc' : 1,
431         'locrian' : 1,  
432         'aeo' : 3,
433         'aeolian' : 3,
434         'mix' : 5,
435         'mixolydian' : 5,       
436         'lyd' : -5,
437         'lydian' : -5,  
438         'dor' : -2,
439         'dorian' :      -2      
440 }
441 def compute_key (k):
442         k = string.lower (k)
443         intkey = (ord (k[0]) - ord('a') + 5) % 7
444         intkeyacc =0
445         k = k[1:]
446         
447         if k and k[0] == 'b':
448                 intkeyacc = -1
449                 k = k[1:]
450         elif  k and k[0] == '#':
451                 intkeyacc = 1
452                 k = k[1:]
453         k = k[0:3]
454         if k and key_shift.has_key(k):
455                 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
456         keytup = (intkey, intkeyacc)
457         
458         sharp_key_seq = sharp_keys ()
459         flat_key_seq = flat_keys ()
460
461         accseq = None
462         accsign = 0
463         if keytup in sharp_key_seq:
464                 accsign = 1
465                 key_count = sharp_key_seq.index (keytup)
466                 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
467
468         elif keytup in flat_key_seq:
469                 accsign = -1
470                 key_count = flat_key_seq.index (keytup)
471                 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
472         else:
473                 error ("Huh?")
474                 raise "Huh"
475         
476         key_table = [0] * 7
477         for a in accseq:
478                  key_table[a] = key_table[a] + accsign
479
480         return key_table
481
482 tup_lookup = {
483         '2' : '3/2',
484         '3' : '2/3',
485         '4' : '4/3',
486         '5' : '4/5',
487         '6' : '4/6',
488         '7' : '6/7',
489         '9' : '8/9',
490         }
491
492
493 def try_parse_tuplet_begin (str, state):
494         if re.match ('\([2-9]', str):
495                 dig = str[1]
496                 str = str[2:]
497                 prev_tuplet_state = state.parsing_tuplet
498                 state.parsing_tuplet = string.atoi (dig[0])
499                 if prev_tuplet_state:
500                         voices_append ("}")             
501                 voices_append ("\\times %s {" % tup_lookup[dig])
502         return str
503
504 def  try_parse_group_end (str, state):
505         if str and str[0] in HSPACE:
506                 str = str[1:]
507         return str
508         
509 def header_append (key, a):
510         s = ''
511         if header.has_key (key):
512                 s = header[key] + "\n"
513                 header [key] = s + a
514
515 def wordwrap(a, v):
516         linelen = len (v) - string.rfind(v, '\n')
517         if linelen + len (a) > 80:
518                 v = v + '\n'
519         return v + a + ' '
520
521 def stuff_append (stuff, idx, a):
522         if not stuff:
523                 stuff.append (a)
524         else:
525                 stuff [idx] = wordwrap(a, stuff[idx])
526
527
528
529 def voices_append(a):
530         if current_voice_idx < 0:
531                 select_voice ('default', '')
532         stuff_append (voices, current_voice_idx, a)
533
534 def repeat_prepend():
535         global repeat_state
536         if current_voice_idx < 0:
537                 select_voice ('default', '')
538         if not using_old:
539                 repeat_state[current_voice_idx] = 't'
540
541         
542 def lyrics_append(a):
543         a = re.sub ( '#', '\\#', a)     # latex does not like naked #'s
544         a = re.sub ( '"', '\\"', a)     # latex does not like naked "'s
545         a = '\t{ \\lyrics "' + a + '" }\n'
546         stuff_append (lyrics, current_lyric_idx, a)
547
548 # break lyrics to words and put "'s around words containing numbers and '"'s
549 def fix_lyric(str):
550         ret = ''
551         while str != '':
552                 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
553                 if m:
554                         word = m.group(1)
555                         str = m.group(2)
556                         word = re.sub('"', '\\"', word) # escape "
557                         if re.match('.*[0-9"\(]', word):
558                                 word = re.sub('_', ' ', word) # _ causes probs inside ""
559                                 ret = ret + '\"' + word + '\" '
560                         else:
561                                 ret = ret + word + ' '
562                 else:
563                         return (ret)
564         return (ret)
565
566 def slyrics_append(a):
567         a = re.sub ( '_', ' _ ', a)     # _ to ' _ '
568         a = re.sub ( '-', '- ', a)      # split words with -
569         a = re.sub ( '\\\\- ', '-', a)  # unless \-
570         a = re.sub ( '~', '_', a)       # ~ to space('_')
571         a = re.sub ( '\*', '_ ', a)     # * to to space
572         a = re.sub ( '#', '\\#', a)     # latex does not like naked #'s
573         if re.match('.*[0-9"\(]', a):   # put numbers and " and ( into quoted string
574                 a = fix_lyric(a)
575         a = re.sub ( '$', ' ', a)       # insure space between lines
576         __main__.lyric_idx = lyric_idx + 1
577         if len(slyrics[current_voice_idx]) <= lyric_idx:
578                 slyrics[current_voice_idx].append(a)
579         else:
580                 v = slyrics[current_voice_idx][lyric_idx]
581                 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
582
583
584 def try_parse_header_line (ln, state):
585         global length_specified
586         m = re.match ('^([A-Za-z]): *(.*)$', ln)
587
588         if m:
589                 g =m.group (1)
590                 a = m.group (2)
591                 if g == 'T':    #title
592                         a = re.sub('[ \t]*$','', a)     #strip trailing blanks
593                         if header.has_key('title'):
594                                 if a:
595                                         if len(header['title']):
596                                                 header['title'] = header['title'] + '\\\\\\\\' + a
597                                         else:
598                                                 header['subtitle'] = a
599                         else:
600                                 header['title'] =  a
601                 if g == 'M':    # Meter
602                         if a == 'C':
603                                 if not state.common_time:
604                                         state.common_time = 1
605                                         voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
606                                 a = '4/4'
607                         if a == 'C|':
608                                 if not state.common_time:
609                                         state.common_time = 1
610                                         voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
611                                 a = '2/2'
612                         if not length_specified:
613                                 set_default_len_from_time_sig (a)
614                         else:
615                                 length_specified = 0
616                         if not a == 'none':
617                                 voices_append ('\\time %s' % a)
618                         state.next_bar = ''
619                 if g == 'K': # KEY
620                         a = check_clef(a)
621                         if a:
622                                 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
623                                 if m:
624                                         # there may or may not be a space
625                                         # between the key letter and the mode
626                                         if key_lookup.has_key(m.group(2)[0:3]):
627                                                 key_info = m.group(1) + m.group(2)[0:3]
628                                                 clef_info = m.group(2)[4:]
629                                         else:
630                                                 key_info = m.group(1)
631                                                 clef_info = m.group(2)
632                                         __main__.global_key  = compute_key (key_info)# ugh.
633                                         voices_append ('\\key %s' % lily_key(key_info))
634                                         check_clef(clef_info)
635                                 else:
636                                         __main__.global_key  = compute_key (a)# ugh.
637                                         voices_append ('\\key %s \\major' % lily_key(a))
638                 if g == 'N': # Notes
639                         header ['footnotes'] = header['footnotes'] +  '\\\\\\\\' + a
640                 if g == 'O': # Origin
641                         header ['origin'] = a
642                 if g == 'X': # Reference Number
643                         header ['crossRefNumber'] = a
644                 if g == 'A': #  Area
645                         header ['area'] = a
646                 if g == 'H':    # History
647                         header_append ('history', a)
648                 if g == 'B':    # Book
649                         header ['book'] = a
650                 if g == 'C':    # Composer
651                         if header.has_key('composer'):
652                                 if a:
653                                         header['composer'] = header['composer'] + '\\\\\\\\' + a
654                         else:
655                                 header['composer'] =  a
656                 if g == 'S':
657                         header ['subtitle'] = a
658                 if g == 'L':    # Default note length
659                         set_default_length (ln)
660                 if g == 'V':    # Voice 
661                         voice = re.sub (' .*$', '', a)
662                         rest = re.sub ('^[^ \t]*  *', '', a)
663                         if state.next_bar:
664                                 voices_append(state.next_bar)
665                                 state.next_bar = ''
666                         select_voice (voice, rest)
667                 if g == 'W':    # Words
668                         lyrics_append(a)
669                 if g == 'w':    # vocals
670                         slyrics_append (a)
671                 if g == 'Q':    #tempo
672                         try_parse_q (a)
673                 return ''
674         return ln
675
676 # we use in this order specified accidental, active accidental for bar,
677 # active accidental for key
678 def pitch_to_lilypond_name (name, acc, bar_acc, key):
679         s = ''
680         if acc == UNDEF:
681                 if not nobarlines:
682                         acc = bar_acc
683         if acc == UNDEF:
684                 acc = key
685         if acc == -1:
686                 s = 'es'
687         elif acc == 1:
688                 s =  'is'
689         
690         if name > 4:
691                 name = name -7
692         return(chr (name  + ord('c')) + s)
693
694
695 def octave_to_lilypond_quotes (o):
696         o = o + 2
697         s =''
698         if o < 0:
699                 o = -o
700                 s=','
701         else:
702                 s ='\''
703
704         return s * o
705
706 def parse_num (str):
707         durstr = ''
708         while str and str[0] in DIGITS:
709                 durstr = durstr + str[0]
710                 str = str[1:]
711
712         n = None
713         if durstr:
714                 n  =string.atoi (durstr) 
715         return (str,n)
716
717
718 def duration_to_lilypond_duration  (multiply_tup, defaultlen, dots):
719         base = 1
720         # (num /  den)  / defaultlen < 1/base
721         while base * multiply_tup[0] < multiply_tup[1]:
722                 base = base * 2
723         if base == 1:
724                 if (multiply_tup[0] / multiply_tup[1])  == 2:
725                         base = '\\breve'
726                 if (multiply_tup[0] / multiply_tup[1]) == 3:
727                         base = '\\breve'
728                         dots = 1
729                 if (multiply_tup[0] / multiply_tup[1]) == 4:
730                         base = '\longa'
731         return '%s%s' % ( base, '.'* dots)
732
733 class Parser_state:
734         def __init__ (self):
735                 self.in_acc = {}
736                 self.next_articulation = ''
737                 self.next_bar = ''
738                 self.next_dots = 0
739                 self.next_den = 1
740                 self.parsing_tuplet = 0
741                 self.plus_chord = 0
742                 self.base_octave = 0
743                 self.common_time = 0
744
745
746
747 # return (str, num,den,dots) 
748 def parse_duration (str, parser_state):
749         num = 0
750         den = parser_state.next_den
751         parser_state.next_den = 1
752
753         (str, num) = parse_num (str)
754         if not num:
755                 num = 1
756         if len(str):
757                 if str[0] == '/':
758                         if len(str[0]):
759                                 while str[:1] == '/':
760                                         str= str[1:]
761                                         d = 2
762                                         if str[0] in DIGITS:
763                                                 (str, d) =parse_num (str)
764
765                                         den = den * d
766
767         den = den * default_len
768         
769         current_dots = parser_state.next_dots
770         parser_state.next_dots = 0
771         if re.match ('[ \t]*[<>]', str):
772                 while str[0] in HSPACE:
773                         str = str[1:]
774                 while str[0] == '>':
775                         str = str [1:]
776                         current_dots = current_dots + 1
777                         parser_state.next_den = parser_state.next_den * 2
778                 
779                 while str[0] == '<':
780                         str = str [1:]
781                         den = den * 2
782                         parser_state.next_dots = parser_state.next_dots + 1
783
784
785
786         try_dots = [3, 2, 1]
787         for d in try_dots:
788                 f = 1 << d
789                 multiplier = (2*f-1)
790                 if num % multiplier == 0 and den % f == 0:
791                         num = num / multiplier
792                         den = den / f
793                         current_dots = current_dots + d
794                 
795         return (str, num,den,current_dots)
796
797
798 def try_parse_rest (str, parser_state):
799         if not str or str[0] <> 'z' and str[0] <> 'x':
800                 return str
801
802         __main__.lyric_idx = -1
803
804         if parser_state.next_bar:
805                 voices_append(parser_state.next_bar)
806                 parser_state.next_bar = ''
807
808         if str[0] == 'z':
809                 rest = 'r'
810         else:
811                 rest = 's'
812         str = str[1:]
813
814         (str, num,den,d) = parse_duration (str, parser_state)
815         voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
816         if parser_state.next_articulation:
817                 voices_append (parser_state.next_articulation)
818                 parser_state.next_articulation = ''
819
820         return str
821
822 artic_tbl = {
823         '.'  : '-.',
824          'T' : '^\\trill',
825          'H' : '^\\fermata',
826          'u' : '^\\upbow',
827          'K' : '^\\ltoe',
828          'k' : '^\\accent',
829          'M' : '^\\tenuto',
830          '~' : '^"~" ',
831          'J' : '',              # ignore slide
832          'R' : '',              # ignore roll
833          'v' : '^\\downbow'
834 }
835         
836 def try_parse_articulation (str, state):
837         while str and  artic_tbl.has_key(str[:1]):
838                 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
839                 if not artic_tbl[str[:1]]:
840                         sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
841
842                 str = str[1:]
843
844         
845                 
846         # s7m2 input doesnt care about spaces
847         if re.match('[ \t]*\(', str):
848                 str = string.lstrip (str)
849
850         slur_begin =0
851         while str[:1] =='(' and str[1] not in DIGITS:
852                 slur_begin = slur_begin + 1
853                 state.next_articulation = state.next_articulation + '('
854                 str = str[1:]
855
856         return str
857                 
858 #
859 # remember accidental for rest of bar
860 #
861 def set_bar_acc(note, octave, acc, state):
862         if acc == UNDEF:
863                 return
864         n_oct = note + octave * 7
865         state.in_acc[n_oct] = acc
866
867 # get accidental set in this bar or UNDEF if not set
868 def get_bar_acc(note, octave, state):
869         n_oct = note + octave * 7
870         if state.in_acc.has_key(n_oct):
871                 return(state.in_acc[n_oct])
872         else:
873                 return(UNDEF)
874
875 def clear_bar_acc(state):
876         for k in state.in_acc.keys():
877                 del state.in_acc[k]
878         
879
880                 
881 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP  !
882 def try_parse_note (str, parser_state):
883         mud = ''
884
885         slur_begin =0
886         if not str:
887                 return str
888
889         articulation =''
890         acc = UNDEF
891         if str[0] in '^=_':
892                 c = str[0]
893                 str = str[1:]
894                 if c == '^':
895                         acc = 1
896                 if c == '=':
897                         acc = 0
898                 if c == '_':
899                         acc = -1
900
901         octave = parser_state.base_octave
902         if str[0] in "ABCDEFG":
903                 str = string.lower (str[0]) + str[1:]
904                 octave = octave - 1
905
906
907         notename = 0
908         if str[0] in "abcdefg":
909                 notename = (ord(str[0]) - ord('a') + 5)%7
910                 str = str[1:]
911         else:
912                 return str              # failed; not a note!
913
914         
915         __main__.lyric_idx = -1
916
917         if parser_state.next_bar:
918                 voices_append(parser_state.next_bar)
919                 parser_state.next_bar = ''
920
921         while str[0] == ',':
922                  octave = octave - 1
923                  str = str[1:]
924         while str[0] == '\'':
925                  octave = octave + 1
926                  str = str[1:]
927
928         (str, num,den,current_dots) = parse_duration (str, parser_state)
929
930         if re.match('[ \t]*\)', str):
931                 str = string.lstrip (str)
932         
933         slur_end =0
934         while str[:1] ==')':
935                 slur_end = slur_end + 1
936                 str = str[1:]
937
938         
939         bar_acc = get_bar_acc(notename, octave, parser_state)
940         pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
941         oct = octave_to_lilypond_quotes (octave)
942         if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
943                 mod='!'
944         else:
945                 mod = ''
946         voices_append ("%s%s%s%s" %
947                 (pit, oct, mod,
948                  duration_to_lilypond_duration ((num,den), default_len, current_dots)))
949         
950         set_bar_acc(notename, octave, acc, parser_state)
951         if parser_state.next_articulation:
952                 articulation = articulation + parser_state.next_articulation
953                 parser_state.next_articulation = ''
954
955         voices_append (articulation)
956
957         if parser_state.parsing_tuplet:
958                 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
959                 if not parser_state.parsing_tuplet:
960                         voices_append ("}")
961         if slur_begin:
962                 voices_append ('-(' * slur_begin )
963         if slur_end:
964                 voices_append ('-)' *slur_end )
965
966
967
968         return str
969
970 def junk_space (str):
971         while str and str[0] in '\t\n ':
972                 str = str[1:]
973
974         return str
975
976
977 def try_parse_guitar_chord (str, state):
978         if str[:1] =='"':
979                 str = str[1:]
980                 gc = ''
981                 if str[0] == '_' or (str[0] == '^'):
982                         position = str[0]
983                         str = str[1:]
984                 else:
985                         position = '^'
986                 while str and str[0] != '"':
987                         gc = gc + str[0]
988                         str = str[1:]
989                         
990                 if str:
991                         str = str[1:]
992                 gc = re.sub('#', '\\#', gc)     # escape '#'s
993                 state.next_articulation = ("%c\"%s\"" % (position ,gc)) + state.next_articulation
994         return str
995
996 def try_parse_escape (str):
997         if not str or str [0] != '\\':
998                 return str
999         
1000         str = str[1:]
1001         if str[:1] =='K':
1002                 key_table = compute_key ()
1003         return str
1004
1005 #
1006 # |] thin-thick double bar line
1007 # || thin-thin double bar line
1008 # [| thick-thin double bar line
1009 # :| left repeat
1010 # |: right repeat
1011 # :: left-right repeat
1012 # |1 volta 1
1013 # |2 volta 2
1014 old_bar_dict = {
1015 '|]' : '|.',
1016 '||' : '||',
1017 '[|' : '||',
1018 ':|' : ':|',
1019 '|:' : '|:',
1020 '::' : ':|:',
1021 '|1' : '|',
1022 '|2' : '|',
1023 ':|2' : ':|',
1024 '|' :  '|'
1025 }
1026 bar_dict = {
1027  '|]' : '\\bar "|."',
1028  '||' : '\\bar "||"',
1029  '[|' : '\\bar "||"',
1030  ':|' : '}',
1031  '|:' : '\\repeat volta 2 {',
1032  '::' : '} \\repeat volta 2 {',
1033  '|1' : '} \\alternative{{',
1034  '|2' : '} {',
1035  ':|2' : '} {',
1036  '|' :  '\\bar "|"'
1037   }
1038
1039
1040 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1041 alternative_opener = ['|1', '|2', ':|2']
1042 repeat_ender = ['::', ':|']
1043 repeat_opener = ['::', '|:']
1044 in_repeat = [''] * 8
1045 doing_alternative = [''] * 8
1046 using_old = ''
1047
1048 def try_parse_bar (str,state):
1049         global in_repeat, doing_alternative, using_old
1050         do_curly = ''
1051         bs = None
1052         if current_voice_idx < 0:
1053                 select_voice ('default', '')
1054         # first try the longer one
1055         for trylen in [3,2,1]:
1056                 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1057                         s = str[:trylen]
1058                         if using_old:
1059                                 bs = "\\bar \"%s\"" % old_bar_dict[s]
1060                         else:
1061                                 bs = "%s" % bar_dict[s]
1062                         str = str[trylen:]
1063                         if s in alternative_opener:
1064                                 if not in_repeat[current_voice_idx]:
1065                                         using_old = 't'
1066                                         bs = "\\bar \"%s\"" % old_bar_dict[s]
1067                                 else:
1068                                         doing_alternative[current_voice_idx] = 't'
1069
1070                         if s in repeat_ender:
1071                                 if not in_repeat[current_voice_idx]:
1072                                         sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1073                                         repeat_prepend()
1074                                         in_repeat[current_voice_idx] = ''
1075                                 else:
1076                                         if doing_alternative[current_voice_idx]:
1077                                                 do_curly = 't'
1078                                 if using_old:
1079                                         bs = "\\bar \"%s\"" % old_bar_dict[s]
1080                                 else:
1081                                         bs =  bar_dict[s]
1082                                 doing_alternative[current_voice_idx] = ''
1083                                 in_repeat[current_voice_idx] = ''
1084                         if s in repeat_opener:
1085                                 in_repeat[current_voice_idx] = 't'
1086                                 if using_old:
1087                                         bs = "\\bar \"%s\"" % old_bar_dict[s]
1088                                 else:
1089                                         bs =  bar_dict[s]
1090                         break
1091         if str[:1] == '|':
1092                 state.next_bar = '|\n'
1093                 str = str[1:]
1094                 clear_bar_acc(state)
1095         
1096         if bs <> None or state.next_bar != '':
1097                 if state.parsing_tuplet:
1098                         state.parsing_tuplet =0
1099                         voices_append ('} ')
1100                 
1101         if bs <> None:
1102                 clear_bar_acc(state)
1103                 voices_append (bs)
1104                 if do_curly != '':
1105                         voices_append("} }")
1106                         do_curly = ''
1107         return str
1108
1109 def try_parse_tie (str):
1110         if str[:1] =='-':
1111                 str = str[1:]
1112                 voices_append (' ~ ')
1113         return str
1114
1115 def bracket_escape (str, state):
1116         m = re.match ( '^([^\]]*)] *(.*)$', str)
1117         if m:
1118                 cmd = m.group (1)
1119                 str = m.group (2)
1120                 try_parse_header_line (cmd, state)
1121         return str
1122
1123 def try_parse_chord_delims (str, state):
1124         if str[:1] =='[':
1125                 str = str[1:]
1126                 if re.match('[A-Z]:', str):     # bracket escape
1127                         return bracket_escape(str, state)
1128                 if state.next_bar:
1129                         voices_append(state.next_bar)
1130                         state.next_bar = ''
1131                 voices_append ('<')
1132
1133         if str[:1] == '+':
1134                 str = str[1:]
1135                 if state.plus_chord:
1136                         voices_append ('>')
1137                         state.plus_chord = 0
1138                 else:
1139                         if state.next_bar:
1140                                 voices_append(state.next_bar)
1141                                 state.next_bar = ''
1142                         voices_append ('<')
1143                         state.plus_chord = 1
1144
1145         ch = ''
1146         if str[:1] ==']':
1147                 str = str[1:]
1148                 ch = '>'
1149
1150         end = 0
1151         while str[:1] ==')':
1152                 end = end + 1
1153                 str = str[1:]
1154
1155         
1156         voices_append ("\\spanrequest \\stop \"slur\"" * end)
1157         voices_append (ch)
1158         return str
1159
1160 def try_parse_grace_delims (str, state):
1161         if str[:1] =='{':
1162                 if state.next_bar:
1163                         voices_append(state.next_bar)
1164                         state.next_bar = ''
1165                 str = str[1:]
1166                 voices_append ('\\grace { ')
1167
1168         if str[:1] =='}':
1169                 str = str[1:]
1170                 voices_append ('}')
1171
1172         return str
1173
1174 def try_parse_comment (str):
1175         global nobarlines
1176         if (str[0] == '%'):
1177                 if str[0:5] == '%MIDI':
1178 #the nobarlines option is necessary for an abc to lilypond translator for
1179 #exactly the same reason abc2midi needs it: abc requires the user to enter
1180 #the note that will be printed, and MIDI and lilypond expect entry of the
1181 #pitch that will be played.
1182 #
1183 #In standard 19th century musical notation, the algorithm for translating
1184 #between printed note and pitch involves using the barlines to determine
1185 #the scope of the accidentals.
1186 #
1187 #Since ABC is frequently used for music in styles that do not use this
1188 #convention, such as most music written before 1700, or ethnic music in
1189 #non-western scales, it is necessary to be able to tell a translator that
1190 #the barlines should not affect its interpretation of the pitch.  
1191                         if (string.find(str,'nobarlines') > 0):
1192                                 nobarlines = 1
1193                 elif str[0:3] == '%LY':
1194                         p = string.find(str, 'voices')
1195                         if (p > -1):
1196                                 voices_append(str[p+7:])
1197                                 voices_append("\n")
1198                         p = string.find(str, 'slyrics')
1199                         if (p > -1):
1200                                 slyrics_append(str[p+8:])
1201                         
1202 #write other kinds of appending  if we ever need them.                  
1203         return str
1204
1205 happy_count = 100
1206 def parse_file (fn):
1207         f = open (fn)
1208         ls = f.readlines ()
1209
1210         select_voice('default', '')
1211         lineno = 0
1212         sys.stderr.write ("Line ... ")
1213         sys.stderr.flush ()
1214         __main__.state = state_list[current_voice_idx]
1215         
1216         for ln in ls:
1217                 lineno = lineno + 1
1218
1219                 if not (lineno % happy_count):
1220                         sys.stderr.write ('[%d]'% lineno)
1221                         sys.stderr.flush ()
1222                 m = re.match  ('^([^%]*)%(.*)$',ln)  # add comments to current voice
1223                 if m:
1224                         if m.group(2):
1225                                 try_parse_comment(m.group(2))
1226                                 voices_append ('%% %s\n' % m.group(2))
1227                         ln = m.group (1)
1228
1229                 orig_ln = ln
1230                 
1231                 ln = try_parse_header_line (ln, state)
1232
1233                 # Try nibbling characters off until the line doesn't change.
1234                 prev_ln = ''
1235                 while ln != prev_ln:
1236                         prev_ln = ln
1237                         ln = try_parse_chord_delims (ln, state)
1238                         ln = try_parse_rest (ln, state)
1239                         ln = try_parse_articulation (ln,state)
1240                         ln = try_parse_note  (ln, state)
1241                         ln = try_parse_bar (ln, state)
1242                         ln = try_parse_tie (ln)
1243                         ln = try_parse_escape (ln)
1244                         ln = try_parse_guitar_chord (ln, state)
1245                         ln = try_parse_tuplet_begin (ln, state)
1246                         ln = try_parse_group_end (ln, state)
1247                         ln = try_parse_grace_delims (ln, state)
1248                         ln = junk_space (ln)
1249
1250                 if ln:
1251                         error ("%s: %d: Huh?  Don't understand\n" % (fn, lineno))
1252                         left = orig_ln[0:-len (ln)]
1253                         sys.stderr.write (left + '\n')
1254                         sys.stderr.write (' ' *  len (left) + ln + '\n')        
1255
1256
1257 def identify():
1258         sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1259
1260 def help ():
1261         print r"""
1262 Convert ABC to lilypond.
1263
1264 Usage: abc2ly [OPTIONS]... ABC-FILE
1265
1266 Options:
1267   -h, --help          this help
1268   -o, --output=FILE   set output filename to FILE
1269   -v, --version       version information
1270   -s, --strict        be strict about succes.
1271   
1272 This program converts ABC music files (see
1273 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) To LilyPond input.
1274
1275
1276 Report bugs to bug-lilypond@gnu.org
1277
1278 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>, Laura Conrad
1279 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>
1280 """
1281
1282 def print_version ():
1283         print r"""abc2ly (GNU lilypond) %s""" % version
1284
1285
1286
1287 (options, files) = getopt.getopt (sys.argv[1:], 'vo:hs', ['help','version', 'output=', 'strict'])
1288 out_filename = ''
1289
1290 for opt in options:
1291         o = opt[0]
1292         a = opt[1]
1293         if o== '--help' or o == '-h':
1294                 help ()
1295                 sys.exit (0)
1296         elif o == '--version' or o == '-v':
1297                 print_version ()
1298                 sys.exit(0)
1299         elif o == '--strict' or o == '-s':
1300                 strict = 1
1301         elif o == '--output' or o == '-o':
1302                 out_filename = a
1303         else:
1304                 print o
1305                 raise getopt.error
1306
1307 identify()
1308
1309 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1310 for f in files:
1311         if f == '-':
1312                 f = ''
1313
1314         sys.stderr.write ('Parsing `%s\'...\n' % f)
1315         parse_file (f)
1316
1317         if not out_filename:
1318                 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1319         sys.stderr.write ('lilypond output to: `%s\'...' % out_filename)
1320         outf = open (out_filename, 'w')
1321
1322 #       dump_global (outf)
1323         dump_header (outf ,header)
1324         dump_slyrics (outf)
1325         dump_voices (outf)
1326         dump_score (outf)
1327         dump_lyrics (outf)
1328         sys.stderr.write ('\n')
1329