-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathselecta
executable file
·414 lines (343 loc) · 8.31 KB
/
selecta
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/usr/bin/env bash
# vim: set ft=ruby:
# This file executes as a bash script, which turns around and executes Ruby via
# the line below. The -x argument to Ruby makes it discard everything before
# the second "!ruby" shebang. This allows us to work on Linux, where the
# shebang can only have one argument so we can't directly say
# "#!/usr/bin/env ruby --disable-gems". Thanks for that, Linux.
#
# If this seems confusing, don't worry. You can treat it as a normal Ruby file
# starting with the "!ruby" shebang below.
exec /usr/bin/env ruby --disable-gems -x "$0"
#!ruby
require "io/console"
# I don't know how to get these key codes other than by hard-coding the
# ordinals
KEY_CTRL_C = 3.chr
KEY_CTRL_N = 14.chr
KEY_CTRL_P = 16.chr
KEY_CTRL_W = 23.chr
KEY_DELETE = 127.chr
def main
options = Options.new(20)
choices = $stdin.readlines.map(&:chomp).sort_by(&:length)
world = World.blank(options, choices)
Screen.with_screen do |screen, tty|
# We emit the number of lines we'll use later so we don't clobber whatever
# was already on the screen.
(options.visible_choices).times { tty.puts }
while not world.done?
Renderer.render!(world, screen)
world = handle_key(world, tty.get_char)
end
screen.move_cursor(screen.height - 1, 0)
end
puts world.selected_choice
end
def handle_key(world, key)
case key
when KEY_CTRL_N then world.down
when KEY_CTRL_P then world.up
when KEY_CTRL_W then world.delete_word
when KEY_DELETE then world.backspace
when ?\r then world.done
when KEY_CTRL_C then raise SystemExit
when /[[:print:]]/ then world.append_search_string(key.chr)
else world
end
end
class Options < Struct.new(:visible_choices)
end
class World
attr_reader :choices, :index, :query, :options
def initialize(vars)
@vars = vars
@options = vars.fetch(:options)
@choices = vars.fetch(:choices)
@index = vars.fetch(:index)
@query = vars.fetch(:query)
@done = vars.fetch(:done)
end
def self.blank(options, choices)
new(:options => options,
:choices => choices,
:index => 0,
:query => "",
:done => false)
end
def merge(vars)
World.new(@vars.merge(vars))
end
def done?
@done
end
def selected_choice
matches.fetch(@index)
end
def down
index = [@index + 1, matches.count - 1, options.visible_choices - 1].min
merge(:index => index)
end
def up
merge(:index => [@index - 1, 0].max)
end
def append_search_string(string)
merge(:index => 0,
:query => @query + string)
end
def backspace
merge(:index => 0,
:query => @query[0...-1])
end
def delete_word
merge(:query => @query.sub(/[^ ]* *$/, ""))
end
def matches
re = query.split(//).map(&Regexp.method(:escape)).join('.*')
re = /#{re}/i
@choices.select { |s| s =~ re }
end
def done
merge(:done => true)
end
end
class Renderer < Struct.new(:world, :screen)
def self.render!(world, screen)
rendered = Renderer.new(world, screen).render
start_line = screen.height - world.options.visible_choices - 1
screen.with_cursor_hidden do
screen.write_lines(start_line, rendered.choices)
screen.move_cursor(start_line, rendered.search_line.length)
end
end
def render
search_line = "> " + world.query
matches = world.matches
unless matches.empty?
matches[world.index] = Text[:default_black, matches.fetch(world.index)]
end
matches = correct_match_count(matches)
choices = [search_line] + matches
Rendered.new(choices, search_line)
end
def correct_match_count(matches)
limited = matches[0, world.options.visible_choices]
padded = limited + [""] * (world.options.visible_choices - limited.length)
padded
end
class Rendered < Struct.new(:choices, :search_line)
end
end
class Screen
def self.with_screen
TTY.with_tty do |tty|
screen = self.new(tty)
screen.configure_tty
begin
yield screen, tty
ensure
screen.restore_tty
tty.puts
end
end
end
attr_reader :tty, :ansi
def initialize(tty)
@tty = tty
@ansi = ANSI.new(tty.out_file)
@original_stty_state = tty.stty("-g")
end
def configure_tty
# raw: Disable input and output processing
# -echo: Don't echo keys back
# cbreak: Set up lots of standard stuff, including INTR signal on ^C
tty.stty("raw -echo cbreak")
end
def restore_tty
tty.stty("#{@original_stty_state}")
end
def suspend
restore_tty
begin
yield
configure_tty
rescue
restore_tty
end
end
def with_cursor_hidden(&block)
ansi.hide_cursor!
begin
block.call
ensure
ansi.show_cursor!
end
end
def height
size[0]
end
def width
size[1]
end
def size
height, width = tty.winsize
[height, width]
end
def move_cursor(line, column)
ansi.setpos!(line, column)
end
def write_line(line, text)
write(line, 0, text)
end
def write_lines(line, texts)
texts.each_with_index do |text, index|
write(line + index, 0, text)
end
end
def write(line, column, text)
# Discard writes outside the main screen area
write_unrestricted(line, column, text) if line < height
end
def write_unrestricted(line, column, text)
text = Text[:default, text] unless text.is_a? Text
write_text_object(line, column,text)
end
def write_text_object(line, column, text)
highlight = false
text.components.each do |component|
if component.is_a? String
ansi.setpos!(line, column)
ansi.addstr!(component)
column += component.length
elsif component == :highlight
highlight = true
else
if component =~ /_/
fg, bg = component.to_s.split(/_/).map(&:to_sym)
else
fg, bg = component, :default
end
ansi.color!(fg, bg)
end
end
remaining_cols = [width - column, 0].max
ansi.addstr!(" " * remaining_cols)
end
end
class Text
attr_reader :components
def self.[](*args)
new(args)
end
def initialize(components)
@components = components
end
def ==(other)
components == other.components
end
def +(other)
Text[*(components + other.components)]
end
end
class ANSI
ESC = 27.chr
attr_reader :file
def initialize(file)
@file = file
end
def escape(sequence)
ESC + "[" + sequence
end
def reset
escape "2J"
end
def hide_cursor
escape "?25l"
end
def show_cursor
escape "?25h"
end
def setpos(line, column)
escape "#{line + 1};#{column + 1}H"
end
def addstr(str)
str
end
def color(fg, bg=:default)
normal = "22"
fg_codes = {
:black => 30,
:red => 31,
:green => 32,
:yellow => 33,
:blue => 34,
:magenta => 35,
:cyan => 36,
:white => 37,
:default => 39,
}
bg_codes = {
:black => 40,
:red => 41,
:green => 42,
:yellow => 43,
:blue => 44,
:magenta => 45,
:cyan => 46,
:white => 47,
:default => 49,
}
fg_code = fg_codes.fetch(fg)
bg_code = bg_codes.fetch(bg)
escape "#{normal};#{fg_code};#{bg_code}m"
end
def reset!(*args); write reset(*args); end
def setpos!(*args); write setpos(*args); end
def addstr!(*args); write addstr(*args); end
def color!(*args); write color(*args); end
def hide_cursor!(*args); write hide_cursor(*args); end
def show_cursor!(*args); write show_cursor(*args); end
def write(bytes)
file.write(bytes)
end
end
class TTY < Struct.new(:in_file, :out_file)
def self.with_tty(&block)
File.open("/dev/tty", "r") do |in_file|
File.open("/dev/tty", "w") do |out_file|
tty = TTY.new(in_file, out_file)
block.call(tty)
end
end
end
def get_char
in_file.getc
end
def puts
out_file.puts
end
def winsize
out_file.winsize
end
def stty(args)
command("stty #{args}")
end
private
# Run a command with the TTY as stdin, capturing the output via a pipe
def command(command)
IO.pipe do |read_io, write_io|
pid = Process.spawn(command, :in => "/dev/tty", :out => write_io)
Process.wait(pid)
raise "Command failed: #{command.inspect}" unless $?.success?
write_io.close
read_io.read
end
end
end
if $0 == __FILE__
begin
main
rescue SystemExit, Interrupt
exit(1)
end
end