aboutsummaryrefslogtreecommitdiffstats
path: root/editor.cpp
blob: 28bd0810d15cb15e7c82848a460c6cb14c01b82c (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
#include "editor.h"
#include "utils.h"
#include <limits>
#include <iostream>

Editor::Editor(std::vector<std::string>* contents):
    m_current_line(0)  {

    m_contents = contents;
}

int Editor::run_editor() {
    std::vector<std::string>* c = m_contents;

    bool stopped = false;
    while (!stopped) {
        print_contents_on_line(m_current_line);
        
        char input = Utils::getch();
        switch (input) {
        case 'e':
            edit_command();
            break;
        case 'm':
            move_to_command();
            break;
        default:
            break;
        }
    }
    return 0;
}

int Editor::print_contents_on_line(int line) const {
    for (int i = line; i < std::min((int) m_contents->size(), line + OUTPUT_LINE_MAX); i++) {
        std::cout << i << " " << m_contents->at(i) << '\n';
    }
}

int Editor::edit_command() {
    std::cout << "Edit which line? ";
    int line;
    std::cin >> line; if (std::cin.fail() || line < 0 || line >= m_contents->size()) {
        std::cout << "Not a valid line number!\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        return 1;
    }

    return edit_line(line);
}

int Editor::edit_line(int line) {
    std::cout << "> ";
    std::string input;

    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    std::getline(std::cin, input);
    std::cin.clear();
    (*m_contents)[line] = input;

    return 0;
}

int Editor::move_to_command() {
    std::cout << "Move to which line? ";
    int line;
    std::cin >> line;
    if (std::cin.fail() || line < 0 || line >= m_contents->size()) {
        std::cout << "Not a valid line number!\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        return 1;
    }

    return move_to_line(line);
}

int Editor::move_to_line(int line) {
    m_current_line = line;
    return 0;
}