當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。