Skip to content

Commit 9904e25

Browse files
committed
test pre format processor
1 parent 24f635e commit 9904e25

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* Copyright (c) 2017. tangzx([email protected])
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.tang.intellij.lua.editor.formatter
18+
19+
import com.intellij.lang.ASTNode
20+
import com.intellij.openapi.util.TextRange
21+
import com.intellij.psi.PsiDocumentManager
22+
import com.intellij.psi.PsiElement
23+
import com.intellij.psi.impl.source.codeStyle.PreFormatProcessor
24+
import com.intellij.util.DocumentUtil
25+
import com.tang.intellij.lua.psi.LuaFile
26+
import com.tang.intellij.lua.psi.LuaTypes
27+
import com.tang.intellij.lua.psi.LuaVisitor
28+
29+
/**
30+
* 移除不用的 ;,
31+
* Created by tangzx on 2017/7/8.
32+
*/
33+
class LuaPreFormatProcessor : PreFormatProcessor {
34+
override fun process(astNode: ASTNode, sourceRange: TextRange): TextRange {
35+
var range = sourceRange
36+
val psi = astNode.psi
37+
if (psi.containingFile is LuaFile) {
38+
val list = mutableListOf<Pair<Int, Boolean>>()
39+
psi.accept(object : LuaVisitor() {
40+
override fun visitElement(o: PsiElement) {
41+
if (o.node.elementType == LuaTypes.SEMI) {
42+
val nextSibling = o.nextSibling
43+
var replaceWithSpace = false
44+
if (nextSibling != null) {
45+
if (nextSibling.node.startOffset == o.node.startOffset + 1) {
46+
replaceWithSpace = true
47+
}
48+
}
49+
list.add(Pair(o.node.startOffset, replaceWithSpace))
50+
} else o.acceptChildren(this)
51+
}
52+
})
53+
54+
val psiDocumentManager = PsiDocumentManager.getInstance(psi.project)
55+
val document = psiDocumentManager.getDocument(psi.containingFile)
56+
document ?: return range
57+
DocumentUtil.executeInBulk(document, true) {
58+
psiDocumentManager.doPostponedOperationsAndUnblockDocument(document)
59+
60+
var removed = 0
61+
list.forEach {
62+
if (it.second) {
63+
document.replaceString(it.first, it.first + 1, " ")
64+
} else {
65+
document.deleteString(it.first, it.first + 1)
66+
removed++
67+
}
68+
}
69+
70+
psiDocumentManager.commitDocument(document)
71+
72+
range = TextRange(sourceRange.startOffset, sourceRange.length - removed)
73+
}
74+
75+
}
76+
return range
77+
}
78+
}

0 commit comments

Comments
 (0)