1616package org.domaframework.doma.intellij.formatter.processor
1717
1818import com.intellij.application.options.CodeStyle
19+ import com.intellij.ide.highlighter.JavaFileType
1920import com.intellij.lang.injection.InjectedLanguageManager
2021import com.intellij.openapi.command.WriteCommandAction
2122import com.intellij.openapi.editor.Document
@@ -27,6 +28,7 @@ import com.intellij.psi.PsiFile
2728import com.intellij.psi.PsiFileFactory
2829import com.intellij.psi.PsiLiteralExpression
2930import com.intellij.psi.codeStyle.CodeStyleManager
31+ import com.intellij.psi.util.PsiTreeUtil
3032import org.domaframework.doma.intellij.common.util.StringUtil
3133import org.domaframework.doma.intellij.formatter.visitor.FormattingTask
3234
@@ -41,13 +43,13 @@ class InjectionSqlFormatter(
4143 private val COMMENT_START_REGEX = Regex (" ^[ \t ]*/[*][ \t ]*\\ *" )
4244 }
4345
44- private val baseIndent = createSpaceIndent(project)
46+ private var baseIndent = createSpaceIndent(project)
4547
4648 private fun createSpaceIndent (project : Project ): String {
4749 val settings = CodeStyle .getSettings(project)
48- val java = settings.indentOptions
50+ val java = settings.getIndentOptions( JavaFileType . INSTANCE )
4951 val indentSize = java.INDENT_SIZE
50- val prefixLen = " @Sql(\"\"\" " .length
52+ val prefixLen = " @Sql(${ TRIPLE_QUOTE } " .length
5153 return StringUtil .SINGLE_SPACE .repeat(indentSize.plus(prefixLen))
5254 }
5355
@@ -165,12 +167,44 @@ class InjectionSqlFormatter(
165167
166168 // Create properly aligned literal text
167169 val literalText = createFormattedLiteralText(processedSql)
170+ updateBaseIndent(task)
171+
168172 val normalizedText = normalizeIndentation(literalText)
169173
170174 val newLiteral = elementFactory.createExpressionFromText(normalizedText, task.expression)
171175 return newLiteral.text
172176 }
173177
178+ /* *
179+ * When formatting styles other than Java code style change the indentation of a text block,
180+ * reset the base indent using the number of spaces before the PsiLiteralExpression.
181+ */
182+ private fun updateBaseIndent (task : FormattingTask ) {
183+ val input = PsiTreeUtil .prevLeaf(task.expression)?.text
184+ val prevTexts = countCharsToLineBreak(task.expression).plus(TRIPLE_QUOTE .length)
185+ if (input != null ) {
186+ val matches = StringUtil .SINGLE_SPACE .repeat(prevTexts)
187+ baseIndent = matches
188+ }
189+ }
190+
191+ private fun countCharsToLineBreak (expression : PsiLiteralExpression ): Int {
192+ var count = 0
193+ var leaf = PsiTreeUtil .prevLeaf(expression)
194+ while (leaf != null ) {
195+ val text = leaf.text
196+ for (i in text.length - 1 downTo 0 ) {
197+ val c = text[i]
198+ if (c == ' \n ' || c == ' \r ' ) {
199+ return count
200+ }
201+ count++
202+ }
203+ leaf = PsiTreeUtil .prevLeaf(leaf)
204+ }
205+ return count
206+ }
207+
174208 /* *
175209 * Creates a Java text block (triple-quoted string) from formatted SQL.
176210 */
0 commit comments