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)
167 ##voices_append ("\\property Staff.instrument = %s\n" % value )
168 voices_append ("\\set Staff.instrument = %s\n" % value )
170 __main__.part_names = 1
171 elif keyword == "sname" or keyword == "snm":
172 ##voices_append ("\\property Staff.instr = %s\n" % value )
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 \\context Lyrics\n <<\n")
189 for i in range (len (lyrics)):
190 outf.write ( lyrics [i])
192 outf.write(" >>\n \\paper{}\n}\n")
194 def dump_default_bar (outf):
196 Nowadays abc2ly outputs explicits barlines (?)
199 ##outf.write ("\n\\property Score.defaultBarType = \"empty\"\n")
200 outf.write ("\n\\set Score.defaultBarType = \"empty\"\n")
203 def dump_slyrics (outf):
204 ks = voice_idx_dict.keys()
207 if re.match('[1-9]', k):
208 m = alphabet[string.atoi(k)]
211 for i in range (len(slyrics[voice_idx_dict[k]])):
213 outf.write ("\nwords%sV%s = \\lyrics {" % (m, l))
214 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
217 def dump_voices (outf):
218 global doing_alternative, in_repeat
219 ks = voice_idx_dict.keys()
222 if re.match ('[1-9]', k):
223 m = alphabet[string.atoi(k)]
226 outf.write ("\nvoice%s = \\notes {" % m)
227 dump_default_bar(outf)
228 if repeat_state[voice_idx_dict[k]]:
229 outf.write("\n\\repeat volta 2 {")
230 outf.write ("\n" + voices [voice_idx_dict[k]])
232 if doing_alternative[voice_idx_dict[k]]:
234 if in_repeat[voice_idx_dict[k]]:
240 #assume that Q takes the form "Q:1/4=120"
241 #There are other possibilities, but they are deprecated
242 if string.count(a, '/') == 1:
243 array=string.split(a,'/')
246 sys.stderr.write("abc2ly: Warning, unable to translate a Q specification with a numerator of %s: %s\n" % (numerator, a))
247 array2=string.split(array[1],'=')
248 denominator=array2[0]
250 duration=str(string.atoi(denominator)/string.atoi(numerator))
251 midi_specs=string.join(["\\tempo", duration, "=", perminute])
253 sys.stderr.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a)
255 def dump_score (outf):
256 outf.write (r"""\score{
260 ks = voice_idx_dict.keys ();
263 if re.match('[1-9]', k):
264 m = alphabet[string.atoi(k)]
267 if k == 'default' and len (voice_idx_dict) > 1:
269 if len ( slyrics [voice_idx_dict[k]] ):
270 outf.write ("\n \\addlyrics")
271 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
273 outf.write ("\t \\voicedefault\n")
274 outf.write ("\t \\voice%s " % m)
275 outf.write ("\n\t}\n")
276 if len ( slyrics [voice_idx_dict[k]] ):
277 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<<\t" % k)
278 if re.match('[1-9]',k):
279 m = alphabet[string.atoi(k)]
282 for i in range (len(slyrics[voice_idx_dict[k]])):
284 outf.write("\n\t { \\words%sV%s }" % ( m, l) )
285 outf.write ( "\n\t>>\n" )
287 outf.write ("\n\t\\paper {\n")
289 outf.write ("\t \\translator \n\t {\n")
290 outf.write ("\t\t\\StaffContext\n")
291 # outf.write ("\t\t\\consists Staff_margin_engraver\n")
292 outf.write ("\t }\n")
293 outf.write ("\t}\n\t\\midi {%s}\n}\n" % midi_specs)
297 def set_default_length (s):
298 global length_specified
299 m = re.search ('1/([0-9]+)', s)
301 __main__.default_len = string.atoi ( m.group (1))
304 def set_default_len_from_time_sig (s):
305 m = re.search ('([0-9]+)/([0-9]+)', s)
307 n = string.atoi (m.group (1))
308 d = string.atoi (m.group (2))
309 if (n * 1.0 )/(d * 1.0) < 0.75:
310 __main__.default_len = 16
312 __main__.default_len = 8
321 sys.stderr.write ("can't open file: `%s'\n" % f)
325 sys.stderr.write ("gulped empty file: `%s'\n" % f)
330 # pitch manipulation. Tuples are (name, alteration).
331 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
332 # pitch in semitones.
333 def semitone_pitch (tup):
343 p = p + t* 2 + tup[1]
346 def fifth_above_pitch (tup):
347 (n, a) = (tup[0] + 4, tup[1])
349 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
360 (t,a) = fifth_above_pitch (p)
361 if semitone_pitch((t,a)) % 12 == 0:
373 (t,a) = quart_above_pitch (p)
374 if semitone_pitch((t,a)) % 12 == 0:
380 def quart_above_pitch (tup):
381 (n, a) = (tup[0] + 3, tup[1])
383 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
388 key_lookup = { # abc to lilypond key mode names
397 'mix' : 'mixolydian',
398 'mixolydian' : 'mixolydian',
411 if k and k[0] == '#':
414 elif k and k[0] == 'b':
418 return '%s \\major' % key
421 if not key_lookup.has_key (type):
422 #ugh, use lilylib, say WARNING:FILE:LINE:
423 sys.stderr.write ("abc2ly:warning:")
424 sys.stderr.write ("ignoring unknown key: `%s'" % orig)
425 sys.stderr.write ('\n')
427 return ("%s \\%s" % ( key, key_lookup[type]))
429 def shift_key (note, acc, shift):
430 s = semitone_pitch((note, acc))
431 s = (s + shift + 12) % 12
443 key_shift = { # semitone shifts for key mode names
466 intkey = (ord (k[0]) - ord('a') + 5) % 7
470 if k and k[0] == 'b':
473 elif k and k[0] == '#':
477 if k and key_shift.has_key(k):
478 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
479 keytup = (intkey, intkeyacc)
481 sharp_key_seq = sharp_keys ()
482 flat_key_seq = flat_keys ()
486 if keytup in sharp_key_seq:
488 key_count = sharp_key_seq.index (keytup)
489 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
491 elif keytup in flat_key_seq:
493 key_count = flat_key_seq.index (keytup)
494 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
501 key_table[a] = key_table[a] + accsign
516 def try_parse_tuplet_begin (str, state):
517 if re.match ('\([2-9]', str):
520 prev_tuplet_state = state.parsing_tuplet
521 state.parsing_tuplet = string.atoi (dig[0])
522 if prev_tuplet_state:
524 voices_append ("\\times %s {" % tup_lookup[dig])
527 def try_parse_group_end (str, state):
528 if str and str[0] in HSPACE:
530 close_beam_state(state)
533 def header_append (key, a):
535 if header.has_key (key):
536 s = header[key] + "\n"
540 linelen = len (v) - string.rfind(v, '\n')
541 if linelen + len (a) > 80:
545 def stuff_append (stuff, idx, a):
549 stuff [idx] = wordwrap(a, stuff[idx])
551 # ignore wordwrap since we are adding to the previous word
552 def stuff_append_back(stuff, idx, a):
556 point = len(stuff[idx])-1
557 while stuff[idx][point] is ' ':
560 stuff[idx] = stuff[idx][:point] + a + stuff[idx][point:]
562 def voices_append(a):
563 if current_voice_idx < 0:
564 select_voice ('default', '')
565 stuff_append (voices, current_voice_idx, a)
567 # word wrap really makes it hard to bind beams to the end of notes since it
568 # pushes out whitespace on every call. The _back functions do an append
569 # prior to the last space, effectively tagging whatever they are given
571 def voices_append_back(a):
572 if current_voice_idx < 0:
573 select_voice ('default', '')
574 stuff_append_back(voices, current_voice_idx, a)
576 def repeat_prepend():
578 if current_voice_idx < 0:
579 select_voice ('default', '')
581 repeat_state[current_voice_idx] = 't'
584 def lyrics_append(a):
585 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
586 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
587 a = '\t{ \\lyrics "' + a + '" }\n'
588 stuff_append (lyrics, current_lyric_idx, a)
590 # break lyrics to words and put "'s around words containing numbers and '"'s
594 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
598 word = re.sub('"', '\\"', word) # escape "
599 if re.match('.*[0-9"\(]', word):
600 word = re.sub('_', ' ', word) # _ causes probs inside ""
601 ret = ret + '\"' + word + '\" '
603 ret = ret + word + ' '
608 def slyrics_append(a):
609 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
610 a = re.sub ( '-', '- ', a) # split words with -
611 a = re.sub ( '\\\\- ', '-', a) # unless \-
612 a = re.sub ( '~', '_', a) # ~ to space('_')
613 a = re.sub ( '\*', '_ ', a) # * to to space
614 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
615 if re.match('.*[0-9"\(]', a): # put numbers and " and ( into quoted string
617 a = re.sub ( '$', ' ', a) # insure space between lines
618 __main__.lyric_idx = lyric_idx + 1
619 if len(slyrics[current_voice_idx]) <= lyric_idx:
620 slyrics[current_voice_idx].append(a)
622 v = slyrics[current_voice_idx][lyric_idx]
623 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
626 def try_parse_header_line (ln, state):
627 global length_specified
628 m = re.match ('^([A-Za-z]): *(.*)$', ln)
634 a = re.sub('[ \t]*$','', a) #strip trailing blanks
635 if header.has_key('title'):
637 if len(header['title']):
638 header['title'] = header['title'] + '\\\\\\\\' + a
640 header['subtitle'] = a
645 if not state.common_time:
646 state.common_time = 1
647 voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
650 if not state.common_time:
651 state.common_time = 1
652 voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
654 if not length_specified:
655 set_default_len_from_time_sig (a)
659 voices_append ('\\time %s' % a)
664 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
666 # there may or may not be a space
667 # between the key letter and the mode
668 if key_lookup.has_key(m.group(2)[0:3]):
669 key_info = m.group(1) + m.group(2)[0:3]
670 clef_info = m.group(2)[4:]
672 key_info = m.group(1)
673 clef_info = m.group(2)
674 __main__.global_key = compute_key (key_info)
675 k = lily_key (key_info)
677 voices_append ('\\key %s' % k)
678 check_clef(clef_info)
680 __main__.global_key = compute_key (a)
683 voices_append ('\\key %s \\major' % k)
685 header ['footnotes'] = header['footnotes'] + '\\\\\\\\' + a
686 if g == 'O': # Origin
687 header ['origin'] = a
688 if g == 'X': # Reference Number
689 header ['crossRefNumber'] = a
692 if g == 'H': # History
693 header_append ('history', a)
696 if g == 'C': # Composer
697 if header.has_key('composer'):
699 header['composer'] = header['composer'] + '\\\\\\\\' + a
701 header['composer'] = a
703 header ['subtitle'] = a
704 if g == 'L': # Default note length
705 set_default_length (ln)
707 voice = re.sub (' .*$', '', a)
708 rest = re.sub ('^[^ \t]* *', '', a)
710 voices_append(state.next_bar)
712 select_voice (voice, rest)
715 if g == 'w': # vocals
722 # we use in this order specified accidental, active accidental for bar,
723 # active accidental for key
724 def pitch_to_lilypond_name (name, acc, bar_acc, key):
738 return(chr (name + ord('c')) + s)
741 def octave_to_lilypond_quotes (o):
754 while str and str[0] in DIGITS:
755 durstr = durstr + str[0]
760 n =string.atoi (durstr)
764 def duration_to_lilypond_duration (multiply_tup, defaultlen, dots):
766 # (num / den) / defaultlen < 1/base
767 while base * multiply_tup[0] < multiply_tup[1]:
770 if (multiply_tup[0] / multiply_tup[1]) == 2:
772 if (multiply_tup[0] / multiply_tup[1]) == 3:
775 if (multiply_tup[0] / multiply_tup[1]) == 4:
777 return '%s%s' % ( base, '.'* dots)
782 self.next_articulation = ''
786 self.parsing_tuplet = 0
790 self.parsing_beam = 0
794 # return (str, num,den,dots)
795 def parse_duration (str, parser_state):
797 den = parser_state.next_den
798 parser_state.next_den = 1
800 (str, num) = parse_num (str)
806 while str[:1] == '/':
810 (str, d) =parse_num (str)
814 den = den * default_len
816 current_dots = parser_state.next_dots
817 parser_state.next_dots = 0
818 if re.match ('[ \t]*[<>]', str):
819 while str[0] in HSPACE:
823 current_dots = current_dots + 1
824 parser_state.next_den = parser_state.next_den * 2
829 parser_state.next_dots = parser_state.next_dots + 1
837 if num % multiplier == 0 and den % f == 0:
838 num = num / multiplier
840 current_dots = current_dots + d
842 return (str, num,den,current_dots)
845 def try_parse_rest (str, parser_state):
846 if not str or str[0] <> 'z' and str[0] <> 'x':
849 __main__.lyric_idx = -1
851 if parser_state.next_bar:
852 voices_append(parser_state.next_bar)
853 parser_state.next_bar = ''
861 (str, num,den,d) = parse_duration (str, parser_state)
862 voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
863 if parser_state.next_articulation:
864 voices_append (parser_state.next_articulation)
865 parser_state.next_articulation = ''
878 'J' : '', # ignore slide
879 'R' : '', # ignore roll
883 def try_parse_articulation (str, state):
884 while str and artic_tbl.has_key(str[:1]):
885 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
886 if not artic_tbl[str[:1]]:
887 sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
893 # s7m2 input doesnt care about spaces
894 if re.match('[ \t]*\(', str):
895 str = string.lstrip (str)
898 while str[:1] =='(' and str[1] not in DIGITS:
899 slur_begin = slur_begin + 1
900 state.next_articulation = state.next_articulation + '('
906 # remember accidental for rest of bar
908 def set_bar_acc(note, octave, acc, state):
911 n_oct = note + octave * 7
912 state.in_acc[n_oct] = acc
914 # get accidental set in this bar or UNDEF if not set
915 def get_bar_acc(note, octave, state):
916 n_oct = note + octave * 7
917 if state.in_acc.has_key(n_oct):
918 return(state.in_acc[n_oct])
922 def clear_bar_acc(state):
923 for k in state.in_acc.keys():
927 # if we are parsing a beam, close it off
928 def close_beam_state(state):
929 if state.parsing_beam and preserve_beams:
930 state.parsing_beam = 0
931 voices_append_back( ']' )
934 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
935 def try_parse_note (str, parser_state):
954 octave = parser_state.base_octave
955 if str[0] in "ABCDEFG":
956 str = string.lower (str[0]) + str[1:]
961 if str[0] in "abcdefg":
962 notename = (ord(str[0]) - ord('a') + 5)%7
965 return str # failed; not a note!
968 __main__.lyric_idx = -1
970 if parser_state.next_bar:
971 voices_append(parser_state.next_bar)
972 parser_state.next_bar = ''
977 while str[0] == '\'':
981 (str, num,den,current_dots) = parse_duration (str, parser_state)
983 if re.match('[ \t]*\)', str):
984 str = string.lstrip (str)
988 slur_end = slur_end + 1
992 bar_acc = get_bar_acc(notename, octave, parser_state)
993 pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
994 oct = octave_to_lilypond_quotes (octave)
995 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
999 voices_append ("%s%s%s%s" %
1001 duration_to_lilypond_duration ((num,den), default_len, current_dots)))
1003 set_bar_acc(notename, octave, acc, parser_state)
1004 if parser_state.next_articulation:
1005 articulation = articulation + parser_state.next_articulation
1006 parser_state.next_articulation = ''
1008 voices_append (articulation)
1010 if parser_state.parsing_tuplet:
1011 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
1012 if not parser_state.parsing_tuplet:
1015 voices_append ('-(' * slur_begin )
1017 voices_append ('-)' *slur_end )
1019 if preserve_beams and \
1020 str[0] in '^=_ABCDEFGabcdefg' and \
1021 not parser_state.parsing_beam and \
1022 not parser_state.parsing_tuplet:
1023 parser_state.parsing_beam = 1
1024 voices_append_back( '[' )
1028 def junk_space (str,state):
1029 while str and str[0] in '\t\n\r ':
1031 close_beam_state(state)
1036 def try_parse_guitar_chord (str, state):
1040 if str[0] == '_' or (str[0] == '^'):
1045 while str and str[0] != '"':
1051 gc = re.sub('#', '\\#', gc) # escape '#'s
1052 state.next_articulation = ("%c\"%s\"" % (position, gc)) \
1053 + state.next_articulation
1056 def try_parse_escape (str):
1057 if not str or str [0] != '\\':
1062 key_table = compute_key ()
1066 # |] thin-thick double bar line
1067 # || thin-thin double bar line
1068 # [| thick-thin double bar line
1071 # :: left-right repeat
1087 '|]' : '\\bar "|."',
1088 '||' : '\\bar "||"',
1089 '[|' : '\\bar "||"',
1091 '|:' : '\\repeat volta 2 {',
1092 '::' : '} \\repeat volta 2 {',
1093 '|1' : '} \\alternative{{',
1100 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1101 alternative_opener = ['|1', '|2', ':|2']
1102 repeat_ender = ['::', ':|']
1103 repeat_opener = ['::', '|:']
1104 in_repeat = [''] * 8
1105 doing_alternative = [''] * 8
1108 def try_parse_bar (str,state):
1109 global in_repeat, doing_alternative, using_old
1112 if current_voice_idx < 0:
1113 select_voice ('default', '')
1114 # first try the longer one
1115 for trylen in [3,2,1]:
1116 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1119 bs = "\\bar \"%s\"" % old_bar_dict[s]
1121 bs = "%s" % bar_dict[s]
1123 if s in alternative_opener:
1124 if not in_repeat[current_voice_idx]:
1126 bs = "\\bar \"%s\"" % old_bar_dict[s]
1128 doing_alternative[current_voice_idx] = 't'
1130 if s in repeat_ender:
1131 if not in_repeat[current_voice_idx]:
1132 sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1134 in_repeat[current_voice_idx] = ''
1136 if doing_alternative[current_voice_idx]:
1139 bs = "\\bar \"%s\"" % old_bar_dict[s]
1142 doing_alternative[current_voice_idx] = ''
1143 in_repeat[current_voice_idx] = ''
1144 if s in repeat_opener:
1145 in_repeat[current_voice_idx] = 't'
1147 bs = "\\bar \"%s\"" % old_bar_dict[s]
1152 state.next_bar = '|\n'
1154 clear_bar_acc(state)
1155 close_beam_state(state)
1157 if bs <> None or state.next_bar != '':
1158 if state.parsing_tuplet:
1159 state.parsing_tuplet =0
1160 voices_append ('} ')
1163 clear_bar_acc(state)
1164 close_beam_state(state)
1167 voices_append("} }")
1171 def try_parse_tie (str):
1174 voices_append (' ~ ')
1177 def bracket_escape (str, state):
1178 m = re.match ( '^([^\]]*)] *(.*)$', str)
1182 try_parse_header_line (cmd, state)
1185 def try_parse_chord_delims (str, state):
1188 if re.match('[A-Z]:', str): # bracket escape
1189 return bracket_escape(str, state)
1191 voices_append(state.next_bar)
1193 voices_append ('<<')
1197 if state.plus_chord:
1198 voices_append ('>>')
1199 state.plus_chord = 0
1202 voices_append(state.next_bar)
1204 voices_append ('<<')
1205 state.plus_chord = 1
1213 while str[:1] ==')':
1218 voices_append ("\\spanrequest \\stop \"slur\"" * end)
1222 def try_parse_grace_delims (str, state):
1225 voices_append(state.next_bar)
1228 voices_append ('\\grace { ')
1236 def try_parse_comment (str):
1239 if str[0:5] == '%MIDI':
1240 #the nobarlines option is necessary for an abc to lilypond translator for
1241 #exactly the same reason abc2midi needs it: abc requires the user to enter
1242 #the note that will be printed, and MIDI and lilypond expect entry of the
1243 #pitch that will be played.
1245 #In standard 19th century musical notation, the algorithm for translating
1246 #between printed note and pitch involves using the barlines to determine
1247 #the scope of the accidentals.
1249 #Since ABC is frequently used for music in styles that do not use this
1250 #convention, such as most music written before 1700, or ethnic music in
1251 #non-western scales, it is necessary to be able to tell a translator that
1252 #the barlines should not affect its interpretation of the pitch.
1253 if (string.find(str,'nobarlines') > 0):
1255 elif str[0:3] == '%LY':
1256 p = string.find(str, 'voices')
1258 voices_append(str[p+7:])
1260 p = string.find(str, 'slyrics')
1262 slyrics_append(str[p+8:])
1264 #write other kinds of appending if we ever need them.
1269 def parse_file (fn):
1272 ls = map (lambda x: re.sub ("\r$", '', x), ls)
1274 select_voice('default', '')
1277 sys.stderr.write ("Line ... ")
1279 __main__.state = state_list[current_voice_idx]
1284 if not (lineno % happy_count):
1285 sys.stderr.write ('[%d]'% lineno)
1287 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1290 try_parse_comment(m.group(2))
1291 voices_append ('%% %s\n' % m.group(2))
1296 ln = try_parse_header_line (ln, state)
1298 # Try nibbling characters off until the line doesn't change.
1300 while ln != prev_ln:
1302 ln = try_parse_chord_delims (ln, state)
1303 ln = try_parse_rest (ln, state)
1304 ln = try_parse_articulation (ln,state)
1305 ln = try_parse_note (ln, state)
1306 ln = try_parse_bar (ln, state)
1307 ln = try_parse_tie (ln)
1308 ln = try_parse_escape (ln)
1309 ln = try_parse_guitar_chord (ln, state)
1310 ln = try_parse_tuplet_begin (ln, state)
1311 ln = try_parse_group_end (ln, state)
1312 ln = try_parse_grace_delims (ln, state)
1313 ln = junk_space (ln, state)
1316 error ("%s: %d: Huh? Don't understand\n" % (fn, lineno))
1317 left = orig_ln[0:-len (ln)]
1318 sys.stderr.write (left + '\n')
1319 sys.stderr.write (' ' * len (left) + ln + '\n')
1323 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1327 Convert ABC to lilypond.
1329 Usage: abc2ly [OPTIONS]... ABC-FILE
1332 -h, --help print this help
1333 -o, --output=FILE set output filename to FILE
1334 -v, --version show version information
1335 -s, --strict be strict about succes
1336 -b, --beams preserve ABC's notion of beams
1338 This program converts ABC music files (see
1339 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) to LilyPond input.
1342 Report bugs to bug-lilypond@gnu.org.
1344 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>, Laura Conrad
1345 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1348 def print_version ():
1349 print r"""abc2ly (GNU lilypond) %s""" % version
1353 (options, files) = getopt.getopt (sys.argv[1:], 'vo:hsb', ['help','version', 'output=', 'strict', 'beams'])
1359 if o== '--help' or o == '-h':
1362 elif o == '--version' or o == '-v':
1365 elif o == '--strict' or o == '-s':
1367 elif o == '--output' or o == '-o':
1369 elif o == '--beams' or o == '-b':
1377 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1382 sys.stderr.write ('Parsing `%s\'...\n' % f)
1385 if not out_filename:
1386 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1387 sys.stderr.write ('lilypond output to: `%s\'...' % out_filename)
1388 outf = open (out_filename, 'w')
1390 # dump_global (outf)
1391 dump_header (outf, header)
1396 sys.stderr.write ('\n')