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
39 # Users of python modules should include this snippet
40 # and customize variables below.
42 # We'll suffer this path initialization stuff as long as we don't install
43 # our python packages in <prefix>/lib/pythonX.Y
45 # If set, LILYPONDPREFIX must take prevalence.
46 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
52 datadir = '@local_lilypond_datadir@'
53 if not os.path.isdir (datadir):
54 datadir = '@lilypond_datadir@'
56 sys.path.insert (0, os.path.join (datadir, 'python'))
58 if os.environ.has_key ('LILYPONDPREFIX'):
59 datadir = os.environ['LILYPONDPREFIX']
60 while datadir[-1] == os.sep:
63 datadir = os.path.join (datadir, "share/lilypond/current/")
64 sys.path.insert (0, os.path.join (datadir, 'python'))
66 # dynamic relocation, for GUB binaries.
67 bindir = os.path.split (sys.argv[0])[0]
70 for prefix_component in ['share', 'lib']:
71 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
72 sys.path.insert (0, datadir)
81 program_version = '@TOPLEVEL_VERSION@'
82 program_name = os.path.basename (sys.argv[0])
84 original_dir = os.getcwd ()
88 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
92 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
93 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
94 lilypond-book --process='lilypond -I include' BOOK
97 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
98 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
101 ################################################################
103 if global_options.verbose:
104 raise _ ('Exiting (%d)...') % i
109 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
111 progress=sys.stderr.write
114 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
117 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
121 sys.stdout.write ('''
128 ''' ( _('Copyright (c) %s by') % '2001--2006',
130 _('Distributed under terms of the GNU General Public License.'),
131 _('It comes with NO WARRANTY.')))
134 def get_option_parser ():
135 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
136 version="@TOPLEVEL_VERSION@",
137 description=help_summary)
139 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
142 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
144 p.add_option ('-f', '--format', help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
146 p.add_option ("-I", '--include', help=_('add DIR to include path'),
148 action='append', dest='include_path',
149 default=[os.path.abspath (os.getcwd ())])
151 p.add_option ("-o", '--output', help=_('write output to DIR'),
153 action='store', dest='output_name', default=None)
154 p.add_option ('-P', '--process', metavar=_("COMMAND"),
155 help = _ ("process ly_files using COMMAND FILE..."),
157 dest='process_cmd', default='lilypond -b eps')
159 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
160 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
161 '''must use this with dvips -h INPUT.psfonts'''),
163 p.add_option ('-V', '--verbose', help=_("be verbose"), action="store_true",
166 p.add_option ('-w', '--warranty',
167 help=_("show warranty and copyright"),
171 p.add_option_group ('bugs',
172 description='''Report bugs via http://post.gmane.org/post.php'''
173 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
177 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
179 # Only use installed binary when we are installed too.
180 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
181 lilypond_binary = 'lilypond'
183 global_options = None
186 default_ly_options = { 'alt': "[image of music]" }
189 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
193 EXAMPLEINDENT = 'exampleindent'
195 FRAGMENT = 'fragment'
200 LINE_WIDTH = 'line-width'
201 NOFRAGMENT = 'nofragment'
202 NOINDENT = 'noindent'
207 OUTPUTIMAGE = 'outputimage'
210 PREAMBLE = 'preamble'
211 PRINTFILENAME = 'printfilename'
213 RAGGED_RIGHT = 'ragged-right'
214 RELATIVE = 'relative'
215 STAFFSIZE = 'staffsize'
218 VERBATIM = 'verbatim'
219 FONTLOAD = 'fontload'
220 FILENAME = 'filename'
224 # NOTIME has no opposite so it isn't part of this dictionary.
225 # NOQUOTE is used internally only.
227 NOFRAGMENT: FRAGMENT,
232 # Recognize special sequences in the input.
234 # (?P<name>regex) -- Assign result of REGEX to NAME.
235 # *? -- Match non-greedily.
236 # (?m) -- Multiline regex: Make ^ and $ match at each line.
237 # (?s) -- Make the dot match all characters including newline.
238 # (?x) -- Ignore whitespace in patterns.
250 (\s*(?P<options>.*?)\s*:)?\s*
258 \s*(?P<options>.*?)\s*
267 \s*(?P<options>.*?)\s*
269 \s*(?P<filename>.*?)\s*
276 (?P<code><!--\s.*?!-->)
279 'singleline_comment':
285 (?P<code><pre>.*?</pre>))''',
291 (?P<code><pre>\s.*?</pre>\s))''',
310 \s*(?P<options>.*?)\s*
321 \s*(?P<options>.*?)\s*
325 \\end\s*{lilypond})''',
333 \s*(?P<options>.*?)\s*
341 'singleline_comment':
364 \\end\s*{verbatim}))''',
373 (?P<filename>\S+))''',
377 ^[^\n]*?(?!@c\s+)[^\n]*?
381 \s*(?P<options>.*?)\s*
391 \s*(?P<options>.*?)\s*
394 ^@end\s+lilypond)\s''',
401 \s*(?P<options>.*?)\s*
412 @end\s+ignore))\s''',
414 'singleline_comment':
419 @c([ \t][^\n]*|)\n))''',
421 # Don't do this: It interferes with @code{@{}.
422 # 'verb': r'''(?P<code>@code{.*?})''',
430 @end\s+example\s))''',
439 'intertext': r',?\s*intertext=\".*?\"',
444 'intertext': r',?\s*intertext=\".*?\"',
445 'option_sep': '\s*,\s*',
449 'intertext': r',?\s*intertext=\".*?\"',
450 'option_sep': '\s*,\s*',
454 # Options without a pattern in ly_options.
471 RELATIVE: r'''\relative c%(relative_quotes)s''',
476 INDENT: r'''indent = %(indent)s''',
478 LINE_WIDTH: r'''line-width = %(line-width)s''',
480 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
482 RAGGED_RIGHT: r'''ragged-right = ##t''',
484 PACKED: r'''packed = ##t''',
496 \remove Time_signature_engraver
502 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
509 FILTER: r'''<lilypond %(options)s>
519 <a href="%(base)s.ly">''',
522 <img align="center" valign="center"
523 border="0" src="%(image)s" alt="%(alt)s">''',
525 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
527 QUOTE: r'''<blockquote>
541 \ifx\preLilyPondExample \undefined%%
544 \preLilyPondExample%%
546 \def\lilypondbook{}%%
547 \input %(base)s-systems.tex%%
548 \ifx\postLilyPondExample \undefined%%
551 \postLilyPondExample%%
555 PRINTFILENAME: '''\\texttt{%(filename)s}
558 QUOTE: r'''\begin{quotation}%(str)s
561 VERBATIM: r'''\noindent
562 \begin{verbatim}%(verb)s\end{verbatim}''',
564 FILTER: r'''\begin{lilypond}[%(options)s]
571 FILTER: r'''@lilypond[%(options)s]
577 @include %(base)s-systems.texi
581 OUTPUTIMAGE: r'''@noindent
583 @image{%(base)s,,,%(alt)s,%(ext)s}
587 <a href="%(base)s.ly">
588 <img align="center" valign="center"
589 border="0" src="%(image)s" alt="%(alt)s">
595 PRINTFILENAME: '''@file{%(filename)s}
598 QUOTE: r'''@quotation
599 %(str)s@end quotation
606 VERBATIM: r'''@exampleindent 0
614 # Maintain line numbers.
619 for f in [HTML, LATEX]:
620 for s in (QUOTE, VERBATIM):
621 output[f][s] = output[f][s].replace("\n"," ")
624 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
625 %%%% Options: [%(option_string)s]
627 #(set! toplevel-score-handler print-score-with-defaults)
628 #(set! toplevel-music-handler
630 (if (not (eq? (ly:music-property m \'void) #t))
631 (print-score-with-defaults
632 p (scorify-music m p)))))
634 #(ly:set-option (quote no-point-and-click))
635 #(define inside-lilypond-book #t)
636 #(define version-seen? #t)
644 %% ****************************************************************
645 %% Start cut-&-pastable-section
646 %% ****************************************************************
649 #(define dump-extents #t)
650 %(font_dump_setting)s
664 %% ****************************************************************
665 %% ly snippet contents follows:
666 %% ****************************************************************
670 %% ****************************************************************
672 %% ****************************************************************
679 %% ****************************************************************
681 %% ****************************************************************
685 %% ****************************************************************
687 %% ****************************************************************
690 texinfo_line_widths = {
691 '@afourpaper': '160\\mm',
692 '@afourwide': '6.5\\in',
693 '@afourlatex': '150\\mm',
694 '@smallbook': '5\\in',
695 '@letterpaper': '6\\in',
698 def classic_lilypond_book_compatibility (key, value):
699 if key == 'singleline' and value == None:
700 return (RAGGED_RIGHT, None)
702 m = re.search ('relative\s*([-0-9])', key)
704 return ('relative', m.group (1))
706 m = re.match ('([0-9]+)pt', key)
708 return ('staffsize', m.group (1))
710 if key == 'indent' or key == 'line-width':
711 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
713 f = float (m.group (1))
714 return (key, '%f\\%s' % (f, m.group (2)))
718 def find_file (name):
719 for i in global_options.include_path:
720 full = os.path.join (i, name)
721 if os.path.exists (full):
724 error (_ ("file not found: %s") % name + '\n')
728 def verbatim_html (s):
729 return re.sub ('>', '>',
731 re.sub ('&', '&', s)))
733 def verbatim_texinfo (s):
734 return re.sub ('{', '@{',
736 re.sub ('@', '@@', s)))
738 def split_options (option_string):
740 if global_options.format == HTML:
741 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
742 for i in range(len(options)):
743 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
746 return re.split (format_res[global_options.format]['option_sep'],
750 def set_default_options (source):
751 global default_ly_options
752 if not default_ly_options.has_key (LINE_WIDTH):
753 if global_options.format == LATEX:
754 textwidth = get_latex_textwidth (source)
755 default_ly_options[LINE_WIDTH] = \
756 '''%.0f\\pt''' % textwidth
757 elif global_options.format == TEXINFO:
758 for (k, v) in texinfo_line_widths.items ():
759 # FIXME: @layout is usually not in
762 # \input texinfo @c -*-texinfo-*-
764 # Bluntly search first K items of
766 # s = chunks[0].replacement_text ()
767 if re.search (k, source[:1024]):
768 default_ly_options[LINE_WIDTH] = v
772 def replacement_text (self):
775 def filter_text (self):
776 return self.replacement_text ()
778 def ly_is_outdated (self):
781 def png_is_outdated (self):
787 class Substring (Chunk):
788 def __init__ (self, source, start, end, line_number):
792 self.line_number = line_number
793 self.override_text = None
798 def replacement_text (self):
799 if self.override_text:
800 return self.override_text
802 return self.source[self.start:self.end]
804 class Snippet (Chunk):
805 def __init__ (self, type, match, format, line_number):
809 self.option_dict = {}
811 self.line_number = line_number
813 def replacement_text (self):
814 return self.match.group ('match')
816 def substring (self, s):
817 return self.match.group (s)
820 return `self.__class__` + ' type = ' + self.type
822 class Include_snippet (Snippet):
823 def processed_filename (self):
824 f = self.substring ('filename')
825 return os.path.splitext (f)[0] + format2ext[global_options.format]
827 def replacement_text (self):
828 s = self.match.group ('match')
829 f = self.substring ('filename')
831 return re.sub (f, self.processed_filename (), s)
833 class Lilypond_snippet (Snippet):
834 def __init__ (self, type, match, format, line_number):
835 Snippet.__init__ (self, type, match, format, line_number)
836 os = match.group ('options')
837 self.do_options (os, self.type)
840 return self.substring ('code')
845 return self.compose_ly (s)
848 def do_options (self, option_string, type):
849 self.option_dict = {}
851 options = split_options (option_string)
854 if string.find (i, '=') > 0:
855 (key, value) = re.split ('\s*=\s*', i)
856 self.option_dict[key] = value
858 if i in no_options.keys ():
859 if no_options[i] in self.option_dict.keys ():
860 del self.option_dict[no_options[i]]
862 self.option_dict[i] = None
864 has_line_width = self.option_dict.has_key (LINE_WIDTH)
865 no_line_width_value = 0
867 # If LINE_WIDTH is used without parameter, set it to default.
868 if has_line_width and self.option_dict[LINE_WIDTH] == None:
869 no_line_width_value = 1
870 del self.option_dict[LINE_WIDTH]
872 for i in default_ly_options.keys ():
873 if i not in self.option_dict.keys ():
874 self.option_dict[i] = default_ly_options[i]
876 if not has_line_width:
877 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
878 self.option_dict[RAGGED_RIGHT] = None
880 if type == 'lilypond':
881 if LINE_WIDTH in self.option_dict.keys ():
882 del self.option_dict[LINE_WIDTH]
884 if RAGGED_RIGHT in self.option_dict.keys ():
885 if LINE_WIDTH in self.option_dict.keys ():
886 del self.option_dict[LINE_WIDTH]
888 if QUOTE in self.option_dict.keys () or type == 'lilypond':
889 if LINE_WIDTH in self.option_dict.keys ():
890 del self.option_dict[LINE_WIDTH]
892 if not INDENT in self.option_dict.keys ():
893 self.option_dict[INDENT] = '0\\mm'
895 # The QUOTE pattern from ly_options only emits the `line-width'
897 if has_line_width and QUOTE in self.option_dict.keys ():
898 if no_line_width_value:
899 del self.option_dict[LINE_WIDTH]
901 del self.option_dict[QUOTE]
903 def compose_ly (self, code):
904 if FRAGMENT in self.option_dict.keys ():
912 # The original concept of the `exampleindent' option is broken.
913 # It is not possible to get a sane value for @exampleindent at all
914 # without processing the document itself. Saying
922 # causes ugly results with the DVI backend of texinfo since the
923 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
924 # value). Executing the above code changes the environment
925 # indentation to an unknown value because we don't know the amount
926 # of 1em in advance since it is font-dependent. Modifying
927 # @exampleindent in the middle of a document is simply not
928 # supported within texinfo.
930 # As a consequence, the only function of @exampleindent is now to
931 # specify the amount of indentation for the `quote' option.
933 # To set @exampleindent locally to zero, we use the @format
934 # environment for non-quoted snippets.
935 override[EXAMPLEINDENT] = r'0.4\in'
936 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
937 override.update (default_ly_options)
940 for (key, value) in self.option_dict.items ():
942 option_list.append (key)
944 option_list.append (key + '=' + value)
945 option_string = string.join (option_list, ',')
948 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
949 for a in compose_types:
952 for (key, value) in self.option_dict.items ():
954 classic_lilypond_book_compatibility (key, value)
958 (_ ("deprecated ly-option used: %s=%s" \
961 (_ ("compatibility mode translation: %s=%s" \
965 (_ ("deprecated ly-option used: %s" \
968 (_ ("compatibility mode translation: %s" \
971 (key, value) = (c_key, c_value)
974 override[key] = value
976 if not override.has_key (key):
980 for type in compose_types:
981 if ly_options[type].has_key (key):
982 compose_dict[type].append (ly_options[type][key])
986 if not found and key not in simple_options:
987 warning (_ ("ignoring unknown ly option: %s") % key)
990 if RELATIVE in override.keys () and override[RELATIVE]:
991 relative = int (override[RELATIVE])
997 relative_quotes += ',' * (- relative)
999 relative_quotes += "'" * relative
1001 paper_string = string.join (compose_dict[PAPER],
1003 layout_string = string.join (compose_dict[LAYOUT],
1005 notes_string = string.join (compose_dict[NOTES],
1007 preamble_string = string.join (compose_dict[PREAMBLE],
1010 font_dump_setting = ''
1011 if FONTLOAD in self.option_dict:
1012 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1014 d = globals().copy()
1016 return (PREAMBLE_LY + body) % d
1019 def get_hash (self):
1021 self.hash = abs (hash (self.full_ly ()))
1024 def basename (self):
1025 if FILENAME in self.option_dict:
1026 return self.option_dict[FILENAME]
1027 if global_options.use_hash:
1028 return 'lily-%d' % self.get_hash ()
1031 def write_ly (self):
1032 outf = open (self.basename () + '.ly', 'w')
1033 outf.write (self.full_ly ())
1035 open (self.basename () + '.txt', 'w').write ('image of music')
1037 def ly_is_outdated (self):
1038 base = self.basename ()
1040 tex_file = '%s.tex' % base
1041 eps_file = '%s.eps' % base
1042 system_file = '%s-systems.tex' % base
1043 ly_file = '%s.ly' % base
1044 ok = os.path.exists (ly_file) \
1045 and os.path.exists (system_file)\
1046 and os.stat (system_file)[stat.ST_SIZE] \
1047 and re.match ('% eof', open (system_file).readlines ()[-1])
1048 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1049 ok = (self.full_ly () == open (ly_file).read ())
1051 # TODO: Do something smart with target formats
1052 # (ps, png) and m/ctimes.
1056 def png_is_outdated (self):
1057 base = self.basename ()
1058 ok = self.ly_is_outdated ()
1059 if global_options.format in (HTML, TEXINFO):
1060 ok = ok and os.path.exists (base + '.eps')
1064 page_count = ly.ps_page_count (base + '.eps')
1067 ok = ok and os.path.exists (base + '.png')
1068 elif page_count > 1:
1069 for a in range (1, page_count + 1):
1070 ok = ok and os.path.exists (base + '-page%d.png' % a)
1074 def texstr_is_outdated (self):
1078 base = self.basename ()
1079 ok = self.ly_is_outdated ()
1080 ok = ok and (os.path.exists (base + '.texstr'))
1083 def filter_text (self):
1084 code = self.substring ('code')
1085 s = run_filter (code)
1088 'options': self.match.group ('options')
1091 return output[self.format][FILTER] % d
1093 def replacement_text (self):
1094 func = Lilypond_snippet.__dict__['output_' + self.format]
1097 def get_images (self):
1098 base = self.basename ()
1100 single = '%(base)s.png' % vars ()
1101 multiple = '%(base)s-page1.png' % vars ()
1103 if os.path.exists (multiple) \
1104 and (not os.path.exists (single) \
1105 or (os.stat (multiple)[stat.ST_MTIME] \
1106 > os.stat (single)[stat.ST_MTIME])):
1107 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1108 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1109 images = tuple (images)
1112 def output_html (self):
1114 base = self.basename ()
1115 if global_options.format == HTML:
1116 str += self.output_print_filename (HTML)
1117 if VERBATIM in self.option_dict:
1118 verb = verbatim_html (self.substring ('code'))
1119 str += output[HTML][VERBATIM] % vars ()
1120 if QUOTE in self.option_dict:
1121 str = output[HTML][QUOTE] % vars ()
1123 str += output[HTML][BEFORE] % vars ()
1124 for image in self.get_images ():
1125 (base, ext) = os.path.splitext (image)
1126 alt = self.option_dict[ALT]
1127 str += output[HTML][OUTPUT] % vars ()
1128 str += output[HTML][AFTER] % vars ()
1131 def output_info (self):
1133 for image in self.get_images ():
1134 (base, ext) = os.path.splitext (image)
1136 # URG, makeinfo implicitly prepends dot to extension.
1137 # Specifying no extension is most robust.
1139 alt = self.option_dict[ALT]
1140 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1142 base = self.basename ()
1143 str += output[global_options.format][OUTPUT] % vars ()
1146 def output_latex (self):
1148 base = self.basename ()
1149 if global_options.format == LATEX:
1150 str += self.output_print_filename (LATEX)
1151 if VERBATIM in self.option_dict:
1152 verb = self.substring ('code')
1153 str += (output[LATEX][VERBATIM] % vars ())
1155 str += (output[LATEX][OUTPUT] % vars ())
1157 ## todo: maintain breaks
1159 breaks = self.ly ().count ("\n")
1160 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1162 if QUOTE in self.option_dict:
1163 str = output[LATEX][QUOTE] % vars ()
1166 def output_print_filename (self, format):
1168 if PRINTFILENAME in self.option_dict:
1169 base = self.basename ()
1170 filename = self.substring ('filename')
1171 str = output[global_options.format][PRINTFILENAME] % vars ()
1175 def output_texinfo (self):
1177 if self.output_print_filename (TEXINFO):
1179 + self.output_print_filename (HTML)
1182 + self.output_print_filename (LATEX)
1184 base = self.basename ()
1185 if TEXIDOC in self.option_dict:
1186 texidoc = base + '.texidoc'
1187 if os.path.exists (texidoc):
1188 str += '@include %(texidoc)s\n\n' % vars ()
1190 if VERBATIM in self.option_dict:
1191 verb = verbatim_texinfo (self.substring ('code'))
1192 str += (output[TEXINFO][VERBATIM] % vars ())
1193 if not QUOTE in self.option_dict:
1194 str = output[TEXINFO][NOQUOTE] % vars ()
1196 str += self.output_info ()
1198 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1199 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1200 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1202 if QUOTE in self.option_dict:
1203 str = output[TEXINFO][QUOTE] % vars ()
1205 # need par after image
1210 class Lilypond_file_snippet (Lilypond_snippet):
1212 name = self.substring ('filename')
1213 return '\\sourcefilename \"%s\"\n%s' \
1214 % (name, open (find_file (name)).read ())
1216 snippet_type_to_class = {
1217 'lilypond_file': Lilypond_file_snippet,
1218 'lilypond_block': Lilypond_snippet,
1219 'lilypond': Lilypond_snippet,
1220 'include': Include_snippet,
1223 def find_linestarts (s):
1228 i = s.find ('\n', start)
1236 nls.append (len (s))
1239 def find_toplevel_snippets (s, types):
1242 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1246 ## found = dict (map (lambda x: (x, None),
1250 map (lambda x, f = found: f.setdefault (x, None),
1253 line_starts = find_linestarts (s)
1255 # We want to search for multiple regexes, without searching
1256 # the string multiple times for one regex.
1257 # Hence, we use earlier results to limit the string portion
1259 # Since every part of the string is traversed at most once for
1260 # every type of snippet, this is linear.
1266 if not found[type] or found[type][0] < index:
1269 m = res[type].search (s[index:endex])
1274 if snippet_type_to_class.has_key (type):
1275 cl = snippet_type_to_class[type]
1278 start = index + m.start ('match')
1279 line_number = line_start_idx
1280 while (line_starts[line_number] < start):
1284 snip = cl (type, m, global_options.format, line_number)
1286 found[type] = (start, snip)
1290 or found[type][0] < found[first][0]):
1295 # Limiting the search space is a cute
1296 # idea, but this *requires* to search
1297 # for possible containing blocks
1298 # first, at least as long as we do not
1299 # search for the start of blocks, but
1300 # always/directly for the entire
1301 # @block ... @end block.
1303 endex = found[first][0]
1306 snippets.append (Substring (s, index, len (s), line_start_idx))
1309 while (start > line_starts[line_start_idx+1]):
1312 (start, snip) = found[first]
1313 snippets.append (Substring (s, index, start, line_start_idx + 1))
1314 snippets.append (snip)
1316 index = start + len (snip.match.group ('match'))
1320 def filter_pipe (input, cmd):
1321 if global_options.verbose:
1322 progress (_ ("Opening filter `%s'") % cmd)
1324 (stdin, stdout, stderr) = os.popen3 (cmd)
1326 status = stdin.close ()
1330 output = stdout.read ()
1331 status = stdout.close ()
1332 error = stderr.read ()
1336 signal = 0x0f & status
1337 if status or (not output and error):
1338 exit_status = status >> 8
1339 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1340 error (_ ("The error log is as follows:"))
1341 sys.stderr.write (error)
1342 sys.stderr.write (stderr.read ())
1345 if global_options.verbose:
1351 return filter_pipe (s, global_options.filter_cmd)
1353 def is_derived_class (cl, baseclass):
1356 for b in cl.__bases__:
1357 if is_derived_class (b, baseclass):
1361 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1362 ly_names = filter (lambda x: x,
1363 map (Lilypond_snippet.basename, ly_snippets))
1364 texstr_names = filter (lambda x: x,
1365 map (Lilypond_snippet.basename, texstr_snippets))
1366 png_names = filter (lambda x: x,
1367 map (Lilypond_snippet.basename, png_snippets))
1370 def my_system (cmd):
1371 status = ly.system (cmd,
1372 ignore_error = 1, progress_p = 1)
1375 error ('Process %s exited unsuccessfully.' % cmd)
1379 # the --process=CMD switch is a bad idea
1380 # it is too generic for lilypond-book.
1382 my_system (string.join ([cmd, '--backend texstr',
1383 'snippet-map.ly'] + texstr_names))
1384 for l in texstr_names:
1385 my_system ('latex %s.texstr' % l)
1388 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1390 LATEX_INSPECTION_DOCUMENT = r'''
1394 \typeout{textwidth=\the\textwidth}
1395 \typeout{columnsep=\the\columnsep}
1396 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1400 # Do we need anything else besides `textwidth'?
1401 def get_latex_textwidth (source):
1402 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1403 preamble = source[:m.start (0)]
1404 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1406 (handle, tmpfile) = tempfile.mkstemp('.tex')
1407 logfile = os.path.splitext (tmpfile)[0] + '.log'
1408 open (tmpfile,'w').write (latex_document)
1409 ly.system ('latex %s' % tmpfile)
1410 parameter_string = open (logfile).read()
1416 m = re.search ('columns=([0-9.]*)', parameter_string)
1418 columns = int (m.group (1))
1421 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1423 columnsep = float (m.group (1))
1426 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1428 textwidth = float (m.group (1))
1430 textwidth = (textwidth - columnsep) / columns
1434 def modify_preamble (chunk):
1435 str = chunk.replacement_text ()
1436 if (re.search (r"\\begin *{document}", str)
1437 and not re.search ("{graphic[sx]", str)):
1438 str = re.sub (r"\\begin{document}",
1439 r"\\usepackage{graphics}" + '\n'
1440 + r"\\begin{document}",
1442 chunk.override_text = str
1454 '.texinfo': TEXINFO,
1460 # TEXINFO: '.texinfo',
1465 class Compile_error:
1468 def write_file_map (lys, name):
1469 snippet_map = open ('snippet-map.ly', 'w')
1470 snippet_map.write ("""
1471 #(define version-seen? #t)
1472 #(ly:add-file-name-alist '(
1475 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1481 snippet_map.write ('))\n')
1483 def do_process_cmd (chunks, input_name):
1484 all_lys = filter (lambda x: is_derived_class (x.__class__,
1488 write_file_map (all_lys, input_name)
1490 filter (lambda x: is_derived_class (x.__class__,
1492 and x.ly_is_outdated (),
1495 filter (lambda x: is_derived_class (x.__class__,
1497 and x.texstr_is_outdated (),
1500 filter (lambda x: is_derived_class (x.__class__,
1502 and x.png_is_outdated (),
1505 progress (_ ("Writing snippets..."))
1506 map (Lilypond_snippet.write_ly, ly_outdated)
1510 progress (_ ("Processing..."))
1512 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1514 progress (_ ("All snippets are up to date..."))
1517 def guess_format (input_filename):
1519 e = os.path.splitext (input_filename)[1]
1520 if e in ext2format.keys ():
1522 format = ext2format[e]
1524 error (_ ("can't determine format for: %s" \
1529 def write_if_updated (file_name, lines):
1531 f = open (file_name)
1533 new_str = string.join (lines, '')
1534 if oldstr == new_str:
1535 progress (_ ("%s is up to date.") % file_name)
1541 progress (_ ("Writing `%s'...") % file_name)
1542 open (file_name, 'w').writelines (lines)
1545 def note_input_file (name, inputs=[]):
1546 ## hack: inputs is mutable!
1547 inputs.append (name)
1550 def do_file (input_filename):
1552 if not input_filename or input_filename == '-':
1553 in_handle = sys.stdin
1554 input_fullname = '<stdin>'
1556 if os.path.exists (input_filename):
1557 input_fullname = input_filename
1558 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1559 input_fullname = os.read_pipe ('kpsewhich ' + input_filename).read()[:-1]
1561 input_fullname = find_file (input_filename)
1563 note_input_file (input_fullname)
1564 in_handle = open (input_fullname)
1566 if input_filename == '-':
1567 input_base = 'stdin'
1569 input_base = os.path.basename \
1570 (os.path.splitext (input_filename)[0])
1572 # Only default to stdout when filtering.
1573 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1574 output_filename = '-'
1575 output_file = sys.stdout
1577 # don't complain when global_options.output_name is existing
1578 output_filename = input_base + format2ext[global_options.format]
1579 if global_options.output_name:
1580 if not os.path.isdir (global_options.output_name):
1581 os.mkdir (global_options.output_name, 0777)
1582 os.chdir (global_options.output_name)
1584 if os.path.exists (input_filename) \
1585 and os.path.exists (output_filename) \
1586 and os.path.samefile (output_filename, input_fullname):
1588 _ ("Output would overwrite input file; use --output."))
1592 progress (_ ("Reading %s...") % input_fullname)
1593 source = in_handle.read ()
1596 set_default_options (source)
1599 # FIXME: Containing blocks must be first, see
1600 # find_toplevel_snippets.
1602 'multiline_comment',
1606 'singleline_comment',
1611 progress (_ ("Dissecting..."))
1612 chunks = find_toplevel_snippets (source, snippet_types)
1614 if global_options.format == LATEX:
1616 if (c.is_plain () and
1617 re.search (r"\\begin *{document}", c.replacement_text())):
1622 if global_options.filter_cmd:
1623 write_if_updated (output_filename,
1624 [c.filter_text () for c in chunks])
1625 elif global_options.process_cmd:
1626 do_process_cmd (chunks, input_fullname)
1627 progress (_ ("Compiling %s...") % output_filename)
1629 write_if_updated (output_filename,
1630 [s.replacement_text ()
1633 def process_include (snippet):
1634 os.chdir (original_dir)
1635 name = snippet.substring ('filename')
1636 progress (_ ("Processing include: %s") % name)
1638 return do_file (name)
1640 include_chunks = map (process_include,
1641 filter (lambda x: is_derived_class (x.__class__,
1646 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1648 except Compile_error:
1649 os.chdir (original_dir)
1650 progress (_ ("Removing `%s'") % output_filename)
1655 opt_parser = get_option_parser()
1656 (options, args) = opt_parser.parse_args ()
1658 if options.format in ('texi-html', 'texi'):
1659 options.format = TEXINFO
1660 options.use_hash = True
1662 options.include_path = map (os.path.abspath, options.include_path)
1664 global global_options
1665 global_options = options
1669 files = do_options ()
1670 if not files or len (files) > 1:
1676 basename = os.path.splitext (file)[0]
1677 basename = os.path.split (basename)[1]
1679 if not global_options.format:
1680 global_options.format = guess_format (files[0])
1683 if global_options.format in (TEXINFO, HTML):
1685 if global_options.process_cmd == '':
1686 global_options.process_cmd = lilypond_binary \
1687 + ' --formats=%s --backend eps ' % formats
1689 if global_options.process_cmd:
1690 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1691 for p in global_options.include_path])
1693 ly.identify (sys.stderr)
1696 chunks = do_file (file)
1697 if global_options.psfonts:
1698 fontextract.verbose = global_options.verbose
1699 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1703 psfonts_file = basename + '.psfonts'
1704 if not global_options.verbose:
1705 progress (_ ("Writing fonts to %s...") % psfonts_file)
1706 fontextract.extract_fonts (psfonts_file,
1707 [x.basename() + '.eps'
1708 for x in snippet_chunks])
1709 if not global_options.verbose:
1712 except Compile_error:
1715 if global_options.format in (TEXINFO, LATEX):
1716 if not global_options.psfonts:
1717 warning (_ ("option --psfonts not used"))
1718 warning (_ ("processing with dvips will have no fonts"))
1720 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1721 output = os.path.join (global_options.output_name, basename + '.dvi' )
1724 progress (_ ("DVIPS usage:"))
1726 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1729 inputs = note_input_file ('')
1732 base_file_name = os.path.splitext (os.path.basename (file))[0]
1733 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1734 final_output_file = os.path.join (global_options.output_name,
1736 + '.%s' % global_options.format)
1738 os.chdir (original_dir)
1739 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1741 if __name__ == '__main__':