2 * Copyright 2000-2016 JetBrains s.r.o.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package com.jetbrains.python.codeInsight.postfix;
18 import com.intellij.codeInsight.template.postfix.templates.SurroundPostfixTemplateBase;
19 import com.intellij.lang.surroundWith.Surrounder;
20 import com.intellij.openapi.editor.Editor;
21 import com.intellij.openapi.project.Project;
22 import com.intellij.openapi.util.TextRange;
23 import com.intellij.psi.PsiDocumentManager;
24 import com.intellij.psi.codeStyle.CodeStyleManager;
25 import com.intellij.util.IncorrectOperationException;
26 import com.jetbrains.python.psi.*;
27 import com.jetbrains.python.refactoring.surround.surrounders.expressions.PyExpressionSurrounder;
28 import org.jetbrains.annotations.NotNull;
30 public class PyIfPostfixTemplate extends SurroundPostfixTemplateBase {
32 public static final String TEMPLATE_DESCRIPTION = "if expr";
34 public PyIfPostfixTemplate() {
35 super("if", TEMPLATE_DESCRIPTION, PyPostfixUtils.PY_PSI_INFO, PyPostfixUtils.selectorTopmost());
40 protected Surrounder getSurrounder() {
41 return new PyIfSurrounder();
44 private static class PyIfSurrounder extends PyExpressionSurrounder {
46 public boolean isApplicable(@NotNull PyExpression expr) {
51 public TextRange surroundExpression(@NotNull Project project, @NotNull Editor editor, @NotNull PyExpression expression)
52 throws IncorrectOperationException {
53 String text = "if a:\n pass";
54 PyIfStatement ifStatement = PyElementGenerator.getInstance(project).
55 createFromText(LanguageLevel.getDefault(), PyIfStatement.class, text);
56 final PyExpression condition = ifStatement.getIfPart().getCondition();
57 if (condition != null) {
58 condition.replace(expression);
60 ifStatement = (PyIfStatement)CodeStyleManager.getInstance(project).reformat(ifStatement);
61 ifStatement = (PyIfStatement)expression.getParent().replace(ifStatement);
62 PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
63 PyStatementList statementList = ifStatement.getIfPart().getStatementList();
64 PyStatement[] statements = statementList.getStatements();
65 final TextRange range = statements[0].getTextRange();
66 editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
67 return TextRange.from(range.getStartOffset(), 0);
71 public String getTemplateDescription() {
72 return TEMPLATE_DESCRIPTION;