DEFINITIONS
This source file includes following functions.
1 #!/usr/local/bin/ruby
2
3 require "curses"
4
5 if ARGV.size != 1 then
6 printf("usage: view file\n");
7 exit
8 end
9 begin
10 fp = open(ARGV[0], "r")
11 rescue
12 raise "cannot open file: #{ARGV[1]}"
13 end
14
15 # signal(SIGINT, finish)
16
17 Curses.init_screen
18 Curses.nonl
19 Curses.cbreak
20 Curses.noecho
21
22 $screen = Curses.stdscr
23
24 $screen.scrollok(true)
25 #$screen.keypad(true)
26
27 # slurp the file
28 $data_lines = []
29 fp.each_line { |l|
30 $data_lines.push(l.chop)
31 }
32 fp.close
33
34 $top = 0
35 $data_lines[0..$screen.maxy-1].each_with_index{|line, idx|
36 $screen.setpos(idx, 0)
37 $screen.addstr(line)
38 }
39 $screen.setpos(0,0)
40 $screen.refresh
41
42 def scroll_up
43 if( $top > 0 )
44 $screen.scrl(-1)
45 $top -= 1
46 str = $data_lines[$top]
47 if( str )
48 $screen.setpos(0, 0)
49 $screen.addstr(str)
50 end
51 return true
52 else
53 return false
54 end
55 end
56
57 def scroll_down
58 if( $top + $screen.maxy < $data_lines.length )
59 $screen.scrl(1)
60 $top += 1
61 str = $data_lines[$top + $screen.maxy - 1]
62 if( str )
63 $screen.setpos($screen.maxy - 1, 0)
64 $screen.addstr(str)
65 end
66 return true
67 else
68 return false
69 end
70 end
71
72 while true
73 result = true
74 c = Curses.getch
75 case c
76 when Curses::KEY_DOWN, Curses::KEY_CTRL_N
77 result = scroll_down
78 when Curses::KEY_UP, Curses::KEY_CTRL_P
79 result = scroll_up
80 when Curses::KEY_NPAGE, ?\s # white space
81 for i in 0..($screen.maxy - 2)
82 if( ! scroll_down )
83 if( i == 0 )
84 result = false
85 end
86 break
87 end
88 end
89 when Curses::KEY_PPAGE
90 for i in 0..($screen.maxy - 2)
91 if( ! scroll_up )
92 if( i == 0 )
93 result = false
94 end
95 break
96 end
97 end
98 when Curses::KEY_LEFT, Curses::KEY_CTRL_T
99 while( scroll_up )
100 end
101 when Curses::KEY_RIGHT, Curses::KEY_CTRL_B
102 while( scroll_down )
103 end
104 when ?q
105 break
106 else
107 $screen.setpos(0,0)
108 $screen.addstr("[unknown key `#{Curses.keyname(c)}'=#{c}] ")
109 end
110 if( !result )
111 Curses.beep
112 end
113 $screen.setpos(0,0)
114 end
115 Curses.close_screen