Skip to content

Instantly share code, notes, and snippets.

@oprypin
Created August 9, 2017 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oprypin/36ca2b9e108763c0aed0dc25bbe4e03b to your computer and use it in GitHub Desktop.
Save oprypin/36ca2b9e108763c0aed0dc25bbe4e03b to your computer and use it in GitHub Desktop.
def key
STDIN.raw do |io|
loop do
buffer = Bytes.new(3)
bytes_read = io.read(buffer)
if bytes_read > 0
return String.new(buffer[0, bytes_read])
end
end
end
end
string = ""
cursor_pos = 0
loop do
input = key()
case input
when "\x7f" # backspace
if cursor_pos > 0
cursor_pos -= 1
string = string.sub(cursor_pos, "")
end
when "\e[D" # left
cursor_pos = {cursor_pos - 1, 0}.max
when "\e[C" # right
cursor_pos = {cursor_pos + 1, string.size}.min
when "\t"
exit
else
if input[0] >= ' ' # non-control characters
string = string.sub(cursor_pos...cursor_pos, input)
cursor_pos += input.size
end
end
print "\r" + string + " \r" + string[0, cursor_pos]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment