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
45 for d in ['@lilypond_datadir@',
47 sys.path.insert (0, os.path.join (d, 'python'))
49 # dynamic relocation, for GUB binaries.
50 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
52 os.environ['PATH'] = bindir + os.pathsep + os.environ['PATH']
53 for p in ['share', 'lib']:
54 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
55 sys.path.insert (0, datadir)
64 program_version = '@TOPLEVEL_VERSION@'
65 program_name = os.path.basename (sys.argv[0])
67 original_dir = os.getcwd ()
71 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
75 lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
76 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
77 lilypond-book --process='lilypond -I include' %(BOOK)s
78 ''' % {'BOOK': _ ("BOOK")})
80 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
81 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
83 ################################################################
85 if global_options.verbose:
86 raise _ ('Exiting (%d)...') % i
91 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
97 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
100 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
102 def ps_page_count (ps_name):
103 header = open (ps_name).read (1024)
104 m = re.search ('\n%%Pages: ([0-9]+)', header)
106 return string.atoi (m.group (1))
111 sys.stdout.write ('''
118 ''' % ( _ ('Copyright (c) %s by') % '2001--2006',
120 _ ("Distributed under terms of the GNU General Public License."),
121 _ ("It comes with NO WARRANTY.")))
123 def get_option_parser ():
124 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
125 version="@TOPLEVEL_VERSION@",
126 description=help_summary)
128 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
131 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
133 p.add_option ('-f', '--format',
134 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
137 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
139 action='append', dest='include_path',
140 default=[os.path.abspath (os.getcwd ())])
142 p.add_option ('--left-padding',
145 help="Pad left side of music to align music inspite of uneven bar numbers. (in mm)",
149 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
151 action='store', dest='output_name',
154 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
155 help = _ ("process ly_files using COMMAND FILE..."),
157 dest='process_cmd', default='lilypond -b eps')
158 p.add_option ('--pdf',
161 help=_ ("Create PDF files for use with PDFTeX"),
163 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
164 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
165 must use this with dvips -h INPUT.psfonts'''),
167 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
171 p.add_option ('-w', '--warranty',
172 help=_ ("show warranty and copyright"),
174 p.add_option_group ('bugs',
175 description=(_ ("Report bugs via")
176 + ''' http://post.gmane.org/post.php'''
177 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
180 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
182 # Only use installed binary when we are installed too.
183 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
184 lilypond_binary = 'lilypond'
186 global_options = None
189 default_ly_options = { 'alt': "[image of music]" }
192 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
197 EXAMPLEINDENT = 'exampleindent'
199 FRAGMENT = 'fragment'
204 LINE_WIDTH = 'line-width'
205 NOFRAGMENT = 'nofragment'
206 NOINDENT = 'noindent'
211 OUTPUTIMAGE = 'outputimage'
214 PREAMBLE = 'preamble'
215 PRINTFILENAME = 'printfilename'
217 RAGGED_RIGHT = 'ragged-right'
218 RELATIVE = 'relative'
219 STAFFSIZE = 'staffsize'
222 VERBATIM = 'verbatim'
223 FONTLOAD = 'fontload'
224 FILENAME = 'filename'
228 # NOTIME has no opposite so it isn't part of this dictionary.
229 # NOQUOTE is used internally only.
231 NOFRAGMENT: FRAGMENT,
236 # Recognize special sequences in the input.
238 # (?P<name>regex) -- Assign result of REGEX to NAME.
239 # *? -- Match non-greedily.
240 # (?m) -- Multiline regex: Make ^ and $ match at each line.
241 # (?s) -- Make the dot match all characters including newline.
242 # (?x) -- Ignore whitespace in patterns.
253 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
258 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
263 <(?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>)''',
269 (?P<code><!--\s.*?!-->)
272 'singleline_comment':
291 (\s*(?P<options>.*?)\s*:)?\s*
299 \s*(?P<options>.*?)\s*
308 \s*(?P<options>.*?)\s*
310 \s*(?P<filename>.*?)\s*
317 (?P<code><!--\s.*?!-->)
320 'singleline_comment':
326 (?P<code><pre>.*?</pre>))''',
332 (?P<code><pre>\s.*?</pre>\s))''',
351 \s*(?P<options>.*?)\s*
362 \s*(?P<options>.*?)\s*
366 \\end\s*{lilypond})''',
374 \s*(?P<options>.*?)\s*
382 'singleline_comment':
405 \\end\s*{verbatim}))''',
414 (?P<filename>\S+))''',
418 ^[^\n]*?(?!@c\s+)[^\n]*?
422 \s*(?P<options>.*?)\s*
432 \s*(?P<options>.*?)\s*
435 ^@end\s+lilypond)\s''',
442 \s*(?P<options>.*?)\s*
453 @end\s+ignore))\s''',
455 'singleline_comment':
460 @c([ \t][^\n]*|)\n))''',
462 # Don't do this: It interferes with @code{@{}.
463 # 'verb': r'''(?P<code>@code{.*?})''',
471 @end\s+example\s))''',
480 'intertext': r',?\s*intertext=\".*?\"',
484 'intertext': r',?\s*intertext=\".*?\"',
489 'intertext': r',?\s*intertext=\".*?\"',
490 'option_sep': '\s*,\s*',
494 'intertext': r',?\s*intertext=\".*?\"',
495 'option_sep': '\s*,\s*',
499 # Options without a pattern in ly_options.
516 RELATIVE: r'''\relative c%(relative_quotes)s''',
521 INDENT: r'''indent = %(indent)s''',
523 LINE_WIDTH: r'''line-width = %(line-width)s''',
525 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
527 RAGGED_RIGHT: r'''ragged-right = ##t''',
529 PACKED: r'''packed = ##t''',
541 \remove Time_signature_engraver
547 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
554 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
557 <imageobject role="latex">
558 <imagedata fileref="%(base)s.pdf" format="PDF"/>
560 <imageobject role="html">
561 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
563 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
565 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
569 FILTER: r'''<lilypond %(options)s>
579 <a href="%(base)s.ly">''',
582 <img align="center" valign="center"
583 border="0" src="%(image)s" alt="%(alt)s">''',
585 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
587 QUOTE: r'''<blockquote>
600 \ifx\preLilyPondExample \undefined%%
603 \preLilyPondExample%%
605 \def\lilypondbook{}%%
606 \input %(base)s-systems.tex%%
607 \ifx\postLilyPondExample \undefined%%
610 \postLilyPondExample%%
614 PRINTFILENAME: '''\\texttt{%(filename)s}
617 QUOTE: r'''\begin{quotation}%(str)s
620 VERBATIM: r'''\noindent
621 \begin{verbatim}%(verb)s\end{verbatim}''',
623 FILTER: r'''\begin{lilypond}[%(options)s]
630 FILTER: r'''@lilypond[%(options)s]
636 @include %(base)s-systems.texi
640 OUTPUTIMAGE: r'''@noindent
642 @image{%(base)s,,,%(alt)s,%(ext)s}
646 <a href="%(base)s.ly">
647 <img align="center" valign="center"
648 border="0" src="%(image)s" alt="%(alt)s">
656 <a href="%(base)s.ly">
664 QUOTE: r'''@quotation
665 %(str)s@end quotation
672 VERBATIM: r'''@exampleindent 0
674 %(verb)s@end verbatim
680 # Maintain line numbers.
685 for f in [HTML, LATEX]:
686 for s in (QUOTE, VERBATIM):
687 output[f][s] = output[f][s].replace("\n"," ")
690 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
691 %%%% Options: [%(option_string)s]
692 \\include "lilypond-book-preamble.ly"
700 %% ****************************************************************
701 %% Start cut-&-pastable-section
702 %% ****************************************************************
705 #(define dump-extents #t)
706 %(font_dump_setting)s
708 force-assignment = #""
709 line-width = #(- line-width (* mm %(padding_mm)f))
722 %% ****************************************************************
723 %% ly snippet contents follows:
724 %% ****************************************************************
728 %% ****************************************************************
730 %% ****************************************************************
737 %% ****************************************************************
739 %% ****************************************************************
743 %% ****************************************************************
745 %% ****************************************************************
748 texinfo_line_widths = {
749 '@afourpaper': '160\\mm',
750 '@afourwide': '6.5\\in',
751 '@afourlatex': '150\\mm',
752 '@smallbook': '5\\in',
753 '@letterpaper': '6\\in',
756 def classic_lilypond_book_compatibility (key, value):
757 if key == 'singleline' and value == None:
758 return (RAGGED_RIGHT, None)
760 m = re.search ('relative\s*([-0-9])', key)
762 return ('relative', m.group (1))
764 m = re.match ('([0-9]+)pt', key)
766 return ('staffsize', m.group (1))
768 if key == 'indent' or key == 'line-width':
769 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
771 f = float (m.group (1))
772 return (key, '%f\\%s' % (f, m.group (2)))
776 def find_file (name):
777 for i in global_options.include_path:
778 full = os.path.join (i, name)
779 if os.path.exists (full):
782 error (_ ("file not found: %s") % name + '\n')
786 def verbatim_html (s):
787 return re.sub ('>', '>',
789 re.sub ('&', '&', s)))
791 def split_options (option_string):
793 if global_options.format == HTML:
794 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
795 for i in range(len(options)):
796 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
799 return re.split (format_res[global_options.format]['option_sep'],
803 def set_default_options (source):
804 global default_ly_options
805 if not default_ly_options.has_key (LINE_WIDTH):
806 if global_options.format == LATEX:
807 textwidth = get_latex_textwidth (source)
808 default_ly_options[LINE_WIDTH] = \
809 '''%.0f\\pt''' % textwidth
810 elif global_options.format == TEXINFO:
811 for (k, v) in texinfo_line_widths.items ():
812 # FIXME: @layout is usually not in
815 # \input texinfo @c -*-texinfo-*-
817 # Bluntly search first K items of
819 # s = chunks[0].replacement_text ()
820 if re.search (k, source[:1024]):
821 default_ly_options[LINE_WIDTH] = v
825 def replacement_text (self):
828 def filter_text (self):
829 return self.replacement_text ()
831 def ly_is_outdated (self):
834 def png_is_outdated (self):
840 class Substring (Chunk):
841 def __init__ (self, source, start, end, line_number):
845 self.line_number = line_number
846 self.override_text = None
851 def replacement_text (self):
852 if self.override_text:
853 return self.override_text
855 return self.source[self.start:self.end]
857 class Snippet (Chunk):
858 def __init__ (self, type, match, format, line_number):
862 self.option_dict = {}
864 self.line_number = line_number
866 def replacement_text (self):
867 return self.match.group ('match')
869 def substring (self, s):
870 return self.match.group (s)
873 return `self.__class__` + ' type = ' + self.type
875 class Include_snippet (Snippet):
876 def processed_filename (self):
877 f = self.substring ('filename')
878 return os.path.splitext (f)[0] + format2ext[global_options.format]
880 def replacement_text (self):
881 s = self.match.group ('match')
882 f = self.substring ('filename')
884 return re.sub (f, self.processed_filename (), s)
886 class Lilypond_snippet (Snippet):
887 def __init__ (self, type, match, format, line_number):
888 Snippet.__init__ (self, type, match, format, line_number)
889 os = match.group ('options')
890 self.do_options (os, self.type)
893 contents = self.substring ('code')
894 return ('\\sourcefileline %d\n%s'
895 % (self.line_number - 1, contents))
900 return self.compose_ly (s)
903 def do_options (self, option_string, type):
904 self.option_dict = {}
906 options = split_options (option_string)
910 (key, value) = re.split ('\s*=\s*', i)
911 self.option_dict[key] = value
913 if i in no_options.keys ():
914 if no_options[i] in self.option_dict.keys ():
915 del self.option_dict[no_options[i]]
917 self.option_dict[i] = None
919 has_line_width = self.option_dict.has_key (LINE_WIDTH)
920 no_line_width_value = 0
922 # If LINE_WIDTH is used without parameter, set it to default.
923 if has_line_width and self.option_dict[LINE_WIDTH] == None:
924 no_line_width_value = 1
925 del self.option_dict[LINE_WIDTH]
927 for i in default_ly_options.keys ():
928 if i not in self.option_dict.keys ():
929 self.option_dict[i] = default_ly_options[i]
931 if not has_line_width:
932 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
933 self.option_dict[RAGGED_RIGHT] = None
935 if type == 'lilypond':
936 if LINE_WIDTH in self.option_dict.keys ():
937 del self.option_dict[LINE_WIDTH]
939 if RAGGED_RIGHT in self.option_dict.keys ():
940 if LINE_WIDTH in self.option_dict.keys ():
941 del self.option_dict[LINE_WIDTH]
943 if QUOTE in self.option_dict.keys () or type == 'lilypond':
944 if LINE_WIDTH in self.option_dict.keys ():
945 del self.option_dict[LINE_WIDTH]
947 if not INDENT in self.option_dict.keys ():
948 self.option_dict[INDENT] = '0\\mm'
950 # The QUOTE pattern from ly_options only emits the `line-width'
952 if has_line_width and QUOTE in self.option_dict.keys ():
953 if no_line_width_value:
954 del self.option_dict[LINE_WIDTH]
956 del self.option_dict[QUOTE]
958 def compose_ly (self, code):
959 if FRAGMENT in self.option_dict.keys ():
967 # The original concept of the `exampleindent' option is broken.
968 # It is not possible to get a sane value for @exampleindent at all
969 # without processing the document itself. Saying
977 # causes ugly results with the DVI backend of texinfo since the
978 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
979 # value). Executing the above code changes the environment
980 # indentation to an unknown value because we don't know the amount
981 # of 1em in advance since it is font-dependent. Modifying
982 # @exampleindent in the middle of a document is simply not
983 # supported within texinfo.
985 # As a consequence, the only function of @exampleindent is now to
986 # specify the amount of indentation for the `quote' option.
988 # To set @exampleindent locally to zero, we use the @format
989 # environment for non-quoted snippets.
990 override[EXAMPLEINDENT] = r'0.4\in'
991 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
992 override.update (default_ly_options)
995 for (key, value) in self.option_dict.items ():
997 option_list.append (key)
999 option_list.append (key + '=' + value)
1000 option_string = string.join (option_list, ',')
1003 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1004 for a in compose_types:
1005 compose_dict[a] = []
1007 for (key, value) in self.option_dict.items ():
1008 (c_key, c_value) = \
1009 classic_lilypond_book_compatibility (key, value)
1013 (_ ("deprecated ly-option used: %s=%s" \
1016 (_ ("compatibility mode translation: %s=%s" \
1017 % (c_key, c_value)))
1020 (_ ("deprecated ly-option used: %s" \
1023 (_ ("compatibility mode translation: %s" \
1026 (key, value) = (c_key, c_value)
1029 override[key] = value
1031 if not override.has_key (key):
1032 override[key] = None
1035 for type in compose_types:
1036 if ly_options[type].has_key (key):
1037 compose_dict[type].append (ly_options[type][key])
1041 if not found and key not in simple_options:
1042 warning (_ ("ignoring unknown ly option: %s") % key)
1045 if RELATIVE in override.keys () and override[RELATIVE]:
1046 relative = int (override[RELATIVE])
1048 relative_quotes = ''
1052 relative_quotes += ',' * (- relative)
1054 relative_quotes += "'" * relative
1056 paper_string = string.join (compose_dict[PAPER],
1058 layout_string = string.join (compose_dict[LAYOUT],
1060 notes_string = string.join (compose_dict[NOTES],
1062 preamble_string = string.join (compose_dict[PREAMBLE],
1064 padding_mm = global_options.padding_mm
1065 font_dump_setting = ''
1066 if FONTLOAD in self.option_dict:
1067 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1069 d = globals().copy()
1071 return (PREAMBLE_LY + body) % d
1073 def get_hash (self):
1075 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1077 ## let's not create too long names.
1078 self.hash = hash.hexdigest ()[:10]
1082 def basename (self):
1083 if FILENAME in self.option_dict:
1084 return self.option_dict[FILENAME]
1085 if global_options.use_hash:
1086 return 'lily-%s' % self.get_hash ()
1089 def write_ly (self):
1090 outf = open (self.basename () + '.ly', 'w')
1091 outf.write (self.full_ly ())
1092 open (self.basename () + '.txt', 'w').write ('image of music')
1094 def relevant_contents (self, ly):
1095 return re.sub (r'\\(version|sourcefileline)[^\n]*\n', '', ly)
1097 def ly_is_outdated (self):
1098 base = self.basename ()
1099 ly_file = base + '.ly'
1100 tex_file = base + '.tex'
1101 eps_file = base + '.eps'
1102 systems_file = base + '-systems.tex'
1104 if (os.path.exists (ly_file)
1105 and os.path.exists (systems_file)
1106 and os.stat (systems_file)[stat.ST_SIZE]
1107 and re.match ('% eof', open (systems_file).readlines ()[-1])
1108 and (global_options.use_hash or FILENAME in self.option_dict)
1109 and (self.relevant_contents (self.full_ly ())
1110 == self.relevant_contents (open (ly_file).read ()))):
1115 def png_is_outdated (self):
1116 base = self.basename ()
1117 # FIXME: refactor stupid OK stuff
1118 ok = not self.ly_is_outdated ()
1119 if global_options.format in (HTML, TEXINFO):
1120 ok = ok and os.path.exists (base + '.eps')
1124 page_count = ps_page_count (base + '.eps')
1127 ok = ok and os.path.exists (base + '.png')
1129 elif page_count > 1:
1130 for a in range (1, page_count + 1):
1131 ok = ok and os.path.exists (base + '-page%d.png' % a)
1135 def texstr_is_outdated (self):
1139 # FIXME: refactor stupid OK stuff
1140 base = self.basename ()
1141 ok = self.ly_is_outdated ()
1142 ok = ok and (os.path.exists (base + '.texstr'))
1145 def filter_text (self):
1146 code = self.substring ('code')
1147 s = run_filter (code)
1150 'options': self.match.group ('options')
1153 return output[self.format][FILTER] % d
1155 def replacement_text (self):
1156 func = Lilypond_snippet.__dict__['output_' + self.format]
1159 def get_images (self):
1160 base = self.basename ()
1162 single = '%(base)s.png' % vars ()
1163 multiple = '%(base)s-page1.png' % vars ()
1165 if os.path.exists (multiple) \
1166 and (not os.path.exists (single) \
1167 or (os.stat (multiple)[stat.ST_MTIME] \
1168 > os.stat (single)[stat.ST_MTIME])):
1169 count = ps_page_count ('%(base)s.eps' % vars ())
1170 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1171 images = tuple (images)
1174 def output_docbook (self):
1176 base = self.basename ()
1177 for image in self.get_images ():
1178 (base, ext) = os.path.splitext (image)
1179 str += output[DOCBOOK][OUTPUT] % vars ()
1180 str += self.output_print_filename (DOCBOOK)
1181 if (self.substring('inline') == 'inline'):
1182 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1184 str = '<mediaobject>' + str + '</mediaobject>'
1185 if VERBATIM in self.option_dict:
1186 verb = verbatim_html (self.substring ('code'))
1187 str = output[DOCBOOK][VERBATIM] % vars () + str
1190 def output_html (self):
1192 base = self.basename ()
1193 if global_options.format == HTML:
1194 str += self.output_print_filename (HTML)
1195 if VERBATIM in self.option_dict:
1196 verb = verbatim_html (self.substring ('code'))
1197 str += output[HTML][VERBATIM] % vars ()
1198 if QUOTE in self.option_dict:
1199 str = output[HTML][QUOTE] % vars ()
1201 str += output[HTML][BEFORE] % vars ()
1202 for image in self.get_images ():
1203 (base, ext) = os.path.splitext (image)
1204 alt = self.option_dict[ALT]
1205 str += output[HTML][OUTPUT] % vars ()
1206 str += output[HTML][AFTER] % vars ()
1209 def output_info (self):
1211 for image in self.get_images ():
1212 (base, ext) = os.path.splitext (image)
1214 # URG, makeinfo implicitly prepends dot to extension.
1215 # Specifying no extension is most robust.
1217 alt = self.option_dict[ALT]
1218 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1220 base = self.basename ()
1221 str += output[global_options.format][OUTPUT] % vars ()
1224 def output_latex (self):
1226 base = self.basename ()
1227 if global_options.format == LATEX:
1228 str += self.output_print_filename (LATEX)
1229 if VERBATIM in self.option_dict:
1230 verb = self.substring ('code')
1231 str += (output[LATEX][VERBATIM] % vars ())
1233 str += (output[LATEX][OUTPUT] % vars ())
1235 ## todo: maintain breaks
1237 breaks = self.ly ().count ("\n")
1238 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1240 if QUOTE in self.option_dict:
1241 str = output[LATEX][QUOTE] % vars ()
1244 def output_print_filename (self, format):
1246 if PRINTFILENAME in self.option_dict:
1247 base = self.basename ()
1248 filename = self.substring ('filename')
1249 str = output[global_options.format][PRINTFILENAME] % vars ()
1253 def output_texinfo (self):
1255 if self.output_print_filename (TEXINFO):
1257 + self.output_print_filename (HTML)
1260 + self.output_print_filename (LATEX)
1262 base = self.basename ()
1263 if TEXIDOC in self.option_dict:
1264 texidoc = base + '.texidoc'
1265 if os.path.exists (texidoc):
1266 str += '@include %(texidoc)s\n\n' % vars ()
1268 if VERBATIM in self.option_dict:
1269 verb = self.substring ('code')
1270 str += (output[TEXINFO][VERBATIM] % vars ())
1271 if not QUOTE in self.option_dict:
1272 str = output[TEXINFO][NOQUOTE] % vars ()
1274 str += self.output_info ()
1276 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1277 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1278 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1280 if QUOTE in self.option_dict:
1281 str = output[TEXINFO][QUOTE] % vars ()
1283 # need par after image
1288 class Lilypond_file_snippet (Lilypond_snippet):
1290 name = self.substring ('filename')
1291 contents = open (find_file (name)).read ()
1292 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1295 snippet_type_to_class = {
1296 'lilypond_file': Lilypond_file_snippet,
1297 'lilypond_block': Lilypond_snippet,
1298 'lilypond': Lilypond_snippet,
1299 'include': Include_snippet,
1302 def find_linestarts (s):
1307 i = s.find ('\n', start)
1315 nls.append (len (s))
1318 def find_toplevel_snippets (s, types):
1321 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1325 found = dict ([(t, None) for t in types])
1327 line_starts = find_linestarts (s)
1329 # We want to search for multiple regexes, without searching
1330 # the string multiple times for one regex.
1331 # Hence, we use earlier results to limit the string portion
1333 # Since every part of the string is traversed at most once for
1334 # every type of snippet, this is linear.
1340 if not found[type] or found[type][0] < index:
1343 m = res[type].search (s[index:endex])
1348 if snippet_type_to_class.has_key (type):
1349 cl = snippet_type_to_class[type]
1352 start = index + m.start ('match')
1353 line_number = line_start_idx
1354 while (line_starts[line_number] < start):
1358 snip = cl (type, m, global_options.format, line_number)
1360 found[type] = (start, snip)
1364 or found[type][0] < found[first][0]):
1369 # Limiting the search space is a cute
1370 # idea, but this *requires* to search
1371 # for possible containing blocks
1372 # first, at least as long as we do not
1373 # search for the start of blocks, but
1374 # always/directly for the entire
1375 # @block ... @end block.
1377 endex = found[first][0]
1380 snippets.append (Substring (s, index, len (s), line_start_idx))
1383 while (start > line_starts[line_start_idx+1]):
1386 (start, snip) = found[first]
1387 snippets.append (Substring (s, index, start, line_start_idx + 1))
1388 snippets.append (snip)
1390 index = start + len (snip.match.group ('match'))
1394 def filter_pipe (input, cmd):
1395 if global_options.verbose:
1396 progress (_ ("Opening filter `%s'") % cmd)
1398 (stdin, stdout, stderr) = os.popen3 (cmd)
1400 status = stdin.close ()
1404 output = stdout.read ()
1405 status = stdout.close ()
1406 error = stderr.read ()
1410 signal = 0x0f & status
1411 if status or (not output and error):
1412 exit_status = status >> 8
1413 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1414 error (_ ("The error log is as follows:"))
1415 sys.stderr.write (error)
1416 sys.stderr.write (stderr.read ())
1419 if global_options.verbose:
1425 return filter_pipe (s, global_options.filter_cmd)
1427 def is_derived_class (cl, baseclass):
1430 for b in cl.__bases__:
1431 if is_derived_class (b, baseclass):
1435 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1436 ly_names = filter (lambda x: x,
1437 map (Lilypond_snippet.basename, ly_snippets))
1438 texstr_names = filter (lambda x: x,
1439 map (Lilypond_snippet.basename, texstr_snippets))
1441 png_names = filter (lambda x: x,
1442 map (Lilypond_snippet.basename, png_snippets))
1445 def my_system (cmd):
1446 status = ly.system (cmd,
1447 be_verbose=global_options.verbose,
1450 if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1451 cmd += ' --formats=png '
1452 elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1453 cmd += ' --formats=png,pdf '
1457 # the --process=CMD switch is a bad idea
1458 # it is too generic for lilypond-book.
1460 my_system (string.join ([cmd, '--backend texstr',
1461 'snippet-map.ly'] + texstr_names))
1462 for l in texstr_names:
1463 my_system ('latex %s.texstr' % l)
1466 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1469 my_system (string.join ([cmd, 'snippet-names']))
1472 LATEX_INSPECTION_DOCUMENT = r'''
1476 \typeout{textwidth=\the\textwidth}
1477 \typeout{columnsep=\the\columnsep}
1478 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1482 # Do we need anything else besides `textwidth'?
1483 def get_latex_textwidth (source):
1484 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1486 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1488 ## what's a sensible default?
1491 preamble = source[:m.start (0)]
1492 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1494 (handle, tmpfile) = tempfile.mkstemp('.tex')
1495 logfile = os.path.splitext (tmpfile)[0] + '.log'
1496 logfile = os.path.split (logfile)[1]
1498 tmp_handle = os.fdopen (handle,'w')
1499 tmp_handle.write (latex_document)
1502 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1503 parameter_string = open (logfile).read()
1509 m = re.search ('columns=([0-9.]*)', parameter_string)
1511 columns = int (m.group (1))
1514 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1516 columnsep = float (m.group (1))
1519 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1521 textwidth = float (m.group (1))
1523 textwidth = (textwidth - columnsep) / columns
1527 def modify_preamble (chunk):
1528 str = chunk.replacement_text ()
1529 if (re.search (r"\\begin *{document}", str)
1530 and not re.search ("{graphic[sx]", str)):
1531 str = re.sub (r"\\begin{document}",
1532 r"\\usepackage{graphics}" + '\n'
1533 + r"\\begin{document}",
1535 chunk.override_text = str
1547 '.texinfo': TEXINFO,
1554 # TEXINFO: '.texinfo',
1560 class Compile_error:
1563 def write_file_map (lys, name):
1564 snippet_map = open ('snippet-map.ly', 'w')
1565 snippet_map.write ("""
1566 #(define version-seen #t)
1567 #(define output-empty-score-list #f)
1568 #(ly:add-file-name-alist '(
1571 snippet_map.write ('("%s.ly" . "%s")\n'
1575 snippet_map.write ('))\n')
1577 def do_process_cmd (chunks, input_name):
1578 all_lys = filter (lambda x: is_derived_class (x.__class__,
1582 write_file_map (all_lys, input_name)
1583 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1585 and x.ly_is_outdated (), chunks)
1586 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1588 and x.texstr_is_outdated (),
1590 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1592 and x.png_is_outdated (),
1595 outdated = png_outdated + texstr_outdated + ly_outdated
1597 progress (_ ("Writing snippets..."))
1598 map (Lilypond_snippet.write_ly, ly_outdated)
1602 progress (_ ("Processing..."))
1604 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1606 progress (_ ("All snippets are up to date..."))
1609 def guess_format (input_filename):
1611 e = os.path.splitext (input_filename)[1]
1612 if e in ext2format.keys ():
1614 format = ext2format[e]
1616 error (_ ("cannot determine format for: %s" \
1621 def write_if_updated (file_name, lines):
1623 f = open (file_name)
1625 new_str = string.join (lines, '')
1626 if oldstr == new_str:
1627 progress (_ ("%s is up to date.") % file_name)
1633 progress (_ ("Writing `%s'...") % file_name)
1634 open (file_name, 'w').writelines (lines)
1637 def note_input_file (name, inputs=[]):
1638 ## hack: inputs is mutable!
1639 inputs.append (name)
1642 def samefile (f1, f2):
1644 return os.path.samefile (f1, f2)
1645 except AttributeError: # Windoze
1646 f1 = re.sub ("//*", "/", f1)
1647 f2 = re.sub ("//*", "/", f2)
1650 def do_file (input_filename):
1652 if not input_filename or input_filename == '-':
1653 in_handle = sys.stdin
1654 input_fullname = '<stdin>'
1656 if os.path.exists (input_filename):
1657 input_fullname = input_filename
1658 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1659 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1661 input_fullname = find_file (input_filename)
1663 note_input_file (input_fullname)
1664 in_handle = open (input_fullname)
1666 if input_filename == '-':
1667 input_base = 'stdin'
1669 input_base = os.path.basename \
1670 (os.path.splitext (input_filename)[0])
1672 # Only default to stdout when filtering.
1673 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1674 output_filename = '-'
1675 output_file = sys.stdout
1677 # don't complain when global_options.output_name is existing
1678 output_filename = input_base + format2ext[global_options.format]
1679 if global_options.output_name:
1680 if not os.path.isdir (global_options.output_name):
1681 os.mkdir (global_options.output_name, 0777)
1682 os.chdir (global_options.output_name)
1684 if (os.path.exists (input_filename)
1685 and os.path.exists (output_filename)
1686 and samefile (output_filename, input_fullname)):
1688 _ ("Output would overwrite input file; use --output."))
1692 progress (_ ("Reading %s...") % input_fullname)
1693 source = in_handle.read ()
1696 set_default_options (source)
1699 # FIXME: Containing blocks must be first, see
1700 # find_toplevel_snippets.
1702 'multiline_comment',
1706 'singleline_comment',
1711 progress (_ ("Dissecting..."))
1712 chunks = find_toplevel_snippets (source, snippet_types)
1714 if global_options.format == LATEX:
1716 if (c.is_plain () and
1717 re.search (r"\\begin *{document}", c.replacement_text())):
1722 if global_options.filter_cmd:
1723 write_if_updated (output_filename,
1724 [c.filter_text () for c in chunks])
1725 elif global_options.process_cmd:
1726 do_process_cmd (chunks, input_fullname)
1727 progress (_ ("Compiling %s...") % output_filename)
1729 write_if_updated (output_filename,
1730 [s.replacement_text ()
1733 def process_include (snippet):
1734 os.chdir (original_dir)
1735 name = snippet.substring ('filename')
1736 progress (_ ("Processing include: %s") % name)
1738 return do_file (name)
1740 include_chunks = map (process_include,
1741 filter (lambda x: is_derived_class (x.__class__,
1746 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1748 except Compile_error:
1749 os.chdir (original_dir)
1750 progress (_ ("Removing `%s'") % output_filename)
1756 global global_options
1758 opt_parser = get_option_parser()
1759 (global_options, args) = opt_parser.parse_args ()
1761 if global_options.format in ('texi-html', 'texi'):
1762 global_options.format = TEXINFO
1763 global_options.use_hash = True
1765 global_options.include_path = map (os.path.abspath, global_options.include_path)
1767 if global_options.warranty:
1770 if not args or len (args) > 1:
1771 opt_parser.print_help ()
1776 def psfonts_warning (options, basename):
1777 if options.format in (TEXINFO, LATEX):
1778 psfonts_file = os.path.join (options.output_name, basename + '.psfonts')
1779 output = os.path.join (options.output_name, basename + '.dvi' )
1781 if not options.create_pdf:
1782 if not options.psfonts:
1783 warning (_ ("option --psfonts not used"))
1784 warning (_ ("processing with dvips will have no fonts"))
1787 progress (_ ("DVIPS usage:"))
1789 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1793 # FIXME: 85 lines of `main' macramee??
1794 files = do_options ()
1798 basename = os.path.splitext (file)[0]
1799 basename = os.path.split (basename)[1]
1801 if not global_options.format:
1802 global_options.format = guess_format (files[0])
1805 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1809 if global_options.process_cmd == '':
1810 global_options.process_cmd = (lilypond_binary
1811 + ' --formats=%s --backend eps ' % formats)
1813 if global_options.process_cmd:
1814 global_options.process_cmd += string.join ([(' -I %s' % ly.mkarg (p))
1815 for p in global_options.include_path])
1817 if global_options.format in (TEXINFO, LATEX):
1818 ## prevent PDF from being switched on by default.
1819 global_options.process_cmd += ' --formats=eps '
1820 if global_options.create_pdf:
1821 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1823 if global_options.verbose:
1824 global_options.process_cmd += " --verbose "
1826 if global_options.padding_mm:
1827 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1829 global_options.process_cmd += " -dread-file-list "
1834 chunks = do_file (file)
1835 if global_options.psfonts:
1836 fontextract.verbose = global_options.verbose
1837 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1841 psfonts_file = basename + '.psfonts'
1842 if not global_options.verbose:
1843 progress (_ ("Writing fonts to %s...") % psfonts_file)
1844 fontextract.extract_fonts (psfonts_file,
1845 [x.basename() + '.eps'
1846 for x in snippet_chunks])
1847 if not global_options.verbose:
1850 except Compile_error:
1853 psfonts_warning (global_options, basename)
1855 inputs = note_input_file ('')
1858 base_file_name = os.path.splitext (os.path.basename (file))[0]
1859 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1860 final_output_file = os.path.join (global_options.output_name,
1862 + '.%s' % global_options.format)
1864 os.chdir (original_dir)
1865 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1867 if __name__ == '__main__':