-
Notifications
You must be signed in to change notification settings - Fork 0
/
opn
executable file
·101 lines (77 loc) · 2.44 KB
/
opn
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
#!/usr/bin/env python3
import os, sys
import tty, termios
import fcntl, struct
COLOR_BLACK = "\033[30m"
COLOR_BG_CYAN = "\033[46m"
COLOR_RESET = "\033[0;0m"
CLEAR_LINE = "\033[K"
KEY_ESC = "\x1B"
KEY_RETURN = "\x0D"
def manual():
print("Usage: opn [command ...] [keyword]")
print("The last paramater will be used as [keyword] " +
"for subdirectory searching.")
print("[command ...] will be applied to the selected file.")
def search(keyword):
result = []
for (root, dirs, files) in os.walk("."):
result_curdir = filter(lambda file: keyword in file, files)
result += map(lambda x: os.path.join(root, x), result_curdir)
return result
def get_terminal_size():
th, tw, hp, wp = struct.unpack("HHHH", fcntl.ioctl(
0, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0)))
return (tw, th)
def print_files(l, pos, width, height):
start = pos - int(height / 2);
start = min(len(l) - height, start)
start = max(0, start)
end = start + min(len(l), height)
for i in range(start, end):
print(CLEAR_LINE, end = "")
if i == pos:
print(COLOR_BLACK + COLOR_BG_CYAN, end = "")
print(l[i][:width], end = "")
if i == pos:
print(COLOR_RESET, end = "")
print("")
def get_key():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
def ui(l):
width = get_terminal_size()[0]
height = get_terminal_size()[1] - 1 # Leave a line for cursor
pos = 0
while True:
print_files(l, pos, width, height)
k = get_key()
if k == "k": pos -= 1
elif k == "j": pos += 1
elif k == "h": pos = max(0, pos - int(height / 2))
elif k == "l": pos = min(len(l) - 1, pos + int(height / 2))
elif k == "q" or k == KEY_ESC: break
elif k == KEY_RETURN:
run_command(l[pos])
break;
pos %= len(l)
pos_moveup = min(len(l), height)
print("\033[" + str(pos_moveup) + "A", end = "")
def run_command(s):
cmds = sys.argv[1:-1] + ["\"" + s + "\""]
os.system(" ".join(cmds))
try:
if len(sys.argv) <= 1:
manual()
exit()
result = search(sys.argv[-1])
if len(result) <= 0:
exit()
ui(result)
except (KeyboardInterrupt, SystemExit):
exit()