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