-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadline.lua
133 lines (127 loc) · 2.42 KB
/
readline.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
-- vim:et
class "Readline"
function Readline:initialize(size)
self.buf={}
self.len=0
self.sz=size
self.str=""
self.i=1
self.cr=true
self.hist={}
self.old=nil
self.hi=0
end
function Readline:clr()
self.buf={}
self.len=0
self.str=""
self.i=1
self.old=nil
self.hi=0
end
function Readline:done()
self.hist[#self.hist+1]=self.buf
self:clr()
end
function Readline:key(key,ch)
if key=="left" then
if self.i>1 then
self.i=self.i-1
end
return
end
if key=="right" then
if self.i<=self.len then
self.i=self.i+1
end
return
end
if key=="home" then
self.i=1
return
end
if key=="end" then
self.i=self.len+1
return
end
if key=="backspace" then
if self.i>1 then
self.i=self.i-1
table.remove(self.buf,self.i)
self.len=self.len-1
self.str=table.concat(self.buf)
end
return
end
if key=="delete" then
if self.i<=self.len then
table.remove(self.buf,self.i)
self.len=self.len-1
self.str=table.concat(self.buf)
end
return
end
if key=="up" then
if #self.hist<1 then
return
end
if self.hi>1 then
self.hi=self.hi-1
end
if self.hi==0 then
self.old=self.buf
self.hi=#self.hist
end
self.buf=icopy(self.hist[self.hi])
self.len=#self.buf
self.i=self.len+1
self.str=table.concat(self.buf)
return
end
if key=="down" then
if #self.hist<1 then
return
end
if self.hi==0 then
return
end
if self.hi<#self.hist then
self.hi=self.hi+1
self.buf=icopy(self.hist[self.hi])
self.len=#self.buf
self.i=self.len+1
self.str=table.concat(self.buf)
return
end
if self.old then
self.hi=0
self.buf=self.old
self.len=#self.buf
self.i=self.len+1
self.str=table.concat(self.buf)
end
return
end
if ch<32 or ch>127 then
return
end
if self.len<self.sz then
table.insert(self.buf,self.i,string.char(ch))
self.len=self.len+1
self.i=self.i+1
self.str=table.concat(self.buf)
end
end
function Readline:draw(x,y,prompt)
local font=graph.getFont()
local str=string.format("%s%s",prompt,self.str)
local l=prompt:len()
local wy=font:getHeight()
local wx=font:getWidth(str:sub(1,self.i+l-1))
graph.setColor(255,255,255)
graph.print(str,x,y)
graph.setLine(2,"rough")
if self.cr then
graph.line(x+wx,y,x+wx,y+wy)
end
end