3 # gtk-doc - GTK DocBook documentation generator.
4 # Copyright (C) 1998 Damon Chaplin
5 # 2007-2016 Stefan Sauer
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 ''"Fix cross-references in the HTML documentation.''"
31 from . import common
, config
33 # This contains all the entities and their relative URLs.
36 # failing link targets we don't warn about even once
54 # Cache of dirs we already scanned for index files
59 #logging.basicConfig(level=logging.INFO)
62 m
= re
.search(r
'(.*?)/share/gtk-doc/html', options
.html_dir
)
64 path_prefix
= m
.group(1)
65 logging
.info('Path prefix: %s', path_prefix
)
66 prefix_match
= r
'^' + re
.escape(path_prefix
) + r
'/'
68 # We scan the directory containing GLib and any directories in GNOME2_PATH
69 # first, but these will be overriden by any later scans.
70 dir = common
.GetModuleDocDir('glib-2.0')
71 if os
.path
.exists(dir):
72 # Some predefined link targets to get links into type hierarchies as these
73 # have no targets. These are always absolute for now.
74 Links
['GBoxed'] = dir + '/gobject/gobject-Boxed-Types.html'
75 Links
['GEnum'] = dir + '/gobject/gobject-Enumeration-and-Flag-Types.html'
76 Links
['GFlags'] = dir + '/gobject/gobject-Enumeration-and-Flag-Types.html'
77 Links
['GInterface'] = dir + '/gobject/GTypeModule.html'
79 if dir != options
.html_dir
:
80 logging
.info('Scanning GLib directory: %s', dir)
81 ScanIndices(dir, (re
.search(prefix_match
, dir) is None))
83 path
= os
.environ
.get('GNOME2_PATH')
85 for dir in path
.split(':'):
86 dir += '/share/gtk-doc/html'
87 if os
.path
.exists(dir) and dir != options
.html_dir
:
88 logging
.info('Scanning GNOME2_PATH directory: %s', dir)
89 ScanIndices(dir, (re
.search(prefix_match
, dir) is None))
91 logging
.info('Scanning HTML_DIR directory: %s', options
.html_dir
)
92 ScanIndices(options
.html_dir
, 0)
93 logging
.info('Scanning MODULE_DIR directory: %s', options
.module_dir
)
94 ScanIndices(options
.module_dir
, 0)
96 # check all extra dirs, but skip already scanned dirs or subdirs of those
97 for dir in options
.extra_dir
:
99 logging
.info('Scanning EXTRA_DIR directory: %s', dir)
101 # If the --extra-dir option is not relative and is not sharing the same
102 # prefix as the target directory of the docs, we need to use absolute
103 # directories for the links
104 if not dir.startswith('..') and re
.search(prefix_match
, dir) is None:
109 ReadSections(options
)
110 FixCrossReferences(options
)
113 def ScanIndices(scan_dir
, use_absolute_links
):
114 if not scan_dir
or scan_dir
in DirCache
:
116 DirCache
[scan_dir
] = 1
118 logging
.info('Scanning index directory: %s, absolute: %d', scan_dir
, use_absolute_links
)
120 # This array holds any subdirectories found.
123 # TODO(ensonic): this code is the same as in rebase.py
124 for entry
in os
.listdir(scan_dir
):
125 full_entry
= os
.path
.join(scan_dir
, entry
)
126 if os
.path
.isdir(full_entry
):
127 subdirs
.append(full_entry
)
130 if entry
.endswith('.devhelp2'):
131 # if devhelp-file is good don't read index.sgml
132 ReadDevhelp(full_entry
, use_absolute_links
)
133 elif entry
== "index.sgml.gz" and not os
.path
.exists(os
.path
.join(scan_dir
, 'index.sgml')):
134 # debian/ubuntu started to compress this as index.sgml.gz :/
135 print(''' Please fix https://bugs.launchpad.net/ubuntu/+source/gtk-doc/+bug/77138 . For now run:
138 elif entry
.endswith('.devhelp2.gz') and not os
.path
.exists(full_entry
[:-3]):
139 # debian/ubuntu started to compress this as *devhelp2.gz :/
140 print('''Please fix https://bugs.launchpad.net/ubuntu/+source/gtk-doc/+bug/1466210 . For now run:
143 # we could consider supporting: gzip module
145 # Now recursively scan the subdirectories.
146 for subdir
in subdirs
:
147 ScanIndices(subdir
, use_absolute_links
)
150 def ReadDevhelp(file, use_absolute_links
):
151 # Determine the absolute directory, to be added to links in $file
152 # if we need to use an absolute link.
153 # $file will be something like /prefix/gnome/share/gtk-doc/html/gtk/$file
154 # We want the part up to 'html/.*' since the links in $file include
157 if use_absolute_links
:
158 # For uninstalled index files we'd need to map the path to where it
159 # will be installed to
160 if not file.startswith('./'):
161 m
= re
.search(r
'(.*\/)(.*?)\/.*?\.devhelp2', file)
162 dir = m
.group(1) + m
.group(2) + '/'
164 m
= re
.search(r
'(.*\/)(.*?)\/.*?\.devhelp2', file)
166 dir += m
.group(2) + '/'
170 logging
.info('Scanning index file=%s, absolute=%d, dir=%s', file, use_absolute_links
, dir)
172 for line
in open(file):
173 m
= re
.search(r
' link="([^#]*)#([^"]*)"', line
)
175 link
= m
.group(1) + '#' + m
.group(2)
176 logging
.debug('Found id: %s href: %s', m
.group(2), link
)
177 Links
[m
.group(2)] = dir + link
180 def ReadSections(options
):
181 for line
in open(options
.module
+ '-sections.txt'):
182 m1
= re
.search('^<SUBSECTION\s*(.*)>', line
)
183 if line
.startswith('#') or line
.strip() == '':
185 elif line
.startswith('<SECTION>'):
188 subsection
= m1
.group(1)
189 elif line
.startswith('<SUBSECTION>') or line
.startswith('<\/SECTION>'):
191 elif re
.search(r
'^<TITLE>(.*)<\/TITLE>', line
):
193 elif re
.search(r
'^<FILE>(.*)<\/FILE>', line
):
195 elif re
.search(r
'^<INCLUDE>(.*)<\/INCLUDE>', line
):
198 symbol
= line
.strip()
199 if subsection
== "Standard" or subsection
== "Private":
200 NoLinks
.add(common
.CreateValidSGMLID(symbol
))
203 def FixCrossReferences(options
):
204 scan_dir
= options
.module_dir
205 # TODO(ensonic): use glob.glob()?
206 for entry
in os
.listdir(scan_dir
):
207 full_entry
= os
.path
.join(scan_dir
, entry
)
208 if os
.path
.isdir(full_entry
):
210 elif entry
.endswith('.html') or entry
.endswith('.htm'):
211 FixHTMLFile(options
, full_entry
)
214 def FixHTMLFile(options
, file):
215 logging
.info('Fixing file: %s', file)
217 content
= open(file).read()
220 # FIXME: ideally we'd pass a clue about the example language to the highligher
221 # unfortunately the "language" attribute is not appearing in the html output
222 # we could patch the customization to have <code class="xxx"> inside of <pre>
223 if config
.highlight
.endswith('vim'):
225 return HighlightSourceVim(options
, m
.group(1), m
.group(2))
227 r
'<div class=\"(example-contents|informalexample)\"><pre class=\"programlisting\">(.*?)</pre></div>',
228 repl_func
, content
, flags
=re
.DOTALL
)
231 return HighlightSource(options
, m
.group(1), m
.group(2))
233 r
'<div class=\"(example-contents|informalexample)\"><pre class=\"programlisting\">(.*?)</pre></div>',
234 repl_func
, content
, flags
=re
.DOTALL
)
236 content
= re
.sub(r
'\<GTKDOCLINK\s+HREF=\"(.*?)\"\>(.*?)\</GTKDOCLINK\>',
237 r
'\<GTKDOCLINK\ HREF=\"\1\"\>\2\</GTKDOCLINK\>', content
, flags
=re
.DOTALL
)
239 # From the highlighter we get all the functions marked up. Now we can turn them into GTKDOCLINK items
241 return MakeGtkDocLink(m
.group(1), m
.group(2), m
.group(3))
242 content
= re
.sub(r
'(<span class=\"function\">)(.*?)(</span>)', repl_func
, content
, flags
=re
.DOTALL
)
243 # We can also try the first item in stuff marked up as 'normal'
245 r
'(<span class=\"normal\">\s*)(.+?)((\s+.+?)?\s*</span>)', repl_func
, content
, flags
=re
.DOTALL
)
247 lines
= content
.rstrip().split('\n')
249 def repl_func_with_ix(i
):
251 return MakeXRef(options
, file, i
+ 1, m
.group(1), m
.group(2))
254 for i
in range(len(lines
)):
255 lines
[i
] = re
.sub(r
'<GTKDOCLINK\s+HREF="([^"]*)"\s*>(.*?)</GTKDOCLINK\s*>', repl_func_with_ix(i
), lines
[i
])
256 if 'GTKDOCLINK' in lines
[i
]:
257 logging
.info('make xref failed for line %d: "%s"', i
, lines
[i
])
259 new_file
= file + '.new'
260 open(new_file
, 'w').write('\n'.join(lines
))
263 os
.rename(new_file
, file)
266 def MakeXRef(options
, file, line
, id, text
):
269 # This is a workaround for some inconsistency we have with CreateValidSGMLID
270 if not href
and ':' in id:
271 href
= Links
.get(id.replace(':', '--'))
272 # poor mans plural support
273 if not href
and id.endswith('s'):
275 href
= Links
.get(tid
)
277 href
= Links
.get(tid
+ '-struct')
279 href
= Links
.get(id + '-struct')
282 # if it is a link to same module, remove path to make it work uninstalled
283 m
= re
.search(r
'^\.\./' + options
.module
+ '/(.*)$', href
)
286 logging
.info('Fixing link to uninstalled doc: %s, %s, %s', id, href
, text
)
288 logging
.info('Fixing link: %s, %s, %s', id, href
, text
)
289 return "<a href=\"%s\">%s</a>" % (href
, text
)
291 logging
.info('no link for: %s, %s', id, text
)
293 # don't warn multiple times and also skip blacklisted (ctypes)
296 # if it's a function, don't warn if it does not contain a "_"
297 # (transformed to "-")
298 # - gnome coding style would use '_'
299 # - will avoid wrong warnings for ansi c functions
300 if re
.search(r
' class=\"function\"', text
) and '-' not in id:
302 # if it's a 'return value', don't warn (implicitly created link)
303 if re
.search(r
' class=\"returnvalue\"', text
):
305 # if it's a 'type', don't warn if it starts with lowercase
306 # - gnome coding style would use CamelCase
307 if re
.search(r
' class=\"type\"', text
) and id[0].islower():
309 # don't warn for self links
313 common
.LogWarning(file, line
, 'no link for: "%s" -> (%s).' % (id, text
))
318 def MakeGtkDocLink(pre
, symbol
, post
):
319 id = common
.CreateValidSGMLID(symbol
)
321 # these are implicitely created links in highlighed sources
322 # we don't want warnings for those if the links cannot be resolved.
325 return pre
+ '<GTKDOCLINK HREF="' + id + '">' + symbol
+ '</GTKDOCLINK>' + post
328 def HighlightSource(options
, type, source
):
329 source
= HighlightSourcePreProcess(source
)
331 # write source to a temp file
332 # FIXME: use .c for now to hint the language to the highlighter
333 with tempfile
.NamedTemporaryFile(suffix
='.c') as f
:
336 temp_source_file
= f
.name
337 highlight_options
= config
.highlight_options
.replace('$SRC_LANG', options
.src_lang
)
339 logging
.info('running %s %s %s', config
.highlight
, highlight_options
, temp_source_file
)
342 highlighted_source
= subprocess
.check_output(
343 [config
.highlight
] + shlex
.split(highlight_options
) + [temp_source_file
])
344 logging
.debug('result: [%s]', highlighted_source
)
345 if config
.highlight
.endswith('/source-highlight'):
346 highlighted_source
= re
.sub(r
'^<\!-- .*? -->', '', highlighted_source
, flags
=re
.MULTILINE | re
.DOTALL
)
347 highlighted_source
= re
.sub(
348 r
'<pre><tt>(.*?)</tt></pre>', r
'\1', highlighted_source
, flags
=re
.MULTILINE | re
.DOTALL
)
349 elif config
.highlight
.endswith('/highlight'):
350 # need to rewrite the stylesheet classes
351 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc com">', '<span class="comment">')
352 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc dir">', '<span class="preproc">')
353 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc kwd">', '<span class="function">')
354 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc kwa">', '<span class="keyword">')
355 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc line">', '<span class="linenum">')
356 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc num">', '<span class="number">')
357 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc str">', '<span class="string">')
358 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc sym">', '<span class="symbol">')
360 # highlighted_source = re.sub(r'</span>(.+)<span', '</span><span class="normal">\1</span><span')
362 return HighlightSourcePostprocess(type, highlighted_source
)
365 def HighlightSourceVim(options
, type, source
):
366 source
= HighlightSourcePreProcess(source
)
368 # write source to a temp file
369 with tempfile
.NamedTemporaryFile(suffix
='.h') as f
:
372 temp_source_file
= f
.name
375 # TODO(ensonic): use p.communicate()
376 script
= "echo 'let html_number_lines=0|let html_use_css=1|let html_use_xhtml=1|e %s|syn on|set syntax=%s|run! syntax/2html.vim|w! %s.html|qa!' | " % (
377 temp_source_file
, options
.src_lang
, temp_source_file
)
378 script
+= "%s -n -e -u NONE -T xterm >/dev/null" % config
.highlight
379 subprocess
.check_call([script
], shell
=True)
381 highlighted_source
= open(temp_source_file
+ ".html").read()
382 highlighted_source
= re
.sub(r
'.*<pre\b[^>]*>\n', '', highlighted_source
, flags
=re
.MULTILINE
)
383 highlighted_source
= re
.sub(r
'</pre>.*', '', highlighted_source
, flags
=re
.MULTILINE
)
385 # need to rewrite the stylesheet classes
386 highlighted_source
= highlighted_source
.replace('<span class="Comment">', '<span class="comment">')
387 highlighted_source
= highlighted_source
.replace('<span class="PreProc">', '<span class="preproc">')
388 highlighted_source
= highlighted_source
.replace('<span class="Statement">', '<span class="keyword">')
389 highlighted_source
= highlighted_source
.replace('<span class="Identifier">', '<span class="function">')
390 highlighted_source
= highlighted_source
.replace('<span class="Constant">', '<span class="number">')
391 highlighted_source
= highlighted_source
.replace('<span class="Special">', '<span class="symbol">')
392 highlighted_source
= highlighted_source
.replace('<span class="Type">', '<span class="type">')
395 os
.unlink(temp_source_file
+ '.html')
397 return HighlightSourcePostprocess(type, highlighted_source
)
400 def HighlightSourcePreProcess(source
):
401 # chop of leading and trailing empty lines, leave leading space in first real line
402 source
= source
.strip(' ')
403 source
= source
.strip('\n')
404 source
= source
.rstrip()
407 m
= re
.search(r
'^(\s+)', source
)
409 source
= re
.sub(r
'^' + m
.group(1), '', source
, flags
=re
.MULTILINE
)
410 # avoid double entity replacement
411 source
= source
.replace('<', '<')
412 source
= source
.replace('>', '>')
413 source
= source
.replace('&', '&')
417 def HighlightSourcePostprocess(type, highlighted_source
):
418 # chop of leading and trailing empty lines
419 highlighted_source
= highlighted_source
.strip()
421 # turn common urls in comments into links
422 highlighted_source
= re
.sub(r
'<span class="url">(.*?)</span>',
423 r
'<span class="url"><a href="\1">\1</a></span>',
424 highlighted_source
, flags
=re
.DOTALL
)
426 # we do own line-numbering
427 line_count
= highlighted_source
.count('\n')
428 source_lines
= '\n'.join([str(i
) for i
in range(1, line_count
+ 2)])
430 return """<div class="%s">
431 <table class="listing_frame" border="0" cellpadding="0" cellspacing="0">
434 <td class="listing_lines" align="right"><pre>%s</pre></td>
435 <td class="listing_code"><pre class="programlisting">%s</pre></td>
440 """ % (type, source_lines
, highlighted_source
)