.. _moduleLily.translate:

music21.lily.translate
======================

.. WARNING: DO NOT EDIT THIS FILE: AUTOMATICALLY GENERATED. Edit the .py file directly

.. module:: music21.lily.translate


music21 translates to Lilypond format and if Lilypond is installed on the
local computer, can automatically generate .pdf, .png, and .svg versions
of musical files using Lilypond

this replaces (July 2012) the old LilyString() conversion methods.




LilypondConverter
-----------------



.. class:: LilypondConverter()


    **LilypondConverter** **attributes**

        .. attribute:: versionScheme


            represents Scheme embedded in Lilypond code.

            Can be either a SCM_TOKEN (Scheme Token) or SCM_IDENTIFIER String stored in self.content

            Note that if any LyEmbeddedScm is found in an output then the output SHOULD be marked as unsafe.
            But a lot of standard lilypond functions are actually embedded scheme.
            For instance, \clef, which as http://lilypond.org/doc/v2.12/input/lsr/lilypond-snippets/Pitches#Tweaking-clef-properties
            shows is a macro to run a lot of \set commands.



        .. attribute:: context


            corresponds to the highest level lilypond object in Appendix C:

            ::

              `lilypond: /* empty */
                     | lilypond toplevel_expression
                     | lilypond assignment
                     | lilypond error
                     | lilypond "\invalid"`


            error and \invalid are not defined by music21



        .. attribute:: topLevelObject


            corresponds to the highest level lilypond object in Appendix C:

            ::

              `lilypond: /* empty */
                     | lilypond toplevel_expression
                     | lilypond assignment
                     | lilypond error
                     | lilypond "\invalid"`


            error and \invalid are not defined by music21



        Attributes without Documentation: `accidentalConvert`, `barlineDict`, `colorDef`, `fictaDef`, `simplePaperDefinitionScm`, `transparencyStartScheme`, `transparencyStopScheme`, `majorVersion`, `LILYEXEC`, `minorVersion`, `currentMeasure`, `storedContexts`, `versionString`, `backendString`, `backend`

    **LilypondConverter** **methods**

        .. method:: appendBeamCode(noteOrChord)


            Adds an LyEmbeddedScm object to the context's contents if the object's has a .beams
            attribute.



            >>> from music21 import *
            >>> lpc = lily.translate.LilypondConverter()
            >>> lpMusicList = lyo.LyMusicList()
            >>> lpc.context = lpMusicList
            >>> lpc.context.contents
            []
            >>> n1 = note.Note(quarterLength = 0.25)
            >>> n2 = note.Note(quarterLength = 0.25)
            >>> n1.beams.fill(2, 'start')
            >>> n2.beams.fill(2, 'stop')
            ⁠ 
            >>> lpc.appendBeamCode(n1)
            >>> print lpc.context.contents
            [<music21.lily.lilyObjects.LyEmbeddedScm object at 0x...>, <music21.lily.lilyObjects.LyEmbeddedScm object at 0x...>]
            >>> print lpc.context
            \set stemLeftBeamCount = #0
            \set stemRightBeamCount = #2



        .. method:: appendContextFromNoteOrRest(noteOrRest)


            appends lySimpleMusicFromNoteOrRest to the
            current context.



            >>> from music21 import *
            >>> n = note.Note("C#4")
            >>> lpc = lily.translate.LilypondConverter()
            >>> lpMusicList = lily.lilyObjects.LyMusicList()
            >>> lpc.context = lpMusicList
            >>> lpc.appendContextFromNoteOrRest(n)
            >>> print lpMusicList
            cis' 4
            <BLANKLINE>




            >>> n2 = note.Note("D#4")
            >>> n2.duration.quarterLength = 0.3333333333333
            >>> n2.duration.tuplets[0].type = 'start'
            >>> n3 = note.Note("E4")
            >>> n3.duration.quarterLength = 0.3333333333333
            >>> n4 = note.Note("F4")
            >>> n4.duration.quarterLength = 0.3333333333333
            >>> n4.duration.tuplets[0].type = 'stop'
            ⁠ 
            >>> n5 = note.Note("F#4")



            >>> lpc.appendContextFromNoteOrRest(n2)
            >>> lpc.appendContextFromNoteOrRest(n3)
            >>> lpc.appendContextFromNoteOrRest(n4)
            >>> lpc.appendContextFromNoteOrRest(n5)
            ⁠ 
            >>> print lpc.context
            cis' 4
            \times 2/3 { dis' 8
               e' 8
               f' 8
                }
            <BLANKLINE>
            fis' 4
            <BLANKLINE>




        .. method:: appendM21ObjectToContext(thisObject)


            converts any type of object into a lilyObject of LyMusic (
            LySimpleMusic, LyEmbeddedScm etc.) type



        .. method:: appendObjectsToContextFromStream(streamObject)


            takes a Stream and appends all the elements in it to the current
            context's .contents list, and deals with creating Voices in it.

            (should eventually replace the main Score parts finding tools)



            >>> from music21 import *
            >>> lpc = lily.translate.LilypondConverter()
            >>> lpMusicList = lyo.LyMusicList()
            >>> lpc.context = lpMusicList
            >>> lpc.context.contents
            []
            >>> c = converter.parse('tinynotation: 3/4 c4 d- e#')
            >>> lpc.appendObjectsToContextFromStream(c)
            >>> print lpc.context.contents
            [<music21.lily.lilyObjects.LyEmbeddedScm...>, <music21.lily.lilyObjects.LySimpleMusic...>, <music21.lily.lilyObjects.LySimpleMusic...>, <music21.lily.lilyObjects.LySimpleMusic...]
            >>> print lpc.context
            \time 3/4
            c' 4
            des' 4
            eis' 4
            <BLANKLINE>




            >>> v1 = stream.Voice()
            >>> v1.append(note.Note("C5", quarterLength = 4.0))
            >>> v2 = stream.Voice()
            >>> v2.append(note.Note("C#5", quarterLength = 4.0))
            >>> m = stream.Measure()
            >>> m.insert(0, v1)
            >>> m.insert(0, v2)
            >>> lpMusicList = lyo.LyMusicList()
            >>> lpc.context = lpMusicList
            >>> lpc.appendObjectsToContextFromStream(m)
            >>> print lpc.context # internal spaces removed...
              << \new Voice { c'' 1
                      }
               \new Voice { cis'' 1
                      }
                >>



        .. method:: appendStemCode(noteOrChord)


            Adds an LyEmbeddedScm object to the context's contents if the object's stem direction
            is set (currrently, only "up" and "down" are supported).



            >>> from music21 import *
            >>> lpc = lily.translate.LilypondConverter()
            >>> lpMusicList = lyo.LyMusicList()
            >>> lpc.context = lpMusicList
            >>> lpc.context.contents
            []
            >>> n = note.Note()
            >>> n.stemDirection = 'up'
            >>> lpc.appendStemCode(n)
            >>> print lpc.context.contents
            [<music21.lily.lilyObjects.LyEmbeddedScm object at 0x...>]
            >>> print lpc.context.contents[0]
            \once \override Stem #'direction = #UP



        .. method:: baseNameFromPitch(pitch)


            returns a string of the base name (including accidental)
            for a music21 pitch



        .. method:: closeMeasure()


            return a LyObject or None for the end of the previous Measure

            uses self.currentMeasure



            >>> from music21 import *
            >>> lpc = lily.translate.LilypondConverter()
            >>> m = stream.Measure()
            >>> m.number = 2
            >>> m.rightBarline = 'double'
            >>> lpc.currentMeasure = m
            >>> lyObj = lpc.closeMeasure()
            >>> lpc.currentMeasure is None
            True
            >>> print lyObj
            \bar "||"  %{ end measure 2 %}



        .. method:: createPDF(fileName=None)


            create a PDF file from self.topLevelObject and return the filepath of the file.

            most users will just call stream.write('lily.pdf') on a stream.



        .. method:: createPNG(fileName=None)


            create a PNG file from self.topLevelObject and return the filepath of the file.

            most users will just call stream.write('lily.png') on a stream.

            if PIL is installed then a small white border is created around the score



        .. method:: createSVG(fileName=None)


            create an SVG file from self.topLevelObject and return the filepath of the file.

            most users will just call stream.Stream.write('lily.svg') on a stream.



        .. method:: getSchemeForPadding(measureObject)


            lilypond partial durations are very strange and are really of
            type LyMultipliedDuration.  You notate how many
            notes are left in the measure, for a quarter note, write "4"
            for an eighth, write "8", but for 3 eighths, write "8*3" !
            so we will measure in 32nd notes always... won't work for tuplets
            of course.

            returns a scheme object or None if not needed



            >>> from music21 import *
            >>> m = stream.Measure()
            >>> m.append(meter.TimeSignature('3/4'))
            >>> m.paddingLeft = 2.0
            >>> lpc = lily.translate.LilypondConverter()
            >>> outScheme = lpc.getSchemeForPadding(m)
            >>> print outScheme
            \partial 32*8



        .. method:: loadFromMusic21Object(m21ObjectIn)


            Create a Lilypond object hierarchy in self.topLevelObject from an
            arbitrary music21 object.

            TODO: Add tests...
            TODO: Add test for TinyNotationStream...



        .. method:: loadObjectFromOpus(opusIn=None, makeNotation=True)


            creates a filled topLevelObject (lily.lilyObjects.LyLilypondTop)
            whose string representation accurately reflects all the Score objects
            in this Opus object.



            >>> from music21 import *
            >>> fifeOpus = corpus.parse('miscFolk/americanfifeopus.abc')
            >>> lpc = lily.translate.LilypondConverter()
            >>> lpc.loadObjectFromOpus(fifeOpus, makeNotation = False)
            >>> lpc.showPDF()



        .. method:: loadObjectFromScore(scoreIn=None, makeNotation=True)



            creates a filled topLevelObject (lily.lilyObjects.LyLilypondTop)
            whose string representation accurately reflects this Score object.



            >>> from music21 import *
            >>> lpc = lily.translate.LilypondConverter()
            >>> #b = corpus.parse('bwv66.6')
            >>> lpc.loadObjectFromScore(b)
            >>> #print lpc.topLevelObject



        .. method:: lyEmbeddedScmFromClef(clefObj)


            converts a Clef object to a
            lilyObjects.LyEmbeddedScm object



            >>> from music21 import *
            >>> tc = clef.TrebleClef()
            >>> conv = lily.translate.LilypondConverter()
            >>> lpEmbeddedScm = conv.lyEmbeddedScmFromClef(tc)
            >>> print lpEmbeddedScm
            \clef "treble"




        .. method:: lyEmbeddedScmFromKeySignature(keyObj)


            converts a Key or KeySignature object
            to a lilyObjects.LyEmbeddedScm object



            >>> from music21 import *
            >>> d = key.KeySignature(-1)
            >>> d.mode = 'minor'
            >>> conv = lily.translate.LilypondConverter()
            >>> lpEmbeddedScm = conv.lyEmbeddedScmFromKeySignature(d)
            >>> print lpEmbeddedScm
            \key d \minor

            Major is assumed:



            >>> fsharp = key.KeySignature(6)
            >>> print conv.lyEmbeddedScmFromKeySignature(fsharp)
            \key fis \major




        .. method:: lyEmbeddedScmFromTimeSignature(ts)


            convert a :class:`~music21.meter.TimeSignature` object
            to a lilyObjects.LyEmbeddedScm object



            >>> from music21 import *
            >>> ts = meter.TimeSignature('3/4')
            >>> conv = lily.translate.LilypondConverter()
            >>> print conv.lyEmbeddedScmFromTimeSignature(ts)
            \time 3/4



        .. method:: lyGroupedMusicListFromScoreWithParts(scoreIn)





            >>> from music21 import *
            >>> lpc = lily.translate.LilypondConverter()
            >>> b = corpus.parse('bwv66.6')
            >>> lpGroupedMusicList = lpc.lyGroupedMusicListFromScoreWithParts(b)
            >>> print lpGroupedMusicList
            << \new Staff { \partial 32*8
                   \clef "treble"
                   \key fis \minor
                   \time 4/4
                   \once \override Stem #'direction = #DOWN
                   cis'' 8
                   \once \override Stem #'direction = #DOWN
                   b' 8
                   \bar "|"  %{ end measure 0 %}
                   \once \override Stem #'direction = #UP
                   a' 4
                   \once \override Stem #'direction = #DOWN
                   b' 4
                   \once \override Stem #'direction = #DOWN
                   cis'' 4  \fermata
                   \once \override Stem #'direction = #DOWN
                   e'' 4
                   \bar "|"  %{ end measure 1 %}
                   \once \override Stem #'direction = #DOWN
                   cis'' 4
                   ...
            }
            <BLANKLINE>
            \new Staff { \partial 32*8
                \clef "treble"...
                \once \override Stem #'direction = #UP
                e' 4
                \bar "|"  %{ end measure 0 %}
                \once \override Stem #'direction = #UP
                fis' 4
                \once \override Stem #'direction = #UP
                e' 4
            ...
            }
            <BLANKLINE>
            >>



        .. method:: lyMultipliedDurationFromDuration(durationObj)

            No documentation.


        .. method:: lyPitchFromPitch(pitch)


            converts a music21.pitch.Pitch object to a lily.lilyObjects.LyPitch
            object.



        .. method:: lyPrefixCompositeMusicFromStream(part)


            returns an LyPrefixCompositeMusic object from
            a stream (generally a part, but who knows...)



        .. method:: lyScoreBlockFromScore(scoreIn)

            No documentation.


        .. method:: lySimpleMusicFromChord(chordObj)





            >>> from music21 import *
            >>> conv = lily.translate.LilypondConverter()
            >>> c1 = chord.Chord(["C#2", "E4", "D#5"])
            >>> c1.quarterLength = 3.5
            >>> c1.pitches[2].accidental.displayType = 'always'
            >>> print conv.lySimpleMusicFromChord(c1)
             < cis, e' dis''  !  > 2..



        .. method:: lySimpleMusicFromNoteOrRest(noteOrRest)


            returns a lilyObjects.LySimpleMusic object for the generalNote containing...

                LyEventChord   containing
                LySimpleChordElements containing
                LySimpleElement containing
                LyPitch  AND
                LyMultipliedDuration containing:

                    LyMultipliedDuration containing
                    LyStenoDuration

            does not check for tuplets.  That's in
            appendContextFromNoteOrRest

            read-only property that returns a string of the lilypond representation of
            a note (or via subclassing, rest or chord)



            >>> from music21 import *
            >>> conv = lily.translate.LilypondConverter()
            ⁠ 
            >>> n0 = note.Note("D#5")
            >>> n0.pitch.accidental.displayType = 'always'
            >>> n0.pitch.accidental.displayStyle = 'parentheses'
            >>> n0.editorial.color = 'blue'
            >>> sm = conv.lySimpleMusicFromNoteOrRest(n0)
            >>> print sm
            \color "blue" dis'' ! ? 4




        .. method:: newContext(newContext)

            No documentation.


        .. method:: octaveCharactersFromPitch(pitch)


            returns a string of single-quotes or commas or "" representing
            the octave of a :class:`~music21.pitch.Pitch` object



        .. method:: postEventsFromObject(generalNote)


            attaches events that apply to notes and chords (and some other things) equally



        .. method:: restoreContext()

            No documentation.


        .. method:: runThroughLily(format='png', backend='ps', fileName=None, skipWriting=False)


            creates a .ly file from self.topLevelObject via .writeLyFile
            then runs the file through Lilypond.

            Returns the full path of the file produced by lilypond including the format extension.

            If skipWriting is True and a fileName is given then it will run that file through lilypond instead




        .. method:: setContextForTupletStart(inObj)


            if the inObj has tuplets then we set a new context
            for the tuplets and anything up till a tuplet stop.

            Note that a broken tuplet (a la Michael Gordon)
            will not work.

            If there are no tuplets, this routine does
            nothing.

            For now, no nested tuplets.  They're an
            easy extension, but there's too much
            else missing to do it now...



        .. method:: setContextForTupletStop(inObj)


            Reverse of setContextForTupletStart



        .. method:: setHeaderFromMetadata(metadataObject=None, lpHeader=None)


            Returns a lilypond.lilyObjects.LyLilypondHeader object
            set with data from the metadata object



            >>> from music21 import *
            >>> md = metadata.Metadata()
            >>> md.title = 'My Title'
            >>> md.alternativeTitle = 'My "sub"-title'
            ⁠ 
            >>> lpc = lily.translate.LilypondConverter()
            >>> lpHeader = lpc.setHeaderFromMetadata(md)
            >>> print lpHeader
            \header { title = "My Title"
            subtitle = "My \"sub\"-title"
            }



        .. method:: setupTools()

            No documentation.


        .. method:: showPDF()


            create a SVG file from self.topLevelObject, show it with your pdf reader (often Adobe Acrobat/Adobe Reader or Apple Preview)
            and return the filepath of the file.

            most users will just call stream.Stream.show('lily.pdf') on a stream.



        .. method:: showPNG()


            Take the object, run it through LilyPond, and then show it as a PNG file.
            On Windows, the PNG file will not be deleted, so you  will need to clean out
            TEMP every once in a while.

            Most users will just want to call stream.Stream.show('lily.png') instead.



        .. method:: showSVG(fileName=None)


            create a SVG file from self.topLevelObject, show it with your svg reader (often Internet Explorer on PC)
            and return the filepath of the file.

            most users will just call stream.Stream.show('lily.png') on a stream.



        .. method:: textFromMusic21Object(m21ObjectIn)


            get a proper lilypond text file for writing from a music21 object



            >>> from music21 import *
            >>> n = note.Note()
            >>> print lily.translate.LilypondConverter().textFromMusic21Object(n)
            \version "2.13"
            color = #(define-music-function (parser location color) (string?) #{
                    \once \override NoteHead #'color = #(x11-color $color)
                    \once \override Stem #'color = #(x11-color $color)
                    \once \override Rest #'color = #(x11-color $color)
                    \once \override Beam #'color = #(x11-color $color)
                 #})
            \header { }
            \score  {
                  << \new Staff { c' 4
                          }
                    >>
              }
            \paper { }



        .. method:: writeLyFile(ext='', fp=None)


            writes the contents of the self.topLevelObject to a file.

            The extension should be ly.  If fp is None then a named temporary
            file is created by environment.getTempFile.





