]> git.donarmstrong.com Git - lilypond.git/blob - scripts/abc2ly.py
(out_filename): fix thinko with \version.
[lilypond.git] / scripts / abc2ly.py
1 #!@PYTHON@
2 # -*- coding: utf-8 -*-
3 # once upon a rainy monday afternoon.
4 #
5 #   ...
6 #
7 # (not finished.)
8 # ABC standard v1.6:  http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt
9 #
10 # Enhancements  (Roy R. Rankin)
11 #
12 # Header section moved to top of lilypond file
13 # handle treble, treble-8, alto, and bass clef
14 # Handle voices (V: headers) with clef and part names, multiple voices
15 # Handle w: lyrics with multiple verses
16 # Handle key mode names for minor, major, phrygian, ionian, locrian, aeolian,
17 #     mixolydian, lydian, dorian
18 # Handle part names from V: header
19 # Tuplets handling fixed up
20 # Lines starting with |: not discarded as header lines
21 # Multiple T: and C: header entries handled
22 # Accidental maintained until next bar check
23 # Silent rests supported
24 # articulations fermata, upbow, downbow, ltoe, accent, tenuto supported
25 # Chord strings([-^]"string") can contain a '#'
26 # Header fields enclosed by [] in notes string processed
27 # W: words output after tune as abc2ps does it (they failed before)
28
29 # Enhancements (Laura Conrad)
30 #
31 # Barring now preserved between ABC and lilypond
32 # the default placement for text in abc is above the staff.
33 # %%LY now supported.
34 # \breve and \longa supported.
35 # M:none doesn't crash lily.
36
37 # Enhancements (Guy Gascoigne-Piggford)
38 #
39 # Add support for maintaining ABC's notion of beaming, this is selectable
40 # from the command line with a -b or --beam option.
41 # Fixd a problem where on cygwin empty lines weren't being correctly identifed
42 # and so were complaining, but still generating the correct output.
43
44 # Limitations
45 #
46 # Multiple tunes in single file not supported
47 # Blank T: header lines should write score and open a new score
48 # Not all header fields supported
49 # ABC line breaks are ignored
50 # Block comments generate error and are ignored
51 # Postscript commands are ignored
52 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
53 # %%LY slyrics can't be directly before a w: line.
54 # ???
55
56
57
58 #TODO:
59 #
60 # * lilylib
61 # * GNU style messages:  warning:FILE:LINE:
62 # * l10n
63
64 # Convert to new chord styles.
65 #
66 # UNDEF -> None
67 #
68   
69
70 import __main__
71 import getopt
72 import sys
73 import re
74 import string
75 import os
76
77 program_name = sys.argv[0]
78
79 version = '@TOPLEVEL_VERSION@'
80 if version == '@' + 'TOPLEVEL_VERSION' + '@':
81         version = '(unknown version)'           # uGUHGUHGHGUGH  
82
83 UNDEF = 255
84 state = UNDEF
85 strict = 0
86 preserve_beams = 0
87 voice_idx_dict = {}
88 header = {}
89 header['footnotes'] = ''
90 lyrics = []
91 slyrics = []
92 voices = []
93 state_list = []
94 repeat_state = [0] * 8
95 current_voice_idx = -1
96 current_lyric_idx = -1
97 lyric_idx = -1
98 part_names = 0
99 default_len = 8
100 length_specified = 0
101 nobarlines = 0
102 global_key = [0] * 7                    # UGH
103 names = ["One", "Two", "Three"]
104 DIGITS='0123456789'
105 HSPACE=' \t'
106 midi_specs = ''
107
108
109 def error (msg):
110         sys.stderr.write (msg)
111         if strict:
112                 sys.exit (1)
113         
114
115 def alphabet (i):
116         return chr (i + ord('A'))
117         
118 def check_clef(s):
119         if not s:
120                 return ''
121         if re.match('-8va', s) or re.match('treble8', s):
122                 # treble8 is used by abctab2ps; -8va is used by barfly,
123                 # and by my patch to abc2ps. If there's ever a standard
124                 # about this we'll support that.
125                 s = s[4:]
126                 state.base_octave = -1
127                 voices_append("\\clef \"G_8\"\n")
128         elif re.match('^treble', s):
129                 s = s[6:]
130                 if re.match ('^-8', s):
131                         s = s[2:]
132                         state.base_octave = -2
133                         voices_append("\\clef \"G_8\"\n")
134                 else:
135                         state.base_octave = 0
136                         voices_append("\\clef treble\n")
137         elif re.match('^alto', s):
138                 s = s[4:]
139                 state.base_octave = -1
140                 voices_append ("\\clef alto\n" )
141         elif re.match('^bass',s ):
142                 s = s[4:]
143                 state.base_octave = -2
144                 voices_append ("\\clef bass\n" )
145         return s
146
147 def select_voice (name, rol):
148         if not voice_idx_dict.has_key (name):
149                 state_list.append(Parser_state())
150                 voices.append ('')
151                 slyrics.append ([])
152                 voice_idx_dict[name] = len (voices) -1
153         __main__.current_voice_idx =  voice_idx_dict[name]
154         __main__.state = state_list[current_voice_idx]
155         while rol != '':
156                 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
157                 if m:
158                         keyword = m.group(1)
159                         rol = m.group (2)
160                         a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
161                         if a:
162                                 value = a.group (1)
163                                 rol = a.group ( 2)
164                                 if keyword == 'clef':
165                                         check_clef(value)
166                                 elif keyword == "name":
167                                         value = re.sub ('\\\\','\\\\\\\\', value)
168                                         ## < 2.2
169                                         voices_append ("\\set Staff.instrument = %s\n" % value )
170                                         
171                                         __main__.part_names = 1
172                                 elif keyword == "sname" or keyword == "snm":
173                                         voices_append ("\\set Staff.instr = %s\n" % value )
174                 else:
175                         break
176
177 def dump_header (outf,hdr):
178         outf.write ('\\header {\n')
179         ks = hdr.keys ()
180         ks.sort ()
181         for k in ks:
182                 hdr[k] = re.sub('"', '\\"', hdr[k])             
183                 outf.write ('\t%s = "%s"\n'% (k,hdr[k]))
184         outf.write ('}')
185
186 def dump_lyrics (outf):
187         if (len(lyrics)):
188                 outf.write("\n\\score\n{\n \\lyrics\n <<\n")
189                 for i in range (len (lyrics)):
190                         outf.write ( lyrics [i])
191                         outf.write ("\n")
192                 outf.write("    >>\n    \\layout{}\n}\n")
193
194 def dump_default_bar (outf):
195         """
196         Nowadays abc2ly outputs explicits barlines (?)
197         """
198         ## < 2.2
199         outf.write ("\n\\set Score.defaultBarType = \"empty\"\n")
200
201
202 def dump_slyrics (outf):
203         ks = voice_idx_dict.keys()
204         ks.sort ()
205         for k in ks:
206                 if re.match('[1-9]', k):
207                         m = alphabet(string.atoi(k))
208                 else:
209                         m = k
210                 for i in range (len(slyrics[voice_idx_dict[k]])):
211                         l= alphabet(i)
212                         outf.write ("\nwords%sV%s = \lyricmode {" % (m, l))
213                         outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
214                         outf.write ("\n}")
215
216 def dump_voices (outf):
217         global doing_alternative, in_repeat
218         ks = voice_idx_dict.keys()
219         ks.sort ()
220         for k in ks:
221                 if re.match ('[1-9]', k):
222                         m = alphabet(string.atoi(k))
223                 else:
224                         m = k
225                 outf.write ("\nvoice%s =  {" % m)
226                 dump_default_bar(outf)
227                 if repeat_state[voice_idx_dict[k]]:
228                         outf.write("\n\\repeat volta 2 {")
229                 outf.write ("\n" + voices [voice_idx_dict[k]])
230                 if not using_old:
231                         if doing_alternative[voice_idx_dict[k]]:
232                                 outf.write("}")
233                         if in_repeat[voice_idx_dict[k]]:
234                                 outf.write("}")
235                 outf.write ("\n}")
236
237 def try_parse_q(a):
238         global midi_specs
239         #assume that Q takes the form "Q:1/4=120"
240         #There are other possibilities, but they are deprecated
241         if string.count(a, '/') == 1:
242                 array=string.split(a,'/')
243                 numerator=array[0]
244                 if numerator != 1:
245                         sys.stderr.write("abc2ly: Warning, unable to translate a Q specification with a numerator of %s: %s\n" % (numerator, a))
246                 array2=string.split(array[1],'=')
247                 denominator=array2[0]
248                 perminute=array2[1]
249                 duration=str(string.atoi(denominator)/string.atoi(numerator))
250                 midi_specs=string.join(["\\tempo", duration, "=", perminute])
251         else:
252                 sys.stderr.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a)
253         
254 def dump_score (outf):
255         outf.write (r"""
256
257 \score{
258          <<
259 """)
260
261         ks = voice_idx_dict.keys ();
262         ks.sort ()
263         for k in  ks:
264                 if re.match('[1-9]', k):
265                         m = alphabet (string.atoi(k))
266                 else:
267                         m = k
268                 if k == 'default' and len (voice_idx_dict) > 1:
269                         break
270                 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k ) 
271                 if k != 'default':
272                         outf.write ("\t    \\voicedefault\n")
273                 outf.write ("\t    \\voice%s " % m)
274                 outf.write ("\n\t}\n")
275
276                 l = ord( 'A' )
277                 for lyrics in slyrics [voice_idx_dict[k]]:
278                         outf.write ("\n\t\\addlyrics { \n")
279                         if re.match('[1-9]',k):
280                                 m = alphabet (string.atoi(k))
281                         else:
282                                 m = k
283
284                         outf.write ( " \\words%sV%s } " % ( m, chr (l)) )
285                         l += 1
286
287         outf.write ("\n    >>")
288         outf.write ("\n\t\\layout {\n")
289         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                                                 # the non-ascii character
640                                                 # in the string below is a
641                                                 # punctuation dash. (TeX ---)
642                                                 header['title'] = header['title'] + ' â€” ' + a
643                                         else:
644                                                 header['subtitle'] = a
645                         else:
646                                 header['title'] =  a
647                 if g == 'M':    # Meter
648                         if a == 'C':
649                                 if not state.common_time:
650                                         state.common_time = 1
651                                         voices_append (" \\override Staff.TimeSignature #\'style = #'C\n")
652                                 a = '4/4'
653                         if a == 'C|':
654                                 if not state.common_time:
655                                         state.common_time = 1
656                                         voices_append ("\\override Staff.TimeSignature #\'style = #'C\n")
657                                 a = '2/2'
658                         if not length_specified:
659                                 set_default_len_from_time_sig (a)
660                         else:
661                                 length_specified = 0
662                         if not a == 'none':
663                                 voices_append ('\\time %s' % a)
664                         state.next_bar = ''
665                 if g == 'K': # KEY
666                         a = check_clef(a)
667                         if a:
668                                 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
669                                 if m:
670                                         # there may or may not be a space
671                                         # between the key letter and the mode
672                                         if key_lookup.has_key(m.group(2)[0:3]):
673                                                 key_info = m.group(1) + m.group(2)[0:3]
674                                                 clef_info = m.group(2)[4:]
675                                         else:
676                                                 key_info = m.group(1)
677                                                 clef_info = m.group(2)
678                                         __main__.global_key  = compute_key (key_info)
679                                         k = lily_key (key_info)
680                                         if k:
681                                                 voices_append ('\\key %s' % k)
682                                         check_clef(clef_info)
683                                 else:
684                                         __main__.global_key  = compute_key (a)
685                                         k = lily_key (a)
686                                         if k:
687                                                 voices_append ('\\key %s \\major' % k)
688                 if g == 'N': # Notes
689                         header ['footnotes'] = header['footnotes'] +  '\\\\\\\\' + a
690                 if g == 'O': # Origin
691                         header ['origin'] = a
692                 if g == 'X': # Reference Number
693                         header ['crossRefNumber'] = a
694                 if g == 'A': #  Area
695                         header ['area'] = a
696                 if g == 'H':    # History
697                         header_append ('history', a)
698                 if g == 'B':    # Book
699                         header ['book'] = a
700                 if g == 'C':    # Composer
701                         if header.has_key('composer'):
702                                 if a:
703                                         header['composer'] = header['composer'] + '\\\\\\\\' + a
704                         else:
705                                 header['composer'] =  a
706                 if g == 'S':
707                         header ['subtitle'] = a
708                 if g == 'L':    # Default note length
709                         set_default_length (ln)
710                 if g == 'V':    # Voice 
711                         voice = re.sub (' .*$', '', a)
712                         rest = re.sub ('^[^ \t]*  *', '', a)
713                         if state.next_bar:
714                                 voices_append(state.next_bar)
715                                 state.next_bar = ''
716                         select_voice (voice, rest)
717                 if g == 'W':    # Words
718                         lyrics_append(a)
719                 if g == 'w':    # vocals
720                         slyrics_append (a)
721                 if g == 'Q':    #tempo
722                         try_parse_q (a)
723                 return ''
724         return ln
725
726 # we use in this order specified accidental, active accidental for bar,
727 # active accidental for key
728 def pitch_to_lilypond_name (name, acc, bar_acc, key):
729         s = ''
730         if acc == UNDEF:
731                 if not nobarlines:
732                         acc = bar_acc
733         if acc == UNDEF:
734                 acc = key
735         if acc == -1:
736                 s = 'es'
737         elif acc == 1:
738                 s =  'is'
739         
740         if name > 4:
741                 name = name -7
742         return(chr (name  + ord('c')) + s)
743
744
745 def octave_to_lilypond_quotes (o):
746         o = o + 2
747         s =''
748         if o < 0:
749                 o = -o
750                 s=','
751         else:
752                 s ='\''
753
754         return s * o
755
756 def parse_num (str):
757         durstr = ''
758         while str and str[0] in DIGITS:
759                 durstr = durstr + str[0]
760                 str = str[1:]
761
762         n = None
763         if durstr:
764                 n  =string.atoi (durstr) 
765         return (str,n)
766
767
768 def duration_to_lilypond_duration  (multiply_tup, defaultlen, dots):
769         base = 1
770         # (num /  den)  / defaultlen < 1/base
771         while base * multiply_tup[0] < multiply_tup[1]:
772                 base = base * 2
773         if base == 1:
774                 if (multiply_tup[0] / multiply_tup[1])  == 2:
775                         base = '\\breve'
776                 if (multiply_tup[0] / multiply_tup[1]) == 3:
777                         base = '\\breve'
778                         dots = 1
779                 if (multiply_tup[0] / multiply_tup[1]) == 4:
780                         base = '\longa'
781         return '%s%s' % ( base, '.'* dots)
782
783 class Parser_state:
784         def __init__ (self):
785                 self.in_acc = {}
786                 self.next_articulation = ''
787                 self.next_bar = ''
788                 self.next_dots = 0
789                 self.next_den = 1
790                 self.parsing_tuplet = 0
791                 self.plus_chord = 0
792                 self.base_octave = 0
793                 self.common_time = 0
794                 self.parsing_beam = 0
795
796
797
798 # return (str, num,den,dots) 
799 def parse_duration (str, parser_state):
800         num = 0
801         den = parser_state.next_den
802         parser_state.next_den = 1
803
804         (str, num) = parse_num (str)
805         if not num:
806                 num = 1
807         if len(str):
808                 if str[0] == '/':
809                         if len(str[0]):
810                                 while str[:1] == '/':
811                                         str= str[1:]
812                                         d = 2
813                                         if str[0] in DIGITS:
814                                                 (str, d) =parse_num (str)
815
816                                         den = den * d
817
818         den = den * default_len
819         
820         current_dots = parser_state.next_dots
821         parser_state.next_dots = 0
822         if re.match ('[ \t]*[<>]', str):
823                 while str[0] in HSPACE:
824                         str = str[1:]
825                 while str[0] == '>':
826                         str = str [1:]
827                         current_dots = current_dots + 1
828                         parser_state.next_den = parser_state.next_den * 2
829                 
830                 while str[0] == '<':
831                         str = str [1:]
832                         den = den * 2
833                         parser_state.next_dots = parser_state.next_dots + 1
834
835
836
837         try_dots = [3, 2, 1]
838         for d in try_dots:
839                 f = 1 << d
840                 multiplier = (2*f-1)
841                 if num % multiplier == 0 and den % f == 0:
842                         num = num / multiplier
843                         den = den / f
844                         current_dots = current_dots + d
845                 
846         return (str, num,den,current_dots)
847
848
849 def try_parse_rest (str, parser_state):
850         if not str or str[0] <> 'z' and str[0] <> 'x':
851                 return str
852
853         __main__.lyric_idx = -1
854
855         if parser_state.next_bar:
856                 voices_append(parser_state.next_bar)
857                 parser_state.next_bar = ''
858
859         if str[0] == 'z':
860                 rest = 'r'
861         else:
862                 rest = 's'
863         str = str[1:]
864
865         (str, num,den,d) = parse_duration (str, parser_state)
866         voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
867         if parser_state.next_articulation:
868                 voices_append (parser_state.next_articulation)
869                 parser_state.next_articulation = ''
870
871         return str
872
873 artic_tbl = {
874         '.'  : '-.',
875          'T' : '^\\trill',
876          'H' : '^\\fermata',
877          'u' : '^\\upbow',
878          'K' : '^\\ltoe',
879          'k' : '^\\accent',
880          'M' : '^\\tenuto',
881          '~' : '^"~" ',
882          'J' : '',              # ignore slide
883          'R' : '',              # ignore roll
884          'v' : '^\\downbow'
885 }
886         
887 def try_parse_articulation (str, state):
888         while str and  artic_tbl.has_key(str[:1]):
889                 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
890                 if not artic_tbl[str[:1]]:
891                         sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
892
893                 str = str[1:]
894
895         
896                 
897         # s7m2 input doesnt care about spaces
898         if re.match('[ \t]*\(', str):
899                 str = string.lstrip (str)
900
901         slur_begin =0
902         while str[:1] =='(' and str[1] not in DIGITS:
903                 slur_begin = slur_begin + 1
904                 state.next_articulation = state.next_articulation + '('
905                 str = str[1:]
906
907         return str
908                 
909 #
910 # remember accidental for rest of bar
911 #
912 def set_bar_acc(note, octave, acc, state):
913         if acc == UNDEF:
914                 return
915         n_oct = note + octave * 7
916         state.in_acc[n_oct] = acc
917
918 # get accidental set in this bar or UNDEF if not set
919 def get_bar_acc(note, octave, state):
920         n_oct = note + octave * 7
921         if state.in_acc.has_key(n_oct):
922                 return(state.in_acc[n_oct])
923         else:
924                 return(UNDEF)
925
926 def clear_bar_acc(state):
927         for k in state.in_acc.keys():
928                 del state.in_acc[k]
929         
930
931 # if we are parsing a beam, close it off
932 def close_beam_state(state):
933         if state.parsing_beam and preserve_beams:
934                 state.parsing_beam = 0
935                 voices_append_back( ']' )
936
937                 
938 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP  !
939 def try_parse_note (str, parser_state):
940         mud = ''
941
942         slur_begin =0
943         if not str:
944                 return str
945
946         articulation =''
947         acc = UNDEF
948         if str[0] in '^=_':
949                 c = str[0]
950                 str = str[1:]
951                 if c == '^':
952                         acc = 1
953                 if c == '=':
954                         acc = 0
955                 if c == '_':
956                         acc = -1
957
958         octave = parser_state.base_octave
959         if str[0] in "ABCDEFG":
960                 str = string.lower (str[0]) + str[1:]
961                 octave = octave - 1
962
963
964         notename = 0
965         if str[0] in "abcdefg":
966                 notename = (ord(str[0]) - ord('a') + 5)%7
967                 str = str[1:]
968         else:
969                 return str              # failed; not a note!
970
971         
972         __main__.lyric_idx = -1
973
974         if parser_state.next_bar:
975                 voices_append(parser_state.next_bar)
976                 parser_state.next_bar = ''
977
978         while str[0] == ',':
979                  octave = octave - 1
980                  str = str[1:]
981         while str[0] == '\'':
982                  octave = octave + 1
983                  str = str[1:]
984
985         (str, num,den,current_dots) = parse_duration (str, parser_state)
986
987         if re.match('[ \t]*\)', str):
988                 str = string.lstrip (str)
989         
990         slur_end =0
991         while str[:1] ==')':
992                 slur_end = slur_end + 1
993                 str = str[1:]
994
995         
996         bar_acc = get_bar_acc(notename, octave, parser_state)
997         pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
998         oct = octave_to_lilypond_quotes (octave)
999         if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
1000                 mod='!'
1001         else:
1002                 mod = ''
1003         voices_append ("%s%s%s%s" %
1004                 (pit, oct, mod,
1005                  duration_to_lilypond_duration ((num,den), default_len, current_dots)))
1006         
1007         set_bar_acc(notename, octave, acc, parser_state)
1008         if parser_state.next_articulation:
1009                 articulation = articulation + parser_state.next_articulation
1010                 parser_state.next_articulation = ''
1011
1012         voices_append (articulation)
1013
1014         if parser_state.parsing_tuplet:
1015                 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
1016                 if not parser_state.parsing_tuplet:
1017                         voices_append ("}")
1018         if slur_begin:
1019                 voices_append ('-(' * slur_begin )
1020         if slur_end:
1021                 voices_append ('-)' *slur_end )
1022
1023         if preserve_beams and \
1024            str[0] in '^=_ABCDEFGabcdefg' and \
1025            not parser_state.parsing_beam and \
1026            not parser_state.parsing_tuplet:
1027                 parser_state.parsing_beam = 1
1028                 voices_append_back( '[' )
1029                 
1030         return str
1031
1032 def junk_space (str,state):
1033         while str and str[0] in '\t\n\r ':
1034                 str = str[1:]
1035                 close_beam_state(state)
1036
1037         return str
1038
1039
1040 def try_parse_guitar_chord (str, state):
1041         if str[:1] =='"':
1042                 str = str[1:]
1043                 gc = ''
1044                 if str[0] == '_' or (str[0] == '^'):
1045                         position = str[0]
1046                         str = str[1:]
1047                 else:
1048                         position = '^'
1049                 while str and str[0] != '"':
1050                         gc = gc + str[0]
1051                         str = str[1:]
1052                         
1053                 if str:
1054                         str = str[1:]
1055                 gc = re.sub('#', '\\#', gc)     # escape '#'s
1056                 state.next_articulation = ("%c\"%s\"" % (position, gc)) \
1057                                           + state.next_articulation
1058         return str
1059
1060 def try_parse_escape (str):
1061         if not str or str [0] != '\\':
1062                 return str
1063         
1064         str = str[1:]
1065         if str[:1] =='K':
1066                 key_table = compute_key ()
1067         return str
1068
1069 #
1070 # |] thin-thick double bar line
1071 # || thin-thin double bar line
1072 # [| thick-thin double bar line
1073 # :| left repeat
1074 # |: right repeat
1075 # :: left-right repeat
1076 # |1 volta 1
1077 # |2 volta 2
1078 old_bar_dict = {
1079 '|]' : '|.',
1080 '||' : '||',
1081 '[|' : '||',
1082 ':|' : ':|',
1083 '|:' : '|:',
1084 '::' : ':|:',
1085 '|1' : '|',
1086 '|2' : '|',
1087 ':|2' : ':|',
1088 '|' :  '|'
1089 }
1090 bar_dict = {
1091  '|]' : '\\bar "|."',
1092  '||' : '\\bar "||"',
1093  '[|' : '\\bar "||"',
1094  ':|' : '}',
1095  '|:' : '\\repeat volta 2 {',
1096  '::' : '} \\repeat volta 2 {',
1097  '|1' : '} \\alternative{{',
1098  '|2' : '} {',
1099  ':|2' : '} {',
1100  '|' :  '\\bar "|"'
1101   }
1102
1103
1104 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1105 alternative_opener = ['|1', '|2', ':|2']
1106 repeat_ender = ['::', ':|']
1107 repeat_opener = ['::', '|:']
1108 in_repeat = [''] * 8
1109 doing_alternative = [''] * 8
1110 using_old = ''
1111
1112 def try_parse_bar (str,state):
1113         global in_repeat, doing_alternative, using_old
1114         do_curly = ''
1115         bs = None
1116         if current_voice_idx < 0:
1117                 select_voice ('default', '')
1118         # first try the longer one
1119         for trylen in [3,2,1]:
1120                 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1121                         s = str[:trylen]
1122                         if using_old:
1123                                 bs = "\\bar \"%s\"" % old_bar_dict[s]
1124                         else:
1125                                 bs = "%s" % bar_dict[s]
1126                         str = str[trylen:]
1127                         if s in alternative_opener:
1128                                 if not in_repeat[current_voice_idx]:
1129                                         using_old = 't'
1130                                         bs = "\\bar \"%s\"" % old_bar_dict[s]
1131                                 else:
1132                                         doing_alternative[current_voice_idx] = 't'
1133
1134                         if s in repeat_ender:
1135                                 if not in_repeat[current_voice_idx]:
1136                                         sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1137                                         repeat_prepend()
1138                                         in_repeat[current_voice_idx] = ''
1139                                 else:
1140                                         if doing_alternative[current_voice_idx]:
1141                                                 do_curly = 't'
1142                                 if using_old:
1143                                         bs = "\\bar \"%s\"" % old_bar_dict[s]
1144                                 else:
1145                                         bs =  bar_dict[s]
1146                                 doing_alternative[current_voice_idx] = ''
1147                                 in_repeat[current_voice_idx] = ''
1148                         if s in repeat_opener:
1149                                 in_repeat[current_voice_idx] = 't'
1150                                 if using_old:
1151                                         bs = "\\bar \"%s\"" % old_bar_dict[s]
1152                                 else:
1153                                         bs =  bar_dict[s]
1154                         break
1155         if str[:1] == '|':
1156                 state.next_bar = '|\n'
1157                 str = str[1:]
1158                 clear_bar_acc(state)
1159                 close_beam_state(state)
1160         
1161         if bs <> None or state.next_bar != '':
1162                 if state.parsing_tuplet:
1163                         state.parsing_tuplet =0
1164                         voices_append ('} ')
1165                 
1166         if bs <> None:
1167                 clear_bar_acc(state)
1168                 close_beam_state(state)
1169                 voices_append (bs)
1170                 if do_curly != '':
1171                         voices_append("} }")
1172                         do_curly = ''
1173         return str
1174
1175 def try_parse_tie (str):
1176         if str[:1] =='-':
1177                 str = str[1:]
1178                 voices_append (' ~ ')
1179         return str
1180
1181 def bracket_escape (str, state):
1182         m = re.match ( '^([^\]]*)] *(.*)$', str)
1183         if m:
1184                 cmd = m.group (1)
1185                 str = m.group (2)
1186                 try_parse_header_line (cmd, state)
1187         return str
1188
1189 def try_parse_chord_delims (str, state):
1190         if str[:1] =='[':
1191                 str = str[1:]
1192                 if re.match('[A-Z]:', str):     # bracket escape
1193                         return bracket_escape(str, state)
1194                 if state.next_bar:
1195                         voices_append(state.next_bar)
1196                         state.next_bar = ''
1197                 voices_append ('<<')
1198
1199         if str[:1] == '+':
1200                 str = str[1:]
1201                 if state.plus_chord:
1202                         voices_append ('>>')
1203                         state.plus_chord = 0
1204                 else:
1205                         if state.next_bar:
1206                                 voices_append(state.next_bar)
1207                                 state.next_bar = ''
1208                         voices_append ('<<')
1209                         state.plus_chord = 1
1210
1211         ch = ''
1212         if str[:1] ==']':
1213                 str = str[1:]
1214                 ch = '>>'
1215
1216         end = 0
1217         while str[:1] ==')':
1218                 end = end + 1
1219                 str = str[1:]
1220
1221         
1222         voices_append ("\\spanrequest \\stop \"slur\"" * end)
1223         voices_append (ch)
1224         return str
1225
1226 def try_parse_grace_delims (str, state):
1227         if str[:1] =='{':
1228                 if state.next_bar:
1229                         voices_append(state.next_bar)
1230                         state.next_bar = ''
1231                 str = str[1:]
1232                 voices_append ('\\grace { ')
1233
1234         if str[:1] =='}':
1235                 str = str[1:]
1236                 voices_append ('}')
1237
1238         return str
1239
1240 def try_parse_comment (str):
1241         global nobarlines
1242         if (str[0] == '%'):
1243                 if str[0:5] == '%MIDI':
1244 #the nobarlines option is necessary for an abc to lilypond translator for
1245 #exactly the same reason abc2midi needs it: abc requires the user to enter
1246 #the note that will be printed, and MIDI and lilypond expect entry of the
1247 #pitch that will be played.
1248 #
1249 #In standard 19th century musical notation, the algorithm for translating
1250 #between printed note and pitch involves using the barlines to determine
1251 #the scope of the accidentals.
1252 #
1253 #Since ABC is frequently used for music in styles that do not use this
1254 #convention, such as most music written before 1700, or ethnic music in
1255 #non-western scales, it is necessary to be able to tell a translator that
1256 #the barlines should not affect its interpretation of the pitch.  
1257                         if (string.find(str,'nobarlines') > 0):
1258                                 nobarlines = 1
1259                 elif str[0:3] == '%LY':
1260                         p = string.find(str, 'voices')
1261                         if (p > -1):
1262                                 voices_append(str[p+7:])
1263                                 voices_append("\n")
1264                         p = string.find(str, 'slyrics')
1265                         if (p > -1):
1266                                 slyrics_append(str[p+8:])
1267                         
1268 #write other kinds of appending  if we ever need them.                  
1269         return str
1270
1271 lineno = 0
1272 happy_count = 100
1273 def parse_file (fn):
1274         f = open (fn)
1275         ls = f.readlines ()
1276         ls = map (lambda x: re.sub ("\r$", '', x), ls)
1277
1278         select_voice('default', '')
1279         global lineno
1280         lineno = 0
1281         sys.stderr.write ("Line ... ")
1282         sys.stderr.flush ()
1283         __main__.state = state_list[current_voice_idx]
1284         
1285         for ln in ls:
1286                 lineno = lineno + 1
1287
1288                 if not (lineno % happy_count):
1289                         sys.stderr.write ('[%d]'% lineno)
1290                         sys.stderr.flush ()
1291                 m = re.match  ('^([^%]*)%(.*)$',ln)  # add comments to current voice
1292                 if m:
1293                         if m.group(2):
1294                                 try_parse_comment(m.group(2))
1295                                 voices_append ('%% %s\n' % m.group(2))
1296                         ln = m.group (1)
1297
1298                 orig_ln = ln
1299                 
1300                 ln = try_parse_header_line (ln, state)
1301
1302                 # Try nibbling characters off until the line doesn't change.
1303                 prev_ln = ''
1304                 while ln != prev_ln:
1305                         prev_ln = ln
1306                         ln = try_parse_chord_delims (ln, state)
1307                         ln = try_parse_rest (ln, state)
1308                         ln = try_parse_articulation (ln,state)
1309                         ln = try_parse_note  (ln, state)
1310                         ln = try_parse_bar (ln, state)
1311                         ln = try_parse_tie (ln)
1312                         ln = try_parse_escape (ln)
1313                         ln = try_parse_guitar_chord (ln, state)
1314                         ln = try_parse_tuplet_begin (ln, state)
1315                         ln = try_parse_group_end (ln, state)
1316                         ln = try_parse_grace_delims (ln, state)
1317                         ln = junk_space (ln, state)
1318
1319                 if ln:
1320                         error ("%s: %d: Huh?  Don't understand\n" % (fn, lineno))
1321                         left = orig_ln[0:-len (ln)]
1322                         sys.stderr.write (left + '\n')
1323                         sys.stderr.write (' ' *  len (left) + ln + '\n')        
1324
1325
1326 def identify():
1327         sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1328
1329 def help ():
1330         print r"""
1331 Convert ABC to lilypond.
1332
1333 Usage: abc2ly [OPTIONS]... ABC-FILE
1334
1335 Options:
1336   -h, --help          print this help
1337   -o, --output=FILE   set output filename to FILE
1338   -v, --version       show version information
1339   -s, --strict        be strict about succes
1340   -b, --beams         preserve ABC's notion of beams
1341   
1342 This program converts ABC music files (see
1343 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) to LilyPond input.
1344
1345
1346 Report bugs to bug-lilypond@gnu.org.
1347
1348 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>, Laura Conrad
1349 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1350 """
1351
1352 def print_version ():
1353         print r"""abc2ly (GNU lilypond) %s""" % version
1354
1355
1356
1357 (options, files) = getopt.getopt (sys.argv[1:], 'vo:hsb', ['help','version', 'output=', 'strict', 'beams'])
1358 out_filename = ''
1359
1360 for opt in options:
1361         o = opt[0]
1362         a = opt[1]
1363         if o== '--help' or o == '-h':
1364                 help ()
1365                 sys.exit (0)
1366         elif o == '--version' or o == '-v':
1367                 print_version ()
1368                 sys.exit(0)
1369         elif o == '--strict' or o == '-s':
1370                 strict = 1
1371         elif o == '--output' or o == '-o':
1372                 out_filename = a
1373         elif o == '--beams' or o == '-b':
1374                 preserve_beams = 1
1375         else:
1376                 print o
1377                 raise getopt.error
1378
1379 identify()
1380
1381 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1382 for f in files:
1383         if f == '-':
1384                 f = ''
1385
1386         sys.stderr.write ('Parsing `%s\'...\n' % f)
1387         parse_file (f)
1388
1389         if not out_filename:
1390                 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1391         sys.stderr.write ('lilypond output to: `%s\'...' % out_filename)
1392         outf = open (out_filename, 'w')
1393
1394 # don't substitute @VERSION@. We want this to reflect
1395 # the last version that was verified to work.
1396         outf.write ('\\version "2.5.20"\n')
1397
1398 #       dump_global (outf)
1399         dump_header (outf, header)
1400         dump_slyrics (outf)
1401         dump_voices (outf)
1402         dump_score (outf)
1403         dump_lyrics (outf)
1404         sys.stderr.write ('\n')
1405