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 # Did we ever have \mudela-version? I doubt it.
28 # lilypond_version_re_str = '\\\\version *\"(.*)\"'
29 lilypond_version_re_str = '\\\\(mudela-)?version *\"(.*)\"'
30 lilypond_version_re = re.compile (lilypond_version_re_str)
33 return '%s (GNU LilyPond) %s' %(program_name, version);
36 sys.stderr.write (program_id () + '\n')
40 r"""Usage: %s [OPTION]... [FILE]...
41 Try to convert to newer lilypond-versions. The version number of the
42 input is guessed by default from \version directive
45 -h, --help print this help
46 -e, --edit in place edit
47 -f, --from=VERSION start from version
48 -s, --show-rules print all rules.
49 -t, --to=VERSION target version
50 --version print program version
52 Report bugs to bugs-gnu-music@gnu.org
61 sys.stdout.write (r"""%s
63 This is free software. It is covered by the GNU General Public
64 License, and you are welcome to change it and/or distribute copies of
65 it under certain conditions. invoke as `%s --warranty' for more
68 """ % (program_id() , program_name))
77 print 'can\'t open file: ' + f + '\n'
81 print 'gulped empty file: ' + f + '\n'
86 return tuple (map (string.atoi, string.split (s,'.')))
89 return string.join (map (lambda x: '%s' % x, list (t)), '.')
91 def version_cmp (t1, t2):
97 def guess_lilypond_version (filename):
98 s = gulp_file (filename)
99 m = lilypond_version_re.search (s)
105 class FatalConversionError:
110 def show_rules (file):
111 for x in conversions:
112 file.write ('%s: %s\n' % (tup_to_str (x[0]), x[2]))
114 ############################
116 if 1: # need new a namespace
118 if re.search ('\\\\octave', str):
119 sys.stderr.write ('\nNot smart enough to convert \\octave')
120 raise FatalConversionError()
124 conversions.append ((
125 ((0,1,19), conv, 'deprecated \\octave; can\'t convert automatically')))
128 if 1: # need new a namespace
130 str = re.sub ('\\\\textstyle([^;]+);',
131 '\\\\property Lyrics . textstyle = \\1', str)
132 str = re.sub ('\\\\key([^;]+);', '\\\\accidentals \\1;', str)
136 conversions.append ((
137 ((0,1,20), conv, 'deprecated \\textstyle, new \key syntax')))
142 str = re.sub ('\\\\musical_pitch', '\\\\musicalpitch',str)
143 str = re.sub ('\\\\meter', '\\\\time',str)
147 conversions.append ((
148 ((0,1,21), conv, '\\musical_pitch -> \\musicalpitch, '+
149 '\\meter -> \\time')))
155 conversions.append ((
156 ((1,0,0), conv, '0.1.21 -> 1.0.0 ')))
161 str = re.sub ('\\\\accidentals', '\\\\keysignature',str)
162 str = re.sub ('specialaccidentals *= *1', 'keyoctaviation = 0',str)
163 str = re.sub ('specialaccidentals *= *0', 'keyoctaviation = 1',str)
167 conversions.append ((
168 ((1,0,1), conv, '\\accidentals -> \\keysignature, ' +
169 'specialaccidentals -> keyoctaviation')))
173 if re.search ('\\\\header', str):
174 sys.stderr.write ('\nNot smart enough to convert to new \\header format')
177 conversions.append (((1,0,2), conv, '\\header { key = concat + with + operator }'))
181 str = re.sub ('\\\\melodic', '\\\\notes',str)
182 if re.search ('\\\\header', str):
183 sys.stderr.write ('\nNot smart enough to convert \\multi constructs')
187 conversions.append (((1,0,3), conv, '\\melodic -> \\notes'))
191 str = re.sub ('default_paper *=', '',str)
192 str = re.sub ('default_midi *=', '',str)
195 conversions.append (((1,0,4), conv, 'default_{paper,midi}'))
199 str = re.sub ('ChoireStaff', 'ChoirStaff',str)
200 str = re.sub ('\\output', 'output = ',str)
204 conversions.append (((1,0,5), conv, 'ChoireStaff -> ChoirStaff'))
208 if re.search ('[a-zA-Z]+ = *\\translator',str):
209 sys.stderr.write ('\nNot smart enough to change \\translator syntax')
210 raise FatalConversionError()
213 conversions.append (((1,0,6), conv, 'foo = \\translator {\\type .. } ->\\translator {\\type ..; foo; }'))
218 str = re.sub ('\\\\lyric', '\\\\lyrics',str)
222 conversions.append (((1,0,7), conv, '\\lyric -> \\lyrics'))
226 str = re.sub ('\\\\\\[/3+', '\\\\times 2/3 { ',str)
227 str = re.sub ('\\[/3+', '\\\\times 2/3 { [',str)
228 str = re.sub ('\\\\\\[([0-9/]+)', '\\\\times \\1 {',str)
229 str = re.sub ('\\[([0-9/]+)', '\\\\times \\1 { [',str)
230 str = re.sub ('\\\\\\]([0-9/]+)', '}', str)
231 str = re.sub ('\\\\\\]', '}',str)
232 str = re.sub ('\\]([0-9/]+)', '] }', str)
235 conversions.append (((1,0,10), conv, '[2/3 ]1/1 -> \\times 2/3 '))
240 conversions.append (((1,0,12), conv, 'Chord syntax stuff'))
247 str = re.sub ('<([^>~]+)~([^>]*)>','<\\1 \\2> ~', str)
251 conversions.append (((1,0,13), conv, '<a ~ b> c -> <a b> ~ c'))
255 str = re.sub ('<\\[','[<', str)
256 str = re.sub ('\\]>','>]', str)
260 conversions.append (((1,0,14), conv, '<[a b> <a b]>c -> [<a b> <a b>]'))
265 str = re.sub ('\\\\type','\\\\context', str)
266 str = re.sub ('textstyle','textStyle', str)
270 conversions.append (((1,0,16), conv, '\\type -> \\context, textstyle -> textStyle'))
275 if re.search ('\\\\repeat',str):
276 sys.stderr.write ('\nNot smart enough to convert \\repeat')
277 raise FatalConversionError()
280 conversions.append (((1,0,18), conv,
281 '\\repeat NUM Music Alternative -> \\repeat FOLDSTR Music Alternative'))
285 str = re.sub ('SkipBars','skipBars', str)
286 str = re.sub ('fontsize','fontSize', str)
287 str = re.sub ('midi_instrument','midiInstrument', str)
291 conversions.append (((1,0,19), conv,
292 'fontsize -> fontSize, midi_instrument -> midiInstrument, SkipBars -> skipBars'))
297 str = re.sub ('tieydirection','tieVerticalDirection', str)
298 str = re.sub ('slurydirection','slurVerticalDirection', str)
299 str = re.sub ('ydirection','verticalDirection', str)
303 conversions.append (((1,0,20), conv,
304 '{,tie,slur}ydirection -> {v,tieV,slurV}erticalDirection'))
309 str = re.sub ('hshift','horizontalNoteShift', str)
313 conversions.append (((1,0,21), conv,
314 'hshift -> horizontalNoteShift'))
319 str = re.sub ('\\\\grouping[^;]*;','', str)
323 conversions.append (((1,1,52), conv,
324 'deprecate \\grouping'))
329 str = re.sub ('\\\\wheel','\\\\coda', str)
333 conversions.append (((1,1,55), conv,
334 '\\wheel -> \\coda'))
338 str = re.sub ('keyoctaviation','keyOctaviation', str)
339 str = re.sub ('slurdash','slurDash', str)
343 conversions.append (((1,1,65), conv,
344 'slurdash -> slurDash, keyoctaviation -> keyOctaviation'))
348 str = re.sub ('\\\\repeat *\"?semi\"?','\\\\repeat "volta"', str)
352 conversions.append (((1,1,66), conv,
358 str = re.sub ('\"?beamAuto\"? *= *\"?0?\"?','noAutoBeaming = "1"', str)
362 conversions.append (((1,1,67), conv,
363 'beamAuto -> noAutoBeaming'))
367 str = re.sub ('automaticMelismas', 'automaticMelismata', str)
371 conversions.append (((1,2,0), conv,
372 'automaticMelismas -> automaticMelismata'))
376 str = re.sub ('dynamicDir\\b', 'dynamicDirection', str)
380 conversions.append (((1,2,1), conv,
381 'dynamicDir -> dynamicDirection'))
385 str = re.sub ('\\\\cadenza *0 *;', '\\\\cadenzaOff', str)
386 str = re.sub ('\\\\cadenza *1 *;', '\\\\cadenzaOn', str)
390 conversions.append (((1,3,4), conv,
391 '\\cadenza -> \cadenza{On|Off}'))
395 str = re.sub ('"?beamAuto([^"=]+)"? *= *"([0-9]+)/([0-9]+)" *;*',
396 'beamAuto\\1 = #(make-moment \\2 \\3)',
400 conversions.append (((1,3,5), conv, 'beamAuto moment properties'))
404 str = re.sub ('stemStyle',
409 conversions.append (((1,3,17), conv, 'stemStyle -> flagStyle'))
413 str = re.sub ('staffLineLeading',
418 conversions.append (((1,3,18), conv, 'staffLineLeading -> staffSpace'))
422 str = re.sub ('textEmptyDimension *= *##t',
423 'textNonEmpty = ##f',
425 str = re.sub ('textEmptyDimension *= *##f',
426 'textNonEmpty = ##t',
430 conversions.append (((1,3,35), conv, 'textEmptyDimension -> textNonEmpty'))
434 str = re.sub ("([a-z]+)[ \t]*=[ \t]*\\\\musicalpitch *{([- 0-9]+)} *\n",
435 "(\\1 . (\\2))\n", str)
436 str = re.sub ("\\\\musicalpitch *{([0-9 -]+)}",
437 "\\\\musicalpitch #'(\\1)", str)
438 if re.search ('\\\\notenames',str):
439 sys.stderr.write ('\nNot smart enough to convert to new \\notenames format')
442 conversions.append (((1,3,38), conv, '\musicalpitch { a b c } -> #\'(a b c)'))
447 return '\\key %s;' % string.lower (match.group (1))
449 str = re.sub ("\\\\key ([^;]+);", replace, str)
452 conversions.append (((1,3,39), conv, '\\key A ; ->\\key a;'))
456 if re.search ('\\[:',str):
457 sys.stderr.write ('\nNot smart enough to convert to new tremolo format')
460 conversions.append (((1,3,41), conv,
461 '[:16 c4 d4 ] -> \\repeat "tremolo" 2 { c16 d16 }'))
465 str = re.sub ('Staff_margin_engraver' , 'Instrument_name_engraver', str)
468 conversions.append (((1,3,42), conv,
469 'Staff_margin_engraver deprecated, use Instrument_name_engraver'))
473 str = re.sub ('note[hH]eadStyle\\s*=\\s*"?(\\w+)"?' , "noteHeadStyle = #'\\1", str)
476 conversions.append (((1,3,49), conv,
477 'noteHeadStyle value: string -> symbol'))
481 str = re.sub (r"""\\key *([a-z]+) *;""", r"""\\key \1 \major;""",str);
483 conversions.append (((1,3,59), conv,
484 '\key X ; -> \key X major; '))
488 str = re.sub (r'latexheaders *= *"\\\\input ',
492 conversions.append (((1,3,68), conv, 'latexheaders = "\\input global" -> latexheaders = "global"'))
496 ################ TODO: lots of other syntax change should be done here as well
502 str = re.sub ('basicCollisionProperties', 'NoteCollision', str)
503 str = re.sub ('basicVoltaSpannerProperties' , "VoltaBracket", str)
504 str = re.sub ('basicKeyProperties' , "KeySignature", str)
506 str = re.sub ('basicClefItemProperties' ,"Clef", str)
509 str = re.sub ('basicLocalKeyProperties' ,"Accidentals", str)
510 str = re.sub ('basicMarkProperties' ,"Accidentals", str)
511 str = re.sub ('basic([A-Za-z_]+)Properties', '\\1', str)
515 conversions.append (((1,3,92), conv, 'basicXXXProperties -> XXX'))
519 # Ugh, but meaning of \stemup changed too
520 # maybe we should do \stemup -> \stemUp\slurUp\tieUp ?
521 str = re.sub ('\\\\stemup', '\\\\stemUp', str)
522 str = re.sub ('\\\\stemdown', '\\\\stemDown', str)
523 str = re.sub ('\\\\stemboth', '\\\\stemBoth', str)
525 str = re.sub ('\\\\slurup', '\\\\slurUp', str)
526 str = re.sub ('\\\\slurboth', '\\\\slurBoth', str)
527 str = re.sub ('\\\\slurdown', '\\\\slurDown', str)
528 str = re.sub ('\\\\slurdotted', '\\\\slurDotted', str)
529 str = re.sub ('\\\\slurnormal', '\\\\slurNoDots', str)
531 str = re.sub ('\\\\shiftoff', '\\\\shiftOff', str)
532 str = re.sub ('\\\\shifton', '\\\\shiftOn', str)
533 str = re.sub ('\\\\shiftonn', '\\\\shiftOnn', str)
534 str = re.sub ('\\\\shiftonnn', '\\\\shiftOnnn', str)
536 str = re.sub ('\\\\onevoice', '\\\\oneVoice', str)
537 str = re.sub ('\\\\voiceone', '\\\\voiceOne', str)
538 str = re.sub ('\\\\voicetwo', '\\\\voiceTwo', str)
539 str = re.sub ('\\\\voicethree', '\\\\voiceThree', str)
540 str = re.sub ('\\\\voicefour', '\\\\voiceFour', str)
542 # I don't know exactly when these happened...
543 str = re.sub ('\\\\property *[^ ]*verticalDirection[^=]*= *#?(1|(\\\\up))', '\\\\stemUp\\\\slurUp\\\\tieUp', str)
544 str = re.sub ('\\\\property *[^ ]*verticalDirection[^=]*= *#?((-1)|(\\\\down))', '\\\\stemDown\\\\slurDown\\\\tieDown', str)
545 str = re.sub ('\\\\property *[^ .]*[.]?([a-z]+)VerticalDirection[^=]*= *#?(1|(\\\\up))', '\\\\\\1Up', str)
546 str = re.sub ('\\\\property *[^ .]*[.]?([a-z]+)VerticalDirection[^=]*= *#?((-1)|(\\\\down))', '\\\\\\1Down', str)
550 conversions.append (((1,3,93), conv,
551 'property definiton case (eg. onevoice -> oneVoice)'))
556 str = re.sub ('ChordNames*', 'ChordNames', str)
557 if re.search ('\\\\textscript "[^"]* *"[^"]*"', str):
558 sys.stderr.write ('\nNot smart enough to convert to new \\textscript markup text')
560 str = re.sub ('\\textscript +("[^"]*")', '\\textscript #\\1', str)
564 conversions.append (((1,3,97), conv, 'ChordName -> ChordNames'))
567 ## TODO: add lots of these
571 str = re.sub ('\\\\property *"?Voice"? *[.] *"?textStyle"? *= *"([^"]*)"', '\\\\property Voice.TextScript \\\\set #\'font-style = #\'\\1', str)
572 str = re.sub ('\\\\property *"?Lyrics"? *[.] *"?textStyle"? *= *"([^"]*)"', '\\\\property Lyrics.LyricText \\\\set #\'font-style = #\'\\1', str)
574 str = re.sub ('\\\\property *"?([^.]+)"? *[.] *"?timeSignatureStyle"? *= *"([^"]*)"', '\\\\property \\1.TimeSignature \\\\override #\'style = #\'\\2', str)
576 str = re.sub ('"?timeSignatureStyle"? *= *#?""', 'TimeSignature \\\\override #\'style = ##f', str)
578 str = re.sub ('"?timeSignatureStyle"? *= *#?"([^"]*)"', 'TimeSignature \\\\override #\'style = #\'\\1', str)
580 str = re.sub ('#\'style *= #*"([^"])"', '#\'style = #\'\\1', str)
582 str = re.sub ('\\\\property *"?([^.]+)"? *[.] *"?horizontalNoteShift"? *= *"?#?([0-9]+)"?', '\\\\property \\1.NoteColumn \\\\override #\'horizontal-shift = #\\2', str)
585 str = re.sub ('\\\\property *"?([^.]+)"? *[.] *"?flagStyle"? *= *""', '\\\\property \\1.Stem \\\\override #\'flag-style = ##f', str)
587 str = re.sub ('\\\\property *"?([^.]+)"? *[.] *"?flagStyle"? *= *"([^"]*)"', '\\\\property \\1.Stem \\\\override #\'flag-style = #\'\\2', str)
590 conversions.append (((1,3,98), conv, 'CONTEXT.textStyle -> GROB.#font-style '))
594 str = re.sub ('"?beamAutoEnd_([0-9]*)"? *= *(#\\([^)]*\\))', 'autoBeamSettings \\push #\'(end 1 \\1 * *) = \\2', str)
595 str = re.sub ('"?beamAutoBegin_([0-9]*)"? *= *(#\\([^)]*\))', 'autoBeamSettings \\push #\'(begin 1 \\1 * *) = \\2', str)
596 str = re.sub ('"?beamAutoEnd"? *= *(#\\([^)]*\\))', 'autoBeamSettings \\push #\'(end * * * *) = \\1', str)
597 str = re.sub ('"?beamAutoBegin"? *= *(#\\([^)]*\\))', 'autoBeamSettings \\push #\'(begin * * * *) = \\1', str)
602 conversions.append (((1,3,102), conv, 'beamAutoEnd -> autoBeamSettings \\push (end * * * *)'))
607 str = re.sub ('\\\\push', '\\\\override', str)
608 str = re.sub ('\\\\pop', '\\\\revert', str)
612 conversions.append (((1,3,111), conv, '\\push -> \\override, \\pop -> \\revert'))
616 str = re.sub ('LyricVoice', 'LyricsVoice', str)
618 str = re.sub ('Chord[Nn]ames*.Chord[Nn]ames*', 'ChordNames.ChordName', str)
621 conversions.append (((1,3,113), conv, 'LyricVoice -> LyricsVoice'))
623 def regularize_id (str):
630 elif x in string.digits:
631 x = chr(ord (x) - ord ('0') +ord ('A'))
632 elif x not in string.letters:
634 elif x in string.lowercase and lastx == '_':
643 def regularize_dollar_reference (match):
644 return regularize_id (match.group (1))
645 def regularize_assignment (match):
646 return '\n' + regularize_id (match.group (1)) + ' = '
647 str = re.sub ('\$([^\t\n ]+)', regularize_dollar_reference, str)
648 str = re.sub ('\n([^ \t\n]+) = ', regularize_assignment, str)
651 conversions.append (((1,3,117), conv, 'identifier names: $!foo_bar_123 -> xfooBarABC'))
656 def regularize_paper (match):
657 return regularize_id (match.group (1))
659 str = re.sub ('(paper_[a-z]+)', regularize_paper, str)
660 str = re.sub ('sustainup', 'sustainUp', str)
661 str = re.sub ('nobreak', 'noBreak', str)
662 str = re.sub ('sustaindown', 'sustainDown', str)
663 str = re.sub ('sostenutoup', 'sostenutoUp', str)
664 str = re.sub ('sostenutodown', 'sostenutoDown', str)
665 str = re.sub ('unachorda', 'unaChorda', str)
666 str = re.sub ('trechorde', 'treChorde', str)
670 conversions.append (((1,3,120), conv, 'paper_xxx -> paperXxxx, pedalup -> pedalUp.'))
674 str = re.sub ('drarnChords', 'chordChanges', str)
675 str = re.sub ('\\musicalpitch', '\\pitch', str)
678 conversions.append (((1,3,122), conv, 'drarnChords -> chordChanges, \\musicalpitch -> \\pitch'))
682 str = re.sub ('ly-([sg])et-elt-property', 'ly-\\1et-grob-property', str)
685 conversions.append (((1,3,136), conv, 'ly-X-elt-property -> ly-X-grob-property'))
689 str = re.sub ('point-and-click +#t', 'point-and-click line-column-location', str)
692 conversions.append (((1,3,138), conv, 'point-and-click argument changed to procedure.'))
695 ############################
698 def get_conversions (from_version, to_version):
699 def version_b (v, f = from_version, t = to_version):
700 return version_cmp (v[0], f) > 0 and version_cmp (v[0], t) <= 0
701 return filter (version_b, conversions)
704 def latest_version ():
705 return conversions[-1][0]
707 def do_conversion (infile, from_version, outfile, to_version):
708 conv_list = get_conversions (from_version, to_version)
710 sys.stderr.write ('Applying conversions: ')
715 sys.stderr.write (tup_to_str (x[0]) + ', ')
717 last_conversion = x[0]
719 except FatalConversionError:
720 sys.stderr.write ('Error while converting; I won\'t convert any further')
723 sys.stderr.write ('\n')
724 new_ver = '\\version \"%s\"' % tup_to_str (last_conversion)
726 # ugh: this all really doesn't help
727 # esp. as current conversion rules are soo incomplete
728 if re.search (lilypond_version_re_str, str):
729 str = re.sub (lilypond_version_re_str,'\\'+new_ver , str)
731 # str = new_ver + '\n' + str
735 return last_conversion
737 class UnknownVersion:
740 def do_one_file (infile_name):
741 sys.stderr.write ('Processing `%s\' ... '% infile_name)
744 outfile_name = infile_name + '.NEW'
745 elif __main__.outfile_name:
746 outfile_name = __main__.outfile_name
748 if __main__.from_version:
749 from_version = __main__.from_version
751 guess = guess_lilypond_version (infile_name)
753 raise UnknownVersion()
754 from_version = str_to_tuple (guess)
756 if __main__.to_version:
757 to_version = __main__.to_version
759 to_version = latest_version ()
763 infile = open (infile_name,'r')
768 outfile = open (outfile_name, 'w')
772 touched = do_conversion (infile, from_version, outfile, to_version)
780 if __main__.edit and touched:
782 os.remove(infile_name + '~')
785 os.rename (infile_name, infile_name + '~')
786 os.rename (infile_name + '.NEW', infile_name)
788 sys.stderr.write ('\n')
796 (options, files) = getopt.getopt (
797 sys.argv[1:], 'o:f:t:seh', ['version', 'output', 'show-rules', 'help', 'edit', 'from=', 'to='])
802 if o== '--help' or o == '-h':
805 if o == '--version' or o == '-v':
808 elif o== '--from' or o=='-f':
809 from_version = str_to_tuple (a)
810 elif o== '--to' or o=='-t':
811 to_version = str_to_tuple (a)
812 elif o== '--edit' or o == '-e':
814 elif o== '--show-rules' or o == '-s':
815 show_rules (sys.stdout)
817 elif o == '--output' or o == '-o':
829 except UnknownVersion:
830 sys.stderr.write ('\n')
831 sys.stderr.write ("%s: can't determine version for %s" % (program_name, f))
832 sys.stderr.write ('\n')
833 sys.stderr.write ("%s: skipping" % program_name)
835 sys.stderr.write ('\n')