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