aboutsummaryrefslogtreecommitdiff
path: root/src/line/input.cc
blob: 1b9520bb82e6f1b940e667d774e6c55291a6631d (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
95
96
97
98
99
100
101
102
103
104
105
106

#include "line/line_editor.h"

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

#include "history.h"
#include "util/non_block_input.h"
#include "pipe.h"

using namespace std;

namespace ov4
{

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

string T_line_editor::readline(int prompt_len)
{
    prompt_pos = prompt_len+1;
    update_window_size();
    history_vec.push_back("");
    history_index = get_last_index();
    reset_editor();

    char c; int src;
    while (non_block_read_char(&c, &src) == 1)
    {
        // if signal'd
        if (src == self_pipe_fd[0])
        {
            check_window_update();
            continue;
        }
        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]);
            }

            // backspace
            else if (c == '\b' || c == '\x7f')
            {
                cursor_input_char(c);
                print_override(line_buffer);
            }
        }

        // 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;
}

}