kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

hook_manager.cc (6297B)


      1 #include "hook_manager.hh"
      2 
      3 #include "debug.hh"
      4 #include "command_manager.hh"
      5 #include "context.hh"
      6 #include "display_buffer.hh"
      7 #include "face_registry.hh"
      8 #include "option_manager.hh"
      9 #include "option_types.hh"
     10 #include "profile.hh"
     11 #include "ranges.hh"
     12 #include "regex.hh"
     13 
     14 namespace Kakoune
     15 {
     16 
     17 struct HookManager::HookData
     18 {
     19     String group;
     20     HookFlags flags;
     21     Regex filter;
     22     String commands;
     23 
     24     bool should_run(bool only_always, const Regex& disabled_hooks, StringView param,
     25                     MatchResults<const char*>& captures) const
     26     {
     27         return (not only_always or (flags & HookFlags::Always)) and
     28                 (group.empty() or disabled_hooks.empty() or
     29                  not regex_match(group.begin(), group.end(), disabled_hooks))
     30                 and regex_match(param.begin(), param.end(), captures, filter);
     31     }
     32 
     33     void exec(Hook hook, StringView param, Context& context, const MatchResults<const char*>& captures)
     34     {
     35         if (context.options()["debug"].get<DebugFlags>() & DebugFlags::Hooks)
     36             write_to_debug_buffer(format("hook {}({})/{}",
     37                                   enum_desc(Meta::Type<Hook>{})[to_underlying(hook)].name,
     38                                   param, group));
     39 
     40         EnvVarMap env_vars{ {"hook_param", param.str()} };
     41         for (size_t i = 0; i < captures.size(); ++i)
     42             env_vars.insert({format("hook_param_capture_{}", i),
     43                              {captures[i].first, captures[i].second}});
     44         for (auto& c : filter.impl()->named_captures)
     45             env_vars.insert({format("hook_param_capture_{}", c.name),
     46                              {captures[c.index].first, captures[c.index].second}});
     47 
     48         CommandManager::instance().execute(commands, context, {{}, std::move(env_vars)});
     49     }
     50 
     51 };
     52 
     53 HookManager::HookManager() : m_parent(nullptr) {}
     54 HookManager::HookManager(HookManager& parent) : SafeCountable{}, m_parent(&parent) {}
     55 HookManager::~HookManager() = default;
     56 
     57 void HookManager::add_hook(Hook hook, String group, HookFlags flags, Regex filter, String commands, Context& context)
     58 {
     59     UniquePtr<HookData> hook_data{new HookData{std::move(group), flags, std::move(filter), std::move(commands)}};
     60     if (hook == Hook::ModuleLoaded)
     61     {
     62         const bool only_always = context.hooks_disabled();
     63         auto& disabled_hooks = context.options()["disabled_hooks"].get<Regex>();
     64 
     65         for (auto&& name : CommandManager::instance().loaded_modules())
     66         {
     67             MatchResults<const char*> captures;
     68             if (hook_data->should_run(only_always, disabled_hooks, name, captures))
     69             {
     70                 hook_data->exec(hook, name, context, captures);
     71                 if (hook_data->flags & HookFlags::Once)
     72                     return;
     73             }
     74         }
     75     }
     76     m_hooks[to_underlying(hook)].push_back(std::move(hook_data));
     77 }
     78 
     79 void HookManager::remove_hooks(const Regex& regex)
     80 {
     81     for (auto& list : m_hooks)
     82     {
     83         list.erase(remove_if(list, [this, &regex](UniquePtr<HookData>& h) {
     84                        if (not regex_match(h->group.begin(), h->group.end(), regex))
     85                            return false;
     86                        m_hooks_trash.push_back(std::move(h));
     87                        return true;
     88                    }), list.end());
     89     }
     90 }
     91 
     92 CandidateList HookManager::complete_hook_group(StringView prefix, ByteCount pos_in_token)
     93 {
     94     CandidateList res;
     95     for (auto& list : m_hooks)
     96     {
     97         auto container = list | transform([](const UniquePtr<HookData>& h) -> const String& { return h->group; });
     98         for (auto& c : complete(prefix, pos_in_token, container))
     99         {
    100             if (not contains(res, c))
    101                 res.push_back(c);
    102         }
    103     }
    104     return res;
    105 }
    106 
    107 void HookManager::run_hook(Hook hook, StringView param, Context& context)
    108 {
    109     const bool only_always = context.hooks_disabled();
    110     auto& disabled_hooks = context.options()["disabled_hooks"].get<Regex>();
    111 
    112     struct ToRun { HookData* hook; MatchResults<const char*> captures; };
    113     Vector<ToRun> hooks_to_run; // The m_hooks_trash vector ensure hooks wont die during this method
    114     for (auto& hook : m_hooks[to_underlying(hook)])
    115     {
    116         MatchResults<const char*> captures;
    117         if (hook->should_run(only_always, disabled_hooks, param, captures))
    118             hooks_to_run.push_back({hook.get(), std::move(captures)});
    119     }
    120 
    121     auto hook_name = enum_desc(Meta::Type<Hook>{})[to_underlying(hook)].name;
    122     if (contains(m_running_hooks, std::make_pair(hook, param)))
    123     {
    124         auto error = format("recursive call of hook {}/{}, not executing", hook_name, param);
    125         write_to_debug_buffer(error);
    126         return;
    127     }
    128 
    129     m_running_hooks.emplace_back(hook, param);
    130     auto pop_running_hook = OnScopeEnd([this]{
    131         m_running_hooks.pop_back();
    132         if (m_running_hooks.empty())
    133             m_hooks_trash.clear();
    134     });
    135 
    136     if (m_parent)
    137         m_parent->run_hook(hook, param, context);
    138 
    139     ProfileScope profile{context.options()["debug"].get<DebugFlags>(), [&](std::chrono::microseconds duration) {
    140         write_to_debug_buffer(format("hook '{}({})' took {} us", hook_name, param, (size_t)duration.count()));
    141     }};
    142 
    143     bool hook_error = false;
    144     for (auto& to_run : hooks_to_run)
    145     {
    146         try
    147         {
    148             if (contains(m_hooks_trash, to_run.hook))
    149                 continue;
    150 
    151             to_run.hook->exec(hook, param, context, to_run.captures);
    152 
    153             if (to_run.hook->flags & HookFlags::Once)
    154             {
    155                 auto& hook_list = m_hooks[to_underlying(hook)];
    156                 if (auto it = find(hook_list, to_run.hook); it != hook_list.end())
    157                 {
    158                     m_hooks_trash.push_back(std::move(*it));
    159                     hook_list.erase(it);
    160                 }
    161             }
    162         }
    163         catch (runtime_error& err)
    164         {
    165             hook_error = true;
    166             write_to_debug_buffer(format("error running hook {}({})/{}: {}",
    167                                          hook_name, param, to_run.hook->group, err.what()));
    168         }
    169     }
    170 
    171     if (hook_error)
    172         context.print_status({
    173             format("Error running hooks for '{}' '{}', see *debug* buffer",
    174                    hook_name, param), context.faces()["Error"] });
    175 }
    176 
    177 }