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 ly.require_python_version ()
51 program_version = '@TOPLEVEL_VERSION@'
52 program_name = os.path.basename (sys.argv[0])
54 original_dir = os.getcwd ()
58 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
62 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
63 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
64 $ lilypond-book --process='lilypond -I include' %(BOOK)s
65 ''' % {'BOOK': _ ("BOOK")})
67 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
68 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
70 ################################################################
72 if global_options.verbose:
73 raise Exception (_ ('Exiting (%d)...') % i)
78 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
80 progress = ly.progress
83 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
86 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
88 def ps_page_count (ps_name):
89 header = file (ps_name).read (1024)
90 m = re.search ('\n%%Pages: ([0-9]+)', header)
92 return int (m.group (1))
97 ly.encoded_write (sys.stdout, '''
104 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
106 _ ("Distributed under terms of the GNU General Public License."),
107 _ ("It comes with NO WARRANTY.")))
109 def get_option_parser ():
110 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
111 description=help_summary,
112 add_help_option=False)
114 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
117 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
120 p.add_option ('-f', '--format',
121 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
122 metavar=_ ("FORMAT"),
125 p.add_option("-h", "--help",
127 help=_ ("show this help and exit"))
129 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
131 action='append', dest='include_path',
132 default=[os.path.abspath (os.getcwd ())])
134 p.add_option ('--info-images-dir',
135 help=_ ("format Texinfo output so that Info will "
136 "look for images of music in DIR"),
138 action='store', dest='info_images_dir',
141 p.add_option ('--latex-program',
142 help=_ ("run executable PROG instead of latex"),
144 action='store', dest='latex_program',
147 p.add_option ('--left-padding',
150 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
154 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
156 action='store', dest='output_dir',
159 p.add_option ('--skip-lily-check',
160 help=_ ("do not fail if no lilypond output is found"),
162 action='store_true', dest='skip_lilypond_run',
165 p.add_option ('--skip-png-check',
166 help=_ ("do not fail if no PNG images are found for EPS files"),
168 action='store_true', dest='skip_png_check',
171 p.add_option ('--lily-output-dir',
172 help=_ ("write lily-XXX files to DIR, link into --output dir"),
174 action='store', dest='lily_output_dir',
177 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
178 help = _ ("process ly_files using COMMAND FILE..."),
180 dest='process_cmd', default='')
182 p.add_option ('--pdf',
185 help=_ ("create PDF files for use with PDFTeX"),
188 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
193 p.version = "@TOPLEVEL_VERSION@"
194 p.add_option("--version",
196 help=_ ("show version number and exit"))
198 p.add_option ('-w', '--warranty',
199 help=_ ("show warranty and copyright"),
201 p.add_option_group ('',
203 _ ("Report bugs via")
204 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
207 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
209 # If we are called with full path, try to use lilypond binary
210 # installed in the same path; this is needed in GUB binaries, where
211 # @bindir is always different from the installed binary path.
212 if 'bindir' in globals () and bindir:
213 lilypond_binary = os.path.join (bindir, 'lilypond')
215 # Only use installed binary when we are installed too.
216 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
217 lilypond_binary = 'lilypond'
219 global_options = None
222 default_ly_options = { 'alt': "[image of music]" }
224 document_language = ''
227 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
229 ADDVERSION = 'addversion'
233 EXAMPLEINDENT = 'exampleindent'
235 FRAGMENT = 'fragment'
241 LINE_WIDTH = 'line-width'
242 LILYQUOTE = 'lilyquote'
243 NOFRAGMENT = 'nofragment'
244 NOINDENT = 'noindent'
246 NORAGGED_RIGHT = 'noragged-right'
250 OUTPUTIMAGE = 'outputimage'
253 PREAMBLE = 'preamble'
254 PRINTFILENAME = 'printfilename'
256 RAGGED_RIGHT = 'ragged-right'
257 RELATIVE = 'relative'
258 STAFFSIZE = 'staffsize'
259 DOCTITLE = 'doctitle'
262 VERBATIM = 'verbatim'
263 FONTLOAD = 'fontload'
264 FILENAME = 'filename'
268 # NOTIME has no opposite so it isn't part of this dictionary.
269 # NOQUOTE is used internally only.
271 NOFRAGMENT: FRAGMENT,
276 # Recognize special sequences in the input.
278 # (?P<name>regex) -- Assign result of REGEX to NAME.
279 # *? -- Match non-greedily.
280 # (?m) -- Multiline regex: Make ^ and $ match at each line.
281 # (?s) -- Make the dot match all characters including newline.
282 # (?x) -- Ignore whitespace in patterns.
293 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
298 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
303 <(?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>)''',
309 (?P<code><!--\s.*?!-->)
312 'singleline_comment':
331 (\s*(?P<options>.*?)\s*:)?\s*
339 \s*(?P<options>.*?)\s*
348 \s*(?P<options>.*?)\s*
350 \s*(?P<filename>.*?)\s*
357 (?P<code><!--\s.*?!-->)
360 'singleline_comment':
366 (?P<code><pre>.*?</pre>))''',
372 (?P<code><pre>\s.*?</pre>\s))''',
391 \s*(?P<options>.*?)\s*
402 \s*(?P<options>.*?)\s*
406 \\end\s*{lilypond})''',
414 \s*(?P<options>.*?)\s*
422 'singleline_comment':
445 \\end\s*{verbatim}))''',
454 (?P<filename>\S+))''',
458 ^[^\n]*?(?!@c\s+)[^\n]*?
462 \s*(?P<options>.*?)\s*
472 \s*(?P<options>.*?)\s*
475 ^@end\s+lilypond)\s''',
482 \s*(?P<options>.*?)\s*
493 @end\s+ignore))\s''',
495 'singleline_comment':
500 @c([ \t][^\n]*|)\n))''',
502 # Don't do this: It interferes with @code{@{}.
503 # 'verb': r'''(?P<code>@code{.*?})''',
511 @end\s+example\s))''',
520 'intertext': r',?\s*intertext=\".*?\"',
524 'intertext': r',?\s*intertext=\".*?\"',
529 'intertext': r',?\s*intertext=\".*?\"',
530 'option_sep': '\s*,\s*',
534 'intertext': r',?\s*intertext=\".*?\"',
535 'option_sep': '\s*,\s*',
539 # Options without a pattern in ly_options.
559 RELATIVE: r'''\relative c%(relative_quotes)s''',
564 INDENT: r'''indent = %(indent)s''',
566 LINE_WIDTH: r'''line-width = %(line-width)s''',
568 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
570 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
572 RAGGED_RIGHT: r'''ragged-right = ##t''',
574 NORAGGED_RIGHT: r'''ragged-right = ##f''',
576 PACKED: r'''packed = ##t''',
588 \remove "Time_signature_engraver"
594 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
601 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
604 <imageobject role="latex">
605 <imagedata fileref="%(base)s.pdf" format="PDF"/>
607 <imageobject role="html">
608 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
610 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
612 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
616 FILTER: r'''<lilypond %(options)s>
626 <a href="%(base)s.ly">''',
630 border="0" src="%(image)s" alt="%(alt)s">''',
632 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
634 QUOTE: r'''<blockquote>
647 \ifx\preLilyPondExample \undefined%%
650 \preLilyPondExample%%
652 \def\lilypondbook{}%%
653 \input %(base)s-systems.tex%%
654 \ifx\postLilyPondExample \undefined%%
657 \postLilyPondExample%%
661 PRINTFILENAME: '''\\texttt{%(filename)s}
664 QUOTE: r'''\begin{quotation}%(str)s
667 VERBATIM: r'''\noindent
668 \begin{verbatim}%(verb)s\end{verbatim}''',
670 FILTER: r'''\begin{lilypond}[%(options)s]
677 FILTER: r'''@lilypond[%(options)s]
683 @include %(base)s-systems.texi
687 OUTPUTIMAGE: r'''@noindent
689 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
693 <a href="%(base)s.ly">
695 border="0" src="%(image)s" alt="%(alt)s">
703 <a href="%(base)s.ly">
711 QUOTE: r'''@quotation
712 %(str)s@end quotation
719 VERBATIM: r'''@exampleindent 0
721 %(verb)s@end verbatim
724 ADDVERSION: r'''@example
725 \version @w{"@version{}"}
732 # Maintain line numbers.
737 for f in [HTML, LATEX]:
738 for s in (QUOTE, VERBATIM):
739 output[f][s] = output[f][s].replace("\n"," ")
742 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
743 %%%% Options: [%(option_string)s]
744 \\include "lilypond-book-preamble.ly"
747 %% ****************************************************************
748 %% Start cut-&-pastable-section
749 %% ****************************************************************
754 #(define dump-extents #t)
755 %(font_dump_setting)s
757 force-assignment = #""
758 line-width = #(- line-width (* mm %(padding_mm)f))
771 %% ****************************************************************
772 %% ly snippet contents follows:
773 %% ****************************************************************
777 %% ****************************************************************
779 %% ****************************************************************
786 %% ****************************************************************
788 %% ****************************************************************
792 %% ****************************************************************
794 %% ****************************************************************
797 texinfo_line_widths = {
798 '@afourpaper': '160\\mm',
799 '@afourwide': '6.5\\in',
800 '@afourlatex': '150\\mm',
801 '@smallbook': '5\\in',
802 '@letterpaper': '6\\in',
805 def classic_lilypond_book_compatibility (key, value):
806 if key == 'singleline' and value == None:
807 return (RAGGED_RIGHT, None)
809 m = re.search ('relative\s*([-0-9])', key)
811 return ('relative', m.group (1))
813 m = re.match ('([0-9]+)pt', key)
815 return ('staffsize', m.group (1))
817 if key == 'indent' or key == 'line-width':
818 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
820 f = float (m.group (1))
821 return (key, '%f\\%s' % (f, m.group (2)))
825 def find_file (name, raise_error=True):
826 for i in global_options.include_path:
827 full = os.path.join (i, name)
828 if os.path.exists (full):
832 error (_ ("file not found: %s") % name + '\n')
836 def verbatim_html (s):
837 return re.sub ('>', '>',
839 re.sub ('&', '&', s)))
841 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
842 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
843 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
844 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
846 def ly_comment_gettext (t, m):
847 return m.group (1) + t (m.group (2))
849 def verb_ly_gettext (s):
850 if not document_language:
853 t = langdefs.translation[document_language]
857 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
859 for v in ly_var_def_re.findall (s):
860 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
861 "\\1" + t (v) + "\\2",
863 for id in ly_context_id_re.findall (s):
864 s = re.sub (r'(\s+|")%s(\s+|")' % id,
865 "\\1" + t (id) + "\\2",
869 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
870 def set_default_options (source, default_ly_options, format):
871 global document_language
872 if LINE_WIDTH not in default_ly_options:
874 textwidth = get_latex_textwidth (source)
875 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
876 elif format == TEXINFO:
877 m = texinfo_lang_re.search (source)
878 if m and not m.group (1).startswith ('en'):
879 document_language = m.group (1)
881 document_language = ''
882 for regex in texinfo_line_widths:
883 # FIXME: @layout is usually not in
886 # \input texinfo @c -*-texinfo-*-
888 # Bluntly search first K items of
890 # s = chunks[0].replacement_text ()
891 if re.search (regex, source[:1024]):
892 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
896 def replacement_text (self):
899 def filter_text (self):
900 return self.replacement_text ()
905 class Substring (Chunk):
906 """A string that does not require extra memory."""
907 def __init__ (self, source, start, end, line_number):
911 self.line_number = line_number
912 self.override_text = None
917 def replacement_text (self):
918 if self.override_text:
919 return self.override_text
921 return self.source[self.start:self.end]
923 class Snippet (Chunk):
924 def __init__ (self, type, match, format, line_number):
928 self.option_dict = {}
930 self.line_number = line_number
932 def replacement_text (self):
933 return self.match.group ('match')
935 def substring (self, s):
936 return self.match.group (s)
939 return `self.__class__` + ' type = ' + self.type
941 class IncludeSnippet (Snippet):
942 def processed_filename (self):
943 f = self.substring ('filename')
944 return os.path.splitext (f)[0] + format2ext[self.format]
946 def replacement_text (self):
947 s = self.match.group ('match')
948 f = self.substring ('filename')
950 return re.sub (f, self.processed_filename (), s)
952 class LilypondSnippet (Snippet):
953 def __init__ (self, type, match, format, line_number):
954 Snippet.__init__ (self, type, match, format, line_number)
955 os = match.group ('options')
956 self.do_options (os, self.type)
959 return verb_ly_gettext (self.substring ('code'))
962 contents = self.substring ('code')
963 return ('\\sourcefileline %d\n%s'
964 % (self.line_number - 1, contents))
969 return self.compose_ly (s)
972 def split_options (self, option_string):
974 if self.format == HTML:
975 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
977 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
981 return re.split (format_res[self.format]['option_sep'],
985 def do_options (self, option_string, type):
986 self.option_dict = {}
988 options = self.split_options (option_string)
990 for option in options:
992 (key, value) = re.split ('\s*=\s*', option)
993 self.option_dict[key] = value
995 if option in no_options:
996 if no_options[option] in self.option_dict:
997 del self.option_dict[no_options[option]]
999 self.option_dict[option] = None
1001 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1002 no_line_width_value = 0
1004 # If LINE_WIDTH is used without parameter, set it to default.
1005 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1006 no_line_width_value = 1
1007 del self.option_dict[LINE_WIDTH]
1009 for k in default_ly_options:
1010 if k not in self.option_dict:
1011 self.option_dict[k] = default_ly_options[k]
1013 # RELATIVE does not work without FRAGMENT;
1014 # make RELATIVE imply FRAGMENT
1015 has_relative = self.option_dict.has_key (RELATIVE)
1016 if has_relative and not self.option_dict.has_key (FRAGMENT):
1017 self.option_dict[FRAGMENT] = None
1019 if not has_line_width:
1020 if type == 'lilypond' or FRAGMENT in self.option_dict:
1021 self.option_dict[RAGGED_RIGHT] = None
1023 if type == 'lilypond':
1024 if LINE_WIDTH in self.option_dict:
1025 del self.option_dict[LINE_WIDTH]
1027 if RAGGED_RIGHT in self.option_dict:
1028 if LINE_WIDTH in self.option_dict:
1029 del self.option_dict[LINE_WIDTH]
1031 if QUOTE in self.option_dict or type == 'lilypond':
1032 if LINE_WIDTH in self.option_dict:
1033 del self.option_dict[LINE_WIDTH]
1035 if not INDENT in self.option_dict:
1036 self.option_dict[INDENT] = '0\\mm'
1038 # The QUOTE pattern from ly_options only emits the `line-width'
1040 if has_line_width and QUOTE in self.option_dict:
1041 if no_line_width_value:
1042 del self.option_dict[LINE_WIDTH]
1044 del self.option_dict[QUOTE]
1046 def compose_ly (self, code):
1047 if FRAGMENT in self.option_dict:
1055 # The original concept of the `exampleindent' option is broken.
1056 # It is not possible to get a sane value for @exampleindent at all
1057 # without processing the document itself. Saying
1065 # causes ugly results with the DVI backend of texinfo since the
1066 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1067 # value). Executing the above code changes the environment
1068 # indentation to an unknown value because we don't know the amount
1069 # of 1em in advance since it is font-dependent. Modifying
1070 # @exampleindent in the middle of a document is simply not
1071 # supported within texinfo.
1073 # As a consequence, the only function of @exampleindent is now to
1074 # specify the amount of indentation for the `quote' option.
1076 # To set @exampleindent locally to zero, we use the @format
1077 # environment for non-quoted snippets.
1078 override[EXAMPLEINDENT] = r'0.4\in'
1079 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1080 override.update (default_ly_options)
1083 for (key, value) in self.option_dict.items ():
1085 option_list.append (key)
1087 option_list.append (key + '=' + value)
1088 option_string = ','.join (option_list)
1091 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1092 for a in compose_types:
1093 compose_dict[a] = []
1095 for (key, value) in self.option_dict.items ():
1096 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1100 _ ("deprecated ly-option used: %s=%s") % (key, value))
1102 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1105 _ ("deprecated ly-option used: %s") % key)
1107 _ ("compatibility mode translation: %s") % c_key)
1109 (key, value) = (c_key, c_value)
1112 override[key] = value
1114 if not override.has_key (key):
1115 override[key] = None
1118 for type in compose_types:
1119 if ly_options[type].has_key (key):
1120 compose_dict[type].append (ly_options[type][key])
1124 if not found and key not in simple_options:
1125 warning (_ ("ignoring unknown ly option: %s") % key)
1128 if RELATIVE in override and override[RELATIVE]:
1129 relative = int (override[RELATIVE])
1131 relative_quotes = ''
1135 relative_quotes += ',' * (- relative)
1137 relative_quotes += "'" * relative
1139 paper_string = '\n '.join (compose_dict[PAPER]) % override
1140 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1141 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1142 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1143 padding_mm = global_options.padding_mm
1144 font_dump_setting = ''
1145 if FONTLOAD in self.option_dict:
1146 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1148 d = globals().copy()
1150 return (PREAMBLE_LY + body) % d
1152 def get_checksum (self):
1153 if not self.checksum:
1154 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1156 ## let's not create too long names.
1157 self.checksum = hash.hexdigest ()[:10]
1159 return self.checksum
1161 def basename (self):
1162 cs = self.get_checksum ()
1163 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1166 def write_ly (self):
1167 base = self.basename ()
1168 path = os.path.join (global_options.lily_output_dir, base)
1169 directory = os.path.split(path)[0]
1170 if not os.path.isdir (directory):
1171 os.makedirs (directory)
1172 out = file (path + '.ly', 'w')
1173 out.write (self.full_ly ())
1174 file (path + '.txt', 'w').write ('image of music')
1176 def relevant_contents (self, ly):
1177 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1179 def link_all_output_files (self, output_dir, output_dir_files, destination):
1180 existing, missing = self.all_output_files (output_dir, output_dir_files)
1182 print '\nMissing', missing
1183 raise CompileError(self.basename())
1184 for name in existing:
1186 os.unlink (os.path.join (destination, name))
1190 src = os.path.join (output_dir, name)
1191 dst = os.path.join (destination, name)
1192 dst_path = os.path.split(dst)[0]
1193 if not os.path.isdir (dst_path):
1194 os.makedirs (dst_path)
1198 def all_output_files (self, output_dir, output_dir_files):
1199 """Return all files generated in lily_output_dir, a set.
1201 output_dir_files is the list of files in the output directory.
1205 base = self.basename()
1206 full = os.path.join (output_dir, base)
1207 def consider_file (name):
1208 if name in output_dir_files:
1211 def require_file (name):
1212 if name in output_dir_files:
1217 # UGH - junk global_options
1218 skip_lily = global_options.skip_lilypond_run
1219 for required in [base + '.ly',
1221 require_file (required)
1223 require_file (base + '-systems.count')
1225 if 'ddump-profile' in global_options.process_cmd:
1226 require_file (base + '.profile')
1227 if 'dseparate-log-file' in global_options.process_cmd:
1228 require_file (base + '.log')
1230 map (consider_file, [base + '.tex',
1234 base + '-systems.texi',
1235 base + '-systems.tex',
1236 base + '-systems.pdftexi'])
1237 if document_language:
1239 [base + '.texidoc' + document_language,
1240 base + '.doctitle' + document_language])
1242 # UGH - junk global_options
1243 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1244 and not global_options.skip_png_check):
1245 page_count = ps_page_count (full + '.eps')
1247 require_file (base + '.png')
1249 for page in range (1, page_count + 1):
1250 require_file (base + '-page%d.png' % page)
1253 if not skip_lily and not missing:
1254 system_count = int(file (full + '-systems.count').read())
1256 for number in range(1, system_count + 1):
1257 systemfile = '%s-%d' % (base, number)
1258 require_file (systemfile + '.eps')
1259 consider_file (systemfile + '.pdf')
1261 # We can't require signatures, since books and toplevel
1262 # markups do not output a signature.
1263 if 'ddump-signature' in global_options.process_cmd:
1264 consider_file (systemfile + '.signature')
1267 return (result, missing)
1269 def is_outdated (self, output_dir, current_files):
1270 found, missing = self.all_output_files (output_dir, current_files)
1273 def filter_text (self):
1274 """Run snippet bodies through a command (say: convert-ly).
1276 This functionality is rarely used, and this code must have bitrot.
1278 code = self.substring ('code')
1279 s = filter_pipe (code, global_options.filter_cmd)
1282 'options': self.match.group ('options')
1285 return output[self.format][FILTER] % d
1287 def replacement_text (self):
1288 func = LilypondSnippet.__dict__['output_' + self.format]
1291 def get_images (self):
1292 base = self.basename ()
1294 single = '%(base)s.png' % vars ()
1295 multiple = '%(base)s-page1.png' % vars ()
1297 if (os.path.exists (multiple)
1298 and (not os.path.exists (single)
1299 or (os.stat (multiple)[stat.ST_MTIME]
1300 > os.stat (single)[stat.ST_MTIME]))):
1301 count = ps_page_count ('%(base)s.eps' % vars ())
1302 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1303 images = tuple (images)
1307 def output_docbook (self):
1309 base = self.basename ()
1310 for image in self.get_images ():
1311 (base, ext) = os.path.splitext (image)
1312 str += output[DOCBOOK][OUTPUT] % vars ()
1313 str += self.output_print_filename (DOCBOOK)
1314 if (self.substring('inline') == 'inline'):
1315 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1317 str = '<mediaobject>' + str + '</mediaobject>'
1318 if VERBATIM in self.option_dict:
1319 verb = verbatim_html (self.verb_ly ())
1320 str = output[DOCBOOK][VERBATIM] % vars () + str
1323 def output_html (self):
1325 base = self.basename ()
1326 if self.format == HTML:
1327 str += self.output_print_filename (HTML)
1328 if VERBATIM in self.option_dict:
1329 verb = verbatim_html (self.verb_ly ())
1330 str += output[HTML][VERBATIM] % vars ()
1331 if QUOTE in self.option_dict:
1332 str = output[HTML][QUOTE] % vars ()
1334 str += output[HTML][BEFORE] % vars ()
1335 for image in self.get_images ():
1336 (base, ext) = os.path.splitext (image)
1337 alt = self.option_dict[ALT]
1338 str += output[HTML][OUTPUT] % vars ()
1339 str += output[HTML][AFTER] % vars ()
1342 def output_info (self):
1344 for image in self.get_images ():
1345 (base, ext) = os.path.splitext (image)
1347 # URG, makeinfo implicitly prepends dot to extension.
1348 # Specifying no extension is most robust.
1350 alt = self.option_dict[ALT]
1351 info_image_path = os.path.join (global_options.info_images_dir, base)
1352 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1354 base = self.basename ()
1355 str += output[self.format][OUTPUT] % vars ()
1358 def output_latex (self):
1360 base = self.basename ()
1361 if self.format == LATEX:
1362 str += self.output_print_filename (LATEX)
1363 if VERBATIM in self.option_dict:
1364 verb = self.verb_ly ()
1365 str += (output[LATEX][VERBATIM] % vars ())
1367 str += (output[LATEX][OUTPUT] % vars ())
1369 ## todo: maintain breaks
1371 breaks = self.ly ().count ("\n")
1372 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1374 if QUOTE in self.option_dict:
1375 str = output[LATEX][QUOTE] % vars ()
1378 def output_print_filename (self, format):
1380 if PRINTFILENAME in self.option_dict:
1381 base = self.basename ()
1382 filename = os.path.basename (self.substring ('filename'))
1383 str = output[format][PRINTFILENAME] % vars ()
1387 def output_texinfo (self):
1388 str = self.output_print_filename (TEXINFO)
1389 base = self.basename ()
1390 if DOCTITLE in self.option_dict:
1391 doctitle = base + '.doctitle'
1392 translated_doctitle = doctitle + document_language
1393 if os.path.exists (translated_doctitle):
1394 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1395 elif os.path.exists (doctitle):
1396 str += '@lydoctitle %s\n' % open (doctitle).read ()
1397 if TEXIDOC in self.option_dict:
1398 texidoc = base + '.texidoc'
1399 translated_texidoc = texidoc + document_language
1400 if os.path.exists (translated_texidoc):
1401 str += '@include %(translated_texidoc)s\n\n' % vars ()
1402 elif os.path.exists (texidoc):
1403 str += '@include %(texidoc)s\n\n' % vars ()
1406 if VERBATIM in self.option_dict:
1408 if ADDVERSION in self.option_dict:
1409 version = output[TEXINFO][ADDVERSION]
1410 verb = self.verb_ly ()
1411 substr = output[TEXINFO][VERBATIM] % vars ()
1412 substr += self.output_info ()
1413 if LILYQUOTE in self.option_dict:
1414 substr = output[TEXINFO][QUOTE] % {'str':substr}
1417 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1418 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1419 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1421 if QUOTE in self.option_dict:
1422 str = output[TEXINFO][QUOTE] % vars ()
1424 # need par after image
1429 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1430 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1432 class LilypondFileSnippet (LilypondSnippet):
1433 def __init__ (self, type, match, format, line_number):
1434 LilypondSnippet.__init__ (self, type, match, format, line_number)
1435 self.contents = file (find_file (self.substring ('filename'))).read ()
1439 s = re_begin_verbatim.split (s)[-1]
1440 s = re_end_verbatim.split (s)[0]
1441 return verb_ly_gettext (s)
1444 name = self.substring ('filename')
1445 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1446 % (name, self.contents))
1449 snippet_type_to_class = {
1450 'lilypond_file': LilypondFileSnippet,
1451 'lilypond_block': LilypondSnippet,
1452 'lilypond': LilypondSnippet,
1453 'include': IncludeSnippet,
1456 def find_linestarts (s):
1461 i = s.find ('\n', start)
1469 nls.append (len (s))
1472 def find_toplevel_snippets (input_string, format, types):
1475 res[t] = re.compile (snippet_res[format][t])
1479 found = dict ([(t, None) for t in types])
1481 line_starts = find_linestarts (input_string)
1483 # We want to search for multiple regexes, without searching
1484 # the string multiple times for one regex.
1485 # Hence, we use earlier results to limit the string portion
1487 # Since every part of the string is traversed at most once for
1488 # every type of snippet, this is linear.
1494 if not found[type] or found[type][0] < index:
1497 m = res[type].search (input_string[index:endex])
1502 if type in snippet_type_to_class:
1503 klass = snippet_type_to_class[type]
1505 start = index + m.start ('match')
1506 line_number = line_start_idx
1507 while (line_starts[line_number] < start):
1511 snip = klass (type, m, format, line_number)
1513 found[type] = (start, snip)
1517 or found[type][0] < found[first][0])):
1522 # Limiting the search space is a cute
1523 # idea, but this *requires* to search
1524 # for possible containing blocks
1525 # first, at least as long as we do not
1526 # search for the start of blocks, but
1527 # always/directly for the entire
1528 # @block ... @end block.
1530 endex = found[first][0]
1533 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1536 while (start > line_starts[line_start_idx+1]):
1539 (start, snip) = found[first]
1540 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1541 snippets.append (snip)
1543 index = start + len (snip.match.group ('match'))
1547 def filter_pipe (input, cmd):
1548 """Pass input through cmd, and return the result."""
1550 if global_options.verbose:
1551 progress (_ ("Opening filter `%s'") % cmd)
1553 (stdin, stdout, stderr) = os.popen3 (cmd)
1555 status = stdin.close ()
1559 output = stdout.read ()
1560 status = stdout.close ()
1561 error = stderr.read ()
1565 signal = 0x0f & status
1566 if status or (not output and error):
1567 exit_status = status >> 8
1568 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1569 error (_ ("The error log is as follows:"))
1570 ly.stderr_write (error)
1571 ly.stderr_write (stderr.read ())
1574 if global_options.verbose:
1579 def system_in_directory (cmd, directory):
1580 """Execute a command in a different directory.
1582 Because of win32 compatibility, we can't simply use subprocess.
1585 current = os.getcwd()
1586 os.chdir (directory)
1587 ly.system(cmd, be_verbose=global_options.verbose,
1592 def process_snippets (cmd, snippets,
1593 format, lily_output_dir):
1594 """Run cmd on all of the .ly files from snippets."""
1599 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1600 cmd += ' --formats=png '
1601 elif format in (DOCBOOK) and '--formats' not in cmd:
1602 cmd += ' --formats=png,pdf '
1604 checksum = snippet_list_checksum (snippets)
1605 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1606 + [snip.basename() + '.ly' for snip in snippets])
1607 name = os.path.join (lily_output_dir,
1608 'snippet-names-%d.ly' % checksum)
1609 file (name, 'wb').write (contents)
1611 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1616 # Retrieve dimensions from LaTeX
1617 LATEX_INSPECTION_DOCUMENT = r'''
1621 \typeout{textwidth=\the\textwidth}
1622 \typeout{columnsep=\the\columnsep}
1623 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1627 # Do we need anything else besides `textwidth'?
1628 def get_latex_textwidth (source):
1629 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1631 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1633 ## what's a sensible default?
1636 preamble = source[:m.start (0)]
1637 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1639 (handle, tmpfile) = tempfile.mkstemp('.tex')
1640 logfile = os.path.splitext (tmpfile)[0] + '.log'
1641 logfile = os.path.split (logfile)[1]
1643 tmp_handle = os.fdopen (handle,'w')
1644 tmp_handle.write (latex_document)
1647 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1648 be_verbose=global_options.verbose)
1649 parameter_string = file (logfile).read()
1655 m = re.search ('columns=([0-9.]*)', parameter_string)
1657 columns = int (m.group (1))
1660 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1662 columnsep = float (m.group (1))
1665 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1667 textwidth = float (m.group (1))
1669 textwidth = (textwidth - columnsep) / columns
1673 def modify_preamble (chunk):
1674 str = chunk.replacement_text ()
1675 if (re.search (r"\\begin *{document}", str)
1676 and not re.search ("{graphic[sx]", str)):
1677 str = re.sub (r"\\begin{document}",
1678 r"\\usepackage{graphics}" + '\n'
1679 + r"\\begin{document}",
1681 chunk.override_text = str
1686 # TEXINFO: '.texinfo',
1692 class CompileError(Exception):
1695 def snippet_list_checksum (snippets):
1696 return hash (' '.join([l.basename() for l in snippets]))
1698 def write_file_map (lys, name):
1699 snippet_map = file (os.path.join (
1700 global_options.lily_output_dir,
1701 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1703 snippet_map.write ("""
1704 #(define version-seen #t)
1705 #(define output-empty-score-list #f)
1706 #(ly:add-file-name-alist '(%s
1708 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1711 def split_output_files(directory):
1712 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1714 Return value is a set of strings.
1717 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1718 base_subdir = os.path.split (subdir)[1]
1719 sub_files = [os.path.join (base_subdir, name)
1720 for name in os.listdir (subdir)]
1724 def do_process_cmd (chunks, input_name, options):
1725 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1727 output_files = split_output_files (options.lily_output_dir)
1728 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1730 write_file_map (outdated, input_name)
1731 progress (_ ("Writing snippets..."))
1732 for snippet in outdated:
1737 progress (_ ("Processing..."))
1739 process_snippets (options.process_cmd, outdated,
1740 options.format, options.lily_output_dir)
1743 progress (_ ("All snippets are up to date..."))
1745 if options.lily_output_dir != options.output_dir:
1746 output_files = split_output_files (options.lily_output_dir)
1747 for snippet in snippets:
1748 snippet.link_all_output_files (options.lily_output_dir,
1756 # Format guessing data
1765 '.texinfo': TEXINFO,
1770 def guess_format (input_filename):
1772 e = os.path.splitext (input_filename)[1]
1775 format = ext2format[e]
1777 error (_ ("cannot determine format for: %s"
1782 def write_if_updated (file_name, lines):
1784 f = file (file_name)
1786 new_str = ''.join (lines)
1787 if oldstr == new_str:
1788 progress (_ ("%s is up to date.") % file_name)
1791 # this prevents make from always rerunning lilypond-book:
1792 # output file must be touched in order to be up to date
1793 os.utime (file_name, None)
1798 output_dir = os.path.dirname (file_name)
1799 if not os.path.exists (output_dir):
1800 os.makedirs (output_dir)
1802 progress (_ ("Writing `%s'...") % file_name)
1803 file (file_name, 'w').writelines (lines)
1807 def note_input_file (name, inputs=[]):
1808 ## hack: inputs is mutable!
1809 inputs.append (name)
1812 def samefile (f1, f2):
1814 return os.path.samefile (f1, f2)
1815 except AttributeError: # Windoze
1816 f1 = re.sub ("//*", "/", f1)
1817 f2 = re.sub ("//*", "/", f2)
1820 def do_file (input_filename, included=False):
1822 if not input_filename or input_filename == '-':
1823 in_handle = sys.stdin
1824 input_fullname = '<stdin>'
1826 if os.path.exists (input_filename):
1827 input_fullname = input_filename
1828 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1829 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1831 input_fullname = find_file (input_filename)
1833 note_input_file (input_fullname)
1834 in_handle = file (input_fullname)
1836 if input_filename == '-':
1837 input_base = 'stdin'
1839 input_base = os.path.splitext (input_filename)[0]
1841 input_base = os.path.basename (
1842 os.path.splitext (input_filename)[0])
1844 # don't complain when global_options.output_dir is existing
1845 if not global_options.output_dir:
1846 global_options.output_dir = os.getcwd()
1848 global_options.output_dir = os.path.abspath(global_options.output_dir)
1850 if not os.path.isdir (global_options.output_dir):
1851 os.mkdir (global_options.output_dir, 0777)
1852 os.chdir (global_options.output_dir)
1854 output_filename = os.path.join(global_options.output_dir,
1855 input_base + format2ext[global_options.format])
1856 if (os.path.exists (input_filename)
1857 and os.path.exists (output_filename)
1858 and samefile (output_filename, input_fullname)):
1860 _ ("Output would overwrite input file; use --output."))
1864 progress (_ ("Reading %s...") % input_fullname)
1865 source = in_handle.read ()
1868 set_default_options (source, default_ly_options, global_options.format)
1871 # FIXME: Containing blocks must be first, see
1872 # find_toplevel_snippets.
1874 'multiline_comment',
1878 'singleline_comment',
1883 progress (_ ("Dissecting..."))
1884 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1886 if global_options.format == LATEX:
1888 if (c.is_plain () and
1889 re.search (r"\\begin *{document}", c.replacement_text())):
1894 if global_options.filter_cmd:
1895 write_if_updated (output_filename,
1896 [c.filter_text () for c in chunks])
1897 elif global_options.process_cmd:
1898 do_process_cmd (chunks, input_fullname, global_options)
1899 progress (_ ("Compiling %s...") % output_filename)
1901 write_if_updated (output_filename,
1902 [s.replacement_text ()
1905 def process_include (snippet):
1906 os.chdir (original_dir)
1907 name = snippet.substring ('filename')
1908 progress (_ ("Processing include: %s") % name)
1910 return do_file (name, included=True)
1912 include_chunks = map (process_include,
1913 filter (lambda x: isinstance (x, IncludeSnippet),
1916 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1918 except CompileError:
1919 os.chdir (original_dir)
1920 progress (_ ("Removing `%s'") % output_filename)
1925 global global_options
1927 opt_parser = get_option_parser()
1928 (global_options, args) = opt_parser.parse_args ()
1929 if global_options.format in ('texi-html', 'texi'):
1930 global_options.format = TEXINFO
1932 global_options.include_path = map (os.path.abspath, global_options.include_path)
1934 if global_options.warranty:
1937 if not args or len (args) > 1:
1938 opt_parser.print_help ()
1944 # FIXME: 85 lines of `main' macramee??
1945 files = do_options ()
1947 basename = os.path.splitext (files[0])[0]
1948 basename = os.path.split (basename)[1]
1950 if not global_options.format:
1951 global_options.format = guess_format (files[0])
1954 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1957 if global_options.process_cmd == '':
1958 global_options.process_cmd = (lilypond_binary
1959 + ' --formats=%s -dbackend=eps ' % formats)
1961 if global_options.process_cmd:
1962 includes = global_options.include_path
1963 if global_options.lily_output_dir:
1964 # This must be first, so lilypond prefers to read .ly
1965 # files in the other lybookdb dir.
1966 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
1967 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
1970 if global_options.format in (TEXINFO, LATEX):
1971 ## prevent PDF from being switched on by default.
1972 global_options.process_cmd += ' --formats=eps '
1973 if global_options.create_pdf:
1974 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1976 if global_options.verbose:
1977 global_options.process_cmd += " --verbose "
1979 if global_options.padding_mm:
1980 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1982 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1984 if global_options.lily_output_dir:
1985 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1986 if not os.path.isdir (global_options.lily_output_dir):
1987 os.makedirs (global_options.lily_output_dir)
1989 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1994 chunks = do_file (files[0])
1995 except CompileError:
1998 inputs = note_input_file ('')
2001 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2002 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2003 final_output_file = os.path.join (global_options.output_dir,
2005 + '.%s' % global_options.format)
2007 os.chdir (original_dir)
2008 file (dep_file, 'w').write ('%s: %s'
2009 % (final_output_file, ' '.join (inputs)))
2011 if __name__ == '__main__':