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