2 # -*- coding: utf-8 -*-
3 # once upon a rainy monday afternoon.
8 # ABC standard v1.6: http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt
10 # Enhancements (Roy R. Rankin)
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)
29 # Enhancements (Laura Conrad)
31 # Barring now preserved between ABC and lilypond
32 # the default placement for text in abc is above the staff.
34 # \breve and \longa supported.
35 # M:none doesn't crash lily.
37 # Enhancements (Guy Gascoigne-Piggford)
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.
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.
61 # * GNU style messages: warning:FILE:LINE:
64 # Convert to new chord styles.
77 program_name = sys.argv[0]
79 version = '@TOPLEVEL_VERSION@'
80 if version == '@' + 'TOPLEVEL_VERSION' + '@':
81 version = '(unknown version)' # uGUHGUHGHGUGH
89 header['footnotes'] = ''
94 repeat_state = [0] * 8
95 current_voice_idx = -1
96 current_lyric_idx = -1
102 global_key = [0] * 7 # UGH
103 names = ["One", "Two", "Three"]
110 sys.stderr.write (msg)
116 return chr (i + ord('A'))
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.
126 state.base_octave = -1
127 voices_append("\\clef \"G_8\"\n")
128 elif re.match('^treble', s):
130 if re.match ('^-8', s):
132 state.base_octave = -2
133 voices_append("\\clef \"G_8\"\n")
135 state.base_octave = 0
136 voices_append("\\clef treble\n")
137 elif re.match('^alto', s):
139 state.base_octave = -1
140 voices_append ("\\clef alto\n" )
141 elif re.match('^bass',s ):
143 state.base_octave = -2
144 voices_append ("\\clef bass\n" )
147 def select_voice (name, rol):
148 if not voice_idx_dict.has_key (name):
149 state_list.append(Parser_state())
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]
156 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
160 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
164 if keyword == 'clef':
166 elif keyword == "name":
167 value = re.sub ('\\\\','\\\\\\\\', value)
169 voices_append ("\\set Staff.instrument = %s\n" % value )
171 __main__.part_names = 1
172 elif keyword == "sname" or keyword == "snm":
173 voices_append ("\\set Staff.instr = %s\n" % value )
177 def dump_header (outf,hdr):
178 outf.write ('\\header {\n')
182 hdr[k] = re.sub('"', '\\"', hdr[k])
183 outf.write ('\t%s = "%s"\n'% (k,hdr[k]))
186 def dump_lyrics (outf):
188 outf.write("\n\\score\n{\n \\lyrics\n <<\n")
189 for i in range (len (lyrics)):
190 outf.write ( lyrics [i])
192 outf.write(" >>\n \\layout{}\n}\n")
194 def dump_default_bar (outf):
196 Nowadays abc2ly outputs explicits barlines (?)
199 outf.write ("\n\\set Score.defaultBarType = \"empty\"\n")
202 def dump_slyrics (outf):
203 ks = voice_idx_dict.keys()
206 if re.match('[1-9]', k):
207 m = alphabet(string.atoi(k))
210 for i in range (len(slyrics[voice_idx_dict[k]])):
212 outf.write ("\nwords%sV%s = \lyricmode {" % (m, l))
213 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
216 def dump_voices (outf):
217 global doing_alternative, in_repeat
218 ks = voice_idx_dict.keys()
221 if re.match ('[1-9]', k):
222 m = alphabet(string.atoi(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]])
231 if doing_alternative[voice_idx_dict[k]]:
233 if in_repeat[voice_idx_dict[k]]:
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,'/')
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]
249 duration=str(string.atoi(denominator)/string.atoi(numerator))
250 midi_specs=string.join(["\\tempo", duration, "=", perminute])
252 sys.stderr.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a)
254 def dump_score (outf):
261 ks = voice_idx_dict.keys ();
264 if re.match('[1-9]', k):
265 m = alphabet (string.atoi(k))
268 if k == 'default' and len (voice_idx_dict) > 1:
270 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
272 outf.write ("\t \\voicedefault\n")
273 outf.write ("\t \\voice%s " % m)
274 outf.write ("\n\t}\n")
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))
284 outf.write ( " \\words%sV%s } " % ( m, chr (l)) )
288 outf.write ("\n\t\\layout {\n")
289 outf.write ("\t}\n\t\\midi {%s}\n}\n" % midi_specs)
293 def set_default_length (s):
294 global length_specified
295 m = re.search ('1/([0-9]+)', s)
297 __main__.default_len = string.atoi ( m.group (1))
300 def set_default_len_from_time_sig (s):
301 m = re.search ('([0-9]+)/([0-9]+)', s)
303 n = string.atoi (m.group (1))
304 d = string.atoi (m.group (2))
305 if (n * 1.0 )/(d * 1.0) < 0.75:
306 __main__.default_len = 16
308 __main__.default_len = 8
317 sys.stderr.write ("can't open file: `%s'\n" % f)
321 sys.stderr.write ("gulped empty file: `%s'\n" % f)
326 # pitch manipulation. Tuples are (name, alteration).
327 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
328 # pitch in semitones.
329 def semitone_pitch (tup):
339 p = p + t* 2 + tup[1]
342 def fifth_above_pitch (tup):
343 (n, a) = (tup[0] + 4, tup[1])
345 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
356 (t,a) = fifth_above_pitch (p)
357 if semitone_pitch((t,a)) % 12 == 0:
369 (t,a) = quart_above_pitch (p)
370 if semitone_pitch((t,a)) % 12 == 0:
376 def quart_above_pitch (tup):
377 (n, a) = (tup[0] + 3, tup[1])
379 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
384 key_lookup = { # abc to lilypond key mode names
393 'mix' : 'mixolydian',
394 'mixolydian' : 'mixolydian',
407 if k and k[0] == '#':
410 elif k and k[0] == 'b':
414 return '%s \\major' % key
417 if not key_lookup.has_key (type):
418 #ugh, use lilylib, say WARNING:FILE:LINE:
419 sys.stderr.write ("abc2ly:warning:")
420 sys.stderr.write ("ignoring unknown key: `%s'" % orig)
421 sys.stderr.write ('\n')
423 return ("%s \\%s" % ( key, key_lookup[type]))
425 def shift_key (note, acc, shift):
426 s = semitone_pitch((note, acc))
427 s = (s + shift + 12) % 12
439 key_shift = { # semitone shifts for key mode names
462 intkey = (ord (k[0]) - ord('a') + 5) % 7
466 if k and k[0] == 'b':
469 elif k and k[0] == '#':
473 if k and key_shift.has_key(k):
474 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
475 keytup = (intkey, intkeyacc)
477 sharp_key_seq = sharp_keys ()
478 flat_key_seq = flat_keys ()
482 if keytup in sharp_key_seq:
484 key_count = sharp_key_seq.index (keytup)
485 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
487 elif keytup in flat_key_seq:
489 key_count = flat_key_seq.index (keytup)
490 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
497 key_table[a] = key_table[a] + accsign
512 def try_parse_tuplet_begin (str, state):
513 if re.match ('\([2-9]', str):
516 prev_tuplet_state = state.parsing_tuplet
517 state.parsing_tuplet = string.atoi (dig[0])
518 if prev_tuplet_state:
520 voices_append ("\\times %s {" % tup_lookup[dig])
523 def try_parse_group_end (str, state):
524 if str and str[0] in HSPACE:
526 close_beam_state(state)
529 def header_append (key, a):
531 if header.has_key (key):
532 s = header[key] + "\n"
536 linelen = len (v) - string.rfind(v, '\n')
537 if linelen + len (a) > 80:
541 def stuff_append (stuff, idx, a):
545 stuff [idx] = wordwrap(a, stuff[idx])
547 # ignore wordwrap since we are adding to the previous word
548 def stuff_append_back(stuff, idx, a):
552 point = len(stuff[idx])-1
553 while stuff[idx][point] is ' ':
556 stuff[idx] = stuff[idx][:point] + a + stuff[idx][point:]
558 def voices_append(a):
559 if current_voice_idx < 0:
560 select_voice ('default', '')
561 stuff_append (voices, current_voice_idx, a)
563 # word wrap really makes it hard to bind beams to the end of notes since it
564 # pushes out whitespace on every call. The _back functions do an append
565 # prior to the last space, effectively tagging whatever they are given
567 def voices_append_back(a):
568 if current_voice_idx < 0:
569 select_voice ('default', '')
570 stuff_append_back(voices, current_voice_idx, a)
572 def repeat_prepend():
574 if current_voice_idx < 0:
575 select_voice ('default', '')
577 repeat_state[current_voice_idx] = 't'
580 def lyrics_append(a):
581 a = re.sub ('#', '\\#', a) # latex does not like naked #'s
582 a = re.sub ('"', '\\"', a) # latex does not like naked "'s
583 a = '\t{ "' + a + '" }\n'
584 stuff_append (lyrics, current_lyric_idx, a)
586 # break lyrics to words and put "'s around words containing numbers and '"'s
590 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
594 word = re.sub('"', '\\"', word) # escape "
595 if re.match('.*[0-9"\(]', word):
596 word = re.sub('_', ' ', word) # _ causes probs inside ""
597 ret = ret + '\"' + word + '\" '
599 ret = ret + word + ' '
604 def slyrics_append(a):
605 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
606 a = re.sub ( '-', '- ', a) # split words with -
607 a = re.sub ( '\\\\- ', '-', a) # unless \-
608 a = re.sub ( '~', '_', a) # ~ to space('_')
609 a = re.sub ( '\*', '_ ', a) # * to to space
610 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
611 if re.match('.*[0-9"\(]', a): # put numbers and " and ( into quoted string
613 a = re.sub ( '$', ' ', a) # insure space between lines
614 __main__.lyric_idx = lyric_idx + 1
615 if len(slyrics[current_voice_idx]) <= lyric_idx:
616 slyrics[current_voice_idx].append(a)
618 v = slyrics[current_voice_idx][lyric_idx]
619 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
622 def try_parse_header_line (ln, state):
623 global length_specified
624 m = re.match ('^([A-Za-z]): *(.*)$', ln)
630 a = re.sub('[ \t]*$','', a) #strip trailing blanks
631 if header.has_key('title'):
633 if len(header['title']):
634 # the non-ascii character
635 # in the string below is a
636 # punctuation dash. (TeX ---)
637 header['title'] = header['title'] + ' — ' + a
639 header['subtitle'] = a
644 if not state.common_time:
645 state.common_time = 1
646 voices_append (" \\override Staff.TimeSignature #\'style = #'C\n")
649 if not state.common_time:
650 state.common_time = 1
651 voices_append ("\\override Staff.TimeSignature #\'style = #'C\n")
653 if not length_specified:
654 set_default_len_from_time_sig (a)
658 voices_append ('\\time %s' % a)
663 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
665 # there may or may not be a space
666 # between the key letter and the mode
667 if key_lookup.has_key(m.group(2)[0:3]):
668 key_info = m.group(1) + m.group(2)[0:3]
669 clef_info = m.group(2)[4:]
671 key_info = m.group(1)
672 clef_info = m.group(2)
673 __main__.global_key = compute_key (key_info)
674 k = lily_key (key_info)
676 voices_append ('\\key %s' % k)
677 check_clef(clef_info)
679 __main__.global_key = compute_key (a)
682 voices_append ('\\key %s \\major' % k)
684 header ['footnotes'] = header['footnotes'] + '\\\\\\\\' + a
685 if g == 'O': # Origin
686 header ['origin'] = a
687 if g == 'X': # Reference Number
688 header ['crossRefNumber'] = a
691 if g == 'H': # History
692 header_append ('history', a)
695 if g == 'C': # Composer
696 if header.has_key('composer'):
698 header['composer'] = header['composer'] + '\\\\\\\\' + a
700 header['composer'] = a
702 header ['subtitle'] = a
703 if g == 'L': # Default note length
704 set_default_length (ln)
706 voice = re.sub (' .*$', '', a)
707 rest = re.sub ('^[^ \t]* *', '', a)
709 voices_append(state.next_bar)
711 select_voice (voice, rest)
714 if g == 'w': # vocals
721 # we use in this order specified accidental, active accidental for bar,
722 # active accidental for key
723 def pitch_to_lilypond_name (name, acc, bar_acc, key):
737 return(chr (name + ord('c')) + s)
740 def octave_to_lilypond_quotes (o):
753 while str and str[0] in DIGITS:
754 durstr = durstr + str[0]
759 n =string.atoi (durstr)
763 def duration_to_lilypond_duration (multiply_tup, defaultlen, dots):
765 # (num / den) / defaultlen < 1/base
766 while base * multiply_tup[0] < multiply_tup[1]:
769 if (multiply_tup[0] / multiply_tup[1]) == 2:
771 if (multiply_tup[0] / multiply_tup[1]) == 3:
774 if (multiply_tup[0] / multiply_tup[1]) == 4:
776 return '%s%s' % ( base, '.'* dots)
781 self.next_articulation = ''
785 self.parsing_tuplet = 0
789 self.parsing_beam = 0
793 # return (str, num,den,dots)
794 def parse_duration (str, parser_state):
796 den = parser_state.next_den
797 parser_state.next_den = 1
799 (str, num) = parse_num (str)
805 while str[:1] == '/':
809 (str, d) =parse_num (str)
813 den = den * default_len
815 current_dots = parser_state.next_dots
816 parser_state.next_dots = 0
817 if re.match ('[ \t]*[<>]', str):
818 while str[0] in HSPACE:
822 current_dots = current_dots + 1
823 parser_state.next_den = parser_state.next_den * 2
828 parser_state.next_dots = parser_state.next_dots + 1
836 if num % multiplier == 0 and den % f == 0:
837 num = num / multiplier
839 current_dots = current_dots + d
841 return (str, num,den,current_dots)
844 def try_parse_rest (str, parser_state):
845 if not str or str[0] <> 'z' and str[0] <> 'x':
848 __main__.lyric_idx = -1
850 if parser_state.next_bar:
851 voices_append(parser_state.next_bar)
852 parser_state.next_bar = ''
860 (str, num,den,d) = parse_duration (str, parser_state)
861 voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
862 if parser_state.next_articulation:
863 voices_append (parser_state.next_articulation)
864 parser_state.next_articulation = ''
877 'J' : '', # ignore slide
878 'R' : '', # ignore roll
882 def try_parse_articulation (str, state):
883 while str and artic_tbl.has_key(str[:1]):
884 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
885 if not artic_tbl[str[:1]]:
886 sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
892 # s7m2 input doesnt care about spaces
893 if re.match('[ \t]*\(', str):
894 str = string.lstrip (str)
897 while str[:1] =='(' and str[1] not in DIGITS:
898 slur_begin = slur_begin + 1
899 state.next_articulation = state.next_articulation + '('
905 # remember accidental for rest of bar
907 def set_bar_acc(note, octave, acc, state):
910 n_oct = note + octave * 7
911 state.in_acc[n_oct] = acc
913 # get accidental set in this bar or UNDEF if not set
914 def get_bar_acc(note, octave, state):
915 n_oct = note + octave * 7
916 if state.in_acc.has_key(n_oct):
917 return(state.in_acc[n_oct])
921 def clear_bar_acc(state):
922 for k in state.in_acc.keys():
926 # if we are parsing a beam, close it off
927 def close_beam_state(state):
928 if state.parsing_beam and preserve_beams:
929 state.parsing_beam = 0
930 voices_append_back( ']' )
933 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
934 def try_parse_note (str, parser_state):
953 octave = parser_state.base_octave
954 if str[0] in "ABCDEFG":
955 str = string.lower (str[0]) + str[1:]
960 if str[0] in "abcdefg":
961 notename = (ord(str[0]) - ord('a') + 5)%7
964 return str # failed; not a note!
967 __main__.lyric_idx = -1
969 if parser_state.next_bar:
970 voices_append(parser_state.next_bar)
971 parser_state.next_bar = ''
976 while str[0] == '\'':
980 (str, num,den,current_dots) = parse_duration (str, parser_state)
982 if re.match('[ \t]*\)', str):
983 str = string.lstrip (str)
987 slur_end = slur_end + 1
991 bar_acc = get_bar_acc(notename, octave, parser_state)
992 pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
993 oct = octave_to_lilypond_quotes (octave)
994 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
998 voices_append ("%s%s%s%s" %
1000 duration_to_lilypond_duration ((num,den), default_len, current_dots)))
1002 set_bar_acc(notename, octave, acc, parser_state)
1003 if parser_state.next_articulation:
1004 articulation = articulation + parser_state.next_articulation
1005 parser_state.next_articulation = ''
1007 voices_append (articulation)
1009 if parser_state.parsing_tuplet:
1010 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
1011 if not parser_state.parsing_tuplet:
1014 voices_append ('-(' * slur_begin )
1016 voices_append ('-)' *slur_end )
1018 if preserve_beams and \
1019 str[0] in '^=_ABCDEFGabcdefg' and \
1020 not parser_state.parsing_beam and \
1021 not parser_state.parsing_tuplet:
1022 parser_state.parsing_beam = 1
1023 voices_append_back( '[' )
1027 def junk_space (str,state):
1028 while str and str[0] in '\t\n\r ':
1030 close_beam_state(state)
1035 def try_parse_guitar_chord (str, state):
1039 if str[0] == '_' or (str[0] == '^'):
1044 while str and str[0] != '"':
1050 gc = re.sub('#', '\\#', gc) # escape '#'s
1051 state.next_articulation = ("%c\"%s\"" % (position, gc)) \
1052 + state.next_articulation
1055 def try_parse_escape (str):
1056 if not str or str [0] != '\\':
1061 key_table = compute_key ()
1065 # |] thin-thick double bar line
1066 # || thin-thin double bar line
1067 # [| thick-thin double bar line
1070 # :: left-right repeat
1086 '|]' : '\\bar "|."',
1087 '||' : '\\bar "||"',
1088 '[|' : '\\bar "||"',
1090 '|:' : '\\repeat volta 2 {',
1091 '::' : '} \\repeat volta 2 {',
1092 '|1' : '} \\alternative{{',
1099 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1100 alternative_opener = ['|1', '|2', ':|2']
1101 repeat_ender = ['::', ':|']
1102 repeat_opener = ['::', '|:']
1103 in_repeat = [''] * 8
1104 doing_alternative = [''] * 8
1107 def try_parse_bar (str,state):
1108 global in_repeat, doing_alternative, using_old
1111 if current_voice_idx < 0:
1112 select_voice ('default', '')
1113 # first try the longer one
1114 for trylen in [3,2,1]:
1115 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1118 bs = "\\bar \"%s\"" % old_bar_dict[s]
1120 bs = "%s" % bar_dict[s]
1122 if s in alternative_opener:
1123 if not in_repeat[current_voice_idx]:
1125 bs = "\\bar \"%s\"" % old_bar_dict[s]
1127 doing_alternative[current_voice_idx] = 't'
1129 if s in repeat_ender:
1130 if not in_repeat[current_voice_idx]:
1131 sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1133 in_repeat[current_voice_idx] = ''
1135 if doing_alternative[current_voice_idx]:
1138 bs = "\\bar \"%s\"" % old_bar_dict[s]
1141 doing_alternative[current_voice_idx] = ''
1142 in_repeat[current_voice_idx] = ''
1143 if s in repeat_opener:
1144 in_repeat[current_voice_idx] = 't'
1146 bs = "\\bar \"%s\"" % old_bar_dict[s]
1151 state.next_bar = '|\n'
1153 clear_bar_acc(state)
1154 close_beam_state(state)
1156 if bs <> None or state.next_bar != '':
1157 if state.parsing_tuplet:
1158 state.parsing_tuplet =0
1159 voices_append ('} ')
1162 clear_bar_acc(state)
1163 close_beam_state(state)
1166 voices_append("} }")
1170 def try_parse_tie (str):
1173 voices_append (' ~ ')
1176 def bracket_escape (str, state):
1177 m = re.match ( '^([^\]]*)] *(.*)$', str)
1181 try_parse_header_line (cmd, state)
1184 def try_parse_chord_delims (str, state):
1187 if re.match('[A-Z]:', str): # bracket escape
1188 return bracket_escape(str, state)
1190 voices_append(state.next_bar)
1192 voices_append ('<<')
1196 if state.plus_chord:
1197 voices_append ('>>')
1198 state.plus_chord = 0
1201 voices_append(state.next_bar)
1203 voices_append ('<<')
1204 state.plus_chord = 1
1212 while str[:1] ==')':
1217 voices_append ("\\spanrequest \\stop \"slur\"" * end)
1221 def try_parse_grace_delims (str, state):
1224 voices_append(state.next_bar)
1227 voices_append ('\\grace { ')
1235 def try_parse_comment (str):
1238 if str[0:5] == '%MIDI':
1239 #the nobarlines option is necessary for an abc to lilypond translator for
1240 #exactly the same reason abc2midi needs it: abc requires the user to enter
1241 #the note that will be printed, and MIDI and lilypond expect entry of the
1242 #pitch that will be played.
1244 #In standard 19th century musical notation, the algorithm for translating
1245 #between printed note and pitch involves using the barlines to determine
1246 #the scope of the accidentals.
1248 #Since ABC is frequently used for music in styles that do not use this
1249 #convention, such as most music written before 1700, or ethnic music in
1250 #non-western scales, it is necessary to be able to tell a translator that
1251 #the barlines should not affect its interpretation of the pitch.
1252 if (string.find(str,'nobarlines') > 0):
1254 elif str[0:3] == '%LY':
1255 p = string.find(str, 'voices')
1257 voices_append(str[p+7:])
1259 p = string.find(str, 'slyrics')
1261 slyrics_append(str[p+8:])
1263 #write other kinds of appending if we ever need them.
1268 def parse_file (fn):
1271 ls = map (lambda x: re.sub ("\r$", '', x), ls)
1273 select_voice('default', '')
1276 sys.stderr.write ("Line ... ")
1278 __main__.state = state_list[current_voice_idx]
1283 if not (lineno % happy_count):
1284 sys.stderr.write ('[%d]'% lineno)
1286 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1289 try_parse_comment(m.group(2))
1290 voices_append ('%% %s\n' % m.group(2))
1295 ln = try_parse_header_line (ln, state)
1297 # Try nibbling characters off until the line doesn't change.
1299 while ln != prev_ln:
1301 ln = try_parse_chord_delims (ln, state)
1302 ln = try_parse_rest (ln, state)
1303 ln = try_parse_articulation (ln,state)
1304 ln = try_parse_note (ln, state)
1305 ln = try_parse_bar (ln, state)
1306 ln = try_parse_tie (ln)
1307 ln = try_parse_escape (ln)
1308 ln = try_parse_guitar_chord (ln, state)
1309 ln = try_parse_tuplet_begin (ln, state)
1310 ln = try_parse_group_end (ln, state)
1311 ln = try_parse_grace_delims (ln, state)
1312 ln = junk_space (ln, state)
1315 error ("%s: %d: Huh? Don't understand\n" % (fn, lineno))
1316 left = orig_ln[0:-len (ln)]
1317 sys.stderr.write (left + '\n')
1318 sys.stderr.write (' ' * len (left) + ln + '\n')
1322 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1326 Convert ABC to lilypond.
1328 Usage: abc2ly [OPTIONS]... ABC-FILE
1331 -h, --help print this help
1332 -o, --output=FILE set output filename to FILE
1333 -v, --version show version information
1334 -s, --strict be strict about succes
1335 -b, --beams preserve ABC's notion of beams
1337 This program converts ABC music files (see
1338 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) to LilyPond input.
1343 http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
1345 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>, Laura Conrad
1346 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1349 def print_version ():
1350 print r"""abc2ly (GNU lilypond) %s""" % version
1354 (options, files) = getopt.getopt (sys.argv[1:], 'vo:hsb', ['help','version', 'output=', 'strict', 'beams'])
1360 if o== '--help' or o == '-h':
1363 elif o == '--version' or o == '-v':
1366 elif o == '--strict' or o == '-s':
1368 elif o == '--output' or o == '-o':
1370 elif o == '--beams' or o == '-b':
1378 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1383 sys.stderr.write ('Parsing `%s\'...\n' % f)
1386 if not out_filename:
1387 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1388 sys.stderr.write ('lilypond output to: `%s\'...' % out_filename)
1389 outf = open (out_filename, 'w')
1391 # don't substitute @VERSION@. We want this to reflect
1392 # the last version that was verified to work.
1393 outf.write ('\\version "2.5.20"\n')
1395 # dump_global (outf)
1396 dump_header (outf, header)
1401 sys.stderr.write ('\n')