diff options
author | Linus Groh <mail@linusgroh.de> | 2020-10-25 23:25:41 +0000 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-10-26 11:27:54 +0100 |
commit | b2e4fe1299bd57b4ab4bb7ea0e0133038db52b26 (patch) | |
tree | 991fa54dd3333d8fc502d7cc9a6cfb55cbf18e52 /Libraries/LibLine | |
parent | af056718437f23e895f45e9b6c473d37a3e5f699 (diff) | |
download | serenity-b2e4fe1299bd57b4ab4bb7ea0e0133038db52b26.zip |
Shell+LibLine: Move Shell::{load,save}_history() to Line::Editor
This allows us to easily re-use history loading and saving in other
programs using Line::Editor, as well as implementing universally
recognized HISTCONTROL.
Diffstat (limited to 'Libraries/LibLine')
-rw-r--r-- | Libraries/LibLine/Editor.cpp | 27 | ||||
-rw-r--r-- | Libraries/LibLine/Editor.h | 4 |
2 files changed, 30 insertions, 1 deletions
diff --git a/Libraries/LibLine/Editor.cpp b/Libraries/LibLine/Editor.cpp index 28f66ce718..c103d5ccf9 100644 --- a/Libraries/LibLine/Editor.cpp +++ b/Libraries/LibLine/Editor.cpp @@ -34,6 +34,7 @@ #include <LibCore/ConfigFile.h> #include <LibCore/Event.h> #include <LibCore/EventLoop.h> +#include <LibCore/File.h> #include <LibCore/Notifier.h> #include <ctype.h> #include <signal.h> @@ -212,6 +213,32 @@ void Editor::add_to_history(const String& line) m_history.append(line); } +bool Editor::load_history(const String& path) +{ + auto history_file = Core::File::construct(path); + if (!history_file->open(Core::IODevice::ReadOnly)) + return false; + while (history_file->can_read_line()) { + auto b = history_file->read_line(1024); + // skip the newline and terminating bytes + add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2)); + } + return true; +} + +bool Editor::save_history(const String& path) +{ + auto file_or_error = Core::File::open(path, Core::IODevice::WriteOnly, 0600); + if (file_or_error.is_error()) + return false; + auto& file = *file_or_error.value(); + for (const auto& line : m_history) { + file.write(line); + file.write("\n"); + } + return true; +} + void Editor::clear_line() { for (size_t i = 0; i < m_cursor; ++i) diff --git a/Libraries/LibLine/Editor.h b/Libraries/LibLine/Editor.h index 076acdc830..f2513fbe6c 100644 --- a/Libraries/LibLine/Editor.h +++ b/Libraries/LibLine/Editor.h @@ -143,7 +143,9 @@ public: void initialize(); - void add_to_history(const String&); + void add_to_history(const String& line); + bool load_history(const String& path); + bool save_history(const String& path); const Vector<String>& history() const { return m_history; } void register_key_input_callback(const KeyBinding&); |