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 = chr(string.atoi(k) + 'A')
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 = chr(string.atoi(k) + 'A')
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")
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)
298 def set_default_length (s):
299 global length_specified
300 m = re.search ('1/([0-9]+)', s)
302 __main__.default_len = string.atoi ( m.group (1))
305 def set_default_len_from_time_sig (s):
306 m = re.search ('([0-9]+)/([0-9]+)', s)
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
313 __main__.default_len = 8
322 sys.stderr.write ("can't open file: `%s'\n" % f)
326 sys.stderr.write ("gulped empty file: `%s'\n" % f)
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):
344 p = p + t* 2 + tup[1]
347 def fifth_above_pitch (tup):
348 (n, a) = (tup[0] + 4, tup[1])
350 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
361 (t,a) = fifth_above_pitch (p)
362 if semitone_pitch((t,a)) % 12 == 0:
374 (t,a) = quart_above_pitch (p)
375 if semitone_pitch((t,a)) % 12 == 0:
381 def quart_above_pitch (tup):
382 (n, a) = (tup[0] + 3, tup[1])
384 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
389 key_lookup = { # abc to lilypond key mode names
398 'mix' : 'mixolydian',
399 'mixolydian' : 'mixolydian',
412 if k and k[0] == '#':
415 elif k and k[0] == 'b':
419 return '%s \\major' % key
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')
428 return ("%s \\%s" % ( key, key_lookup[type]))
430 def shift_key (note, acc, shift):
431 s = semitone_pitch((note, acc))
432 s = (s + shift + 12) % 12
444 key_shift = { # semitone shifts for key mode names
467 intkey = (ord (k[0]) - ord('a') + 5) % 7
471 if k and k[0] == 'b':
474 elif k and k[0] == '#':
478 if k and key_shift.has_key(k):
479 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
480 keytup = (intkey, intkeyacc)
482 sharp_key_seq = sharp_keys ()
483 flat_key_seq = flat_keys ()
487 if keytup in sharp_key_seq:
489 key_count = sharp_key_seq.index (keytup)
490 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
492 elif keytup in flat_key_seq:
494 key_count = flat_key_seq.index (keytup)
495 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
502 key_table[a] = key_table[a] + accsign
517 def try_parse_tuplet_begin (str, state):
518 if re.match ('\([2-9]', str):
521 prev_tuplet_state = state.parsing_tuplet
522 state.parsing_tuplet = string.atoi (dig[0])
523 if prev_tuplet_state:
525 voices_append ("\\times %s {" % tup_lookup[dig])
528 def try_parse_group_end (str, state):
529 if str and str[0] in HSPACE:
531 close_beam_state(state)
534 def header_append (key, a):
536 if header.has_key (key):
537 s = header[key] + "\n"
541 linelen = len (v) - string.rfind(v, '\n')
542 if linelen + len (a) > 80:
546 def stuff_append (stuff, idx, a):
550 stuff [idx] = wordwrap(a, stuff[idx])
552 # ignore wordwrap since we are adding to the previous word
553 def stuff_append_back(stuff, idx, a):
557 point = len(stuff[idx])-1
558 while stuff[idx][point] is ' ':
561 stuff[idx] = stuff[idx][:point] + a + stuff[idx][point:]
563 def voices_append(a):
564 if current_voice_idx < 0:
565 select_voice ('default', '')
566 stuff_append (voices, current_voice_idx, a)
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
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)
577 def repeat_prepend():
579 if current_voice_idx < 0:
580 select_voice ('default', '')
582 repeat_state[current_voice_idx] = 't'
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)
591 # break lyrics to words and put "'s around words containing numbers and '"'s
595 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
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 + '\" '
604 ret = ret + word + ' '
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
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)
623 v = slyrics[current_voice_idx][lyric_idx]
624 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
627 def try_parse_header_line (ln, state):
628 global length_specified
629 m = re.match ('^([A-Za-z]): *(.*)$', ln)
635 a = re.sub('[ \t]*$','', a) #strip trailing blanks
636 if header.has_key('title'):
638 if len(header['title']):
639 header['title'] = header['title'] + '\\\\\\\\' + a
641 header['subtitle'] = a
646 if not state.common_time:
647 state.common_time = 1
648 voices_append (" \\override Staff.TimeSignature #\'style = #'C\n")
651 if not state.common_time:
652 state.common_time = 1
653 voices_append ("\\override Staff.TimeSignature #\'style = #'C\n")
655 if not length_specified:
656 set_default_len_from_time_sig (a)
660 voices_append ('\\time %s' % a)
665 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
667 # there may or may not be a space
668 # between the key letter and the mode
669 if key_lookup.has_key(m.group(2)[0:3]):
670 key_info = m.group(1) + m.group(2)[0:3]
671 clef_info = m.group(2)[4:]
673 key_info = m.group(1)
674 clef_info = m.group(2)
675 __main__.global_key = compute_key (key_info)
676 k = lily_key (key_info)
678 voices_append ('\\key %s' % k)
679 check_clef(clef_info)
681 __main__.global_key = compute_key (a)
684 voices_append ('\\key %s \\major' % k)
686 header ['footnotes'] = header['footnotes'] + '\\\\\\\\' + a
687 if g == 'O': # Origin
688 header ['origin'] = a
689 if g == 'X': # Reference Number
690 header ['crossRefNumber'] = a
693 if g == 'H': # History
694 header_append ('history', a)
697 if g == 'C': # Composer
698 if header.has_key('composer'):
700 header['composer'] = header['composer'] + '\\\\\\\\' + a
702 header['composer'] = a
704 header ['subtitle'] = a
705 if g == 'L': # Default note length
706 set_default_length (ln)
708 voice = re.sub (' .*$', '', a)
709 rest = re.sub ('^[^ \t]* *', '', a)
711 voices_append(state.next_bar)
713 select_voice (voice, rest)
716 if g == 'w': # vocals
723 # we use in this order specified accidental, active accidental for bar,
724 # active accidental for key
725 def pitch_to_lilypond_name (name, acc, bar_acc, key):
739 return(chr (name + ord('c')) + s)
742 def octave_to_lilypond_quotes (o):
755 while str and str[0] in DIGITS:
756 durstr = durstr + str[0]
761 n =string.atoi (durstr)
765 def duration_to_lilypond_duration (multiply_tup, defaultlen, dots):
767 # (num / den) / defaultlen < 1/base
768 while base * multiply_tup[0] < multiply_tup[1]:
771 if (multiply_tup[0] / multiply_tup[1]) == 2:
773 if (multiply_tup[0] / multiply_tup[1]) == 3:
776 if (multiply_tup[0] / multiply_tup[1]) == 4:
778 return '%s%s' % ( base, '.'* dots)
783 self.next_articulation = ''
787 self.parsing_tuplet = 0
791 self.parsing_beam = 0
795 # return (str, num,den,dots)
796 def parse_duration (str, parser_state):
798 den = parser_state.next_den
799 parser_state.next_den = 1
801 (str, num) = parse_num (str)
807 while str[:1] == '/':
811 (str, d) =parse_num (str)
815 den = den * default_len
817 current_dots = parser_state.next_dots
818 parser_state.next_dots = 0
819 if re.match ('[ \t]*[<>]', str):
820 while str[0] in HSPACE:
824 current_dots = current_dots + 1
825 parser_state.next_den = parser_state.next_den * 2
830 parser_state.next_dots = parser_state.next_dots + 1
838 if num % multiplier == 0 and den % f == 0:
839 num = num / multiplier
841 current_dots = current_dots + d
843 return (str, num,den,current_dots)
846 def try_parse_rest (str, parser_state):
847 if not str or str[0] <> 'z' and str[0] <> 'x':
850 __main__.lyric_idx = -1
852 if parser_state.next_bar:
853 voices_append(parser_state.next_bar)
854 parser_state.next_bar = ''
862 (str, num,den,d) = parse_duration (str, parser_state)
863 voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
864 if parser_state.next_articulation:
865 voices_append (parser_state.next_articulation)
866 parser_state.next_articulation = ''
879 'J' : '', # ignore slide
880 'R' : '', # ignore roll
884 def try_parse_articulation (str, state):
885 while str and artic_tbl.has_key(str[:1]):
886 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
887 if not artic_tbl[str[:1]]:
888 sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
894 # s7m2 input doesnt care about spaces
895 if re.match('[ \t]*\(', str):
896 str = string.lstrip (str)
899 while str[:1] =='(' and str[1] not in DIGITS:
900 slur_begin = slur_begin + 1
901 state.next_articulation = state.next_articulation + '('
907 # remember accidental for rest of bar
909 def set_bar_acc(note, octave, acc, state):
912 n_oct = note + octave * 7
913 state.in_acc[n_oct] = acc
915 # get accidental set in this bar or UNDEF if not set
916 def get_bar_acc(note, octave, state):
917 n_oct = note + octave * 7
918 if state.in_acc.has_key(n_oct):
919 return(state.in_acc[n_oct])
923 def clear_bar_acc(state):
924 for k in state.in_acc.keys():
928 # if we are parsing a beam, close it off
929 def close_beam_state(state):
930 if state.parsing_beam and preserve_beams:
931 state.parsing_beam = 0
932 voices_append_back( ']' )
935 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
936 def try_parse_note (str, parser_state):
955 octave = parser_state.base_octave
956 if str[0] in "ABCDEFG":
957 str = string.lower (str[0]) + str[1:]
962 if str[0] in "abcdefg":
963 notename = (ord(str[0]) - ord('a') + 5)%7
966 return str # failed; not a note!
969 __main__.lyric_idx = -1
971 if parser_state.next_bar:
972 voices_append(parser_state.next_bar)
973 parser_state.next_bar = ''
978 while str[0] == '\'':
982 (str, num,den,current_dots) = parse_duration (str, parser_state)
984 if re.match('[ \t]*\)', str):
985 str = string.lstrip (str)
989 slur_end = slur_end + 1
993 bar_acc = get_bar_acc(notename, octave, parser_state)
994 pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
995 oct = octave_to_lilypond_quotes (octave)
996 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
1000 voices_append ("%s%s%s%s" %
1002 duration_to_lilypond_duration ((num,den), default_len, current_dots)))
1004 set_bar_acc(notename, octave, acc, parser_state)
1005 if parser_state.next_articulation:
1006 articulation = articulation + parser_state.next_articulation
1007 parser_state.next_articulation = ''
1009 voices_append (articulation)
1011 if parser_state.parsing_tuplet:
1012 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
1013 if not parser_state.parsing_tuplet:
1016 voices_append ('-(' * slur_begin )
1018 voices_append ('-)' *slur_end )
1020 if preserve_beams and \
1021 str[0] in '^=_ABCDEFGabcdefg' and \
1022 not parser_state.parsing_beam and \
1023 not parser_state.parsing_tuplet:
1024 parser_state.parsing_beam = 1
1025 voices_append_back( '[' )
1029 def junk_space (str,state):
1030 while str and str[0] in '\t\n\r ':
1032 close_beam_state(state)
1037 def try_parse_guitar_chord (str, state):
1041 if str[0] == '_' or (str[0] == '^'):
1046 while str and str[0] != '"':
1052 gc = re.sub('#', '\\#', gc) # escape '#'s
1053 state.next_articulation = ("%c\"%s\"" % (position, gc)) \
1054 + state.next_articulation
1057 def try_parse_escape (str):
1058 if not str or str [0] != '\\':
1063 key_table = compute_key ()
1067 # |] thin-thick double bar line
1068 # || thin-thin double bar line
1069 # [| thick-thin double bar line
1072 # :: left-right repeat
1088 '|]' : '\\bar "|."',
1089 '||' : '\\bar "||"',
1090 '[|' : '\\bar "||"',
1092 '|:' : '\\repeat volta 2 {',
1093 '::' : '} \\repeat volta 2 {',
1094 '|1' : '} \\alternative{{',
1101 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1102 alternative_opener = ['|1', '|2', ':|2']
1103 repeat_ender = ['::', ':|']
1104 repeat_opener = ['::', '|:']
1105 in_repeat = [''] * 8
1106 doing_alternative = [''] * 8
1109 def try_parse_bar (str,state):
1110 global in_repeat, doing_alternative, using_old
1113 if current_voice_idx < 0:
1114 select_voice ('default', '')
1115 # first try the longer one
1116 for trylen in [3,2,1]:
1117 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1120 bs = "\\bar \"%s\"" % old_bar_dict[s]
1122 bs = "%s" % bar_dict[s]
1124 if s in alternative_opener:
1125 if not in_repeat[current_voice_idx]:
1127 bs = "\\bar \"%s\"" % old_bar_dict[s]
1129 doing_alternative[current_voice_idx] = 't'
1131 if s in repeat_ender:
1132 if not in_repeat[current_voice_idx]:
1133 sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1135 in_repeat[current_voice_idx] = ''
1137 if doing_alternative[current_voice_idx]:
1140 bs = "\\bar \"%s\"" % old_bar_dict[s]
1143 doing_alternative[current_voice_idx] = ''
1144 in_repeat[current_voice_idx] = ''
1145 if s in repeat_opener:
1146 in_repeat[current_voice_idx] = 't'
1148 bs = "\\bar \"%s\"" % old_bar_dict[s]
1153 state.next_bar = '|\n'
1155 clear_bar_acc(state)
1156 close_beam_state(state)
1158 if bs <> None or state.next_bar != '':
1159 if state.parsing_tuplet:
1160 state.parsing_tuplet =0
1161 voices_append ('} ')
1164 clear_bar_acc(state)
1165 close_beam_state(state)
1168 voices_append("} }")
1172 def try_parse_tie (str):
1175 voices_append (' ~ ')
1178 def bracket_escape (str, state):
1179 m = re.match ( '^([^\]]*)] *(.*)$', str)
1183 try_parse_header_line (cmd, state)
1186 def try_parse_chord_delims (str, state):
1189 if re.match('[A-Z]:', str): # bracket escape
1190 return bracket_escape(str, state)
1192 voices_append(state.next_bar)
1194 voices_append ('<<')
1198 if state.plus_chord:
1199 voices_append ('>>')
1200 state.plus_chord = 0
1203 voices_append(state.next_bar)
1205 voices_append ('<<')
1206 state.plus_chord = 1
1214 while str[:1] ==')':
1219 voices_append ("\\spanrequest \\stop \"slur\"" * end)
1223 def try_parse_grace_delims (str, state):
1226 voices_append(state.next_bar)
1229 voices_append ('\\grace { ')
1237 def try_parse_comment (str):
1240 if str[0:5] == '%MIDI':
1241 #the nobarlines option is necessary for an abc to lilypond translator for
1242 #exactly the same reason abc2midi needs it: abc requires the user to enter
1243 #the note that will be printed, and MIDI and lilypond expect entry of the
1244 #pitch that will be played.
1246 #In standard 19th century musical notation, the algorithm for translating
1247 #between printed note and pitch involves using the barlines to determine
1248 #the scope of the accidentals.
1250 #Since ABC is frequently used for music in styles that do not use this
1251 #convention, such as most music written before 1700, or ethnic music in
1252 #non-western scales, it is necessary to be able to tell a translator that
1253 #the barlines should not affect its interpretation of the pitch.
1254 if (string.find(str,'nobarlines') > 0):
1256 elif str[0:3] == '%LY':
1257 p = string.find(str, 'voices')
1259 voices_append(str[p+7:])
1261 p = string.find(str, 'slyrics')
1263 slyrics_append(str[p+8:])
1265 #write other kinds of appending if we ever need them.
1270 def parse_file (fn):
1273 ls = map (lambda x: re.sub ("\r$", '', x), ls)
1275 select_voice('default', '')
1278 sys.stderr.write ("Line ... ")
1280 __main__.state = state_list[current_voice_idx]
1285 if not (lineno % happy_count):
1286 sys.stderr.write ('[%d]'% lineno)
1288 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1291 try_parse_comment(m.group(2))
1292 voices_append ('%% %s\n' % m.group(2))
1297 ln = try_parse_header_line (ln, state)
1299 # Try nibbling characters off until the line doesn't change.
1301 while ln != prev_ln:
1303 ln = try_parse_chord_delims (ln, state)
1304 ln = try_parse_rest (ln, state)
1305 ln = try_parse_articulation (ln,state)
1306 ln = try_parse_note (ln, state)
1307 ln = try_parse_bar (ln, state)
1308 ln = try_parse_tie (ln)
1309 ln = try_parse_escape (ln)
1310 ln = try_parse_guitar_chord (ln, state)
1311 ln = try_parse_tuplet_begin (ln, state)
1312 ln = try_parse_group_end (ln, state)
1313 ln = try_parse_grace_delims (ln, state)
1314 ln = junk_space (ln, state)
1317 error ("%s: %d: Huh? Don't understand\n" % (fn, lineno))
1318 left = orig_ln[0:-len (ln)]
1319 sys.stderr.write (left + '\n')
1320 sys.stderr.write (' ' * len (left) + ln + '\n')
1324 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1328 Convert ABC to lilypond.
1330 Usage: abc2ly [OPTIONS]... ABC-FILE
1333 -h, --help print this help
1334 -o, --output=FILE set output filename to FILE
1335 -v, --version show version information
1336 -s, --strict be strict about succes
1337 -b, --beams preserve ABC's notion of beams
1339 This program converts ABC music files (see
1340 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) to LilyPond input.
1343 Report bugs to bug-lilypond@gnu.org.
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 outf.write ('\\version "2.3.25"\n')
1393 # dump_global (outf)
1394 dump_header (outf, header)
1399 sys.stderr.write ('\n')