summaryrefslogtreecommitdiff
path: root/sphinx/writers/websupport.py
blob: 18c0807d6f60c0b530674be10f6651ee17ac3b57 (plain)
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
# -*- coding: utf-8 -*-
"""
    sphinx.writers.websupport
    ~~~~~~~~~~~~~~~~~~~~~~~~~

    docutils writers handling Sphinx' custom nodes.

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

from sphinx.writers.html import HTMLTranslator

class WebSupportTranslator(HTMLTranslator):
    """
    Our custom HTML translator.
    """
    commentable_nodes = ['bullet_list', 'paragraph', 'desc']

    def __init__(self, builder, *args, **kwargs):
        HTMLTranslator.__init__(self, builder, *args, **kwargs)
        self.comment_class = 'spxcmt'
        self.init_support()

    def init_support(self):
        self.in_commentable = False
        self.current_id = 0
        
    def dispatch_visit(self, node):
        if node.__class__.__name__ in self.commentable_nodes:
            self.handle_visit_commentable(node)
        HTMLTranslator.dispatch_visit(self, node)

    def dispatch_departure(self, node):
        HTMLTranslator.dispatch_departure(self, node)
        if node.__class__.__name__ in self.commentable_nodes:
            self.handle_depart_commentable(node)

    def handle_visit_commentable(self, node):
        # If this node is nested inside another commentable node this
        # node will not be commented.
        if not self.in_commentable:
            self.in_commentable = True
            node_id = self.add_db_node(node)
            # We will place the node in the HTML id attribute. If the node
            # already has an id (for indexing purposes) put an empty
            # span with the existing id directly before this node's HTML.
            if node.attributes['ids']:
                self.body.append('<span id="%s"></span>'
                                 % node.attributes['ids'][0])
            node.attributes['ids'] = ['s%s' % node_id]
            node.attributes['classes'].append(self.comment_class)

    def handle_depart_commentable(self, node):
        assert(self.in_commentable)
        if self.comment_class in node.attributes['classes']:
            self.in_commentable = False

    def add_db_node(self, node):
        comments = self.builder.app.comments
        db_node_id = comments.add_node(document=self.builder.cur_docname,
                                       line=node.line,
                                       source=node.rawsource,
                                       treeloc='???')
        return db_node_id