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