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]
80 for d in ['@lilypond_datadir@',
82 sys.path.insert (0, os.path.join (d, 'python'))
84 # dynamic relocation, for GUB binaries.
85 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
86 for p in ['share', 'lib']:
87 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
88 sys.path.insert (0, datadir)
94 version = '@TOPLEVEL_VERSION@'
95 if version == '@' + 'TOPLEVEL_VERSION' + '@':
96 version = '(unknown version)' # uGUHGUHGHGUGH
102 header['footnotes'] = ''
107 repeat_state = [0] * 8
108 current_voice_idx = -1
109 current_lyric_idx = -1
115 global_key = [0] * 7 # UGH
116 names = ["One", "Two", "Three"]
123 sys.stderr.write (msg)
124 if global_options.strict:
129 return chr (i + ord('A'))
134 if re.match('-8va', s) or re.match('treble8', s):
135 # treble8 is used by abctab2ps; -8va is used by barfly,
136 # and by my patch to abc2ps. If there's ever a standard
137 # about this we'll support that.
139 state.base_octave = -1
140 voices_append("\\clef \"G_8\"\n")
141 elif re.match('^treble', s):
143 if re.match ('^-8', s):
145 state.base_octave = -2
146 voices_append("\\clef \"G_8\"\n")
148 state.base_octave = 0
149 voices_append("\\clef treble\n")
150 elif re.match('^alto', s):
152 state.base_octave = -1
153 voices_append ("\\clef alto\n" )
154 elif re.match('^bass',s ):
156 state.base_octave = -2
157 voices_append ("\\clef bass\n" )
160 def select_voice (name, rol):
161 if not voice_idx_dict.has_key (name):
162 state_list.append(Parser_state())
165 voice_idx_dict[name] = len (voices) -1
166 __main__.current_voice_idx = voice_idx_dict[name]
167 __main__.state = state_list[current_voice_idx]
169 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
173 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
177 if keyword == 'clef':
179 elif keyword == "name":
180 value = re.sub ('\\\\','\\\\\\\\', value)
182 voices_append ("\\set Staff.instrument = %s\n" % value )
184 __main__.part_names = 1
185 elif keyword == "sname" or keyword == "snm":
186 voices_append ("\\set Staff.instr = %s\n" % value )
190 def dump_header (outf,hdr):
191 outf.write ('\\header {\n')
195 hdr[k] = re.sub('"', '\\"', hdr[k])
196 outf.write ('\t%s = "%s"\n'% (k,hdr[k]))
199 def dump_lyrics (outf):
201 outf.write("\n\\score\n{\n \\lyrics\n <<\n")
202 for i in range (len (lyrics)):
203 outf.write ( lyrics [i])
205 outf.write(" >>\n \\layout{}\n}\n")
207 def dump_default_bar (outf):
209 Nowadays abc2ly outputs explicits barlines (?)
212 outf.write ("\n\\set Score.defaultBarType = \"empty\"\n")
215 def dump_slyrics (outf):
216 ks = voice_idx_dict.keys()
219 if re.match('[1-9]', k):
220 m = alphabet(string.atoi(k))
223 for i in range (len(slyrics[voice_idx_dict[k]])):
225 outf.write ("\nwords%sV%s = \lyricmode {" % (m, l))
226 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
229 def dump_voices (outf):
230 global doing_alternative, in_repeat
231 ks = voice_idx_dict.keys()
234 if re.match ('[1-9]', k):
235 m = alphabet(string.atoi(k))
238 outf.write ("\nvoice%s = {" % m)
239 dump_default_bar(outf)
240 if repeat_state[voice_idx_dict[k]]:
241 outf.write("\n\\repeat volta 2 {")
242 outf.write ("\n" + voices [voice_idx_dict[k]])
244 if doing_alternative[voice_idx_dict[k]]:
246 if in_repeat[voice_idx_dict[k]]:
252 #assume that Q takes the form "Q:1/4=120"
253 #There are other possibilities, but they are deprecated
254 if string.count(a, '/') == 1:
255 array=string.split(a,'/')
258 sys.stderr.write("abc2ly: Warning, unable to translate a Q specification with a numerator of %s: %s\n" % (numerator, a))
259 array2=string.split(array[1],'=')
260 denominator=array2[0]
262 duration=str(string.atoi(denominator)/string.atoi(numerator))
263 midi_specs=string.join(["\\tempo", duration, "=", perminute])
265 sys.stderr.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a)
267 def dump_score (outf):
274 ks = voice_idx_dict.keys ();
277 if re.match('[1-9]', k):
278 m = alphabet (string.atoi(k))
281 if k == 'default' and len (voice_idx_dict) > 1:
283 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
285 outf.write ("\t \\voicedefault\n")
286 outf.write ("\t \\voice%s " % m)
287 outf.write ("\n\t}\n")
290 for lyrics in slyrics [voice_idx_dict[k]]:
291 outf.write ("\n\t\\addlyrics { \n")
292 if re.match('[1-9]',k):
293 m = alphabet (string.atoi(k))
297 outf.write ( " \\words%sV%s } " % ( m, chr (l)) )
301 outf.write ("\n\t\\layout {\n")
302 outf.write ("\t}\n\t\\midi {%s}\n}\n" % midi_specs)
306 def set_default_length (s):
307 global length_specified
308 m = re.search ('1/([0-9]+)', s)
310 __main__.default_len = string.atoi ( m.group (1))
313 def set_default_len_from_time_sig (s):
314 m = re.search ('([0-9]+)/([0-9]+)', s)
316 n = string.atoi (m.group (1))
317 d = string.atoi (m.group (2))
318 if (n * 1.0 )/(d * 1.0) < 0.75:
319 __main__.default_len = 16
321 __main__.default_len = 8
330 sys.stderr.write ("can't open file: `%s'\n" % f)
334 sys.stderr.write ("gulped empty file: `%s'\n" % f)
339 # pitch manipulation. Tuples are (name, alteration).
340 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
341 # pitch in semitones.
342 def semitone_pitch (tup):
352 p = p + t* 2 + tup[1]
355 def fifth_above_pitch (tup):
356 (n, a) = (tup[0] + 4, tup[1])
358 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
369 (t,a) = fifth_above_pitch (p)
370 if semitone_pitch((t,a)) % 12 == 0:
382 (t,a) = quart_above_pitch (p)
383 if semitone_pitch((t,a)) % 12 == 0:
389 def quart_above_pitch (tup):
390 (n, a) = (tup[0] + 3, tup[1])
392 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
397 key_lookup = { # abc to lilypond key mode names
406 'mix' : 'mixolydian',
407 'mixolydian' : 'mixolydian',
420 if k and k[0] == '#':
423 elif k and k[0] == 'b':
427 return '%s \\major' % key
430 if not key_lookup.has_key (type):
431 #ugh, use lilylib, say WARNING:FILE:LINE:
432 sys.stderr.write ("abc2ly:warning:")
433 sys.stderr.write ("ignoring unknown key: `%s'" % orig)
434 sys.stderr.write ('\n')
436 return ("%s \\%s" % ( key, key_lookup[type]))
438 def shift_key (note, acc, shift):
439 s = semitone_pitch((note, acc))
440 s = (s + shift + 12) % 12
452 key_shift = { # semitone shifts for key mode names
475 intkey = (ord (k[0]) - ord('a') + 5) % 7
479 if k and k[0] == 'b':
482 elif k and k[0] == '#':
486 if k and key_shift.has_key(k):
487 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
488 keytup = (intkey, intkeyacc)
490 sharp_key_seq = sharp_keys ()
491 flat_key_seq = flat_keys ()
495 if keytup in sharp_key_seq:
497 key_count = sharp_key_seq.index (keytup)
498 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
500 elif keytup in flat_key_seq:
502 key_count = flat_key_seq.index (keytup)
503 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
510 key_table[a] = key_table[a] + accsign
525 def try_parse_tuplet_begin (str, state):
526 if re.match ('\([2-9]', str):
529 prev_tuplet_state = state.parsing_tuplet
530 state.parsing_tuplet = string.atoi (dig[0])
531 if prev_tuplet_state:
533 voices_append ("\\times %s {" % tup_lookup[dig])
536 def try_parse_group_end (str, state):
537 if str and str[0] in HSPACE:
539 close_beam_state(state)
542 def header_append (key, a):
544 if header.has_key (key):
545 s = header[key] + "\n"
549 linelen = len (v) - string.rfind(v, '\n')
550 if linelen + len (a) > 80:
554 def stuff_append (stuff, idx, a):
558 stuff [idx] = wordwrap(a, stuff[idx])
560 # ignore wordwrap since we are adding to the previous word
561 def stuff_append_back(stuff, idx, a):
565 point = len(stuff[idx])-1
566 while stuff[idx][point] is ' ':
569 stuff[idx] = stuff[idx][:point] + a + stuff[idx][point:]
571 def voices_append(a):
572 if current_voice_idx < 0:
573 select_voice ('default', '')
574 stuff_append (voices, current_voice_idx, a)
576 # word wrap really makes it hard to bind beams to the end of notes since it
577 # pushes out whitespace on every call. The _back functions do an append
578 # prior to the last space, effectively tagging whatever they are given
580 def voices_append_back(a):
581 if current_voice_idx < 0:
582 select_voice ('default', '')
583 stuff_append_back(voices, current_voice_idx, a)
585 def repeat_prepend():
587 if current_voice_idx < 0:
588 select_voice ('default', '')
590 repeat_state[current_voice_idx] = 't'
593 def lyrics_append(a):
594 a = re.sub ('#', '\\#', a) # latex does not like naked #'s
595 a = re.sub ('"', '\\"', a) # latex does not like naked "'s
596 a = '\t{ "' + a + '" }\n'
597 stuff_append (lyrics, current_lyric_idx, a)
599 # break lyrics to words and put "'s around words containing numbers and '"'s
603 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
607 word = re.sub('"', '\\"', word) # escape "
608 if re.match('.*[0-9"\(]', word):
609 word = re.sub('_', ' ', word) # _ causes probs inside ""
610 ret = ret + '\"' + word + '\" '
612 ret = ret + word + ' '
617 def slyrics_append(a):
618 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
619 a = re.sub ( '-', '- ', a) # split words with -
620 a = re.sub ( ' - - ', ' -- ', a) # unless was originally " -- "
621 a = re.sub ( '\\\\- ', '-', a) # unless \-
622 a = re.sub ( '~', '_', a) # ~ to space('_')
623 a = re.sub ( '\*', '_ ', a) # * to to space
624 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
625 if re.match('.*[0-9"\(]', a): # put numbers and " and ( into quoted string
627 a = re.sub ( '$', ' ', a) # insure space between lines
628 __main__.lyric_idx = lyric_idx + 1
629 if len(slyrics[current_voice_idx]) <= lyric_idx:
630 slyrics[current_voice_idx].append(a)
632 v = slyrics[current_voice_idx][lyric_idx]
633 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
636 def try_parse_header_line (ln, state):
637 global length_specified
638 m = re.match ('^([A-Za-z]): *(.*)$', ln)
644 a = re.sub('[ \t]*$','', a) #strip trailing blanks
645 if header.has_key('title'):
647 if len(header['title']):
648 # the non-ascii character
649 # in the string below is a
650 # punctuation dash. (TeX ---)
651 header['title'] = header['title'] + ' — ' + a
653 header['subtitle'] = a
658 if not state.common_time:
659 state.common_time = 1
660 voices_append (" \\override Staff.TimeSignature #\'style = #'C\n")
663 if not state.common_time:
664 state.common_time = 1
665 voices_append ("\\override Staff.TimeSignature #\'style = #'C\n")
667 if not length_specified:
668 set_default_len_from_time_sig (a)
672 voices_append ('\\time %s' % a)
677 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
679 # there may or may not be a space
680 # between the key letter and the mode
681 if key_lookup.has_key(m.group(2)[0:3]):
682 key_info = m.group(1) + m.group(2)[0:3]
683 clef_info = m.group(2)[4:]
685 key_info = m.group(1)
686 clef_info = m.group(2)
687 __main__.global_key = compute_key (key_info)
688 k = lily_key (key_info)
690 voices_append ('\\key %s' % k)
691 check_clef(clef_info)
693 __main__.global_key = compute_key (a)
696 voices_append ('\\key %s \\major' % k)
698 header ['footnotes'] = header['footnotes'] + '\\\\\\\\' + a
699 if g == 'O': # Origin
700 header ['origin'] = a
701 if g == 'X': # Reference Number
702 header ['crossRefNumber'] = a
705 if g == 'H': # History
706 header_append ('history', a)
709 if g == 'C': # Composer
710 if header.has_key('composer'):
712 header['composer'] = header['composer'] + '\\\\\\\\' + a
714 header['composer'] = a
716 header ['subtitle'] = a
717 if g == 'L': # Default note length
718 set_default_length (ln)
720 voice = re.sub (' .*$', '', a)
721 rest = re.sub ('^[^ \t]* *', '', a)
723 voices_append(state.next_bar)
725 select_voice (voice, rest)
728 if g == 'w': # vocals
735 # we use in this order specified accidental, active accidental for bar,
736 # active accidental for key
737 def pitch_to_lilypond_name (name, acc, bar_acc, key):
751 return(chr (name + ord('c')) + s)
754 def octave_to_lilypond_quotes (o):
767 while str and str[0] in DIGITS:
768 durstr = durstr + str[0]
773 n =string.atoi (durstr)
777 def duration_to_lilypond_duration (multiply_tup, defaultlen, dots):
779 # (num / den) / defaultlen < 1/base
780 while base * multiply_tup[0] < multiply_tup[1]:
783 if (multiply_tup[0] / multiply_tup[1]) == 2:
785 if (multiply_tup[0] / multiply_tup[1]) == 3:
788 if (multiply_tup[0] / multiply_tup[1]) == 4:
790 return '%s%s' % ( base, '.'* dots)
795 self.next_articulation = ''
799 self.parsing_tuplet = 0
803 self.parsing_beam = 0
807 # return (str, num,den,dots)
808 def parse_duration (str, parser_state):
810 den = parser_state.next_den
811 parser_state.next_den = 1
813 (str, num) = parse_num (str)
819 while str[:1] == '/':
823 (str, d) =parse_num (str)
827 den = den * default_len
829 current_dots = parser_state.next_dots
830 parser_state.next_dots = 0
831 if re.match ('[ \t]*[<>]', str):
832 while str[0] in HSPACE:
836 current_dots = current_dots + 1
837 parser_state.next_den = parser_state.next_den * 2
842 parser_state.next_dots = parser_state.next_dots + 1
850 if num % multiplier == 0 and den % f == 0:
851 num = num / multiplier
853 current_dots = current_dots + d
855 return (str, num,den,current_dots)
858 def try_parse_rest (str, parser_state):
859 if not str or str[0] <> 'z' and str[0] <> 'x':
862 __main__.lyric_idx = -1
864 if parser_state.next_bar:
865 voices_append(parser_state.next_bar)
866 parser_state.next_bar = ''
874 (str, num,den,d) = parse_duration (str, parser_state)
875 voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
876 if parser_state.next_articulation:
877 voices_append (parser_state.next_articulation)
878 parser_state.next_articulation = ''
891 'J' : '', # ignore slide
892 'R' : '', # ignore roll
898 def try_parse_articulation (str, state):
899 while str and artic_tbl.has_key(str[:1]):
900 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
901 if not artic_tbl[str[:1]]:
902 sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
908 # s7m2 input doesnt care about spaces
909 if re.match('[ \t]*\(', str):
910 str = string.lstrip (str)
913 while str[:1] =='(' and str[1] not in DIGITS:
914 slur_begin = slur_begin + 1
915 state.next_articulation = state.next_articulation + '('
921 # remember accidental for rest of bar
923 def set_bar_acc(note, octave, acc, state):
926 n_oct = note + octave * 7
927 state.in_acc[n_oct] = acc
929 # get accidental set in this bar or UNDEF if not set
930 def get_bar_acc(note, octave, state):
931 n_oct = note + octave * 7
932 if state.in_acc.has_key(n_oct):
933 return(state.in_acc[n_oct])
937 def clear_bar_acc(state):
938 for k in state.in_acc.keys():
942 # if we are parsing a beam, close it off
943 def close_beam_state(state):
944 if state.parsing_beam and global_options.beams:
945 state.parsing_beam = 0
946 voices_append_back( ']' )
949 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
950 def try_parse_note (str, parser_state):
969 octave = parser_state.base_octave
970 if str[0] in "ABCDEFG":
971 str = string.lower (str[0]) + str[1:]
976 if str[0] in "abcdefg":
977 notename = (ord(str[0]) - ord('a') + 5)%7
980 return str # failed; not a note!
983 __main__.lyric_idx = -1
985 if parser_state.next_bar:
986 voices_append(parser_state.next_bar)
987 parser_state.next_bar = ''
992 while str[0] == '\'':
996 (str, num,den,current_dots) = parse_duration (str, parser_state)
998 if re.match('[ \t]*\)', str):
999 str = string.lstrip (str)
1002 while str[:1] ==')':
1003 slur_end = slur_end + 1
1007 bar_acc = get_bar_acc(notename, octave, parser_state)
1008 pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
1009 oct = octave_to_lilypond_quotes (octave)
1010 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
1014 voices_append ("%s%s%s%s" %
1016 duration_to_lilypond_duration ((num,den), default_len, current_dots)))
1018 set_bar_acc(notename, octave, acc, parser_state)
1019 if parser_state.next_articulation:
1020 articulation = articulation + parser_state.next_articulation
1021 parser_state.next_articulation = ''
1023 voices_append (articulation)
1025 if parser_state.parsing_tuplet:
1026 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
1027 if not parser_state.parsing_tuplet:
1030 voices_append ('-(' * slur_begin )
1032 voices_append ('-)' *slur_end )
1034 if global_options.beams and \
1035 str[0] in '^=_ABCDEFGabcdefg' and \
1036 not parser_state.parsing_beam and \
1037 not parser_state.parsing_tuplet:
1038 parser_state.parsing_beam = 1
1039 voices_append_back( '[' )
1043 def junk_space (str,state):
1044 while str and str[0] in '\t\n\r ':
1046 close_beam_state(state)
1051 def try_parse_guitar_chord (str, state):
1055 if str[0] == '_' or (str[0] == '^'):
1060 while str and str[0] != '"':
1066 gc = re.sub('#', '\\#', gc) # escape '#'s
1067 state.next_articulation = ("%c\"%s\"" % (position, gc)) \
1068 + state.next_articulation
1071 def try_parse_escape (str):
1072 if not str or str [0] != '\\':
1077 key_table = compute_key ()
1081 # |] thin-thick double bar line
1082 # || thin-thin double bar line
1083 # [| thick-thin double bar line
1086 # :: left-right repeat
1102 '|]' : '\\bar "|."',
1103 '||' : '\\bar "||"',
1104 '[|' : '\\bar "||"',
1106 '|:' : '\\repeat volta 2 {',
1107 '::' : '} \\repeat volta 2 {',
1108 '|1' : '} \\alternative{{',
1115 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1116 alternative_opener = ['|1', '|2', ':|2']
1117 repeat_ender = ['::', ':|']
1118 repeat_opener = ['::', '|:']
1119 in_repeat = [''] * 8
1120 doing_alternative = [''] * 8
1123 def try_parse_bar (str,state):
1124 global in_repeat, doing_alternative, using_old
1127 if current_voice_idx < 0:
1128 select_voice ('default', '')
1129 # first try the longer one
1130 for trylen in [3,2,1]:
1131 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1134 bs = "\\bar \"%s\"" % old_bar_dict[s]
1136 bs = "%s" % bar_dict[s]
1138 if s in alternative_opener:
1139 if not in_repeat[current_voice_idx]:
1141 bs = "\\bar \"%s\"" % old_bar_dict[s]
1143 doing_alternative[current_voice_idx] = 't'
1145 if s in repeat_ender:
1146 if not in_repeat[current_voice_idx]:
1147 sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1149 in_repeat[current_voice_idx] = ''
1151 if doing_alternative[current_voice_idx]:
1154 bs = "\\bar \"%s\"" % old_bar_dict[s]
1157 doing_alternative[current_voice_idx] = ''
1158 in_repeat[current_voice_idx] = ''
1159 if s in repeat_opener:
1160 in_repeat[current_voice_idx] = 't'
1162 bs = "\\bar \"%s\"" % old_bar_dict[s]
1167 state.next_bar = '|\n'
1169 clear_bar_acc(state)
1170 close_beam_state(state)
1172 if bs <> None or state.next_bar != '':
1173 if state.parsing_tuplet:
1174 state.parsing_tuplet =0
1175 voices_append ('} ')
1178 clear_bar_acc(state)
1179 close_beam_state(state)
1182 voices_append("} }")
1186 def try_parse_tie (str):
1189 voices_append (' ~ ')
1192 def bracket_escape (str, state):
1193 m = re.match ( '^([^\]]*)] *(.*)$', str)
1197 try_parse_header_line (cmd, state)
1200 def try_parse_chord_delims (str, state):
1203 if re.match('[A-Z]:', str): # bracket escape
1204 return bracket_escape(str, state)
1206 voices_append(state.next_bar)
1208 voices_append ('<<')
1212 if state.plus_chord:
1213 voices_append ('>>')
1214 state.plus_chord = 0
1217 voices_append(state.next_bar)
1219 voices_append ('<<')
1220 state.plus_chord = 1
1228 while str[:1] ==')':
1233 voices_append ("\\spanrequest \\stop \"slur\"" * end)
1237 def try_parse_grace_delims (str, state):
1240 voices_append(state.next_bar)
1243 voices_append ('\\grace { ')
1251 def try_parse_comment (str):
1254 if str[0:5] == '%MIDI':
1255 #the nobarlines option is necessary for an abc to lilypond translator for
1256 #exactly the same reason abc2midi needs it: abc requires the user to enter
1257 #the note that will be printed, and MIDI and lilypond expect entry of the
1258 #pitch that will be played.
1260 #In standard 19th century musical notation, the algorithm for translating
1261 #between printed note and pitch involves using the barlines to determine
1262 #the scope of the accidentals.
1264 #Since ABC is frequently used for music in styles that do not use this
1265 #convention, such as most music written before 1700, or ethnic music in
1266 #non-western scales, it is necessary to be able to tell a translator that
1267 #the barlines should not affect its interpretation of the pitch.
1268 if 'nobarlines' in str:
1270 elif str[0:3] == '%LY':
1271 p = string.find(str, 'voices')
1273 voices_append(str[p+7:])
1275 p = string.find(str, 'slyrics')
1277 slyrics_append(str[p+8:])
1279 #write other kinds of appending if we ever need them.
1284 def parse_file (fn):
1287 ls = map (lambda x: re.sub ("\r$", '', x), ls)
1289 select_voice('default', '')
1292 sys.stderr.write ("Line ... ")
1294 __main__.state = state_list[current_voice_idx]
1299 if not (lineno % happy_count):
1300 sys.stderr.write ('[%d]'% lineno)
1302 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1305 try_parse_comment(m.group(2))
1306 voices_append ('%% %s\n' % m.group(2))
1311 ln = try_parse_header_line (ln, state)
1313 # Try nibbling characters off until the line doesn't change.
1315 while ln != prev_ln:
1317 ln = try_parse_chord_delims (ln, state)
1318 ln = try_parse_rest (ln, state)
1319 ln = try_parse_articulation (ln,state)
1320 ln = try_parse_note (ln, state)
1321 ln = try_parse_bar (ln, state)
1322 ln = try_parse_tie (ln)
1323 ln = try_parse_escape (ln)
1324 ln = try_parse_guitar_chord (ln, state)
1325 ln = try_parse_tuplet_begin (ln, state)
1326 ln = try_parse_group_end (ln, state)
1327 ln = try_parse_grace_delims (ln, state)
1328 ln = junk_space (ln, state)
1331 error ("%s: %d: Huh? Don't understand\n" % (fn, lineno))
1332 left = orig_ln[0:-len (ln)]
1333 sys.stderr.write (left + '\n')
1334 sys.stderr.write (' ' * len (left) + ln + '\n')
1338 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1341 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>, Laura Conrad
1342 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1345 def print_version ():
1346 print r"""abc2ly (GNU lilypond) %s""" % version
1348 def get_option_parser ():
1349 p = ly.get_option_parser (usage='abc2ly [OPTIONS] FILE',
1350 version="abc2ly (LilyPond) @TOPLEVEL_VERSION@",
1351 description=_('''This program converts ABC music files (see
1352 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) to LilyPond input.'''))
1354 p.add_option ('-o', '--output', metavar='FILE',help=_("set output filename to FILE"),
1356 p.add_option ('-s', '--strict', help=_("be strict about succes"),
1357 action='store_true')
1358 p.add_option ('-b', '--beams', help=_("preserve ABC's notion of beams"))
1359 p.add_option_group ('bugs',
1360 description='''Report bugs via http://post.gmane.org/post.php'''
1361 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
1366 option_parser = get_option_parser()
1367 (global_options, files) = option_parser.parse_args()
1372 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1377 sys.stderr.write ('Parsing `%s\'...\n' % f)
1380 if not global_options.output:
1381 global_options.output = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1382 sys.stderr.write ('lilypond output to: `%s\'...' % global_options.output)
1383 outf = open (global_options.output, 'w')
1385 # don't substitute @VERSION@. We want this to reflect
1386 # the last version that was verified to work.
1387 outf.write ('\\version "2.7.40"\n')
1389 # dump_global (outf)
1390 dump_header (outf, header)
1395 sys.stderr.write ('\n')