Last active
June 23, 2024 09:12
-
-
Save dkandalov/fc8638d21d4ba8b48aec5b25f565c726 to your computer and use it in GitHub Desktop.
Mini-plugin for paragraph navigation in IntelliJ IDEs (to be use with https://github.com/dkandalov/live-plugin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.intellij.openapi.command.executeCommand | |
import com.intellij.openapi.editor.Editor | |
import com.intellij.openapi.editor.EditorModificationUtil | |
import com.intellij.openapi.editor.LogicalPosition | |
import com.intellij.openapi.editor.ScrollType.CENTER_DOWN | |
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory | |
import liveplugin.editor | |
import liveplugin.registerAction | |
registerAction("Previous Paragraph", "alt shift COMMA") { event -> | |
event.editor?.moveToLine { lineIndex, lines -> | |
val i = (lineIndex - 1).downTo(0) | |
.dropWhile { lines[it].isBlank() } | |
.dropWhile { lines[it].isNotBlank() } | |
.firstOrNull() ?: 0 | |
if (lines[i].isBlank() && i + 1 in lines.indices && lines[i + 1].isNotBlank()) i + 1 else i | |
} | |
} | |
registerAction("Next Paragraph", "alt shift PERIOD") { event -> | |
event.editor?.moveToLine { lineIndex, lines -> | |
(lineIndex..lines.lastIndex) | |
.dropWhile { lines[it].isNotBlank() } | |
.dropWhile { lines[it].isBlank() } | |
.firstOrNull() ?: lines.lastIndex | |
} | |
} | |
fun Editor.moveToLine(findLine: (Int, List<String>) -> Int) { | |
executeCommand { | |
val lines = document.text.lines() | |
val lineIndex = findLine(caretModel.logicalPosition.line, lines) | |
val columnIndex = lines[lineIndex] | |
.indexOfFirst { !it.isWhitespace() } | |
.let { if (it == -1) 0 else it } | |
caretModel.moveToLogicalPosition(LogicalPosition(lineIndex, columnIndex)) | |
caretModel.removeSecondaryCarets() | |
caretModel.currentCaret.removeSelection() | |
scrollingModel.scrollToCaret(CENTER_DOWN) | |
EditorModificationUtil.scrollToCaret(this) | |
IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment