From ac306ae3e50381ddb494e2be65949f9663ae2e60 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Mon, 15 Dec 2025 14:26:10 +0900 Subject: [PATCH] mruby-bin-mirb: preserve cursor position during TAB auto-indent When TAB triggers auto-indentation, preserve the cursor's relative position within the line instead of moving it to the indent boundary. Co-authored-by: Claude --- mrbgems/mruby-bin-mirb/tools/mirb/mirb_editor.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/mrbgems/mruby-bin-mirb/tools/mirb/mirb_editor.c b/mrbgems/mruby-bin-mirb/tools/mirb/mirb_editor.c index 1277ca53e..2a44b1ee1 100644 --- a/mrbgems/mruby-bin-mirb/tools/mirb/mirb_editor.c +++ b/mrbgems/mruby-bin-mirb/tools/mirb/mirb_editor.c @@ -358,6 +358,7 @@ handle_tab_indent(mirb_editor *ed) size_t current_spaces = 0; size_t i; const char *content; + size_t saved_cursor_col = ed->buf.cursor_col; /* Calculate expected indent from code up to previous line */ if (ed->buf.cursor_line > 0) { @@ -401,7 +402,6 @@ handle_tab_indent(mirb_editor *ed) for (i = 0; i < add; i++) { mirb_buffer_insert_char(&ed->buf, ' '); } - ed->buf.cursor_col = target_spaces; } else if (target_spaces < current_spaces) { /* Need to remove spaces */ @@ -410,11 +410,20 @@ handle_tab_indent(mirb_editor *ed) for (i = 0; i < remove; i++) { mirb_buffer_delete_back(&ed->buf); } - ed->buf.cursor_col = target_spaces; + } + + /* Restore cursor position adjusted for indent change */ + if (target_spaces >= current_spaces) { + ed->buf.cursor_col = saved_cursor_col + (target_spaces - current_spaces); } else { - /* Already correct, move cursor to end of indent */ - ed->buf.cursor_col = target_spaces; + size_t removed = current_spaces - target_spaces; + if (saved_cursor_col >= removed) { + ed->buf.cursor_col = saved_cursor_col - removed; + } + else { + ed->buf.cursor_col = 0; + } } }