command_system.hpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include <functional>
  5. #include <unordered_map>
  6. #include <optional>
  7. #include <variant>
  8. namespace lumacs {
  9. // Forward declaration for EditorCore, as CommandSystem will interact with it
  10. class EditorCore;
  11. /// @brief Represents the result of a command execution.
  12. struct CommandResult {
  13. bool success;
  14. std::string message;
  15. // Potentially add more fields, like return value, error code, etc.
  16. };
  17. /// @brief Type for command functions.
  18. /// Commands take a vector of string arguments and return a CommandResult.
  19. using CommandFunction = std::function<CommandResult(const std::vector<std::string>&)>;
  20. /// @brief Represents a single command.
  21. struct Command {
  22. std::string name;
  23. CommandFunction function;
  24. std::string doc_string; // Documentation for the command
  25. bool interactive; // Whether the command can be called interactively (e.g., via M-x)
  26. std::string interactive_spec; // Emacs-like interactive spec for argument gathering
  27. Command(std::string name, CommandFunction func, std::string doc = "", bool interactive = false, std::string i_spec = "")
  28. : name(std::move(name)), function(std::move(func)), doc_string(std::move(doc)), interactive(interactive), interactive_spec(std::move(i_spec)) {}
  29. };
  30. /// @brief Manages the registration and execution of editor commands.
  31. class CommandSystem {
  32. public:
  33. explicit CommandSystem(EditorCore* core = nullptr);
  34. /// @brief Registers a command with the system.
  35. void register_command(const std::string& name, CommandFunction function,
  36. const std::string& doc_string = "", bool interactive = false);
  37. /// @brief Executes a command by name with given arguments.
  38. /// @param name The name of the command to execute.
  39. /// @param args Arguments for the command.
  40. /// @return CommandResult indicating success/failure and a message.
  41. CommandResult execute(const std::string& name, const std::vector<std::string>& args);
  42. /// @brief Get a list of all registered command names.
  43. std::vector<std::string> get_command_names() const;
  44. /// @brief Get documentation for a specific command.
  45. std::optional<std::string> get_command_doc_string(const std::string& name) const;
  46. private:
  47. EditorCore* core_; // Pointer to EditorCore for commands to interact with editor state
  48. std::unordered_map<std::string, Command> commands_;
  49. };
  50. } // namespace lumacs