Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid echoing newline when reading user input?

Tags:

ruby

I'm writing an curses-like program in Ruby, and I'm using stty and ansi escape characters to achieve what I want. My problem occurs when I want to get user input. Like many console based programs, I want to get user input from the bottom of the terminal.

Thus, I place the cursor at the bottom of the screen and call Readline.readline (or whatever method to get user input). As usual, it reads everything until I hit return, and a newline is printed. Since the cursor is at the last line of the terminal, it scrolls one line, which messes up the screen.

How can I avoid this? I tried to use stty to stop echoing of newlines, but I didn't succeed. Maybe one can use stty to stop the terminal from scrolling? Of course, I could write my own method for catching input by reading one character at a time (and catching the "return"), but I want to use all the extras that readline provides.

like image 841
Joakim Arnlind Avatar asked Aug 14 '11 13:08

Joakim Arnlind


Video Answer


1 Answers

Ruby Readline is a simple wrapper for the GNU Readline library, which directly manages terminal modes - this is why you might not be having much luck using stty to modify terminal settings. The Readline.readline method specifically puts the terminal into raw mode and echoes all characters back to STDOUT (or Readline.output for Ruby 1.9, which defaults to STDOUT).

Unfortunately, the Ruby Readline wrapper does not completely wrap the GNU Readline library; GNU Readline provides a number of functions for redisplay, but the Ruby Readline wrapper does not expose these functions.

If you specifically want to use Readline and Ruby and need to ignore that newline, you don't have a ton of options. One option, which is kind of silly, is to open a pipe as an intermediary listening on its own thread and forward all Readline output to it. The following accomplishes this, but be warned, this isn't what you really want (and on OSX it required ruby 1.9.2 linked against readline instead of libedit, because libedit is blocking)....

require 'readline'

`mkfifo /tmp/readline-pipe`

Readline.output = File.open("/tmp/readline-pipe", "w+")

Thread.new {
  input = open("/tmp/readline-pipe", "r+")
  while true
    character = input.getc
    if character != "\n"
      $stdout.write(character)
      $stdout.flush
    end
  end
}

begin
  while line = Readline.readline("", true)
    $stdout.write(" NEWLINE ENTERED BUT NOT DISPLAYED ")
    $stdout.flush
  end
rescue EOFError
  puts "Exiting..."
end
like image 169
hoxworth Avatar answered Oct 16 '22 23:10

hoxworth