aboutsummaryrefslogtreecommitdiff
path: root/src/line/input.cc
blob: 9c593f79a8a0ef1ae3166f3a5905c2914272d748 (plain)
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

#include "line/input.h"

#include <print>
#include <string>
#include <unistd.h>

#include "line/cursor.h"
#include "history.h"
#include "line/getter.h"

using namespace std;

namespace ov4
{

void clear_below()
{
    print("\x1b[0J");
}

string readline()
{
    update_window_size();
    history_vec.push_back("");
    history_index = get_last_index();
    reset_editor();

    T_position pos = get_cursor_position();
    prompt_pos = pos.col;
    char c;
    while (read(STDIN_FILENO, &c, 1) == 1)
    {
        if (iscntrl(c))
        {
            //print("control: {}\r\n", static_cast<unsigned char>(c));
            //fflush(stdout);
            if (c == 0x0A || c == 0x0D) // \n OR \r
            {
                //print("line: {}\r\n", line_buffer);
                if (line_buffer.empty())
                {
                    history_index--;
                    history_vec.pop_back();
                }
                else
                {
                    history_vec[get_last_index()] = line_buffer;
                }
                return line_buffer;
            }

            else if (c == 0x03) // control C
            {
                history_index--;
                history_vec.pop_back();
                return "";
            }

            // ESC sequence
            else if (c == '\x1b')
            {
                char seq[10];
                // eat [
                if (read(STDIN_FILENO, seq + 0, 1) != 1)
                    continue;

                if (read(STDIN_FILENO, seq + 1, 1) != 1)
                    continue;

                move_cursor(seq[1]);
            }
        }

        // normal char
        else
        {
            cursor_input_char(c);
            print_override(line_buffer);
        }
    }

    if (line_buffer.empty())
    {
        history_index--;
        history_vec.pop_back();
    }
    else
    {
        history_vec[get_last_index()] = line_buffer;
    }
    return line_buffer;
}

}