@@ -28,6 +28,7 @@ import com.intellij.psi.PsiFile
2828import com.intellij.psi.PsiFileFactory
2929import com.intellij.psi.PsiLiteralExpression
3030import com.intellij.psi.codeStyle.CodeStyleManager
31+ import com.intellij.psi.util.PsiTreeUtil
3132import org.domaframework.doma.intellij.common.util.StringUtil
3233import org.domaframework.doma.intellij.formatter.visitor.FormattingTask
3334
@@ -42,13 +43,13 @@ class InjectionSqlFormatter(
4243 private val COMMENT_START_REGEX = Regex (" ^[ \t ]*/[*][ \t ]*\\ *" )
4344 }
4445
45- private val baseIndent = createSpaceIndent(project)
46+ private var baseIndent = createSpaceIndent(project)
4647
4748 private fun createSpaceIndent (project : Project ): String {
4849 val settings = CodeStyle .getSettings(project)
4950 val java = settings.getIndentOptions(JavaFileType .INSTANCE )
5051 val indentSize = java.INDENT_SIZE
51- val prefixLen = " @Sql(\"\"\" " .length
52+ val prefixLen = " @Sql(${ TRIPLE_QUOTE } " .length
5253 return StringUtil .SINGLE_SPACE .repeat(indentSize.plus(prefixLen))
5354 }
5455
@@ -166,12 +167,44 @@ class InjectionSqlFormatter(
166167
167168 // Create properly aligned literal text
168169 val literalText = createFormattedLiteralText(processedSql)
170+ updateBaseIndent(task)
171+
169172 val normalizedText = normalizeIndentation(literalText)
170173
171174 val newLiteral = elementFactory.createExpressionFromText(normalizedText, task.expression)
172175 return newLiteral.text
173176 }
174177
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+
175208 /* *
176209 * Creates a Java text block (triple-quoted string) from formatted SQL.
177210 */
0 commit comments