sup

A curses threads-with-tags style email client

ncursesw-ruby.git

git clone https://supmua.dev/git/ncursesw-ruby/

examples/read_line.rb (1962B) - raw

      1 #!/usr/bin/env ruby
      2 # Emacs: This is -*- ruby -*- code!
      3 #
      4 # Unfinished read_line function
      5 #
      6 # Written 2003, 2004 by Tobias Peters
      7 # No warranties
      8 # Share and enjoy!
      9 #
     10 # 2014: Updated by Gaute Hope
     11 # Note: This is not wide char / unicode safe - take a look at
     12 #       form_get_wch.rb for a better example.
     13 
     14 require "ncursesw"
     15 
     16 # read_line returns an array
     17 # [string, last_cursor_position_in_string, keycode_of_terminating_enter_key].
     18 # Complete the "when" clauses before including in your app!
     19 def read_line(y, x,
     20               window     = Ncurses.stdscr,
     21               max_len    = (window.getmaxx - x - 1),
     22               string     = "",
     23               cursor_pos = 0)
     24   loop do
     25     window.mvaddstr(y,x,string)
     26     window.move(y,x+cursor_pos)
     27     ch = window.getch
     28     case ch
     29     when Ncurses::KEY_LEFT
     30       cursor_pos = [0, cursor_pos-1].max
     31     when Ncurses::KEY_RIGHT
     32       # similar, implement yourself !
     33     when Ncurses::KEY_ENTER, "\n".ord
     34       return string, cursor_pos, ch # Which return key has been used?
     35     when Ncurses::KEY_BACKSPACE
     36       string = string[0...([0, cursor_pos-1].max)] + string[cursor_pos..-1]
     37       cursor_pos = [0, cursor_pos-1].max
     38       window.mvaddstr(y, x+string.length, " ")
     39     # when etc...
     40     when " ".ord..255 # remaining printables
     41       if (cursor_pos < max_len)
     42         string[cursor_pos,0] = ch.chr
     43         cursor_pos += 1
     44       else
     45         Ncurses.mvprintw(15, 10, "A: Got: #{ch.inspect} (#{[ch].pack("U")})")
     46         Ncurses.beep
     47       end
     48     else
     49       Ncurses.mvprintw(16, 10, "B: Got: #{ch.inspect} (#{[ch].pack("U")})")
     50       Ncurses.beep
     51     end
     52   end
     53 end
     54 
     55 if (__FILE__ == $0) then begin
     56   # demo mode
     57   Ncurses.initscr
     58   Ncurses.cbreak
     59   Ncurses.noecho
     60 
     61   # recognize KEY_ENTER, KEY_BACKSPACE  etc
     62   Ncurses.keypad(Ncurses.stdscr, true)
     63   #Ncurses.nonl()
     64 
     65   y = 10
     66   x = 2
     67   prompt = "Hallo > "
     68   Ncurses.mvaddstr(y,x, prompt)
     69   s = read_line(y, x + prompt.length)
     70 
     71 ensure
     72   Ncurses.endwin
     73 end end
     74 p s