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.
70 program_name = 'abc2ly'
71 version = '@TOPLEVEL_VERSION@'
72 if version == '@' + 'TOPLEVEL_VERSION' + '@':
73 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"]
105 alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
111 sys.stderr.write (msg)
119 if re.match('-8va', s) or re.match('treble8', s):
120 # treble8 is used by abctab2ps; -8va is used by barfly,
121 # and by my patch to abc2ps. If there's ever a standard
122 # about this we'll support that.
124 state.base_octave = -1
125 voices_append("\\clef \"G_8\"\n")
126 elif re.match('^treble', s):
128 if re.match ('^-8', s):
130 state.base_octave = -2
131 voices_append("\\clef \"G_8\"\n")
133 state.base_octave = 0
134 voices_append("\\clef treble\n")
135 elif re.match('^alto', s):
137 state.base_octave = -1
138 voices_append ("\\clef alto\n" )
139 elif re.match('^bass',s ):
141 state.base_octave = -2
142 voices_append ("\\clef bass\n" )
145 def select_voice (name, rol):
146 if not voice_idx_dict.has_key (name):
147 state_list.append(Parser_state())
150 voice_idx_dict[name] = len (voices) -1
151 __main__.current_voice_idx = voice_idx_dict[name]
152 __main__.state = state_list[current_voice_idx]
154 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
158 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
162 if keyword == 'clef':
164 elif keyword == "name":
165 value = re.sub ('\\\\','\\\\\\\\', value)
166 voices_append ("\\property Staff.instrument = %s\n" % value )
167 __main__.part_names = 1
168 elif keyword == "sname" or keyword == "snm":
169 voices_append ("\\property Staff.instr = %s\n" % value )
173 def dump_header (outf,hdr):
174 outf.write ('\\header {\n')
178 hdr[k] = re.sub('"', '\\"', hdr[k])
179 outf.write ('\t%s = "%s"\n'% (k,hdr[k]))
182 def dump_lyrics (outf):
184 outf.write("\n\\score\n{\n \\context Lyrics\n <<\n")
185 for i in range (len (lyrics)):
186 outf.write ( lyrics [i])
188 outf.write(" >>\n \\paper{}\n}\n")
190 def dump_default_bar (outf):
192 Nowadays abc2ly outputs explicits barlines (?)
194 outf.write ("\n\\property Score.defaultBarType=\"empty\"\n")
197 def dump_slyrics (outf):
198 ks = voice_idx_dict.keys()
201 if re.match('[1-9]', k):
202 m = alphabet[string.atoi(k)]
205 for i in range (len(slyrics[voice_idx_dict[k]])):
207 outf.write ("\nwords%sV%s = \\lyrics {" % (m, l))
208 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
211 def dump_voices (outf):
212 global doing_alternative, in_repeat
213 ks = voice_idx_dict.keys()
216 if re.match ('[1-9]', k):
217 m = alphabet[string.atoi(k)]
220 outf.write ("\nvoice%s = \\notes {" % m)
221 dump_default_bar(outf)
222 if repeat_state[voice_idx_dict[k]]:
223 outf.write("\n\\repeat volta 2 {")
224 outf.write ("\n" + voices [voice_idx_dict[k]])
226 if doing_alternative[voice_idx_dict[k]]:
228 if in_repeat[voice_idx_dict[k]]:
234 #assume that Q takes the form "Q:1/4=120"
235 #There are other possibilities, but they are deprecated
236 if string.count(a, '/') == 1:
237 array=string.split(a,'/')
240 sys.stderr.write("abc2ly: Warning, unable to translate a Q specification with a numerator of %s: %s\n" % (numerator, a))
241 array2=string.split(array[1],'=')
242 denominator=array2[0]
244 duration=str(string.atoi(denominator)/string.atoi(numerator))
245 midi_specs=string.join(["\\tempo", duration, "=", perminute])
247 sys.stderr.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a)
249 def dump_score (outf):
250 outf.write (r"""\score{
254 ks = voice_idx_dict.keys ();
257 if re.match('[1-9]', k):
258 m = alphabet[string.atoi(k)]
261 if k == 'default' and len (voice_idx_dict) > 1:
263 if len ( slyrics [voice_idx_dict[k]] ):
264 outf.write ("\n \\addlyrics")
265 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
267 outf.write ("\t \\voicedefault\n")
268 outf.write ("\t \\voice%s " % m)
269 outf.write ("\n\t}\n")
270 if len ( slyrics [voice_idx_dict[k]] ):
271 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<<\t" % k)
272 if re.match('[1-9]',k):
273 m = alphabet[string.atoi(k)]
276 for i in range (len(slyrics[voice_idx_dict[k]])):
278 outf.write("\n\t { \\words%sV%s }" % ( m, l) )
279 outf.write ( "\n\t>>\n" )
281 outf.write ("\n\t\\paper {\n")
283 outf.write ("\t \\translator \n\t {\n")
284 outf.write ("\t\t\\StaffContext\n")
285 # outf.write ("\t\t\\consists Staff_margin_engraver\n")
286 outf.write ("\t }\n")
287 outf.write ("\t}\n\t\\midi {%s}\n}\n" % midi_specs)
291 def set_default_length (s):
292 global length_specified
293 m = re.search ('1/([0-9]+)', s)
295 __main__.default_len = string.atoi ( m.group (1))
298 def set_default_len_from_time_sig (s):
299 m = re.search ('([0-9]+)/([0-9]+)', s)
301 n = string.atoi (m.group (1))
302 d = string.atoi (m.group (2))
303 if (n * 1.0 )/(d * 1.0) < 0.75:
304 __main__.default_len = 16
306 __main__.default_len = 8
315 sys.stderr.write ("can't open file: `%s'\n" % f)
319 sys.stderr.write ("gulped empty file: `%s'\n" % f)
324 # pitch manipulation. Tuples are (name, alteration).
325 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
326 # pitch in semitones.
327 def semitone_pitch (tup):
337 p = p + t* 2 + tup[1]
340 def fifth_above_pitch (tup):
341 (n, a) = (tup[0] + 4, tup[1])
343 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
354 (t,a) = fifth_above_pitch (p)
355 if semitone_pitch((t,a)) % 12 == 0:
367 (t,a) = quart_above_pitch (p)
368 if semitone_pitch((t,a)) % 12 == 0:
374 def quart_above_pitch (tup):
375 (n, a) = (tup[0] + 3, tup[1])
377 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
382 key_lookup = { # abc to lilypond key mode names
391 'mix' : 'mixolydian',
392 'mixolydian' : 'mixolydian',
405 if k and k[0] == '#':
408 elif k and k[0] == 'b':
412 return '%s \\major' % key
415 if not key_lookup.has_key (type):
416 #ugh, use lilylib, say WARNING:FILE:LINE:
417 sys.stderr.write ("abc2ly:warning:")
418 sys.stderr.write ("ignoring unknown key: `%s'" % orig)
419 sys.stderr.write ('\n')
421 return ("%s \\%s" % ( key, key_lookup[type]))
423 def shift_key (note, acc, shift):
424 s = semitone_pitch((note, acc))
425 s = (s + shift + 12) % 12
437 key_shift = { # semitone shifts for key mode names
460 intkey = (ord (k[0]) - ord('a') + 5) % 7
464 if k and k[0] == 'b':
467 elif k and k[0] == '#':
471 if k and key_shift.has_key(k):
472 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
473 keytup = (intkey, intkeyacc)
475 sharp_key_seq = sharp_keys ()
476 flat_key_seq = flat_keys ()
480 if keytup in sharp_key_seq:
482 key_count = sharp_key_seq.index (keytup)
483 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
485 elif keytup in flat_key_seq:
487 key_count = flat_key_seq.index (keytup)
488 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
495 key_table[a] = key_table[a] + accsign
510 def try_parse_tuplet_begin (str, state):
511 if re.match ('\([2-9]', str):
514 prev_tuplet_state = state.parsing_tuplet
515 state.parsing_tuplet = string.atoi (dig[0])
516 if prev_tuplet_state:
518 voices_append ("\\times %s {" % tup_lookup[dig])
521 def try_parse_group_end (str, state):
522 if str and str[0] in HSPACE:
524 close_beam_state(state)
527 def header_append (key, a):
529 if header.has_key (key):
530 s = header[key] + "\n"
534 linelen = len (v) - string.rfind(v, '\n')
535 if linelen + len (a) > 80:
539 def stuff_append (stuff, idx, a):
543 stuff [idx] = wordwrap(a, stuff[idx])
545 # ignore wordwrap since we are adding to the previous word
546 def stuff_append_back(stuff, idx, a):
550 point = len(stuff[idx])-1
551 while stuff[idx][point] is ' ':
554 stuff[idx] = stuff[idx][:point] + a + stuff[idx][point:]
556 def voices_append(a):
557 if current_voice_idx < 0:
558 select_voice ('default', '')
559 stuff_append (voices, current_voice_idx, a)
561 # word wrap really makes it hard to bind beams to the end of notes since it
562 # pushes out whitespace on every call. The _back functions do an append
563 # prior to the last space, effectively tagging whatever they are given
565 def voices_append_back(a):
566 if current_voice_idx < 0:
567 select_voice ('default', '')
568 stuff_append_back(voices, current_voice_idx, a)
570 def repeat_prepend():
572 if current_voice_idx < 0:
573 select_voice ('default', '')
575 repeat_state[current_voice_idx] = 't'
578 def lyrics_append(a):
579 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
580 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
581 a = '\t{ \\lyrics "' + a + '" }\n'
582 stuff_append (lyrics, current_lyric_idx, a)
584 # break lyrics to words and put "'s around words containing numbers and '"'s
588 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
592 word = re.sub('"', '\\"', word) # escape "
593 if re.match('.*[0-9"\(]', word):
594 word = re.sub('_', ' ', word) # _ causes probs inside ""
595 ret = ret + '\"' + word + '\" '
597 ret = ret + word + ' '
602 def slyrics_append(a):
603 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
604 a = re.sub ( '-', '- ', a) # split words with -
605 a = re.sub ( '\\\\- ', '-', a) # unless \-
606 a = re.sub ( '~', '_', a) # ~ to space('_')
607 a = re.sub ( '\*', '_ ', a) # * to to space
608 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
609 if re.match('.*[0-9"\(]', a): # put numbers and " and ( into quoted string
611 a = re.sub ( '$', ' ', a) # insure space between lines
612 __main__.lyric_idx = lyric_idx + 1
613 if len(slyrics[current_voice_idx]) <= lyric_idx:
614 slyrics[current_voice_idx].append(a)
616 v = slyrics[current_voice_idx][lyric_idx]
617 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
620 def try_parse_header_line (ln, state):
621 global length_specified
622 m = re.match ('^([A-Za-z]): *(.*)$', ln)
628 a = re.sub('[ \t]*$','', a) #strip trailing blanks
629 if header.has_key('title'):
631 if len(header['title']):
632 header['title'] = header['title'] + '\\\\\\\\' + a
634 header['subtitle'] = a
639 if not state.common_time:
640 state.common_time = 1
641 voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
644 if not state.common_time:
645 state.common_time = 1
646 voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
648 if not length_specified:
649 set_default_len_from_time_sig (a)
653 voices_append ('\\time %s' % a)
658 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
660 # there may or may not be a space
661 # between the key letter and the mode
662 if key_lookup.has_key(m.group(2)[0:3]):
663 key_info = m.group(1) + m.group(2)[0:3]
664 clef_info = m.group(2)[4:]
666 key_info = m.group(1)
667 clef_info = m.group(2)
668 __main__.global_key = compute_key (key_info)
669 k = lily_key (key_info)
671 voices_append ('\\key %s' % k)
672 check_clef(clef_info)
674 __main__.global_key = compute_key (a)
677 voices_append ('\\key %s \\major' % k)
679 header ['footnotes'] = header['footnotes'] + '\\\\\\\\' + a
680 if g == 'O': # Origin
681 header ['origin'] = a
682 if g == 'X': # Reference Number
683 header ['crossRefNumber'] = a
686 if g == 'H': # History
687 header_append ('history', a)
690 if g == 'C': # Composer
691 if header.has_key('composer'):
693 header['composer'] = header['composer'] + '\\\\\\\\' + a
695 header['composer'] = a
697 header ['subtitle'] = a
698 if g == 'L': # Default note length
699 set_default_length (ln)
701 voice = re.sub (' .*$', '', a)
702 rest = re.sub ('^[^ \t]* *', '', a)
704 voices_append(state.next_bar)
706 select_voice (voice, rest)
709 if g == 'w': # vocals
716 # we use in this order specified accidental, active accidental for bar,
717 # active accidental for key
718 def pitch_to_lilypond_name (name, acc, bar_acc, key):
732 return(chr (name + ord('c')) + s)
735 def octave_to_lilypond_quotes (o):
748 while str and str[0] in DIGITS:
749 durstr = durstr + str[0]
754 n =string.atoi (durstr)
758 def duration_to_lilypond_duration (multiply_tup, defaultlen, dots):
760 # (num / den) / defaultlen < 1/base
761 while base * multiply_tup[0] < multiply_tup[1]:
764 if (multiply_tup[0] / multiply_tup[1]) == 2:
766 if (multiply_tup[0] / multiply_tup[1]) == 3:
769 if (multiply_tup[0] / multiply_tup[1]) == 4:
771 return '%s%s' % ( base, '.'* dots)
776 self.next_articulation = ''
780 self.parsing_tuplet = 0
784 self.parsing_beam = 0
788 # return (str, num,den,dots)
789 def parse_duration (str, parser_state):
791 den = parser_state.next_den
792 parser_state.next_den = 1
794 (str, num) = parse_num (str)
800 while str[:1] == '/':
804 (str, d) =parse_num (str)
808 den = den * default_len
810 current_dots = parser_state.next_dots
811 parser_state.next_dots = 0
812 if re.match ('[ \t]*[<>]', str):
813 while str[0] in HSPACE:
817 current_dots = current_dots + 1
818 parser_state.next_den = parser_state.next_den * 2
823 parser_state.next_dots = parser_state.next_dots + 1
831 if num % multiplier == 0 and den % f == 0:
832 num = num / multiplier
834 current_dots = current_dots + d
836 return (str, num,den,current_dots)
839 def try_parse_rest (str, parser_state):
840 if not str or str[0] <> 'z' and str[0] <> 'x':
843 __main__.lyric_idx = -1
845 if parser_state.next_bar:
846 voices_append(parser_state.next_bar)
847 parser_state.next_bar = ''
855 (str, num,den,d) = parse_duration (str, parser_state)
856 voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
857 if parser_state.next_articulation:
858 voices_append (parser_state.next_articulation)
859 parser_state.next_articulation = ''
872 'J' : '', # ignore slide
873 'R' : '', # ignore roll
877 def try_parse_articulation (str, state):
878 while str and artic_tbl.has_key(str[:1]):
879 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
880 if not artic_tbl[str[:1]]:
881 sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
887 # s7m2 input doesnt care about spaces
888 if re.match('[ \t]*\(', str):
889 str = string.lstrip (str)
892 while str[:1] =='(' and str[1] not in DIGITS:
893 slur_begin = slur_begin + 1
894 state.next_articulation = state.next_articulation + '('
900 # remember accidental for rest of bar
902 def set_bar_acc(note, octave, acc, state):
905 n_oct = note + octave * 7
906 state.in_acc[n_oct] = acc
908 # get accidental set in this bar or UNDEF if not set
909 def get_bar_acc(note, octave, state):
910 n_oct = note + octave * 7
911 if state.in_acc.has_key(n_oct):
912 return(state.in_acc[n_oct])
916 def clear_bar_acc(state):
917 for k in state.in_acc.keys():
921 # if we are parsing a beam, close it off
922 def close_beam_state(state):
923 if state.parsing_beam and preserve_beams:
924 state.parsing_beam = 0
925 voices_append_back( ']' )
928 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
929 def try_parse_note (str, parser_state):
948 octave = parser_state.base_octave
949 if str[0] in "ABCDEFG":
950 str = string.lower (str[0]) + str[1:]
955 if str[0] in "abcdefg":
956 notename = (ord(str[0]) - ord('a') + 5)%7
959 return str # failed; not a note!
962 __main__.lyric_idx = -1
964 if parser_state.next_bar:
965 voices_append(parser_state.next_bar)
966 parser_state.next_bar = ''
971 while str[0] == '\'':
975 (str, num,den,current_dots) = parse_duration (str, parser_state)
977 if re.match('[ \t]*\)', str):
978 str = string.lstrip (str)
982 slur_end = slur_end + 1
986 bar_acc = get_bar_acc(notename, octave, parser_state)
987 pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
988 oct = octave_to_lilypond_quotes (octave)
989 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
993 voices_append ("%s%s%s%s" %
995 duration_to_lilypond_duration ((num,den), default_len, current_dots)))
997 set_bar_acc(notename, octave, acc, parser_state)
998 if parser_state.next_articulation:
999 articulation = articulation + parser_state.next_articulation
1000 parser_state.next_articulation = ''
1002 voices_append (articulation)
1004 if parser_state.parsing_tuplet:
1005 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
1006 if not parser_state.parsing_tuplet:
1009 voices_append ('-(' * slur_begin )
1011 voices_append ('-)' *slur_end )
1013 if preserve_beams and \
1014 str[0] in '^=_ABCDEFGabcdefg' and \
1015 not parser_state.parsing_beam and \
1016 not parser_state.parsing_tuplet:
1017 parser_state.parsing_beam = 1
1018 voices_append_back( '[' )
1022 def junk_space (str,state):
1023 while str and str[0] in '\t\n\r ':
1025 close_beam_state(state)
1030 def try_parse_guitar_chord (str, state):
1034 if str[0] == '_' or (str[0] == '^'):
1039 while str and str[0] != '"':
1045 gc = re.sub('#', '\\#', gc) # escape '#'s
1046 state.next_articulation = ("%c\"%s\"" % (position, gc)) \
1047 + state.next_articulation
1050 def try_parse_escape (str):
1051 if not str or str [0] != '\\':
1056 key_table = compute_key ()
1060 # |] thin-thick double bar line
1061 # || thin-thin double bar line
1062 # [| thick-thin double bar line
1065 # :: left-right repeat
1081 '|]' : '\\bar "|."',
1082 '||' : '\\bar "||"',
1083 '[|' : '\\bar "||"',
1085 '|:' : '\\repeat volta 2 {',
1086 '::' : '} \\repeat volta 2 {',
1087 '|1' : '} \\alternative{{',
1094 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1095 alternative_opener = ['|1', '|2', ':|2']
1096 repeat_ender = ['::', ':|']
1097 repeat_opener = ['::', '|:']
1098 in_repeat = [''] * 8
1099 doing_alternative = [''] * 8
1102 def try_parse_bar (str,state):
1103 global in_repeat, doing_alternative, using_old
1106 if current_voice_idx < 0:
1107 select_voice ('default', '')
1108 # first try the longer one
1109 for trylen in [3,2,1]:
1110 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1113 bs = "\\bar \"%s\"" % old_bar_dict[s]
1115 bs = "%s" % bar_dict[s]
1117 if s in alternative_opener:
1118 if not in_repeat[current_voice_idx]:
1120 bs = "\\bar \"%s\"" % old_bar_dict[s]
1122 doing_alternative[current_voice_idx] = 't'
1124 if s in repeat_ender:
1125 if not in_repeat[current_voice_idx]:
1126 sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1128 in_repeat[current_voice_idx] = ''
1130 if doing_alternative[current_voice_idx]:
1133 bs = "\\bar \"%s\"" % old_bar_dict[s]
1136 doing_alternative[current_voice_idx] = ''
1137 in_repeat[current_voice_idx] = ''
1138 if s in repeat_opener:
1139 in_repeat[current_voice_idx] = 't'
1141 bs = "\\bar \"%s\"" % old_bar_dict[s]
1146 state.next_bar = '|\n'
1148 clear_bar_acc(state)
1149 close_beam_state(state)
1151 if bs <> None or state.next_bar != '':
1152 if state.parsing_tuplet:
1153 state.parsing_tuplet =0
1154 voices_append ('} ')
1157 clear_bar_acc(state)
1158 close_beam_state(state)
1161 voices_append("} }")
1165 def try_parse_tie (str):
1168 voices_append (' ~ ')
1171 def bracket_escape (str, state):
1172 m = re.match ( '^([^\]]*)] *(.*)$', str)
1176 try_parse_header_line (cmd, state)
1179 def try_parse_chord_delims (str, state):
1182 if re.match('[A-Z]:', str): # bracket escape
1183 return bracket_escape(str, state)
1185 voices_append(state.next_bar)
1191 if state.plus_chord:
1193 state.plus_chord = 0
1196 voices_append(state.next_bar)
1199 state.plus_chord = 1
1207 while str[:1] ==')':
1212 voices_append ("\\spanrequest \\stop \"slur\"" * end)
1216 def try_parse_grace_delims (str, state):
1219 voices_append(state.next_bar)
1222 voices_append ('\\grace { ')
1230 def try_parse_comment (str):
1233 if str[0:5] == '%MIDI':
1234 #the nobarlines option is necessary for an abc to lilypond translator for
1235 #exactly the same reason abc2midi needs it: abc requires the user to enter
1236 #the note that will be printed, and MIDI and lilypond expect entry of the
1237 #pitch that will be played.
1239 #In standard 19th century musical notation, the algorithm for translating
1240 #between printed note and pitch involves using the barlines to determine
1241 #the scope of the accidentals.
1243 #Since ABC is frequently used for music in styles that do not use this
1244 #convention, such as most music written before 1700, or ethnic music in
1245 #non-western scales, it is necessary to be able to tell a translator that
1246 #the barlines should not affect its interpretation of the pitch.
1247 if (string.find(str,'nobarlines') > 0):
1249 elif str[0:3] == '%LY':
1250 p = string.find(str, 'voices')
1252 voices_append(str[p+7:])
1254 p = string.find(str, 'slyrics')
1256 slyrics_append(str[p+8:])
1258 #write other kinds of appending if we ever need them.
1263 def parse_file (fn):
1266 ls = map (lambda x: re.sub ("\r$", '', x), ls)
1268 select_voice('default', '')
1271 sys.stderr.write ("Line ... ")
1273 __main__.state = state_list[current_voice_idx]
1278 if not (lineno % happy_count):
1279 sys.stderr.write ('[%d]'% lineno)
1281 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1284 try_parse_comment(m.group(2))
1285 voices_append ('%% %s\n' % m.group(2))
1290 ln = try_parse_header_line (ln, state)
1292 # Try nibbling characters off until the line doesn't change.
1294 while ln != prev_ln:
1296 ln = try_parse_chord_delims (ln, state)
1297 ln = try_parse_rest (ln, state)
1298 ln = try_parse_articulation (ln,state)
1299 ln = try_parse_note (ln, state)
1300 ln = try_parse_bar (ln, state)
1301 ln = try_parse_tie (ln)
1302 ln = try_parse_escape (ln)
1303 ln = try_parse_guitar_chord (ln, state)
1304 ln = try_parse_tuplet_begin (ln, state)
1305 ln = try_parse_group_end (ln, state)
1306 ln = try_parse_grace_delims (ln, state)
1307 ln = junk_space (ln, state)
1310 error ("%s: %d: Huh? Don't understand\n" % (fn, lineno))
1311 left = orig_ln[0:-len (ln)]
1312 sys.stderr.write (left + '\n')
1313 sys.stderr.write (' ' * len (left) + ln + '\n')
1317 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1321 Convert ABC to lilypond.
1323 Usage: abc2ly [OPTIONS]... ABC-FILE
1326 -h, --help print this help
1327 -o, --output=FILE set output filename to FILE
1328 -v, --version show version information
1329 -s, --strict be strict about succes
1330 -b, --beams preserve ABC's notion of beams
1332 This program converts ABC music files (see
1333 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) to LilyPond input.
1336 Report bugs to bug-lilypond@gnu.org.
1338 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>, Laura Conrad
1339 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1342 def print_version ():
1343 print r"""abc2ly (GNU lilypond) %s""" % version
1347 (options, files) = getopt.getopt (sys.argv[1:], 'vo:hsb', ['help','version', 'output=', 'strict', 'beams'])
1353 if o== '--help' or o == '-h':
1356 elif o == '--version' or o == '-v':
1359 elif o == '--strict' or o == '-s':
1361 elif o == '--output' or o == '-o':
1363 elif o == '--beams' or o == '-b':
1371 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1376 sys.stderr.write ('Parsing `%s\'...\n' % f)
1379 if not out_filename:
1380 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1381 sys.stderr.write ('lilypond output to: `%s\'...' % out_filename)
1382 outf = open (out_filename, 'w')
1384 # dump_global (outf)
1385 dump_header (outf, header)
1390 sys.stderr.write ('\n')