Skip to content

Commit 9377e37

Browse files
committed
Made cursor position 0-origin
1 parent d1f5ae9 commit 9377e37

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

ext/io/console/console.c

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1109,20 +1109,25 @@ console_cursor_pos(VALUE io)
11091109
VALUE query = rb_str_new_cstr("\e[6n");
11101110
VALUE resp = console_vt_response(1, &query, io);
11111111
VALUE row, column, term;
1112+
unsigned int r, c;
11121113
if (!RB_TYPE_P(resp, T_ARRAY) || RARRAY_LEN(resp) != 3) return Qnil;
11131114
term = RARRAY_AREF(resp, 2);
11141115
if (!RB_TYPE_P(term, T_STRING) || RSTRING_LEN(term) != 1) return Qnil;
11151116
if (RSTRING_PTR(term)[0] != 'R') return Qnil;
11161117
row = RARRAY_AREF(resp, 0);
11171118
column = RARRAY_AREF(resp, 1);
11181119
rb_ary_resize(resp, 2);
1120+
r = NUM2UINT(row) - 1;
1121+
c = NUM2UINT(column) - 1;
1122+
RARRAY_ASET(resp, 0, INT2NUM(r));
1123+
RARRAY_ASET(resp, 1, INT2NUM(c));
11191124
return resp;
11201125
}
11211126

11221127
static VALUE
11231128
console_goto(VALUE io, VALUE y, VALUE x)
11241129
{
1125-
rb_io_write(io, rb_sprintf("\x1b[%d;%dH", NUM2UINT(y), NUM2UINT(x)));
1130+
rb_io_write(io, rb_sprintf("\x1b[%d;%dH", NUM2UINT(y)+1, NUM2UINT(x)+1));
11261131
return io;
11271132
}
11281133

@@ -1223,7 +1228,7 @@ static VALUE
12231228
console_clear_screen(VALUE io)
12241229
{
12251230
console_erase_screen(io, INT2FIX(2));
1226-
console_goto(io, INT2FIX(1), INT2FIX(1));
1231+
console_goto(io, INT2FIX(0), INT2FIX(0));
12271232
return io;
12281233
}
12291234

test/io/console/test_io_console.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,26 @@ def test_set_winsize_invalid_dev
281281
set_winsize_teardown
282282
end
283283

284+
def test_cursor_position
285+
run_pty("#{<<~"begin;"}\n#{<<~'end;'}") do |r, w, _|
286+
begin;
287+
con = IO.console
288+
p con.cursor
289+
con.cursor_down(3); con.puts
290+
con.cursor_right(4); con.puts
291+
con.cursor_left(2); con.puts
292+
con.cursor_up(1); con.puts
293+
end;
294+
assert_equal("\e[6n", r.readpartial(5))
295+
w.print("\e[12;34R"); w.flush
296+
assert_equal([11, 33], eval(r.gets))
297+
assert_equal("\e[3B", r.gets.chomp)
298+
assert_equal("\e[4C", r.gets.chomp)
299+
assert_equal("\e[2D", r.gets.chomp)
300+
assert_equal("\e[1A", r.gets.chomp)
301+
end
302+
end
303+
284304
unless IO.console
285305
def test_close
286306
assert_equal(["true"], run_pty("IO.console.close; p IO.console.fileno >= 0"))

0 commit comments

Comments
 (0)