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
16 * ly-options: intertext?
18 * eps in latex / eps by lilypond -b ps?
19 * check latex parameters, twocolumn, multicolumn?
20 * use --png --ps --pdf for making images?
22 * Converting from lilypond-book source, substitute:
23 @mbinclude foo.itely -> @include foo.itely
33 # Users of python modules should include this snippet
34 # and customize variables below.
36 # We'll suffer this path initialization stuff as long as we don't install
37 # our python packages in <prefix>/lib/pythonX.Y (and don't kludge around
38 # it as we do with teTeX on Red Hat Linux: set some environment variables
39 # (PYTHONPATH) in `etc/profile').
41 # If set, LILYPONDPREFIX must take prevalence.
42 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
43 import getopt, os, sys
44 datadir = '@local_lilypond_datadir@'
45 if not os.path.isdir (datadir):
46 datadir = '@lilypond_datadir@'
47 if os.environ.has_key ('LILYPONDPREFIX'):
48 datadir = os.environ['LILYPONDPREFIX']
49 while datadir[-1] == os.sep:
52 sys.path.insert (0, os.path.join (datadir, 'python'))
55 #if __name__ == '__main__':
62 program_version = '@TOPLEVEL_VERSION@'
63 program_name = sys.argv[0]
66 original_dir = os.getcwd ()
70 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
73 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
74 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
75 lilypond-book --process='lilypond -I include' BOOK
78 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
79 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
81 option_definitions = [
82 (_ ("FMT"), 'f', 'format',
83 _ ('''use output format FMT (texi [default], texi-html,
85 (_ ("FILTER"), 'F', 'filter',
86 _ ("pipe snippets through FILTER [convert-ly -n -]")),
88 _ ("print this help")),
89 (_ ("DIR"), 'I', 'include',
90 _ ("add DIR to include path")),
91 (_ ("DIR"), 'o', 'output',
92 _ ("write output to DIR")),
93 (_ ("COMMAND"), 'P', 'process',
94 _ ("process ly_files using COMMAND FILE...")),
98 _ ("print version information")),
100 _ ("show warranty and copyright")),
103 include_path = [ly.abspath (os.getcwd ())]
104 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
106 # Only use installed binary when we are installed too.
107 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
108 lilypond_binary = 'lilypond'
113 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
116 default_ly_options = {}
119 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
123 EXAMPLEINDENT = 'exampleindent'
125 FRAGMENT = 'fragment'
130 LINEWIDTH = 'linewidth'
131 NOFRAGMENT = 'nofragment'
132 NOINDENT = 'noindent'
137 OUTPUTIMAGE = 'outputimage'
140 PREAMBLE = 'preamble'
141 PRINTFILENAME = 'printfilename'
143 RAGGEDRIGHT = 'raggedright'
144 RELATIVE = 'relative'
145 STAFFSIZE = 'staffsize'
148 VERBATIM = 'verbatim'
149 FONTLOAD = 'fontload'
152 # NOTIME has no opposite so it isn't part of this dictionary.
153 # NOQUOTE is used internally only.
155 NOFRAGMENT: FRAGMENT,
159 # Recognize special sequences in the input.
161 # (?P<name>regex) -- Assign result of REGEX to NAME.
162 # *? -- Match non-greedily.
163 # (?m) -- Multiline regex: Make ^ and $ match at each line.
164 # (?s) -- Make the dot match all characters including newline.
165 # (?x) -- Ignore whitespace in patterns.
177 (\s*(?P<options>.*?)\s*:)?\s*
185 \s*(?P<options>.*?)\s*
194 \s*(?P<options>.*?)\s*
196 \s*(?P<filename>.*?)\s*
203 (?P<code><!--\s.*?!-->)
206 'singleline_comment':
212 (?P<code><pre>.*?</pre>))''',
218 (?P<code><pre>\s.*?</pre>\s))''',
237 \s*(?P<options>.*?)\s*
248 \s*(?P<options>.*?)\s*
252 \\end\s*{lilypond})''',
260 \s*(?P<options>.*?)\s*
268 'singleline_comment':
291 \\end\s*{verbatim}))''',
300 (?P<filename>\S+))''',
304 ^[^\n]*?(?!@c\s+)[^\n]*?
308 \s*(?P<options>.*?)\s*
318 \s*(?P<options>.*?)\s*
321 ^@end\s+lilypond)\s''',
328 \s*(?P<options>.*?)\s*
339 @end\s+ignore))\s''',
341 'singleline_comment':
346 @c([ \t][^\n]*|)\n))''',
348 # Don't do this: It interferes with @code{@{}.
349 # 'verb': r'''(?P<code>@code{.*?})''',
357 @end\s+example\s))''',
363 'intertext': r',?\s*intertext=\".*?\"',
368 'intertext': r',?\s*intertext=\".*?\"',
369 'option_sep': '\s*,\s*',
373 'intertext': r',?\s*intertext=\".*?\"',
374 'option_sep': '\s*,\s*',
378 # Options without a pattern in ly_options.
393 RELATIVE: r'''\relative c%(relative_quotes)s''',
398 INDENT: r'''indent = %(indent)s''',
400 LINEWIDTH: r'''linewidth = %(linewidth)s''',
402 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
404 RAGGEDRIGHT: r'''raggedright = ##t''',
406 PACKED: r'''packed = ##t''',
411 NOTIME: r'''\context {
413 \remove Time_signature_engraver
419 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
426 FILTER: r'''<lilypond %(options)s>
436 <a href="%(base)s.ly">''',
439 <img align="center" valign="center"
440 border="0" src="%(image)s" alt="[image of music]">''',
442 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
444 QUOTE: r'''<blockquote>
458 \ifx\preLilyPondExample \undefined
463 \def\lilypondbook{}%%
464 \input %(base)s-systems.tex
465 \ifx\postLilyPondExample \undefined
472 PRINTFILENAME: '''\\texttt{%(filename)s}
475 QUOTE: r'''\begin{quotation}
480 VERBATIM: r'''\noindent
482 %(verb)s\end{verbatim}
485 FILTER: r'''\begin{lilypond}[%(options)s]
492 FILTER: r'''@lilypond[%(options)s]
498 @include %(base)s-systems.texi
502 OUTPUTIMAGE: r'''@noindent
504 @image{%(base)s,,,[image of music],%(ext)s}
508 <a href="%(base)s.ly">
509 <img align="center" valign="center"
510 border="0" src="%(image)s" alt="[image of music]">
516 PRINTFILENAME: '''@file{%(filename)s}
519 QUOTE: r'''@quotation
520 %(str)s@end quotation
527 VERBATIM: r'''@exampleindent 0
534 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
535 %%%% Options: [%(option_string)s]
537 #(set! toplevel-score-handler ly:parser-print-score)
538 #(set! toplevel-music-handler (lambda (p m)
539 (ly:parser-print-score
540 p (ly:music-scorify m p))))
542 #(define version-seen? #t)
546 #(define dump-extents #t)
547 %(font_dump_setting)s
559 %% ly snippet contents follows:
571 texinfo_linewidths = {
572 '@afourpaper': '160\\mm',
573 '@afourwide': '6.5\\in',
574 '@afourlatex': '150\\mm',
575 '@smallbook': '5\\in',
576 '@letterpaper': '6\\in',
579 def classic_lilypond_book_compatibility (key, value):
580 if key == 'singleline' and value == None:
581 return (RAGGEDRIGHT, None)
583 m = re.search ('relative\s*([-0-9])', key)
585 return ('relative', m.group (1))
587 m = re.match ('([0-9]+)pt', key)
589 return ('staffsize', m.group (1))
591 if key == 'indent' or key == 'linewidth':
592 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
594 f = float (m.group (1))
595 return (key, '%f\\%s' % (f, m.group (2)))
599 def find_file (name):
600 for i in include_path:
601 full = os.path.join (i, name)
602 if os.path.exists (full):
604 ly.error (_ ("file not found: %s") % name + '\n')
608 def verbatim_html (s):
609 return re.sub ('>', '>',
611 re.sub ('&', '&', s)))
613 def verbatim_texinfo (s):
614 return re.sub ('{', '@{',
616 re.sub ('@', '@@', s)))
618 def split_options (option_string):
620 return re.split (format_res[format]['option_sep'],
625 def replacement_text (self):
628 def filter_text (self):
629 return self.replacement_text ()
631 def ly_is_outdated (self):
634 def png_is_outdated (self):
637 class Substring (Chunk):
638 def __init__ (self, source, start, end, line_number):
642 self.line_number = line_number
644 def replacement_text (self):
645 return self.source[self.start:self.end]
647 class Snippet (Chunk):
648 def __init__ (self, type, match, format, line_number):
652 self.option_dict = {}
654 self.line_number = line_number
656 def replacement_text (self):
657 return self.match.group ('match')
659 def substring (self, s):
660 return self.match.group (s)
663 return `self.__class__` + ' type = ' + self.type
665 class Include_snippet (Snippet):
666 def processed_filename (self):
667 f = self.substring ('filename')
668 return os.path.splitext (f)[0] + format2ext[format]
670 def replacement_text (self):
671 s = self.match.group ('match')
672 f = self.substring ('filename')
674 return re.sub (f, self.processed_filename (), s)
676 class Lilypond_snippet (Snippet):
677 def __init__ (self, type, match, format, line_number):
678 Snippet.__init__ (self, type, match, format, line_number)
679 os = match.group ('options')
681 self.do_options (os, self.type)
684 return self.substring ('code')
689 return self.compose_ly (s)
692 def do_options (self, option_string, type):
693 self.option_dict = {}
695 options = split_options (option_string)
698 if string.find (i, '=') > 0:
699 (key, value) = re.split ('\s*=\s*', i)
700 self.option_dict[key] = value
702 if i in no_options.keys ():
703 if no_options[i] in self.option_dict.keys ():
704 del self.option_dict[no_options[i]]
706 self.option_dict[i] = None
708 has_linewidth = self.option_dict.has_key (LINEWIDTH)
709 no_linewidth_value = 0
711 # If LINEWIDTH is used without parameter, set it to default.
712 if has_linewidth and self.option_dict[LINEWIDTH] == None:
713 no_linewidth_value = 1
714 del self.option_dict[LINEWIDTH]
716 for i in default_ly_options.keys ():
717 if i not in self.option_dict.keys ():
718 self.option_dict[i] = default_ly_options[i]
720 if not has_linewidth:
721 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
722 self.option_dict[RAGGEDRIGHT] = None
724 if type == 'lilypond':
725 if LINEWIDTH in self.option_dict.keys ():
726 del self.option_dict[LINEWIDTH]
728 if RAGGEDRIGHT in self.option_dict.keys ():
729 if LINEWIDTH in self.option_dict.keys ():
730 del self.option_dict[LINEWIDTH]
732 if QUOTE in self.option_dict.keys () or type == 'lilypond':
733 if LINEWIDTH in self.option_dict.keys ():
734 del self.option_dict[LINEWIDTH]
736 if not INDENT in self.option_dict.keys ():
737 self.option_dict[INDENT] = '0\\mm'
739 # The QUOTE pattern from ly_options only emits the `linewidth'
741 if has_linewidth and QUOTE in self.option_dict.keys ():
742 if no_linewidth_value:
743 del self.option_dict[LINEWIDTH]
745 del self.option_dict[QUOTE]
747 def compose_ly (self, code):
748 if FRAGMENT in self.option_dict.keys ():
756 # The original concept of the `exampleindent' option is broken.
757 # It is not possible to get a sane value for @exampleindent at all
758 # without processing the document itself. Saying
766 # causes ugly results with the DVI backend of texinfo since the
767 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
768 # value). Executing the above code changes the environment
769 # indentation to an unknown value because we don't know the amount
770 # of 1em in advance since it is font-dependent. Modifying
771 # @exampleindent in the middle of a document is simply not
772 # supported within texinfo.
774 # As a consequence, the only function of @exampleindent is now to
775 # specify the amount of indentation for the `quote' option.
777 # To set @exampleindent locally to zero, we use the @format
778 # environment for non-quoted snippets.
779 override[EXAMPLEINDENT] = r'0.4\in'
780 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
781 override.update (default_ly_options)
784 for (key, value) in self.option_dict.items ():
786 option_list.append (key)
788 option_list.append (key + '=' + value)
789 option_string = string.join (option_list, ',')
792 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
793 for a in compose_types:
796 for (key, value) in self.option_dict.items ():
798 classic_lilypond_book_compatibility (key, value)
802 (_ ("deprecated ly-option used: %s=%s" \
805 (_ ("compatibility mode translation: %s=%s" \
809 (_ ("deprecated ly-option used: %s" \
812 (_ ("compatibility mode translation: %s" \
815 (key, value) = (c_key, c_value)
818 override[key] = value
820 if not override.has_key (key):
824 for type in compose_types:
825 if ly_options[type].has_key (key):
826 compose_dict[type].append (ly_options[type][key])
830 if not found and key not in simple_options:
831 ly.warning (_ ("ignoring unknown ly option: %s") % key)
834 if RELATIVE in override.keys () and override[RELATIVE]:
835 relative = string.atoi (override[RELATIVE])
841 relative_quotes += ',' * (- relative)
843 relative_quotes += "'" * relative
845 program_name = __main__.program_name
847 paper_string = string.join (compose_dict[PAPER],
849 layout_string = string.join (compose_dict[LAYOUT],
851 notes_string = string.join (compose_dict[NOTES],
853 preamble_string = string.join (compose_dict[PREAMBLE],
856 font_dump_setting = ''
857 if FONTLOAD in self.option_dict:
858 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
860 return (PREAMBLE_LY + body) % vars ()
865 self.hash = abs (hash (self.full_ly ()))
870 return 'lily-%d' % self.get_hash ()
874 outf = open (self.basename () + '.ly', 'w')
875 outf.write (self.full_ly ())
877 open (self.basename () + '.txt', 'w').write ('image of music')
879 def ly_is_outdated (self):
880 base = self.basename ()
882 tex_file = '%s.tex' % base
883 eps_file = '%s.eps' % base
884 system_file = '%s-systems.tex' % base
885 ly_file = '%s.ly' % base
886 ok = os.path.exists (ly_file) \
887 and os.path.exists (system_file)\
888 and os.stat (system_file)[stat.ST_SIZE] \
889 and re.match ('% eof', open (system_file).readlines ()[-1])
890 if ok and (use_hash_p \
891 or self.ly () == open (ly_file).read ()):
892 # TODO: Do something smart with target formats
893 # (ps, png) and m/ctimes.
897 def png_is_outdated (self):
898 base = self.basename ()
899 ok = self.ly_is_outdated ()
900 if format == HTML or format == TEXINFO:
901 ok = ok and (os.path.exists (base + '.png')
902 or glob.glob (base + '-page*.png'))
904 def texstr_is_outdated (self):
908 base = self.basename ()
909 ok = self.ly_is_outdated ()
910 ok = ok and (os.path.exists (base + '.texstr'))
913 def filter_text (self):
914 code = self.substring ('code')
915 s = run_filter (code)
918 'options': self.match.group ('options')
921 return output[self.format][FILTER] % d
923 def replacement_text (self):
924 func = Lilypond_snippet.__dict__['output_' + self.format]
927 def get_images (self):
928 base = self.basename ()
930 single = '%(base)s.png' % vars ()
931 multiple = '%(base)s-page1.png' % vars ()
933 if os.path.exists (multiple) \
934 and (not os.path.exists (single) \
935 or (os.stat (multiple)[stat.ST_MTIME] \
936 > os.stat (single)[stat.ST_MTIME])):
937 images = glob.glob ('%(base)s-page*.png' % vars ())
940 def output_html (self):
942 base = self.basename ()
944 str += self.output_print_filename (HTML)
945 if VERBATIM in self.option_dict:
946 verb = verbatim_html (self.substring ('code'))
947 str += write (output[HTML][VERBATIM] % vars ())
948 if QUOTE in self.option_dict:
949 str = output[HTML][QUOTE] % vars ()
951 str += output[HTML][BEFORE] % vars ()
952 for image in self.get_images ():
953 (base, ext) = os.path.splitext (image)
954 str += output[HTML][OUTPUT] % vars ()
955 str += output[HTML][AFTER] % vars ()
958 def output_info (self):
960 for image in self.get_images ():
961 (base, ext) = os.path.splitext (image)
963 # URG, makeinfo implicitly prepends dot to extension.
964 # Specifying no extension is most robust.
966 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
968 base = self.basename ()
969 str += output[format][OUTPUT] % vars ()
972 def output_latex (self):
974 base = self.basename ()
976 str += self.output_print_filename (LATEX)
977 if VERBATIM in self.option_dict:
978 verb = self.substring ('code')
979 str += (output[LATEX][VERBATIM] % vars ())
980 if QUOTE in self.option_dict:
981 str = output[LATEX][QUOTE] % vars ()
983 str += (output[LATEX][OUTPUT] % vars ())
986 def output_print_filename (self, format):
988 if PRINTFILENAME in self.option_dict:
989 base = self.basename ()
990 filename = self.substring ('filename')
991 str = output[format][PRINTFILENAME] % vars ()
995 def output_texinfo (self):
997 if self.output_print_filename (TEXINFO):
999 + self.output_print_filename (HTML)
1002 + self.output_print_filename (LATEX)
1004 base = self.basename ()
1005 if TEXIDOC in self.option_dict:
1006 texidoc = base + '.texidoc'
1007 if os.path.exists (texidoc):
1008 str += '@include %(texidoc)s\n\n' % vars ()
1010 if VERBATIM in self.option_dict:
1011 verb = verbatim_texinfo (self.substring ('code'))
1012 str += (output[TEXINFO][VERBATIM] % vars ())
1013 if not QUOTE in self.option_dict:
1014 str = output[TEXINFO][NOQUOTE] % vars ()
1016 str += self.output_info ()
1018 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1019 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1020 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1022 if QUOTE in self.option_dict:
1023 str = output[TEXINFO][QUOTE] % vars ()
1025 # need par after image
1030 class Lilypond_file_snippet (Lilypond_snippet):
1032 name = self.substring ('filename')
1033 return '\\renameinput \"%s\"\n%s' \
1034 % (name, open (find_file (name)).read ())
1036 snippet_type_to_class = {
1037 'lilypond_file': Lilypond_file_snippet,
1038 'lilypond_block': Lilypond_snippet,
1039 'lilypond': Lilypond_snippet,
1040 'include': Include_snippet,
1043 def find_linestarts (s):
1048 i = s.find ('\n', start)
1056 nls.append (len (s))
1059 def find_toplevel_snippets (s, types):
1062 res[i] = ly.re.compile (snippet_res[format][i])
1066 ## found = dict (map (lambda x: (x, None),
1070 map (lambda x, f = found: f.setdefault (x, None),
1073 line_starts = find_linestarts (s)
1075 # We want to search for multiple regexes, without searching
1076 # the string multiple times for one regex.
1077 # Hence, we use earlier results to limit the string portion
1079 # Since every part of the string is traversed at most once for
1080 # every type of snippet, this is linear.
1086 if not found[type] or found[type][0] < index:
1088 m = res[type].search (s[index:endex])
1093 if snippet_type_to_class.has_key (type):
1094 cl = snippet_type_to_class[type]
1097 start = index + m.start ('match')
1098 line_number = line_start_idx
1099 while (line_starts[line_number] < start):
1103 snip = cl (type, m, format, line_number)
1104 found[type] = (start, snip)
1108 or found[type][0] < found[first][0]):
1113 # Limiting the search space is a cute
1114 # idea, but this *requires* to search
1115 # for possible containing blocks
1116 # first, at least as long as we do not
1117 # search for the start of blocks, but
1118 # always/directly for the entire
1119 # @block ... @end block.
1121 endex = found[first][0]
1124 snippets.append (Substring (s, index, len (s), line_start_idx))
1127 while (start > line_starts[line_start_idx+1]):
1130 (start, snip) = found[first]
1131 snippets.append (Substring (s, index, start, line_start_idx + 1))
1132 snippets.append (snip)
1134 index = start + len (snip.match.group ('match'))
1138 def filter_pipe (input, cmd):
1140 ly.progress (_ ("Opening filter `%s'") % cmd)
1142 (stdin, stdout, stderr) = os.popen3 (cmd)
1144 status = stdin.close ()
1148 output = stdout.read ()
1149 status = stdout.close ()
1150 error = stderr.read ()
1154 signal = 0x0f & status
1155 if status or (not output and error):
1156 exit_status = status >> 8
1157 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1158 ly.error (_ ("The error log is as follows:"))
1159 sys.stderr.write (error)
1160 sys.stderr.write (stderr.read ())
1169 return filter_pipe (s, filter_cmd)
1171 def is_derived_class (cl, baseclass):
1174 for b in cl.__bases__:
1175 if is_derived_class (b, baseclass):
1179 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1180 ly_names = filter (lambda x: x,
1181 map (Lilypond_snippet.basename, ly_snippets))
1182 texstr_names = filter (lambda x: x,
1183 map (Lilypond_snippet.basename, texstr_snippets))
1184 png_names = filter (lambda x: x,
1185 map (Lilypond_snippet.basename, png_snippets))
1188 def my_system (cmd):
1189 status = ly.system (cmd,
1190 ignore_error = 1, progress_p = 1)
1193 ly.error ('Process %s exited unsuccessfully.' % cmd)
1197 # the --process=CMD switch is a bad idea
1198 # it is too generic for lilypond-book.
1199 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1201 my_system (string.join ([cmd, '--backend texstr',
1202 'snippet-map.ly'] + texstr_names))
1203 for l in texstr_names:
1204 my_system ('latex %s.texstr' % l)
1207 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1209 LATEX_DOCUMENT = r'''
1212 \typeout{textwidth=\the\textwidth}
1213 \typeout{columnsep=\the\columnsep}
1214 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1218 # Do we need anything else besides `textwidth'?
1219 def get_latex_textwidth (source):
1220 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1221 preamble = source[:m.start (0)]
1222 latex_document = LATEX_DOCUMENT % vars ()
1223 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1226 m = re.search ('columns=([0-9.]*)', parameter_string)
1228 columns = string.atoi (m.group (1))
1231 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1233 columnsep = string.atof (m.group (1))
1236 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1238 textwidth = string.atof (m.group (1))
1240 textwidth = (textwidth - columnsep) / columns
1252 '.texinfo': TEXINFO,
1258 # TEXINFO: '.texinfo',
1263 class Compile_error:
1266 def write_file_map (lys, name):
1267 snippet_map = open ('snippet-map.ly', 'w')
1268 snippet_map.write ("""
1269 #(define version-seen? #t)
1270 #(ly:add-file-name-alist '(
1273 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1279 snippet_map.write ('))\n')
1281 def do_process_cmd (chunks, input_name):
1282 all_lys = filter (lambda x: is_derived_class (x.__class__,
1286 write_file_map (all_lys, input_name)
1288 filter (lambda x: is_derived_class (x.__class__,
1290 and x.ly_is_outdated (),
1293 filter (lambda x: is_derived_class (x.__class__,
1295 and x.texstr_is_outdated (),
1298 filter (lambda x: is_derived_class (x.__class__,
1300 and x.png_is_outdated (),
1303 ly.progress (_ ("Writing snippets..."))
1304 map (Lilypond_snippet.write_ly, ly_outdated)
1308 ly.progress (_ ("Processing..."))
1310 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1312 ly.progress (_ ("All snippets are up to date..."))
1315 def guess_format (input_filename):
1317 e = os.path.splitext (input_filename)[1]
1318 if e in ext2format.keys ():
1320 format = ext2format[e]
1322 ly.error (_ ("can't determine format for: %s" \
1327 def do_file (input_filename):
1329 if not input_filename or input_filename == '-':
1330 in_handle = sys.stdin
1331 input_fullname = '<stdin>'
1333 if os.path.exists (input_filename):
1334 input_fullname = input_filename
1335 elif format == LATEX:
1336 # urg python interface to libkpathsea?
1337 input_fullname = ly.read_pipe ('kpsewhich '
1338 + input_filename)[:-1]
1340 input_fullname = find_file (input_filename)
1341 in_handle = open (input_fullname)
1343 if input_filename == '-':
1344 input_base = 'stdin'
1346 input_base = os.path.basename \
1347 (os.path.splitext (input_filename)[0])
1349 # Only default to stdout when filtering.
1350 if output_name == '-' or (not output_name and filter_cmd):
1351 output_filename = '-'
1352 output_file = sys.stdout
1355 output_filename = input_base + format2ext[format]
1357 if not os.path.isdir (output_name):
1358 os.mkdir (output_name, 0777)
1359 output_filename = (output_name
1361 + format2ext[format])
1363 if os.path.exists (input_filename) \
1364 and os.path.exists (output_filename) \
1365 and os.path.samefile (output_filename, input_fullname):
1367 _ ("Output would overwrite input file; use --output."))
1370 output_file = open (output_filename, 'w')
1372 os.chdir (output_name)
1374 ly.progress (_ ("Reading %s...") % input_fullname)
1375 source = in_handle.read ()
1378 # FIXME: Containing blocks must be first, see
1379 # find_toplevel_snippets.
1381 'multiline_comment',
1385 'singleline_comment',
1390 ly.progress (_ ("Dissecting..."))
1391 chunks = find_toplevel_snippets (source, snippet_types)
1394 global default_ly_options
1396 if not default_ly_options.has_key (LINEWIDTH):
1398 textwidth = get_latex_textwidth (source)
1399 default_ly_options[LINEWIDTH] = \
1400 '''%.0f\\pt''' % textwidth
1401 elif format == TEXINFO:
1402 for (k, v) in texinfo_linewidths.items ():
1403 # FIXME: @layout is usually not in
1406 # \input texinfo @c -*-texinfo-*-
1408 # Bluntly search first K items of
1410 # s = chunks[0].replacement_text ()
1411 if re.search (k, source[:1024]):
1412 default_ly_options[LINEWIDTH] = v
1416 output_file.writelines ([c.filter_text () \
1420 do_process_cmd (chunks, input_fullname)
1421 ly.progress (_ ("Compiling %s...") % output_filename)
1422 output_file.writelines ([s.replacement_text () \
1426 def process_include (snippet):
1427 os.chdir (original_dir)
1428 name = snippet.substring ('filename')
1429 ly.progress (_ ("Processing include: %s") % name)
1433 map (process_include,
1434 filter (lambda x: is_derived_class (x.__class__,
1437 except Compile_error:
1438 os.chdir (original_dir)
1439 ly.progress (_ ("Removing `%s'") % output_filename)
1442 os.unlink (output_filename)
1446 global format, output_name
1447 global filter_cmd, process_cmd, verbose_p
1449 (sh, long) = ly.getopt_args (option_definitions)
1451 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1452 except getopt.error, s:
1453 sys.stderr.write ('\n')
1454 ly.error (_ ("getopt says: `%s'" % s))
1455 sys.stderr.write ('\n')
1465 elif o == '--filter' or o == '-F':
1468 elif o == '--format' or o == '-f':
1470 if a == 'texi-html' or a == 'texi':
1472 elif o == '--tex-backend ':
1474 elif o == '--help' or o == '-h':
1477 elif o == '--include' or o == '-I':
1478 include_path.append (os.path.join (original_dir,
1480 elif o == '--output' or o == '-o':
1482 elif o == '--outdir':
1484 elif o == '--process' or o == '-P':
1487 elif o == '--version' or o == '-v':
1488 ly.identify (sys.stdout)
1490 elif o == '--verbose' or o == '-V':
1492 elif o == '--warranty' or o == '-w':
1499 files = do_options ()
1501 ly.warning ("Need to have command line option")
1505 global process_cmd, format
1507 format = guess_format (files[0])
1510 if format == TEXINFO or format == HTML:
1512 if process_cmd == '':
1513 process_cmd = lilypond_binary \
1514 + ' --formats=%s --backend eps ' % formats
1517 process_cmd += string.join ([(' -I %s' % p)
1518 for p in include_path])
1520 ly.identify (sys.stderr)
1521 ly.setup_environment ()
1525 except Compile_error:
1529 if __name__ == '__main__':