3 # convert-lilypond.py -- convertor for lilypond versions
5 # source file of the GNU LilyPond music typesetter
10 # use -f and -t for -s output
16 program_name = 'convert-ly'
17 version = '@TOPLEVEL_VERSION@'
27 lilypond_version_re_str = '\\\\version *\"(.*)\"'
28 lilypond_version_re = re.compile(lilypond_version_re_str)
31 return '%s (GNU LilyPond) %s' %(program_name, version);
34 sys.stderr.write (program_id () + '\n')
38 r"""Usage: %s [OPTION]... [FILE]...
39 Try to convert to newer lilypond-versions. The version number of the
40 input is guessed by default from \version directive
43 -h, --help print this help
44 -e, --edit in place edit
45 -f, --from=VERSION start from version
46 -s, --show-rules print all rules.
47 -t, --to=VERSION target version
48 --version print program version
50 Report bugs to bugs-gnu-music@gnu.org
59 sys.stdout.write (r"""%s
61 This is free software. It is covered by the GNU General Public
62 License, and you are welcome to change it and/or distribute copies of
63 it under certain conditions. invoke as `%s --warranty' for more
66 """ % (program_id() , program_name))
75 print 'can\'t open file: ' + f + '\n'
79 print 'gulped empty file: ' + f + '\n'
84 return tuple (map (string.atoi, string.split (s,'.')))
87 return string.join (map (lambda x: '%s' % x, list (t)), '.')
89 def version_cmp (t1, t2):
95 def guess_lilypond_version(filename):
96 s = gulp_file (filename)
97 m = lilypond_version_re.search (s)
103 class FatalConversionError:
108 def show_rules (file):
109 for x in conversions:
110 file.write ('%s: %s\n' % (tup_to_str (x[0]), x[2]))
112 ############################
114 if 1: # need new a namespace
116 if re.search ('\\\\octave', str):
117 sys.stderr.write ('\nNot smart enough to convert \\octave')
118 raise FatalConversionError()
122 conversions.append ((
123 ((0,1,19), conv, 'deprecated \\octave; can\'t convert automatically')))
126 if 1: # need new a namespace
128 str = re.sub ('\\\\textstyle([^;]+);',
129 '\\\\property Lyrics . textstyle = \\1', str)
130 str = re.sub ('\\\\key([^;]+);', '\\\\accidentals \\1;', str)
134 conversions.append ((
135 ((0,1,20), conv, 'deprecated \\textstyle, new \key syntax')))
140 str = re.sub ('\\\\musical_pitch', '\\\\musicalpitch',str)
141 str = re.sub ('\\\\meter', '\\\\time',str)
145 conversions.append ((
146 ((0,1,21), conv, '\\musical_pitch -> \\musicalpitch, '+
147 '\\meter -> \\time')))
153 conversions.append ((
154 ((1,0,0), conv, '0.1.21 -> 1.0.0 ')))
159 str = re.sub ('\\\\accidentals', '\\\\keysignature',str)
160 str = re.sub ('specialaccidentals *= *1', 'keyoctaviation = 0',str)
161 str = re.sub ('specialaccidentals *= *0', 'keyoctaviation = 1',str)
165 conversions.append ((
166 ((1,0,1), conv, '\\accidentals -> \\keysignature, ' +
167 'specialaccidentals -> keyoctaviation')))
171 if re.search ('\\\\header', str):
172 sys.stderr.write ('\nNot smart enough to convert to new \\header format')
175 conversions.append (((1,0,2), conv, '\\header { key = concat + with + operator }'))
179 str = re.sub ('\\\\melodic', '\\\\notes',str)
183 conversions.append (((1,0,3), conv, '\\melodic -> \\notes'))
187 str = re.sub ('default_paper *=', '',str)
188 str = re.sub ('default_midi *=', '',x)
192 conversions.append (((1,0,4), conv, 'default_{paper,midi}'))
196 str = re.sub ('ChoireStaff', 'ChoirStaff',str)
197 str = re.sub ('\\output', 'output = ',str)
201 conversions.append (((1,0,5), conv, 'ChoireStaff -> ChoirStaff'))
205 if re.search ('[a-zA-Z]+ = *\\translator',str):
206 sys.stderr.write ('\nNot smart enough to change \\translator syntax')
207 raise FatalConversionError()
210 conversions.append (((1,0,6), conv, 'foo = \\translator {\\type .. } ->\\translator {\\type ..; foo; }'))
215 str = re.sub ('\\\\lyric', '\\\\lyrics',str)
219 conversions.append (((1,0,7), conv, '\\lyric -> \\lyrics'))
223 str = re.sub ('\\\\\\[/3+', '\\\\times 2/3 { ',str)
224 str = re.sub ('\\[/3+', '\\\\times 2/3 { [',str)
225 str = re.sub ('\\\\\\[([0-9/]+)', '\\\\times \\1 {',str)
226 str = re.sub ('\\[([0-9/]+)', '\\\\times \\1 { [',str)
227 str = re.sub ('\\\\\\]([0-9/]+)', '}', str)
228 str = re.sub ('\\\\\\]', '}',str)
229 str = re.sub ('\\]([0-9/]+)', '] }', str)
232 conversions.append (((1,0,10), conv, '[2/3 ]1/1 -> \\times 2/3 '))
237 conversions.append (((1,0,12), conv, 'Chord syntax stuff'))
244 str = re.sub ('<([^>~]+)~([^>]*)>','<\\1 \\2> ~', str)
248 conversions.append (((1,0,13), conv, '<a ~ b> c -> <a b> ~ c'))
252 str = re.sub ('<\\[','[<', str)
253 str = re.sub ('\\]>','>]', str)
257 conversions.append (((1,0,14), conv, '<[a b> <a b]>c -> [<a b> <a b>]'))
262 str = re.sub ('\\\\type','\\\\context', str)
263 str = re.sub ('textstyle','textStyle', str)
267 conversions.append (((1,0,16), conv, '\\type -> \\context, textstyle -> textStyle'))
272 if re.search ('\\\\repeat',str):
273 sys.stderr.write ('\nNot smart enough to convert \\repeat')
274 raise FatalConversionError()
277 conversions.append (((1,0,18), conv,
278 '\\repeat NUM Music Alternative -> \\repeat FOLDSTR Music Alternative'))
282 str = re.sub ('SkipBars','skipBars', str)
283 str = re.sub ('fontsize','fontSize', str)
284 str = re.sub ('midi_instrument','midiInstrument', str)
288 conversions.append (((1,0,19), conv,
289 'fontsize -> fontSize, midi_instrument -> midiInstrument, SkipBars -> skipBars'))
294 str = re.sub ('tieydirection','tieVerticalDirection', str)
295 str = re.sub ('slurydirection','slurVerticalDirection', str)
296 str = re.sub ('ydirection','verticalDirection', str)
300 conversions.append (((1,0,20), conv,
301 '{,tie,slur}ydirection -> {v,tieV,slurV}erticalDirection'))
306 str = re.sub ('hshift','horizontalNoteShift', str)
310 conversions.append (((1,0,21), conv,
311 'hshift -> horizontalNoteShift'))
316 str = re.sub ('\\\\grouping[^;]*;','', str)
320 conversions.append (((1,1,52), conv,
321 'deprecate \\grouping'))
326 str = re.sub ('\\\\wheel','\\\\coda', str)
330 conversions.append (((1,1,55), conv,
331 '\\wheel -> \\coda'))
335 str = re.sub ('keyoctaviation','keyOctaviation', str)
336 str = re.sub ('slurdash','slurDash', str)
340 conversions.append (((1,1,65), conv,
341 'slurdash -> slurDash, keyoctaviation -> keyOctaviation'))
345 str = re.sub ('\\\\repeat *\"?semi\"?','\\\\repeat "volta"', str)
349 conversions.append (((1,1,66), conv,
355 str = re.sub ('\"?beamAuto\"? *= *\"?0?\"?','noAutoBeaming = "1"', str)
359 conversions.append (((1,1,67), conv,
360 'beamAuto -> noAutoBeaming'))
364 str = re.sub ('automaticMelismas', 'automaticMelismata', str)
368 conversions.append (((1,2,0), conv,
369 'automaticMelismas -> automaticMelismata'))
373 str = re.sub ('dynamicDir\\b', 'dynamicDirection', str)
377 conversions.append (((1,2,1), conv,
378 'dynamicDir -> dynamicDirection'))
382 str = re.sub ('\\\\cadenza *0 *;', '\\\\cadenzaOff', str)
383 str = re.sub ('\\\\cadenza *1 *;', '\\\\cadenzaOn', str)
387 conversions.append (((1,3,4), conv,
388 '\\cadenza -> \cadenza{On|Off}'))
392 str = re.sub ('beamAuto([^=]+)= *"([0-9]+)/([0-9]+)" *;',
393 'beamAuto\\1 = #(make-moment \\2 \\3)',
397 conversions.append (((1,3,5), conv, 'beamAuto moment properties'))
401 str = re.sub ('stemStyle',
406 conversions.append (((1,3,17), conv, 'stemStyle -> flagStyle'))
410 str = re.sub ('staffLineLeading',
415 conversions.append (((1,3,18), conv, 'staffLineLeading -> staffSpace'))
419 str = re.sub ('textEmptyDimension *= *##t',
420 'textNonEmpty = ##f',
422 str = re.sub ('textEmptyDimension *= *##f',
423 'textNonEmpty = ##t',
427 conversions.append (((1,3,35), conv, 'textEmptyDimension -> textNonEmpty'))
431 str = re.sub ("([a-z]+)[ \t]*=[ \t]*\\\\musicalpitch *{([- 0-9]+)} *\n",
432 "(\\1 . (\\2))\n", str)
433 str = re.sub ("\\\\musicalpitch *{([0-9 -]+)}",
434 "\\\\musicalpitch #'(\\1)", str)
435 if re.search ('\\\\notenames',str):
436 sys.stderr.write ('\nNot smart enough to convert to new \\notenames format')
439 conversions.append (((1,3,38), conv, '\musicalpitch { a b c } -> #\'(a b c)'))
444 return '\\key %s;' % string.lower (match.group (1))
446 str = re.sub ("\\\\key ([^;]+);", replace, str)
449 conversions.append (((1,3,39), conv, '\\key A ; ->\\key a;'))
453 if re.search ('\\[:',str):
454 sys.stderr.write ('\nNot smart enough to convert to new tremolo format')
457 conversions.append (((1,3,41), conv,
458 '[:16 c4 d4 ] -> \\repeat "tremolo" 2 { c16 d16 }'))
462 str = re.sub ('Staff_margin_engraver' , 'Instrument_name_engraver', str)
465 conversions.append (((1,3,42), conv,
466 'Staff_margin_engraver deprecated, use Instrument_name_engraver'))
470 str = re.sub ('note[hH]eadStyle\\s*=\\s*"?(\\w+)"?' , "noteHeadStyle = #'\\1", str)
473 conversions.append (((1,3,49), conv,
474 'noteHeadStyle value: string -> symbol'))
478 str = re.sub (r"""\\key *([a-z]+) *;""", r"""\\key \1 \major;""",str);
480 conversions.append (((1,3,59), conv,
481 '\key X ; -> \key X major; '))
485 str = re.sub (r'latexheaders *= *"\\\\input ',
489 conversions.append (((1,3,68), conv, 'latexheaders = "\\input global" -> latexheaders = "global"'))
493 ################ TODO: lots of other syntax change should be done here as well
499 str = re.sub ('basicCollisionProperties', 'NoteCollision', str)
500 str = re.sub ('basicVoltaSpannerProperties' , "VoltaBracket", str)
501 str = re.sub ('basicKeyProperties' , "KeySignature", str)
503 str = re.sub ('basicClefItemProperties' ,"Clef", str)
506 str = re.sub ('basicLocalKeyProperties' ,"Accidentals", str)
507 str = re.sub ('basicMarkProperties' ,"Accidentals", str)
508 str = re.sub ('basic([A-Za-z_]+)Properties', '\\1', str)
511 conversions.append (((1,3,92), conv, 'basicXXXProperties -> XXX'))
515 str = re.sub ('\\\\stemup', '\\\\stemUp', str)
516 str = re.sub ('\\\\stemdown', '\\\\stemDown', str)
517 str = re.sub ('\\\\stemboth', '\\\\stemBoth', str)
518 str = re.sub ('\\\\slurup', '\\\\slurUp', str)
519 str = re.sub ('\\\\slurboth', '\\\\slurBoth', str)
520 str = re.sub ('\\\\slurdown', '\\\\slurDown', str)
521 str = re.sub ('\\\\slurdotted', '\\\\slurDotted', str)
522 str = re.sub ('\\\\slurnormal', '\\\\slurNoDots', str)
524 str = re.sub ('\\\\shiftoff', '\\\\shiftOff', str)
525 str = re.sub ('\\\\shifton', '\\\\shiftOn', str)
526 str = re.sub ('\\\\shiftonn', '\\\\shiftOnn', str)
527 str = re.sub ('\\\\shiftonnn', '\\\\shiftOnnn', str)
529 str = re.sub ('\\\\onevoice', '\\\\oneVoice', str)
530 str = re.sub ('\\\\voiceone', '\\\\voiceOne', str)
531 str = re.sub ('\\\\voicetwo', '\\\\voiceTwo', str)
532 str = re.sub ('\\\\voicethree', '\\\\voiceThree', str)
533 str = re.sub ('\\\\voicefour', '\\\\voiceFour', str)
537 conversions.append (((1,3,93), conv,
538 'property definiton case (eg. onevoice -> oneVoice)'))
543 str = re.sub ('ChordNames*', 'ChordNames', str)
544 if re.search ('\\\\textscript "[^"]* *"[^"]*"', str):
545 sys.stderr.write ('\nNot smart enough to convert to new \\textscript markup text')
547 str = re.sub ('\\textscript +("[^"]*")', '\\textscript #\\1', str)
551 conversions.append (((1,3,97), conv, 'ChordName -> ChordNames'))
555 str = re.sub ('beamAutoEnd_([0-9]*) *= *(#\\([^)]*\\))', 'autoBeamSettings \\push #\'(end 1 \\1 * *) = \\2', str)
556 str = re.sub ('beamAutoBegin_([0-9]*) *= *(#\\([^)]*\))', 'autoBeamSettings \\push #\'(begin 1 \\1 * *) = \\2', str)
557 str = re.sub ('beamAutoEnd *= *(#\\([^)]*\\))', 'autoBeamSettings \\push #\'(end * * * *) = \\1', str)
558 str = re.sub ('beamAutoBegin *= *(#\\([^)]*\\))', 'autoBeamSettings \\push #\'(begin * * * *) = \\1', str)
563 conversions.append (((1,3,102), conv, 'beamAutoEnd -> autoBeamSettings \\push (end * * * *)'))
568 str = re.sub ('\\\\push', '\\\\override', str)
569 str = re.sub ('\\\\pop', '\\\\revert', str)
573 conversions.append (((1,3,111), conv, '\\push -> \\override, \\pop -> \\revert'))
577 str = re.sub ('LyricVoice', 'LyricsVoice', str)
579 str = re.sub ('Chord[Nn]ames*.Chord[Nn]ames*', 'ChordNames.ChordName', str)
582 conversions.append (((1,3,113), conv, 'LyricVoice -> LyricsVoice'))
584 def regularize_id (str):
591 elif x in string.digits:
592 x = chr(ord (x) - ord ('0') +ord ('A'))
593 elif x not in string.letters:
595 elif x in string.lowercase and lastx == '_':
604 def regularize_dollar_reference (match):
605 return regularize_id (match.group (1))
606 def regularize_assignment (match):
607 return '\n' + regularize_id (match.group (1)) + ' = '
608 str = re.sub ('\$([^\t\n ]+)', regularize_dollar_reference, str)
609 str = re.sub ('\n([^ \t\n]+) = ', regularize_assignment, str)
612 conversions.append (((1,3,117), conv, 'identifier names: $!foo_bar_123 -> xfooBarABC'))
617 def regularize_paper (match):
618 return regularize_id (match.group (1))
620 str = re.sub ('(paper_[a-z]+)', regularize_paper, str)
621 str = re.sub ('sustainup', 'sustainUp', str)
622 str = re.sub ('nobreak', 'noBreak', str)
623 str = re.sub ('sustaindown', 'sustainDown', str)
624 str = re.sub ('sostenutoup', 'sostenutoUp', str)
625 str = re.sub ('sostenutodown', 'sostenutoDown', str)
626 str = re.sub ('unachorda', 'unaChorda', str)
627 str = re.sub ('trechorde', 'treChorde', str)
631 conversions.append (((1,3,120), conv, 'paper_xxx -> paperXxxx, pedalup -> pedalUp.'))
635 str = re.sub ('drarnChords', 'chordChanges', str)
636 str = re.sub ('\\musicalpitch', '\\pitch', str)
639 conversions.append (((1,3,122), conv, 'drarnChords -> chordChanges, \\musicalpitch -> \\pitch'))
642 ############################
645 def get_conversions (from_version, to_version):
646 def version_b (v, f = from_version, t = to_version):
647 return version_cmp (v[0], f) > 0 and version_cmp (v[0], t) <= 0
648 return filter (version_b, conversions)
651 def latest_version ():
652 return conversions[-1][0]
654 def do_conversion (infile, from_version, outfile, to_version):
655 conv_list = get_conversions (from_version, to_version)
657 sys.stderr.write ('Applying conversions: ')
662 sys.stderr.write (tup_to_str (x[0]) + ', ')
664 last_conversion = x[0]
666 except FatalConversionError:
667 sys.stderr.write ('Error while converting; I won\'t convert any further')
670 sys.stderr.write ('\n')
671 new_ver = '\\version \"%s\"' % tup_to_str (last_conversion)
672 if re.search (lilypond_version_re_str, str):
673 str = re.sub (lilypond_version_re_str,'\\'+new_ver , str)
675 str = new_ver + '\n' + str
679 return last_conversion
681 class UnknownVersion:
684 def do_one_file (infile_name):
685 sys.stderr.write ('Processing `%s\' ... '% infile_name)
688 outfile_name = infile_name + '.NEW'
689 elif __main__.outfile_name:
690 outfile_name = __main__.outfile_name
692 if __main__.from_version:
693 from_version = __main__.from_version
695 guess = guess_lilypond_version (infile_name)
697 raise UnknownVersion()
698 from_version = str_to_tuple (guess)
700 if __main__.to_version:
701 to_version = __main__.to_version
703 to_version = latest_version ()
707 infile = open (infile_name,'r')
712 outfile = open (outfile_name, 'w')
716 touched = do_conversion (infile, from_version, outfile, to_version)
724 if __main__.edit and touched:
726 os.remove(infile_name + '~')
729 os.rename (infile_name, infile_name + '~')
730 os.rename (infile_name + '.NEW', infile_name)
732 sys.stderr.write ('\n')
740 (options, files) = getopt.getopt (
741 sys.argv[1:], 'o:f:t:seh', ['version', 'output', 'show-rules', 'help', 'edit', 'from=', 'to'])
746 if o== '--help' or o == '-h':
749 if o == '--version' or o == '-v':
752 elif o== '--from' or o=='-f':
753 from_version = str_to_tuple (a)
754 elif o== '--to' or o=='-t':
755 to_version = str_to_tuple (a)
756 elif o== '--edit' or o == '-e':
758 elif o== '--show-rules' or o == '-s':
759 show_rules (sys.stdout)
761 elif o == '--output' or o == '-o':
773 except UnknownVersion: