Skip to content

Commit 1a3f085

Browse files
committed
Trim leading whitespace at the beginning of SQL files for improved formatting
1 parent cca6dc5 commit 1a3f085

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed

src/main/kotlin/org/domaframework/doma/intellij/formatter/processor/SqlFormatPreProcessor.kt

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,41 @@ class SqlFormatPreProcessor : PreFormatProcessor {
116116
}
117117
}
118118

119+
trimLeadingWhitespaceAtFileHead(document, source, rangeToReformat)
119120
docManager.commitDocument(document)
120121

121122
return ProcessResult(document, rangeToReformat.grown(visitor.replaces.size))
122123
}
123124

125+
private fun trimLeadingWhitespaceAtFileHead(
126+
document: Document,
127+
source: PsiFile,
128+
rangeToReformat: TextRange,
129+
) {
130+
if (rangeToReformat.startOffset != 0) return
131+
if (isInjectedSqlFile(source)) return
132+
133+
val chars = document.charsSequence
134+
if (chars.isEmpty()) return
135+
136+
var start = 0
137+
// Save Bom
138+
if (chars[0] == '\uFEFF') start = 1
139+
140+
var i = start
141+
while (i < chars.length) {
142+
val c = chars[i]
143+
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
144+
i++
145+
} else {
146+
break
147+
}
148+
}
149+
if (i > start) {
150+
document.deleteString(start, i)
151+
}
152+
}
153+
124154
private fun processNonWhiteSpaceElement(
125155
current: PsiElement,
126156
document: Document,
@@ -145,7 +175,7 @@ class SqlFormatPreProcessor : PreFormatProcessor {
145175
else -> getUpperText(current)
146176
}
147177

148-
return if (isFirstElementInFile(current)) getUpperText(current) else newKeyword
178+
return newKeyword
149179
}
150180

151181
private fun processKeyword(current: PsiElement): String {
@@ -164,11 +194,6 @@ class SqlFormatPreProcessor : PreFormatProcessor {
164194
getNewLineString(PsiTreeUtil.prevLeaf(current), getUpperText(current))
165195
}
166196

167-
private fun isFirstElementInFile(current: PsiElement): Boolean {
168-
val prev = PsiTreeUtil.prevLeaf(current)
169-
return prev == null || PsiTreeUtil.prevLeaf(prev) == null
170-
}
171-
172197
private fun removeSpacesAroundNewline(
173198
document: Document,
174199
element: PsiWhiteSpace,

0 commit comments

Comments
 (0)