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