7 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
10 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
12 classic lilypond-book:
13 lilypond-book --process="lilypond" BOOK.tely
17 * this script is too complex. Modularize.
19 * ly-options: intertext?
21 * eps in latex / eps by lilypond -b ps?
22 * check latex parameters, twocolumn, multicolumn?
23 * use --png --ps --pdf for making images?
25 * Converting from lilypond-book source, substitute:
26 @mbinclude foo.itely -> @include foo.itely
48 program_version = '@TOPLEVEL_VERSION@'
49 program_name = os.path.basename (sys.argv[0])
51 original_dir = os.getcwd ()
55 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
59 lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
60 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
61 lilypond-book --process='lilypond -I include' %(BOOK)s
62 ''' % {'BOOK': _ ("BOOK")})
64 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
65 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
67 ################################################################
69 if global_options.verbose:
70 raise Exception (_ ('Exiting (%d)...') % i)
75 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
77 progress = ly.progress
80 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
83 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
85 def ps_page_count (ps_name):
86 header = file (ps_name).read (1024)
87 m = re.search ('\n%%Pages: ([0-9]+)', header)
89 return int (m.group (1))
94 ly.encoded_write (sys.stdout, '''
101 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
103 _ ("Distributed under terms of the GNU General Public License."),
104 _ ("It comes with NO WARRANTY.")))
106 def get_option_parser ():
107 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
108 description=help_summary,
109 add_help_option=False)
111 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
114 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
117 p.add_option ('-f', '--format',
118 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
121 p.add_option("-h", "--help",
123 help=_ ("show this help and exit"))
125 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
127 action='append', dest='include_path',
128 default=[os.path.abspath (os.getcwd ())])
130 p.add_option ('--info-images-dir',
131 help=_ ("format Texinfo output so that Info will "
132 "look for images of music in DIR"),
134 action='store', dest='info_images_dir',
137 p.add_option ('--left-padding',
140 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
144 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
146 action='store', dest='output_dir',
149 p.add_option ('--skip-lily-check',
150 help=_ ("do not fail if no lilypond output is found."),
152 action='store_true', dest='skip_lilypond_run',
155 p.add_option ('--skip-png-check',
156 help=_ ("do not fail if no PNG images are found for EPS files"),
158 action='store_true', dest='skip_png_check',
161 p.add_option ('--lily-output-dir',
162 help=_ ("write lily-XXX files to DIR, link into --output dir."),
164 action='store', dest='lily_output_dir',
167 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
168 help = _ ("process ly_files using COMMAND FILE..."),
170 dest='process_cmd', default='')
172 p.add_option ('--pdf',
175 help=_ ("create PDF files for use with PDFTeX"),
178 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
179 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
180 must use this with dvips -h INPUT.psfonts'''),
183 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
188 p.version = "@TOPLEVEL_VERSION@"
189 p.add_option("--version",
191 help=_ ("show version number and exit"))
193 p.add_option ('-w', '--warranty',
194 help=_ ("show warranty and copyright"),
196 p.add_option_group (ly.display_encode (_ ('Bugs')),
198 _ ("Report bugs via")
199 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
202 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
204 # Only use installed binary when we are installed too.
205 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
206 lilypond_binary = 'lilypond'
208 global_options = None
211 default_ly_options = { 'alt': "[image of music]" }
214 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
216 ADDVERSION = 'addversion'
220 EXAMPLEINDENT = 'exampleindent'
222 FRAGMENT = 'fragment'
228 LINE_WIDTH = 'line-width'
229 LILYQUOTE = 'lilyquote'
230 NOFRAGMENT = 'nofragment'
231 NOINDENT = 'noindent'
236 OUTPUTIMAGE = 'outputimage'
239 PREAMBLE = 'preamble'
240 PRINTFILENAME = 'printfilename'
242 RAGGED_RIGHT = 'ragged-right'
243 RELATIVE = 'relative'
244 STAFFSIZE = 'staffsize'
247 VERBATIM = 'verbatim'
248 FONTLOAD = 'fontload'
249 FILENAME = 'filename'
253 # NOTIME has no opposite so it isn't part of this dictionary.
254 # NOQUOTE is used internally only.
256 NOFRAGMENT: FRAGMENT,
261 # Recognize special sequences in the input.
263 # (?P<name>regex) -- Assign result of REGEX to NAME.
264 # *? -- Match non-greedily.
265 # (?m) -- Multiline regex: Make ^ and $ match at each line.
266 # (?s) -- Make the dot match all characters including newline.
267 # (?x) -- Ignore whitespace in patterns.
278 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
283 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
288 <(?P<inline>(inline)?)mediaobject>\s*<imageobject.*?>\s*<imagedata\s+fileref="(?P<filename>.*?\.ly)"\s*(role="(?P<options>.*?)")?\s*(/>|>\s*</imagedata>)\s*</imageobject>\s*</(inline)?mediaobject>)''',
294 (?P<code><!--\s.*?!-->)
297 'singleline_comment':
316 (\s*(?P<options>.*?)\s*:)?\s*
324 \s*(?P<options>.*?)\s*
333 \s*(?P<options>.*?)\s*
335 \s*(?P<filename>.*?)\s*
342 (?P<code><!--\s.*?!-->)
345 'singleline_comment':
351 (?P<code><pre>.*?</pre>))''',
357 (?P<code><pre>\s.*?</pre>\s))''',
376 \s*(?P<options>.*?)\s*
387 \s*(?P<options>.*?)\s*
391 \\end\s*{lilypond})''',
399 \s*(?P<options>.*?)\s*
407 'singleline_comment':
430 \\end\s*{verbatim}))''',
439 (?P<filename>\S+))''',
443 ^[^\n]*?(?!@c\s+)[^\n]*?
447 \s*(?P<options>.*?)\s*
457 \s*(?P<options>.*?)\s*
460 ^@end\s+lilypond)\s''',
467 \s*(?P<options>.*?)\s*
478 @end\s+ignore))\s''',
480 'singleline_comment':
485 @c([ \t][^\n]*|)\n))''',
487 # Don't do this: It interferes with @code{@{}.
488 # 'verb': r'''(?P<code>@code{.*?})''',
496 @end\s+example\s))''',
505 'intertext': r',?\s*intertext=\".*?\"',
509 'intertext': r',?\s*intertext=\".*?\"',
514 'intertext': r',?\s*intertext=\".*?\"',
515 'option_sep': '\s*,\s*',
519 'intertext': r',?\s*intertext=\".*?\"',
520 'option_sep': '\s*,\s*',
524 # Options without a pattern in ly_options.
543 RELATIVE: r'''\relative c%(relative_quotes)s''',
548 INDENT: r'''indent = %(indent)s''',
550 LINE_WIDTH: r'''line-width = %(line-width)s''',
552 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
554 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
556 RAGGED_RIGHT: r'''ragged-right = ##t''',
558 PACKED: r'''packed = ##t''',
570 \remove Time_signature_engraver
576 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
583 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
586 <imageobject role="latex">
587 <imagedata fileref="%(base)s.pdf" format="PDF"/>
589 <imageobject role="html">
590 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
592 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
594 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
598 FILTER: r'''<lilypond %(options)s>
608 <a href="%(base)s.ly">''',
612 border="0" src="%(image)s" alt="%(alt)s">''',
614 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
616 QUOTE: r'''<blockquote>
629 \ifx\preLilyPondExample \undefined%%
632 \preLilyPondExample%%
634 \def\lilypondbook{}%%
635 \input %(base)s-systems.tex%%
636 \ifx\postLilyPondExample \undefined%%
639 \postLilyPondExample%%
643 PRINTFILENAME: '''\\texttt{%(filename)s}
646 QUOTE: r'''\begin{quotation}%(str)s
649 VERBATIM: r'''\noindent
650 \begin{verbatim}%(verb)s\end{verbatim}''',
652 FILTER: r'''\begin{lilypond}[%(options)s]
659 FILTER: r'''@lilypond[%(options)s]
665 @include %(base)s-systems.texi
669 OUTPUTIMAGE: r'''@noindent
671 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
675 <a href="%(base)s.ly">
677 border="0" src="%(image)s" alt="%(alt)s">
685 <a href="%(base)s.ly">
693 QUOTE: r'''@quotation
694 %(str)s@end quotation
701 VERBATIM: r'''@exampleindent 0
703 %(verb)s@end verbatim
706 ADDVERSION: r'''@example
707 \version @w{"@version{}"}
714 # Maintain line numbers.
719 for f in [HTML, LATEX]:
720 for s in (QUOTE, VERBATIM):
721 output[f][s] = output[f][s].replace("\n"," ")
724 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
725 %%%% Options: [%(option_string)s]
726 \\include "lilypond-book-preamble.ly"
729 %% ****************************************************************
730 %% Start cut-&-pastable-section
731 %% ****************************************************************
736 #(define dump-extents #t)
737 %(font_dump_setting)s
739 force-assignment = #""
740 line-width = #(- line-width (* mm %(padding_mm)f))
753 %% ****************************************************************
754 %% ly snippet contents follows:
755 %% ****************************************************************
759 %% ****************************************************************
761 %% ****************************************************************
768 %% ****************************************************************
770 %% ****************************************************************
774 %% ****************************************************************
776 %% ****************************************************************
779 texinfo_line_widths = {
780 '@afourpaper': '160\\mm',
781 '@afourwide': '6.5\\in',
782 '@afourlatex': '150\\mm',
783 '@smallbook': '5\\in',
784 '@letterpaper': '6\\in',
787 def classic_lilypond_book_compatibility (key, value):
788 if key == 'singleline' and value == None:
789 return (RAGGED_RIGHT, None)
791 m = re.search ('relative\s*([-0-9])', key)
793 return ('relative', m.group (1))
795 m = re.match ('([0-9]+)pt', key)
797 return ('staffsize', m.group (1))
799 if key == 'indent' or key == 'line-width':
800 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
802 f = float (m.group (1))
803 return (key, '%f\\%s' % (f, m.group (2)))
807 def find_file (name, raise_error=True):
808 for i in global_options.include_path:
809 full = os.path.join (i, name)
810 if os.path.exists (full):
814 error (_ ("file not found: %s") % name + '\n')
818 def verbatim_html (s):
819 return re.sub ('>', '>',
821 re.sub ('&', '&', s)))
824 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
825 def set_default_options (source, default_ly_options, format):
826 if LINE_WIDTH not in default_ly_options:
828 textwidth = get_latex_textwidth (source)
829 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
830 elif format == TEXINFO:
831 m = texinfo_lang_re.search (source)
832 if m and not m.group (1).startswith ('en'):
833 default_ly_options[LANG] = m.group (1)
835 default_ly_options[LANG] = ''
836 for regex in texinfo_line_widths:
837 # FIXME: @layout is usually not in
840 # \input texinfo @c -*-texinfo-*-
842 # Bluntly search first K items of
844 # s = chunks[0].replacement_text ()
845 if re.search (regex, source[:1024]):
846 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
850 def replacement_text (self):
853 def filter_text (self):
854 return self.replacement_text ()
859 class Substring (Chunk):
860 """A string that does not require extra memory."""
861 def __init__ (self, source, start, end, line_number):
865 self.line_number = line_number
866 self.override_text = None
871 def replacement_text (self):
872 if self.override_text:
873 return self.override_text
875 return self.source[self.start:self.end]
877 class Snippet (Chunk):
878 def __init__ (self, type, match, format, line_number):
882 self.option_dict = {}
884 self.line_number = line_number
886 def replacement_text (self):
887 return self.match.group ('match')
889 def substring (self, s):
890 return self.match.group (s)
893 return `self.__class__` + ' type = ' + self.type
895 class IncludeSnippet (Snippet):
896 def processed_filename (self):
897 f = self.substring ('filename')
898 return os.path.splitext (f)[0] + format2ext[self.format]
900 def replacement_text (self):
901 s = self.match.group ('match')
902 f = self.substring ('filename')
904 return re.sub (f, self.processed_filename (), s)
906 class LilypondSnippet (Snippet):
907 def __init__ (self, type, match, format, line_number):
908 Snippet.__init__ (self, type, match, format, line_number)
909 os = match.group ('options')
910 self.do_options (os, self.type)
913 return self.substring ('code')
916 contents = self.substring ('code')
917 return ('\\sourcefileline %d\n%s'
918 % (self.line_number - 1, contents))
923 return self.compose_ly (s)
926 def split_options (self, option_string):
928 if self.format == HTML:
929 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
931 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
935 return re.split (format_res[self.format]['option_sep'],
939 def do_options (self, option_string, type):
940 self.option_dict = {}
942 options = self.split_options (option_string)
944 for option in options:
946 (key, value) = re.split ('\s*=\s*', option)
947 self.option_dict[key] = value
949 if option in no_options:
950 if no_options[option] in self.option_dict:
951 del self.option_dict[no_options[option]]
953 self.option_dict[option] = None
955 has_line_width = self.option_dict.has_key (LINE_WIDTH)
956 no_line_width_value = 0
958 # If LINE_WIDTH is used without parameter, set it to default.
959 if has_line_width and self.option_dict[LINE_WIDTH] == None:
960 no_line_width_value = 1
961 del self.option_dict[LINE_WIDTH]
963 for k in default_ly_options:
964 if k not in self.option_dict:
965 self.option_dict[k] = default_ly_options[k]
967 if not has_line_width:
968 if type == 'lilypond' or FRAGMENT in self.option_dict:
969 self.option_dict[RAGGED_RIGHT] = None
971 if type == 'lilypond':
972 if LINE_WIDTH in self.option_dict:
973 del self.option_dict[LINE_WIDTH]
975 if RAGGED_RIGHT in self.option_dict:
976 if LINE_WIDTH in self.option_dict:
977 del self.option_dict[LINE_WIDTH]
979 if QUOTE in self.option_dict or type == 'lilypond':
980 if LINE_WIDTH in self.option_dict:
981 del self.option_dict[LINE_WIDTH]
983 if not INDENT in self.option_dict:
984 self.option_dict[INDENT] = '0\\mm'
986 # The QUOTE pattern from ly_options only emits the `line-width'
988 if has_line_width and QUOTE in self.option_dict:
989 if no_line_width_value:
990 del self.option_dict[LINE_WIDTH]
992 del self.option_dict[QUOTE]
994 def compose_ly (self, code):
995 if FRAGMENT in self.option_dict:
1003 # The original concept of the `exampleindent' option is broken.
1004 # It is not possible to get a sane value for @exampleindent at all
1005 # without processing the document itself. Saying
1013 # causes ugly results with the DVI backend of texinfo since the
1014 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1015 # value). Executing the above code changes the environment
1016 # indentation to an unknown value because we don't know the amount
1017 # of 1em in advance since it is font-dependent. Modifying
1018 # @exampleindent in the middle of a document is simply not
1019 # supported within texinfo.
1021 # As a consequence, the only function of @exampleindent is now to
1022 # specify the amount of indentation for the `quote' option.
1024 # To set @exampleindent locally to zero, we use the @format
1025 # environment for non-quoted snippets.
1026 override[EXAMPLEINDENT] = r'0.4\in'
1027 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1028 override.update (default_ly_options)
1031 for (key, value) in self.option_dict.items ():
1033 option_list.append (key)
1035 option_list.append (key + '=' + value)
1036 option_string = ','.join (option_list)
1039 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1040 for a in compose_types:
1041 compose_dict[a] = []
1043 for (key, value) in self.option_dict.items ():
1044 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1048 _ ("deprecated ly-option used: %s=%s") % (key, value))
1050 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1053 _ ("deprecated ly-option used: %s") % key)
1055 _ ("compatibility mode translation: %s") % c_key)
1057 (key, value) = (c_key, c_value)
1060 override[key] = value
1062 if not override.has_key (key):
1063 override[key] = None
1066 for type in compose_types:
1067 if ly_options[type].has_key (key):
1068 compose_dict[type].append (ly_options[type][key])
1072 if not found and key not in simple_options:
1073 warning (_ ("ignoring unknown ly option: %s") % key)
1076 if RELATIVE in override and override[RELATIVE]:
1077 relative = int (override[RELATIVE])
1079 relative_quotes = ''
1083 relative_quotes += ',' * (- relative)
1085 relative_quotes += "'" * relative
1087 paper_string = '\n '.join (compose_dict[PAPER]) % override
1088 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1089 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1090 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1091 padding_mm = global_options.padding_mm
1092 font_dump_setting = ''
1093 if FONTLOAD in self.option_dict:
1094 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1096 d = globals().copy()
1098 return (PREAMBLE_LY + body) % d
1100 def get_checksum (self):
1101 if not self.checksum:
1102 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1104 ## let's not create too long names.
1105 self.checksum = hash.hexdigest ()[:10]
1107 return self.checksum
1109 def basename (self):
1110 if FILENAME in self.option_dict:
1111 return self.option_dict[FILENAME]
1113 cs = self.get_checksum ()
1115 # TODO: use xx/xxxxx directory layout.
1116 name = 'lily-%s' % cs[:10]
1119 def write_ly (self):
1120 base = self.basename ()
1121 path = os.path.join (global_options.lily_output_dir, base)
1123 out = file (path + '.ly', 'w')
1124 out.write (self.full_ly ())
1125 file (path + '.txt', 'w').write ('image of music')
1127 def relevant_contents (self, ly):
1128 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1130 def link_all_output_files (self, output_dir, output_dir_files, destination):
1131 existing, missing = self.all_output_files (output_dir, output_dir_files)
1133 print '\nMissing', missing
1134 raise CompileError(self.basename())
1135 for name in existing:
1137 os.unlink (os.path.join (destination, name))
1141 src = os.path.join (output_dir, name)
1142 dst = os.path.join (destination, name)
1146 def all_output_files (self, output_dir, output_dir_files):
1147 """Return all files generated in lily_output_dir, a set.
1149 output_dir_files is the list of files in the output directory.
1153 base = self.basename()
1154 full = os.path.join (output_dir, base)
1155 def consider_file (name):
1156 if name in output_dir_files:
1159 def require_file (name):
1160 if name in output_dir_files:
1165 # UGH - junk global_options
1166 skip_lily = global_options.skip_lilypond_run
1167 for required in [base + '.ly',
1169 require_file (required)
1171 require_file (base + '-systems.count')
1173 map (consider_file, [base + '.tex',
1176 base + '-systems.texi',
1177 base + '-systems.tex',
1178 base + '-systems.pdftexi'])
1180 # UGH - junk global_options
1181 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1182 and not global_options.skip_png_check):
1183 page_count = ps_page_count (full + '.eps')
1185 require_file (base + '.png')
1187 for page in range (1, page_count + 1):
1188 require_file (base + '-page%d.png' % page)
1191 if not skip_lily and not missing:
1192 system_count = int(file (full + '-systems.count').read())
1193 for number in range(1, system_count + 1):
1194 systemfile = '%s-%d' % (base, number)
1195 require_file (systemfile + '.eps')
1196 consider_file (systemfile + '.pdf')
1198 return (result, missing)
1200 def is_outdated (self, output_dir, current_files):
1201 found, missing = self.all_output_files (output_dir, current_files)
1204 def filter_text (self):
1205 """Run snippet bodies through a command (say: convert-ly).
1207 This functionality is rarely used, and this code must have bitrot.
1209 code = self.substring ('code')
1210 s = filter_pipe (code, global_options.filter_cmd)
1213 'options': self.match.group ('options')
1216 return output[self.format][FILTER] % d
1218 def replacement_text (self):
1219 func = LilypondSnippet.__dict__['output_' + self.format]
1222 def get_images (self):
1223 base = self.basename ()
1225 single = '%(base)s.png' % vars ()
1226 multiple = '%(base)s-page1.png' % vars ()
1228 if (os.path.exists (multiple)
1229 and (not os.path.exists (single)
1230 or (os.stat (multiple)[stat.ST_MTIME]
1231 > os.stat (single)[stat.ST_MTIME]))):
1232 count = ps_page_count ('%(base)s.eps' % vars ())
1233 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1234 images = tuple (images)
1238 def output_docbook (self):
1240 base = self.basename ()
1241 for image in self.get_images ():
1242 (base, ext) = os.path.splitext (image)
1243 str += output[DOCBOOK][OUTPUT] % vars ()
1244 str += self.output_print_filename (DOCBOOK)
1245 if (self.substring('inline') == 'inline'):
1246 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1248 str = '<mediaobject>' + str + '</mediaobject>'
1249 if VERBATIM in self.option_dict:
1250 verb = verbatim_html (self.verb_ly ())
1251 str = output[DOCBOOK][VERBATIM] % vars () + str
1254 def output_html (self):
1256 base = self.basename ()
1257 if self.format == HTML:
1258 str += self.output_print_filename (HTML)
1259 if VERBATIM in self.option_dict:
1260 verb = verbatim_html (self.verb_ly ())
1261 str += output[HTML][VERBATIM] % vars ()
1262 if QUOTE in self.option_dict:
1263 str = output[HTML][QUOTE] % vars ()
1265 str += output[HTML][BEFORE] % vars ()
1266 for image in self.get_images ():
1267 (base, ext) = os.path.splitext (image)
1268 alt = self.option_dict[ALT]
1269 str += output[HTML][OUTPUT] % vars ()
1270 str += output[HTML][AFTER] % vars ()
1273 def output_info (self):
1275 for image in self.get_images ():
1276 (base, ext) = os.path.splitext (image)
1278 # URG, makeinfo implicitly prepends dot to extension.
1279 # Specifying no extension is most robust.
1281 alt = self.option_dict[ALT]
1282 info_image_path = os.path.join (global_options.info_images_dir, base)
1283 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1285 base = self.basename ()
1286 str += output[self.format][OUTPUT] % vars ()
1289 def output_latex (self):
1291 base = self.basename ()
1292 if self.format == LATEX:
1293 str += self.output_print_filename (LATEX)
1294 if VERBATIM in self.option_dict:
1295 verb = self.verb_ly ()
1296 str += (output[LATEX][VERBATIM] % vars ())
1298 str += (output[LATEX][OUTPUT] % vars ())
1300 ## todo: maintain breaks
1302 breaks = self.ly ().count ("\n")
1303 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1305 if QUOTE in self.option_dict:
1306 str = output[LATEX][QUOTE] % vars ()
1309 def output_print_filename (self, format):
1311 if PRINTFILENAME in self.option_dict:
1312 base = self.basename ()
1313 filename = os.path.basename (self.substring ('filename'))
1314 str = output[format][PRINTFILENAME] % vars ()
1318 def output_texinfo (self):
1319 str = self.output_print_filename (TEXINFO)
1320 base = self.basename ()
1321 if TEXIDOC in self.option_dict:
1322 texidoc = base + '.texidoc'
1323 translated_texidoc = texidoc + default_ly_options[LANG]
1324 if os.path.exists (translated_texidoc):
1325 str += '@include %(translated_texidoc)s\n\n' % vars ()
1326 elif os.path.exists (texidoc):
1327 str += '@include %(texidoc)s\n\n' % vars ()
1330 if VERBATIM in self.option_dict:
1332 if ADDVERSION in self.option_dict:
1333 version = output[TEXINFO][ADDVERSION]
1334 verb = self.verb_ly ()
1335 substr = output[TEXINFO][VERBATIM] % vars ()
1336 substr += self.output_info ()
1337 if LILYQUOTE in self.option_dict:
1338 substr = output[TEXINFO][QUOTE] % {'str':substr}
1341 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1342 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1343 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1345 if QUOTE in self.option_dict:
1346 str = output[TEXINFO][QUOTE] % vars ()
1348 # need par after image
1353 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1354 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1356 class LilypondFileSnippet (LilypondSnippet):
1357 def __init__ (self, type, match, format, line_number):
1358 LilypondSnippet.__init__ (self, type, match, format, line_number)
1359 self.contents = file (find_file (self.substring ('filename'))).read ()
1363 s = re_begin_verbatim.split (s)[-1]
1364 s = re_end_verbatim.split (s)[0]
1368 name = self.substring ('filename')
1369 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1370 % (name, self.contents))
1373 snippet_type_to_class = {
1374 'lilypond_file': LilypondFileSnippet,
1375 'lilypond_block': LilypondSnippet,
1376 'lilypond': LilypondSnippet,
1377 'include': IncludeSnippet,
1380 def find_linestarts (s):
1385 i = s.find ('\n', start)
1393 nls.append (len (s))
1396 def find_toplevel_snippets (input_string, format, types):
1399 res[t] = re.compile (snippet_res[format][t])
1403 found = dict ([(t, None) for t in types])
1405 line_starts = find_linestarts (input_string)
1407 # We want to search for multiple regexes, without searching
1408 # the string multiple times for one regex.
1409 # Hence, we use earlier results to limit the string portion
1411 # Since every part of the string is traversed at most once for
1412 # every type of snippet, this is linear.
1418 if not found[type] or found[type][0] < index:
1421 m = res[type].search (input_string[index:endex])
1426 if type in snippet_type_to_class:
1427 klass = snippet_type_to_class[type]
1429 start = index + m.start ('match')
1430 line_number = line_start_idx
1431 while (line_starts[line_number] < start):
1435 snip = klass (type, m, format, line_number)
1437 found[type] = (start, snip)
1441 or found[type][0] < found[first][0])):
1446 # Limiting the search space is a cute
1447 # idea, but this *requires* to search
1448 # for possible containing blocks
1449 # first, at least as long as we do not
1450 # search for the start of blocks, but
1451 # always/directly for the entire
1452 # @block ... @end block.
1454 endex = found[first][0]
1457 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1460 while (start > line_starts[line_start_idx+1]):
1463 (start, snip) = found[first]
1464 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1465 snippets.append (snip)
1467 index = start + len (snip.match.group ('match'))
1471 def filter_pipe (input, cmd):
1472 """Pass input through cmd, and return the result."""
1474 if global_options.verbose:
1475 progress (_ ("Opening filter `%s'") % cmd)
1477 (stdin, stdout, stderr) = os.popen3 (cmd)
1479 status = stdin.close ()
1483 output = stdout.read ()
1484 status = stdout.close ()
1485 error = stderr.read ()
1489 signal = 0x0f & status
1490 if status or (not output and error):
1491 exit_status = status >> 8
1492 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1493 error (_ ("The error log is as follows:"))
1494 ly.stderr_write (error)
1495 ly.stderr_write (stderr.read ())
1498 if global_options.verbose:
1503 def system_in_directory (cmd, directory):
1504 """Execute a command in a different directory.
1506 Because of win32 compatibility, we can't simply use subprocess.
1509 current = os.getcwd()
1510 os.chdir (directory)
1511 ly.system(cmd, be_verbose=global_options.verbose,
1516 def process_snippets (cmd, snippets,
1517 format, lily_output_dir):
1518 """Run cmd on all of the .ly files from snippets."""
1523 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1524 cmd += ' --formats=png '
1525 elif format in (DOCBOOK) and '--formats' not in cmd:
1526 cmd += ' --formats=png,pdf '
1528 checksum = snippet_list_checksum (snippets)
1529 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1530 + [snip.basename() for snip in snippets])
1531 name = os.path.join (lily_output_dir,
1532 'snippet-names-%d' % checksum)
1533 file (name, 'wb').write (contents)
1535 system_in_directory (' '.join ([cmd, name]),
1540 # Retrieve dimensions from LaTeX
1541 LATEX_INSPECTION_DOCUMENT = r'''
1545 \typeout{textwidth=\the\textwidth}
1546 \typeout{columnsep=\the\columnsep}
1547 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1551 # Do we need anything else besides `textwidth'?
1552 def get_latex_textwidth (source):
1553 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1555 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1557 ## what's a sensible default?
1560 preamble = source[:m.start (0)]
1561 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1563 (handle, tmpfile) = tempfile.mkstemp('.tex')
1564 logfile = os.path.splitext (tmpfile)[0] + '.log'
1565 logfile = os.path.split (logfile)[1]
1567 tmp_handle = os.fdopen (handle,'w')
1568 tmp_handle.write (latex_document)
1571 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1572 parameter_string = file (logfile).read()
1578 m = re.search ('columns=([0-9.]*)', parameter_string)
1580 columns = int (m.group (1))
1583 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1585 columnsep = float (m.group (1))
1588 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1590 textwidth = float (m.group (1))
1592 textwidth = (textwidth - columnsep) / columns
1596 def modify_preamble (chunk):
1597 str = chunk.replacement_text ()
1598 if (re.search (r"\\begin *{document}", str)
1599 and not re.search ("{graphic[sx]", str)):
1600 str = re.sub (r"\\begin{document}",
1601 r"\\usepackage{graphics}" + '\n'
1602 + r"\\begin{document}",
1604 chunk.override_text = str
1609 # TEXINFO: '.texinfo',
1615 class CompileError(Exception):
1618 def snippet_list_checksum (snippets):
1619 return hash (' '.join([l.basename() for l in snippets]))
1621 def write_file_map (lys, name):
1622 snippet_map = file (os.path.join (
1623 global_options.lily_output_dir,
1624 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1626 snippet_map.write ("""
1627 #(define version-seen #t)
1628 #(define output-empty-score-list #f)
1629 #(ly:add-file-name-alist '(%s
1631 """ % '\n'.join('("%s.ly" . "%s")\n' % (ly.basename (), name)
1634 def do_process_cmd (chunks, input_name, options):
1635 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1638 output_files = set(os.listdir(options.lily_output_dir))
1639 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1641 write_file_map (outdated, input_name)
1642 progress (_ ("Writing snippets..."))
1643 for snippet in outdated:
1648 progress (_ ("Processing..."))
1650 process_snippets (options.process_cmd, outdated,
1651 options.format, options.lily_output_dir)
1654 progress (_ ("All snippets are up to date..."))
1656 if options.lily_output_dir != options.output_dir:
1657 output_files = set(os.listdir(options.lily_output_dir))
1658 for snippet in snippets:
1659 snippet.link_all_output_files (options.lily_output_dir,
1667 # Format guessing data
1676 '.texinfo': TEXINFO,
1681 def guess_format (input_filename):
1683 e = os.path.splitext (input_filename)[1]
1686 format = ext2format[e]
1688 error (_ ("cannot determine format for: %s"
1693 def write_if_updated (file_name, lines):
1695 f = file (file_name)
1697 new_str = ''.join (lines)
1698 if oldstr == new_str:
1699 progress (_ ("%s is up to date.") % file_name)
1702 # this prevents make from always rerunning lilypond-book:
1703 # output file must be touched in order to be up to date
1704 os.utime (file_name, None)
1708 progress (_ ("Writing `%s'...") % file_name)
1709 file (file_name, 'w').writelines (lines)
1713 def note_input_file (name, inputs=[]):
1714 ## hack: inputs is mutable!
1715 inputs.append (name)
1718 def samefile (f1, f2):
1720 return os.path.samefile (f1, f2)
1721 except AttributeError: # Windoze
1722 f1 = re.sub ("//*", "/", f1)
1723 f2 = re.sub ("//*", "/", f2)
1726 def do_file (input_filename):
1728 if not input_filename or input_filename == '-':
1729 in_handle = sys.stdin
1730 input_fullname = '<stdin>'
1732 if os.path.exists (input_filename):
1733 input_fullname = input_filename
1734 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1735 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1737 input_fullname = find_file (input_filename)
1739 note_input_file (input_fullname)
1740 in_handle = file (input_fullname)
1742 if input_filename == '-':
1743 input_base = 'stdin'
1745 input_base = os.path.basename (
1746 os.path.splitext (input_filename)[0])
1748 # don't complain when global_options.output_dir is existing
1749 if not global_options.output_dir:
1750 global_options.output_dir = os.getcwd()
1752 global_options.output_dir = os.path.abspath(global_options.output_dir)
1754 if not os.path.isdir (global_options.output_dir):
1755 os.mkdir (global_options.output_dir, 0777)
1756 os.chdir (global_options.output_dir)
1758 output_filename = os.path.join(global_options.output_dir,
1759 input_base + format2ext[global_options.format])
1760 if (os.path.exists (input_filename)
1761 and os.path.exists (output_filename)
1762 and samefile (output_filename, input_fullname)):
1764 _ ("Output would overwrite input file; use --output."))
1768 progress (_ ("Reading %s...") % input_fullname)
1769 source = in_handle.read ()
1772 set_default_options (source, default_ly_options, global_options.format)
1775 # FIXME: Containing blocks must be first, see
1776 # find_toplevel_snippets.
1778 'multiline_comment',
1782 'singleline_comment',
1787 progress (_ ("Dissecting..."))
1788 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1790 if global_options.format == LATEX:
1792 if (c.is_plain () and
1793 re.search (r"\\begin *{document}", c.replacement_text())):
1798 if global_options.filter_cmd:
1799 write_if_updated (output_filename,
1800 [c.filter_text () for c in chunks])
1801 elif global_options.process_cmd:
1802 do_process_cmd (chunks, input_fullname, global_options)
1803 progress (_ ("Compiling %s...") % output_filename)
1805 write_if_updated (output_filename,
1806 [s.replacement_text ()
1809 def process_include (snippet):
1810 os.chdir (original_dir)
1811 name = snippet.substring ('filename')
1812 progress (_ ("Processing include: %s") % name)
1814 return do_file (name)
1816 include_chunks = map (process_include,
1817 filter (lambda x: isinstance (x, IncludeSnippet),
1820 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1822 except CompileError:
1823 os.chdir (original_dir)
1824 progress (_ ("Removing `%s'") % output_filename)
1829 global global_options
1831 opt_parser = get_option_parser()
1832 (global_options, args) = opt_parser.parse_args ()
1833 if global_options.format in ('texi-html', 'texi'):
1834 global_options.format = TEXINFO
1836 global_options.include_path = map (os.path.abspath, global_options.include_path)
1838 if global_options.warranty:
1841 if not args or len (args) > 1:
1842 opt_parser.print_help ()
1848 # FIXME: 85 lines of `main' macramee??
1849 files = do_options ()
1851 basename = os.path.splitext (files[0])[0]
1852 basename = os.path.split (basename)[1]
1854 if not global_options.format:
1855 global_options.format = guess_format (files[0])
1858 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1861 if global_options.process_cmd == '':
1862 global_options.process_cmd = (lilypond_binary
1863 + ' --formats=%s -dbackend=eps ' % formats)
1865 if global_options.process_cmd:
1866 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1867 for p in global_options.include_path])
1869 if global_options.format in (TEXINFO, LATEX):
1870 ## prevent PDF from being switched on by default.
1871 global_options.process_cmd += ' --formats=eps '
1872 if global_options.create_pdf:
1873 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1875 if global_options.verbose:
1876 global_options.process_cmd += " --verbose "
1878 if global_options.padding_mm:
1879 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1881 global_options.process_cmd += " -dread-file-list "
1883 if global_options.lily_output_dir:
1884 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1885 if not os.path.isdir (global_options.lily_output_dir):
1886 os.makedirs (global_options.lily_output_dir)
1888 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1893 chunks = do_file (files[0])
1894 except CompileError:
1897 inputs = note_input_file ('')
1900 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1901 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1902 final_output_file = os.path.join (global_options.output_dir,
1904 + '.%s' % global_options.format)
1906 os.chdir (original_dir)
1907 file (dep_file, 'w').write ('%s: %s'
1908 % (final_output_file, ' '.join (inputs)))
1910 if __name__ == '__main__':