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