Skip to content

Instantly share code, notes, and snippets.

@hamoid
Created April 9, 2022 16:03
Show Gist options
  • Save hamoid/ed0fda8518ec231205378003120a7e96 to your computer and use it in GitHub Desktop.
Save hamoid/ed0fda8518ec231205378003120a7e96 to your computer and use it in GitHub Desktop.
An example Kotlin script to process source code inside IntelliJ Idea
import java.io.File
// Process your selection inside IntelliJ Idea using a Kotlin script.
//
// 1. Install https://plugins.jetbrains.com/plugin/15539-external-tools-text-replace
// 2. Settings > Tools > External Tools > Create a new tool
// Set these values according to your system:
//
// Name: ?
// Description: ?
// Program: /snap/intellij-idea-community/352/plugins/Kotlin/kotlinc/bin/kotlinc
// Working directory: /snap/intellij-idea-community/352/plugins/Kotlin/kotlinc/bin
// Arguments: -script /path/to/your/script/myScript.kts -- $FilePath$ $SelectionStartLine$ $SelectionStartColumn$ $SelectionEndLine$ $SelectionEndColumn$
//
// 3. Save this file as myScript.kts and set the absolute path in Arguments above
// 4. Select some text
// 5. Right click, choose External Tools Replace, choose the Tool you created
// 6. Enjoy your upper case text XD
// Why? Sometimes you need to do complex processing of code in which macros
// are not enough: you want to extract values with regex, move lines around,
// reformat, delete... With this approach you use your Kotlin abilities to
// alter your code.
val fileLines = File(args[0]).readLines()
val (startLine, startCol, endLine, endCol) = args.slice(1..4).map { it.toInt() - 1 }
val selLines = fileLines.slice(startLine..endLine) .toMutableList()
// remove end
selLines[selLines.lastIndex] = selLines[selLines.lastIndex].substring(0, endCol)
// remove beginning
selLines[0] = selLines[0].substring(startCol)
// TODO: `selLines` contains the selection as a MutableList<String>.
// Process that list in any way you need, then print it at the end.
val result = selLines.joinToString("\n").uppercase()
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment