]> git.donarmstrong.com Git - lilypond.git/blob - scripts/build/extract_texi_filenames.py
Docs: extract_texi_filenames.py: improve node names normalization
[lilypond.git] / scripts / build / extract_texi_filenames.py
1 #!@PYTHON@
2 # -*- coding: utf-8 -*-
3 # extract_texi_filenames.py
4
5 # USAGE:  extract_texi_filenames.py [-o OUTDIR] FILES
6 #
7 # -o OUTDIR specifies that output files should rather be written in OUTDIR
8 #
9 # Description:
10 # This script parses the .texi file given and creates a file with the
11 # nodename <=> filename/anchor map.
12 # The idea behind: Unnumbered subsections go into the same file as the
13 # previous numbered section, @translationof gives the original node name,
14 # which is then used for the filename/anchor.
15 #
16 # If this script is run on a file texifile.texi, it produces a file
17 # texifile[.LANG].xref-map with tab-separated entries of the form
18 #        NODE\tFILENAME\tANCHOR
19 # LANG is the document language in case it's not 'en'
20 # Note: The filename does not have any extension appended!
21 # This file should then be used by our texi2html init script to determine
22 # the correct file name and anchor for external refs
23
24 # For translated documentation: cross-references to nodes that exist
25 # only in documentation in English are allowed, that's why the already
26 # generated map file of docs in English is loaded with
27 # --master-map-file option, then the node names that are defined in
28 # the map for the manual in English but not in the translated manual
29 # are added to the map for the translated manual.
30
31
32 import sys
33 import re
34 import os
35 import getopt
36
37 options_list, files = getopt.getopt (sys.argv[1:],'o:s:hI:m:',
38                                      ['output=', 'split=',
39                                       'help', 'include=',
40                                       'master-map-file='])
41
42 help_text = r"""Usage: %(program_name)s [OPTIONS]... TEXIFILE...
43 Extract files names for texinfo (sub)sections from the texinfo files.
44
45 Options:
46  -h, --help                     print this help
47  -I, --include=DIRECTORY        append DIRECTORY to include search path
48  -m, --master-map-file=FILE     use FILE as master map file
49  -o, --output=DIRECTORY         write .xref-map files to DIRECTORY
50  -s, --split=MODE               split manual according to MODE. Possible values
51                                 are section and custom (default)
52 """
53
54 def help (text):
55     sys.stdout.write ( text)
56     sys.exit (0)
57
58 outdir = '.'
59 split = "custom"
60 include_path = ['.',]
61 master_map_file = ''
62 initial_map = {}
63 for opt in options_list:
64     o = opt[0]
65     a = opt[1]
66     if o == '-h' or o == '--help':
67         help (help_text % vars ())
68     if o == '-I' or o == '--include':
69         if os.path.isdir (a):
70             include_path.append (a)
71         else:
72             print 'NOT A DIR from: ', os.getcwd (), a
73     elif o == '-o' or o == '--output':
74         outdir = a
75     elif o == '-s' or o == '--split':
76         split = a
77     elif o == '-m' or o == '--master-map-file':
78         if os.path.isfile (a):
79             master_map_file = a
80     else:
81         raise Exception ('unknown option: ' + o)
82
83
84 if not os.path.isdir (outdir):
85     if os.path.exists (outdir):
86         os.unlink (outdir)
87     os.makedirs (outdir)
88
89 include_re = re.compile (r'@include ((?!../lily-).*?\.i?texi)$', re.M)
90 whitespaces = re.compile (r'\s+')
91 section_translation_re = re.compile ('^@(node|(?:unnumbered|appendix)\
92 (?:(?:sub){0,2}sec)?|top|chapter|(?:sub){0,2}section|\
93 (?:major|chap|(?:sub){0,2})heading|lydoctitle|translationof) \
94 (.+)$', re.MULTILINE)
95 external_node_re = re.compile (r'\s+@c\s+external.*')
96
97 def expand_includes (m, filename):
98     include_name = m.group (1)
99     filepath = os.path.join (os.path.dirname (filename), include_name)
100     if os.path.exists (filepath):
101         return extract_sections (filepath)[1]
102     else:
103         for directory in include_path:
104             filepath = os.path.join (directory, include_name)
105             if os.path.exists (filepath):
106                 return extract_sections (filepath)[1]
107         print 'No such file: ' + include_name
108         print 'Search path: ' + ':'.join (include_path)
109         return ''
110
111 lang_re = re.compile (r'^@documentlanguage (.+)', re.M)
112
113 def extract_sections (filename):
114     result = ''
115     f = open (filename, 'r')
116     page = f.read ()
117     f.close()
118     # Search document language
119     m = lang_re.search (page)
120     if m and m.group (1) != 'en':
121         lang_suffix = '.' + m.group (1)
122     else:
123         lang_suffix = ''
124     # Replace all includes by their list of sections and extract all sections
125     page = include_re.sub (lambda m: expand_includes (m, filename), page)
126     sections = section_translation_re.findall (page)
127     for sec in sections:
128         result += "@" + sec[0] + " " + sec[1] + "\n"
129     return (lang_suffix, result)
130
131 # Convert a given node name to its proper file name (normalization as
132 # explained in the texinfo manual:
133 # http://www.gnu.org/software/texinfo/manual/texinfo/html_node/HTML-Xref-Node-Name-Expansion.html
134 def texinfo_file_name(title):
135     # exception: The top node is always mapped to index.html
136     if title == "Top":
137         return "index"
138     # File name normalization by texinfo (described in the texinfo manual):
139     # 1/2: letters and numbers are left unchanged
140     # 3/4: multiple, leading and trailing whitespace is removed
141     title = title.strip ();
142     title = whitespaces.sub (' ', title)
143     # 5:   all remaining spaces are converted to '-'
144     # 6:   all other 7- or 8-bit chars are replaced by _xxxx (xxxx=ascii character code)
145     result = ''
146     for index in range(len(title)):
147         char = title[index]
148         if char == ' ': # space -> '-'
149             result += '-'
150         elif ( ('0' <= char and char <= '9' ) or
151                ('A' <= char and char <= 'Z' ) or
152                ('a' <= char and char <= 'z' ) ):  # number or letter
153             result += char
154         else:
155             ccode = ord(char)
156             if ccode <= 0xFFFF:
157                 result += "_%04x" % ccode
158             else:
159                 result += "__%06x" % ccode
160     # 7: if name begins with number, prepend 't_g' (so it starts with a letter)
161     if (result != '') and (ord(result[0]) in range (ord('0'), ord('9'))):
162         result = 't_g' + result
163     return result
164
165 texinfo_re = re.compile (r'@.*?{(.*?)}')
166 def remove_texinfo (title):
167     title = title.replace ('--', '-')
168     return texinfo_re.sub (r'\1', title).strip ()
169
170 def create_texinfo_anchor (title):
171     return texinfo_file_name (remove_texinfo (title))
172
173 unnumbered_re = re.compile (r'unnumbered.+|lydoctitle')
174 file_name_section_level = {
175     'top': 4,
176     'chapter':3,
177     'unnumbered':3,
178     'appendix':3,
179     'section':2,
180     'unnumberedsec':2,
181     'appendixsec':2,
182     'subsection':1,
183     'unnumberedsubsec':1,
184     'appendixsubsec':1,
185     'subsubsection':0,
186     'unnumberedsubsubsec':0,
187     'appendixsubsubsec':0
188 }
189 if split in file_name_section_level:
190     splitting_level = file_name_section_level[split]
191 else:
192     splitting_level = -1
193 def process_sections (filename, lang_suffix, page):
194     sections = section_translation_re.findall (page)
195     basename = os.path.splitext (os.path.basename (filename))[0]
196     p = os.path.join (outdir, basename) + lang_suffix + '.xref-map'
197     print 'writing:', p
198     f = open (p, 'w')
199
200     this_title = ''
201     this_filename = 'index'
202     this_anchor = ''
203     this_unnumbered = False
204     had_section = False
205     for sec in sections:
206         if sec[0] == "node":
207             # Write out the cached values to the file and start a new
208             # section:
209             if this_title and this_title != 'Top':
210                     f.write (this_title + "\t" + this_filename + "\t" + this_anchor + "\n")
211             had_section = False
212             this_title = remove_texinfo (sec[1])
213             this_anchor = create_texinfo_anchor (sec[1])
214             # delete entry from master map file
215             if this_title in initial_map:
216                 del initial_map[this_title]
217         elif sec[0] == "translationof":
218             (original_node, external_node) = external_node_re.subn ('', sec[1])
219             original_node = remove_texinfo (original_node)
220             # The following binds the translator to use the
221             # translated node name in cross-references in case
222             # it exists
223             if external_node and original_node in initial_map:
224                 del initial_map[original_node]
225             anchor = create_texinfo_anchor (sec[1])
226             # If @translationof is used, it gives the original
227             # node name, which we use for the anchor and the file
228             # name (if it is a numbered node)
229             this_anchor = anchor
230             if not this_unnumbered:
231                 this_filename = anchor
232             elif original_node in initial_map:
233                 this_filename = initial_map[original_node][2]
234         else:
235             # Some pages might not use a node for every section, so
236             # treat this case here, too: If we already had a section
237             # and encounter another one before the next @node, we
238             # write out the old one and start with the new values
239             if had_section and this_title:
240                 f.write (this_title + "\t" + this_filename + "\t" + this_anchor + "\n")
241                 this_title = remove_texinfo (sec[1])
242                 this_anchor = create_texinfo_anchor (sec[1])
243             had_section = True
244
245             if split == 'custom':
246                 # unnumbered nodes use the previously used file name,
247                 # only numbered nodes get their own filename! However,
248                 # top-level @unnumbered still get their own file.
249                 this_unnumbered = unnumbered_re.match (sec[0])
250                 if not this_unnumbered:
251                     this_filename = this_anchor
252             elif split == 'node':
253                 this_filename = this_anchor
254             else:
255                 if sec[0] in file_name_section_level and \
256                         file_name_section_level[sec[0]] >= splitting_level:
257                     this_filename = this_anchor
258
259     if this_title and this_title != 'Top':
260         f.write (this_title + "\t" + this_filename + "\t" + this_anchor + "\n")
261
262     for node in initial_map:
263         f.write ("\t".join (initial_map[node]) + "\n")
264     f.close ()
265
266 xref_map_line_re = re.compile (r'(.*?)\t(.*?)\t(.*?)$')
267 if master_map_file:
268     for line in open (master_map_file):
269         m = xref_map_line_re.match (line)
270         if m:
271             initial_map[m.group (1)] = (m.group (1), m.group (2), m.group (3))
272
273 for filename in files:
274     print "extract_texi_filenames.py: Processing %s" % filename
275     (lang_suffix, sections) = extract_sections (filename)
276     process_sections (filename, lang_suffix, sections)