Ejemplo n.º 1
0
    def run(self):
        language = self.arguments[0]

        indexed_languages = self.options.get('index_as') or language
        index_specs = ['pair: {}; language'.format(l)
                       for l in indexed_languages.splitlines()]

        name = nodes.fully_normalize_name(language)
        target = 'language-{}'.format(name)
        targetnode = nodes.target('', '', ids=[target])
        self.state.document.note_explicit_target(targetnode)

        indexnode = addnodes.index()
        indexnode['entries'] = []
        indexnode['inline'] = False
        set_source_info(self, indexnode)
        for spec in index_specs:
            indexnode['entries'].extend(process_index_entry(spec, target))

        sectionnode = nodes.section()
        sectionnode['names'].append(name)

        title, messages = self.state.inline_text(language, self.lineno)
        titlenode = nodes.title(language, '', *title)

        sectionnode += titlenode
        sectionnode += messages
        self.state.document.note_implicit_target(sectionnode, sectionnode)

        self.state.nested_parse(self.content, self.content_offset, sectionnode)

        return [indexnode, targetnode, sectionnode]
Ejemplo n.º 2
0
def index_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    # create new reference target
    env = inliner.document.settings.env
    targetid = 'index-%s' % env.new_serialno('index')
    targetnode = nodes.target('', '', ids=[targetid])
    # split text and target in role content
    has_explicit_title, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    # if an explicit target is given, we can process it as a full entry
    if has_explicit_title:
        entries = process_index_entry(target, targetid)
    # otherwise we just create a "single" entry
    else:
        # but allow giving main entry
        main = ''
        if target.startswith('!'):
            target = target[1:]
            title = title[1:]
            main = 'main'
        entries = [('single', target, targetid, main)]
    indexnode = addnodes.index()
    indexnode['entries'] = entries
    set_role_source_info(inliner, lineno, indexnode)
    textnode = nodes.Text(title, title)
    return [indexnode, targetnode, textnode], []
Ejemplo n.º 3
0
def index_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    # create new reference target
    env = inliner.document.settings.env
    targetid = 'index-%s' % env.new_serialno('index')
    targetnode = nodes.target('', '', ids=[targetid])
    # split text and target in role content
    has_explicit_title, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    # if an explicit target is given, we can process it as a full entry
    if has_explicit_title:
        entries = process_index_entry(target, targetid)
    # otherwise we just create a "single" entry
    else:
        # but allow giving main entry
        main = ''
        if target.startswith('!'):
            target = target[1:]
            title = title[1:]
            main = 'main'
        entries = [('single', target, targetid, main)]
    indexnode = addnodes.index()
    indexnode['entries'] = entries
    set_role_source_info(inliner, lineno, indexnode)
    textnode = nodes.Text(title, title)
    return [indexnode, targetnode, textnode], []
Ejemplo n.º 4
0
    def run(self):
        language = self.arguments[0]

        indexed_languages = self.options.get('index_as') or language
        index_specs = [
            'pair: {}; language'.format(lang)
            for lang in indexed_languages.splitlines()
        ]

        name = nodes.fully_normalize_name(language)
        target = 'language-{}'.format(name)
        targetnode = nodes.target('', '', ids=[target])
        self.state.document.note_explicit_target(targetnode)

        indexnode = addnodes.index()
        indexnode['entries'] = []
        indexnode['inline'] = False
        set_source_info(self, indexnode)
        for spec in index_specs:
            indexnode['entries'].extend(process_index_entry(spec, target))

        sectionnode = nodes.section()
        sectionnode['names'].append(name)

        title, messages = self.state.inline_text(language, self.lineno)
        titlenode = nodes.title(language, '', *title)

        sectionnode += titlenode
        sectionnode += messages
        self.state.document.note_implicit_target(sectionnode, sectionnode)

        self.state.nested_parse(self.content, self.content_offset, sectionnode)

        return [indexnode, targetnode, sectionnode]
Ejemplo n.º 5
0
def index_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner,
               options: Dict = {}, content: List[str] = []
               ) -> Tuple[List[Node], List[system_message]]:
    warnings.warn('index_role() is deprecated.  Please use Index class instead.',
                  RemovedInSphinx40Warning, stacklevel=2)
    # create new reference target
    env = inliner.document.settings.env
    targetid = 'index-%s' % env.new_serialno('index')
    targetnode = nodes.target('', '', ids=[targetid])
    # split text and target in role content
    has_explicit_title, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    # if an explicit target is given, we can process it as a full entry
    if has_explicit_title:
        entries = process_index_entry(target, targetid)
    # otherwise we just create a "single" entry
    else:
        # but allow giving main entry
        main = ''
        if target.startswith('!'):
            target = target[1:]
            title = title[1:]
            main = 'main'
        entries = [('single', target, targetid, main, None)]
    indexnode = addnodes.index()
    indexnode['entries'] = entries
    set_role_source_info(inliner, lineno, indexnode)
    textnode = nodes.Text(title, title)
    return [indexnode, targetnode, textnode], []
Ejemplo n.º 6
0
 def run(self):
     arguments = self.arguments[0].split('\n')
     env = self.state.document.settings.env
     targetid = 'index-%s' % env.new_serialno('index')
     targetnode = nodes.target('', '', ids=[targetid])
     self.state.document.note_explicit_target(targetnode)
     indexnode = addnodes.index()
     indexnode['entries'] = ne = []
     indexnode['inline'] = False
     for entry in arguments:
         ne.extend(process_index_entry(entry, targetid))
     return [indexnode, targetnode]
Ejemplo n.º 7
0
 def run(self) -> List[Node]:
     arguments = self.arguments[0].split('\n')
     targetid = 'index-%s' % self.env.new_serialno('index')
     targetnode = nodes.target('', '', ids=[targetid])
     self.state.document.note_explicit_target(targetnode)
     indexnode = addnodes.index()
     indexnode['entries'] = []
     indexnode['inline'] = False
     self.set_source_info(indexnode)
     for entry in arguments:
         indexnode['entries'].extend(process_index_entry(entry, targetid))
     return [indexnode, targetnode]
Ejemplo n.º 8
0
 def run(self):
     arguments = self.arguments[0].split('\n')
     env = self.state.document.settings.env
     targetid = 'index-%s' % env.new_serialno('index')
     targetnode = nodes.target('', '', ids=[targetid])
     self.state.document.note_explicit_target(targetnode)
     indexnode = addnodes.index()
     indexnode['entries'] = ne = []
     indexnode['inline'] = False
     for entry in arguments:
         ne.extend(process_index_entry(entry, targetid))
     return [indexnode, targetnode]
Ejemplo n.º 9
0
 def run(self):
     # type: () -> List[nodes.Node]
     arguments = self.arguments[0].split('\n')
     targetid = 'index-%s' % self.env.new_serialno('index')
     targetnode = nodes.target('', '', ids=[targetid])
     self.state.document.note_explicit_target(targetnode)
     indexnode = addnodes.index()
     indexnode['entries'] = []
     indexnode['inline'] = False
     set_source_info(self, indexnode)
     for entry in arguments:
         indexnode['entries'].extend(process_index_entry(entry, targetid))
     return [indexnode, targetnode]
Ejemplo n.º 10
0
 def __call__(self,
              name,
              rawtext,
              text,
              lineno,
              inliner,
              options={},
              content=[]):
     targetnode = nodes.target('', '')
     inliner.document.note_explicit_target(targetnode)
     targetid = targetnode['ids'][0]
     indexnode = addnodes.index()
     indexnode['entries'] = ne = []
     indexnode['inline'] = True
     indexnode.source, indexnode.line = inliner.document.current_source, lineno
     ne.extend(process_index_entry(text, targetid))
     textnode = self.node_class(text, text)
     return ([textnode, indexnode, targetnode], [])
Ejemplo n.º 11
0
    def _init(self, trait_name: str):
        self._node_id = trait_node_id_from_trait_name(trait_name)
        self._node = TraitNode(ids=[self._node_id])
        self._parse_msgs = []
        self._target = nodes.target()
        self.state.add_target(self._node_id, '', self._target, self.lineno)

        ## add node to index
        name_in_index = 'Trait; ' + trait_name
        target_anchor = self._node_id

        self._indexnode = addnodes.index()
        self._indexnode['entries'] = ne = []
        self._indexnode['inline'] = False
        set_source_info(self, self._indexnode)
        ne.extend(process_index_entry(name_in_index, target_anchor))

        self._trait_instance = reflectionutil.trait_instance(trait_name)
        self._trait_class = reflectionutil.trait_class(trait_name)
Ejemplo n.º 12
0
    def _init(self, name: str, qualified_type_name: str):
        self._node_id = nodes.make_id(nodes.fully_normalize_name(name))
        self._node = ModelElementNode(ids=[self._node_id])
        self._parse_msgs = []
        self._target = nodes.target()
        self.state.add_target(self._node_id, '', self._target, self.lineno)

        ## add node to index
        name_in_index = 'ModelElement; ' + name
        target_anchor = self._node_id

        self._indexnode = addnodes.index()
        self._indexnode['entries'] = ne = []
        self._indexnode['inline'] = False
        set_source_info(self, self._indexnode)
        ne.extend(process_index_entry(name_in_index, target_anchor))

        self._model_element_type = reflectionutil.model_element_type(
            qualified_type_name=qualified_type_name, )
Ejemplo n.º 13
0
    def run(self) -> Tuple[List[Node], List[system_message]]:
        target_id = 'index-%s' % self.env.new_serialno('index')
        if self.has_explicit_title:
            # if an explicit target is given, process it as a full entry
            title = self.title
            entries = process_index_entry(self.target, target_id)
        else:
            # otherwise we just create a single entry
            if self.target.startswith('!'):
                title = self.title[1:]
                entries = [('single', self.target[1:], target_id, 'main', None)]
            else:
                title = self.title
                entries = [('single', self.target, target_id, '', None)]

        index = addnodes.index(entries=entries)
        target = nodes.target('', '', ids=[target_id])
        text = nodes.Text(title, title)
        self.set_source_info(index)
        return [index, target, text], []
Ejemplo n.º 14
0
def macro_def_role(name,
                   rawtext,
                   text,
                   lineno,
                   inliner,
                   options={},
                   content=[]):
    app = inliner.document.settings.env.app
    docname = inliner.document.settings.env.docname

    # Create a new linkable target using the macro name
    targetid = text
    targetnode = nodes.target('', text, ids=[targetid], classes=["macro-def"])

    # Automatically include an index entry for macro definitions
    entries = process_index_entry(text, targetid)
    indexnode = addnodes.index()
    indexnode['entries'] = entries
    set_role_source_info(inliner, lineno, indexnode)

    return [indexnode, targetnode], []
Ejemplo n.º 15
0
def classad_attribute_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    app = inliner.document.settings.env.app
    docname = inliner.document.settings.env.docname

    # Create the attribute title with the classad attribute name, also containing an anchor
    anchor_title_node = make_anchor_title_node(text)

    # Create a headerlink node, which can be used to link to the anchor
    headerlink_node = make_headerlink_node(str(text), options)

    # Determine the classad type (job, submitted, collector, etc.) by ripping it out of the document title
    attr_type = ""
    type_matches = re.findall(r"/([\w]*)-classad-attributes", docname)
    for match in type_matches:
        attr_type = match.capitalize() + " "

    # Automatically include an index entry
    entries = process_index_entry(f"{text} ({attr_type}ClassAd Attribute)", text)
    index_node = addnodes.index()
    index_node['entries'] = entries
    set_role_source_info(inliner, lineno, index_node)

    return [index_node, anchor_title_node, headerlink_node], []
Ejemplo n.º 16
0
    def run(self):
        """
        builds the mathdef text
        """
        # sett = self.state.document.settings
        # language_code = sett.language_code
        lineno = self.lineno

        env = self.state.document.settings.env if hasattr(
            self.state.document.settings, "env") else None
        docname = None if env is None else env.docname
        if docname is not None:
            docname = docname.replace("\\", "/").split("/")[-1]
            legend = "{0}:{1}".format(docname, lineno)
        else:
            legend = ''

        if hasattr(env, "settings") and hasattr(env.settings, "mathdef_link_number"):
            number_format = env.settings.mathdef_link_number
        elif hasattr(self.state.document.settings, "mathdef_link_number"):
            number_format = self.state.document.settings.mathdef_link_number
        elif hasattr(env, "config") and hasattr(env.config, "mathdef_link_number"):
            number_format = env.config.mathdef_link_number
        else:
            raise ValueError(
                "mathdef_link_number is not defined in the configuration")

        if not self.options.get('class'):
            self.options['class'] = ['admonition-mathdef']

        # body
        (mathdef,) = super(MathDef, self).run()
        if isinstance(mathdef, nodes.system_message):
            return [mathdef]

        # add a label
        lid = self.options.get('lid', self.options.get('label', None))
        if lid:
            container = nodes.container()
            tnl = [".. _{0}:".format(lid), ""]
            content = StringList(tnl)
            self.state.nested_parse(content, self.content_offset, container)
        else:
            container = None

        # mid
        mathtag = self.options.get('tag', '').strip()
        if len(mathtag) == 0:
            raise ValueError("tag is empty")
        if env is not None:
            mid = int(env.new_serialno('indexmathe-u-%s' % mathtag)) + 1
        else:
            mid = -1

        # id of the section
        first_letter = docname[0] if docname else ""
        number = mid
        try:
            label_number = number_format.format(
                number=number, first_letter=first_letter)
        except ValueError as e:
            raise Exception(
                "Unable to interpret format '{0}'.".format(number_format)) from e

        # title
        title = self.options.get('title', "").strip()
        if len(title) > 0:
            title = "{0} {1} : {2}".format(mathtag, label_number, title)
        else:
            raise ValueError("title is empty")

        # main node
        ttitle = title
        title = nodes.title(text=_(title))
        if container is not None:
            mathdef.insert(0, title)
            mathdef.insert(0, container)
        else:
            mathdef.insert(0, title)
        mathdef['mathtag'] = mathtag
        mathdef['mathmid'] = mid
        mathdef['mathtitle'] = ttitle
        set_source_info(self, mathdef)

        if env is not None:
            targetid = 'indexmathe-%s%s' % (mathtag,
                                            env.new_serialno('indexmathe%s' % mathtag))
            ids = [targetid]
            targetnode = nodes.target(legend, '', ids=ids[0])
            try:
                self.state.add_target(targetid, '', targetnode, lineno)
            except Exception as e:
                raise Exception("Issue in\n  File '{0}', line {1}\ntid={2}\ntnode={3}".format(
                    None if env is None else env.docname, lineno, targetid, targetnode)) from e

            # index node
            index = self.options.get('index', None)
            imposed = ",".join(a for a in [mathtag, ttitle] if a)
            if index is None or len(index.strip()) == 0:
                index = imposed
            else:
                index += "," + imposed
            if index is not None:
                indexnode = addnodes.index()
                indexnode['entries'] = ne = []
                indexnode['inline'] = False
                set_source_info(self, indexnode)
                for entry in index.split(","):
                    ne.extend(process_index_entry(entry, targetid))
            else:
                indexnode = None
        else:
            targetnode = None
            indexnode = None

        return [a for a in [indexnode, targetnode, mathdef] if a is not None]
Ejemplo n.º 17
0
    def fill_node(self, node, env, tag, p, language_code, targetnode,
                  sharepost):
        """
        Fill the node of an aggregated page.
        """
        # add a label
        suffix_label = self.suffix_label()
        container = nodes.container()
        tnl = [".. _{0}{1}:".format(tag, suffix_label), ""]
        content = StringList(tnl)
        self.state.nested_parse(content, self.content_offset, container)
        node += container

        # id section
        if env is not None:
            mid = int(env.new_serialno('indexblog-u-%s' % p["date"][:4])) + 1
        else:
            mid = -1

        # add title
        sids = "y{0}-{1}".format(p["date"][:4], mid)
        section = nodes.section(ids=[sids])
        section['year'] = p["date"][:4]
        section['blogmid'] = mid
        node += section
        textnodes, messages = self.state.inline_text(p["title"], self.lineno)
        section += nodes.title(p["title"], '', *textnodes)
        section += messages

        # add date and share buttons
        tnl = [":bigger:`::5:{0}`".format(p["date"])]
        if sharepost is not None:
            tnl.append(":sharenet:`{0}`".format(sharepost))
        tnl.append('')
        content = StringList(tnl)
        content = content + self.content

        # parse the content into sphinx directive,
        # it adds it to section
        container = nodes.container()
        # nested_parse_with_titles(self.state, content, paragraph)
        self.state.nested_parse(content, self.content_offset, container)
        section += container

        # final
        p['blogpost'] = node
        self.exe_class = p.copy()
        p["content"] = content
        node['classes'] += ["blogpost"]

        # target
        # self.state.add_target(p['title'], '', targetnode, lineno)

        # index (see site-packages/sphinx/directives/code.py, class Index)
        if self.__class__.add_index:
            # it adds an index
            # self.state.document.note_explicit_target(targetnode)
            indexnode = addnodes.index()
            indexnode['entries'] = ne = []
            indexnode['inline'] = False
            set_source_info(self, indexnode)
            for entry in set(p["keywords"] + p["categories"] + [p["date"]]):
                ne.extend(process_index_entry(entry, tag))  # targetid))
            ns = [indexnode, targetnode, node]
        else:
            ns = [targetnode, node]

        return ns
Ejemplo n.º 18
0
    def run(self):
        """
        builds the todo text
        """
        sett = self.state.document.settings
        language_code = sett.language_code
        lineno = self.lineno

        env = self.state.document.settings.env if hasattr(
            self.state.document.settings, "env") else None
        docname = None if env is None else env.docname
        if docname is not None:
            docname = docname.replace("\\", "/").split("/")[-1]
            legend = "{0}:{1}".format(docname, lineno)
        else:
            legend = ''

        if not self.options.get('class'):
            self.options['class'] = ['admonition-todoext']

        # link to issue
        issue = self.options.get('issue', "").strip()
        if issue is not None and len(issue) > 0:
            if hasattr(sett, "extlinks"):
                extlinks = sett.extlinks
            elif env is not None and hasattr(env.config, "extlinks"):
                extlinks = env.config.extlinks
            else:
                available = "\n".join(sorted(sett.__dict__.keys()))
                available2 = "\n".join(
                    sorted(env.config.__dict__.keys())) if env is not None else "-"
                raise ValueError("extlinks (wih a key 'issue') is not defined in the documentation settings, available in sett\n{0}\nCONFIG\n{1}".format(
                    available, available2))

            if "issue" not in extlinks:
                raise KeyError("key 'issue' is not present in extlinks")
            url, label = extlinks["issue"]
            url = url % str(issue)
            lab = label.format(issue)
            linkin = nodes.reference(lab, locale_(lab), refuri=url)
            link = nodes.paragraph()
            link += linkin
        else:
            link = None

        # cost
        cost = self.options.get('cost', "").strip()
        if cost:
            try:
                fcost = float(cost)
            except ValueError:
                raise ValueError(
                    "unable to convert cost '{0}' into float".format(cost))
        else:
            fcost = 0.0

        # priority
        prio = self.options.get('priority', "").strip()

        # hidden
        hidden = self.options.get('hidden', "false").strip().lower() in {
            'true', '1', ''}

        # body
        (todoext,) = super(TodoExt, self).run()
        if isinstance(todoext, nodes.system_message):
            return [todoext]

        # link
        if link:
            todoext += link

        # title
        title = self.options.get('title', "").strip()
        todotag = self.options.get('tag', '').strip()
        if len(title) > 0:
            title = ": " + title

        # prefix
        prefix = TITLES[language_code]["todo"]
        tododate = self.options.get('date', "").strip()
        todorelease = self.options.get('release', "").strip()
        infos = []
        if len(todotag) > 0:
            infos.append(todotag)
        if len(prio) > 0:
            infos.append('P=%s' % prio)
        if fcost > 0:
            if int(fcost) == fcost:
                infos.append('C=%d' % int(fcost))
            else:
                infos.append('C=%1.1f' % fcost)
        if todorelease:
            infos.append('v{0}'.format(todorelease))
        if tododate:
            infos.append(tododate)
        if infos:
            prefix += "({0})".format(" - ".join(infos))

        # main node
        title = nodes.title(text=locale_(prefix + title))
        todoext.insert(0, title)
        todoext['todotag'] = todotag
        todoext['todocost'] = fcost
        todoext['todoprio'] = prio
        todoext['todohidden'] = hidden
        todoext['tododate'] = tododate
        todoext['todorelease'] = todorelease
        todoext['todotitle'] = self.options.get('title', "").strip()
        set_source_info(self, todoext)

        if hidden:
            todoext['todoext_copy'] = todoext.deepcopy()
            todoext.clear()

        if env is not None:
            targetid = 'indextodoe-%s' % env.new_serialno('indextodoe')
            targetnode = nodes.target(legend, '', ids=[targetid])
            self.state.add_target(targetid, '', targetnode, lineno)

            # index node
            index = self.options.get('index', None)
            if index is not None:
                indexnode = addnodes.index()
                indexnode['entries'] = ne = []
                indexnode['inline'] = False
                set_source_info(self, indexnode)
                for entry in index.split(","):
                    ne.extend(process_index_entry(entry, targetid))
            else:
                indexnode = None
        else:
            targetnode = None
            indexnode = None

        return [a for a in [indexnode, targetnode, todoext] if a is not None]
Ejemplo n.º 19
0
    def run(self):
        """
        builds the blocref text
        """
        name_desc = self.__class__.name_sphinx
        # sett = self.state.document.settings
        # language_code = sett.language_code
        lineno = self.lineno

        env = self.state.document.settings.env if hasattr(
            self.state.document.settings, "env") else None
        docname = None if env is None else env.docname
        if docname is not None:
            docname = docname.replace("\\", "/").split("/")[-1]
            legend = "{0}:{1}".format(docname, lineno)
        else:
            legend = ''

        if not self.options.get('class'):
            self.options['class'] = ['admonition-%s' % name_desc]

        # body
        (blocref,) = super(BlocRef, self).run()
        if isinstance(blocref, nodes.system_message):
            return [blocref]

        # add a label
        lid = self.options.get('lid', self.options.get('label', None))
        if lid:
            container = nodes.container()
            tnl = [".. _{0}:".format(lid), ""]
            content = StringList(tnl)
            self.state.nested_parse(content, self.content_offset, container)
        else:
            container = None

        # mid
        breftag = self.options.get('tag', '').strip()
        if len(breftag) == 0:
            raise ValueError("tag is empty")
        if env is not None:
            mid = int(env.new_serialno('index%s-%s' %
                                       (name_desc, breftag))) + 1
        else:
            mid = -1

        # title
        titleo = self.options.get('title', "").strip()
        if len(titleo) == 0:
            raise ValueError("title is empty")
        title = self._update_title(titleo, breftag, mid)

        # main node
        ttitle = title
        title = nodes.title(text=_(title))
        if container is not None:
            blocref.insert(0, title)
            blocref.insert(0, container)
        else:
            blocref.insert(0, title)
        blocref['breftag'] = breftag
        blocref['brefmid'] = mid
        blocref['breftitle'] = ttitle
        blocref['breftitleo'] = titleo
        blocref['brefline'] = lineno
        blocref['breffile'] = docname
        set_source_info(self, blocref)

        if env is not None:
            targetid = 'index%s-%s%s' % (name_desc,
                                         breftag, env.new_serialno('index%s%s' % (name_desc, breftag)))
            blocref["breftargetid"] = targetid
            ids = [targetid]
            targetnode = nodes.target(legend, '', ids=ids)
            try:
                self.state.add_target(targetid, '', targetnode, lineno)
            except Exception as e:
                raise Exception("Issue in \n  File '{0}', line {1}\ntitle={2}\ntag={3}\ntargetid={4}".format(docname,
                                                                                                             lineno, title, breftag, targetid)) from e

            # index node
            index = self.options.get('index', None)
            if index is not None:
                indexnode = addnodes.index()
                indexnode['entries'] = ne = []
                indexnode['inline'] = False
                set_source_info(self, indexnode)
                for entry in index.split(","):
                    ne.extend(process_index_entry(entry, targetid))
            else:
                indexnode = None
        else:
            targetnode = None
            indexnode = None

        return [a for a in [indexnode, targetnode, blocref] if a is not None]
    def run(self):
        """
        Builds the mathdef text.
        """
        # sett = self.state.document.settings
        # language_code = sett.language_code
        lineno = self.lineno

        env = self.state.document.settings.env if hasattr(
            self.state.document.settings, "env") else None
        docname = None if env is None else env.docname
        if docname is not None:
            docname = docname.replace("\\", "/").split("/")[-1]
            legend = "{0}:{1}".format(docname, lineno)
        else:
            legend = ''

        if hasattr(env, "settings") and hasattr(env.settings, "mathdef_link_number"):
            number_format = env.settings.mathdef_link_number
        elif hasattr(self.state.document.settings, "mathdef_link_number"):
            number_format = self.state.document.settings.mathdef_link_number
        elif hasattr(env, "config") and hasattr(env.config, "mathdef_link_number"):
            number_format = env.config.mathdef_link_number
        else:
            raise ValueError(  # pragma: no cover
                "mathdef_link_number is not defined in the configuration")

        if not self.options.get('class'):
            self.options['class'] = ['admonition-mathdef']

        # body
        (mathdef,) = super(MathDef, self).run()
        if isinstance(mathdef, nodes.system_message):
            return [mathdef]

        # add a label
        lid = self.options.get('lid', self.options.get('label', None))
        if lid:
            container = nodes.container()
            tnl = [".. _{0}:".format(lid), ""]
            content = StringList(tnl)
            self.state.nested_parse(content, self.content_offset, container)
        else:
            container = None

        # mid
        mathtag = self.options.get('tag', '').strip()
        if len(mathtag) == 0:
            raise ValueError("tag is empty")  # pragma: no cover
        if env is not None:
            mid = int(env.new_serialno('indexmathe-u-%s' % mathtag)) + 1
        else:
            mid = -1

        # id of the section
        first_letter = mathtag[0].upper()
        number = mid
        try:
            label_number = number_format.format(
                number=number, first_letter=first_letter)
        except ValueError as e:  # pragma: no cover
            raise Exception(
                "Unable to interpret format '{0}'.".format(number_format)) from e

        # title
        title = self.options.get('title', "").strip()
        if len(title) > 0:
            title = "{0} {1} : {2}".format(mathtag, label_number, title)
        else:
            raise ValueError("title is empty")  # pragma: no cover

        # main node
        ttitle = title
        title = nodes.title(text=_(title))
        if container is not None:
            mathdef.insert(0, title)
            mathdef.insert(0, container)
        else:
            mathdef.insert(0, title)
        mathdef['mathtag'] = mathtag
        mathdef['mathmid'] = mid
        mathdef['mathtitle'] = ttitle
        set_source_info(self, mathdef)

        if env is not None:
            targetid = 'indexmathe-%s%s' % (mathtag,
                                            env.new_serialno('indexmathe%s' % mathtag))
            ids = [targetid]
            targetnode = nodes.target(legend, '', ids=ids[0])
            set_source_info(self, targetnode)
            try:
                self.state.add_target(targetid, '', targetnode, lineno)
            except Exception as e:  # pragma: no cover
                raise Exception(
                    "Issue in\n  File '{0}', line {1}\ntid={2}\ntnode={3}".format(
                        None if env is None else env.docname, lineno,
                        targetid, targetnode)) from e

            # index node
            index = self.options.get('index', None)
            imposed = ",".join(a for a in [mathtag, ttitle] if a)
            if index is None or len(index.strip()) == 0:
                index = imposed
            else:
                index += "," + imposed
            if index is not None:
                indexnode = addnodes.index()
                indexnode['entries'] = ne = []
                indexnode['inline'] = False
                set_source_info(self, indexnode)
                for entry in index.split(","):
                    ne.extend(process_index_entry(entry, targetid))
            else:
                indexnode = None
        else:
            targetnode = None
            indexnode = None

        return [a for a in [indexnode, targetnode, mathdef] if a is not None]
Ejemplo n.º 21
0
    def private_run(self, add_container=False):
        """
        Builds a node @see cl blocref_node.

        @param      add_container       add a container node and return as a second result
        @return                         list of nodes or list of nodes, container
        """
        name_desc = self.__class__.name_sphinx
        lineno = self.lineno

        settings = self.state.document.settings
        env = settings.env if hasattr(settings, "env") else None
        docname = None if env is None else env.docname
        if docname is not None:
            docname = docname.replace("\\", "/").split("/")[-1]
            legend = "{0}:{1}".format(docname, lineno)
        else:
            legend = ''

        if not self.options.get('class'):
            self.options['class'] = ['admonition-%s' % name_desc]

        # body
        (blocref, ) = super(BlocRef, self).run()
        if isinstance(blocref, nodes.system_message):
            return [blocref]

        # add a label
        lid = self.options.get('lid', self.options.get('label', None))
        if lid:
            container = nodes.container()
            tnl = [".. _{0}:".format(lid), ""]
            content = StringList(tnl)
            self.state.nested_parse(content, self.content_offset, container)
        else:
            container = None

        # mid
        breftag = self.options.get('tag', '').strip()
        if len(breftag) == 0:
            raise ValueError("tag is empty")  # pragma: no cover
        if env is not None:
            mid = int(env.new_serialno('index%s-%s' %
                                       (name_desc, breftag))) + 1
        else:
            mid = -1

        # title
        titleo = self.options.get('title', "").strip()
        if len(titleo) == 0:
            raise ValueError("title is empty")  # pragma: no cover
        title = self._update_title(titleo, breftag, mid)

        # main node
        ttitle = title
        title = nodes.title(text=_(title))
        if container is not None:
            blocref.insert(0, title)
            blocref.insert(0, container)
        else:
            blocref.insert(0, title)

        if add_container:
            ret_container = nodes.container()
            blocref += ret_container

        blocref['breftag'] = breftag
        blocref['brefmid'] = mid
        blocref['breftitle'] = ttitle
        blocref['breftitleo'] = titleo
        blocref['brefline'] = lineno
        blocref['breffile'] = docname
        set_source_info(self, blocref)

        if env is not None:
            targetid = 'index%s-%s%s' % (name_desc, breftag,
                                         env.new_serialno(
                                             'index%s%s' %
                                             (name_desc, breftag)))
            blocref["breftargetid"] = targetid
            ids = [targetid]
            targetnode = nodes.target(legend, '', ids=ids)
            set_source_info(self, targetnode)
            try:
                self.state.add_target(targetid, '', targetnode, lineno)
            except Exception as e:  # pragma: no cover
                mes = "Issue in \n  File '{0}', line {1}\ntitle={2}\ntag={3}\ntargetid={4}"
                raise Exception(
                    mes.format(docname, lineno, title, breftag,
                               targetid)) from e

            # index node
            index = self.options.get('index', None)
            if index is not None:
                indexnode = addnodes.index()
                indexnode['entries'] = ne = []
                indexnode['inline'] = False
                set_source_info(self, indexnode)
                for entry in index.split(","):
                    ne.extend(process_index_entry(entry, targetid))
            else:
                indexnode = None
        else:
            targetnode = None
            indexnode = None

        res = [a for a in [indexnode, targetnode, blocref] if a is not None]
        if add_container:
            return res, ret_container
        return res
Ejemplo n.º 22
0
    def run(self):
        env = self.state.document.settings.env
        self.assert_has_content()
        assert self.options
        assert "name" in self.options
        assert "brief" in self.options
        assert "actors" in self.options
        assert "events" in self.options
        assert "results" in self.options

        targetid = "%s" % self.arguments[0]
        targetnode = nodes.target("", "", ids=[targetid])

        # ad = make_topic(usecase, self.name, [_('%s' % self.arguments[0])], self.options,
        #                     self.content, self.lineno, self.content_offset,
        #                     self.block_text, self.state, self.state_machine)

        # we create a section
        idb = nodes.make_id("UseCase-" + self.arguments[0])
        section = nodes.section(ids=[idb])
        # we create a title and we add it to section
        textnodes, messages = self.state.inline_text("UseCase: " + self.options["name"], self.lineno)
        section += nodes.title(self.options["name"], "", *textnodes)
        # we create the content of the blog post
        # because it contains any kind of RST
        # we parse parse it with function nested_parse

        usecase_attributes = nodes.paragraph("", "")
        usecase_attributes["classes"] = ["usecase_attributes"]

        usecase_attributes.append(nodes.paragraph(text="brief: " + _(self.options["brief"])))
        usecase_attributes.append(nodes.paragraph(text="actors: " + _(self.options["actors"])))
        usecase_attributes.append(nodes.paragraph(text="events: " + _(self.options["events"])))
        usecase_attributes.append(nodes.paragraph(text="results: " + _(self.options["results"])))

        par = nodes.paragraph()
        par["classes"].append("usecase_description")
        self.state.nested_parse(self.content, self.content_offset, par)

        node = usecase()
        node += section
        node += usecase_attributes
        node += par

        if not hasattr(env, "usecase_all_usecases"):
            env.usecase_all_usecases = []
        env.usecase_all_usecases.append(
            {"docname": env.docname, "lineno": self.lineno, "usecase-name": self.arguments[0], "target": targetnode}
        )

        # we add an index
        if self.__class__.add_index:
            self.state.document.note_explicit_target(targetnode)
            indexnode = addnodes.index()
            indexnode["entries"] = ne = []
            indexnode["inline"] = False
            set_source_info(self, indexnode)
            # for entry in set("UseCase: " + self.options['name']):
            ne.extend(process_index_entry("UseCase: " + self.options["name"], targetid))  # targetid))
            ns = [indexnode, targetnode, node]
        else:
            ns = [targetnode, node]

        return ns

        # return [targetnode] + node
        return ns
Ejemplo n.º 23
0
    def run(self):
        """
        builds the todo text
        """
        sett = self.state.document.settings
        language_code = sett.language_code
        lineno = self.lineno

        env = self.state.document.settings.env if hasattr(
            self.state.document.settings, "env") else None
        docname = None if env is None else env.docname
        if docname is not None:
            docname = docname.replace("\\", "/").split("/")[-1]
            legend = "{0}:{1}".format(docname, lineno)
        else:
            legend = ''

        if not self.options.get('class'):
            self.options['class'] = ['admonition-todoext']

        # link to issue
        issue = self.options.get('issue', "").strip()
        if issue is not None and len(issue) > 0:
            if hasattr(sett, "extlinks"):
                extlinks = sett.extlinks
            elif env is not None and hasattr(env.config, "extlinks"):
                extlinks = env.config.extlinks
            else:
                available = "\n".join(sorted(sett.__dict__.keys()))
                available2 = "\n".join(sorted(
                    env.config.__dict__.keys())) if env is not None else "-"
                mes = "extlinks (wih a key 'issue') is not defined in the documentation settings, available in sett\n{0}\nCONFIG\n{1}"
                raise ValueError(mes.format(available, available2))

            if "issue" not in extlinks:
                raise KeyError("key 'issue' is not present in extlinks")
            url, label = extlinks["issue"]
            url = url % str(issue)
            lab = label.format(issue)
            linkin = nodes.reference(lab, locale_(lab), refuri=url)
            link = nodes.paragraph()
            link += linkin
        else:
            link = None

        # cost
        cost = self.options.get('cost', "").strip()
        if cost:
            try:
                fcost = float(cost)
            except ValueError:
                raise ValueError(
                    "unable to convert cost '{0}' into float".format(cost))
        else:
            fcost = 0.0

        # priority
        prio = self.options.get('priority', "").strip()

        # hidden
        hidden = self.options.get(
            'hidden', "false").strip().lower() in {'true', '1', ''}

        # body
        (todoext, ) = super(TodoExt, self).run()
        if isinstance(todoext, nodes.system_message):
            return [todoext]

        # link
        if link:
            todoext += link

        # title
        title = self.options.get('title', "").strip()
        todotag = self.options.get('tag', '').strip()
        if len(title) > 0:
            title = ": " + title

        # prefix
        prefix = TITLES[language_code]["todo"]
        tododate = self.options.get('date', "").strip()
        todorelease = self.options.get('release', "").strip()
        infos = []
        if len(todotag) > 0:
            infos.append(todotag)
        if len(prio) > 0:
            infos.append('P=%s' % prio)
        if fcost > 0:
            if int(fcost) == fcost:
                infos.append('C=%d' % int(fcost))
            else:
                infos.append('C=%1.1f' % fcost)
        if todorelease:
            infos.append('v{0}'.format(todorelease))
        if tododate:
            infos.append(tododate)
        if infos:
            prefix += "({0})".format(" - ".join(infos))

        # main node
        title = nodes.title(text=locale_(prefix + title))
        todoext.insert(0, title)
        todoext['todotag'] = todotag
        todoext['todocost'] = fcost
        todoext['todoprio'] = prio
        todoext['todohidden'] = hidden
        todoext['tododate'] = tododate
        todoext['todorelease'] = todorelease
        todoext['todotitle'] = self.options.get('title', "").strip()
        set_source_info(self, todoext)

        if hidden:
            todoext['todoext_copy'] = todoext.deepcopy()
            todoext.clear()

        if env is not None:
            targetid = 'indextodoe-%s' % env.new_serialno('indextodoe')
            targetnode = nodes.target(legend, '', ids=[targetid])
            set_source_info(self, targetnode)
            self.state.add_target(targetid, '', targetnode, lineno)

            # index node
            index = self.options.get('index', None)
            if index is not None:
                indexnode = addnodes.index()
                indexnode['entries'] = ne = []
                indexnode['inline'] = False
                set_source_info(self, indexnode)
                for entry in index.split(","):
                    ne.extend(process_index_entry(entry, targetid))
            else:
                indexnode = None
        else:
            targetnode = None
            indexnode = None

        return [a for a in [indexnode, targetnode, todoext] if a is not None]
Ejemplo n.º 24
0
    def run(self):
        """
        extracts the information in a dictionary and displays it
        if the environment is not null

        @return      a list of nodes
        """
        # settings
        sett = self.state.document.settings
        language_code = sett.language_code
        if hasattr(sett, "out_blogpostlist"):
            sett.out_blogpostlist.append(self)

        # env
        if hasattr(self.state.document.settings, "env"):
            env = self.state.document.settings.env
        else:
            env = None

        if env is None:
            docname = "___unknown_docname___"
            config = None
            blog_background = False
            sharepost = None
        else:
            # otherwise, it means sphinx is running
            docname = env.docname
            # settings and configuration
            config = env.config
            blog_background = config.blog_background
            sharepost = config.sharepost if self.__class__.add_share else None

        # post
        p = {
            'docname': docname,
            'lineno': self.lineno,
            'date': self.options["date"],
            'title': self.options["title"],
            'keywords': [a.strip() for a in self.options["keywords"].split(",")],
            'categories': [a.strip() for a in self.options["categories"].split(",")],
            'blog_background': self.options.get("blog_background", str(blog_background)).strip() in ("True", "true", "1"),
            'lid': self.options.get("lid", self.options.get("label", None)),
        }

        tag = BlogPost.build_tag(p["date"], p["title"]) if p[
            'lid'] is None else p['lid']
        targetnode = nodes.target(p['title'], '', ids=[tag])
        p["target"] = targetnode
        idbp = tag + "-container"

        if env is not None:
            if not hasattr(env, 'blogpost_all'):
                env.blogpost_all = []
            env.blogpost_all.append(p)

        # build node
        node = self.__class__.blogpost_class(ids=[idbp], year=p["date"][:4],
                                             rawfile=self.options.get(
                                                 "rawfile", None),
                                             linktitle=p[
                                                 "title"], lg=language_code,
                                             blog_background=p["blog_background"])

        # add a label
        suffix_label = self.suffix_label()
        container = nodes.container()
        tnl = [".. _{0}{1}:".format(tag, suffix_label), ""]
        content = StringList(tnl)
        self.state.nested_parse(content, self.content_offset, container)
        node += container

        # id section
        if env is not None:
            mid = int(env.new_serialno('indexblog-u-%s' % p["date"][:4])) + 1
        else:
            mid = -1

        # add title
        sids = "y{0}-{1}".format(p["date"][:4], mid)
        section = nodes.section(ids=[sids])
        section['year'] = p["date"][:4]
        section['blogmid'] = mid
        node += section
        textnodes, messages = self.state.inline_text(p["title"], self.lineno)
        section += nodes.title(p["title"], '', *textnodes)
        section += messages

        # add date and share buttons
        tnl = [":bigger:`::5:{0}`".format(p["date"])]
        if sharepost is not None:
            tnl.append(":sharenet:`{0}`".format(sharepost))
        tnl.append('')
        content = StringList(tnl)
        content = content + self.content

        # parse the content into sphinx directive, we add it to section
        container = nodes.container()
        # nested_parse_with_titles(self.state, content, paragraph)
        self.state.nested_parse(content, self.content_offset, container)
        section += container

        # final
        p['blogpost'] = node
        self.exe_class = p.copy()
        p["content"] = content
        node['classes'] += "-blogpost"

        # target
        # self.state.add_target(p['title'], '', targetnode, lineno)

        # index (see site-packages/sphinx/directives/code.py, class Index)
        if self.__class__.add_index:
            # we add an index
            # self.state.document.note_explicit_target(targetnode)
            indexnode = addnodes.index()
            indexnode['entries'] = ne = []
            indexnode['inline'] = False
            set_source_info(self, indexnode)
            for entry in set(p["keywords"] + p["categories"] + [p["date"]]):
                ne.extend(process_index_entry(entry, tag))  # targetid))
            ns = [indexnode, targetnode, node]
        else:
            ns = [targetnode, node]

        return ns
Ejemplo n.º 25
0
    def run(self):
        """
        extracts the information in a dictionary and displays it
        if the environment is not null

        @return      a list of nodes
        """
        # settings
        sett = self.state.document.settings
        language_code = sett.language_code
        if hasattr(sett, "out_blogpostlist"):
            sett.out_blogpostlist.append(self)

        # env
        if hasattr(self.state.document.settings, "env"):
            env = self.state.document.settings.env
        else:
            env = None

        if env is None:
            # we need an access to the environment to process the blog post
            # this path is used by the BlogPost class to extract the content of
            # the job
            return []
        else:
            # otherwise, it means sphinx is running
            pass

        # settings and configuration
        config = env.config
        blog_background = config.blog_background

        # post
        p = {
            'docname': env.docname,
            'lineno': self.lineno,
            'date': self.options["date"],
            'title': self.options["title"],
            'keywords': [_.strip() for _ in self.options["keywords"].split(",")],
            'categories': [_.strip() for _ in self.options["categories"].split(",")],
            'blog_background': self.options.get("blog_background", str(blog_background)).strip() in ("True", "true", "1"),
        }

        # label
        #targetid = "blogpost-%d" % env.new_serialno('blogpost')
        #targetnode = nodes.target('', '', ids=[targetid])
        #p["target"] = targetnode

        tag = BlogPost.build_tag(p["date"], p["title"])
        targetnode = nodes.target('', '', ids=[tag])
        p["target"] = targetnode

        if not hasattr(env, 'blogpost_all'):
            env.blogpost_all = []
        env.blogpost_all.append(p)

        # we add a title
        idb = nodes.make_id("blog-" + p["date"] + "-" + p["title"])
        idbp = nodes.make_id("blogcl-" + p["date"] + "-" + p["title"])
        section = nodes.section(ids=[idb])

        textnodes, messages = self.state.inline_text(p["title"], self.lineno)
        section += nodes.title(p["title"], '', *textnodes)
        section += messages

        # build node
        node = self.__class__.blogpost_class(ids=[idbp], year=p["date"][:4],
                                             rawfile=self.options.get(
                                                 "rawfile", None),
                                             linktitle=p["title"],
                                             lg=language_code,
                                             blog_background=p["blog_background"])
        node += section

        # we add the date
        content = StringList(["**{0}**".format(p["date"]), ""])
        content = content + self.content

        # parse the content into sphinx directive, we add it to section
        paragraph = nodes.paragraph()
        self.state.nested_parse(content, self.content_offset, paragraph)
        node += paragraph
        p['blogpost'] = node

        # classes
        node['classes'] += "-blogpost"

        # create a reference
        refnode = nodes.reference('', '', internal=True)
        refnode['refid'] = tag
        refnode['reftitle'] = p["title"]
        # still does not work

        # index (see site-packages/sphinx/directives/code.py, class Index)
        if self.__class__.add_index:
            # we add an index
            self.state.document.note_explicit_target(targetnode)
            indexnode = addnodes.index()
            indexnode['entries'] = ne = []
            indexnode['inline'] = False
            set_source_info(self, indexnode)
            for entry in set(p["keywords"] + p["categories"] + [p["date"]]):
                ne.extend(process_index_entry(entry, tag))  # targetid))
            ns = [indexnode, targetnode, node]
        else:
            ns = [targetnode, node]

        return ns