#include #include #include #include #include #include "treap.hpp" using std::string; using std::vector; #define adds(s) addstr(s.c_str()) enum mode_type { insert, normal }; // Global variables treap file; int row = 0, col = 0; // Accessing the file string get_line(int r) { return file.find(r)->text; } char get(int r, int s) { return get_line(r)[s]; } void set(int r, int s, char ch) { file.find(r)->text[s] = ch; } void add_line(int r, string text = "") { file.insert(r, text); } void remove_line(int r) { file.remove(r); } void insert_char(int r, int s, char ch) { file.find(r)->text.insert(s, string{ch}); } void remove_char(int r, int s) { file.find(r)->text.erase(s); } // For normal mode not to write to terminal void step_back() { move(row, col); char ch = col < get_line(row).size() ? get(row, col) : ' '; addch(ch); move(row, col); } // Load file to buffer bool load(string filename) { std::ifstream infile(filename); if(!infile.good()) return 1; string line; while (std::getline(infile, line)) file.insert(file.size(), line); return 0; } // Save file from buffer bool save(string filename) { std::ofstream outfile(filename); if(!outfile.good()) return 1; for(int i = 0; i < file.size(); ++i) outfile << get_line(i) << std::endl; return 0; } // Print file content void print_file() { clear(); for(int i = 0; i < file.size(); i++) { move(i, 0); adds(get_line(i)); } move(row, col); } // Print line void print_line(int r) { move(r, 0); clrtoeol(); move(r, 0); adds(get_line(r)); move(row, col); } // TODO mazání v souboru // TODO skoky a přesuny // TODO kopirování // TODO hledání a nahrazování // TODO undo // Jump to end of line void jump_line_end() { int line_size = get_line(row).size(); if(col > line_size) { col = line_size; move(row, col); } } // Cursor movement void move_cursor(char ch) { switch(ch) { case 'h': if(col > 0) move(row, --col); break; case 'j': if(row < file.size()-1) { move(++row, col); jump_line_end(); } break; case 'k': if(row > 0) { move(--row, col); jump_line_end(); } break; case 'l': if(col < get_line(row).size()) move(row, ++col); break; } } int main(int argc, char* argv[]) { // Init initscr(); refresh(); // Check valid filename and load if(argc <= 1) return 1; string filename = argv[1]; if(load(filename)) return 1; print_file(); mode_type mode = normal; // Main loop bool run = true; while(run) { char ch = getch(); switch(mode) { case normal: step_back(); switch(ch) { case 'h': case 'j': case 'k': case 'l': move_cursor(ch); break; case 'd': remove_line(row); print_file(); break; case 'x': remove_char(row, col); print_line(row); break; case 'o': add_line(row); print_file(); break; case 'q': run = false; break; case 'w': save(filename); break; case 'i': mode = insert; break; } break; case insert: insert_char(row, col++, ch); print_line(row); break; } refresh(); } if(argc > 1 && save(argv[1])) return 1; // End endwin(); return 0; }