Line inserts/deletes

This commit is contained in:
Matúš Púll 2025-03-17 17:37:54 +01:00
parent 515a25cee0
commit 571fefc8c0

View file

@ -15,6 +15,22 @@ enum mode_type { insert, normal };
vector<string> file(0);
int row = 0, col = 0;
// Accessing the file
char get(int r, int s) { return file[r][s]; }
void set(int r, int s, char ch) { file[r][s] = ch; }
string get_line(int r) { return file[r]; }
void add_line(int r) { file.insert(file.begin() + r, ""); }
void remove_line(int r) { file.erase(file.begin() + r); }
// 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);
@ -38,6 +54,7 @@ bool save(string filename) {
// Print file content
void print_file() {
clear();
for(int i = 0; i < file.size(); i++) {
move(i, 0);
adds(file[i]);
@ -47,18 +64,23 @@ void print_file() {
// TODO psaní do souboru
// TODO mazání v souboru
// TODO vkládání a mazání řádků
// 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) {
move(row, col);
addch(file[row][col]);
move(row, col);
switch(ch) {
case 'h':
if(col > 0)
@ -68,25 +90,19 @@ void move_cursor(char ch) {
case 'j':
if(row < file.size()-1) {
move(++row, col);
if(file[row].size() <= col) {
col = file[row].size()-1;
move(row, col);
}
jump_line_end();
}
break;
case 'k':
if(row > 0) {
move(--row, col);
if(file[row].size() <= col) {
col = file[row].size()-1;
move(row, col);
}
jump_line_end();
}
break;
case 'l':
if(col < file[row].size()-1)
if(col < file[row].size())
move(row, ++col);
break;
}
@ -97,9 +113,12 @@ int main(int argc, char* argv[]) {
// Init
initscr();
refresh();
if(argc > 1 && load(argv[1]))
// Check valid filename and load
if(argc <= 1)
return 1;
if(argc > 1 && save(argv[1]))
string filename = argv[1];
if(load(filename))
return 1;
print_file();
@ -107,12 +126,42 @@ int main(int argc, char* argv[]) {
mode_type mode = normal;
// Main loop
while(true) {
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 'o':
add_line(row);
print_file();
break;
case 'q':
run = false;
break;
case 'w':
save(filename);
break;
}
break;
case insert:
// insert
break;
}
refresh();
}
if(argc > 1 && save(argv[1]))
return 1;
// End
endwin();
return 0;