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