Exemplo n.º 1
0
def test_empty_blocklist():
    "Test function block with zero lines"
    text = trim("""
        TEXT ---
        Hi!
        ---
        """)
    blocks = BlockList(text)
    assert class_list(blocks) == ['FunctionBlock']
    assert blocks.text() == text
Exemplo n.º 2
0
def test_pop_titles_oneline():
    """
    We should be able to extract the title and summary lines.
    """
    text = trim("""
        Title
        """)
    blocks = BlockList(text)
    title, summary = blocks.pop_titles()
    assert title == "Title"
    assert summary == ""
    assert blocks.text() == ""
Exemplo n.º 3
0
def test_nested_blocklist():
    "Test function block with zero lines"
    text = trim("""
        LEFT (35%) ---
        TEXT ===
        Hi!
        ===
        ---
        """)
    blocks = BlockList(text)
    assert class_list(blocks) == ['FunctionBlock']
    subclass_list = [
        _.__class__.__name__ for _ in list(iter(blocks))[0].blocks
    ]
    assert subclass_list == ['FunctionBlock']
    assert blocks.text() == text
Exemplo n.º 4
0
 def extract(self, parts: dict):
     """
     Scan the index_part for global document settings; these parts should
     have already had DEMO blocks removed, as they can also contain
     settings.
     """
     if 'index' in parts:
         blocks = BlockList(parts['index']).find('CharacterBlock', '$')
         for block in blocks:
             self.read_settings_block(block.content)
Exemplo n.º 5
0
def reformat_part(slug, part):
    """
    Normalise the layout of user-entered text. Remove bibliography and Demo
    blocks, process as a Blocklist, then put them back.
    """
    if slug == 'biblio':
        return part
    else:
        content, bibliography = split_bibliography(clean_text(part))
        demo_placeholders = Demo(Settings())
        parts_sans_demo_blocks = demo_placeholders.insert({slug: content})
        blocks = BlockList(parts_sans_demo_blocks[slug])
        out_sans_demo_blocks = blocks.text()
        out_parts = demo_placeholders.replace({slug: out_sans_demo_blocks},
                                              lambda text, slug: text)
        out = out_parts[slug]
        if bibliography:
            out += "\n\n\n_____\n\n" + bibliography
        return out
Exemplo n.º 6
0
def match_footnotes(text):
    """
    Find the footnote references in a block of text.
    """
    def join_lists(_):
        return [elem for sublist in _ for elem in sublist]

    footnotes = join_lists([
        split_to_array(_.content, '^', capture_characters=False)
        for _ in BlockList(text).find('CharacterBlock', '^')
    ])
    return {count: _ for count, _ in zip(Numbers(), footnotes)}
Exemplo n.º 7
0
def test_find():
    """
    s
    """
    text = trim("""
        Title

        = Summary

        @ Heading

        OK

        @ Subheading

        OK
        """)
    blocks = BlockList(text)
    headings = blocks.find('CharacterBlock', "@")
    assert class_list(headings) == [
        'CharacterBlock',
        'CharacterBlock',
    ]
Exemplo n.º 8
0
def extract_outline(text: str, counters: list) -> list:
    """
    Pull back the first outline block from wiki text.

    - Chapter One
    - - Heading
    """
    for _ in BlockList(text):
        if isinstance(_, CharacterBlock) and _.control_character == "-":
            hierarchy = split_to_recursive_array(_.content, '- ')
            enumeration = enumerate_list(hierarchy, counters, [])
            outline = [(numbering, (slugify(_), _, slugify(_), ''))
                       for numbering, _ in enumeration]
            return outline
    return []
Exemplo n.º 9
0
    def make_section(self,
                     numbering,
                     slug,
                     text,
                     fragment=False,
                     preview=False):
        """
        Wrap section HTML in titles and nav.
        A fragment has no heading. A preview has a heading but no context,so no
        numbering.
        """
        env = Environment(autoescape=True)
        tpl = env.from_string(
            trim("""
        <section class="body depth-{{ depth }}">
        {% if not fragment %}
        <nav class="button-list button-list-edge no-preview no-print">
            <a class="button" href="{{ edit_link }}">
                <i class="fa fa-pencil"></i> Edit
            </a>
        </nav>
        {% endif %}
        {{ content_html|safe }}
        </section>
        """))

        content, _ = split_bibliography(text)
        blocks = BlockList(content)
        content_html = blocks.html(numbering, slug, self.settings, fragment,
                                   preview)

        return tpl.render(depth=len(numbering),
                          edit_link=self.settings.get_base_uri('edit') + '/' +
                          slug,
                          content_html=content_html,
                          fragment=fragment)
Exemplo n.º 10
0
def test_empty_function_block():
    spaced = trim("""
        COMPACT ---

        ---
        """)
    unspaced = trim("""
        COMPACT ---
        ---
        """)
    blocks = BlockList(spaced)
    assert blocks.text() == unspaced
    blocks = BlockList(unspaced)
    assert blocks.text() == unspaced
Exemplo n.º 11
0
def user_page(user_slug):
    """
    Show <user_slug>/fixtures/author + user documents.
    """
    header_buttons = [login_or_logout_button()]
    login = get_login()
    if login and login['username'] == user_slug:
        header_buttons += [
            new_article_button(user_slug),
        ]

    header_buttons += [
        edit_button(user_slug, 'fixtures', 'author'),
    ]

    if not login:
        header_buttons += [subscribe_button(), rss_button(user_slug)]

    footer_buttons = []
    if config['ARTICLE_WIKI_CREDIT'] == 'YES':
        footer_buttons += [source_button()]
    footer_buttons += [help_button()]
    if has_authority_for_user(user_slug):
        footer_buttons += [export_archive_button(user_slug)]

    slugs = data.userDocumentSet_list(user_slug)
    changes_list = data.userDocumentLastChanged_list(user_slug)

    if not has_authority_for_user(user_slug):
        # Show only those that have been published
        changes_list, __ = split_published(changes_list)

    article_slugs = [_ for _ in slugs if _ not in ['fixtures', 'templates']]
    article_keys = [
        data.userDocumentMetadata_key(user_slug, _) for _ in article_slugs
    ]
    article_list = sorted(data.get_hashes(article_keys),
                          key=lambda _: _.get('title', ''))

    published_articles, unpublished_articles = split_published(article_list)
    if not has_authority_for_user(user_slug):
        unpublished_articles = []

    settings = Settings({
        'config:host': domain_name(bottle.request),
        'config:user': user_slug,
        'config:document': 'fixtures',
    })
    wiki = Wiki(settings)
    document = data.userDocument_get(user_slug, 'fixtures')
    if not document:
        msg = "User '{:s}' not found."
        bottle.abort(HTTP_NOT_FOUND, msg.format(user_slug))
    if 'author' in document:
        text = document['author']
    else:
        text = trim("""
            Author Page

            (Author information to be added here...)
            """)

    blocks = BlockList(clean_text(text))
    page_title, page_summary = blocks.pop_titles()
    content_html = wiki.process(None,
                                None, {'index': blocks.text()},
                                fragment=True,
                                preview=True)
    inline = Inline()

    return views.get_template('user.html').render(
        config=config,
        user=user_slug,
        page_title="{:s} - {:s}".format(page_title, page_summary),
        title_html=inline.process(page_title),
        summary_html=inline.process(page_summary),
        header_buttons=header_buttons,
        footer_buttons=footer_buttons,
        changes_list=changes_list,
        published_articles=published_articles,
        unpublished_articles=unpublished_articles,
        content_html=content_html,
        pluralize=pluralize  # <-- hack function injection
    )
Exemplo n.º 12
0
def test_blocklist():
    "List of blocks..."
    # 1
    text = trim("""
        @ Heading

        Paragraph

        - - -

        Paragraph

        TEXT (verse) ---
        Text
        ---

        Paragraph

        TEXT ---
        Text
        ---
        """)
    blocks = BlockList(text)
    assert class_list(blocks) == [
        'CharacterBlock',
        'Paragraph',
        'Divider',
        'Paragraph',
        'FunctionBlock',
        'Paragraph',
        'FunctionBlock',
    ]
    assert blocks.text() == "\n" + text
    # 2
    text = trim("""
        TEXT ---
        Text
        ---


        @ Heading

        Paragraph

        - - -

        Paragraph

        TEXT (verse) ---
        Text
        ---

        Paragraph
        """)
    blocks = BlockList(text)
    assert class_list(blocks) == [
        'FunctionBlock',
        'CharacterBlock',
        'Paragraph',
        'Divider',
        'Paragraph',
        'FunctionBlock',
        'Paragraph',
    ]
    assert blocks.text() == text
Exemplo n.º 13
0
    def make_index(self, text):
        """
        Front matter preceding index text.
        Multi-author blocks are disabled for now; v.0.1.0 is SINGLE_USER.
        """
        env = Environment(autoescape=True)
        tpl = env.from_string(
            trim("""
        <header>

            {% if title_html != "" %}
            <hgroup>
                <h1 class="balance-text">{{ title_html|safe }}</h1>
            {% if summary != "" %}
                <h2 class="balance-text">{{ summary_html|safe }}</h2>
            {% endif %}
            </hgroup>
            {% endif %}

            {% if author != "" or email != "" %}
            <div class="author-list">
                <address>
                {% if author != "" %}
                    <div>{{ author }}</div>
                {% endif %}
                {% if email != "" %}
                    <div><a href="mailto:{{ email }}">{{ email }}</a></div>
                {% endif %}
                </address>
            </div>
            {% endif %}

            {% if facebook != "" or twitter != "" %}
            <p class="space space-between">
                {% if facebook != "" %}
                <a href="https://facebook.com/{{ facebook }}" target="_blank">
                    FB: {{ facebook }}
                </a>
                {% endif %}
                {% if twitter != "" %}
                <a href="https://twitter.com/{{ twitter }}" target="_blank">
                    TW: {{ twitter }}
                </a>
                {% endif %}
            </p>
            {% endif %}

            {% if date %}
            <p class="space" rel="date">
                {% if parsed_date != None %}
                <time pubdate datetime="{{ parsed_date }}">{{ date }}</time>
                {% else %}
                {{ date }}
                {% endif %}
            </p>
            {% endif %}

        </header>
        <section class="depth-0">
            {{ content_html|safe }}
        </section>
        """))

        inline = Inline()
        content, _ = split_bibliography(text)
        blocks = BlockList(content)
        title, summary = blocks.pop_titles()
        content_html = blocks.html(['0'],
                                   'index',
                                   self.settings,
                                   fragment=True)

        date_string = inline.process(self.settings.get('DATE', ''))
        try:
            dt = parse(date_string)
            date_yyyymmdd = dt.date().isoformat()
        except ValueError:
            date_yyyymmdd = None

        # author = self.split_author()
        return tpl.render(
            title_html=inline.process(title),
            summary_html=inline.process(summary),
            author=self.settings.get('AUTHOR', ''),
            email=self.settings.get('EMAIL', ''),
            facebook=self.settings.get('FACEBOOK', ''),
            twitter=self.settings.get('TWITTER', ''),
            date=date_string,
            parsed_date=date_yyyymmdd,
            edit_link=self.settings.get_base_uri('edit') + '/index',
            content_html=content_html,
        )