editor_core.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. #include "lumacs/editor_core.hpp"
  2. #include "lumacs/lua_api.hpp" // Include LuaApi header
  3. #include "lumacs/command_system.hpp"
  4. #include "lumacs/completion_system.hpp" // Include CompletionSystem header
  5. #include "lumacs/minibuffer_manager.hpp" // Include MinibufferManager header
  6. #include "lumacs/plugin_manager.hpp" // New include for PluginManager
  7. #include "lumacs/buffer_manager.hpp" // New include for BufferManager
  8. #include "lumacs/window_manager.hpp" // New include for WindowManager
  9. #include "lumacs/kill_ring_manager.hpp" // New include for KillRingManager
  10. #include "lumacs/register_manager.hpp" // New include for RegisterManager
  11. #include "lumacs/macro_manager.hpp" // New include for MacroManager
  12. #include "lumacs/rectangle_manager.hpp" // New include for RectangleManager
  13. #include "lumacs/logger.hpp"
  14. #include <spdlog/spdlog.h>
  15. #include <algorithm>
  16. #include <chrono>
  17. #include <ctime>
  18. #include <iomanip>
  19. #include <sstream>
  20. namespace lumacs {
  21. EditorCore::EditorCore() :
  22. last_message_(),
  23. message_clear_time_(),
  24. event_callbacks_(),
  25. theme_manager_(),
  26. config_(),
  27. modeline_manager_member_(), // Direct member
  28. // Subsystem initializations - order matters for dependencies based on member declaration order in .hpp
  29. // Corrected Order based on dependencies and declaration order:
  30. lua_api_(std::make_unique<LuaApi>()),
  31. completion_system_(std::make_unique<CompletionSystem>(*this)),
  32. minibuffer_manager_(std::make_unique<MinibufferManager>(*this, *lua_api_, *completion_system_)),
  33. command_system_(std::make_unique<CommandSystem>(*this, *minibuffer_manager_)),
  34. keybinding_manager_(std::make_unique<KeyBindingManager>(command_system_.get())), // Pass raw pointer
  35. plugin_manager_(std::make_unique<PluginManager>(*this, *lua_api_)),
  36. // Initialize BufferManager with *this (IEditorNotifier) and a placeholder for IWindowManager until WindowManager is initialized
  37. // Wait, WindowManager depends on BufferManager for initialization.
  38. // This is a classic chicken-and-egg problem if we strictly enforce constructor injection.
  39. // BufferManager needs IWindowManager. WindowManager needs BufferManager.
  40. // WindowManager creates the initial buffer via BufferManager.
  41. //
  42. // To break this:
  43. // 1. BufferManager shouldn't need IWindowManager in constructor if it only uses it in methods.
  44. // It stores the reference.
  45. // We can use a two-phase init or pass references to managers after creation?
  46. // Or, rely on the fact that we are constructing them here.
  47. // But we can't pass *window_manager_ before it's constructed.
  48. //
  49. // Solution:
  50. // Create BufferManager without IWindowManager reference initially? No, it's a reference member.
  51. //
  52. // Alternative: EditorCore implements IWindowManager too!
  53. // Since EditorCore owns WindowManager and delegates to it, EditorCore can implement IWindowManager
  54. // and just forward calls to window_manager_.
  55. // This allows passing *this to BufferManager.
  56. //
  57. // Let's verify if EditorCore implements IWindowManager. Not yet.
  58. //
  59. // Let's update EditorCore to implement IWindowManager as well.
  60. buffer_manager_(nullptr), // Temporary null, will initialize in body? No, unique_ptr.
  61. window_manager_(nullptr),
  62. kill_ring_manager_(std::make_unique<KillRingManager>()),
  63. register_manager_(std::make_unique<RegisterManager>()),
  64. macro_manager_(std::make_unique<MacroManager>(*this)),
  65. rectangle_manager_(std::make_unique<RectangleManager>(*this))
  66. {
  67. // We need to initialize buffer_manager_ and window_manager_ carefully.
  68. // We can use a raw pointer trick or late initialization if we change members to not be references?
  69. // Or implementing interfaces on EditorCore is the cleanest way to maintain the "Core is the mediator" pattern
  70. // while breaking the direct dependency on the *concrete* Core class.
  71. // Let's assume EditorCore implements IWindowManager.
  72. // Then:
  73. // buffer_manager_ = std::make_unique<BufferManager>(*this, *this);
  74. // window_manager_ = std::make_unique<WindowManager>(*this, *buffer_manager_);
  75. // But wait, we haven't made EditorCore implement IWindowManager yet.
  76. // Let's modify the plan slightly to make EditorCore implement IWindowManager.
  77. // Reverting to the prompt instruction context: I should probably just implement the initialization
  78. // assuming I will fix the header next.
  79. // Actually, I can't change the header in the same turn easily if I'm stuck here.
  80. // But I can use a deferred initialization approach or a temporary valid object.
  81. // BETTER APPROACH:
  82. // Initialize BufferManager and WindowManager.
  83. // WindowManager needs BufferManager.
  84. // BufferManager needs WindowManager.
  85. //
  86. // We can't satisfy both const references at construction time if they depend on each other.
  87. //
  88. // One must take the other as a setter, or we proxy through EditorCore.
  89. // If EditorCore implements both interfaces, we pass *this to both.
  90. //
  91. // buffer_manager_ = std::make_unique<BufferManager>(*this, *this);
  92. // window_manager_ = std::make_unique<WindowManager>(*this, *buffer_manager_);
  93. // This requires EditorCore to be IWindowManager.
  94. // Let's do that.
  95. // For this step, I will initialize them assuming EditorCore implements IWindowManager.
  96. // I will need to update EditorCore header in the next tool call.
  97. buffer_manager_ = std::make_unique<BufferManager>(*this, *this);
  98. window_manager_ = std::make_unique<WindowManager>(*this, *buffer_manager_);
  99. // ... rest of constructor
  100. // LuaApi needs core_ pointer to be valid, so set it after constructor body starts
  101. lua_api_->set_core(*this);
  102. // Ensure the initial window has a valid buffer
  103. new_buffer("*scratch*");
  104. // Initialize themes
  105. // theme_manager_.create_default_themes(); // REMOVED: Themes are now loaded from Lua
  106. // theme_manager_.set_active_theme("everforest-dark"); // REMOVED: Initial theme will be set by Lua
  107. }
  108. EditorCore::~EditorCore() = default;
  109. // === Cursor Proxies ===
  110. Position EditorCore::cursor() const noexcept {
  111. Position cursor_pos = active_window()->cursor();
  112. return cursor_pos;
  113. }
  114. void EditorCore::set_cursor(Position pos) {
  115. active_window()->set_cursor(pos);
  116. adjust_scroll();
  117. }
  118. void EditorCore::move_up() {
  119. window_manager_->active_window()->move_up();
  120. emit_event(EditorEvent::CursorMoved);
  121. }
  122. void EditorCore::move_down() {
  123. window_manager_->active_window()->move_down();
  124. emit_event(EditorEvent::CursorMoved);
  125. }
  126. void EditorCore::move_left() {
  127. window_manager_->active_window()->move_left();
  128. emit_event(EditorEvent::CursorMoved);
  129. }
  130. void EditorCore::move_right() {
  131. window_manager_->active_window()->move_right();
  132. emit_event(EditorEvent::CursorMoved);
  133. }
  134. void EditorCore::move_to_line_start() {
  135. window_manager_->active_window()->move_to_line_start();
  136. emit_event(EditorEvent::CursorMoved);
  137. }
  138. void EditorCore::move_to_line_end() {
  139. window_manager_->active_window()->move_to_line_end();
  140. emit_event(EditorEvent::CursorMoved);
  141. }
  142. // Helper: Check if character is a word constituent
  143. static bool is_word_char(char c) {
  144. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  145. (c >= '0' && c <= '9') || c == '_';
  146. }
  147. void EditorCore::move_forward_word() {
  148. auto new_pos = calculate_forward_word_pos(window_manager_->active_window()->cursor());
  149. window_manager_->active_window()->set_cursor(new_pos);
  150. emit_event(EditorEvent::CursorMoved);
  151. }
  152. void EditorCore::move_backward_word() {
  153. auto new_pos = calculate_backward_word_pos(window_manager_->active_window()->cursor());
  154. window_manager_->active_window()->set_cursor(new_pos);
  155. emit_event(EditorEvent::CursorMoved);
  156. }
  157. Position EditorCore::calculate_forward_word_pos(Position start_pos) {
  158. // Delegates to active buffer
  159. auto& buf = *buffer_manager_->active_buffer();
  160. auto cursor = start_pos;
  161. // Check if we are at the end of buffer
  162. if (cursor.line >= buf.line_count()) {
  163. return cursor;
  164. }
  165. // 1. Skip non-word chars (whitespace/punctuation)
  166. while (true) {
  167. const auto& line = buf.line(cursor.line);
  168. while (cursor.column < line.size() && !is_word_char(line[cursor.column])) {
  169. cursor.column++;
  170. }
  171. // If we found a word char, we're done with step 1
  172. if (cursor.column < line.size()) {
  173. break;
  174. }
  175. // Move to next line
  176. if (cursor.line < buf.line_count() - 1) {
  177. cursor.line++;
  178. cursor.column = 0;
  179. } else {
  180. // At end of buffer
  181. return cursor;
  182. }
  183. }
  184. // 2. Skip word chars
  185. const auto& line = buf.line(cursor.line);
  186. while (cursor.column < line.size() && is_word_char(line[cursor.column])) {
  187. cursor.column++;
  188. }
  189. return cursor;
  190. }
  191. Position EditorCore::calculate_backward_word_pos(Position start_pos) {
  192. // Delegates to active buffer
  193. auto& buf = *buffer_manager_->active_buffer();
  194. auto cursor = start_pos;
  195. // Skip whitespace and punctuation backwards
  196. while (true) {
  197. // If at start of line, go to previous line
  198. if (cursor.column == 0) {
  199. if (cursor.line == 0) {
  200. // At start of buffer
  201. break;
  202. }
  203. cursor.line--;
  204. cursor.column = buf.line(cursor.line).size();
  205. continue;
  206. }
  207. // Move back one char
  208. cursor.column--;
  209. const auto& line = buf.line(cursor.line);
  210. // If we hit a word char, keep going back through the word
  211. if (is_word_char(line[cursor.column])) {
  212. // Move to start of word
  213. while (cursor.column > 0 && is_word_char(line[cursor.column - 1])) {
  214. cursor.column--;
  215. }
  216. break;
  217. }
  218. }
  219. return cursor;
  220. }
  221. void EditorCore::page_up() {
  222. auto& viewport = window_manager_->active_window()->viewport();
  223. auto cursor = window_manager_->active_window()->cursor();
  224. // Move up by viewport height (minus 2 for overlap)
  225. int page_size = std::max(1, viewport.height - 2);
  226. if (cursor.line >= static_cast<size_t>(page_size)) {
  227. cursor.line -= page_size;
  228. } else {
  229. cursor.line = 0;
  230. }
  231. // Keep column position if possible
  232. auto& buf = *buffer_manager_->active_buffer();
  233. const auto& line = buf.line(cursor.line);
  234. cursor.column = std::min(cursor.column, line.size());
  235. window_manager_->active_window()->set_cursor(cursor);
  236. window_manager_->active_window()->adjust_scroll();
  237. emit_event(EditorEvent::CursorMoved);
  238. emit_event(EditorEvent::ViewportChanged);
  239. }
  240. void EditorCore::page_down() {
  241. auto& viewport = window_manager_->active_window()->viewport();
  242. auto cursor = window_manager_->active_window()->cursor();
  243. auto& buf = *buffer_manager_->active_buffer();
  244. // Move down by viewport height (minus 2 for overlap)
  245. int page_size = std::max(1, viewport.height - 2);
  246. cursor.line = std::min(cursor.line + page_size, buf.line_count() - 1);
  247. // Keep column position if possible
  248. const auto& line = buf.line(cursor.line);
  249. cursor.column = std::min(cursor.column, line.size());
  250. window_manager_->active_window()->set_cursor(cursor);
  251. window_manager_->active_window()->adjust_scroll();
  252. emit_event(EditorEvent::CursorMoved);
  253. emit_event(EditorEvent::ViewportChanged);
  254. }
  255. void EditorCore::goto_beginning() {
  256. Position pos = {0, 0};
  257. window_manager_->active_window()->set_cursor(pos);
  258. window_manager_->active_window()->adjust_scroll();
  259. emit_event(EditorEvent::CursorMoved);
  260. emit_event(EditorEvent::ViewportChanged);
  261. }
  262. void EditorCore::goto_end() {
  263. auto& buf = *buffer_manager_->active_buffer();
  264. size_t last_line = buf.line_count() > 0 ? buf.line_count() - 1 : 0;
  265. size_t last_col = buf.line(last_line).size();
  266. Position pos = {last_line, last_col};
  267. window_manager_->active_window()->set_cursor(pos);
  268. window_manager_->active_window()->adjust_scroll();
  269. emit_event(EditorEvent::CursorMoved);
  270. emit_event(EditorEvent::ViewportChanged);
  271. }
  272. void EditorCore::goto_line(size_t line) {
  273. auto& buf = *buffer_manager_->active_buffer();
  274. line = std::min(line, buf.line_count() > 0 ? buf.line_count() - 1 : 0); // Clamp to max line index
  275. Position pos = {line, 0};
  276. window_manager_->active_window()->set_cursor(pos);
  277. window_manager_->active_window()->adjust_scroll();
  278. emit_event(EditorEvent::CursorMoved);
  279. emit_event(EditorEvent::ViewportChanged);
  280. }
  281. // === Viewport Management (Proxies to active window) ===
  282. const Viewport& EditorCore::viewport() const noexcept {
  283. return window_manager_->active_window()->viewport();
  284. }
  285. void EditorCore::set_viewport_size(int width, int height) {
  286. window_manager_->active_window()->set_viewport_size(width, height);
  287. emit_event(EditorEvent::ViewportChanged);
  288. }
  289. void EditorCore::adjust_scroll() {
  290. window_manager_->active_window()->adjust_scroll();
  291. emit_event(EditorEvent::ViewportChanged);
  292. }
  293. std::pair<size_t, size_t> EditorCore::visible_line_range() const {
  294. return window_manager_->active_window()->visible_line_range();
  295. }
  296. // === Undo/Redo ===
  297. bool EditorCore::undo() {
  298. auto& buf = *buffer_manager_->active_buffer();
  299. buf.save_undo_state(window_manager_->active_window()->cursor());
  300. Position new_cursor = window_manager_->active_window()->cursor();
  301. if (buf.undo(new_cursor)) {
  302. window_manager_->active_window()->set_cursor(new_cursor);
  303. emit_event(EditorEvent::CursorMoved);
  304. emit_event(EditorEvent::BufferModified);
  305. return true;
  306. }
  307. return false;
  308. }
  309. bool EditorCore::redo() {
  310. auto& buf = *buffer_manager_->active_buffer();
  311. Position new_cursor = window_manager_->active_window()->cursor();
  312. if (buf.redo(new_cursor)) {
  313. window_manager_->active_window()->set_cursor(new_cursor);
  314. emit_event(EditorEvent::CursorMoved);
  315. emit_event(EditorEvent::BufferModified);
  316. return true;
  317. }
  318. return false;
  319. }
  320. bool EditorCore::can_undo() const {
  321. return buffer_manager_->active_buffer()->can_undo();
  322. }
  323. bool EditorCore::can_redo() const {
  324. return buffer_manager_->active_buffer()->can_redo();
  325. }
  326. // === Kill Ring (Delegated to KillRingManager) ===
  327. void EditorCore::kill_line() {
  328. auto& buf = *buffer_manager_->active_buffer();
  329. auto cursor = window_manager_->active_window()->cursor();
  330. const auto& line_text = buf.line(cursor.line);
  331. Range range_to_kill;
  332. std::string killed_text;
  333. if (cursor.column == 0 && cursor.line < buf.line_count() - 1) {
  334. // Kill whole line including newline
  335. range_to_kill = {{cursor.line, 0}, {cursor.line + 1, 0}};
  336. } else if (cursor.column < line_text.size()) {
  337. // Kill from cursor to end of line
  338. range_to_kill = {cursor, {cursor.line, line_text.size()}};
  339. } else { // Cursor is at or past end of line
  340. if (cursor.line < buf.line_count() - 1) {
  341. // Kill only the newline (join with next line)
  342. range_to_kill = {{cursor.line, line_text.size()}, {cursor.line + 1, 0}};
  343. } else {
  344. // At end of last line, nothing to kill
  345. return;
  346. }
  347. }
  348. killed_text = buf.get_text_in_range(range_to_kill); // Get text BEFORE erase
  349. if (!killed_text.empty()) {
  350. kill_ring_manager_->push(killed_text);
  351. buf.erase(range_to_kill);
  352. // Cursor position does not change after kill-line; it remains at the beginning of the killed region.
  353. emit_event(EditorEvent::BufferModified);
  354. emit_event(EditorEvent::CursorMoved);
  355. }
  356. }
  357. void EditorCore::kill_region() {
  358. auto& buf = *buffer_manager_->active_buffer();
  359. auto cursor = window_manager_->active_window()->cursor();
  360. auto region = buf.get_region(cursor);
  361. if (!region.has_value()) {
  362. set_message("No active region");
  363. return;
  364. }
  365. std::string killed_text = buf.get_text_in_range(region.value());
  366. if (!killed_text.empty()) {
  367. kill_ring_manager_->push(killed_text); // Delegate to manager
  368. buf.deactivate_mark();
  369. // Move cursor to start of killed region
  370. window_manager_->active_window()->set_cursor(region.value().start);
  371. emit_event(EditorEvent::BufferModified);
  372. emit_event(EditorEvent::CursorMoved);
  373. spdlog::debug("Killed region: '{}'", killed_text);
  374. }
  375. }
  376. void EditorCore::kill_word() {
  377. auto cursor = window_manager_->active_window()->cursor();
  378. auto end_pos = calculate_forward_word_pos(cursor);
  379. if (cursor == end_pos) return;
  380. Range range = {cursor, end_pos};
  381. auto& buf = *buffer_manager_->active_buffer();
  382. std::string text = buf.get_text_in_range(range);
  383. if (!text.empty()) {
  384. kill_ring_manager_->push(text); // Delegate to manager
  385. buf.erase(range);
  386. emit_event(EditorEvent::BufferModified);
  387. spdlog::debug("Killed word: '{}'", text);
  388. }
  389. }
  390. void EditorCore::backward_kill_word() {
  391. auto cursor = window_manager_->active_window()->cursor();
  392. auto start_pos = calculate_backward_word_pos(cursor);
  393. if (cursor == start_pos) return;
  394. Range range = {start_pos, cursor};
  395. auto& buf = *buffer_manager_->active_buffer();
  396. std::string text = buf.get_text_in_range(range);
  397. if (!text.empty()) {
  398. kill_ring_manager_->push(text); // Delegate to manager
  399. buf.erase(range);
  400. window_manager_->active_window()->set_cursor(start_pos);
  401. emit_event(EditorEvent::BufferModified);
  402. emit_event(EditorEvent::CursorMoved);
  403. spdlog::debug("Backward killed word: '{}'", text);
  404. }
  405. }
  406. void EditorCore::copy_region_as_kill() {
  407. auto& buf = *buffer_manager_->active_buffer();
  408. auto cursor = window_manager_->active_window()->cursor();
  409. auto region = buf.get_region(cursor);
  410. if (!region.has_value()) {
  411. set_message("No active region");
  412. return;
  413. }
  414. std::string copied_text = buf.get_text_in_range(region.value());
  415. if (!copied_text.empty()) {
  416. kill_ring_manager_->push(copied_text); // Delegate to manager
  417. buf.deactivate_mark();
  418. set_message("Region copied");
  419. spdlog::debug("Copied region: '{}'", copied_text);
  420. }
  421. }
  422. void EditorCore::yank() {
  423. if (kill_ring_manager_->empty()) {
  424. set_message("Kill ring is empty");
  425. return;
  426. }
  427. std::string text = kill_ring_manager_->current();
  428. if (text.empty()) {
  429. return;
  430. }
  431. auto& buf = *buffer_manager_->active_buffer();
  432. auto cursor = window_manager_->active_window()->cursor();
  433. // Insert the text
  434. buf.insert(cursor, text);
  435. // Calculate new cursor position after insertion
  436. Position new_cursor = cursor;
  437. size_t newline_count = std::count(text.begin(), text.end(), '\n');
  438. if (newline_count > 0) {
  439. // Multi-line yank: cursor goes to end of inserted text
  440. new_cursor.line += newline_count;
  441. size_t last_newline = text.rfind('\n');
  442. new_cursor.column = (last_newline != std::string::npos) ? (text.size() - last_newline - 1) : 0;
  443. } else {
  444. // Single-line yank: advance column
  445. new_cursor.column += text.size();
  446. }
  447. // Save yank range in KillRingManager for yank-pop
  448. kill_ring_manager_->set_yank_range(cursor, new_cursor);
  449. window_manager_->active_window()->set_cursor(new_cursor);
  450. emit_event(EditorEvent::BufferModified);
  451. emit_event(EditorEvent::CursorMoved);
  452. spdlog::debug("Yanked: '{}'", text);
  453. }
  454. void EditorCore::yank_pop() {
  455. if (kill_ring_manager_->empty()) {
  456. set_message("Kill ring is empty");
  457. return;
  458. }
  459. if (!kill_ring_manager_->has_yank_state()) {
  460. set_message("Previous command was not a yank");
  461. return;
  462. }
  463. // Delete the previously yanked text
  464. auto& buf = *buffer_manager_->active_buffer();
  465. Range yank_range = {kill_ring_manager_->yank_start().value(), kill_ring_manager_->yank_end().value()};
  466. buf.erase(yank_range);
  467. // Get previous entry in kill ring
  468. std::string text = kill_ring_manager_->previous();
  469. // Restore cursor to yank start
  470. auto cursor = kill_ring_manager_->yank_start().value();
  471. window_manager_->active_window()->set_cursor(cursor);
  472. // Insert new text
  473. buf.insert(cursor, text);
  474. // Calculate new end position
  475. Position new_cursor = cursor;
  476. size_t newline_count = std::count(text.begin(), text.end(), '\n');
  477. if (newline_count > 0) {
  478. new_cursor.line += newline_count;
  479. size_t last_newline = text.rfind('\n');
  480. new_cursor.column = (last_newline != std::string::npos) ? (text.size() - last_newline - 1) : 0;
  481. } else {
  482. new_cursor.column += text.size();
  483. }
  484. // Update yank end position
  485. kill_ring_manager_->set_yank_end(new_cursor);
  486. window_manager_->active_window()->set_cursor(new_cursor);
  487. emit_event(EditorEvent::BufferModified);
  488. emit_event(EditorEvent::CursorMoved);
  489. spdlog::debug("Yank-pop: '{}'", text);
  490. }
  491. // === Registers (Delegated to RegisterManager) ===
  492. void EditorCore::copy_to_register(char register_name, const std::string& text) {
  493. // Validate register name (a-z, A-Z, 0-9)
  494. if (!std::isalnum(register_name)) {
  495. set_message("Invalid register name");
  496. return;
  497. }
  498. register_manager_->copy_to_register(register_name, text);
  499. set_message(std::string("Saved text to register ") + register_name);
  500. }
  501. bool EditorCore::insert_register(char register_name) {
  502. // Validate register name
  503. if (!std::isalnum(register_name)) {
  504. set_message("Invalid register name");
  505. return false;
  506. }
  507. std::optional<std::string> text_opt = register_manager_->get_from_register(register_name);
  508. if (!text_opt.has_value()) {
  509. set_message(std::string("Register ") + register_name + " is empty");
  510. return false;
  511. }
  512. std::string text = text_opt.value();
  513. auto& buf = *buffer_manager_->active_buffer();
  514. Position cursor = window_manager_->active_window()->cursor();
  515. buf.insert(cursor, text);
  516. // Move cursor to end of inserted text
  517. size_t newline_count = std::count(text.begin(), text.end(), '\n');
  518. if (newline_count > 0) {
  519. cursor.line += newline_count;
  520. size_t last_newline = text.rfind('\n');
  521. cursor.column = (last_newline != std::string::npos) ? (text.size() - last_newline - 1) : 0;
  522. } else {
  523. cursor.column += text.size();
  524. }
  525. window_manager_->active_window()->set_cursor(cursor);
  526. emit_event(EditorEvent::BufferModified);
  527. emit_event(EditorEvent::CursorMoved);
  528. set_message(std::string("Inserted register ") + register_name);
  529. return true;
  530. }
  531. void EditorCore::copy_region_to_register(char register_name) {
  532. auto& buf = *buffer_manager_->active_buffer();
  533. Position cursor = window_manager_->active_window()->cursor();
  534. auto region = buf.get_region(cursor);
  535. if (!region) {
  536. set_message("No active region");
  537. return;
  538. }
  539. std::string text = buf.get_text_in_range(*region);
  540. copy_to_register(register_name, text);
  541. }
  542. bool EditorCore::yank_from_register(char register_name) {
  543. return insert_register(register_name);
  544. }
  545. // === Keyboard Macros (Delegated to MacroManager) ===
  546. void EditorCore::start_kbd_macro() {
  547. macro_manager_->start_kbd_macro();
  548. }
  549. void EditorCore::end_kbd_macro_or_call() {
  550. macro_manager_->end_kbd_macro_or_call();
  551. }
  552. void EditorCore::record_key_sequence(const std::string& key_sequence) {
  553. macro_manager_->record_key_sequence(key_sequence);
  554. }
  555. // === Rectangles (Delegated to RectangleManager) ===
  556. void EditorCore::kill_rectangle() {
  557. rectangle_manager_->kill_rectangle();
  558. }
  559. void EditorCore::yank_rectangle() {
  560. rectangle_manager_->yank_rectangle();
  561. }
  562. void EditorCore::string_rectangle(const std::string& text) {
  563. rectangle_manager_->string_rectangle(text);
  564. }
  565. // === Helper Implementation ===
  566. void EditorCore::collect_windows(LayoutNode* node, std::vector<std::shared_ptr<Window>>& windows) {
  567. if (!node) return;
  568. if (node->type == LayoutNode::Type::Leaf && node->window) {
  569. windows.push_back(node->window);
  570. } else {
  571. collect_windows(node->child1.get(), windows);
  572. collect_windows(node->child2.get(), windows);
  573. }
  574. }
  575. void EditorCore::set_message(std::string msg, MessageSeverity severity) {
  576. // Log to *Messages* buffer with timestamp
  577. if (buffer_manager_) {
  578. auto messages_buf = buffer_manager_->get_buffer_by_name("*Messages*");
  579. if (!messages_buf) {
  580. messages_buf = buffer_manager_->create_buffer_no_window("*Messages*");
  581. }
  582. if (messages_buf) {
  583. // Format timestamp and severity prefix
  584. auto now = std::chrono::system_clock::now();
  585. auto time_t_now = std::chrono::system_clock::to_time_t(now);
  586. std::stringstream timestamp_ss;
  587. timestamp_ss << "[" << std::put_time(std::localtime(&time_t_now), "%H:%M:%S") << "] ";
  588. // Add severity prefix for non-info messages
  589. std::string severity_prefix;
  590. switch (severity) {
  591. case MessageSeverity::Warning: severity_prefix = "[WARN] "; break;
  592. case MessageSeverity::Error: severity_prefix = "[ERROR] "; break;
  593. case MessageSeverity::Debug: severity_prefix = "[DEBUG] "; break;
  594. default: break;
  595. }
  596. // Append message with timestamp to buffer
  597. size_t last_line = messages_buf->line_count() > 0 ? messages_buf->line_count() - 1 : 0;
  598. size_t last_col = 0;
  599. if (messages_buf->line_count() > 0) {
  600. last_col = messages_buf->lines().back().length();
  601. }
  602. messages_buf->insert({last_line, last_col}, timestamp_ss.str() + severity_prefix + msg + "\n");
  603. }
  604. }
  605. // Debug messages are only logged, not displayed in echo area
  606. if (severity == MessageSeverity::Debug) {
  607. return;
  608. }
  609. last_message_ = std::move(msg);
  610. last_message_severity_ = severity;
  611. // Set timeout based on severity
  612. switch (severity) {
  613. case MessageSeverity::Info:
  614. message_clear_time_ = std::chrono::steady_clock::now() + std::chrono::seconds(3);
  615. break;
  616. case MessageSeverity::Warning:
  617. message_clear_time_ = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  618. break;
  619. case MessageSeverity::Error:
  620. // Error messages don't auto-clear
  621. message_clear_time_.reset();
  622. break;
  623. default:
  624. message_clear_time_ = std::chrono::steady_clock::now() + std::chrono::seconds(3);
  625. break;
  626. }
  627. emit_event(EditorEvent::Message);
  628. }
  629. void EditorCore::check_and_clear_message() {
  630. if (message_clear_time_.has_value() && std::chrono::steady_clock::now() > message_clear_time_.value()) {
  631. last_message_.clear();
  632. message_clear_time_.reset();
  633. emit_event(EditorEvent::TransientMessageCleared);
  634. }
  635. }
  636. void EditorCore::request_quit() {
  637. emit_event(EditorEvent::Quit);
  638. }
  639. bool EditorCore::is_recording_macro() const noexcept {
  640. return macro_manager_->is_recording_macro();
  641. }
  642. void EditorCore::enter_command_mode() { emit_event(EditorEvent::CommandMode); }
  643. void EditorCore::enter_buffer_switch_mode() { emit_event(EditorEvent::BufferSwitchMode); }
  644. void EditorCore::enter_kill_buffer_mode() { emit_event(EditorEvent::KillBufferMode); }
  645. void EditorCore::enter_find_file_mode() { emit_event(EditorEvent::FindFileMode); }
  646. void EditorCore::enter_theme_selection_mode() { emit_event(EditorEvent::ThemeSelectionMode); }
  647. void EditorCore::enter_isearch_mode() { emit_event(EditorEvent::ISearchMode); }
  648. void EditorCore::enter_isearch_backward_mode() { emit_event(EditorEvent::ISearchBackwardMode); }
  649. void EditorCore::set_theme(const std::string& theme_name) {
  650. theme_manager_.set_active_theme(theme_name);
  651. emit_event(EditorEvent::ThemeChanged);
  652. }
  653. // === Private ===
  654. void EditorCore::emit_event(EditorEvent event) {
  655. for (const auto& callback : event_callbacks_) {
  656. callback(event);
  657. }
  658. }
  659. } // namespace lumacs