summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibMarkdown/LineIterator.h
blob: 8109e1d8e43ccfff9a8ff99e49d9a2904d5291e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
 * Copyright (c) 2021, Peter Elliott <pelliott@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Iterator.h>
#include <AK/StringView.h>
#include <AK/Vector.h>

namespace Markdown {

template<typename T>
class FakePtr {
public:
    FakePtr(T item)
        : m_item(move(item))
    {
    }

    T const* operator->() const { return &m_item; }
    T* operator->() { return &m_item; }

private:
    T m_item;
};

class LineIterator {
public:
    struct Context {
        enum class Type {
            ListItem,
            BlockQuote,
        };

        Type type;
        size_t indent;
        bool ignore_prefix;

        static Context list_item(size_t indent) { return { Type::ListItem, indent, true }; }
        static Context block_quote() { return { Type::BlockQuote, 0, false }; }
    };

    LineIterator(Vector<StringView>::ConstIterator const& lines)
        : m_iterator(lines)
    {
    }

    bool is_end() const;
    StringView operator*() const;

    LineIterator operator++()
    {
        reset_ignore_prefix();
        ++m_iterator;
        return *this;
    }

    LineIterator operator++(int)
    {
        LineIterator tmp = *this;
        reset_ignore_prefix();
        ++m_iterator;
        return tmp;
    }

    LineIterator operator+(ptrdiff_t delta) const
    {
        LineIterator copy = *this;
        copy.reset_ignore_prefix();
        copy.m_iterator = copy.m_iterator + delta;
        return copy;
    }

    LineIterator operator-(ptrdiff_t delta) const
    {
        LineIterator copy = *this;
        copy.reset_ignore_prefix();
        copy.m_iterator = copy.m_iterator - delta;
        return copy;
    }

    ptrdiff_t operator-(LineIterator other) const { return m_iterator - other.m_iterator; }

    FakePtr<StringView> operator->() const { return FakePtr<StringView>(operator*()); }

    void push_context(Context context) { m_context_stack.append(move(context)); }
    void pop_context() { m_context_stack.take_last(); }

private:
    void reset_ignore_prefix();
    Optional<StringView> match_context(StringView const& line) const;

    Vector<StringView>::ConstIterator m_iterator;
    Vector<Context> m_context_stack;
};

}