Skip to content

Commit 9902bc6

Browse files
committed
Fix bug #83
(cherry picked from commit 79b22d7)
1 parent 52e765e commit 9902bc6

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/main/kotlin/wu/seal/jsontokotlin/ImportClassWriter.kt

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,19 @@ object ImportClassWriter : IImportClassWriter {
7878

7979
if (importClassLineString !in text) {
8080

81-
val packageIndex = text.indexOf("package ")
82-
val importIndex = Math.max(text.lastIndexOf("import"), packageIndex)
81+
val packageIndex = try {
82+
"^[\\s]*package".toRegex(RegexOption.MULTILINE).find(text)!!.range.endInclusive
83+
} catch (e: Exception) {
84+
-1
85+
}
86+
val lastImportKeywordIndex = try {
87+
"^[\\s]*import".toRegex(RegexOption.MULTILINE).findAll(text).last().range.endInclusive
88+
} catch (e: Exception) {
89+
-1
90+
}
91+
val index = Math.max(lastImportKeywordIndex, packageIndex)
8392
val insertIndex =
84-
if (importIndex == -1) 0 else editFile.getLineEndOffset(editFile.getLineNumber(importIndex))
85-
93+
if (index == -1) 0 else editFile.getLineEndOffset(editFile.getLineNumber(index))
8694

8795
executeCouldRollBackAction(project) {
8896
editFile.insertString(insertIndex, "\n" + importClassLineString + "\n")

src/main/kotlin/wu/seal/jsontokotlin/MakeKotlinClassAction.kt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import wu.seal.jsontokotlin.feedback.sendActionInfo
1616
import wu.seal.jsontokotlin.ui.JsonInputDialog
1717
import wu.seal.jsontokotlin.utils.ClassCodeFilter
1818
import wu.seal.jsontokotlin.utils.executeCouldRollBackAction
19+
import java.awt.SystemColor.text
1920
import java.net.URL
2021
import java.util.*
2122

@@ -144,6 +145,23 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") {
144145
if (offset == 0) {
145146
offset = document.textLength
146147
}
148+
val lastPackageKeywordLineEndIndex = try {
149+
"^[\\s]*package.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.endInclusive
150+
} catch (e: Exception) {
151+
-1
152+
}
153+
val lastImportKeywordLineEndIndex = try {
154+
"^[\\s]*import.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.endInclusive
155+
} catch (e: Exception) {
156+
-1
157+
}
158+
if (offset < lastPackageKeywordLineEndIndex) {
159+
offset = lastPackageKeywordLineEndIndex + 1
160+
}
161+
if (offset < lastImportKeywordLineEndIndex) {
162+
offset = lastImportKeywordLineEndIndex + 1
163+
}
164+
147165
} else {
148166
offset = document.textLength
149167
}

0 commit comments

Comments
 (0)