1+ /*
2+ * Copyright (c) 2017. tangzx(love.tangzx@qq.com)
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
18+
19+ import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate
20+ import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter
21+ import com.intellij.openapi.actionSystem.DataContext
22+ import com.intellij.openapi.editor.Editor
23+ import com.intellij.openapi.editor.actionSystem.EditorActionHandler
24+ import com.intellij.openapi.util.Ref
25+ import com.intellij.psi.PsiDocumentManager
26+ import com.intellij.psi.PsiFile
27+ import com.intellij.psi.codeStyle.CodeStyleManager
28+ import com.intellij.util.IncorrectOperationException
29+ import com.intellij.util.text.CharArrayUtil
30+ import com.tang.intellij.lua.lang.LuaLanguage
31+ import com.tang.intellij.lua.psi.LuaBlock
32+ import com.tang.intellij.lua.psi.LuaIndentRange
33+
34+ class LuaEnterBetweenRangeBlockHandler : EnterHandlerDelegateAdapter () {
35+
36+ override fun preprocessEnter (psiFile : PsiFile ,
37+ editor : Editor ,
38+ caretOffsetRef : Ref <Int >,
39+ caretAdvance : Ref <Int >,
40+ dataContext : DataContext ,
41+ originalHandler : EditorActionHandler ? ): EnterHandlerDelegate .Result {
42+ if (! psiFile.language.`is `(LuaLanguage .INSTANCE )) {
43+ return EnterHandlerDelegate .Result .Continue
44+ }
45+
46+ val caretOffset = caretOffsetRef.get()
47+ val document = editor.document
48+ val text = document.charsSequence
49+ val prevCharOffset = CharArrayUtil .shiftBackward(text, caretOffset - 1 , " \t " )
50+ val nextCharOffset = CharArrayUtil .shiftForward(text, caretOffset, " \t " )
51+
52+ val prev = psiFile.findElementAt(prevCharOffset)
53+ val next = psiFile.findElementAt(nextCharOffset)
54+ if (prev != next &&
55+ prev != null &&
56+ next != null &&
57+ prev.parent == next.parent &&
58+ prev.parent is LuaIndentRange &&
59+ prev.nextSibling is LuaBlock ) {
60+ originalHandler?.execute(editor, editor.caretModel.currentCaret, dataContext)
61+ PsiDocumentManager .getInstance(psiFile.project).commitDocument(editor.document)
62+ try {
63+ CodeStyleManager .getInstance(psiFile.project).adjustLineIndent(psiFile, editor.caretModel.offset)
64+ } catch (e: IncorrectOperationException ) {
65+ }
66+
67+ return EnterHandlerDelegate .Result .DefaultForceIndent
68+ }
69+ return EnterHandlerDelegate .Result .Continue
70+ }
71+ }
0 commit comments