history_manager.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include <numeric> // For std::iota
  5. namespace lumacs {
  6. /// @brief Manages history for a specific minibuffer type (e.g., commands, file paths).
  7. class HistoryManager {
  8. public:
  9. HistoryManager() : history_index_(0) {}
  10. /// @brief Adds an item to the history.
  11. /// Only adds if the item is not empty and not a duplicate of the last item.
  12. void add_item(const std::string& item) {
  13. if (!item.empty() && (history_.empty() || history_.back() != item)) {
  14. history_.push_back(item);
  15. }
  16. history_index_ = history_.size(); // Reset index to end after adding
  17. }
  18. /// @brief Navigates to the previous item in history.
  19. /// @return The previous item, or empty string if no more history.
  20. std::string previous() {
  21. if (!history_.empty()) {
  22. if (history_index_ > 0) {
  23. history_index_--;
  24. }
  25. return history_[history_index_];
  26. }
  27. return "";
  28. }
  29. /// @brief Navigates to the next item in history.
  30. /// @return The next item, or empty string if at the end of history.
  31. std::string next() {
  32. if (!history_.empty()) {
  33. if (history_index_ < history_.size() - 1) {
  34. history_index_++;
  35. return history_[history_index_];
  36. } else if (history_index_ == history_.size() - 1) {
  37. // If at the end, and pressing next, clear input (or original input before history nav)
  38. history_index_++; // Move past the last valid index
  39. return "";
  40. }
  41. }
  42. return "";
  43. }
  44. /// @brief Clears the history.
  45. void clear() {
  46. history_.clear();
  47. history_index_ = 0;
  48. }
  49. /// @brief Returns true if history is empty, false otherwise.
  50. bool empty() const {
  51. return history_.empty();
  52. }
  53. private:
  54. std::vector<std::string> history_;
  55. size_t history_index_; // Current position in history
  56. };
  57. } // namespace lumacs