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