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.''"
24 # Support both Python 2 and 3
25 from __future__
import print_function
35 from . import common
, config
37 # This contains all the entities and their relative URLs.
40 # failing link targets we don't warn about even once
60 logging
.info('options: %s', str(options
.__dict
__))
62 LoadIndicies(options
.module_dir
, options
.html_dir
, options
.extra_dir
)
63 ReadSections(options
.module
)
64 FixCrossReferences(options
.module_dir
, options
.module
, options
.src_lang
)
67 # TODO(ensonic): try to refactor so that we get a list of path's and then just
69 # - module_dir is by default 'html'
70 # - html_dir can be set by configure, but is usually empty
71 def LoadIndicies(module_dir
, html_dir
, extra_dirs
):
72 # Cache of dirs we already scanned for index files
76 m
= re
.search(r
'(.*?)/share/gtk-doc/html', html_dir
)
78 path_prefix
= m
.group(1)
79 logging
.info('Path prefix: %s', path_prefix
)
80 prefix_match
= r
'^' + re
.escape(path_prefix
) + r
'/'
82 # We scan the directory containing GLib and any directories in GNOME2_PATH
83 # first, but these will be overriden by any later scans.
84 dir = common
.GetModuleDocDir('glib-2.0')
85 if dir and os
.path
.exists(dir):
86 # Some predefined link targets to get links into type hierarchies as these
87 # have no targets. These are always absolute for now.
88 Links
['GBoxed'] = dir + '/gobject/gobject-Boxed-Types.html'
89 Links
['GEnum'] = dir + '/gobject/gobject-Enumeration-and-Flag-Types.html'
90 Links
['GFlags'] = dir + '/gobject/gobject-Enumeration-and-Flag-Types.html'
91 Links
['GInterface'] = dir + '/gobject/GTypeModule.html'
94 logging
.info('Scanning GLib directory: %s', dir)
95 ScanIndices(dir, (re
.search(prefix_match
, dir) is None), dir_cache
)
97 path
= os
.environ
.get('GNOME2_PATH')
99 for dir in path
.split(':'):
100 dir += 'share/gtk-doc/html'
101 if os
.path
.exists(dir) and dir != html_dir
:
102 logging
.info('Scanning GNOME2_PATH directory: %s', dir)
103 ScanIndices(dir, (re
.search(prefix_match
, dir) is None), dir_cache
)
105 logging
.info('Scanning HTML_DIR directory: %s', html_dir
)
106 ScanIndices(html_dir
, False, dir_cache
)
107 logging
.info('Scanning MODULE_DIR directory: %s', module_dir
)
108 ScanIndices(module_dir
, False, dir_cache
)
110 # check all extra dirs, but skip already scanned dirs or subdirs of those
111 for dir in extra_dirs
:
112 dir = dir.rstrip('/')
113 logging
.info('Scanning EXTRA_DIR directory: %s', dir)
115 # If the --extra-dir option is not relative and is not sharing the same
116 # prefix as the target directory of the docs, we need to use absolute
117 # directories for the links
118 if not dir.startswith('..') and re
.search(prefix_match
, dir) is None:
119 ScanIndices(dir, True, dir_cache
)
121 ScanIndices(dir, False, dir_cache
)
124 def ScanIndices(scan_dir
, use_absolute_links
, dir_cache
):
125 if not scan_dir
or scan_dir
in dir_cache
:
127 dir_cache
[scan_dir
] = 1
129 logging
.info('Scanning index directory: %s, absolute: %d', scan_dir
, use_absolute_links
)
131 # TODO(ensonic): this code is the same as in rebase.py
132 if not os
.path
.isdir(scan_dir
):
133 logging
.info('Cannot open dir "%s"', scan_dir
)
137 for entry
in sorted(os
.listdir(scan_dir
)):
138 full_entry
= os
.path
.join(scan_dir
, entry
)
139 if os
.path
.isdir(full_entry
):
140 subdirs
.append(full_entry
)
143 if entry
.endswith('.devhelp2'):
144 # if devhelp-file is good don't read index.sgml
145 ReadDevhelp(full_entry
, use_absolute_links
)
146 elif entry
== "index.sgml.gz" and not os
.path
.exists(os
.path
.join(scan_dir
, 'index.sgml')):
147 # debian/ubuntu started to compress this as index.sgml.gz :/
148 print(''' Please fix https://bugs.launchpad.net/ubuntu/+source/gtk-doc/+bug/77138 . For now run:
151 elif entry
.endswith('.devhelp2.gz') and not os
.path
.exists(full_entry
[:-3]):
152 # debian/ubuntu started to compress this as *devhelp2.gz :/
153 print('''Please fix https://bugs.launchpad.net/ubuntu/+source/gtk-doc/+bug/1466210 . For now run:
156 # we could consider supporting: gzip module
158 # Now recursively scan the subdirectories.
159 for subdir
in subdirs
:
160 ScanIndices(subdir
, use_absolute_links
, dir_cache
)
163 def ReadDevhelp(file, use_absolute_links
):
164 # Determine the absolute directory, to be added to links in $file
165 # if we need to use an absolute link.
166 # $file will be something like /prefix/gnome/share/gtk-doc/html/gtk/$file
167 # We want the part up to 'html/.*' since the links in $file include
170 if use_absolute_links
:
171 # For uninstalled index files we'd need to map the path to where it
172 # will be installed to
173 if not file.startswith('./'):
174 m
= re
.search(r
'(.*\/)(.*?)\/.*?\.devhelp2', file)
175 dir = m
.group(1) + m
.group(2) + '/'
177 m
= re
.search(r
'(.*\/)(.*?)\/.*?\.devhelp2', file)
179 dir += m
.group(2) + '/'
183 logging
.info('Scanning index file=%s, absolute=%d, dir=%s', file, use_absolute_links
, dir)
185 for line
in common
.open_text(file):
186 m
= re
.search(r
' link="([^#]*)#([^"]*)"', line
)
188 link
= m
.group(1) + '#' + m
.group(2)
189 logging
.debug('Found id: %s href: %s', m
.group(2), link
)
190 Links
[m
.group(2)] = dir + link
193 def ReadSections(module
):
194 """We don't warn on missing links to non-public sysmbols."""
195 for line
in common
.open_text(module
+ '-sections.txt'):
196 m1
= re
.search(r
'^<SUBSECTION\s*(.*)>', line
)
197 if line
.startswith('#') or line
.strip() == '':
199 elif line
.startswith('<SECTION>'):
202 subsection
= m1
.group(1)
203 elif line
.startswith('<SUBSECTION>') or line
.startswith('</SECTION>'):
205 elif re
.search(r
'^<TITLE>(.*)<\/TITLE>', line
):
207 elif re
.search(r
'^<FILE>(.*)<\/FILE>', line
):
209 elif re
.search(r
'^<INCLUDE>(.*)<\/INCLUDE>', line
):
212 symbol
= line
.strip()
213 if subsection
== "Standard" or subsection
== "Private":
214 NoLinks
.add(common
.CreateValidSGMLID(symbol
))
217 def FixCrossReferences(module_dir
, module
, src_lang
):
218 # TODO(ensonic): use glob.glob()?
219 for entry
in sorted(os
.listdir(module_dir
)):
220 full_entry
= os
.path
.join(module_dir
, entry
)
221 if os
.path
.isdir(full_entry
):
223 elif entry
.endswith('.html') or entry
.endswith('.htm'):
224 FixHTMLFile(src_lang
, module
, full_entry
)
227 def FixHTMLFile(src_lang
, module
, file):
228 logging
.info('Fixing file: %s', file)
230 content
= common
.open_text(file).read()
233 # FIXME: ideally we'd pass a clue about the example language to the highligher
234 # unfortunately the "language" attribute is not appearing in the html output
235 # we could patch the customization to have <code class="xxx"> inside of <pre>
236 if config
.highlight
.endswith('vim'):
238 return HighlightSourceVim(src_lang
, m
.group(1), m
.group(2))
240 r
'<div class=\"(example-contents|informalexample)\"><pre class=\"programlisting\">(.*?)</pre></div>',
241 repl_func
, content
, flags
=re
.DOTALL
)
244 return HighlightSource(src_lang
, m
.group(1), m
.group(2))
246 r
'<div class=\"(example-contents|informalexample)\"><pre class=\"programlisting\">(.*?)</pre></div>',
247 repl_func
, content
, flags
=re
.DOTALL
)
249 content
= re
.sub(r
'\<GTKDOCLINK\s+HREF=\"(.*?)\"\>(.*?)\</GTKDOCLINK\>',
250 r
'\<GTKDOCLINK\ HREF=\"\1\"\>\2\</GTKDOCLINK\>', content
, flags
=re
.DOTALL
)
252 # From the highlighter we get all the functions marked up. Now we can turn them into GTKDOCLINK items
254 return MakeGtkDocLink(m
.group(1), m
.group(2), m
.group(3))
255 content
= re
.sub(r
'(<span class=\"function\">)(.*?)(</span>)', repl_func
, content
, flags
=re
.DOTALL
)
256 # We can also try the first item in stuff marked up as 'normal'
258 r
'(<span class=\"normal\">\s*)(.+?)((\s+.+?)?\s*</span>)', repl_func
, content
, flags
=re
.DOTALL
)
260 lines
= content
.rstrip().split('\n')
262 def repl_func_with_ix(i
):
264 return MakeXRef(module
, file, i
+ 1, m
.group(1), m
.group(2))
267 for i
in range(len(lines
)):
268 lines
[i
] = re
.sub(r
'<GTKDOCLINK\s+HREF="([^"]*)"\s*>(.*?)</GTKDOCLINK\s*>', repl_func_with_ix(i
), lines
[i
])
269 if 'GTKDOCLINK' in lines
[i
]:
270 logging
.info('make xref failed for line %d: "%s"', i
, lines
[i
])
272 new_file
= file + '.new'
273 content
= '\n'.join(lines
)
274 with common
.open_text(new_file
, 'w') as h
:
278 os
.rename(new_file
, file)
281 def MakeXRef(module
, file, line
, id, text
):
284 # This is a workaround for some inconsistency we have with CreateValidSGMLID
285 if not href
and ':' in id:
286 href
= Links
.get(id.replace(':', '--'))
287 # poor mans plural support
288 if not href
and id.endswith('s'):
290 href
= Links
.get(tid
)
292 href
= Links
.get(tid
+ '-struct')
294 href
= Links
.get(id + '-struct')
297 # if it is a link to same module, remove path to make it work uninstalled
298 m
= re
.search(r
'^\.\./' + module
+ '/(.*)$', href
)
301 logging
.info('Fixing link to uninstalled doc: %s, %s, %s', id, href
, text
)
303 logging
.info('Fixing link: %s, %s, %s', id, href
, text
)
304 return "<a href=\"%s\">%s</a>" % (href
, text
)
306 logging
.info('no link for: %s, %s', id, text
)
308 # don't warn multiple times and also skip blacklisted (ctypes)
311 # if it's a function, don't warn if it does not contain a "_"
312 # (transformed to "-")
313 # - gnome coding style would use '_'
314 # - will avoid wrong warnings for ansi c functions
315 if re
.search(r
' class=\"function\"', text
) and '-' not in id:
317 # if it's a 'return value', don't warn (implicitly created link)
318 if re
.search(r
' class=\"returnvalue\"', text
):
320 # if it's a 'type', don't warn if it starts with lowercase
321 # - gnome coding style would use CamelCase
322 if re
.search(r
' class=\"type\"', text
) and id[0].islower():
324 # don't warn for self links
328 common
.LogWarning(file, line
, 'no link for: "%s" -> (%s).' % (id, text
))
333 def MakeGtkDocLink(pre
, symbol
, post
):
334 id = common
.CreateValidSGMLID(symbol
)
336 # these are implicitely created links in highlighed sources
337 # we don't want warnings for those if the links cannot be resolved.
340 return pre
+ '<GTKDOCLINK HREF="' + id + '">' + symbol
+ '</GTKDOCLINK>' + post
343 def HighlightSource(src_lang
, type, source
):
344 # write source to a temp file
345 # FIXME: use .c for now to hint the language to the highlighter
346 with tempfile
.NamedTemporaryFile(mode
='w+', suffix
='.c') as f
:
347 temp_source_file
= HighlightSourcePreProcess(f
, source
)
348 highlight_options
= config
.highlight_options
.replace('$SRC_LANG', src_lang
)
350 logging
.info('running %s %s %s', config
.highlight
, highlight_options
, temp_source_file
)
353 highlighted_source
= subprocess
.check_output(
354 [config
.highlight
] + shlex
.split(highlight_options
) + [temp_source_file
]).decode('utf-8')
355 logging
.debug('result: [%s]', highlighted_source
)
356 if config
.highlight
.endswith('/source-highlight'):
357 highlighted_source
= re
.sub(r
'^<\!-- .*? -->', '', highlighted_source
, flags
=re
.MULTILINE | re
.DOTALL
)
358 highlighted_source
= re
.sub(
359 r
'<pre><tt>(.*?)</tt></pre>', r
'\1', highlighted_source
, flags
=re
.MULTILINE | re
.DOTALL
)
360 elif config
.highlight
.endswith('/highlight'):
361 # need to rewrite the stylesheet classes
362 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc com">', '<span class="comment">')
363 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc dir">', '<span class="preproc">')
364 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc kwd">', '<span class="function">')
365 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc kwa">', '<span class="keyword">')
366 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc line">', '<span class="linenum">')
367 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc num">', '<span class="number">')
368 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc str">', '<span class="string">')
369 highlighted_source
= highlighted_source
.replace('<span class="gtkdoc sym">', '<span class="symbol">')
371 # highlighted_source = re.sub(r'</span>(.+)<span', '</span><span class="normal">\1</span><span')
373 return HighlightSourcePostprocess(type, highlighted_source
)
376 def HighlightSourceVim(src_lang
, type, source
):
377 # write source to a temp file
378 with tempfile
.NamedTemporaryFile(mode
='w+', suffix
='.h') as f
:
379 temp_source_file
= HighlightSourcePreProcess(f
, source
)
382 # TODO(ensonic): use p.communicate()
383 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! plugin/tohtml.vim|run! syntax/2html.vim|w! %s.html|qa!' | " % (
384 temp_source_file
, src_lang
, temp_source_file
)
385 script
+= "%s -n -e -u NONE -T xterm >/dev/null" % config
.highlight
386 subprocess
.check_call([script
], shell
=True)
388 highlighted_source
= common
.open_text(temp_source_file
+ ".html").read()
389 highlighted_source
= re
.sub(r
'.*<pre\b[^>]*>\n', '', highlighted_source
, flags
=re
.DOTALL
)
390 highlighted_source
= re
.sub(r
'</pre>.*', '', highlighted_source
, flags
=re
.DOTALL
)
392 # need to rewrite the stylesheet classes
393 highlighted_source
= highlighted_source
.replace('<span class="Comment">', '<span class="comment">')
394 highlighted_source
= highlighted_source
.replace('<span class="PreProc">', '<span class="preproc">')
395 highlighted_source
= highlighted_source
.replace('<span class="Statement">', '<span class="keyword">')
396 highlighted_source
= highlighted_source
.replace('<span class="Identifier">', '<span class="function">')
397 highlighted_source
= highlighted_source
.replace('<span class="Constant">', '<span class="number">')
398 highlighted_source
= highlighted_source
.replace('<span class="Special">', '<span class="symbol">')
399 highlighted_source
= highlighted_source
.replace('<span class="Type">', '<span class="type">')
402 os
.unlink(temp_source_file
+ '.html')
404 return HighlightSourcePostprocess(type, highlighted_source
)
407 def HighlightSourcePreProcess(f
, source
):
408 # chop of leading and trailing empty lines, leave leading space in first real line
409 source
= source
.strip(' ')
410 source
= source
.strip('\n')
411 source
= source
.rstrip()
414 m
= re
.search(r
'^(\s+)', source
)
416 source
= re
.sub(r
'^' + m
.group(1), '', source
, flags
=re
.MULTILINE
)
417 # avoid double entity replacement
418 source
= source
.replace('<', '<')
419 source
= source
.replace('>', '>')
420 source
= source
.replace('&', '&')
421 if sys
.version_info
< (3,):
422 source
= source
.encode('utf-8')
428 def HighlightSourcePostprocess(type, highlighted_source
):
429 # chop of leading and trailing empty lines
430 highlighted_source
= highlighted_source
.strip()
432 # turn common urls in comments into links
433 highlighted_source
= re
.sub(r
'<span class="url">(.*?)</span>',
434 r
'<span class="url"><a href="\1">\1</a></span>',
435 highlighted_source
, flags
=re
.DOTALL
)
437 # we do own line-numbering
438 line_count
= highlighted_source
.count('\n')
439 source_lines
= '\n'.join([str(i
) for i
in range(1, line_count
+ 2)])
441 return """<div class="%s">
442 <table class="listing_frame" border="0" cellpadding="0" cellspacing="0">
445 <td class="listing_lines" align="right"><pre>%s</pre></td>
446 <td class="listing_code"><pre class="programlisting">%s</pre></td>
451 """ % (type, source_lines
, highlighted_source
)