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