### Godot version

v4.0.beta.custom_build [13f0158]

### System information

Windows 10

### Issue description

When doing operations (`begin_complex_operation` and `end_complex_operation`) with multiple selections in TextEdit, some of these selections don't revert upon undo. This behavior is affects some of script editor's operations, like duplicate selection and delete lines.

### Steps to reproduce

Open script editor, make multiple selections. Keep in mind what you have selected. Do duplicate selection (ctrl+shift+D). Undo (ctrl+Z). Compare the result to what you remember.

### Minimal reproduction project

N/A
delete_selection(p_caret);
		cut_copy_line = "";
		return;
	}
	begin_complex_operation();
	Vector<int> carets_to_remove;
	StringBuilder clipboard;
	
	Vector<int> caret_edit_order = get_caret_index_edit_order();
	for (int i = caret_edit_order.size() - 1; i >= 0; i--) {
		int caret_idx = caret_edit_order[i];
		if (p_caret != -1 && p_caret != caret_idx) {
			continue;
		}
		int cl = get_caret_line(caret_idx);
		int cc = get_caret_column(caret_idx);
		int indent_level = get_indent_level(cl);
		double hscroll = get_h_scroll();
		
		
		for (int j = i - 1; j >= 0; j--) {
			if (get_caret_line(caret_edit_order[j]) == cl) {
				carets_to_remove.push_back(caret_edit_order[j]);
				i = j;
			}
		}
		clipboard += text[cl];
		if (p_caret == -1 && caret_idx != 0) {
			clipboard += "\n";
		}