sphinx / sphinx / application.py

georg.brandl b6419f2 








Georg Brandl b1f4b33 
Georg Brandl 4da052f 
georg.brandl b6419f2 

Jon Waltman d42e859 
georg.brandl b6419f2 
Georg Brandl 87942dc 
georg.brandl be09cf0 
Georg Brandl 368101c 
Georg Brandl 39d715b 
georg.brandl b6419f2 

Georg Brandl 9585f5e 
Georg Brandl 8d2c161 
georg.brandl b6419f2 
Georg Brandl 0fb98f9 
Georg Brandl 09f635e 
Georg Brandl 168a597 
Georg Brandl 0fb98f9 
Georg Brandl 220b8f9 

Georg Brandl a326842 
Georg Brandl 7bed376 
Georg Brandl 05f5a14 
Georg Brandl 09f635e 
Georg Brandl 82e931f 
Georg Brandl 25e024b 
Georg Brandl 84cc1f7 
Georg Brandl 0fb98f9 


georg.brandl d15124c 
georg.brandl b6419f2 
georg.brandl 28bcd32 
Georg Brandl 2936033 
Georg Brandl d51d271 
georg.brandl 0e9311b 
georg.brandl 95aa251 



Georg Brandl ca968dd 
georg.brandl c604e42 
georg.brandl be09cf0 
georg.brandl b6419f2 

georg.brandl cbc5331 
Georg Brandl 09f635e 
georg.brandl cbc5331 
Georg Brandl cc3d24f 
georg.brandl f07e28f 
georg.brandl b6419f2 
georg.brandl 5518267 
Georg Brandl 1de873c 
Jon Waltman 0854f1f 

georg.brandl b6419f2 
Georg Brandl bf713a8 
georg.brandl b6419f2 
Georg Brandl a326842 
Georg Brandl 254e0ff 
georg.brandl b6419f2 
Georg Brandl 09f635e 
georg.brandl b6419f2 
georg.brandl 0a71b9b 



georg.brandl b6419f2 
Georg Brandl 39d715b 





Georg Brandl 604814c 
Georg Brandl 39d715b 



georg.brandl 156653d 
Georg Brandl 604814c 
georg.brandl b6419f2 
georg.brandl d15124c 

gbrandl 90680c1 
Georg Brandl 2a7cd94 
gbrandl 90680c1 
Georg Brandl 39d715b 


georg.brandl b6419f2 
Georg Brandl 25e024b 
Georg Brandl 1de873c 

Georg Brandl 2a22e62 
georg.brandl b6419f2 
Georg Brandl 5dd3800 




Georg Brandl 9ce528f 


georg.brandl e5cba7b 
georg.brandl b6419f2 
georg.brandl a2afdae 
georg.brandl e5cba7b 
georg.brandl a2afdae 
georg.brandl b6419f2 
georg.brandl baddbcf 


Georg Brandl 220b8f9 






Georg Brandl 09f635e 







Georg Brandl d3456c0 

Georg Brandl 09f635e 




















Georg Brandl a326842 

Georg Brandl 09f635e 




Georg Brandl e2283da 
Georg Brandl a326842 
Georg Brandl e2283da 
Georg Brandl a326842 
Georg Brandl 09f635e 

Georg Brandl 29ba4e4 
Georg Brandl 09f635e 


Georg Brandl e2283da 

Georg Brandl 09f635e 


georg.brandl b6419f2 
Georg Brandl 09f635e 
georg.brandl b6419f2 

georg.brandl be09cf0 
georg.brandl b6419f2 

Georg Brandl 254e0ff 




Georg Brandl 09f635e 
georg.brandl b6419f2 

Georg Brandl 1de873c 
georg.brandl be09cf0 
Georg Brandl 1de873c 
georg.brandl be09cf0 





Jon Waltman d42e859 



georg.brandl be09cf0 



Georg Brandl 173e187 
georg.brandl be09cf0 
Jon Waltman 0854f1f 










Georg Brandl dc495b6 
Georg Brandl 19275b6 





Georg Brandl ff4b97a 

Georg Brandl 604814c 
Georg Brandl ff4b97a 
georg.brandl 156653d 
Jon Waltman 0854f1f 
georg.brandl b6419f2 

Jon Waltman 0854f1f 














georg.brandl b6419f2 



Georg Brandl bf713a8 
Jon Waltman 0854f1f 
Georg Brandl bf713a8 

georg.brandl b6419f2 


Georg Brandl d833bd2 

Georg Brandl 4c7414d 



Georg Brandl 220b8f9 







Georg Brandl bf713a8 
georg.brandl b6419f2 
Georg Brandl 220b8f9 




georg.brandl b6419f2 





Georg Brandl d833bd2 

georg.brandl b6419f2 



Georg Brandl d833bd2 

georg.brandl b6419f2 

Georg Brandl d833bd2 

georg.brandl b6419f2 




georg.brandl d15124c 
georg.brandl b6419f2 









Jon Waltman 0854f1f 

georg.brandl b6419f2 


Jon Waltman 0854f1f 
georg.brandl 13123a8 
georg.brandl b6419f2 


Georg Brandl 2c5a02a 
georg.brandl b6419f2 

Georg Brandl 2c5a02a 

georg.brandl b6419f2 
georg.brandl a10e656 





georg.brandl b6419f2 


Jon Waltman 0854f1f 
georg.brandl b6419f2 
Georg Brandl d833bd2 

georg.brandl b6419f2 
Georg Brandl 254e0ff 



Georg Brandl d833bd2 

Georg Brandl 254e0ff 
georg.brandl b6419f2 

Georg Brandl 0844cf7 
Jon Waltman 0854f1f 
georg.brandl cbc5331 
georg.brandl d15124c 
Georg Brandl 0844cf7 


georg.brandl b6419f2 
georg.brandl d15124c 
Jon Waltman 0854f1f 
georg.brandl d15124c 



georg.brandl 6d80e45 
Jon Waltman 0854f1f 
georg.brandl b6419f2 
georg.brandl 6d80e45 



Georg Brandl d833bd2 

georg.brandl 6d80e45 
Georg Brandl 254e0ff 
georg.brandl 6d80e45 
Georg Brandl 254e0ff 
georg.brandl 6d80e45 
Georg Brandl 254e0ff 
Georg Brandl 2ffdb09 
Georg Brandl 8213361 

Georg Brandl 19d9870 


georg.brandl 6d80e45 





georg.brandl b6419f2 
Georg Brandl cf0081d 
Georg Brandl 9585f5e 





Georg Brandl 535b00f 


Georg Brandl b805155 
Georg Brandl cf0081d 

Jon Waltman 0854f1f 

Georg Brandl cf0081d 

georg.brandl b6419f2 

Jon Waltman 0854f1f 
Georg Brandl 4f2aaa4 
georg.brandl b05d8c7 
Georg Brandl 4ae6e2b 
Georg Brandl da63f1c 

Jon Waltman 0854f1f 
Georg Brandl da63f1c 

Georg Brandl 4ae6e2b 
Georg Brandl 98f9c2d 
Jon Waltman 0854f1f 
Georg Brandl a326842 
Georg Brandl 98f9c2d 
Georg Brandl a326842 
Georg Brandl 98f9c2d 
Georg Brandl 95e572b 
Jon Waltman 0854f1f 
Georg Brandl 95e572b 


Franck Michea d4718ee 
Georg Brandl 95e572b 


Georg Brandl b805155 

Jon Waltman 0854f1f 

Georg Brandl a326842 
Georg Brandl cf0081d 
Georg Brandl a326842 
Georg Brandl b805155 
Georg Brandl cf0081d 

Jon Waltman 0854f1f 
Georg Brandl a326842 
Georg Brandl cf0081d 
Georg Brandl a326842 
Georg Brandl cf0081d 
Georg Brandl 6359829 
Jon Waltman 0854f1f 
Georg Brandl 6ef0637 

Georg Brandl 6359829 
Georg Brandl 6ef0637 
Georg Brandl 7bed376 
Georg Brandl e08c693 

Jon Waltman 0854f1f 


Georg Brandl 7bed376 
Georg Brandl 68d3dc0 
Georg Brandl 7bed376 


Georg Brandl e08c693 

Georg Brandl 7bed376 
Georg Brandl 168a597 
Georg Brandl 7bed376 



georg.brandl 6a7d8ab 

Georg Brandl 68d3dc0 
Jon Waltman 0854f1f 


Georg Brandl 7bed376 
Georg Brandl 68d3dc0 
Georg Brandl 7bed376 





georg.brandl ee489e1 

Jon Waltman 0854f1f 
georg.brandl ee489e1 
georg.brandl 4976feb 
georg.brandl be09cf0 
Jon Waltman 0854f1f 
Georg Brandl 254e0ff 
Georg Brandl f03bf97 




georg.brandl be09cf0 
Georg Brandl 5a9ce7c 
Jon Waltman 0854f1f 
Georg Brandl 5a9ce7c 
Mateusz Paprocki 91b4fc9 




Georg Brandl 5a9ce7c 
Georg Brandl 849b21d 
Jon Waltman 0854f1f 
Georg Brandl 849b21d 




Georg Brandl 535b00f 
Jon Waltman 0854f1f 
Georg Brandl 535b00f 



Georg Brandl a8f8eec 
Jon Waltman 0854f1f 
Georg Brandl a8f8eec 


Georg Brandl bb92596 
Jon Waltman 0854f1f 
Georg Brandl bb92596 



georg.brandl 4976feb 


georg.brandl fa8c04d 

georg.brandl 4976feb 

Georg Brandl e3ea500 
Georg Brandl d3456c0 
Georg Brandl e3ea500 





georg.brandl 4976feb 



Georg Brandl d3456c0 
georg.brandl 4976feb 





Georg Brandl d3456c0 

georg.brandl 4976feb 

Georg Brandl c46e5f7 

Georg Brandl d3456c0 
Georg Brandl c46e5f7 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
# -*- coding: utf-8 -*-
"""
    sphinx.application
    ~~~~~~~~~~~~~~~~~~

    Sphinx application object.

    Gracefully adapted from the TextPress system by Armin.

    :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import os
import sys
import types
import posixpath
from os import path
from cStringIO import StringIO

from docutils import nodes
from docutils.parsers.rst import convert_directive_function, \
     directives, roles

import sphinx
from sphinx import package_dir, locale
from sphinx.roles import XRefRole
from sphinx.config import Config
from sphinx.errors import SphinxError, SphinxWarning, ExtensionError, \
     VersionRequirementError
from sphinx.domains import ObjType, BUILTIN_DOMAINS
from sphinx.domains.std import GenericObject, Target, StandardDomain
from sphinx.builders import BUILTIN_BUILDERS
from sphinx.environment import BuildEnvironment, SphinxStandaloneReader
from sphinx.util import pycompat  # imported for side-effects
from sphinx.util.tags import Tags
from sphinx.util.osutil import ENOENT
from sphinx.util.console import bold


# List of all known core events. Maps name to arguments description.
events = {
    'builder-inited': '',
    'env-get-outdated': 'env, added, changed, removed',
    'env-purge-doc': 'env, docname',
    'source-read': 'docname, source text',
    'doctree-read': 'the doctree before being pickled',
    'missing-reference': 'env, node, contnode',
    'doctree-resolved': 'doctree, docname',
    'env-updated': 'env',
    'html-collect-pages': 'builder',
    'html-page-context': 'pagename, context, doctree or None',
    'build-finished': 'exception',
}

CONFIG_FILENAME = 'conf.py'
ENV_PICKLE_FILENAME = 'environment.pickle'


class Sphinx(object):

    def __init__(self, srcdir, confdir, outdir, doctreedir, buildername,
                 confoverrides=None, status=sys.stdout, warning=sys.stderr,
                 freshenv=False, warningiserror=False, tags=None, verbosity=0):
        self.verbosity = verbosity
        self.next_listener_id = 0
        self._extensions = {}
        self._listeners = {}
        self.domains = BUILTIN_DOMAINS.copy()
        self.builderclasses = BUILTIN_BUILDERS.copy()
        self.builder = None
        self.env = None

        self.srcdir = srcdir
        self.confdir = confdir
        self.outdir = outdir
        self.doctreedir = doctreedir

        if status is None:
            self._status = StringIO()
            self.quiet = True
        else:
            self._status = status
            self.quiet = False

        if warning is None:
            self._warning = StringIO()
        else:
            self._warning = warning
        self._warncount = 0
        self.warningiserror = warningiserror

        self._events = events.copy()

        # say hello to the world
        self.info(bold('Running Sphinx v%s' % sphinx.__version__))

        # status code for command-line application
        self.statuscode = 0

        # read config
        self.tags = Tags(tags)
        self.config = Config(confdir, CONFIG_FILENAME,
                             confoverrides or {}, self.tags)
        self.config.check_unicode(self.warn)

        # set confdir to srcdir if -C given (!= no confdir); a few pieces
        # of code expect a confdir to be set
        if self.confdir is None:
            self.confdir = self.srcdir

        # backwards compatibility: activate old C markup
        self.setup_extension('sphinx.ext.oldcmarkup')
        # load all user-given extension modules
        for extension in self.config.extensions:
            self.setup_extension(extension)
        # the config file itself can be an extension
        if self.config.setup:
            self.config.setup(self)

        # now that we know all config values, collect them from conf.py
        self.config.init_values()

        # check the Sphinx version if requested
        if self.config.needs_sphinx and \
           self.config.needs_sphinx > sphinx.__version__[:3]:
            raise VersionRequirementError(
                'This project needs at least Sphinx v%s and therefore cannot '
                'be built with this version.' % self.config.needs_sphinx)

        # set up translation infrastructure
        self._init_i18n()
        # set up the build environment
        self._init_env(freshenv)
        # set up the builder
        self._init_builder(buildername)

    def _init_i18n(self):
        """Load translated strings from the configured localedirs if enabled in
        the configuration.
        """
        if self.config.language is not None:
            self.info(bold('loading translations [%s]... ' %
                           self.config.language), nonl=True)
            locale_dirs = [None, path.join(package_dir, 'locale')] + \
                [path.join(self.srcdir, x) for x in self.config.locale_dirs]
        else:
            locale_dirs = []
        self.translator, has_translation = locale.init(locale_dirs,
                                                       self.config.language)
        if self.config.language is not None:
            if has_translation:
                self.info('done')
            else:
                self.info('locale not available')

    def _init_env(self, freshenv):
        if freshenv:
            self.env = BuildEnvironment(self.srcdir, self.doctreedir,
                                        self.config)
            self.env.find_files(self.config)
            for domain in self.domains.keys():
                self.env.domains[domain] = self.domains[domain](self.env)
        else:
            try:
                self.info(bold('loading pickled environment... '), nonl=True)
                self.env = BuildEnvironment.frompickle(self.config,
                    path.join(self.doctreedir, ENV_PICKLE_FILENAME))
                self.env.domains = {}
                for domain in self.domains.keys():
                    # this can raise if the data version doesn't fit
                    self.env.domains[domain] = self.domains[domain](self.env)
                self.info('done')
            except Exception, err:
                if type(err) is IOError and err.errno == ENOENT:
                    self.info('not yet created')
                else:
                    self.info('failed: %s' % err)
                return self._init_env(freshenv=True)

        self.env.set_warnfunc(self.warn)

    def _init_builder(self, buildername):
        if buildername is None:
            print >>self._status, 'No builder selected, using default: html'
            buildername = 'html'
        if buildername not in self.builderclasses:
            raise SphinxError('Builder name %s not registered' % buildername)

        builderclass = self.builderclasses[buildername]
        if isinstance(builderclass, tuple):
            # builtin builder
            mod, cls = builderclass
            builderclass = getattr(
                __import__('sphinx.builders.' + mod, None, None, [cls]), cls)
        self.builder = builderclass(self)
        self.emit('builder-inited')

    def build(self, force_all=False, filenames=None):
        try:
            if force_all:
                self.builder.build_all()
            elif filenames:
                self.builder.build_specific(filenames)
            else:
                self.builder.build_update()
        except Exception, err:
            # delete the saved env to force a fresh build next time
            envfile = path.join(self.doctreedir, ENV_PICKLE_FILENAME)
            if path.isfile(envfile):
                os.unlink(envfile)
            self.emit('build-finished', err)
            raise
        else:
            self.emit('build-finished', None)
        self.builder.cleanup()

    def _log(self, message, wfile, nonl=False):
        try:
            wfile.write(message)
        except UnicodeEncodeError:
            encoding = getattr(wfile, 'encoding', 'ascii') or 'ascii'
            wfile.write(message.encode(encoding, 'replace'))
        if not nonl:
            wfile.write('\n')
        if hasattr(wfile, 'flush'):
            wfile.flush()

    def warn(self, message, location=None, prefix='WARNING: '):
        if isinstance(location, tuple):
            docname, lineno = location
            if docname:
                location = '%s:%s' % (self.env.doc2path(docname), lineno or '')
            else:
                location = None
        warntext = location and '%s: %s%s\n' % (location, prefix, message) or \
                   '%s%s\n' % (prefix, message)
        if self.warningiserror:
            raise SphinxWarning(warntext)
        self._warncount += 1
        self._log(warntext, self._warning, True)

    def info(self, message='', nonl=False):
        self._log(message, self._status, nonl)

    def verbose(self, message, *args, **kwargs):
        if self.verbosity < 1:
            return
        if args or kwargs:
            message = message % (args or kwargs)
        self._log(message, self._warning)

    def debug(self, message, *args, **kwargs):
        if self.verbosity < 2:
            return
        if args or kwargs:
            message = message % (args or kwargs)
        self._log(message, self._warning)

    # general extensibility interface

    def setup_extension(self, extension):
        """Import and setup a Sphinx extension module. No-op if called twice."""
        self.debug('setting up extension: %r', extension)
        if extension in self._extensions:
            return
        try:
            mod = __import__(extension, None, None, ['setup'])
        except ImportError, err:
            raise ExtensionError('Could not import extension %s' % extension,
                                 err)
        if not hasattr(mod, 'setup'):
            self.warn('extension %r has no setup() function; is it really '
                      'a Sphinx extension module?' % extension)
        else:
            try:
                mod.setup(self)
            except VersionRequirementError, err:
                # add the extension name to the version required
                raise VersionRequirementError(
                    'The %s extension used by this project needs at least '
                    'Sphinx v%s; it therefore cannot be built with this '
                    'version.' % (extension, err))
        self._extensions[extension] = mod

    def require_sphinx(self, version):
        # check the Sphinx version if requested
        if version > sphinx.__version__[:3]:
            raise VersionRequirementError(version)

    def import_object(self, objname, source=None):
        """Import an object from a 'module.name' string."""
        try:
            module, name = objname.rsplit('.', 1)
        except ValueError, err:
            raise ExtensionError('Invalid full object name %s' % objname +
                                 (source and ' (needed for %s)' % source or ''),
                                 err)
        try:
            return getattr(__import__(module, None, None, [name]), name)
        except ImportError, err:
            raise ExtensionError('Could not import %s' % module +
                                 (source and ' (needed for %s)' % source or ''),
                                 err)
        except AttributeError, err:
            raise ExtensionError('Could not find %s' % objname +
                                 (source and ' (needed for %s)' % source or ''),
                                 err)

    # event interface

    def _validate_event(self, event):
        event = intern(event)
        if event not in self._events:
            raise ExtensionError('Unknown event name: %s' % event)

    def connect(self, event, callback):
        self._validate_event(event)
        listener_id = self.next_listener_id
        if event not in self._listeners:
            self._listeners[event] = {listener_id: callback}
        else:
            self._listeners[event][listener_id] = callback
        self.next_listener_id += 1
        self.debug('connecting event %r: %r [id=%s]',
                   event, callback, listener_id)
        return listener_id

    def disconnect(self, listener_id):
        self.debug('disconnecting event: [id=%s]', listener_id)
        for event in self._listeners.itervalues():
            event.pop(listener_id, None)

    def emit(self, event, *args):
        results = []
        if event in self._listeners:
            for _, callback in self._listeners[event].iteritems():
                results.append(callback(self, *args))
        return results

    def emit_firstresult(self, event, *args):
        for result in self.emit(event, *args):
            if result is not None:
                return result
        return None

    # registering addon parts

    def add_builder(self, builder):
        self.debug('adding builder: %r', builder)
        if not hasattr(builder, 'name'):
            raise ExtensionError('Builder class %s has no "name" attribute'
                                 % builder)
        if builder.name in self.builderclasses:
            if isinstance(self.builderclasses[builder.name], tuple):
                raise ExtensionError('Builder %r is a builtin builder' %
                                     builder.name)
            else:
                raise ExtensionError(
                    'Builder %r already exists (in module %s)' % (
                    builder.name, self.builderclasses[builder.name].__module__))
        self.builderclasses[builder.name] = builder

    def add_config_value(self, name, default, rebuild):
        self.debug('adding config value: %r', (name, default, rebuild))
        if name in self.config.values:
            raise ExtensionError('Config value %r already present' % name)
        if rebuild in (False, True):
            rebuild = rebuild and 'env' or ''
        self.config.values[name] = (default, rebuild)

    def add_event(self, name):
        self.debug('adding event: %r', name)
        if name in self._events:
            raise ExtensionError('Event %r already present' % name)
        self._events[name] = ''

    def add_node(self, node, **kwds):
        self.debug('adding node: %r', (node, kwds))
        nodes._add_node_class_names([node.__name__])
        for key, val in kwds.iteritems():
            try:
                visit, depart = val
            except ValueError:
                raise ExtensionError('Value for key %r must be a '
                                     '(visit, depart) function tuple' % key)
            if key == 'html':
                from sphinx.writers.html import HTMLTranslator as translator
            elif key == 'latex':
                from sphinx.writers.latex import LaTeXTranslator as translator
            elif key == 'text':
                from sphinx.writers.text import TextTranslator as translator
            elif key == 'man':
                from sphinx.writers.manpage import ManualPageTranslator \
                    as translator
            elif key == 'texinfo':
                from sphinx.writers.texinfo import TexinfoTranslator \
                    as translator
            else:
                # ignore invalid keys for compatibility
                continue
            setattr(translator, 'visit_'+node.__name__, visit)
            if depart:
                setattr(translator, 'depart_'+node.__name__, depart)

    def _directive_helper(self, obj, content=None, arguments=None, **options):
        if isinstance(obj, (types.FunctionType, types.MethodType)):
            obj.content = content
            obj.arguments = arguments or (0, 0, False)
            obj.options = options
            return convert_directive_function(obj)
        else:
            if content or arguments or options:
                raise ExtensionError('when adding directive classes, no '
                                     'additional arguments may be given')
            return obj

    def add_directive(self, name, obj, content=None, arguments=None, **options):
        self.debug('adding directive: %r',
                   (name, obj, content, arguments, options))
        directives.register_directive(
            name, self._directive_helper(obj, content, arguments, **options))

    def add_role(self, name, role):
        self.debug('adding role: %r', (name, role))
        roles.register_local_role(name, role)

    def add_generic_role(self, name, nodeclass):
        # don't use roles.register_generic_role because it uses
        # register_canonical_role
        self.debug('adding generic role: %r', (name, nodeclass))
        role = roles.GenericRole(name, nodeclass)
        roles.register_local_role(name, role)

    def add_domain(self, domain):
        self.debug('adding domain: %r', domain)
        if domain.name in self.domains:
            raise ExtensionError('domain %s already registered' % domain.name)
        self.domains[domain.name] = domain

    def override_domain(self, domain):
        self.debug('overriding domain: %r', domain)
        if domain.name not in self.domains:
            raise ExtensionError('domain %s not yet registered' % domain.name)
        if not issubclass(domain, self.domains[domain.name]):
            raise ExtensionError('new domain not a subclass of registered %s '
                                 'domain' % domain.name)
        self.domains[domain.name] = domain

    def add_directive_to_domain(self, domain, name, obj,
                                content=None, arguments=None, **options):
        self.debug('adding directive to domain: %r',
                   (domain, name, obj, content, arguments, options))
        if domain not in self.domains:
            raise ExtensionError('domain %s not yet registered' % domain)
        self.domains[domain].directives[name] = \
            self._directive_helper(obj, content, arguments, **options)

    def add_role_to_domain(self, domain, name, role):
        self.debug('adding role to domain: %r', (domain, name, role))
        if domain not in self.domains:
            raise ExtensionError('domain %s not yet registered' % domain)
        self.domains[domain].roles[name] = role

    def add_index_to_domain(self, domain, index):
        self.debug('adding index to domain: %r', (domain, index))
        if domain not in self.domains:
            raise ExtensionError('domain %s not yet registered' % domain)
        self.domains[domain].indices.append(index)

    def add_object_type(self, directivename, rolename, indextemplate='',
                        parse_node=None, ref_nodeclass=None, objname='',
                        doc_field_types=[]):
        self.debug('adding object type: %r',
                   (directivename, rolename, indextemplate, parse_node,
                    ref_nodeclass, objname, doc_field_types))
        StandardDomain.object_types[directivename] = \
            ObjType(objname or directivename, rolename)
        # create a subclass of GenericObject as the new directive
        new_directive = type(directivename, (GenericObject, object),
                             {'indextemplate': indextemplate,
                              'parse_node': staticmethod(parse_node),
                              'doc_field_types': doc_field_types})
        StandardDomain.directives[directivename] = new_directive
        # XXX support more options?
        StandardDomain.roles[rolename] = XRefRole(innernodeclass=ref_nodeclass)

    # backwards compatible alias
    add_description_unit = add_object_type

    def add_crossref_type(self, directivename, rolename, indextemplate='',
                          ref_nodeclass=None, objname=''):
        self.debug('adding crossref type: %r',
                   (directivename, rolename, indextemplate, ref_nodeclass,
                    objname))
        StandardDomain.object_types[directivename] = \
            ObjType(objname or directivename, rolename)
        # create a subclass of Target as the new directive
        new_directive = type(directivename, (Target, object),
                             {'indextemplate': indextemplate})
        StandardDomain.directives[directivename] = new_directive
        # XXX support more options?
        StandardDomain.roles[rolename] = XRefRole(innernodeclass=ref_nodeclass)

    def add_transform(self, transform):
        self.debug('adding transform: %r', transform)
        SphinxStandaloneReader.transforms.append(transform)

    def add_javascript(self, filename):
        self.debug('adding javascript: %r', filename)
        from sphinx.builders.html import StandaloneHTMLBuilder
        if '://' in filename:
            StandaloneHTMLBuilder.script_files.append(filename)
        else:
            StandaloneHTMLBuilder.script_files.append(
                posixpath.join('_static', filename))

    def add_stylesheet(self, filename):
        self.debug('adding stylesheet: %r', filename)
        from sphinx.builders.html import StandaloneHTMLBuilder
        if '://' in filename:
            StandaloneHTMLBuilder.css_files.append(filename)
        else:
            StandaloneHTMLBuilder.css_files.append(
                posixpath.join('_static', filename))

    def add_lexer(self, alias, lexer):
        self.debug('adding lexer: %r', (alias, lexer))
        from sphinx.highlighting import lexers
        if lexers is None:
            return
        lexers[alias] = lexer

    def add_autodocumenter(self, cls):
        self.debug('adding autodocumenter: %r', cls)
        from sphinx.ext import autodoc
        autodoc.add_documenter(cls)
        self.add_directive('auto' + cls.objtype, autodoc.AutoDirective)

    def add_autodoc_attrgetter(self, type, getter):
        self.debug('adding autodoc attrgetter: %r', (type, getter))
        from sphinx.ext import autodoc
        autodoc.AutoDirective._special_attrgetters[type] = getter

    def add_search_language(self, cls):
        self.debug('adding search language: %r', cls)
        from sphinx.search import languages, SearchLanguage
        assert isinstance(cls, SearchLanguage)
        languages[cls.lang] = cls


class TemplateBridge(object):
    """
    This class defines the interface for a "template bridge", that is, a class
    that renders templates given a template name and a context.
    """

    def init(self, builder, theme=None, dirs=None):
        """Called by the builder to initialize the template system.

        *builder* is the builder object; you'll probably want to look at the
        value of ``builder.config.templates_path``.

        *theme* is a :class:`sphinx.theming.Theme` object or None; in the latter
        case, *dirs* can be list of fixed directories to look for templates.
        """
        raise NotImplementedError('must be implemented in subclasses')

    def newest_template_mtime(self):
        """Called by the builder to determine if output files are outdated
        because of template changes.  Return the mtime of the newest template
        file that was changed.  The default implementation returns ``0``.
        """
        return 0

    def render(self, template, context):
        """Called by the builder to render a template given as a filename with
        a specified context (a Python dictionary).
        """
        raise NotImplementedError('must be implemented in subclasses')

    def render_string(self, template, context):
        """Called by the builder to render a template given as a string with a
        specified context (a Python dictionary).
        """
        raise NotImplementedError('must be implemented in subclasses')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.