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