当前位置: 首页>>代码示例>>Python>>正文


Python pandocfilters.Str方法代码示例

本文整理汇总了Python中pandocfilters.Str方法的典型用法代码示例。如果您正苦于以下问题:Python pandocfilters.Str方法的具体用法?Python pandocfilters.Str怎么用?Python pandocfilters.Str使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pandocfilters的用法示例。


在下文中一共展示了pandocfilters.Str方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: attach_attrs_table

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def attach_attrs_table(key, value, fmt, meta):
    """Extracts attributes and attaches them to element."""

    # We can't use attach_attrs_factory() because Table is a block-level element
    if key in ['Table']:
        assert len(value) == 5
        caption = value[0]  # caption, align, x, head, body

        # Set n to the index where the attributes start
        n = 0
        while n < len(caption) and not \
          (caption[n]['t'] == 'Str' and caption[n]['c'].startswith('{')):
            n += 1

        try:
            attrs = extract_attrs(caption, n)
            value.insert(0, attrs.list)
        except (ValueError, IndexError):
            pass

# pylint: disable=too-many-branches 
开发者ID:tomduck,项目名称:pandoc-tablenos,代码行数:23,代码来源:pandoc_tablenos.py

示例2: dollarfy

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def dollarfy(x):
    """Replaces Math elements in element list `x` with a $-enclosed string.

    stringify() passes through TeX math.  Use dollarfy(x) first to replace
    Math elements with math strings set in dollars.  `x` should be a deep copy
    so that the underlying document is left untouched.

    Returns `x`, modified in-place.
    """

    def _dollarfy(key, value, fmt, meta):  # pylint: disable=unused-argument
        """Replaces Math elements"""
        if key == 'Math':
            return Str('$' + value[1] + '$')
        return None

    return walk(x, _dollarfy, '', {})


# extract_attrs() ------------------------------------------------------------ 
开发者ID:tomduck,项目名称:pandoc-xnos,代码行数:22,代码来源:core.py

示例3: join_strings

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def join_strings(key, value, fmt=None, meta=None):
    """Joins adjacent Str elements found in `value`."""
    if key in ['Para', 'Plain']:
        _join_strings(value)
    elif key == 'Span':
        _join_strings(value, 1)
    elif key == 'Image':
        _join_strings(value[-2])
    elif key == 'Table':
        _join_strings(value[-5])


# repair_refs() -------------------------------------------------------------

# Reference pattern.  This splits a reference into three components: the
# prefix, label and suffix.  e.g.:
# >>> _REF.match('xxx{+@fig:1}xxx').groups()
# ('xxx{+', 'fig:1', '}xxx'). 
开发者ID:tomduck,项目名称:pandoc-xnos,代码行数:20,代码来源:core.py

示例4: repair_refs

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def repair_refs(key, value, fmt, meta):  # pylint: disable=unused-argument
    """Using '-f markdown+autolink_bare_uris' with pandoc < 1.18 splits a
    reference like '{@fig:one}' into email Link and Str elements.  This
    function replaces the mess with the Cite and Str elements we normally
    get.  Call this before any reference processing."""

    if _PANDOCVERSION >= '1.18':
        return

    # The problem spans multiple elements, and so can only be identified in
    # element lists.  Element lists are encapsulated in different ways.  We
    # must process them all.

    if key in ('Para', 'Plain'):
        _repair_refs(value)
    elif key == 'Image':
        _repair_refs(value[-2])
    elif key == 'Table':
        _repair_refs(value[-5])


# process_refs_factory() ----------------------------------------------------- 
开发者ID:tomduck,项目名称:pandoc-xnos,代码行数:24,代码来源:core.py

示例5: _adjust_caption

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def _adjust_caption(fmt, table, value):
    """Adjusts the caption."""
    attrs, caption = table['attrs'], table['caption']
    num = references[attrs.id].num
    if fmt in['latex', 'beamer']:  # Append a \label if this is referenceable
        if not table['is_unreferenceable']:
            value[1] += [RawInline('tex', r'\label{%s}'%attrs.id)]
    else:  # Hard-code in the caption name and number/tag
        sep = {'none':'', 'colon':':', 'period':'.', 'space':' ',
               'quad':u'\u2000', 'newline':'\n'}[separator]

        if isinstance(num, int):  # Numbered reference
            if fmt in ['html', 'html5', 'epub', 'epub2', 'epub3']:
                value[1] = [RawInline('html', r'<span>'),
                            Str(captionname), Space(),
                            Str('%d%s'%(num, sep)),
                            RawInline('html', r'</span>')]
            else:
                value[1] = [Str(captionname),
                            Space(),
                            Str('%d%s'%(num, sep))]
            value[1] += [Space()] + list(caption)
        else:  # Tagged reference
            assert isinstance(num, STRTYPES)
            if num.startswith('$') and num.endswith('$'):
                math = num.replace(' ', r'\ ')[1:-1]
                els = [Math({"t":"InlineMath", "c":[]}, math), Str(sep)]
            else:  # Text
                els = [Str(num + sep)]
            if fmt in ['html', 'html5', 'epub', 'epub2', 'epub3']:
                value[1] = \
                  [RawInline('html', r'<span>'),
                   Str(captionname),
                   Space()] + els + [RawInline('html', r'</span>')]
            else:
                value[1] = [Str(captionname), Space()] + els
            value[1] += [Space()] + list(caption) 
开发者ID:tomduck,项目名称:pandoc-tablenos,代码行数:39,代码来源:pandoc_tablenos.py

示例6: get_meta

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def get_meta(meta, name):
    """Retrieves the metadata variable `name` from the `meta` dict."""
    assert name in meta
    data = meta[name]

    if data['t'] in ['MetaString', 'MetaBool']:
        return data['c']
    if data['t'] == 'MetaInlines':
        # Handle bug in pandoc 2.2.3 and 2.2.3.1: Return boolean value rather
        # than strings, as appropriate.
        if len(data['c']) == 1 and data['c'][0]['t'] == 'Str':
            if data['c'][0]['c'] in ['true', 'True', 'TRUE']:
                return True
            if data['c'][0]['c'] in ['false', 'False', 'FALSE']:
                return False
        return stringify(data['c'])
    if data['t'] == 'MetaList':
        try:  # Process MetaList of MetaMaps
            ret = []
            for v in data['c']:
                assert v['t'] == 'MetaMap'
                entry = {}
                for key in v['c']:
                    entry[key] = stringify(v['c'][key])
                ret.append(entry)
            return ret
        except AssertionError:
            pass
        return [stringify(v['c']) for v in data['c']]
    if data['t'] == 'MetaMap':
        ret = {}
        for key in data['c']:
            ret[key] = stringify(data['c'][key])
        return ret
    raise RuntimeError("Could not understand metadata variable '%s'." % name)


# elt() ---------------------------------------------------------------------- 
开发者ID:tomduck,项目名称:pandoc-xnos,代码行数:40,代码来源:core.py

示例7: quotify

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def quotify(x):
    """Replaces Quoted elements in element list `x` with quoted strings.

    Pandoc uses the Quoted element when '--smart' is enabled.  Note that
    output to TeX/pdf automatically triggers '--smart'.

    stringify() ignores Quoted elements.  Use quotify() first to replace
    Quoted elements in `x` with quoted strings.  `x` should be a deep copy so
    that the underlying document is left untouched.

    Returns `x`, modified in-place.
    """

    def _quotify(key, value, fmt, meta):  # pylint: disable=unused-argument
        """Replaced Quoted elements with quoted strings."""
        if key == 'Quoted':
            ret = []
            quote = '"' if value[0]['t'] == 'DoubleQuote' else "'"
            if value[1][0]['t'] == 'Str':
                value[1][0]['c'] = quote + value[1][0]['c']
            else:
                ret.append(Str(quote))

            if value[1][-1]['t'] == 'Str':
                value[1][-1]['c'] = value[1][-1]['c'] + quote
                ret += value[1]
            else:
                ret += value[1] + [Str(quote)]
            return ret
        return None

    return walk(walk(x, _quotify, '', {}), join_strings, '', {})


# dollarfy() ----------------------------------------------------------------- 
开发者ID:tomduck,项目名称:pandoc-xnos,代码行数:37,代码来源:core.py

示例8: _join_strings

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def _join_strings(x, start=0):
    """Joins adjacent Str elements found in the element list `x`."""
    for i in range(start, len(x)-1):  # Process successive pairs of elements
        if x[i]['t'] == 'Str' and x[i+1]['t'] == 'Str':
            x[i]['c'] += x[i+1]['c']
            del x[i+1]  # In-place deletion of element from list
            return None  # Forces processing to repeat
    return True  # Terminates processing

# pylint: disable=unused-argument 
开发者ID:tomduck,项目名称:pandoc-xnos,代码行数:12,代码来源:core.py

示例9: detach_attrs_factory

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def detach_attrs_factory(f, restore=False):
    """Returns detach_attrs(key, value, fmt, meta) action that detaches
    attributes attached to elements of type `f` (e.g. pandocfilters.Math, etc).
    Attributes provided natively by pandoc are left as is."""

    # Get the name and standard length
    name = f.__closure__[0].cell_contents
    n = f.__closure__[1].cell_contents

    def detach_attrs(key, value, fmt, meta):  # pylint: disable=unused-argument
        """Detaches the attributes."""
        if key == name:
            assert len(value) <= n+1
            if len(value) == n+1:
                # Make sure value[0] represents attributes then delete
                assert len(value[0]) == 3
                assert isinstance(value[0][0], STRTYPES)
                assert isinstance(value[0][1], list)
                assert isinstance(value[0][2], list)
                attrs = PandocAttributes(value[0], 'pandoc')
                del value[0]
                if restore:
                    return [elt(key, *value), Str(attrs.to_markdown())]
        return None

    return detach_attrs


# insert_secnos_factory() ---------------------------------------------------- 
开发者ID:tomduck,项目名称:pandoc-xnos,代码行数:31,代码来源:core.py

示例10: _adjust_caption

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def _adjust_caption(fmt, fig, value):
    """Adjusts the caption."""
    attrs, caption = fig['attrs'], fig['caption']
    if fmt in ['latex', 'beamer']:  # Append a \label if this is referenceable
        if PANDOCVERSION < '1.17' and not fig['is_unreferenceable']:
            # pandoc >= 1.17 installs \label for us
            value[0]['c'][1] += \
              [RawInline('tex', r'\protect\label{%s}'%attrs.id)]
    else:  # Hard-code in the caption name and number/tag
        if fig['is_unnumbered']:
            return
        sep = {'none':'', 'colon':':', 'period':'.', 'space':' ',
               'quad':u'\u2000', 'newline':'\n'}[separator]

        num = targets[attrs.id].num
        if isinstance(num, int):  # Numbered target
            if fmt in ['html', 'html5', 'epub', 'epub2', 'epub3']:
                value[0]['c'][1] = [RawInline('html', r'<span>'),
                                    Str(captionname), Space(),
                                    Str('%d%s' % (num, sep)),
                                    RawInline('html', r'</span>')]
            else:
                value[0]['c'][1] = [Str(captionname),
                                    Space(),
                                    Str('%d%s' % (num, sep))]
            value[0]['c'][1] += [Space()] + list(caption)
        else:  # Tagged target
            if num.startswith('$') and num.endswith('$'):  # Math
                math = num.replace(' ', r'\ ')[1:-1]
                els = [Math({"t":"InlineMath", "c":[]}, math), Str(sep)]
            else:  # Text
                els = [Str(num+sep)]
            if fmt in ['html', 'html5', 'epub', 'epub2', 'epub3']:
                value[0]['c'][1] = \
                  [RawInline('html', r'<span>'),
                   Str(captionname),
                   Space()] + els + [RawInline('html', r'</span>')]
            else:
                value[0]['c'][1] = [Str(captionname), Space()] + els
            value[0]['c'][1] += [Space()] + list(caption) 
开发者ID:tomduck,项目名称:pandoc-fignos,代码行数:42,代码来源:pandoc_fignos.py

示例11: _add_markup

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def _add_markup(fmt, eq, value):
    """Adds markup to the output."""

    attrs = eq['attrs']

    # Context-dependent output
    if eq['is_unnumbered']:  # Unnumbered is also unreferenceable
        ret = None
    elif fmt in ['latex', 'beamer']:
        ret = RawInline('tex',
                        r'\begin{equation}%s\end{equation}'%value[-1])
    elif fmt in ('html', 'html5', 'epub', 'epub2', 'epub3') and \
      LABEL_PATTERN.match(attrs.id):
        # Present equation and its number in a span
        num = str(references[attrs.id].num)
        outer = RawInline('html',
                          '<span%sclass="eqnos">' % \
                            (' ' if eq['is_unreferenceable'] else
                             ' id="%s" '%attrs.id))
        inner = RawInline('html', '<span class="eqnos-number">')
        eqno = Math({"t":"InlineMath"}, '(%s)' % num[1:-1]) \
          if num.startswith('$') and num.endswith('$') \
          else Str('(%s)' % num)
        endtags = RawInline('html', '</span></span>')
        ret = [outer, AttrMath(*value), inner, eqno, endtags]
    elif fmt == 'docx':
        # As per http://officeopenxml.com/WPhyperlink.php
        bookmarkstart = \
          RawInline('openxml',
                    '<w:bookmarkStart w:id="0" w:name="%s"/><w:r><w:t>'
                    %attrs.id)
        bookmarkend = \
          RawInline('openxml',
                    '</w:t></w:r><w:bookmarkEnd w:id="0"/>')
        ret = [bookmarkstart, AttrMath(*value), bookmarkend]
    return ret 
开发者ID:tomduck,项目名称:pandoc-eqnos,代码行数:38,代码来源:pandoc_eqnos.py

示例12: metavars

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def metavars(key, value, format, meta):
    if key == 'Str':
        m = pattern.match(value)
        if m:
            field = m.group(1)
            result = meta.get(field, {})
            if 'MetaInlines' in result['t']:
                return Span(attributes({'class': 'interpolated',
                                        'field': field}),
                            result['c'])
            elif 'MetaString' in result[t]:
                return Str(result['c']) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:14,代码来源:metavars.py

示例13: graphviz

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def graphviz(key, value, format, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        caption = "caption"
        if "graphviz" in classes:
            G = pygraphviz.AGraph(string=code)
            G.layout()
            filename = sha1(code)
            if format == "html":
                filetype = "png"
            elif format == "latex":
                filetype = "pdf"
            else:
                filetype = "png"
            alt = Str(caption)
            src = imagedir + '/' + filename + '.' + filetype
            if not os.path.isfile(src):
                try:
                    os.mkdir(imagedir)
                    sys.stderr.write('Created directory ' + imagedir + '\n')
                except OSError:
                    pass
                G.draw(src)
                sys.stderr.write('Created image ' + src + '\n')
            tit = ""
            return Para([Image(['', [], []], [alt], [src, tit])]) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:28,代码来源:graphviz.py

示例14: filter_keyvalues

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def filter_keyvalues(kv):
  res = []
  caption = []
  for k,v in kv:
    if k == u"caption":
      caption = [ Str(v) ]
    else:
      res.append( [k,v] )

  return caption, "fig:" if caption else "", res 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:12,代码来源:plantuml.py

示例15: caps

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Str [as 别名]
def caps(key, value, format, meta):
    if key == 'Str':
        return Str(value.upper()) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:5,代码来源:caps.py


注:本文中的pandocfilters.Str方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。