message_formatter.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #pragma once
  2. #include <string>
  3. #include <cstddef>
  4. namespace lumacs {
  5. /// @brief Shared message formatting utilities for both GTK and TUI frontends.
  6. ///
  7. /// This utility provides consistent message formatting including:
  8. /// - Multi-line message collapsing (show first line + count)
  9. /// - Message truncation with help hint
  10. class MessageFormatter {
  11. public:
  12. /// Truncation suffix shown when message is too long
  13. static constexpr const char* TRUNCATION_SUFFIX = "... [C-h e]";
  14. /// @brief Collapse a multi-line message to show only the first line with a count indicator.
  15. /// @param message The original message (may contain newlines)
  16. /// @return The collapsed message with line count indicator if multi-line, otherwise unchanged
  17. static std::string collapse_multiline(const std::string& message) {
  18. size_t newline_pos = message.find('\n');
  19. if (newline_pos == std::string::npos) {
  20. return message; // Single line, return as-is
  21. }
  22. // Count additional lines
  23. size_t line_count = 1;
  24. size_t pos = 0;
  25. while ((pos = message.find('\n', pos)) != std::string::npos) {
  26. ++line_count;
  27. ++pos;
  28. }
  29. // Return first line with indicator
  30. return message.substr(0, newline_pos) +
  31. " [+" + std::to_string(line_count - 1) + " lines, C-h e]";
  32. }
  33. /// @brief Truncate a message to fit within a maximum character width.
  34. /// @param message The message to truncate
  35. /// @param max_width Maximum number of characters allowed
  36. /// @return The truncated message with suffix if it was too long, otherwise unchanged
  37. static std::string truncate_to_width(const std::string& message, size_t max_width) {
  38. if (message.length() <= max_width) {
  39. return message;
  40. }
  41. const std::string suffix = TRUNCATION_SUFFIX;
  42. if (max_width <= suffix.length()) {
  43. return suffix.substr(0, max_width); // Edge case: very narrow width
  44. }
  45. size_t max_chars = max_width - suffix.length();
  46. return message.substr(0, max_chars) + suffix;
  47. }
  48. /// @brief Format a message for display in the echo area.
  49. /// Combines multi-line collapsing and width truncation.
  50. /// @param message The original message
  51. /// @param max_width Maximum display width in characters
  52. /// @return The formatted message ready for display
  53. static std::string format_for_echo_area(const std::string& message, size_t max_width) {
  54. std::string result = collapse_multiline(message);
  55. return truncate_to_width(result, max_width);
  56. }
  57. };
  58. } // namespace lumacs