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