diff --git a/src/buffer.cc b/src/buffer.cc index 5e42a295b..2a09cc5b6 100644 --- a/src/buffer.cc +++ b/src/buffer.cc @@ -1,4 +1,7 @@ #include "buffer.hh" + +#include "buffer_manager.hh" + #include namespace Kakoune @@ -122,6 +125,8 @@ Buffer::Buffer(const std::string& name, const BufferString& initial_content) : m_name(name), m_history(1), m_history_cursor(m_history.begin()), m_content(initial_content) { + BufferManager::instance().register_buffer(this); + compute_lines(); } diff --git a/src/buffer_manager.cc b/src/buffer_manager.cc new file mode 100644 index 000000000..9d4cd5062 --- /dev/null +++ b/src/buffer_manager.cc @@ -0,0 +1,60 @@ +#include "buffer_manager.hh" + +#include "buffer.hh" +#include "window.hh" +#include + +namespace Kakoune +{ + +struct name_not_unique {}; + + +BufferManager* BufferManager::ms_instance = nullptr; + +BufferManager& BufferManager::instance() +{ + if (not ms_instance) + ms_instance = new BufferManager(); + + return *ms_instance; +} + +void BufferManager::delete_instance() +{ + delete ms_instance; + ms_instance = nullptr; +} + +BufferManager::BufferManager() +{ +} + +void BufferManager::register_buffer(Buffer* buffer) +{ + assert(buffer); + const std::string& name = buffer->name(); + if (m_buffers.find(name) != m_buffers.end()) + throw name_not_unique(); + + m_buffers[name] = std::unique_ptr(buffer); +} + +void BufferManager::delete_buffer(Buffer* buffer) +{ + assert(buffer); + auto buffer_it = m_buffers.find(buffer->name()); + assert(buffer_it->second.get() == buffer); + m_buffers.erase(buffer_it); +} + +Buffer* BufferManager::get_buffer(const std::string& name) +{ + if (m_buffers.find(name) == m_buffers.end()) + return nullptr; + + return m_buffers[name].get(); +} + + +} diff --git a/src/buffer_manager.hh b/src/buffer_manager.hh new file mode 100644 index 000000000..06fb04f00 --- /dev/null +++ b/src/buffer_manager.hh @@ -0,0 +1,32 @@ +#ifndef buffer_manager_hh_INCLUDED +#define buffer_manager_hh_INCLUDED + +#include "buffer.hh" + +#include +#include + +namespace Kakoune +{ + +class BufferManager +{ +public: + void register_buffer(Buffer* buffer); + void delete_buffer(Buffer* buffer); + + Buffer* get_buffer(const std::string& name); + + static BufferManager& instance(); + static void delete_instance(); + +private: + BufferManager(); + static BufferManager* ms_instance; + + std::unordered_map> m_buffers; +}; + +} + +#endif // buffer_manager_hh_INCLUDED