fix(editor): preserve selection after executing 'Organize imports' action (fixes #1598)

This commit is contained in:
Akash Yadav
2024-01-22 23:08:19 +05:30
parent 94449ada46
commit 1eabe1c32b
3 changed files with 43 additions and 0 deletions
@@ -23,6 +23,7 @@ import androidx.annotation.Nullable;
import com.itsaky.androidide.models.Position;
import com.itsaky.androidide.models.Range;
import io.github.rosemoe.sora.text.CharPosition;
import java.io.File;
/**
@@ -66,6 +67,29 @@ public interface IEditor {
}
void setSelection(@NonNull Position start, @NonNull Position end);
/**
* Set selection around the given position.
* @param position The position to set selection around.
*/
default void setSelectionAround(CharPosition position) {
setSelectionAround(position.getLine(), position.getColumn());
}
/**
* Set selection around the given position.
* @param position The position to set selection around.
*/
default void setSelectionAround(Position position) {
setSelectionAround(position.getLine(), position.getColumn());
}
/**
* Set selection around the given position.
* @param line The line index.
* @param column The column index.
*/
void setSelectionAround(int line, int column);
/**
* Get the cursor's selection range in the form of {@link Range}.
@@ -53,6 +53,17 @@ class EditorFeatures(
}
}
override fun setSelectionAround(line: Int, column: Int) {
withEditor {
if (line < lineCount) {
val columnCount = text.getColumnCount(line)
setSelection(line, if (column > columnCount) columnCount else column)
} else {
setSelection(lineCount - 1, text.getColumnCount(lineCount - 1))
}
}
}
override fun getCursorLSPRange(): Range = withEditor {
val end = cursor.right().let {
Position(line = it.line, column = it.column, index = it.index)
@@ -6,6 +6,7 @@ import com.itsaky.androidide.actions.ActionData
import com.itsaky.androidide.actions.hasRequiredData
import com.itsaky.androidide.actions.markInvisible
import com.itsaky.androidide.actions.requireEditor
import com.itsaky.androidide.editor.api.IEditor
import com.itsaky.androidide.lsp.java.JavaLanguageServer
import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction
import com.itsaky.androidide.lsp.java.models.JavaServerSettings
@@ -56,10 +57,17 @@ class OrganizeImportsAction : BaseJavaCodeAction() {
if (result is String) {
if (result.isNotEmpty()) {
val editor = data.requireEditor()
val cursor = editor.cursor.left()
editor.text.apply {
val endLine = getLine(lineCount - 1)
replace(0, 0, lineCount - 1, endLine.length + endLine.lineSeparator.length, result)
}
(editor as? IEditor?)?.also {
it.setSelectionAround(cursor)
editor.ensureSelectionVisible()
}
}
}
}