-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathqselect.cpp
91 lines (77 loc) · 2.09 KB
/
qselect.cpp
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
#include "match.h"
#include "term.h"
#include "prompt.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
static const int MAXLINES = 20;
static char handle_escape(Term &tty);
int main(void)
{
vector<wstr> input;
string line;
while (getline(cin, line)) input.emplace_back(line);
Term tty("/dev/tty");
Term::Size screen_size = tty.get_screen_size();
char ch;
int selection = 1;
Prompt prompt(tty, "> ");
tty.erase_display(Term::FORWARD);
for (;;) {
auto last = match(input.begin(), input.end(), prompt.query());
auto it = input.cbegin();
int i = 1;
for (; it != last; ++i, ++it) {
string str = (*it).str.substr(0, screen_size.columns);
if (i == selection) {
tty.puts_highlighted(str);
} else {
tty.puts(str);
}
if (i == MAXLINES)
break;
tty.putchar('\n');
}
tty.cursor_up(i);
tty.move_to_col(prompt.current_column());
ch = tty.getchar();
if (ch == Term::ESC) {
ch = handle_escape(tty);
}
if (ch == Term::CTRL_C || ch == Term::ENTER) {
break;
} else if (ch == Term::CTRL_N) {
selection = min(selection + 1, i - 1);
} else if (ch == Term::CTRL_P) {
selection = max(selection - 1, 1);
} else if (prompt.handle_key(static_cast<Term::Key>(ch))) {
selection = 1;
}
tty.putchar('\n');
tty.erase_display(Term::FORWARD);
}
tty.move_to_col(1);
tty.erase_display(Term::FORWARD);
if (ch == Term::ENTER) {
cout << input[selection - 1].str.c_str() << endl;
return 0;
}
return 1;
}
static char handle_escape(Term &tty)
{
char ch = tty.getchar();
if (ch != '[') {
return ch;
}
ch = tty.getchar();
if (ch == 'A' || ch == 'D') {
return Term::CTRL_P;
} else if (ch == 'B' || ch == 'C') {
return Term::CTRL_N;
} else {
return 0;
}
}