summaryrefslogtreecommitdiff
path: root/src/function_group.hh
blob: 739b7ffbfa963607b761b1cd8841152c8494d348 (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
#ifndef function_group_hh_INCLUDED
#define function_group_hh_INCLUDED

#include "exception.hh"
#include "idvaluemap.hh"
#include "string.hh"

namespace Kakoune
{

template<typename... Args>
class FunctionGroup
{
public:
    using Function = std::function<void (Args...)>;
    using FunctionAndId = std::pair<String, std::function<void (Args...)>>;

    void operator()(Args&&... args)
    {
        for (auto& func : m_functions)
           func.second(std::forward<Args>(args)...);
    }

    void append(FunctionAndId&& function)
    {
        if (m_functions.contains(function.first))
            throw runtime_error("duplicate id: " + function.first);

        m_functions.append(std::forward<FunctionAndId>(function));
    }
    void remove(const String& id)
    {
        m_functions.remove(id);
    }

    FunctionGroup& get_group(const String& id)
    {
        auto it = m_functions.find(id);
        if (it == m_functions.end())
            throw runtime_error("no such id: " + id);
        FunctionGroup* group = it->second.template target<FunctionGroup>();
        if (not group)
            throw runtime_error("not a group: " + id);
        return *group;
    }

    CandidateList complete_id(const String& prefix, ByteCount cursor_pos) const
    {
        return m_functions.complete_id(prefix, cursor_pos);
    }

    CandidateList complete_group_id(const String& prefix, ByteCount cursor_pos) const
    {
        return m_functions.complete_id_if(
            prefix, cursor_pos, [](const FunctionAndId& func) {
                return func.second.template target<FunctionGroup>() != nullptr;
            });
    }

private:
    idvaluemap<String, Function> m_functions;
};

}

#endif // function_group_hh_INCLUDED