Generalize selection manipulation and add remove selection

This commit is contained in:
Matúš Púll 2025-04-20 11:56:59 +02:00
parent 61ce077ea0
commit 38d2ca1d66

View file

@ -142,8 +142,9 @@ string get_string(string prompt) {
return s;
}
// Copying
void copy_selection(position p = cur + file_offset) {
// Selection manipulation
template <typename F, typename G>
void apply_on_selection(position p, F func, G func2) {
// Determine first and last selected position
position start = p, end = clp;
if(clp.r < cur.r || (clp.r == cur.r && clp.c < cur.c))
@ -152,24 +153,37 @@ void copy_selection(position p = cur + file_offset) {
// Clear previous selection
selection.clear();
// Add all complete lines in between
for(count_type r = start.r+1; r < end.r; ++r)
selection.append(get_line(r));
// Last line start
if(start.r < end.r)
func2(end.r, 0, end.c+1);
// selection.append(get_line(end.r).substr(0, end.c+1));
// Add first line end
// All complete lines in between
for(count_type r = end.r-1; r > start.r; --r)
func(r);
//selection.append(get_line(r));
// First line end
string start_line = get_line(start.r);
count_type size = ((start.r == end.r) ? end.c+1 : start_line.size()) - start.c;
string start_text = start_line.substr(start.c, size);
selection.insert(0, start_text);
// Add last line start
if(start.r < end.r) {
string end_line = get_line(end.r);
string end_text = end_line.substr(0, end.c+1);
selection.append(end_text);
}
func2(start.r, start.c, size); // append
//selection.insert(0, start_line.substr(start.c, size));
}
// Pasting
// Removing selection
void remove_selection(position p = cur + file_offset) {
apply_on_selection(p,
[](count_type r){ remove(r); },
[](count_type r, count_type start_c, count_type size) { remove({r, start_c}, size); }
);
}
// Copying selection
void copy_selection(position p = cur + file_offset) {
apply_on_selection(p,
[](count_type r){ selection.insert(0, get_line(r)); },
[](count_type r, count_type start_c, count_type size) { selection.insert(0, get_line(r).substr(start_c, size)); }
);
}
// Pasting selection
void paste_selection(position p = cur + file_offset) {
if(selection.size() == 0) return;
@ -409,6 +423,11 @@ int main(int argc, char* argv[]) {
copy_selection(cur + file_offset);
mode = NORMAL;
break;
case 'x':
remove_selection(cur + file_offset);
print_file();
mode = NORMAL;
break;
default:
mode = NORMAL;
break;