Skip to content

Commit 5e8a48f

Browse files
committed
Merge pull request #9 from clue-labs/position
Add accessor for current cursor position
2 parents f6c88ab + a4b607c commit 5e8a48f

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/Readline.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,21 @@ public function setMove($move)
110110
return $this;
111111
}
112112

113+
/**
114+
* get current cursor position
115+
*
116+
* cursor position is measured in number of text characters
117+
*
118+
* @return int
119+
* @see self::moveCursorTo() to move the cursor to a given position
120+
* @see self::moveCursorBy() to move the cursor by given number of characters
121+
* @see self::setMove() to toggle whether the user can move the cursor position
122+
*/
123+
public function getCursorPosition()
124+
{
125+
return $this->linepos;
126+
}
127+
113128
/**
114129
* set current text input buffer
115130
*
@@ -323,11 +338,12 @@ public function deleteChar($n)
323338
* zero or out of range moves are simply ignored
324339
*
325340
* @param int $n
341+
* @return self
326342
* @uses self::moveCursorTo()
327343
*/
328344
public function moveCursorBy($n)
329345
{
330-
$this->moveCursorTo($this->linepos + $n);
346+
return $this->moveCursorTo($this->linepos + $n);
331347
}
332348

333349
/**
@@ -336,6 +352,7 @@ public function moveCursorBy($n)
336352
* out of range (exceeding current input buffer) are simply ignored
337353
*
338354
* @param int $n
355+
* @return self
339356
* @uses self::redraw()
340357
*/
341358
public function moveCursorTo($n)
@@ -346,6 +363,8 @@ public function moveCursorTo($n)
346363

347364
$this->linepos = $n;
348365
$this->redraw();
366+
367+
return $this;
349368
}
350369

351370
/**

tests/ReadlineTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,29 @@ public function testSettersReturnSelf()
2020
public function testInputStartsEmpty()
2121
{
2222
$this->assertEquals('', $this->readline->getInput());
23+
$this->assertEquals(0, $this->readline->getCursorPosition());
2324
}
2425

2526
public function testGetInputAfterSetting()
2627
{
2728
$this->assertSame($this->readline, $this->readline->setInput('hello'));
2829
$this->assertEquals('hello', $this->readline->getInput());
30+
$this->assertEquals(5, $this->readline->getCursorPosition());
31+
}
32+
33+
public function testSettingInputMovesCursorToEnd()
34+
{
35+
$this->readline->setInput('hello');
36+
$this->readline->moveCursorTo(3);
37+
38+
$this->readline->setInput('testing');
39+
$this->assertEquals(7, $this->readline->getCursorPosition());
40+
}
41+
42+
public function testMultiByteInput()
43+
{
44+
$this->readline->setInput('täst');
45+
$this->assertEquals('täst', $this->readline->getInput());
46+
$this->assertEquals(4, $this->readline->getCursorPosition());
2947
}
3048
}

0 commit comments

Comments
 (0)