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
49 program_version = '@TOPLEVEL_VERSION@'
50 program_name = os.path.basename (sys.argv[0])
52 original_dir = os.getcwd ()
56 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
60 lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
61 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
62 lilypond-book --process='lilypond -I include' %(BOOK)s
63 ''' % {'BOOK': _ ("BOOK")})
65 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
66 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
68 ################################################################
70 if global_options.verbose:
71 raise Exception (_ ('Exiting (%d)...') % i)
76 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
78 progress = ly.progress
81 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
84 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
86 def ps_page_count (ps_name):
87 header = file (ps_name).read (1024)
88 m = re.search ('\n%%Pages: ([0-9]+)', header)
90 return int (m.group (1))
95 ly.encoded_write (sys.stdout, '''
102 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
104 _ ("Distributed under terms of the GNU General Public License."),
105 _ ("It comes with NO WARRANTY.")))
107 def get_option_parser ():
108 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
109 description=help_summary,
110 add_help_option=False)
112 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
115 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
118 p.add_option ('-f', '--format',
119 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
122 p.add_option("-h", "--help",
124 help=_ ("show this help and exit"))
126 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
128 action='append', dest='include_path',
129 default=[os.path.abspath (os.getcwd ())])
131 p.add_option ('--info-images-dir',
132 help=_ ("format Texinfo output so that Info will "
133 "look for images of music in DIR"),
135 action='store', dest='info_images_dir',
138 p.add_option ('--left-padding',
141 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
145 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
147 action='store', dest='output_dir',
150 p.add_option ('--skip-lily-check',
151 help=_ ("do not fail if no lilypond output is found."),
153 action='store_true', dest='skip_lilypond_run',
156 p.add_option ('--skip-png-check',
157 help=_ ("do not fail if no PNG images are found for EPS files"),
159 action='store_true', dest='skip_png_check',
162 p.add_option ('--lily-output-dir',
163 help=_ ("write lily-XXX files to DIR, link into --output dir."),
165 action='store', dest='lily_output_dir',
168 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
169 help = _ ("process ly_files using COMMAND FILE..."),
171 dest='process_cmd', default='')
173 p.add_option ('--pdf',
176 help=_ ("create PDF files for use with PDFTeX"),
179 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
180 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
181 must use this with dvips -h INPUT.psfonts'''),
184 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
189 p.version = "@TOPLEVEL_VERSION@"
190 p.add_option("--version",
192 help=_ ("show version number and exit"))
194 p.add_option ('-w', '--warranty',
195 help=_ ("show warranty and copyright"),
197 p.add_option_group (ly.display_encode (_ ('Bugs')),
199 _ ("Report bugs via")
200 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
203 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
205 # Only use installed binary when we are installed too.
206 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
207 lilypond_binary = 'lilypond'
209 global_options = None
212 default_ly_options = { 'alt': "[image of music]" }
215 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
217 ADDVERSION = 'addversion'
221 EXAMPLEINDENT = 'exampleindent'
223 FRAGMENT = 'fragment'
229 LINE_WIDTH = 'line-width'
230 LILYQUOTE = 'lilyquote'
231 NOFRAGMENT = 'nofragment'
232 NOINDENT = 'noindent'
237 OUTPUTIMAGE = 'outputimage'
240 PREAMBLE = 'preamble'
241 PRINTFILENAME = 'printfilename'
243 RAGGED_RIGHT = 'ragged-right'
244 RELATIVE = 'relative'
245 STAFFSIZE = 'staffsize'
248 VERBATIM = 'verbatim'
249 FONTLOAD = 'fontload'
250 FILENAME = 'filename'
254 # NOTIME has no opposite so it isn't part of this dictionary.
255 # NOQUOTE is used internally only.
257 NOFRAGMENT: FRAGMENT,
262 # Recognize special sequences in the input.
264 # (?P<name>regex) -- Assign result of REGEX to NAME.
265 # *? -- Match non-greedily.
266 # (?m) -- Multiline regex: Make ^ and $ match at each line.
267 # (?s) -- Make the dot match all characters including newline.
268 # (?x) -- Ignore whitespace in patterns.
279 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
284 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
289 <(?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>)''',
295 (?P<code><!--\s.*?!-->)
298 'singleline_comment':
317 (\s*(?P<options>.*?)\s*:)?\s*
325 \s*(?P<options>.*?)\s*
334 \s*(?P<options>.*?)\s*
336 \s*(?P<filename>.*?)\s*
343 (?P<code><!--\s.*?!-->)
346 'singleline_comment':
352 (?P<code><pre>.*?</pre>))''',
358 (?P<code><pre>\s.*?</pre>\s))''',
377 \s*(?P<options>.*?)\s*
388 \s*(?P<options>.*?)\s*
392 \\end\s*{lilypond})''',
400 \s*(?P<options>.*?)\s*
408 'singleline_comment':
431 \\end\s*{verbatim}))''',
440 (?P<filename>\S+))''',
444 ^[^\n]*?(?!@c\s+)[^\n]*?
448 \s*(?P<options>.*?)\s*
458 \s*(?P<options>.*?)\s*
461 ^@end\s+lilypond)\s''',
468 \s*(?P<options>.*?)\s*
479 @end\s+ignore))\s''',
481 'singleline_comment':
486 @c([ \t][^\n]*|)\n))''',
488 # Don't do this: It interferes with @code{@{}.
489 # 'verb': r'''(?P<code>@code{.*?})''',
497 @end\s+example\s))''',
506 'intertext': r',?\s*intertext=\".*?\"',
510 'intertext': r',?\s*intertext=\".*?\"',
515 'intertext': r',?\s*intertext=\".*?\"',
516 'option_sep': '\s*,\s*',
520 'intertext': r',?\s*intertext=\".*?\"',
521 'option_sep': '\s*,\s*',
525 # Options without a pattern in ly_options.
544 RELATIVE: r'''\relative c%(relative_quotes)s''',
549 INDENT: r'''indent = %(indent)s''',
551 LINE_WIDTH: r'''line-width = %(line-width)s''',
553 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
555 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
557 RAGGED_RIGHT: r'''ragged-right = ##t''',
559 PACKED: r'''packed = ##t''',
571 \remove Time_signature_engraver
577 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
584 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
587 <imageobject role="latex">
588 <imagedata fileref="%(base)s.pdf" format="PDF"/>
590 <imageobject role="html">
591 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
593 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
595 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
599 FILTER: r'''<lilypond %(options)s>
609 <a href="%(base)s.ly">''',
613 border="0" src="%(image)s" alt="%(alt)s">''',
615 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
617 QUOTE: r'''<blockquote>
630 \ifx\preLilyPondExample \undefined%%
633 \preLilyPondExample%%
635 \def\lilypondbook{}%%
636 \input %(base)s-systems.tex%%
637 \ifx\postLilyPondExample \undefined%%
640 \postLilyPondExample%%
644 PRINTFILENAME: '''\\texttt{%(filename)s}
647 QUOTE: r'''\begin{quotation}%(str)s
650 VERBATIM: r'''\noindent
651 \begin{verbatim}%(verb)s\end{verbatim}''',
653 FILTER: r'''\begin{lilypond}[%(options)s]
660 FILTER: r'''@lilypond[%(options)s]
666 @include %(base)s-systems.texi
670 OUTPUTIMAGE: r'''@noindent
672 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
676 <a href="%(base)s.ly">
678 border="0" src="%(image)s" alt="%(alt)s">
686 <a href="%(base)s.ly">
694 QUOTE: r'''@quotation
695 %(str)s@end quotation
702 VERBATIM: r'''@exampleindent 0
704 %(verb)s@end verbatim
707 ADDVERSION: r'''@example
708 \version @w{"@version{}"}
715 # Maintain line numbers.
720 for f in [HTML, LATEX]:
721 for s in (QUOTE, VERBATIM):
722 output[f][s] = output[f][s].replace("\n"," ")
725 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
726 %%%% Options: [%(option_string)s]
727 \\include "lilypond-book-preamble.ly"
730 %% ****************************************************************
731 %% Start cut-&-pastable-section
732 %% ****************************************************************
737 #(define dump-extents #t)
738 %(font_dump_setting)s
740 force-assignment = #""
741 line-width = #(- line-width (* mm %(padding_mm)f))
754 %% ****************************************************************
755 %% ly snippet contents follows:
756 %% ****************************************************************
760 %% ****************************************************************
762 %% ****************************************************************
769 %% ****************************************************************
771 %% ****************************************************************
775 %% ****************************************************************
777 %% ****************************************************************
780 texinfo_line_widths = {
781 '@afourpaper': '160\\mm',
782 '@afourwide': '6.5\\in',
783 '@afourlatex': '150\\mm',
784 '@smallbook': '5\\in',
785 '@letterpaper': '6\\in',
788 def classic_lilypond_book_compatibility (key, value):
789 if key == 'singleline' and value == None:
790 return (RAGGED_RIGHT, None)
792 m = re.search ('relative\s*([-0-9])', key)
794 return ('relative', m.group (1))
796 m = re.match ('([0-9]+)pt', key)
798 return ('staffsize', m.group (1))
800 if key == 'indent' or key == 'line-width':
801 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
803 f = float (m.group (1))
804 return (key, '%f\\%s' % (f, m.group (2)))
808 def find_file (name, raise_error=True):
809 for i in global_options.include_path:
810 full = os.path.join (i, name)
811 if os.path.exists (full):
815 error (_ ("file not found: %s") % name + '\n')
819 def verbatim_html (s):
820 return re.sub ('>', '>',
822 re.sub ('&', '&', s)))
825 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
826 def set_default_options (source, default_ly_options, format):
827 if LINE_WIDTH not in default_ly_options:
829 textwidth = get_latex_textwidth (source)
830 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
831 elif format == TEXINFO:
832 m = texinfo_lang_re.search (source)
833 if m and not m.group (1).startswith ('en'):
834 default_ly_options[LANG] = m.group (1)
836 default_ly_options[LANG] = ''
837 for regex in texinfo_line_widths:
838 # FIXME: @layout is usually not in
841 # \input texinfo @c -*-texinfo-*-
843 # Bluntly search first K items of
845 # s = chunks[0].replacement_text ()
846 if re.search (regex, source[:1024]):
847 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
851 def replacement_text (self):
854 def filter_text (self):
855 return self.replacement_text ()
860 class Substring (Chunk):
861 """A string that does not require extra memory."""
862 def __init__ (self, source, start, end, line_number):
866 self.line_number = line_number
867 self.override_text = None
872 def replacement_text (self):
873 if self.override_text:
874 return self.override_text
876 return self.source[self.start:self.end]
878 class Snippet (Chunk):
879 def __init__ (self, type, match, format, line_number):
883 self.option_dict = {}
885 self.line_number = line_number
887 def replacement_text (self):
888 return self.match.group ('match')
890 def substring (self, s):
891 return self.match.group (s)
894 return `self.__class__` + ' type = ' + self.type
896 class IncludeSnippet (Snippet):
897 def processed_filename (self):
898 f = self.substring ('filename')
899 return os.path.splitext (f)[0] + format2ext[self.format]
901 def replacement_text (self):
902 s = self.match.group ('match')
903 f = self.substring ('filename')
905 return re.sub (f, self.processed_filename (), s)
907 class LilypondSnippet (Snippet):
908 def __init__ (self, type, match, format, line_number):
909 Snippet.__init__ (self, type, match, format, line_number)
910 os = match.group ('options')
911 self.do_options (os, self.type)
914 return self.substring ('code')
917 contents = self.substring ('code')
918 return ('\\sourcefileline %d\n%s'
919 % (self.line_number - 1, contents))
924 return self.compose_ly (s)
927 def split_options (self, option_string):
929 if self.format == HTML:
930 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
932 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
936 return re.split (format_res[self.format]['option_sep'],
940 def do_options (self, option_string, type):
941 self.option_dict = {}
943 options = self.split_options (option_string)
945 for option in options:
947 (key, value) = re.split ('\s*=\s*', option)
948 self.option_dict[key] = value
950 if option in no_options:
951 if no_options[option] in self.option_dict:
952 del self.option_dict[no_options[option]]
954 self.option_dict[option] = None
956 has_line_width = self.option_dict.has_key (LINE_WIDTH)
957 no_line_width_value = 0
959 # If LINE_WIDTH is used without parameter, set it to default.
960 if has_line_width and self.option_dict[LINE_WIDTH] == None:
961 no_line_width_value = 1
962 del self.option_dict[LINE_WIDTH]
964 for k in default_ly_options:
965 if k not in self.option_dict:
966 self.option_dict[k] = default_ly_options[k]
968 if not has_line_width:
969 if type == 'lilypond' or FRAGMENT in self.option_dict:
970 self.option_dict[RAGGED_RIGHT] = None
972 if type == 'lilypond':
973 if LINE_WIDTH in self.option_dict:
974 del self.option_dict[LINE_WIDTH]
976 if RAGGED_RIGHT in self.option_dict:
977 if LINE_WIDTH in self.option_dict:
978 del self.option_dict[LINE_WIDTH]
980 if QUOTE in self.option_dict or type == 'lilypond':
981 if LINE_WIDTH in self.option_dict:
982 del self.option_dict[LINE_WIDTH]
984 if not INDENT in self.option_dict:
985 self.option_dict[INDENT] = '0\\mm'
987 # The QUOTE pattern from ly_options only emits the `line-width'
989 if has_line_width and QUOTE in self.option_dict:
990 if no_line_width_value:
991 del self.option_dict[LINE_WIDTH]
993 del self.option_dict[QUOTE]
995 def compose_ly (self, code):
996 if FRAGMENT in self.option_dict:
1004 # The original concept of the `exampleindent' option is broken.
1005 # It is not possible to get a sane value for @exampleindent at all
1006 # without processing the document itself. Saying
1014 # causes ugly results with the DVI backend of texinfo since the
1015 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1016 # value). Executing the above code changes the environment
1017 # indentation to an unknown value because we don't know the amount
1018 # of 1em in advance since it is font-dependent. Modifying
1019 # @exampleindent in the middle of a document is simply not
1020 # supported within texinfo.
1022 # As a consequence, the only function of @exampleindent is now to
1023 # specify the amount of indentation for the `quote' option.
1025 # To set @exampleindent locally to zero, we use the @format
1026 # environment for non-quoted snippets.
1027 override[EXAMPLEINDENT] = r'0.4\in'
1028 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1029 override.update (default_ly_options)
1032 for (key, value) in self.option_dict.items ():
1034 option_list.append (key)
1036 option_list.append (key + '=' + value)
1037 option_string = ','.join (option_list)
1040 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1041 for a in compose_types:
1042 compose_dict[a] = []
1044 for (key, value) in self.option_dict.items ():
1045 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1049 _ ("deprecated ly-option used: %s=%s") % (key, value))
1051 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1054 _ ("deprecated ly-option used: %s") % key)
1056 _ ("compatibility mode translation: %s") % c_key)
1058 (key, value) = (c_key, c_value)
1061 override[key] = value
1063 if not override.has_key (key):
1064 override[key] = None
1067 for type in compose_types:
1068 if ly_options[type].has_key (key):
1069 compose_dict[type].append (ly_options[type][key])
1073 if not found and key not in simple_options:
1074 warning (_ ("ignoring unknown ly option: %s") % key)
1077 if RELATIVE in override and override[RELATIVE]:
1078 relative = int (override[RELATIVE])
1080 relative_quotes = ''
1084 relative_quotes += ',' * (- relative)
1086 relative_quotes += "'" * relative
1088 paper_string = '\n '.join (compose_dict[PAPER]) % override
1089 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1090 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1091 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1092 padding_mm = global_options.padding_mm
1093 font_dump_setting = ''
1094 if FONTLOAD in self.option_dict:
1095 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1097 d = globals().copy()
1099 return (PREAMBLE_LY + body) % d
1101 def get_checksum (self):
1102 if not self.checksum:
1103 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1105 ## let's not create too long names.
1106 self.checksum = hash.hexdigest ()[:10]
1108 return self.checksum
1110 def basename (self):
1111 cs = self.get_checksum ()
1112 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1115 def write_ly (self):
1116 base = self.basename ()
1117 path = os.path.join (global_options.lily_output_dir, base)
1118 directory = os.path.split(path)[0]
1119 if not os.path.isdir (directory):
1120 os.makedirs (directory)
1121 out = file (path + '.ly', 'w')
1122 out.write (self.full_ly ())
1123 file (path + '.txt', 'w').write ('image of music')
1125 def relevant_contents (self, ly):
1126 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1128 def link_all_output_files (self, output_dir, output_dir_files, destination):
1129 existing, missing = self.all_output_files (output_dir, output_dir_files)
1131 print '\nMissing', missing
1132 raise CompileError(self.basename())
1133 for name in existing:
1135 os.unlink (os.path.join (destination, name))
1139 src = os.path.join (output_dir, name)
1140 dst = os.path.join (destination, name)
1141 dst_path = os.path.split(dst)[0]
1142 if not os.path.isdir (dst_path):
1143 os.makedirs (dst_path)
1147 def all_output_files (self, output_dir, output_dir_files):
1148 """Return all files generated in lily_output_dir, a set.
1150 output_dir_files is the list of files in the output directory.
1154 base = self.basename()
1155 full = os.path.join (output_dir, base)
1156 def consider_file (name):
1157 if name in output_dir_files:
1160 def require_file (name):
1161 if name in output_dir_files:
1166 # UGH - junk global_options
1167 skip_lily = global_options.skip_lilypond_run
1168 for required in [base + '.ly',
1170 require_file (required)
1172 require_file (base + '-systems.count')
1174 map (consider_file, [base + '.tex',
1177 base + '-systems.texi',
1178 base + '-systems.tex',
1179 base + '-systems.pdftexi'])
1181 # UGH - junk global_options
1182 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1183 and not global_options.skip_png_check):
1184 page_count = ps_page_count (full + '.eps')
1186 require_file (base + '.png')
1188 for page in range (1, page_count + 1):
1189 require_file (base + '-page%d.png' % page)
1192 if not skip_lily and not missing:
1193 system_count = int(file (full + '-systems.count').read())
1194 for number in range(1, system_count + 1):
1195 systemfile = '%s-%d' % (base, number)
1196 require_file (systemfile + '.eps')
1197 consider_file (systemfile + '.pdf')
1199 return (result, missing)
1201 def is_outdated (self, output_dir, current_files):
1202 found, missing = self.all_output_files (output_dir, current_files)
1205 def filter_text (self):
1206 """Run snippet bodies through a command (say: convert-ly).
1208 This functionality is rarely used, and this code must have bitrot.
1210 code = self.substring ('code')
1211 s = filter_pipe (code, global_options.filter_cmd)
1214 'options': self.match.group ('options')
1217 return output[self.format][FILTER] % d
1219 def replacement_text (self):
1220 func = LilypondSnippet.__dict__['output_' + self.format]
1223 def get_images (self):
1224 base = self.basename ()
1226 single = '%(base)s.png' % vars ()
1227 multiple = '%(base)s-page1.png' % vars ()
1229 if (os.path.exists (multiple)
1230 and (not os.path.exists (single)
1231 or (os.stat (multiple)[stat.ST_MTIME]
1232 > os.stat (single)[stat.ST_MTIME]))):
1233 count = ps_page_count ('%(base)s.eps' % vars ())
1234 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1235 images = tuple (images)
1239 def output_docbook (self):
1241 base = self.basename ()
1242 for image in self.get_images ():
1243 (base, ext) = os.path.splitext (image)
1244 str += output[DOCBOOK][OUTPUT] % vars ()
1245 str += self.output_print_filename (DOCBOOK)
1246 if (self.substring('inline') == 'inline'):
1247 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1249 str = '<mediaobject>' + str + '</mediaobject>'
1250 if VERBATIM in self.option_dict:
1251 verb = verbatim_html (self.verb_ly ())
1252 str = output[DOCBOOK][VERBATIM] % vars () + str
1255 def output_html (self):
1257 base = self.basename ()
1258 if self.format == HTML:
1259 str += self.output_print_filename (HTML)
1260 if VERBATIM in self.option_dict:
1261 verb = verbatim_html (self.verb_ly ())
1262 str += output[HTML][VERBATIM] % vars ()
1263 if QUOTE in self.option_dict:
1264 str = output[HTML][QUOTE] % vars ()
1266 str += output[HTML][BEFORE] % vars ()
1267 for image in self.get_images ():
1268 (base, ext) = os.path.splitext (image)
1269 alt = self.option_dict[ALT]
1270 str += output[HTML][OUTPUT] % vars ()
1271 str += output[HTML][AFTER] % vars ()
1274 def output_info (self):
1276 for image in self.get_images ():
1277 (base, ext) = os.path.splitext (image)
1279 # URG, makeinfo implicitly prepends dot to extension.
1280 # Specifying no extension is most robust.
1282 alt = self.option_dict[ALT]
1283 info_image_path = os.path.join (global_options.info_images_dir, base)
1284 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1286 base = self.basename ()
1287 str += output[self.format][OUTPUT] % vars ()
1290 def output_latex (self):
1292 base = self.basename ()
1293 if self.format == LATEX:
1294 str += self.output_print_filename (LATEX)
1295 if VERBATIM in self.option_dict:
1296 verb = self.verb_ly ()
1297 str += (output[LATEX][VERBATIM] % vars ())
1299 str += (output[LATEX][OUTPUT] % vars ())
1301 ## todo: maintain breaks
1303 breaks = self.ly ().count ("\n")
1304 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1306 if QUOTE in self.option_dict:
1307 str = output[LATEX][QUOTE] % vars ()
1310 def output_print_filename (self, format):
1312 if PRINTFILENAME in self.option_dict:
1313 base = self.basename ()
1314 filename = os.path.basename (self.substring ('filename'))
1315 str = output[format][PRINTFILENAME] % vars ()
1319 def output_texinfo (self):
1320 str = self.output_print_filename (TEXINFO)
1321 base = self.basename ()
1322 if TEXIDOC in self.option_dict:
1323 texidoc = base + '.texidoc'
1324 translated_texidoc = texidoc + default_ly_options[LANG]
1325 if os.path.exists (translated_texidoc):
1326 str += '@include %(translated_texidoc)s\n\n' % vars ()
1327 elif os.path.exists (texidoc):
1328 str += '@include %(texidoc)s\n\n' % vars ()
1331 if VERBATIM in self.option_dict:
1333 if ADDVERSION in self.option_dict:
1334 version = output[TEXINFO][ADDVERSION]
1335 verb = self.verb_ly ()
1336 substr = output[TEXINFO][VERBATIM] % vars ()
1337 substr += self.output_info ()
1338 if LILYQUOTE in self.option_dict:
1339 substr = output[TEXINFO][QUOTE] % {'str':substr}
1342 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1343 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1344 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1346 if QUOTE in self.option_dict:
1347 str = output[TEXINFO][QUOTE] % vars ()
1349 # need par after image
1354 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1355 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1357 class LilypondFileSnippet (LilypondSnippet):
1358 def __init__ (self, type, match, format, line_number):
1359 LilypondSnippet.__init__ (self, type, match, format, line_number)
1360 self.contents = file (find_file (self.substring ('filename'))).read ()
1364 s = re_begin_verbatim.split (s)[-1]
1365 s = re_end_verbatim.split (s)[0]
1369 name = self.substring ('filename')
1370 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1371 % (name, self.contents))
1374 snippet_type_to_class = {
1375 'lilypond_file': LilypondFileSnippet,
1376 'lilypond_block': LilypondSnippet,
1377 'lilypond': LilypondSnippet,
1378 'include': IncludeSnippet,
1381 def find_linestarts (s):
1386 i = s.find ('\n', start)
1394 nls.append (len (s))
1397 def find_toplevel_snippets (input_string, format, types):
1400 res[t] = re.compile (snippet_res[format][t])
1404 found = dict ([(t, None) for t in types])
1406 line_starts = find_linestarts (input_string)
1408 # We want to search for multiple regexes, without searching
1409 # the string multiple times for one regex.
1410 # Hence, we use earlier results to limit the string portion
1412 # Since every part of the string is traversed at most once for
1413 # every type of snippet, this is linear.
1419 if not found[type] or found[type][0] < index:
1422 m = res[type].search (input_string[index:endex])
1427 if type in snippet_type_to_class:
1428 klass = snippet_type_to_class[type]
1430 start = index + m.start ('match')
1431 line_number = line_start_idx
1432 while (line_starts[line_number] < start):
1436 snip = klass (type, m, format, line_number)
1438 found[type] = (start, snip)
1442 or found[type][0] < found[first][0])):
1447 # Limiting the search space is a cute
1448 # idea, but this *requires* to search
1449 # for possible containing blocks
1450 # first, at least as long as we do not
1451 # search for the start of blocks, but
1452 # always/directly for the entire
1453 # @block ... @end block.
1455 endex = found[first][0]
1458 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1461 while (start > line_starts[line_start_idx+1]):
1464 (start, snip) = found[first]
1465 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1466 snippets.append (snip)
1468 index = start + len (snip.match.group ('match'))
1472 def filter_pipe (input, cmd):
1473 """Pass input through cmd, and return the result."""
1475 if global_options.verbose:
1476 progress (_ ("Opening filter `%s'") % cmd)
1478 (stdin, stdout, stderr) = os.popen3 (cmd)
1480 status = stdin.close ()
1484 output = stdout.read ()
1485 status = stdout.close ()
1486 error = stderr.read ()
1490 signal = 0x0f & status
1491 if status or (not output and error):
1492 exit_status = status >> 8
1493 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1494 error (_ ("The error log is as follows:"))
1495 ly.stderr_write (error)
1496 ly.stderr_write (stderr.read ())
1499 if global_options.verbose:
1504 def system_in_directory (cmd, directory):
1505 """Execute a command in a different directory.
1507 Because of win32 compatibility, we can't simply use subprocess.
1510 current = os.getcwd()
1511 os.chdir (directory)
1512 ly.system(cmd, be_verbose=global_options.verbose,
1517 def process_snippets (cmd, snippets,
1518 format, lily_output_dir):
1519 """Run cmd on all of the .ly files from snippets."""
1524 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1525 cmd += ' --formats=png '
1526 elif format in (DOCBOOK) and '--formats' not in cmd:
1527 cmd += ' --formats=png,pdf '
1529 checksum = snippet_list_checksum (snippets)
1530 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1531 + [snip.basename() + '.ly' for snip in snippets])
1532 name = os.path.join (lily_output_dir,
1533 'snippet-names-%d.ly' % checksum)
1534 file (name, 'wb').write (contents)
1536 system_in_directory (' '.join ([cmd, name]),
1541 # Retrieve dimensions from LaTeX
1542 LATEX_INSPECTION_DOCUMENT = r'''
1546 \typeout{textwidth=\the\textwidth}
1547 \typeout{columnsep=\the\columnsep}
1548 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1552 # Do we need anything else besides `textwidth'?
1553 def get_latex_textwidth (source):
1554 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1556 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1558 ## what's a sensible default?
1561 preamble = source[:m.start (0)]
1562 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1564 (handle, tmpfile) = tempfile.mkstemp('.tex')
1565 logfile = os.path.splitext (tmpfile)[0] + '.log'
1566 logfile = os.path.split (logfile)[1]
1568 tmp_handle = os.fdopen (handle,'w')
1569 tmp_handle.write (latex_document)
1572 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1573 parameter_string = file (logfile).read()
1579 m = re.search ('columns=([0-9.]*)', parameter_string)
1581 columns = int (m.group (1))
1584 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1586 columnsep = float (m.group (1))
1589 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1591 textwidth = float (m.group (1))
1593 textwidth = (textwidth - columnsep) / columns
1597 def modify_preamble (chunk):
1598 str = chunk.replacement_text ()
1599 if (re.search (r"\\begin *{document}", str)
1600 and not re.search ("{graphic[sx]", str)):
1601 str = re.sub (r"\\begin{document}",
1602 r"\\usepackage{graphics}" + '\n'
1603 + r"\\begin{document}",
1605 chunk.override_text = str
1610 # TEXINFO: '.texinfo',
1616 class CompileError(Exception):
1619 def snippet_list_checksum (snippets):
1620 return hash (' '.join([l.basename() for l in snippets]))
1622 def write_file_map (lys, name):
1623 snippet_map = file (os.path.join (
1624 global_options.lily_output_dir,
1625 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1627 snippet_map.write ("""
1628 #(define version-seen #t)
1629 #(define output-empty-score-list #f)
1630 #(ly:add-file-name-alist '(%s
1632 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1635 def split_output_files(directory):
1636 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1638 Return value is a set of strings.
1641 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1642 base_subdir = os.path.split (subdir)[1]
1643 sub_files = [os.path.join (base_subdir, name)
1644 for name in os.listdir (subdir)]
1648 def do_process_cmd (chunks, input_name, options):
1649 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1651 output_files = split_output_files (options.lily_output_dir)
1652 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1654 write_file_map (outdated, input_name)
1655 progress (_ ("Writing snippets..."))
1656 for snippet in outdated:
1661 progress (_ ("Processing..."))
1663 process_snippets (options.process_cmd, outdated,
1664 options.format, options.lily_output_dir)
1667 progress (_ ("All snippets are up to date..."))
1669 if options.lily_output_dir != options.output_dir:
1670 output_files = split_output_files (options.lily_output_dir)
1671 for snippet in snippets:
1672 snippet.link_all_output_files (options.lily_output_dir,
1680 # Format guessing data
1689 '.texinfo': TEXINFO,
1694 def guess_format (input_filename):
1696 e = os.path.splitext (input_filename)[1]
1699 format = ext2format[e]
1701 error (_ ("cannot determine format for: %s"
1706 def write_if_updated (file_name, lines):
1708 f = file (file_name)
1710 new_str = ''.join (lines)
1711 if oldstr == new_str:
1712 progress (_ ("%s is up to date.") % file_name)
1715 # this prevents make from always rerunning lilypond-book:
1716 # output file must be touched in order to be up to date
1717 os.utime (file_name, None)
1721 progress (_ ("Writing `%s'...") % file_name)
1722 file (file_name, 'w').writelines (lines)
1726 def note_input_file (name, inputs=[]):
1727 ## hack: inputs is mutable!
1728 inputs.append (name)
1731 def samefile (f1, f2):
1733 return os.path.samefile (f1, f2)
1734 except AttributeError: # Windoze
1735 f1 = re.sub ("//*", "/", f1)
1736 f2 = re.sub ("//*", "/", f2)
1739 def do_file (input_filename):
1741 if not input_filename or input_filename == '-':
1742 in_handle = sys.stdin
1743 input_fullname = '<stdin>'
1745 if os.path.exists (input_filename):
1746 input_fullname = input_filename
1747 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1748 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1750 input_fullname = find_file (input_filename)
1752 note_input_file (input_fullname)
1753 in_handle = file (input_fullname)
1755 if input_filename == '-':
1756 input_base = 'stdin'
1758 input_base = os.path.basename (
1759 os.path.splitext (input_filename)[0])
1761 # don't complain when global_options.output_dir is existing
1762 if not global_options.output_dir:
1763 global_options.output_dir = os.getcwd()
1765 global_options.output_dir = os.path.abspath(global_options.output_dir)
1767 if not os.path.isdir (global_options.output_dir):
1768 os.mkdir (global_options.output_dir, 0777)
1769 os.chdir (global_options.output_dir)
1771 output_filename = os.path.join(global_options.output_dir,
1772 input_base + format2ext[global_options.format])
1773 if (os.path.exists (input_filename)
1774 and os.path.exists (output_filename)
1775 and samefile (output_filename, input_fullname)):
1777 _ ("Output would overwrite input file; use --output."))
1781 progress (_ ("Reading %s...") % input_fullname)
1782 source = in_handle.read ()
1785 set_default_options (source, default_ly_options, global_options.format)
1788 # FIXME: Containing blocks must be first, see
1789 # find_toplevel_snippets.
1791 'multiline_comment',
1795 'singleline_comment',
1800 progress (_ ("Dissecting..."))
1801 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1803 if global_options.format == LATEX:
1805 if (c.is_plain () and
1806 re.search (r"\\begin *{document}", c.replacement_text())):
1811 if global_options.filter_cmd:
1812 write_if_updated (output_filename,
1813 [c.filter_text () for c in chunks])
1814 elif global_options.process_cmd:
1815 do_process_cmd (chunks, input_fullname, global_options)
1816 progress (_ ("Compiling %s...") % output_filename)
1818 write_if_updated (output_filename,
1819 [s.replacement_text ()
1822 def process_include (snippet):
1823 os.chdir (original_dir)
1824 name = snippet.substring ('filename')
1825 progress (_ ("Processing include: %s") % name)
1827 return do_file (name)
1829 include_chunks = map (process_include,
1830 filter (lambda x: isinstance (x, IncludeSnippet),
1833 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1835 except CompileError:
1836 os.chdir (original_dir)
1837 progress (_ ("Removing `%s'") % output_filename)
1842 global global_options
1844 opt_parser = get_option_parser()
1845 (global_options, args) = opt_parser.parse_args ()
1846 if global_options.format in ('texi-html', 'texi'):
1847 global_options.format = TEXINFO
1849 global_options.include_path = map (os.path.abspath, global_options.include_path)
1851 if global_options.warranty:
1854 if not args or len (args) > 1:
1855 opt_parser.print_help ()
1861 # FIXME: 85 lines of `main' macramee??
1862 files = do_options ()
1864 basename = os.path.splitext (files[0])[0]
1865 basename = os.path.split (basename)[1]
1867 if not global_options.format:
1868 global_options.format = guess_format (files[0])
1871 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1874 if global_options.process_cmd == '':
1875 global_options.process_cmd = (lilypond_binary
1876 + ' --formats=%s -dbackend=eps ' % formats)
1878 if global_options.process_cmd:
1879 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1880 for p in global_options.include_path])
1882 if global_options.format in (TEXINFO, LATEX):
1883 ## prevent PDF from being switched on by default.
1884 global_options.process_cmd += ' --formats=eps '
1885 if global_options.create_pdf:
1886 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1888 if global_options.verbose:
1889 global_options.process_cmd += " --verbose "
1891 if global_options.padding_mm:
1892 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1894 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1896 if global_options.lily_output_dir:
1897 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1898 if not os.path.isdir (global_options.lily_output_dir):
1899 os.makedirs (global_options.lily_output_dir)
1901 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1906 chunks = do_file (files[0])
1907 except CompileError:
1910 inputs = note_input_file ('')
1913 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1914 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1915 final_output_file = os.path.join (global_options.output_dir,
1917 + '.%s' % global_options.format)
1919 os.chdir (original_dir)
1920 file (dep_file, 'w').write ('%s: %s'
1921 % (final_output_file, ' '.join (inputs)))
1923 if __name__ == '__main__':