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 ('--lily-output-dir',
150 help=_ ("write lily-XXX files to DIR, link into --output dir."),
152 action='store', dest='lily_output_dir',
155 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
156 help = _ ("process ly_files using COMMAND FILE..."),
158 dest='process_cmd', default='')
160 p.add_option ('--pdf',
163 help=_ ("create PDF files for use with PDFTeX"),
166 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
167 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
168 must use this with dvips -h INPUT.psfonts'''),
171 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
176 p.version = "@TOPLEVEL_VERSION@"
177 p.add_option("--version",
179 help=_ ("show version number and exit"))
181 p.add_option ('-w', '--warranty',
182 help=_ ("show warranty and copyright"),
184 p.add_option_group (ly.display_encode (_ ('Bugs')),
186 _ ("Report bugs via")
187 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
190 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
192 # Only use installed binary when we are installed too.
193 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
194 lilypond_binary = 'lilypond'
196 global_options = None
199 default_ly_options = { 'alt': "[image of music]" }
202 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
204 ADDVERSION = 'addversion'
208 EXAMPLEINDENT = 'exampleindent'
210 FRAGMENT = 'fragment'
216 LINE_WIDTH = 'line-width'
217 LILYQUOTE = 'lilyquote'
218 NOFRAGMENT = 'nofragment'
219 NOINDENT = 'noindent'
224 OUTPUTIMAGE = 'outputimage'
227 PREAMBLE = 'preamble'
228 PRINTFILENAME = 'printfilename'
230 RAGGED_RIGHT = 'ragged-right'
231 RELATIVE = 'relative'
232 STAFFSIZE = 'staffsize'
235 VERBATIM = 'verbatim'
236 FONTLOAD = 'fontload'
237 FILENAME = 'filename'
241 # NOTIME has no opposite so it isn't part of this dictionary.
242 # NOQUOTE is used internally only.
244 NOFRAGMENT: FRAGMENT,
249 # Recognize special sequences in the input.
251 # (?P<name>regex) -- Assign result of REGEX to NAME.
252 # *? -- Match non-greedily.
253 # (?m) -- Multiline regex: Make ^ and $ match at each line.
254 # (?s) -- Make the dot match all characters including newline.
255 # (?x) -- Ignore whitespace in patterns.
266 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
271 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
276 <(?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>)''',
282 (?P<code><!--\s.*?!-->)
285 'singleline_comment':
304 (\s*(?P<options>.*?)\s*:)?\s*
312 \s*(?P<options>.*?)\s*
321 \s*(?P<options>.*?)\s*
323 \s*(?P<filename>.*?)\s*
330 (?P<code><!--\s.*?!-->)
333 'singleline_comment':
339 (?P<code><pre>.*?</pre>))''',
345 (?P<code><pre>\s.*?</pre>\s))''',
364 \s*(?P<options>.*?)\s*
375 \s*(?P<options>.*?)\s*
379 \\end\s*{lilypond})''',
387 \s*(?P<options>.*?)\s*
395 'singleline_comment':
418 \\end\s*{verbatim}))''',
427 (?P<filename>\S+))''',
431 ^[^\n]*?(?!@c\s+)[^\n]*?
435 \s*(?P<options>.*?)\s*
445 \s*(?P<options>.*?)\s*
448 ^@end\s+lilypond)\s''',
455 \s*(?P<options>.*?)\s*
466 @end\s+ignore))\s''',
468 'singleline_comment':
473 @c([ \t][^\n]*|)\n))''',
475 # Don't do this: It interferes with @code{@{}.
476 # 'verb': r'''(?P<code>@code{.*?})''',
484 @end\s+example\s))''',
493 'intertext': r',?\s*intertext=\".*?\"',
497 'intertext': r',?\s*intertext=\".*?\"',
502 'intertext': r',?\s*intertext=\".*?\"',
503 'option_sep': '\s*,\s*',
507 'intertext': r',?\s*intertext=\".*?\"',
508 'option_sep': '\s*,\s*',
512 # Options without a pattern in ly_options.
531 RELATIVE: r'''\relative c%(relative_quotes)s''',
536 INDENT: r'''indent = %(indent)s''',
538 LINE_WIDTH: r'''line-width = %(line-width)s''',
540 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
542 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
544 RAGGED_RIGHT: r'''ragged-right = ##t''',
546 PACKED: r'''packed = ##t''',
558 \remove Time_signature_engraver
564 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
571 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
574 <imageobject role="latex">
575 <imagedata fileref="%(base)s.pdf" format="PDF"/>
577 <imageobject role="html">
578 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
580 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
582 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
586 FILTER: r'''<lilypond %(options)s>
596 <a href="%(base)s.ly">''',
600 border="0" src="%(image)s" alt="%(alt)s">''',
602 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
604 QUOTE: r'''<blockquote>
617 \ifx\preLilyPondExample \undefined%%
620 \preLilyPondExample%%
622 \def\lilypondbook{}%%
623 \input %(base)s-systems.tex%%
624 \ifx\postLilyPondExample \undefined%%
627 \postLilyPondExample%%
631 PRINTFILENAME: '''\\texttt{%(filename)s}
634 QUOTE: r'''\begin{quotation}%(str)s
637 VERBATIM: r'''\noindent
638 \begin{verbatim}%(verb)s\end{verbatim}''',
640 FILTER: r'''\begin{lilypond}[%(options)s]
647 FILTER: r'''@lilypond[%(options)s]
653 @include %(base)s-systems.texi
657 OUTPUTIMAGE: r'''@noindent
659 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
663 <a href="%(base)s.ly">
665 border="0" src="%(image)s" alt="%(alt)s">
673 <a href="%(base)s.ly">
681 QUOTE: r'''@quotation
682 %(str)s@end quotation
689 VERBATIM: r'''@exampleindent 0
691 %(verb)s@end verbatim
694 ADDVERSION: r'''@example
695 \version @w{"@version{}"}
702 # Maintain line numbers.
707 for f in [HTML, LATEX]:
708 for s in (QUOTE, VERBATIM):
709 output[f][s] = output[f][s].replace("\n"," ")
712 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
713 %%%% Options: [%(option_string)s]
714 \\include "lilypond-book-preamble.ly"
717 %% ****************************************************************
718 %% Start cut-&-pastable-section
719 %% ****************************************************************
724 #(define dump-extents #t)
725 %(font_dump_setting)s
727 force-assignment = #""
728 line-width = #(- line-width (* mm %(padding_mm)f))
741 %% ****************************************************************
742 %% ly snippet contents follows:
743 %% ****************************************************************
747 %% ****************************************************************
749 %% ****************************************************************
756 %% ****************************************************************
758 %% ****************************************************************
762 %% ****************************************************************
764 %% ****************************************************************
767 texinfo_line_widths = {
768 '@afourpaper': '160\\mm',
769 '@afourwide': '6.5\\in',
770 '@afourlatex': '150\\mm',
771 '@smallbook': '5\\in',
772 '@letterpaper': '6\\in',
775 def classic_lilypond_book_compatibility (key, value):
776 if key == 'singleline' and value == None:
777 return (RAGGED_RIGHT, None)
779 m = re.search ('relative\s*([-0-9])', key)
781 return ('relative', m.group (1))
783 m = re.match ('([0-9]+)pt', key)
785 return ('staffsize', m.group (1))
787 if key == 'indent' or key == 'line-width':
788 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
790 f = float (m.group (1))
791 return (key, '%f\\%s' % (f, m.group (2)))
795 def find_file (name, raise_error=True):
796 for i in global_options.include_path:
797 full = os.path.join (i, name)
798 if os.path.exists (full):
802 error (_ ("file not found: %s") % name + '\n')
806 def verbatim_html (s):
807 return re.sub ('>', '>',
809 re.sub ('&', '&', s)))
812 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
813 def set_default_options (source, default_ly_options, format):
814 if LINE_WIDTH not in default_ly_options:
816 textwidth = get_latex_textwidth (source)
817 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
818 elif format == TEXINFO:
819 m = texinfo_lang_re.search (source)
820 if m and not m.group (1).startswith ('en'):
821 default_ly_options[LANG] = m.group (1)
823 default_ly_options[LANG] = ''
824 for regex in texinfo_line_widths:
825 # FIXME: @layout is usually not in
828 # \input texinfo @c -*-texinfo-*-
830 # Bluntly search first K items of
832 # s = chunks[0].replacement_text ()
833 if re.search (regex, source[:1024]):
834 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
838 def replacement_text (self):
841 def filter_text (self):
842 return self.replacement_text ()
847 class Substring (Chunk):
848 """A string that does not require extra memory."""
849 def __init__ (self, source, start, end, line_number):
853 self.line_number = line_number
854 self.override_text = None
859 def replacement_text (self):
860 if self.override_text:
861 return self.override_text
863 return self.source[self.start:self.end]
865 class Snippet (Chunk):
866 def __init__ (self, type, match, format, line_number):
870 self.option_dict = {}
872 self.line_number = line_number
874 def replacement_text (self):
875 return self.match.group ('match')
877 def substring (self, s):
878 return self.match.group (s)
881 return `self.__class__` + ' type = ' + self.type
883 class IncludeSnippet (Snippet):
884 def processed_filename (self):
885 f = self.substring ('filename')
886 return os.path.splitext (f)[0] + format2ext[self.format]
888 def replacement_text (self):
889 s = self.match.group ('match')
890 f = self.substring ('filename')
892 return re.sub (f, self.processed_filename (), s)
894 class LilypondSnippet (Snippet):
895 def __init__ (self, type, match, format, line_number):
896 Snippet.__init__ (self, type, match, format, line_number)
897 os = match.group ('options')
898 self.do_options (os, self.type)
901 return self.substring ('code')
904 contents = self.substring ('code')
905 return ('\\sourcefileline %d\n%s'
906 % (self.line_number - 1, contents))
911 return self.compose_ly (s)
914 def split_options (self, option_string):
916 if self.format == HTML:
917 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
919 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
923 return re.split (format_res[self.format]['option_sep'],
927 def do_options (self, option_string, type):
928 self.option_dict = {}
930 options = self.split_options (option_string)
932 for option in options:
934 (key, value) = re.split ('\s*=\s*', option)
935 self.option_dict[key] = value
937 if option in no_options:
938 if no_options[option] in self.option_dict:
939 del self.option_dict[no_options[option]]
941 self.option_dict[option] = None
943 has_line_width = self.option_dict.has_key (LINE_WIDTH)
944 no_line_width_value = 0
946 # If LINE_WIDTH is used without parameter, set it to default.
947 if has_line_width and self.option_dict[LINE_WIDTH] == None:
948 no_line_width_value = 1
949 del self.option_dict[LINE_WIDTH]
951 for k in default_ly_options:
952 if k not in self.option_dict:
953 self.option_dict[k] = default_ly_options[k]
955 if not has_line_width:
956 if type == 'lilypond' or FRAGMENT in self.option_dict:
957 self.option_dict[RAGGED_RIGHT] = None
959 if type == 'lilypond':
960 if LINE_WIDTH in self.option_dict:
961 del self.option_dict[LINE_WIDTH]
963 if RAGGED_RIGHT in self.option_dict:
964 if LINE_WIDTH in self.option_dict:
965 del self.option_dict[LINE_WIDTH]
967 if QUOTE in self.option_dict or type == 'lilypond':
968 if LINE_WIDTH in self.option_dict:
969 del self.option_dict[LINE_WIDTH]
971 if not INDENT in self.option_dict:
972 self.option_dict[INDENT] = '0\\mm'
974 # The QUOTE pattern from ly_options only emits the `line-width'
976 if has_line_width and QUOTE in self.option_dict:
977 if no_line_width_value:
978 del self.option_dict[LINE_WIDTH]
980 del self.option_dict[QUOTE]
982 def compose_ly (self, code):
983 if FRAGMENT in self.option_dict:
991 # The original concept of the `exampleindent' option is broken.
992 # It is not possible to get a sane value for @exampleindent at all
993 # without processing the document itself. Saying
1001 # causes ugly results with the DVI backend of texinfo since the
1002 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1003 # value). Executing the above code changes the environment
1004 # indentation to an unknown value because we don't know the amount
1005 # of 1em in advance since it is font-dependent. Modifying
1006 # @exampleindent in the middle of a document is simply not
1007 # supported within texinfo.
1009 # As a consequence, the only function of @exampleindent is now to
1010 # specify the amount of indentation for the `quote' option.
1012 # To set @exampleindent locally to zero, we use the @format
1013 # environment for non-quoted snippets.
1014 override[EXAMPLEINDENT] = r'0.4\in'
1015 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1016 override.update (default_ly_options)
1019 for (key, value) in self.option_dict.items ():
1021 option_list.append (key)
1023 option_list.append (key + '=' + value)
1024 option_string = ','.join (option_list)
1027 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1028 for a in compose_types:
1029 compose_dict[a] = []
1031 for (key, value) in self.option_dict.items ():
1032 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1036 _ ("deprecated ly-option used: %s=%s") % (key, value))
1038 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1041 _ ("deprecated ly-option used: %s") % key)
1043 _ ("compatibility mode translation: %s") % c_key)
1045 (key, value) = (c_key, c_value)
1048 override[key] = value
1050 if not override.has_key (key):
1051 override[key] = None
1054 for type in compose_types:
1055 if ly_options[type].has_key (key):
1056 compose_dict[type].append (ly_options[type][key])
1060 if not found and key not in simple_options:
1061 warning (_ ("ignoring unknown ly option: %s") % key)
1064 if RELATIVE in override and override[RELATIVE]:
1065 relative = int (override[RELATIVE])
1067 relative_quotes = ''
1071 relative_quotes += ',' * (- relative)
1073 relative_quotes += "'" * relative
1075 paper_string = '\n '.join (compose_dict[PAPER]) % override
1076 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1077 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1078 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1079 padding_mm = global_options.padding_mm
1080 font_dump_setting = ''
1081 if FONTLOAD in self.option_dict:
1082 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1084 d = globals().copy()
1086 return (PREAMBLE_LY + body) % d
1088 def get_checksum (self):
1089 if not self.checksum:
1090 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1092 ## let's not create too long names.
1093 self.checksum = hash.hexdigest ()[:10]
1095 return self.checksum
1097 def basename (self):
1098 if FILENAME in self.option_dict:
1099 return self.option_dict[FILENAME]
1101 cs = self.get_checksum ()
1103 # TODO: use xx/xxxxx directory layout.
1104 name = 'lily-%s' % cs[:10]
1107 def write_ly (self):
1108 base = self.basename ()
1109 path = os.path.join (global_options.lily_output_dir, base)
1111 out = file (path + '.ly', 'w')
1112 out.write (self.full_ly ())
1113 file (path + '.txt', 'w').write ('image of music')
1115 def relevant_contents (self, ly):
1116 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1118 def link_all_output_files (self, output_dir, output_dir_files, destination):
1119 existing = self.all_output_files (output_dir, output_dir_files)
1120 for name in existing:
1122 os.unlink (os.path.join (destination, name))
1126 src = os.path.join (output_dir, name)
1127 dst = os.path.join (destination, name)
1131 def all_output_files (self, output_dir, output_dir_files):
1132 """Return all files generated in lily_output_dir, a set.
1134 output_dir_files is the list of files in the output directory.
1136 class Missing(Exception):
1140 base = self.basename()
1141 full = os.path.join (output_dir, base)
1142 def consider_file (name):
1143 if name in output_dir_files:
1146 def require_file (name):
1147 if name not in output_dir_files:
1152 for required in [base + '.ly',
1154 base + '-systems.count']:
1155 require_file (required)
1157 map (consider_file, [base + '.tex',
1160 base + '-systems.texi',
1161 base + '-systems.tex',
1162 base + '-systems.pdftexi'])
1164 if base + '.eps' in result and self.format in (HTML, TEXINFO):
1165 page_count = ps_page_count (full + '.eps')
1167 require_file (base + '.png')
1169 for page in range (1, page_count + 1):
1170 require_file (base + '-page%d.png' % page)
1172 system_count = int(file (full + '-systems.count').read())
1173 for number in range(1, system_count + 1):
1174 systemfile = '%s-%d' % (base, number)
1175 require_file (systemfile + '.eps')
1176 consider_file (systemfile + '.pdf')
1182 def is_outdated (self, output_dir, current_files):
1183 return self.all_output_files (output_dir, current_files) is None
1185 def filter_text (self):
1186 """Run snippet bodies through a command (say: convert-ly).
1188 This functionality is rarely used, and this code must have bitrot.
1191 code = self.substring ('code')
1192 s = filter_pipe (code, global_options.filter_cmd)
1195 'options': self.match.group ('options')
1198 return output[self.format][FILTER] % d
1200 def replacement_text (self):
1201 func = LilypondSnippet.__dict__['output_' + self.format]
1204 def get_images (self):
1205 base = self.basename ()
1207 single = '%(base)s.png' % vars ()
1208 multiple = '%(base)s-page1.png' % vars ()
1210 if (os.path.exists (multiple)
1211 and (not os.path.exists (single)
1212 or (os.stat (multiple)[stat.ST_MTIME]
1213 > os.stat (single)[stat.ST_MTIME]))):
1214 count = ps_page_count ('%(base)s.eps' % vars ())
1215 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1216 images = tuple (images)
1220 def output_docbook (self):
1222 base = self.basename ()
1223 for image in self.get_images ():
1224 (base, ext) = os.path.splitext (image)
1225 str += output[DOCBOOK][OUTPUT] % vars ()
1226 str += self.output_print_filename (DOCBOOK)
1227 if (self.substring('inline') == 'inline'):
1228 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1230 str = '<mediaobject>' + str + '</mediaobject>'
1231 if VERBATIM in self.option_dict:
1232 verb = verbatim_html (self.verb_ly ())
1233 str = output[DOCBOOK][VERBATIM] % vars () + str
1236 def output_html (self):
1238 base = self.basename ()
1239 if self.format == HTML:
1240 str += self.output_print_filename (HTML)
1241 if VERBATIM in self.option_dict:
1242 verb = verbatim_html (self.verb_ly ())
1243 str += output[HTML][VERBATIM] % vars ()
1244 if QUOTE in self.option_dict:
1245 str = output[HTML][QUOTE] % vars ()
1247 str += output[HTML][BEFORE] % vars ()
1248 for image in self.get_images ():
1249 (base, ext) = os.path.splitext (image)
1250 alt = self.option_dict[ALT]
1251 str += output[HTML][OUTPUT] % vars ()
1252 str += output[HTML][AFTER] % vars ()
1255 def output_info (self):
1257 for image in self.get_images ():
1258 (base, ext) = os.path.splitext (image)
1260 # URG, makeinfo implicitly prepends dot to extension.
1261 # Specifying no extension is most robust.
1263 alt = self.option_dict[ALT]
1264 info_image_path = os.path.join (global_options.info_images_dir, base)
1265 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1267 base = self.basename ()
1268 str += output[self.format][OUTPUT] % vars ()
1271 def output_latex (self):
1273 base = self.basename ()
1274 if self.format == LATEX:
1275 str += self.output_print_filename (LATEX)
1276 if VERBATIM in self.option_dict:
1277 verb = self.verb_ly ()
1278 str += (output[LATEX][VERBATIM] % vars ())
1280 str += (output[LATEX][OUTPUT] % vars ())
1282 ## todo: maintain breaks
1284 breaks = self.ly ().count ("\n")
1285 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1287 if QUOTE in self.option_dict:
1288 str = output[LATEX][QUOTE] % vars ()
1291 def output_print_filename (self, format):
1293 if PRINTFILENAME in self.option_dict:
1294 base = self.basename ()
1295 filename = os.path.basename (self.substring ('filename'))
1296 str = output[format][PRINTFILENAME] % vars ()
1300 def output_texinfo (self):
1301 str = self.output_print_filename (TEXINFO)
1302 base = self.basename ()
1303 if TEXIDOC in self.option_dict:
1304 texidoc = base + '.texidoc'
1305 translated_texidoc = texidoc + default_ly_options[LANG]
1306 if os.path.exists (translated_texidoc):
1307 str += '@include %(translated_texidoc)s\n\n' % vars ()
1308 elif os.path.exists (texidoc):
1309 str += '@include %(texidoc)s\n\n' % vars ()
1312 if VERBATIM in self.option_dict:
1314 if ADDVERSION in self.option_dict:
1315 version = output[TEXINFO][ADDVERSION]
1316 verb = self.verb_ly ()
1317 substr = output[TEXINFO][VERBATIM] % vars ()
1318 substr += self.output_info ()
1319 if LILYQUOTE in self.option_dict:
1320 substr = output[TEXINFO][QUOTE] % {'str':substr}
1323 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1324 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1325 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1327 if QUOTE in self.option_dict:
1328 str = output[TEXINFO][QUOTE] % vars ()
1330 # need par after image
1335 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1336 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1338 class LilypondFileSnippet (LilypondSnippet):
1339 def __init__ (self, type, match, format, line_number):
1340 LilypondSnippet.__init__ (self, type, match, format, line_number)
1341 self.contents = file (find_file (self.substring ('filename'))).read ()
1345 s = re_begin_verbatim.split (s)[-1]
1346 s = re_end_verbatim.split (s)[0]
1350 name = self.substring ('filename')
1351 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1352 % (name, self.contents))
1355 snippet_type_to_class = {
1356 'lilypond_file': LilypondFileSnippet,
1357 'lilypond_block': LilypondSnippet,
1358 'lilypond': LilypondSnippet,
1359 'include': IncludeSnippet,
1362 def find_linestarts (s):
1367 i = s.find ('\n', start)
1375 nls.append (len (s))
1378 def find_toplevel_snippets (input_string, format, types):
1381 res[t] = ly.re.compile (snippet_res[format][t])
1385 found = dict ([(t, None) for t in types])
1387 line_starts = find_linestarts (input_string)
1389 # We want to search for multiple regexes, without searching
1390 # the string multiple times for one regex.
1391 # Hence, we use earlier results to limit the string portion
1393 # Since every part of the string is traversed at most once for
1394 # every type of snippet, this is linear.
1400 if not found[type] or found[type][0] < index:
1403 m = res[type].search (input_string[index:endex])
1408 if type in snippet_type_to_class:
1409 klass = snippet_type_to_class[type]
1411 start = index + m.start ('match')
1412 line_number = line_start_idx
1413 while (line_starts[line_number] < start):
1417 snip = klass (type, m, format, line_number)
1419 found[type] = (start, snip)
1423 or found[type][0] < found[first][0])):
1428 # Limiting the search space is a cute
1429 # idea, but this *requires* to search
1430 # for possible containing blocks
1431 # first, at least as long as we do not
1432 # search for the start of blocks, but
1433 # always/directly for the entire
1434 # @block ... @end block.
1436 endex = found[first][0]
1439 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1442 while (start > line_starts[line_start_idx+1]):
1445 (start, snip) = found[first]
1446 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1447 snippets.append (snip)
1449 index = start + len (snip.match.group ('match'))
1453 def filter_pipe (input, cmd):
1454 """Pass input through cmd, and return the result."""
1456 if global_options.verbose:
1457 progress (_ ("Opening filter `%s'") % cmd)
1459 (stdin, stdout, stderr) = os.popen3 (cmd)
1461 status = stdin.close ()
1465 output = stdout.read ()
1466 status = stdout.close ()
1467 error = stderr.read ()
1471 signal = 0x0f & status
1472 if status or (not output and error):
1473 exit_status = status >> 8
1474 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1475 error (_ ("The error log is as follows:"))
1476 ly.stderr_write (error)
1477 ly.stderr_write (stderr.read ())
1480 if global_options.verbose:
1485 def system_in_directory (cmd, directory):
1486 """Execute a command in a different directory.
1488 Because of win32 compatibility, we can't simply use subprocess.
1491 current = os.getcwd()
1492 os.chdir (directory)
1493 ly.system(cmd, be_verbose=global_options.verbose,
1498 def process_snippets (cmd, snippets,
1499 format, lily_output_dir):
1500 """Run cmd on all of the .ly files from snippets."""
1505 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1506 cmd += ' --formats=png '
1507 elif format in (DOCBOOK) and '--formats' not in cmd:
1508 cmd += ' --formats=png,pdf '
1510 checksum = snippet_list_checksum (snippets)
1511 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1512 + [snip.basename() for snip in snippets])
1513 name = os.path.join (lily_output_dir,
1514 'snippet-names-%d' % checksum)
1515 file (name, 'wb').write (contents)
1517 system_in_directory (' '.join ([cmd, name]),
1522 # Retrieve dimensions from LaTeX
1523 LATEX_INSPECTION_DOCUMENT = r'''
1527 \typeout{textwidth=\the\textwidth}
1528 \typeout{columnsep=\the\columnsep}
1529 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1533 # Do we need anything else besides `textwidth'?
1534 def get_latex_textwidth (source):
1535 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1537 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1539 ## what's a sensible default?
1542 preamble = source[:m.start (0)]
1543 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1545 (handle, tmpfile) = tempfile.mkstemp('.tex')
1546 logfile = os.path.splitext (tmpfile)[0] + '.log'
1547 logfile = os.path.split (logfile)[1]
1549 tmp_handle = os.fdopen (handle,'w')
1550 tmp_handle.write (latex_document)
1553 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1554 parameter_string = file (logfile).read()
1560 m = re.search ('columns=([0-9.]*)', parameter_string)
1562 columns = int (m.group (1))
1565 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1567 columnsep = float (m.group (1))
1570 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1572 textwidth = float (m.group (1))
1574 textwidth = (textwidth - columnsep) / columns
1578 def modify_preamble (chunk):
1579 str = chunk.replacement_text ()
1580 if (re.search (r"\\begin *{document}", str)
1581 and not re.search ("{graphic[sx]", str)):
1582 str = re.sub (r"\\begin{document}",
1583 r"\\usepackage{graphics}" + '\n'
1584 + r"\\begin{document}",
1586 chunk.override_text = str
1591 # TEXINFO: '.texinfo',
1597 class CompileError(Exception):
1600 def snippet_list_checksum (snippets):
1601 return hash (' '.join([l.basename() for l in snippets]))
1603 def write_file_map (lys, name):
1604 snippet_map = file (os.path.join (
1605 global_options.lily_output_dir,
1606 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1608 snippet_map.write ("""
1609 #(define version-seen #t)
1610 #(define output-empty-score-list #f)
1611 #(ly:add-file-name-alist '(%s
1613 """ % '\n'.join('("%s.ly" . "%s")\n' % (ly.basename (), name)
1616 def do_process_cmd (chunks, input_name, options):
1617 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1620 output_files = set(os.listdir(options.lily_output_dir))
1621 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1623 write_file_map (outdated, input_name)
1624 progress (_ ("Writing snippets..."))
1625 for snippet in outdated:
1630 progress (_ ("Processing..."))
1632 process_snippets (options.process_cmd, outdated,
1633 options.format, options.lily_output_dir)
1636 progress (_ ("All snippets are up to date..."))
1638 if options.lily_output_dir != options.output_dir:
1639 output_files = set(os.listdir(options.lily_output_dir))
1640 for snippet in snippets:
1641 snippet.link_all_output_files (options.lily_output_dir,
1649 # Format guessing data
1658 '.texinfo': TEXINFO,
1663 def guess_format (input_filename):
1665 e = os.path.splitext (input_filename)[1]
1668 format = ext2format[e]
1670 error (_ ("cannot determine format for: %s"
1675 def write_if_updated (file_name, lines):
1677 f = file (file_name)
1679 new_str = ''.join (lines)
1680 if oldstr == new_str:
1681 progress (_ ("%s is up to date.") % file_name)
1684 # this prevents make from always rerunning lilypond-book:
1685 # output file must be touched in order to be up to date
1686 os.utime (file_name, None)
1690 progress (_ ("Writing `%s'...") % file_name)
1691 file (file_name, 'w').writelines (lines)
1695 def note_input_file (name, inputs=[]):
1696 ## hack: inputs is mutable!
1697 inputs.append (name)
1700 def samefile (f1, f2):
1702 return os.path.samefile (f1, f2)
1703 except AttributeError: # Windoze
1704 f1 = re.sub ("//*", "/", f1)
1705 f2 = re.sub ("//*", "/", f2)
1708 def do_file (input_filename):
1710 if not input_filename or input_filename == '-':
1711 in_handle = sys.stdin
1712 input_fullname = '<stdin>'
1714 if os.path.exists (input_filename):
1715 input_fullname = input_filename
1716 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1717 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1719 input_fullname = find_file (input_filename)
1721 note_input_file (input_fullname)
1722 in_handle = file (input_fullname)
1724 if input_filename == '-':
1725 input_base = 'stdin'
1727 input_base = os.path.basename (
1728 os.path.splitext (input_filename)[0])
1730 # don't complain when global_options.output_dir is existing
1731 if not global_options.output_dir:
1732 global_options.output_dir = os.getcwd()
1734 global_options.output_dir = os.path.abspath(global_options.output_dir)
1736 if not os.path.isdir (global_options.output_dir):
1737 os.mkdir (global_options.output_dir, 0777)
1738 os.chdir (global_options.output_dir)
1740 output_filename = os.path.join(global_options.output_dir,
1741 input_base + format2ext[global_options.format])
1742 if (os.path.exists (input_filename)
1743 and os.path.exists (output_filename)
1744 and samefile (output_filename, input_fullname)):
1746 _ ("Output would overwrite input file; use --output."))
1750 progress (_ ("Reading %s...") % input_fullname)
1751 source = in_handle.read ()
1754 set_default_options (source, default_ly_options, global_options.format)
1757 # FIXME: Containing blocks must be first, see
1758 # find_toplevel_snippets.
1760 'multiline_comment',
1764 'singleline_comment',
1769 progress (_ ("Dissecting..."))
1770 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1772 if global_options.format == LATEX:
1774 if (c.is_plain () and
1775 re.search (r"\\begin *{document}", c.replacement_text())):
1780 if global_options.filter_cmd:
1781 write_if_updated (output_filename,
1782 [c.filter_text () for c in chunks])
1783 elif global_options.process_cmd:
1784 do_process_cmd (chunks, input_fullname, global_options)
1785 progress (_ ("Compiling %s...") % output_filename)
1787 write_if_updated (output_filename,
1788 [s.replacement_text ()
1791 def process_include (snippet):
1792 os.chdir (original_dir)
1793 name = snippet.substring ('filename')
1794 progress (_ ("Processing include: %s") % name)
1796 return do_file (name)
1798 include_chunks = map (process_include,
1799 filter (lambda x: isinstance (x, IncludeSnippet),
1802 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1804 except CompileError:
1805 os.chdir (original_dir)
1806 progress (_ ("Removing `%s'") % output_filename)
1811 global global_options
1813 opt_parser = get_option_parser()
1814 (global_options, args) = opt_parser.parse_args ()
1815 if global_options.format in ('texi-html', 'texi'):
1816 global_options.format = TEXINFO
1818 global_options.include_path = map (os.path.abspath, global_options.include_path)
1820 if global_options.warranty:
1823 if not args or len (args) > 1:
1824 opt_parser.print_help ()
1830 # FIXME: 85 lines of `main' macramee??
1831 files = do_options ()
1833 basename = os.path.splitext (files[0])[0]
1834 basename = os.path.split (basename)[1]
1836 if not global_options.format:
1837 global_options.format = guess_format (files[0])
1840 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1843 if global_options.process_cmd == '':
1844 global_options.process_cmd = (lilypond_binary
1845 + ' --formats=%s -dbackend=eps ' % formats)
1847 if global_options.process_cmd:
1848 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1849 for p in global_options.include_path])
1851 if global_options.format in (TEXINFO, LATEX):
1852 ## prevent PDF from being switched on by default.
1853 global_options.process_cmd += ' --formats=eps '
1854 if global_options.create_pdf:
1855 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1857 if global_options.verbose:
1858 global_options.process_cmd += " --verbose "
1860 if global_options.padding_mm:
1861 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1863 global_options.process_cmd += " -dread-file-list "
1865 if global_options.lily_output_dir:
1866 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1867 if not os.path.isdir (global_options.lily_output_dir):
1868 os.makedirs (global_options.lily_output_dir)
1870 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1875 chunks = do_file (files[0])
1876 except CompileError:
1879 inputs = note_input_file ('')
1882 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1883 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1884 final_output_file = os.path.join (global_options.output_dir,
1886 + '.%s' % global_options.format)
1888 os.chdir (original_dir)
1889 file (dep_file, 'w').write ('%s: %s'
1890 % (final_output_file, ' '.join (inputs)))
1892 if __name__ == '__main__':