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