diff --git a/src/main/kotlin/wu/seal/jsontokotlin/ImportClassWriter.kt b/src/main/kotlin/wu/seal/jsontokotlin/ImportClassWriter.kt index f214a705..6538bdff 100644 --- a/src/main/kotlin/wu/seal/jsontokotlin/ImportClassWriter.kt +++ b/src/main/kotlin/wu/seal/jsontokotlin/ImportClassWriter.kt @@ -78,11 +78,19 @@ object ImportClassWriter : IImportClassWriter { if (importClassLineString !in text) { - val packageIndex = text.indexOf("package ") - val importIndex = Math.max(text.lastIndexOf("import"), packageIndex) + val packageIndex = try { + "^[\\s]*package\\s.+\n$".toRegex(RegexOption.MULTILINE).find(text)!!.range.endInclusive + } catch (e: Exception) { + -1 + } + val lastImportKeywordIndex = try { + "^[\\s]*import\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(text).last().range.endInclusive + } catch (e: Exception) { + -1 + } + val index = Math.max(lastImportKeywordIndex, packageIndex) val insertIndex = - if (importIndex == -1) 0 else editFile.getLineEndOffset(editFile.getLineNumber(importIndex)) - + if (index == -1) 0 else editFile.getLineEndOffset(editFile.getLineNumber(index)) executeCouldRollBackAction(project) { editFile.insertString(insertIndex, "\n" + importClassLineString + "\n") diff --git a/src/main/kotlin/wu/seal/jsontokotlin/MakeKotlinClassAction.kt b/src/main/kotlin/wu/seal/jsontokotlin/MakeKotlinClassAction.kt index 8eb3846f..f74598fa 100644 --- a/src/main/kotlin/wu/seal/jsontokotlin/MakeKotlinClassAction.kt +++ b/src/main/kotlin/wu/seal/jsontokotlin/MakeKotlinClassAction.kt @@ -144,6 +144,23 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") { if (offset == 0) { offset = document.textLength } + val lastPackageKeywordLineEndIndex = try { + "^[\\s]*package\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.endInclusive + } catch (e: Exception) { + -1 + } + val lastImportKeywordLineEndIndex = try { + "^[\\s]*import\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.endInclusive + } catch (e: Exception) { + -1 + } + if (offset < lastPackageKeywordLineEndIndex) { + offset = lastPackageKeywordLineEndIndex + 1 + } + if (offset < lastImportKeywordLineEndIndex) { + offset = lastImportKeywordLineEndIndex + 1 + } + } else { offset = document.textLength }