Tidy up code samples and wrap at 80 chars #IJSDK-24

This commit is contained in:
Breandan Considine 2016-03-21 16:08:47 -04:00
parent 8aaf13b046
commit f416f02ce2
127 changed files with 2659 additions and 2528 deletions

View File

@ -3,9 +3,9 @@
<description>Inspection for (probably) inappropriate use of equality relation operation.</description> <description>Inspection for (probably) inappropriate use of equality relation operation.</description>
<version>1.0</version> <version>1.0</version>
<vendor>JetBrains</vendor> <vendor>JetBrains</vendor>
<!-- <!--
<idea-version since-build="3000"/> <idea-version since-build="3000"/>
--> -->
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<inspectionToolProvider implementation="com.intellij.codeInspection.ComparingReferencesProvider"/> <inspectionToolProvider implementation="com.intellij.codeInspection.ComparingReferencesProvider"/>

View File

@ -3,7 +3,6 @@ package com.intellij.codeInspection;
import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*; import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IElementType;
import com.intellij.ui.DocumentAdapter; import com.intellij.ui.DocumentAdapter;
@ -14,8 +13,6 @@ import org.jetbrains.annotations.NotNull;
import javax.swing.*; import javax.swing.*;
import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentEvent;
import java.awt.*; import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer; import java.util.StringTokenizer;
/** /**
@ -26,13 +23,17 @@ public class ComparingReferencesInspection extends BaseJavaLocalInspectionTool {
private final LocalQuickFix myQuickFix = new MyQuickFix(); private final LocalQuickFix myQuickFix = new MyQuickFix();
@SuppressWarnings({"WeakerAccess"}) @NonNls public String CHECKED_CLASSES = "java.lang.String;java.util.Date"; @SuppressWarnings({"WeakerAccess"})
@NonNls private static final String DESCRIPTION_TEMPLATE = InspectionsBundle.message("inspection.comparing.references.problem.descriptor"); @NonNls
public String CHECKED_CLASSES = "java.lang.String;java.util.Date";
@NonNls
private static final String DESCRIPTION_TEMPLATE =
InspectionsBundle.message("inspection.comparing.references.problem.descriptor");
@NotNull @NotNull
public String getDisplayName() { public String getDisplayName() {
return "'==' or '!=' instead of 'equals()'"; return "'==' or '!=' instead of 'equals()'";
} }
@NotNull @NotNull
@ -57,32 +58,33 @@ public class ComparingReferencesInspection extends BaseJavaLocalInspectionTool {
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() { return new JavaElementVisitor() {
@Override @Override
public void visitReferenceExpression(PsiReferenceExpression psiReferenceExpression) { public void visitReferenceExpression(PsiReferenceExpression psiReferenceExpression) {
} }
@Override public void visitBinaryExpression(PsiBinaryExpression expression) { @Override
super.visitBinaryExpression(expression); public void visitBinaryExpression(PsiBinaryExpression expression) {
super.visitBinaryExpression(expression);
IElementType opSign = expression.getOperationTokenType(); IElementType opSign = expression.getOperationTokenType();
if (opSign == JavaTokenType.EQEQ || opSign == JavaTokenType.NE) { if (opSign == JavaTokenType.EQEQ || opSign == JavaTokenType.NE) {
PsiExpression lOperand = expression.getLOperand(); PsiExpression lOperand = expression.getLOperand();
PsiExpression rOperand = expression.getROperand(); PsiExpression rOperand = expression.getROperand();
if (rOperand == null || isNullLiteral(lOperand) || isNullLiteral(rOperand)) return; if (rOperand == null || isNullLiteral(lOperand) || isNullLiteral(rOperand)) return;
PsiType lType = lOperand.getType(); PsiType lType = lOperand.getType();
PsiType rType = rOperand.getType(); PsiType rType = rOperand.getType();
if (isCheckedType(lType) || isCheckedType(rType)) { if (isCheckedType(lType) || isCheckedType(rType)) {
holder.registerProblem(expression, holder.registerProblem(expression,
DESCRIPTION_TEMPLATE, myQuickFix); DESCRIPTION_TEMPLATE, myQuickFix);
}
} }
}
} }
}; };
} }
@ -94,14 +96,14 @@ public class ComparingReferencesInspection extends BaseJavaLocalInspectionTool {
private static class MyQuickFix implements LocalQuickFix { private static class MyQuickFix implements LocalQuickFix {
@NotNull @NotNull
public String getName() { public String getName() {
// The test (see the TestThisPlugin class) uses this string to identify the quick fix action. // The test (see the TestThisPlugin class) uses this string to identify the quick fix action.
return InspectionsBundle.message("inspection.comparing.references.use.quickfix"); return InspectionsBundle.message("inspection.comparing.references.use.quickfix");
} }
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
try { try {
PsiBinaryExpression binaryExpression = (PsiBinaryExpression)descriptor.getPsiElement(); PsiBinaryExpression binaryExpression = (PsiBinaryExpression) descriptor.getPsiElement();
IElementType opSign = binaryExpression.getOperationTokenType(); IElementType opSign = binaryExpression.getOperationTokenType();
PsiExpression lExpr = binaryExpression.getLOperand(); PsiExpression lExpr = binaryExpression.getLOperand();
PsiExpression rExpr = binaryExpression.getROperand(); PsiExpression rExpr = binaryExpression.getROperand();
@ -109,20 +111,20 @@ public class ComparingReferencesInspection extends BaseJavaLocalInspectionTool {
return; return;
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
PsiMethodCallExpression equalsCall = (PsiMethodCallExpression)factory.createExpressionFromText("a.equals(b)", null); PsiMethodCallExpression equalsCall =
(PsiMethodCallExpression) factory.createExpressionFromText("a.equals(b)", null);
equalsCall.getMethodExpression().getQualifierExpression().replace(lExpr); equalsCall.getMethodExpression().getQualifierExpression().replace(lExpr);
equalsCall.getArgumentList().getExpressions()[0].replace(rExpr); equalsCall.getArgumentList().getExpressions()[0].replace(rExpr);
PsiExpression result = (PsiExpression)binaryExpression.replace(equalsCall); PsiExpression result = (PsiExpression) binaryExpression.replace(equalsCall);
if (opSign == JavaTokenType.NE) { if (opSign == JavaTokenType.NE) {
PsiPrefixExpression negation = (PsiPrefixExpression)factory.createExpressionFromText("!a", null); PsiPrefixExpression negation = (PsiPrefixExpression) factory.createExpressionFromText("!a", null);
negation.getOperand().replace(result); negation.getOperand().replace(result);
result.replace(negation); result.replace(negation);
} }
} } catch (IncorrectOperationException e) {
catch (IncorrectOperationException e) {
LOG.error(e); LOG.error(e);
} }
} }

View File

@ -5,6 +5,6 @@ package com.intellij.codeInspection;
*/ */
public class ComparingReferencesProvider implements InspectionToolProvider { public class ComparingReferencesProvider implements InspectionToolProvider {
public Class[] getInspectionClasses() { public Class[] getInspectionClasses() {
return new Class[] { ComparingReferencesInspection.class}; return new Class[]{ComparingReferencesInspection.class};
} }
} }

View File

@ -17,51 +17,52 @@ import java.util.List;
*/ */
public class TestThisPlugin extends UsefulTestCase { public class TestThisPlugin extends UsefulTestCase {
protected CodeInsightTestFixture myFixture; protected CodeInsightTestFixture myFixture;
// Specify path to your test data directory // Specify path to your test data directory
// e.g. final String dataPath = "c:\\users\\john.doe\\idea\\community\\samples\\ComparingReferences/testData"; // e.g. final String dataPath = "c:\\users\\john.doe\\idea\\community\\samples\\ComparingReferences/testData";
final String dataPath = "c:\\users\\John.Doe\\idea\\community\\samples\\comparingReferences/testData"; final String dataPath = "c:\\users\\John.Doe\\idea\\community\\samples\\comparingReferences/testData";
public void setUp() throws Exception { public void setUp() throws Exception {
final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = fixtureFactory.createFixtureBuilder(getName()); final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder =
myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(testFixtureBuilder.getFixture()); fixtureFactory.createFixtureBuilder(getName());
myFixture.setTestDataPath(dataPath); myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(testFixtureBuilder.getFixture());
final JavaModuleFixtureBuilder builder = testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class); myFixture.setTestDataPath(dataPath);
final JavaModuleFixtureBuilder builder = testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class);
builder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot(""); builder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot("");
builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15); builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15);
myFixture.setUp(); myFixture.setUp();
} }
public void tearDown() throws Exception { public void tearDown() throws Exception {
myFixture.tearDown(); myFixture.tearDown();
myFixture = null; myFixture = null;
} }
protected void doTest(String testName, String hint) throws Throwable { protected void doTest(String testName, String hint) throws Throwable {
myFixture.configureByFile(testName + ".java"); myFixture.configureByFile(testName + ".java");
myFixture.enableInspections(ComparingReferencesInspection.class); myFixture.enableInspections(ComparingReferencesInspection.class);
List<HighlightInfo> highlightInfos = myFixture.doHighlighting(); List<HighlightInfo> highlightInfos = myFixture.doHighlighting();
Assert.assertTrue(!highlightInfos.isEmpty()); Assert.assertTrue(!highlightInfos.isEmpty());
final IntentionAction action = myFixture.findSingleIntention(hint); final IntentionAction action = myFixture.findSingleIntention(hint);
Assert.assertNotNull(action); Assert.assertNotNull(action);
myFixture.launchAction(action); myFixture.launchAction(action);
myFixture.checkResultByFile(testName + ".after.java"); myFixture.checkResultByFile(testName + ".after.java");
} }
// Test the "==" case // Test the "==" case
public void test() throws Throwable { public void test() throws Throwable {
doTest("before", "Use equals()"); doTest("before", "Use equals()");
} }
// Test the "!=" case // Test the "!=" case
public void test1() throws Throwable { public void test1() throws Throwable {
doTest("before1", "Use equals()"); doTest("before1", "Use equals()");
} }
} }

View File

@ -1,27 +1,27 @@
<idea-plugin version="2"> <idea-plugin version="2">
<name>Conditional Operator Converter</name> <name>Conditional Operator Converter</name>
<id>ConditionalOperatorConverter</id> <id>ConditionalOperatorConverter</id>
<description>Intention action that suggests to convert a conditional operator into <description>Intention action that suggests to convert a conditional operator into
'if' block. 'if' block.
</description> </description>
<version>1.3</version> <version>1.3</version>
<vendor>JetBrains</vendor> <vendor>JetBrains</vendor>
<!-- <!--
<idea-version since-build="2000"/> <idea-version since-build="2000"/>
--> -->
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<intentionAction> <intentionAction>
<className>com.intellij.codeInsight.intention.ConditionalOperatorConvertor</className> <className>com.intellij.codeInsight.intention.ConditionalOperatorConvertor</className>
<category>Conditional Operator</category> <category>Conditional Operator</category>
<descriptionDirectoryName>ConditionalOperatorConvertor</descriptionDirectoryName> <descriptionDirectoryName>ConditionalOperatorConvertor</descriptionDirectoryName>
</intentionAction> </intentionAction>
</extensions> </extensions>
<project-components> <project-components>
<component> <component>
<implementation-class>com.intellij.codeInsight.intention.ConditionalOperatorConvertor</implementation-class> <implementation-class>com.intellij.codeInsight.intention.ConditionalOperatorConvertor</implementation-class>
</component> </component>
</project-components> </project-components>
</idea-plugin> </idea-plugin>

View File

@ -13,7 +13,8 @@ import org.jetbrains.annotations.Nullable;
/** /**
* @author dsl * @author dsl
*/ */
@NonNls public class ConditionalOperatorConvertor extends PsiElementBaseIntentionAction implements IntentionAction { @NonNls
public class ConditionalOperatorConvertor extends PsiElementBaseIntentionAction implements IntentionAction {
@NotNull @NotNull
public String getText() { public String getText() {
@ -30,10 +31,10 @@ import org.jetbrains.annotations.Nullable;
if (!element.isWritable()) return false; if (!element.isWritable()) return false;
if (element instanceof PsiJavaToken) { if (element instanceof PsiJavaToken) {
final PsiJavaToken token = (PsiJavaToken)element; final PsiJavaToken token = (PsiJavaToken) element;
if (token.getTokenType() != JavaTokenType.QUEST) return false; if (token.getTokenType() != JavaTokenType.QUEST) return false;
if (token.getParent() instanceof PsiConditionalExpression) { if (token.getParent() instanceof PsiConditionalExpression) {
final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)token.getParent(); final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression) token.getParent();
if (conditionalExpression.getThenExpression() == null if (conditionalExpression.getThenExpression() == null
|| conditionalExpression.getElseExpression() == null) { || conditionalExpression.getElseExpression() == null) {
return false; return false;
@ -63,12 +64,13 @@ import org.jetbrains.annotations.Nullable;
// Maintain declrations // Maintain declrations
if (originalStatement instanceof PsiDeclarationStatement) { if (originalStatement instanceof PsiDeclarationStatement) {
final PsiDeclarationStatement declaration = (PsiDeclarationStatement)originalStatement; final PsiDeclarationStatement declaration = (PsiDeclarationStatement) originalStatement;
final PsiElement[] declaredElements = declaration.getDeclaredElements(); final PsiElement[] declaredElements = declaration.getDeclaredElements();
PsiLocalVariable variable = null; PsiLocalVariable variable = null;
for (PsiElement declaredElement : declaredElements) { for (PsiElement declaredElement : declaredElements) {
if (declaredElement instanceof PsiLocalVariable && PsiTreeUtil.isAncestor(declaredElement, conditionalExpression, true)) { if (declaredElement instanceof PsiLocalVariable &&
variable = (PsiLocalVariable)declaredElement; PsiTreeUtil.isAncestor(declaredElement, conditionalExpression, true)) {
variable = (PsiLocalVariable) declaredElement;
break; break;
} }
} }
@ -77,31 +79,31 @@ import org.jetbrains.annotations.Nullable;
final Object marker = new Object(); final Object marker = new Object();
PsiTreeUtil.mark(conditionalExpression, marker); PsiTreeUtil.mark(conditionalExpression, marker);
PsiExpressionStatement statement = PsiExpressionStatement statement =
(PsiExpressionStatement)factory.createStatementFromText(variable.getName() + " = 0;", null); (PsiExpressionStatement) factory.createStatementFromText(variable.getName() + " = 0;", null);
statement = (PsiExpressionStatement)CodeStyleManager.getInstance(project).reformat(statement); statement = (PsiExpressionStatement) CodeStyleManager.getInstance(project).reformat(statement);
((PsiAssignmentExpression)statement.getExpression()).getRExpression().replace(variable.getInitializer()); ((PsiAssignmentExpression) statement.getExpression()).getRExpression().replace(variable.getInitializer());
variable.getInitializer().delete(); variable.getInitializer().delete();
final PsiElement variableParent = variable.getParent(); final PsiElement variableParent = variable.getParent();
originalStatement = variableParent.getParent().addAfter(statement, variableParent); originalStatement = variableParent.getParent().addAfter(statement, variableParent);
conditionalExpression = (PsiConditionalExpression)PsiTreeUtil.releaseMark(originalStatement, marker); conditionalExpression = (PsiConditionalExpression) PsiTreeUtil.releaseMark(originalStatement, marker);
} }
// create then and else branches // create then and else branches
final PsiElement[] originalElements = new PsiElement[]{originalStatement, conditionalExpression}; final PsiElement[] originalElements = new PsiElement[]{originalStatement, conditionalExpression};
final PsiExpression condition = (PsiExpression)conditionalExpression.getCondition().copy(); final PsiExpression condition = (PsiExpression) conditionalExpression.getCondition().copy();
final PsiElement[] thenElements = PsiTreeUtil.copyElements(originalElements); final PsiElement[] thenElements = PsiTreeUtil.copyElements(originalElements);
final PsiElement[] elseElements = PsiTreeUtil.copyElements(originalElements); final PsiElement[] elseElements = PsiTreeUtil.copyElements(originalElements);
thenElements[1].replace(conditionalExpression.getThenExpression()); thenElements[1].replace(conditionalExpression.getThenExpression());
elseElements[1].replace(conditionalExpression.getElseExpression()); elseElements[1].replace(conditionalExpression.getElseExpression());
PsiIfStatement statement = (PsiIfStatement)factory.createStatementFromText("if (true) { a = b } else { c = d }", PsiIfStatement statement = (PsiIfStatement) factory.createStatementFromText("if (true) { a = b } else { c = d }",
null); null);
statement = (PsiIfStatement)CodeStyleManager.getInstance(project).reformat(statement); statement = (PsiIfStatement) CodeStyleManager.getInstance(project).reformat(statement);
statement.getCondition().replace(condition); statement.getCondition().replace(condition);
statement = (PsiIfStatement)originalStatement.replace(statement); statement = (PsiIfStatement) originalStatement.replace(statement);
((PsiBlockStatement)statement.getThenBranch()).getCodeBlock().getStatements()[0].replace(thenElements[0]); ((PsiBlockStatement) statement.getThenBranch()).getCodeBlock().getStatements()[0].replace(thenElements[0]);
((PsiBlockStatement)statement.getElseBranch()).getCodeBlock().getStatements()[0].replace(elseElements[0]); ((PsiBlockStatement) statement.getElseBranch()).getCodeBlock().getStatements()[0].replace(elseElements[0]);
} }
public boolean startInWriteAction() { public boolean startInWriteAction() {

View File

@ -1,5 +1,5 @@
<html> <html>
<body> <body>
This intention converts a ternary operator to a corresponding if statement. <br> This intention converts a ternary operator to a corresponding if statement. <br>
</body> </body>
</html> </html>

View File

@ -1,11 +1,11 @@
public class X { public class X {
void f(boolean isMale) { void f(boolean isMale) {
String title; String title;
if (isMale) { if (isMale) {
title = "Mr."; title = "Mr.";
} else { } else {
title = "Ms."; title = "Ms.";
} }
System.out.println("title = " + title); System.out.println("title = " + title);
} }
} }

View File

@ -1,6 +1,6 @@
public class X { public class X {
void f(boolean isMale) { void f(boolean isMale) {
String title = isMale <caret>? "Mr." : "Ms."; String title = isMale < caret > ? "Mr." : "Ms.";
System.out.println("title = " + title); System.out.println("title = " + title);
} }
} }

View File

@ -1,7 +1,6 @@
package testPlugin; package testPlugin;
import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder; import com.intellij.testFramework.builders.JavaModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.*; import com.intellij.testFramework.fixtures.*;
import junit.framework.Assert; import junit.framework.Assert;
@ -18,45 +17,46 @@ import org.junit.Test;
*/ */
public class YourTest { public class YourTest {
protected CodeInsightTestFixture myFixture; protected CodeInsightTestFixture myFixture;
// Specify path to your test data // Specify path to your test data
// e.g. final String dataPath = "c:\\users\\john.doe\\idea\\community\\samples\\conditionalOperatorConvertor/testData"; // e.g. final String dataPath = "c:\\users\\john
final String dataPath = "c:\\users\\John.Doe\\idea\\community\\samples\\conditionalOperatorConvertor/testData"; // .doe\\idea\\community\\samples\\conditionalOperatorConvertor/testData";
final String dataPath = "c:\\users\\John.Doe\\idea\\community\\samples\\conditionalOperatorConvertor/testData";
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = fixtureFactory.createFixtureBuilder(); final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = fixtureFactory.createFixtureBuilder();
myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(testFixtureBuilder.getFixture()); myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(testFixtureBuilder.getFixture());
myFixture.setTestDataPath(dataPath); myFixture.setTestDataPath(dataPath);
final JavaModuleFixtureBuilder builder = testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class); final JavaModuleFixtureBuilder builder = testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class);
builder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot(""); builder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot("");
builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15); builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15);
myFixture.setUp(); myFixture.setUp();
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
myFixture.tearDown(); myFixture.tearDown();
myFixture = null; myFixture = null;
} }
protected void doTest(String testName, String hint) throws Throwable { protected void doTest(String testName, String hint) throws Throwable {
// Messages.showInfoMessage("Test started", "Info"); // Messages.showInfoMessage("Test started", "Info");
myFixture.configureByFile(testName + ".java"); myFixture.configureByFile(testName + ".java");
final IntentionAction action = myFixture.findSingleIntention(hint); final IntentionAction action = myFixture.findSingleIntention(hint);
Assert.assertNotNull(action); Assert.assertNotNull(action);
myFixture.launchAction(action); myFixture.launchAction(action);
myFixture.checkResultByFile(testName + ".after.java"); myFixture.checkResultByFile(testName + ".after.java");
} }
@Test @Test
public void test() throws Throwable { public void test() throws Throwable {
doTest("before.template", "Convert ternary operator to if statement"); doTest("before.template", "Convert ternary operator to if statement");
} }
} }

View File

@ -25,15 +25,21 @@
</project-components> </project-components>
<actions> <actions>
<action id="EditorBasics.EditorIllustration" class="org.jetbrains.tutorials.editor.basics.EditorIllustration" text="Editor Basics" <action id="EditorBasics.EditorIllustration"
description="Illustrates how to plug an action in"> class="org.jetbrains.tutorials.editor.basics.EditorIllustration"
<add-to-group group-id="EditorPopupMenu" anchor="first"/> text="Editor Basics"
</action>
<action id="EditorBasics.EditorHandlerIllustration" class="org.jetbrains.tutorials.editor.basics.EditorHandlerIllustration" text="Editor Handler"
description="Illustrates how to plug an action in"> description="Illustrates how to plug an action in">
<add-to-group group-id="EditorPopupMenu" anchor="first"/> <add-to-group group-id="EditorPopupMenu" anchor="first"/>
</action> </action>
<action id="EditorBasics.LogicalPositionIllustration" class="org.jetbrains.tutorials.editor.basics.EditorAreaIllustration" text="Caret Position" <action id="EditorBasics.EditorHandlerIllustration"
class="org.jetbrains.tutorials.editor.basics.EditorHandlerIllustration"
text="Editor Handler"
description="Illustrates how to plug an action in">
<add-to-group group-id="EditorPopupMenu" anchor="first"/>
</action>
<action id="EditorBasics.LogicalPositionIllustration"
class="org.jetbrains.tutorials.editor.basics.EditorAreaIllustration"
text="Caret Position"
description="Illustrates how editor area is organized"> description="Illustrates how editor area is organized">
<add-to-group group-id="EditorPopupMenu" anchor="first"/> <add-to-group group-id="EditorPopupMenu" anchor="first"/>
</action> </action>

View File

@ -3,7 +3,10 @@ package org.jetbrains.tutorials.editor.basics;
import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.Messages;
@ -11,22 +14,22 @@ import com.intellij.openapi.ui.Messages;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class EditorAreaIllustration extends AnAction { public class EditorAreaIllustration extends AnAction {
@Override @Override
public void actionPerformed(AnActionEvent anActionEvent) { public void actionPerformed(AnActionEvent anActionEvent) {
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR); final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
CaretModel caretModel = editor.getCaretModel(); CaretModel caretModel = editor.getCaretModel();
LogicalPosition logicalPosition = caretModel.getLogicalPosition(); LogicalPosition logicalPosition = caretModel.getLogicalPosition();
VisualPosition visualPosition = caretModel.getVisualPosition(); VisualPosition visualPosition = caretModel.getVisualPosition();
int offset = caretModel.getOffset(); int offset = caretModel.getOffset();
Messages.showInfoMessage(logicalPosition.toString() + "\n" + Messages.showInfoMessage(logicalPosition.toString() + "\n" +
visualPosition.toString() + "\n" + visualPosition.toString() + "\n" +
"Offset: " + offset, "Caret Parameters Inside The Editor"); "Offset: " + offset, "Caret Parameters Inside The Editor");
} }
@Override @Override
public void update(AnActionEvent e) { public void update(AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT); final Project project = e.getData(CommonDataKeys.PROJECT);
final Editor editor = e.getData(CommonDataKeys.EDITOR); final Editor editor = e.getData(CommonDataKeys.EDITOR);
e.getPresentation().setVisible(project != null && editor != null); e.getPresentation().setVisible(project != null && editor != null);
} }
} }

View File

@ -14,19 +14,21 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class EditorHandlerIllustration extends AnAction { public class EditorHandlerIllustration extends AnAction {
@Override @Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) { public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR); final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
EditorActionManager actionManager = EditorActionManager.getInstance(); EditorActionManager actionManager = EditorActionManager.getInstance();
//Insert one more caret below the active caret //Insert one more caret below the active caret
EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_CLONE_CARET_BELOW); EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_CLONE_CARET_BELOW);
actionHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), anActionEvent.getDataContext()); actionHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), anActionEvent.getDataContext());
} }
@Override
public void update(@NotNull final AnActionEvent anActionEvent) { @Override
//Set visible if at least one caret is available public void update(@NotNull final AnActionEvent anActionEvent) {
final Project project = anActionEvent.getData(CommonDataKeys.PROJECT); //Set visible if at least one caret is available
final Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR); final Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
anActionEvent.getPresentation().setVisible((project != null && editor != null && !editor.getCaretModel().getAllCarets().isEmpty())); final Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);
} anActionEvent.getPresentation()
.setVisible((project != null && editor != null && !editor.getCaretModel().getAllCarets().isEmpty()));
}
} }

View File

@ -16,40 +16,41 @@ import com.intellij.openapi.project.Project;
*/ */
public class EditorIllustration extends AnAction { public class EditorIllustration extends AnAction {
static { static {
final EditorActionManager actionManager = EditorActionManager.getInstance(); final EditorActionManager actionManager = EditorActionManager.getInstance();
final TypedAction typedAction = actionManager.getTypedAction(); final TypedAction typedAction = actionManager.getTypedAction();
typedAction.setupHandler(new MyTypedHandler()); typedAction.setupHandler(new MyTypedHandler());
} }
@Override @Override
public void actionPerformed(final AnActionEvent anActionEvent) { public void actionPerformed(final AnActionEvent anActionEvent) {
//Get all the required data from data keys //Get all the required data from data keys
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR); final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT); final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT);
//Access document, caret, and selection //Access document, caret, and selection
final Document document = editor.getDocument(); final Document document = editor.getDocument();
final SelectionModel selectionModel = editor.getSelectionModel(); final SelectionModel selectionModel = editor.getSelectionModel();
final int start = selectionModel.getSelectionStart(); final int start = selectionModel.getSelectionStart();
final int end = selectionModel.getSelectionEnd(); final int end = selectionModel.getSelectionEnd();
//New instance of Runnable to make a replacement //New instance of Runnable to make a replacement
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
@Override @Override
public void run() { public void run() {
document.replaceString(start, end, "Replacement"); document.replaceString(start, end, "Replacement");
} }
}; };
//Making the replacement //Making the replacement
WriteCommandAction.runWriteCommandAction(project, runnable); WriteCommandAction.runWriteCommandAction(project, runnable);
selectionModel.removeSelection(); selectionModel.removeSelection();
} }
@Override
public void update(final AnActionEvent e) { @Override
//Get required data keys public void update(final AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT); //Get required data keys
final Editor editor = e.getData(CommonDataKeys.EDITOR); final Project project = e.getData(CommonDataKeys.PROJECT);
//Set visibility only in case of existing project and editor and if some text in the editor is selected final Editor editor = e.getData(CommonDataKeys.EDITOR);
e.getPresentation().setVisible((project != null && editor != null && editor.getSelectionModel().hasSelection())); //Set visibility only in case of existing project and editor and if some text in the editor is selected
} e.getPresentation().setVisible((project != null && editor != null && editor.getSelectionModel().hasSelection()));
}
} }

View File

@ -12,16 +12,16 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class MyTypedHandler implements TypedActionHandler { public class MyTypedHandler implements TypedActionHandler {
@Override @Override
public void execute(@NotNull Editor editor, char c, @NotNull DataContext dataContext) { public void execute(@NotNull Editor editor, char c, @NotNull DataContext dataContext) {
final Document document = editor.getDocument(); final Document document = editor.getDocument();
Project project = editor.getProject(); Project project = editor.getProject();
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
@Override @Override
public void run() { public void run() {
document.insertString(0, "Typed\n"); document.insertString(0, "Typed\n");
} }
}; };
WriteCommandAction.runWriteCommandAction(project, runnable); WriteCommandAction.runWriteCommandAction(project, runnable);
} }
} }

View File

@ -1,36 +1,36 @@
<idea-plugin version="2"> <idea-plugin version="2">
<id>com.intellij.tutorials.facet</id> <id>com.intellij.tutorials.facet</id>
<name>Facet Demo</name> <name>Facet Demo</name>
<version>1.0</version> <version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.yourcompany.com">JetBrains</vendor> <vendor email="support@jrtbrains.com" url="http://www.yourcompany.com">JetBrains</vendor>
<description>Basic example of working with facets</description> <description>Basic example of working with facets</description>
<change-notes>Initial commit</change-notes> <change-notes>Initial commit</change-notes>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description --> <!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/> <idea-version since-build="131"/>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products <!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products --> on how to target different products -->
<!-- uncomment to enable plugin in all products <!-- uncomment to enable plugin in all products
<depends>com.intellij.modules.lang</depends> <depends>com.intellij.modules.lang</depends>
--> -->
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<facetType implementation="com.intellij.tutorials.facet.DemoFacetType"/> <facetType implementation="com.intellij.tutorials.facet.DemoFacetType"/>
</extensions> </extensions>
<application-components> <application-components>
<!-- Add your application components here --> <!-- Add your application components here -->
</application-components> </application-components>
<project-components> <project-components>
<!-- Add your project components here --> <!-- Add your project components here -->
</project-components> </project-components>
<actions> <actions>
<!-- Add your actions here --> <!-- Add your actions here -->
</actions> </actions>
</idea-plugin> </idea-plugin>

View File

@ -8,9 +8,13 @@ import com.intellij.openapi.module.Module;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoFacet extends Facet<DemoFacetConfiguration> { public class DemoFacet extends Facet<DemoFacetConfiguration> {
public static final String ID = "DEMO_FACET_ID"; public static final String ID = "DEMO_FACET_ID";
public DemoFacet(FacetType facetType, Module module, String name, DemoFacetConfiguration configuration, Facet underlyingFacet) { public DemoFacet(FacetType facetType,
super(facetType, module, name, configuration, underlyingFacet); Module module,
} String name,
DemoFacetConfiguration configuration,
Facet underlyingFacet) {
super(facetType, module, name, configuration, underlyingFacet);
}
} }

View File

@ -17,63 +17,64 @@ import java.awt.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoFacetConfiguration implements FacetConfiguration { public class DemoFacetConfiguration implements FacetConfiguration {
public static final String DEMO_FACET_TAG_NAME = "DemoFacet"; public static final String DEMO_FACET_TAG_NAME = "DemoFacet";
public static final String PATH_TO_SDK_ATTR_NAME = "pathToSdk"; public static final String PATH_TO_SDK_ATTR_NAME = "pathToSdk";
private String myPathToSdk = ""; private String myPathToSdk = "";
JTextField myPath = new JTextField(myPathToSdk); JTextField myPath = new JTextField(myPathToSdk);
@Override
public FacetEditorTab[] createEditorTabs(FacetEditorContext context, FacetValidatorsManager manager) {
return new FacetEditorTab[] {
new FacetEditorTab() {
@NotNull @Override
@Override public FacetEditorTab[] createEditorTabs(FacetEditorContext context, FacetValidatorsManager manager) {
public JComponent createComponent() { return new FacetEditorTab[]{
JPanel top = new JPanel(new BorderLayout()); new FacetEditorTab() {
top.add(new JLabel("Path to SDK: "), BorderLayout.WEST);
top.add(myPath);
JPanel panel = new JPanel(new BorderLayout());
panel.add(top, BorderLayout.NORTH);
return panel;
}
@Nls @NotNull
@Override @Override
public String getDisplayName() { public JComponent createComponent() {
return "Demo Framework"; JPanel top = new JPanel(new BorderLayout());
} top.add(new JLabel("Path to SDK: "), BorderLayout.WEST);
top.add(myPath);
JPanel panel = new JPanel(new BorderLayout());
panel.add(top, BorderLayout.NORTH);
return panel;
}
@Override @Nls
public boolean isModified() { @Override
return myPath.getText().equalsIgnoreCase(myPathToSdk); public String getDisplayName() {
return "Demo Framework";
}
@Override
public boolean isModified() {
return myPath.getText().equalsIgnoreCase(myPathToSdk);
// return !StringUtil.equalsIgnoreWhitespaces(myPath.getText(), myPathToSdk); // return !StringUtil.equalsIgnoreWhitespaces(myPath.getText(), myPathToSdk);
} }
@Override @Override
public void reset() { public void reset() {
myPath.setText(myPathToSdk);
}
@Override
public void disposeUIResources() {
}
}
};
}
@Override
public void readExternal(Element element) throws InvalidDataException {
Element facet = element.getChild(DEMO_FACET_TAG_NAME);
if (facet != null) {
myPathToSdk = facet.getAttributeValue(PATH_TO_SDK_ATTR_NAME, "");
myPath.setText(myPathToSdk); myPath.setText(myPathToSdk);
} }
}
@Override @Override
public void writeExternal(Element element) throws WriteExternalException { public void disposeUIResources() {
Element facet = new Element(DEMO_FACET_TAG_NAME); }
facet.setAttribute(PATH_TO_SDK_ATTR_NAME, myPathToSdk); }
element.addContent(facet); };
}
@Override
public void readExternal(Element element) throws InvalidDataException {
Element facet = element.getChild(DEMO_FACET_TAG_NAME);
if (facet != null) {
myPathToSdk = facet.getAttributeValue(PATH_TO_SDK_ATTR_NAME, "");
myPath.setText(myPathToSdk);
} }
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
Element facet = new Element(DEMO_FACET_TAG_NAME);
facet.setAttribute(PATH_TO_SDK_ATTR_NAME, myPathToSdk);
element.addContent(facet);
}
} }

View File

@ -15,29 +15,33 @@ import javax.swing.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoFacetType extends FacetType<DemoFacet, DemoFacetConfiguration> { public class DemoFacetType extends FacetType<DemoFacet, DemoFacetConfiguration> {
private static final FacetTypeId<DemoFacet> TYPE_ID = new FacetTypeId<DemoFacet>(DemoFacet.ID); private static final FacetTypeId<DemoFacet> TYPE_ID = new FacetTypeId<DemoFacet>(DemoFacet.ID);
public DemoFacetType() {
super(TYPE_ID, DemoFacet.ID, "Demo Facet");
}
@Override public DemoFacetType() {
public DemoFacetConfiguration createDefaultConfiguration() { super(TYPE_ID, DemoFacet.ID, "Demo Facet");
return new DemoFacetConfiguration(); }
}
@Override @Override
public DemoFacet createFacet(@NotNull Module module, String s, @NotNull DemoFacetConfiguration configuration, Facet facet) { public DemoFacetConfiguration createDefaultConfiguration() {
return new DemoFacet(this, module, s, configuration, facet); return new DemoFacetConfiguration();
} }
@Override @Override
public boolean isSuitableModuleType(ModuleType type) { public DemoFacet createFacet(@NotNull Module module,
return true; String s,
} @NotNull DemoFacetConfiguration configuration,
Facet facet) {
return new DemoFacet(this, module, s, configuration, facet);
}
@Nullable @Override
@Override public boolean isSuitableModuleType(ModuleType type) {
public Icon getIcon() { return true;
return AllIcons.General.Information; }
}
@Nullable
@Override
public Icon getIcon() {
return AllIcons.General.Information;
}
} }

View File

@ -18,54 +18,57 @@ import javax.swing.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoFramework extends FrameworkTypeEx { public class DemoFramework extends FrameworkTypeEx {
public static final String FRAMEWORK_ID = "Demo"; public static final String FRAMEWORK_ID = "Demo";
protected DemoFramework() {
super(FRAMEWORK_ID);
}
@NotNull protected DemoFramework() {
@Override super(FRAMEWORK_ID);
public FrameworkSupportInModuleProvider createProvider() { }
return new FrameworkSupportInModuleProvider() {
@NotNull
@Override
public FrameworkTypeEx getFrameworkType() {
return DemoFramework.this;
}
@NotNull @NotNull
@Override @Override
public FrameworkSupportInModuleConfigurable createConfigurable(@NotNull FrameworkSupportModel model) { public FrameworkSupportInModuleProvider createProvider() {
return new FrameworkSupportInModuleConfigurable() { return new FrameworkSupportInModuleProvider() {
@Nullable @NotNull
@Override @Override
public JComponent createComponent() { public FrameworkTypeEx getFrameworkType() {
return new JCheckBox("Extra Option"); return DemoFramework.this;
} }
@Override @NotNull
public void addSupport(@NotNull Module module, @NotNull ModifiableRootModel model, @NotNull ModifiableModelsProvider provider) { @Override
//do what you want here: setup a library, generate a specific file, etc public FrameworkSupportInModuleConfigurable createConfigurable(@NotNull FrameworkSupportModel model) {
} return new FrameworkSupportInModuleConfigurable() {
}; @Nullable
} @Override
public JComponent createComponent() {
return new JCheckBox("Extra Option");
}
@Override @Override
public boolean isEnabledForModuleType(@NotNull ModuleType type) { public void addSupport(@NotNull Module module,
return true; @NotNull ModifiableRootModel model,
} @NotNull ModifiableModelsProvider provider) {
//do what you want here: setup a library, generate a specific file, etc
}
}; };
} }
@NotNull @Override
@Override public boolean isEnabledForModuleType(@NotNull ModuleType type) {
public String getPresentableName() { return true;
return "Demo Framework"; }
} };
}
@NotNull @NotNull
@Override @Override
public Icon getIcon() { public String getPresentableName() {
return AllIcons.Providers.Apache; return "Demo Framework";
} }
@NotNull
@Override
public Icon getIcon() {
return AllIcons.Providers.Apache;
}
} }

View File

@ -27,5 +27,5 @@ group 'org.jetbrains'
version '0.0.1-SNAPSHOT' version '0.0.1-SNAPSHOT'
repositories { repositories {
mavenCentral () mavenCentral()
} }

View File

@ -8,12 +8,12 @@ import com.intellij.openapi.ui.Messages;
* Created by breandan on 11/25/2015. * Created by breandan on 11/25/2015.
*/ */
public class HelloAction extends AnAction { public class HelloAction extends AnAction {
public HelloAction() { public HelloAction() {
super("Hello"); super("Hello");
} }
public void actionPerformed(AnActionEvent event) { public void actionPerformed(AnActionEvent event) {
Project project = event.getData(PlatformDataKeys.PROJECT); Project project = event.getData(PlatformDataKeys.PROJECT);
Messages.showMessageDialog(project, "Hello world!", "Greeting", Messages.getInformationIcon()); Messages.showMessageDialog(project, "Hello world!", "Greeting", Messages.getInformationIcon());
} }
} }

View File

@ -33,8 +33,8 @@
<actions> <actions>
<group id="MyPlugin.SampleMenu" text="Greeting" description="Greeting menu"> <group id="MyPlugin.SampleMenu" text="Greeting" description="Greeting menu">
<add-to-group group-id="MainMenu" anchor="last" /> <add-to-group group-id="MainMenu" anchor="last"/>
<action id="Myplugin.Textboxes" class="HelloAction" text="Hello" description="Says hello" /> <action id="Myplugin.Textboxes" class="HelloAction" text="Hello" description="Says hello"/>
</group> </group>
</actions> </actions>

View File

@ -1,30 +1,30 @@
<idea-plugin version="2"> <idea-plugin version="2">
<id>com.intellij.tutorials.inspection</id> <id>com.intellij.tutorials.inspection</id>
<name>Inspection Demo</name> <name>Inspection Demo</name>
<version>1.0</version> <version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.jetbrains.com">JetBrains</vendor> <vendor email="support@jrtbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Basic example of working with code inspections</description> <description>Basic example of working with code inspections</description>
<change-notes>Initial commit</change-notes> <change-notes>Initial commit</change-notes>
<idea-version since-build="131"/> <idea-version since-build="131"/>
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<inspectionToolProvider implementation="com.intellij.tutorials.inspection.DemoInspectionToolProvider"/> <inspectionToolProvider implementation="com.intellij.tutorials.inspection.DemoInspectionToolProvider"/>
</extensions> </extensions>
<application-components> <application-components>
<!-- Add your application components here --> <!-- Add your application components here -->
</application-components> </application-components>
<project-components> <project-components>
<!-- Add your project components here --> <!-- Add your project components here -->
</project-components> </project-components>
<actions> <actions>
<!-- Add your actions here --> <!-- Add your actions here -->
</actions> </actions>
</idea-plugin> </idea-plugin>

View File

@ -9,16 +9,16 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoCodeInspection extends LocalInspectionTool { public class DemoCodeInspection extends LocalInspectionTool {
@Nls @Nls
@NotNull @NotNull
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Demo Inspection"; return "Demo Inspection";
} }
@NotNull @NotNull
@Override @Override
public DemoInspectionVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) { public DemoInspectionVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new DemoInspectionVisitor(); return new DemoInspectionVisitor();
} }
} }

View File

@ -6,7 +6,7 @@ import com.intellij.codeInspection.InspectionToolProvider;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoInspectionToolProvider implements InspectionToolProvider { public class DemoInspectionToolProvider implements InspectionToolProvider {
public Class[] getInspectionClasses() { public Class[] getInspectionClasses() {
return new Class[] { DemoCodeInspection.class}; return new Class[]{DemoCodeInspection.class};
} }
} }

View File

@ -8,13 +8,13 @@ import com.intellij.psi.PsiPlainTextFile;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoInspectionVisitor extends PsiElementVisitor { public class DemoInspectionVisitor extends PsiElementVisitor {
@Override @Override
public void visitElement(PsiElement element) { public void visitElement(PsiElement element) {
super.visitElement(element); super.visitElement(element);
} }
@Override @Override
public void visitPlainTextFile(PsiPlainTextFile file) { public void visitPlainTextFile(PsiPlainTextFile file) {
super.visitPlainTextFile(file); super.visitPlainTextFile(file);
} }
} }

View File

@ -30,8 +30,8 @@
<actions> <actions>
<group id="MyPlugin.TestMeu" text="Greeting" description="Greeting menu"> <group id="MyPlugin.TestMeu" text="Greeting" description="Greeting menu">
<add-to-group group-id="MainMenu" anchor="last" /> <add-to-group group-id="MainMenu" anchor="last"/>
<action id="Myplugin.Textboxes" class="HelloAction" text="Hello" description="Says hello" /> <action id="Myplugin.Textboxes" class="HelloAction" text="Hello" description="Says hello"/>
</group> </group>
</actions> </actions>

View File

@ -1,9 +1,13 @@
<templateSet group="Markdown"> <templateSet group="Markdown">
<template name="[" value="[$TEXT$]($LINK$)$END$" description="New link reference." toReformat="false" toShortenFQNames="false"> <template name="["
<variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" /> value="[$TEXT$]($LINK$)$END$"
<variable name="LINK" expression="complete()" defaultValue="" alwaysStopAt="true" /> description="New link reference."
<context> toReformat="false"
<option name="MARKDOWN" value="true" /> toShortenFQNames="false">
</context> <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true"/>
</template> <variable name="LINK" expression="complete()" defaultValue="" alwaysStopAt="true"/>
<context>
<option name="MARKDOWN" value="true"/>
</context>
</template>
</templateSet> </templateSet>

View File

@ -1,17 +1,14 @@
import com.intellij.codeInsight.template.EverywhereContextType;
import com.intellij.codeInsight.template.TemplateContextType; import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MarkdownContext extends TemplateContextType { public class MarkdownContext extends TemplateContextType {
protected MarkdownContext() { protected MarkdownContext() {
super("MARKDOWN", "Markdown"); super("MARKDOWN", "Markdown");
} }
@Override @Override
public boolean isInContext(@NotNull PsiFile file, int offset) { public boolean isInContext(@NotNull PsiFile file, int offset) {
return file.getName().endsWith(".md"); return file.getName().endsWith(".md");
} }
} }

View File

@ -2,15 +2,14 @@ import com.intellij.codeInsight.template.impl.DefaultLiveTemplatesProvider;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class MarkdownTemplateProvider implements DefaultLiveTemplatesProvider { public class MarkdownTemplateProvider implements DefaultLiveTemplatesProvider {
@Override @Override
public String[] getDefaultLiveTemplateFiles() public String[] getDefaultLiveTemplateFiles() {
{ return new String[]{"liveTemplates/Markdown"};
return new String[] {"liveTemplates/Markdown"}; }
}
@Nullable @Nullable
@Override @Override
public String[] getHiddenLiveTemplateFiles() { public String[] getHiddenLiveTemplateFiles() {
return new String[0]; return new String[0];
} }
} }

View File

@ -11,9 +11,9 @@
<project-components> <project-components>
<!-- Add your project components here --> <!-- Add your project components here -->
<component> <component>
<implementation-class>MyPackage.MaxProject</implementation-class> <implementation-class>MyPackage.MaxProject</implementation-class>
</component> </component>
</project-components> </project-components>
<actions> <actions>
@ -22,8 +22,8 @@
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here --> <!-- Add your extensions here -->
<applicationService serviceInterface="MyPackage.MyCounter" serviceImplementation="MyPackage.MyCounter"> <applicationService serviceInterface="MyPackage.MyCounter" serviceImplementation="MyPackage.MyCounter">
</applicationService> </applicationService>
</extensions> </extensions>
</idea-plugin> </idea-plugin>

View File

@ -15,40 +15,41 @@ import org.jetbrains.annotations.NotNull;
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class MaxProject implements ProjectComponent { public class MaxProject implements ProjectComponent {
public MaxProject(Project project) { public MaxProject(Project project) {
}
public void initComponent() {
// TODO: insert component initialization logic here
}
public void disposeComponent() {
// TODO: insert component disposal logic here
}
@NotNull
public String getComponentName() {
return "MaxProject";
}
public void projectOpened() {
// called when project is opened
MyCounter CommandCounter = ServiceManager.getService(MyCounter.class);
if (CommandCounter.IncreaseCounter() == -1) {
Messages.showMessageDialog(
"The maximum number of opened projects exceeds " + String.valueOf(CommandCounter.MaxCount) +
" projects!", "Error", Messages.getErrorIcon());
ProjectManager PM = ProjectManager.getInstance();
Project[] AllProjects = PM.getOpenProjects();
Project project = AllProjects[AllProjects.length - 1];
PM.closeProject(project);
} }
}
public void initComponent() {
// TODO: insert component initialization logic here
}
public void disposeComponent() {
// TODO: insert component disposal logic here
}
@NotNull
public String getComponentName() {
return "MaxProject";
}
public void projectOpened() {
// called when project is opened
MyCounter CommandCounter = ServiceManager.getService(MyCounter.class);
if (CommandCounter.IncreaseCounter() == -1) {
Messages.showMessageDialog("The maximum number of opened projects exceeds " + String.valueOf(CommandCounter.MaxCount) +
" projects!", "Error", Messages.getErrorIcon());
ProjectManager PM=ProjectManager.getInstance();
Project[] AllProjects = PM.getOpenProjects();
Project project = AllProjects[AllProjects.length-1];
PM.closeProject(project);
}
}
public void projectClosed() { public void projectClosed() {
// called when project is being closed // called when project is being closed
MyCounter CommandCounter = ServiceManager.getService(MyCounter.class); MyCounter CommandCounter = ServiceManager.getService(MyCounter.class);
CommandCounter.DecreaseCounter(); CommandCounter.DecreaseCounter();
} }
} }

View File

@ -8,22 +8,23 @@ package MyPackage;
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class MyCounter { public class MyCounter {
private int Count = 0; private int Count = 0;
// Sets the maximum allowed number of opened projects. // Sets the maximum allowed number of opened projects.
public final int MaxCount = 3; public final int MaxCount = 3;
public MyCounter(){
public MyCounter() {
} }
public int IncreaseCounter() { public int IncreaseCounter() {
Count++; Count++;
return (Count > MaxCount) ? -1:Count; return (Count > MaxCount) ? -1 : Count;
} }
public int DecreaseCounter() { public int DecreaseCounter() {
Count--; Count--;
return (Count > MaxCount) ? -1:Count; return (Count > MaxCount) ? -1 : Count;
} }
} }

View File

@ -1,36 +1,36 @@
<idea-plugin version="2"> <idea-plugin version="2">
<id>com.intellij.tutorials.module</id> <id>com.intellij.tutorials.module</id>
<name>Module Type Demo</name> <name>Module Type Demo</name>
<version>1.0</version> <version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.jetbrains.com">JetBrains</vendor> <vendor email="support@jrtbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Basic example of working with module types</description> <description>Basic example of working with module types</description>
<change-notes>Initial commit</change-notes> <change-notes>Initial commit</change-notes>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description --> <!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/> <idea-version since-build="131"/>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products <!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products --> on how to target different products -->
<!-- uncomment to enable plugin in all products <!-- uncomment to enable plugin in all products
<depends>com.intellij.modules.lang</depends> <depends>com.intellij.modules.lang</depends>
--> -->
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<moduleType id="DEMO_MODULE_TYPE" implementationClass="com.intellij.tutorials.module.DemoModuleType"/> <moduleType id="DEMO_MODULE_TYPE" implementationClass="com.intellij.tutorials.module.DemoModuleType"/>
</extensions> </extensions>
<application-components> <application-components>
<!-- Add your application components here --> <!-- Add your application components here -->
</application-components> </application-components>
<project-components> <project-components>
<!-- Add your project components here --> <!-- Add your project components here -->
</project-components> </project-components>
<actions> <actions>
<!-- Add your actions here --> <!-- Add your actions here -->
</actions> </actions>
</idea-plugin> </idea-plugin>

View File

@ -13,19 +13,19 @@ import org.jetbrains.annotations.Nullable;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoModuleBuilder extends ModuleBuilder { public class DemoModuleBuilder extends ModuleBuilder {
@Override @Override
public void setupRootModel(ModifiableRootModel model) throws ConfigurationException { public void setupRootModel(ModifiableRootModel model) throws ConfigurationException {
} }
@Override @Override
public ModuleType getModuleType() { public ModuleType getModuleType() {
return DemoModuleType.getInstance(); return DemoModuleType.getInstance();
} }
@Nullable @Nullable
@Override @Override
public ModuleWizardStep getCustomOptionsStep(WizardContext context, Disposable parentDisposable) { public ModuleWizardStep getCustomOptionsStep(WizardContext context, Disposable parentDisposable) {
return new DemoModuleWizardStep(); return new DemoModuleWizardStep();
} }
} }

View File

@ -14,47 +14,49 @@ import javax.swing.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoModuleType extends ModuleType<DemoModuleBuilder> { public class DemoModuleType extends ModuleType<DemoModuleBuilder> {
private static final String ID = "DEMO_MODULE_TYPE"; private static final String ID = "DEMO_MODULE_TYPE";
public DemoModuleType() { public DemoModuleType() {
super(ID); super(ID);
} }
public static DemoModuleType getInstance() { public static DemoModuleType getInstance() {
return (DemoModuleType) ModuleTypeManager.getInstance().findByID(ID); return (DemoModuleType) ModuleTypeManager.getInstance().findByID(ID);
} }
@NotNull @NotNull
@Override @Override
public DemoModuleBuilder createModuleBuilder() { public DemoModuleBuilder createModuleBuilder() {
return new DemoModuleBuilder(); return new DemoModuleBuilder();
} }
@NotNull @NotNull
@Override @Override
public String getName() { public String getName() {
return "Demo Module Type"; return "Demo Module Type";
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription() {
return "Demo Module Type"; return "Demo Module Type";
} }
@Override @Override
public Icon getBigIcon() { public Icon getBigIcon() {
return AllIcons.General.Information; return AllIcons.General.Information;
} }
@Override @Override
public Icon getNodeIcon(@Deprecated boolean b) { public Icon getNodeIcon(@Deprecated boolean b) {
return AllIcons.General.Information; return AllIcons.General.Information;
} }
@NotNull @NotNull
@Override @Override
public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull DemoModuleBuilder moduleBuilder, @NotNull ModulesProvider modulesProvider) { public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext,
return super.createWizardSteps(wizardContext, moduleBuilder, modulesProvider); @NotNull DemoModuleBuilder moduleBuilder,
} @NotNull ModulesProvider modulesProvider) {
return super.createWizardSteps(wizardContext, moduleBuilder, modulesProvider);
}
} }

View File

@ -8,13 +8,13 @@ import javax.swing.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoModuleWizardStep extends ModuleWizardStep { public class DemoModuleWizardStep extends ModuleWizardStep {
@Override @Override
public JComponent getComponent() { public JComponent getComponent() {
return new JLabel("Provide some setting here"); return new JLabel("Provide some setting here");
} }
@Override @Override
public void updateDataModel() { public void updateDataModel() {
//todo update model according to UI //todo update model according to UI
} }
} }

View File

@ -1,140 +1,143 @@
<idea-plugin version="2" url="www.jetbrains.com" use-idea-classloader="true"> <idea-plugin version="2" url="www.jetbrains.com" use-idea-classloader="true">
<id>org.jetbrains.plugins.sample.PluginSample</id> <id>org.jetbrains.plugins.sample.PluginSample</id>
<name>Basic plugin example</name> <name>Basic plugin example</name>
<version>1.0</version> <version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor> <vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<category>Samples</category> <category>Samples</category>
<description><![CDATA[ <description><![CDATA[
Illustration of configuration options.<br> Illustration of configuration options.<br>
<em>most HTML tags may be used</em> <em>most HTML tags may be used</em>
]]></description> ]]></description>
<change-notes><![CDATA[ <change-notes><![CDATA[
Initial release.<br> Initial release.<br>
<em>most HTML tags may be used</em> <em>most HTML tags may be used</em>
]]> ]]>
</change-notes> </change-notes>
<!-- http://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products --> <!-- http://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products -->
<!-- The unique identifiers of the plugins on which this plugin depends --> <!-- The unique identifiers of the plugins on which this plugin depends -->
<!-- com.intellij.modules.lang is included in every IntelliJ-based IDE, plugin will be available as well --> <!-- com.intellij.modules.lang is included in every IntelliJ-based IDE, plugin will be available as well -->
<depends>com.intellij.modules.lang</depends> <depends>com.intellij.modules.lang</depends>
<!-- Optional dependency on another plugin. If the plugin with the "MySecondPlugin" ID is installed, the contents of mysecondplugin.xml (the format of this file conforms to the format of plugin.xml) will be loaded. --> <!-- Optional dependency on another plugin. If the plugin with the "MySecondPlugin" ID is installed, the contents of mysecondplugin.xml (the format of this file conforms to the format of plugin.xml) will be loaded. -->
<!--<depends optional="true" config-file="custom-plugin.xml">CustomPlugin</depends>--> <!--<depends optional="true" config-file="custom-plugin.xml">CustomPlugin</depends>-->
<!-- Allows a plugin to integrate its help system (in JavaHelp format) with the IDEA help system. The "file" attribute specifies the name of the JAR file <!-- Allows a plugin to integrate its help system (in JavaHelp format) with the IDEA help system. The "file" attribute specifies the name of the JAR file
in the "help" subdirectory of the plugin directory. The "path" attribute specifies the name of the helpset file within the JAR file.--> in the "help" subdirectory of the plugin directory. The "path" attribute specifies the name of the helpset file within the JAR file.-->
<helpset file="plugin-help.jar" path="/Help.hs"/> <helpset file="plugin-help.jar" path="/Help.hs"/>
<!-- Minimum and maximum build of IDEA compatible with the plugin --> <!-- Minimum and maximum build of IDEA compatible with the plugin -->
<idea-version since-build="139.000" until-build="999"/> <idea-version since-build="139.000" until-build="999"/>
<!-- Resource bundle from which the text of plugin descriptions, action names and etc. will be loaded --> <!-- Resource bundle from which the text of plugin descriptions, action names and etc. will be loaded -->
<resource-bundle>org.jetbrains.tutorials.sample.PluginSampleBundle</resource-bundle> <resource-bundle>org.jetbrains.tutorials.sample.PluginSampleBundle</resource-bundle>
<!-- Plugin's application components --> <!-- Plugin's application components -->
<application-components> <application-components>
<component> <component>
<!-- Component's interface class --> <!-- Component's interface class -->
<interface-class>org.jetbrains.tutorials.sample.DummyApplicationComponent</interface-class> <interface-class>org.jetbrains.tutorials.sample.DummyApplicationComponent</interface-class>
<!-- Component's implementation class --> <!-- Component's implementation class -->
<implementation-class>org.jetbrains.tutorials.sample.DummyApplicationComponentImpl</implementation-class> <implementation-class>org.jetbrains.tutorials.sample.DummyApplicationComponentImpl</implementation-class>
</component> </component>
</application-components> </application-components>
<!-- Plugin's project components --> <!-- Plugin's project components -->
<project-components> <project-components>
<component> <component>
<!-- Interface and implementation classes are the same --> <!-- Interface and implementation classes are the same -->
<interface-class>org.jetbrains.tutorials.sample.DummyProjectComponent</interface-class> <interface-class>org.jetbrains.tutorials.sample.DummyProjectComponent</interface-class>
<implementation-class>org.jetbrains.tutorials.sample.DummyProjectComponentImpl</implementation-class> <implementation-class>org.jetbrains.tutorials.sample.DummyProjectComponentImpl</implementation-class>
<!-- If the "workspace" option is set "true", the component saves its state to the .iws file <!-- If the "workspace" option is set "true", the component saves its state to the .iws file
instead of the .ipr file. Note that the <option> element is used only if the component implements the JDOMExternalizable interface. Otherwise, the use of the <option> element takes no effect.--> instead of the .ipr file. Note that the <option> element is used only if the component implements the JDOMExternalizable interface. Otherwise, the use of the <option> element takes no effect.-->
<option name="workspace" value="true"/> <option name="workspace" value="true"/>
<!-- If the "loadForDefaultProject" tag is present, the project component is instantiated also for the default project. --> <!-- If the "loadForDefaultProject" tag is present, the project component is instantiated also for the default project. -->
<loadForDefaultProject/> <loadForDefaultProject/>
</component> </component>
</project-components> </project-components>
<!-- Plugin's module components --> <!-- Plugin's module components -->
<module-components> <module-components>
<component> <component>
<interface-class>org.jetbrains.tutorials.sample.DummyModuleComponent</interface-class> <interface-class>org.jetbrains.tutorials.sample.DummyModuleComponent</interface-class>
<implementation-class>org.jetbrains.tutorials.sample.DummyModuleComponentImpl</implementation-class> <implementation-class>org.jetbrains.tutorials.sample.DummyModuleComponentImpl</implementation-class>
</component> </component>
</module-components> </module-components>
<!-- Actions --> <!-- Actions -->
<actions> <actions>
<!-- The <action> element defines an action to register. <!-- The <action> element defines an action to register.
The mandatory "id" attribute specifies an unique identifier for the action. The mandatory "id" attribute specifies an unique identifier for the action.
The mandatory "class" attribute specifies the full-qualified name of the class implementing the action. The mandatory "class" attribute specifies the full-qualified name of the class implementing the action.
The mandatory "text" attribute specifies the text of the action (tooltip for toolbar button or text for menu item). The mandatory "text" attribute specifies the text of the action (tooltip for toolbar button or text for menu item).
The optional "use-shortcut-of" attribute specifies the ID of the action whose keyboard shortcut this action will use. The optional "use-shortcut-of" attribute specifies the ID of the action whose keyboard shortcut this action will use.
The optional "description" attribute specifies the text which is displayed in the status bar when the action is focused. The optional "description" attribute specifies the text which is displayed in the status bar when the action is focused.
The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the menu item. --> The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the menu item. -->
<action id="PluginSample.DummyAction" class="org.jetbrains.tutorials.sample.actions.SimpleAction" text="Dummy Action" <action id="PluginSample.DummyAction"
description="Illustrates how to plug an action in"> class="org.jetbrains.tutorials.sample.actions.SimpleAction"
<!-- The <keyboard-shortcut> node specifies the keyboard shortcut for the action. An action can have several keyboard shortcuts. text="Dummy Action"
The mandatory "first-keystroke" attribute specifies the first keystroke of the action. The key strokes are specified according to the regular Swing rules. description="Illustrates how to plug an action in">
The optional "second-keystroke" attribute specifies the second keystroke of the action. <!-- The <keyboard-shortcut> node specifies the keyboard shortcut for the action. An action can have several keyboard shortcuts.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as The mandatory "first-keystroke" attribute specifies the first keystroke of the action. The key strokes are specified according to the regular Swing rules.
constants in the com.intellij.openapi.keymap.KeymapManager class. --> The optional "second-keystroke" attribute specifies the second keystroke of the action.
<keyboard-shortcut first-keystroke="control alt A" second-keystroke="C" keymap="$default"/> The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
<!-- The <mouse-shortcut> node specifies the mouse shortcut for the action. An action can have several mouse shortcuts. constants in the com.intellij.openapi.keymap.KeymapManager class. -->
The mandatory "keystroke" attribute specifies the clicks and modifiers for the action. It is defined as a sequence of words separated by spaces: <keyboard-shortcut first-keystroke="control alt A" second-keystroke="C" keymap="$default"/>
"button1", "button2", "button3" for the mouse buttons; "shift", "control", "meta", "alt", "altGraph" for the modifier keys; <!-- The <mouse-shortcut> node specifies the mouse shortcut for the action. An action can have several mouse shortcuts.
"doubleClick" if the action is activated by a double-click of the button. The mandatory "keystroke" attribute specifies the clicks and modifiers for the action. It is defined as a sequence of words separated by spaces:
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as "button1", "button2", "button3" for the mouse buttons; "shift", "control", "meta", "alt", "altGraph" for the modifier keys;
constants in the com.intellij.openapi.keymap.KeymapManager class. --> "doubleClick" if the action is activated by a double-click of the button.
<mouse-shortcut keystroke="control button3 doubleClick" keymap="$default"/> The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
<!-- The <add-to-group> node specifies that the action should be added to an existing group. An action can be added to several groups. constants in the com.intellij.openapi.keymap.KeymapManager class. -->
The mandatory "group-id" attribute specifies the ID of the group to which the action is added. <mouse-shortcut keystroke="control button3 doubleClick" keymap="$default"/>
The group must be implemented by an instance of the DefaultActionGroup class. <!-- The <add-to-group> node specifies that the action should be added to an existing group. An action can be added to several groups.
The mandatory "anchor" attribute specifies the position of the action in the group relative to other actions. It can have the values The mandatory "group-id" attribute specifies the ID of the group to which the action is added.
"first", "last", "before" and "after". The group must be implemented by an instance of the DefaultActionGroup class.
The "relative-to-action" attribute is mandatory if the anchor is set to "before" and "after", and specifies the action before or after which The mandatory "anchor" attribute specifies the position of the action in the group relative to other actions. It can have the values
the current action is inserted. --> "first", "last", "before" and "after".
<add-to-group group-id="ToolsMenu" anchor="after"/> The "relative-to-action" attribute is mandatory if the anchor is set to "before" and "after", and specifies the action before or after which
</action> the current action is inserted. -->
<!-- The <group> element defines an action group. <action>, <group> and <separator> elements defined within it are automatically included in the group. <add-to-group group-id="ToolsMenu" anchor="after"/>
The mandatory "id" attribute specifies an unique identifier for the action. </action>
The optional "class" attribute specifies the full-qualified name of the class implementing the group. If not specified, <!-- The <group> element defines an action group. <action>, <group> and <separator> elements defined within it are automatically included in the group.
com.intellij.openapi.actionSystem.DefaultActionGroup is used. The mandatory "id" attribute specifies an unique identifier for the action.
The optional "text" attribute specifies the text of the group (text for the menu item showing the submenu). The optional "class" attribute specifies the full-qualified name of the class implementing the group. If not specified,
The optional "description" attribute specifies the text which is displayed in the status bar when the group is focused. com.intellij.openapi.actionSystem.DefaultActionGroup is used.
The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the group. The optional "text" attribute specifies the text of the group (text for the menu item showing the submenu).
The optional "popup" attribute specifies how the group is presented in the menu. If a group has popup="true", actions in it The optional "description" attribute specifies the text which is displayed in the status bar when the group is focused.
are placed in a submenu; for popup="false", actions are displayed as a section of the same menu delimited by separators. --> The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the group.
<group id="DummyDefaultActionGroup" text="Default action group"> The optional "popup" attribute specifies how the group is presented in the menu. If a group has popup="true", actions in it
<action class="org.jetbrains.tutorials.sample.actions.GroupedToDefaultAction" id="PluginSample.GroupedToDefaultAction"/> are placed in a submenu; for popup="false", actions are displayed as a section of the same menu delimited by separators. -->
</group> <group id="DummyDefaultActionGroup" text="Default action group">
<group class="org.jetbrains.tutorials.sample.actions.DummyActionGroup" id="DummyActionGroup" text="Action Group" <action class="org.jetbrains.tutorials.sample.actions.GroupedToDefaultAction"
description="Illustration of an action group" id="PluginSample.GroupedToDefaultAction"/>
icon="icons/testgroup.png" popup="true"> </group>
<action id="PluginSample.GroupedAction" class="org.jetbrains.tutorials.sample.actions.GroupedAction" <group class="org.jetbrains.tutorials.sample.actions.DummyActionGroup" id="DummyActionGroup" text="Action Group"
text="Grouped Action" description="An action in the group"/> description="Illustration of an action group"
<!-- The <separator> element defines a separator between actions. It can also have an <add-to-group> child element. --> icon="icons/testgroup.png" popup="true">
<separator/> <action id="PluginSample.GroupedAction" class="org.jetbrains.tutorials.sample.actions.GroupedAction"
<group id="ActionSubGroup"/> text="Grouped Action" description="An action in the group"/>
<!-- The <reference> element allows to add an existing action to the group. The mandatory "ref" attribute specifies the ID of the action to add. --> <!-- The <separator> element defines a separator between actions. It can also have an <add-to-group> child element. -->
<reference ref="EditorCopy"/> <separator/>
<add-to-group group-id="MainMenu" relative-to-action="HelpMenu" anchor="before"/> <group id="ActionSubGroup"/>
</group> <!-- The <reference> element allows to add an existing action to the group. The mandatory "ref" attribute specifies the ID of the action to add. -->
<reference ref="EditorCopy"/>
<add-to-group group-id="MainMenu" relative-to-action="HelpMenu" anchor="before"/>
</group>
</actions> </actions>
<!-- Extension points defined by the plugin. Extension points are registered by a plugin so that other plugins can provide this plugin <!-- Extension points defined by the plugin. Extension points are registered by a plugin so that other plugins can provide this plugin
with certain data. The "beanClass" attribute specifies the class the implementations of which can be used for the extension point. --> with certain data. The "beanClass" attribute specifies the class the implementations of which can be used for the extension point. -->
<!--<extensionPoints>--> <!--<extensionPoints>-->
<!--<extensionPoint name="testExtensionPoint" beanClass="com.foo.impl.MyExtensionBean"/>--> <!--<extensionPoint name="testExtensionPoint" beanClass="com.foo.impl.MyExtensionBean"/>-->
<!--</extensionPoints>--> <!--</extensionPoints>-->
<!-- Extensions which the plugin adds to extension points defined by the IDEA core or by other plugins. The "defaultExtensionNs " attribute must be set to the ID of the plugin defining the extension point, <!-- Extensions which the plugin adds to extension points defined by the IDEA core or by other plugins. The "defaultExtensionNs " attribute must be set to the ID of the plugin defining the extension point,
or to "com.intellij" if the extension point is defined by the IDEA core. The name of the or to "com.intellij" if the extension point is defined by the IDEA core. The name of the
tag within the <extensions> tag matches the name of the extension point, and the "implementation" class specifies the name of the tag within the <extensions> tag matches the name of the extension point, and the "implementation" class specifies the name of the
class added to the extension point. --> class added to the extension point. -->
<extensions> <extensions>
<!--<testExtensionPoint implementation="com.foo.impl.MyExtensionImpl"/>--> <!--<testExtensionPoint implementation="com.foo.impl.MyExtensionImpl"/>-->
</extensions> </extensions>
</idea-plugin> </idea-plugin>

View File

@ -5,5 +5,5 @@ import com.intellij.openapi.components.ApplicationComponent;
/** /**
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
interface DummyApplicationComponent extends ApplicationComponent{ interface DummyApplicationComponent extends ApplicationComponent {
} }

View File

@ -6,19 +6,19 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DummyApplicationComponentImpl implements DummyApplicationComponent { public class DummyApplicationComponentImpl implements DummyApplicationComponent {
@Override @Override
public void initComponent() { public void initComponent() {
} }
@Override @Override
public void disposeComponent() { public void disposeComponent() {
} }
@NotNull @NotNull
@Override @Override
public String getComponentName() { public String getComponentName() {
return "DummyApplicationComponent"; return "DummyApplicationComponent";
} }
} }

View File

@ -5,5 +5,5 @@ import com.intellij.openapi.module.ModuleComponent;
/** /**
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public interface DummyModuleComponent extends ModuleComponent{ public interface DummyModuleComponent extends ModuleComponent {
} }

View File

@ -6,34 +6,34 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DummyModuleComponentImpl implements DummyModuleComponent { public class DummyModuleComponentImpl implements DummyModuleComponent {
@Override @Override
public void projectOpened() { public void projectOpened() {
} }
@Override @Override
public void projectClosed() { public void projectClosed() {
} }
@Override @Override
public void moduleAdded() { public void moduleAdded() {
} }
@Override @Override
public void initComponent() { public void initComponent() {
} }
@Override @Override
public void disposeComponent() { public void disposeComponent() {
} }
@NotNull @NotNull
@Override @Override
public String getComponentName() { public String getComponentName() {
return "DummyModuleComponent"; return "DummyModuleComponent";
} }
} }

View File

@ -5,5 +5,5 @@ import com.intellij.openapi.components.ProjectComponent;
/** /**
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public interface DummyProjectComponent extends ProjectComponent{ public interface DummyProjectComponent extends ProjectComponent {
} }

View File

@ -6,29 +6,29 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DummyProjectComponentImpl implements DummyProjectComponent { public class DummyProjectComponentImpl implements DummyProjectComponent {
@Override @Override
public void projectOpened() { public void projectOpened() {
} }
@Override @Override
public void projectClosed() { public void projectClosed() {
} }
@Override @Override
public void initComponent() { public void initComponent() {
} }
@Override @Override
public void disposeComponent() { public void disposeComponent() {
} }
@NotNull @NotNull
@Override @Override
public String getComponentName() { public String getComponentName() {
return "DummyProjectComponent"; return "DummyProjectComponent";
} }
} }

View File

@ -9,9 +9,9 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DummyActionGroup extends ActionGroup { public class DummyActionGroup extends ActionGroup {
@NotNull @NotNull
@Override @Override
public AnAction[] getChildren(AnActionEvent anActionEvent) { public AnAction[] getChildren(AnActionEvent anActionEvent) {
return new GroupedAction[0]; return new GroupedAction[0];
} }
} }

View File

@ -8,8 +8,8 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class GroupedAction extends AnAction { public class GroupedAction extends AnAction {
@Override @Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) { public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
} }
} }

View File

@ -8,8 +8,8 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class GroupedToDefaultAction extends AnAction { public class GroupedToDefaultAction extends AnAction {
@Override @Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) { public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
} }
} }

View File

@ -9,16 +9,16 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class SimpleAction extends AnAction { public class SimpleAction extends AnAction {
@Override @Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) { public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
} }
@Override @Override
public void update(@NotNull AnActionEvent e) { public void update(@NotNull AnActionEvent e) {
//Make action visible and available only when project is defined //Make action visible and available only when project is defined
final Project project = e.getProject(); final Project project = e.getProject();
boolean isAvailable = project != null; boolean isAvailable = project != null;
e.getPresentation().setVisible(isAvailable); e.getPresentation().setVisible(isAvailable);
e.getPresentation().setEnabled(isAvailable); e.getPresentation().setEnabled(isAvailable);
} }
} }

View File

@ -1,55 +1,55 @@
<idea-plugin version="2" url="www.jetbrains.com"> <idea-plugin version="2" url="www.jetbrains.com">
<id>org.jetbrains.plugins.sample.ProjectModel</id> <id>org.jetbrains.plugins.sample.ProjectModel</id>
<name>Editor basics</name> <name>Editor basics</name>
<version>1.0</version> <version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor> <vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Project model illustration</description> <description>Project model illustration</description>
<change-notes>Initial commit</change-notes> <change-notes>Initial commit</change-notes>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description --> <!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/> <idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends> <depends>com.intellij.modules.lang</depends>
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here --> <!-- Add your extensions here -->
</extensions> </extensions>
<application-components> <application-components>
<!-- Add your application components here --> <!-- Add your application components here -->
</application-components> </application-components>
<project-components> <project-components>
<!-- Add your project components here --> <!-- Add your project components here -->
</project-components> </project-components>
<actions> <actions>
<action id="ProjectModel.SourceRoots" class="com.intellij.tutorials.project.model.ShowSourceRootsActions" <action id="ProjectModel.SourceRoots" class="com.intellij.tutorials.project.model.ShowSourceRootsActions"
text="Show Source Roots" text="Show Source Roots"
description="Illustrates how to get source roots"> description="Illustrates how to get source roots">
<add-to-group group-id="ToolsMenu" anchor="after"/> <add-to-group group-id="ToolsMenu" anchor="after"/>
</action> </action>
<action id="ProjectModel.ProjectSdk" class="com.intellij.tutorials.project.model.ProjectSdkAction" <action id="ProjectModel.ProjectSdk" class="com.intellij.tutorials.project.model.ProjectSdkAction"
text="Show Sdk Info" text="Show Sdk Info"
description="Illustrates how to get source roots"> description="Illustrates how to get source roots">
<add-to-group group-id="ToolsMenu" anchor="after"/> <add-to-group group-id="ToolsMenu" anchor="after"/>
</action> </action>
<action id="ProjectModel.ProjectFileIndex" <action id="ProjectModel.ProjectFileIndex"
class="com.intellij.tutorials.project.model.ProjectFileIndexSampleAction" class="com.intellij.tutorials.project.model.ProjectFileIndexSampleAction"
text="FileProjectIndex in Action" text="FileProjectIndex in Action"
description="Illustrates how to get source roots"> description="Illustrates how to get source roots">
<add-to-group group-id="EditorPopupMenu" anchor="last"/> <add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action> </action>
<action id="ProjectModel.ModificationAction" class="com.intellij.tutorials.project.model.ModificationAction" <action id="ProjectModel.ModificationAction" class="com.intellij.tutorials.project.model.ModificationAction"
text="Project Modification in Action" text="Project Modification in Action"
description="Illustrates how to get source roots"> description="Illustrates how to get source roots">
<add-to-group group-id="EditorPopupMenu" anchor="last"/> <add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action> </action>
<action id="ProjectModel.LibrariesAction" class="com.intellij.tutorials.project.model.LibrariesAction" <action id="ProjectModel.LibrariesAction" class="com.intellij.tutorials.project.model.LibrariesAction"
text="Libraries for file" text="Libraries for file"
description="Illustrates accessing libraries"> description="Illustrates accessing libraries">
<add-to-group group-id="EditorPopupMenu" anchor="last"/> <add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action> </action>
</actions> </actions>
</idea-plugin> </idea-plugin>

View File

@ -17,47 +17,48 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class LibrariesAction extends AnAction { public class LibrariesAction extends AnAction {
@Override @Override
public void update(@NotNull final AnActionEvent event) { public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject(); Project project = event.getProject();
if (project == null) return; if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE); Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) { if (element instanceof PsiClass) {
PsiFile psiFile = ((PsiClass) element).getContainingFile(); PsiFile psiFile = ((PsiClass) element).getContainingFile();
if (psiFile == null) return; if (psiFile == null) return;
VirtualFile virtualFile = psiFile.getVirtualFile(); VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) return; if (virtualFile == null) return;
event.getPresentation().setEnabledAndVisible(true); event.getPresentation().setEnabledAndVisible(true);
}
} }
}
@Override @Override
public void actionPerformed(@NotNull AnActionEvent event) { public void actionPerformed(@NotNull AnActionEvent event) {
Project project = event.getProject(); Project project = event.getProject();
if (project == null) return; if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE); Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) { if (element instanceof PsiClass) {
PsiFile psiFile = ((PsiClass) element).getContainingFile(); PsiFile psiFile = ((PsiClass) element).getContainingFile();
if (psiFile == null) return; if (psiFile == null) return;
VirtualFile virtualFile = psiFile.getVirtualFile(); VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) return; if (virtualFile == null) return;
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
StringBuilder jars = new StringBuilder(); StringBuilder jars = new StringBuilder();
for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) { for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) {
if (orderEntry instanceof LibraryOrderEntry) { if (orderEntry instanceof LibraryOrderEntry) {
final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry; final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry;
final Library library = libraryEntry.getLibrary(); final Library library = libraryEntry.getLibrary();
if (library == null) continue; if (library == null) continue;
VirtualFile[] files = library.getFiles(OrderRootType.CLASSES); VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
if (files.length == 0) continue; if (files.length == 0) continue;
for (VirtualFile jar : files) { for (VirtualFile jar : files) {
jars.append(jar.getName()).append(", "); jars.append(jar.getName()).append(", ");
} }
}
}
if (jars.length() > 0) {
Messages.showInfoMessage("Libraries for file " + virtualFile.getName() + ": " + jars.toString(), "Libraries Info");
}
} }
}
if (jars.length() > 0) {
Messages.showInfoMessage("Libraries for file " + virtualFile.getName() + ": " + jars.toString(),
"Libraries Info");
}
} }
}
} }

View File

@ -19,30 +19,30 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class ModificationAction extends AnAction { public class ModificationAction extends AnAction {
@Override @Override
public void actionPerformed(@NotNull final AnActionEvent event) { public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject(); Project project = event.getProject();
if (project == null) return; if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE); Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) { if (element instanceof PsiClass) {
PsiFile file = ((PsiClass) element).getContainingFile(); PsiFile file = ((PsiClass) element).getContainingFile();
if (file == null) return; if (file == null) return;
final VirtualFile virtualFile = file.getVirtualFile(); final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return; if (virtualFile == null) return;
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
final Module module = fileIndex.getModuleForFile(virtualFile); final Module module = fileIndex.getModuleForFile(virtualFile);
if (module == null) return; if (module == null) return;
if (!ModuleRootManager.getInstance(module).getFileIndex().isInContent(virtualFile)) { if (!ModuleRootManager.getInstance(module).getFileIndex().isInContent(virtualFile)) {
ModuleRootModificationUtil.addModuleLibrary(module, virtualFile.getUrl()); ModuleRootModificationUtil.addModuleLibrary(module, virtualFile.getUrl());
} }
}
} }
@Override }
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject(); @Override
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE); public void update(@NotNull final AnActionEvent event) {
event.getPresentation().setEnabledAndVisible(project != null && element != null); Project project = event.getProject();
} Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
event.getPresentation().setEnabledAndVisible(project != null && element != null);
}
} }

View File

@ -18,38 +18,38 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class ProjectFileIndexSampleAction extends AnAction { public class ProjectFileIndexSampleAction extends AnAction {
@Override @Override
public void update(@NotNull final AnActionEvent event) { public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject(); Project project = event.getProject();
final Editor editor = event.getData(CommonDataKeys.EDITOR); final Editor editor = event.getData(CommonDataKeys.EDITOR);
boolean visibility = project != null && editor != null; boolean visibility = project != null && editor != null;
event.getPresentation().setEnabledAndVisible(visibility); event.getPresentation().setEnabledAndVisible(visibility);
} }
@Override @Override
public void actionPerformed(@NotNull final AnActionEvent event) { public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject(); Project project = event.getProject();
final Editor editor = event.getData(CommonDataKeys.EDITOR); final Editor editor = event.getData(CommonDataKeys.EDITOR);
if (project == null || editor == null) return; if (project == null || editor == null) return;
Document document = editor.getDocument(); Document document = editor.getDocument();
FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance(); FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
VirtualFile virtualFile = fileDocumentManager.getFile(document); VirtualFile virtualFile = fileDocumentManager.getFile(document);
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
if (virtualFile != null) { if (virtualFile != null) {
Module module = projectFileIndex.getModuleForFile(virtualFile); Module module = projectFileIndex.getModuleForFile(virtualFile);
String moduleName; String moduleName;
moduleName = module != null ? module.getName() : "No module defined for file"; moduleName = module != null ? module.getName() : "No module defined for file";
VirtualFile moduleContentRoot = projectFileIndex.getContentRootForFile(virtualFile); VirtualFile moduleContentRoot = projectFileIndex.getContentRootForFile(virtualFile);
boolean isLibraryFile = projectFileIndex.isLibraryClassFile(virtualFile); boolean isLibraryFile = projectFileIndex.isLibraryClassFile(virtualFile);
boolean isInLibraryClasses = projectFileIndex.isInLibraryClasses(virtualFile); boolean isInLibraryClasses = projectFileIndex.isInLibraryClasses(virtualFile);
boolean isInLibrarySource = projectFileIndex.isInLibrarySource(virtualFile); boolean isInLibrarySource = projectFileIndex.isInLibrarySource(virtualFile);
Messages.showInfoMessage("Module: " + moduleName + "\n" + Messages.showInfoMessage("Module: " + moduleName + "\n" +
"Module content root: " + moduleContentRoot + "\n" + "Module content root: " + moduleContentRoot + "\n" +
"Is library file: " + isLibraryFile + "\n" + "Is library file: " + isLibraryFile + "\n" +
"Is in library classes" + isInLibraryClasses + "Is in library classes" + isInLibraryClasses +
"Is in library source" + isInLibrarySource, "Is in library source" + isInLibrarySource,
"Main File Info for" + virtualFile.getName()); "Main File Info for" + virtualFile.getName());
}
} }
}
} }

View File

@ -12,23 +12,23 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class ProjectSdkAction extends AnAction { public class ProjectSdkAction extends AnAction {
@Override @Override
public void actionPerformed(@NotNull final AnActionEvent event) { public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject(); Project project = event.getProject();
if (project != null) { if (project != null) {
String projectSDKName = ProjectRootManager.getInstance(project).getProjectSdkName(); String projectSDKName = ProjectRootManager.getInstance(project).getProjectSdkName();
String newProjectSdkName = "New Sdk Name"; String newProjectSdkName = "New Sdk Name";
ProjectRootManager.getInstance(project).setProjectSdkName(newProjectSdkName); ProjectRootManager.getInstance(project).setProjectSdkName(newProjectSdkName);
Messages.showInfoMessage(projectSDKName + " has changed to " + newProjectSdkName, "Project Sdk Info"); Messages.showInfoMessage(projectSDKName + " has changed to " + newProjectSdkName, "Project Sdk Info");
}
} }
}
@Override @Override
public void update(@NotNull final AnActionEvent event) { public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject(); Project project = event.getProject();
if (project != null) { if (project != null) {
Sdk sdk = ProjectRootManager.getInstance(project).getProjectSdk(); Sdk sdk = ProjectRootManager.getInstance(project).getProjectSdk();
event.getPresentation().setEnabledAndVisible(sdk != null); event.getPresentation().setEnabledAndVisible(sdk != null);
}
} }
}
} }

View File

@ -12,23 +12,24 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class ShowSourceRootsActions extends AnAction { public class ShowSourceRootsActions extends AnAction {
@Override @Override
public void actionPerformed(@NotNull final AnActionEvent event) { public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject(); Project project = event.getProject();
if (project == null) return; if (project == null) return;
String projectName = project.getName(); String projectName = project.getName();
StringBuilder sourceRootsList = new StringBuilder(); StringBuilder sourceRootsList = new StringBuilder();
VirtualFile[] vFiles = ProjectRootManager.getInstance(project).getContentSourceRoots(); VirtualFile[] vFiles = ProjectRootManager.getInstance(project).getContentSourceRoots();
for (VirtualFile file : vFiles) { for (VirtualFile file : vFiles) {
sourceRootsList.append(file.getUrl()).append("\n"); sourceRootsList.append(file.getUrl()).append("\n");
}
Messages.showInfoMessage("Source roots for the " + projectName + " plugin:\n" + sourceRootsList, "Project Properties");
} }
Messages.showInfoMessage("Source roots for the " + projectName + " plugin:\n" + sourceRootsList,
"Project Properties");
}
@Override @Override
public void update(@NotNull final AnActionEvent event) { public void update(@NotNull final AnActionEvent event) {
boolean visibility = event.getProject() != null; boolean visibility = event.getProject() != null;
event.getPresentation().setEnabled(visibility); event.getPresentation().setEnabled(visibility);
event.getPresentation().setVisible(visibility); event.getPresentation().setVisible(visibility);
} }
} }

View File

@ -1,30 +1,30 @@
<idea-plugin version="2" url="www.jetbrains.com"> <idea-plugin version="2" url="www.jetbrains.com">
<id>org.jetbrains.plugins.sample.ProjectViewPane</id> <id>org.jetbrains.plugins.sample.ProjectViewPane</id>
<name>Project View Pain Demo</name> <name>Project View Pain Demo</name>
<version>1.0</version> <version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor> <vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Project View Pain Demo</description> <description>Project View Pain Demo</description>
<change-notes>Initial commit</change-notes> <change-notes>Initial commit</change-notes>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description --> <!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/> <idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends> <depends>com.intellij.modules.lang</depends>
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<projectViewPane implementation="org.jetbrains.tutorials.view.pane.ImagesProjectViewPane"/> <projectViewPane implementation="org.jetbrains.tutorials.view.pane.ImagesProjectViewPane"/>
</extensions> </extensions>
<application-components> <application-components>
<!-- Add your application components here --> <!-- Add your application components here -->
</application-components> </application-components>
<project-components> <project-components>
<!-- Add your project components here --> <!-- Add your project components here -->
</project-components> </project-components>
<actions> <actions>
<!-- Add your actions here --> <!-- Add your actions here -->
</actions> </actions>
</idea-plugin> </idea-plugin>

View File

@ -26,146 +26,148 @@ import java.util.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class ImagesProjectNode extends AbstractTreeNode<VirtualFile> { public class ImagesProjectNode extends AbstractTreeNode<VirtualFile> {
private static final Key<Set<VirtualFile>> IMAGES_PROJECT_DIRS = Key.create("images.files.or.directories"); private static final Key<Set<VirtualFile>> IMAGES_PROJECT_DIRS = Key.create("images.files.or.directories");
public ImagesProjectNode(final Project project) { public ImagesProjectNode(final Project project) {
super(project, project.getBaseDir()); super(project, project.getBaseDir());
scanImages(project); scanImages(project);
subscribeToVFS(project); subscribeToVFS(project);
}
public ImagesProjectNode(Project project, VirtualFile file) {
super(project, file);
}
private void scanImages(Project project) {
addAllByExt(project, "png");
addAllByExt(project, "jpg");
}
private void addAllByExt(Project project, String ext) {
final Set<VirtualFile> imagesFiles = getImagesFiles(project);
final VirtualFile projectDir = project.getBaseDir();
for (VirtualFile file : FilenameIndex.getAllFilesByExt(project, ext)) {
while (file != null && !file.equals(projectDir)) {
imagesFiles.add(file);
file = file.getParent();
}
} }
}
public ImagesProjectNode(Project project, VirtualFile file) { @NotNull
super(project, file); private Set<VirtualFile> getImagesFiles(Project project) {
Set<VirtualFile> files = project.getUserData(IMAGES_PROJECT_DIRS);
if (files == null) {
files = new HashSet<VirtualFile>();
project.putUserData(IMAGES_PROJECT_DIRS, files);
} }
return files;
}
private void scanImages(Project project) { @Override
addAllByExt(project, "png"); protected VirtualFile getVirtualFile() {
addAllByExt(project, "jpg"); return getValue();
}
@NotNull
@Override
public Collection<? extends AbstractTreeNode> getChildren() {
final List<VirtualFile> files = new ArrayList<VirtualFile>(0);
for (VirtualFile file : getValue().getChildren()) {
if (getImagesFiles(myProject).contains(file)) {
files.add(file);
}
} }
if (files.isEmpty()) return Collections.emptyList();
private void addAllByExt(Project project, String ext) { final List<AbstractTreeNode> nodes = new ArrayList<AbstractTreeNode>(files.size());
final Set<VirtualFile> imagesFiles = getImagesFiles(project); final boolean alwaysOnTop = ((ProjectViewImpl) ProjectView.getInstance(myProject)).isFoldersAlwaysOnTop();
final VirtualFile projectDir = project.getBaseDir(); Collections.sort(files, new Comparator<VirtualFile>() {
for (VirtualFile file : FilenameIndex.getAllFilesByExt(project, ext)) { @Override
while (file != null && !file.equals(projectDir)) { public int compare(VirtualFile o1, VirtualFile o2) {
imagesFiles.add(file); if (alwaysOnTop) {
file = file.getParent(); final boolean d1 = o1.isDirectory();
} final boolean d2 = o2.isDirectory();
if (d1 && !d2) return -1;
if (!d1 && d2) return 1;
} }
return StringUtil.naturalCompare(o1.getName(), o2.getName());
}
});
for (VirtualFile file : files) {
nodes.add(new ImagesProjectNode(myProject, file));
} }
return nodes;
}
@NotNull @Override
private Set<VirtualFile> getImagesFiles(Project project) { protected void update(PresentationData data) {
Set<VirtualFile> files = project.getUserData(IMAGES_PROJECT_DIRS); data.setIcon(getValue().isDirectory() ? AllIcons.Nodes.Folder : getValue().getFileType().getIcon());
if (files == null) { data.setPresentableText(getValue().getName());
files = new HashSet<VirtualFile>(); }
project.putUserData(IMAGES_PROJECT_DIRS, files);
}
return files;
}
@Override
protected VirtualFile getVirtualFile() {
return getValue();
}
@NotNull @Override
@Override public boolean canNavigate() {
public Collection<? extends AbstractTreeNode> getChildren() { return !getValue().isDirectory();
final List<VirtualFile> files = new ArrayList<VirtualFile>(0); }
for (VirtualFile file : getValue().getChildren()) {
if (getImagesFiles(myProject).contains(file)) {
files.add(file);
}
}
if (files.isEmpty()) return Collections.emptyList();
final List<AbstractTreeNode> nodes = new ArrayList<AbstractTreeNode>(files.size());
final boolean alwaysOnTop = ((ProjectViewImpl) ProjectView.getInstance(myProject)).isFoldersAlwaysOnTop();
Collections.sort(files, new Comparator<VirtualFile>() {
@Override
public int compare(VirtualFile o1, VirtualFile o2) {
if (alwaysOnTop) {
final boolean d1 = o1.isDirectory();
final boolean d2 = o2.isDirectory();
if (d1 && !d2) return -1;
if (!d1 && d2) return 1;
}
return StringUtil.naturalCompare(o1.getName(), o2.getName()); @Override
} public boolean canNavigateToSource() {
return canNavigate();
}
@Override
public void navigate(boolean requestFocus) {
FileEditorManager.getInstance(myProject).openFile(getValue(), false);
}
private void subscribeToVFS(final Project project) {
final Alarm alarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, project);
LocalFileSystem.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
{
final VirtualFileAdapter me = this;
Disposer.register(project, new Disposable() {
@Override
public void dispose() {
LocalFileSystem.getInstance().removeVirtualFileListener(me);
}
}); });
for (VirtualFile file : files) { }
nodes.add(new ImagesProjectNode(myProject, file));
}
return nodes;
}
@Override @Override
protected void update(PresentationData data) { public void fileCreated(@NotNull VirtualFileEvent event) {
data.setIcon(getValue().isDirectory() ? AllIcons.Nodes.Folder : getValue().getFileType().getIcon()); handle(event);
data.setPresentableText(getValue().getName()); }
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
handle(event);
}
@Override void handle(VirtualFileEvent event) {
public boolean canNavigate() { final String filename = event.getFileName().toLowerCase();
return !getValue().isDirectory(); if (filename.endsWith(".png") || filename.endsWith(".jpg")) {
} alarm.cancelAllRequests();
alarm.addRequest(new Runnable() {
@Override public void run() {
public boolean canNavigateToSource() { getImagesFiles(project).clear();
return canNavigate(); scanImages(project);
} //noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override @Override
public void navigate(boolean requestFocus) { public void run() {
FileEditorManager.getInstance(myProject).openFile(getValue(), false); ProjectView.getInstance(myProject)
} .getProjectViewPaneById(ImagesProjectViewPane.ID)
.updateFromRoot(true);
private void subscribeToVFS(final Project project) {
final Alarm alarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, project);
LocalFileSystem.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
{
final VirtualFileAdapter me = this;
Disposer.register(project, new Disposable() {
@Override
public void dispose() {
LocalFileSystem.getInstance().removeVirtualFileListener(me);
}
});
}
@Override
public void fileCreated(@NotNull VirtualFileEvent event) {
handle(event);
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
handle(event);
}
void handle(VirtualFileEvent event) {
final String filename = event.getFileName().toLowerCase();
if (filename.endsWith(".png") || filename.endsWith(".jpg")) {
alarm.cancelAllRequests();
alarm.addRequest(new Runnable() {
public void run() {
getImagesFiles(project).clear();
scanImages(project);
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ProjectView.getInstance(myProject).getProjectViewPaneById(ImagesProjectViewPane.ID).updateFromRoot(true);
}
});
}
}, 1000);
} }
});
} }
}); }, 1000);
} }
}
});
}
} }

View File

@ -22,88 +22,88 @@ import javax.swing.tree.DefaultTreeModel;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class ImagesProjectViewPane extends AbstractProjectViewPSIPane { public class ImagesProjectViewPane extends AbstractProjectViewPSIPane {
public static final String ID = "IMAGES"; public static final String ID = "IMAGES";
protected ImagesProjectViewPane(Project project) { protected ImagesProjectViewPane(Project project) {
super(project); super(project);
} }
@Override @Override
public String getTitle() { public String getTitle() {
return "Images"; return "Images";
} }
@Override @Override
public javax.swing.Icon getIcon() { public javax.swing.Icon getIcon() {
return AllIcons.FileTypes.Custom; return AllIcons.FileTypes.Custom;
} }
@NotNull @NotNull
@Override @Override
public String getId() { public String getId() {
return ID; return ID;
} }
@Override @Override
public int getWeight() { public int getWeight() {
return 10;
}
@Override
public SelectInTarget createSelectInTarget() {
return new ProjectViewSelectInTarget(myProject) {
@Override
public String toString() {
return "images";
}
@Nullable
@Override
public String getMinorViewId() {
return "images";
}
@Override
public float getWeight() {
return 10; return 10;
} }
};
}
@Override @Override
public SelectInTarget createSelectInTarget() { protected ProjectAbstractTreeStructureBase createStructure() {
return new ProjectViewSelectInTarget(myProject) { return new ProjectTreeStructure(myProject, ID) {
@Override
protected AbstractTreeNode createRoot(Project project, ViewSettings settings) {
return new ImagesProjectNode(project);
}
@Override @Override
public String toString() { public Object[] getChildElements(Object element) {
return "images"; return super.getChildElements(element);
} }
};
}
@Nullable @Override
@Override protected ProjectViewTree createTree(DefaultTreeModel model) {
public String getMinorViewId() { return new ProjectViewTree(myProject, model) {
return "images"; @Override
} public DefaultMutableTreeNode getSelectedNode() {
return ImagesProjectViewPane.this.getSelectedNode();
}
@Override @Override
public float getWeight() { public boolean isRootVisible() {
return 10; return true;
} }
}; };
} }
@Override @Override
protected ProjectAbstractTreeStructureBase createStructure() { protected AbstractTreeUpdater createTreeUpdater(AbstractTreeBuilder builder) {
return new ProjectTreeStructure(myProject, ID) { return new AbstractTreeUpdater(builder);
@Override }
protected AbstractTreeNode createRoot(Project project, ViewSettings settings) {
return new ImagesProjectNode(project);
}
@Override
public Object[] getChildElements(Object element) {
return super.getChildElements(element);
}
};
}
@Override
protected ProjectViewTree createTree(DefaultTreeModel model) {
return new ProjectViewTree(myProject, model) {
@Override
public DefaultMutableTreeNode getSelectedNode() {
return ImagesProjectViewPane.this.getSelectedNode();
}
@Override
public boolean isRootVisible() {
return true;
}
};
}
@Override
protected AbstractTreeUpdater createTreeUpdater(AbstractTreeBuilder builder) {
return new AbstractTreeUpdater(builder);
}
} }

View File

@ -14,7 +14,9 @@
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here --> <!-- Add your extensions here -->
<moduleBuilder builderClass="org.jetbrains.tutorials.project.wizard.DemoModuleWizardStep" id="DEMO_STEP" order="first"/> <moduleBuilder builderClass="org.jetbrains.tutorials.project.wizard.DemoModuleWizardStep"
id="DEMO_STEP"
order="first"/>
</extensions> </extensions>
<application-components> <application-components>

View File

@ -15,26 +15,27 @@ import javax.swing.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoModuleWizardStep extends ModuleBuilder { public class DemoModuleWizardStep extends ModuleBuilder {
public void setupRootModel(ModifiableRootModel modifiableRootModel) throws ConfigurationException { public void setupRootModel(ModifiableRootModel modifiableRootModel) throws ConfigurationException {
} }
public ModuleType getModuleType() { public ModuleType getModuleType() {
return ModuleType.EMPTY; //or it could be other module type return ModuleType.EMPTY; //or it could be other module type
} }
@Override @Override
public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull ModulesProvider modulesProvider) { public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext,
return new ModuleWizardStep[]{new ModuleWizardStep() { @NotNull ModulesProvider modulesProvider) {
@Override return new ModuleWizardStep[]{new ModuleWizardStep() {
public JComponent getComponent() { @Override
return new JLabel("Put your content here"); public JComponent getComponent() {
} return new JLabel("Put your content here");
}
@Override @Override
public void updateDataModel() { public void updateDataModel() {
} }
}}; }};
} }
} }

View File

@ -2,15 +2,15 @@
<id>org.jetbrains.plugins.sample.RegisterActions</id> <id>org.jetbrains.plugins.sample.RegisterActions</id>
<name>Sample plugin for working with IntelliJ Action System</name> <name>Sample plugin for working with IntelliJ Action System</name>
<version>1.0</version> <version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor> <vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Illustration of Action System</description> <description>Illustration of Action System</description>
<change-notes>Initial commit</change-notes> <change-notes>Initial commit</change-notes>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description --> <!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/> <idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends> <depends>com.intellij.modules.lang</depends>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products <!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products --> on how to target different products -->
@ -39,45 +39,45 @@
The optional "use-shortcut-of" attribute specifies the ID of the action whose keyboard shortcut this action will use. The optional "use-shortcut-of" attribute specifies the ID of the action whose keyboard shortcut this action will use.
The optional "description" attribute specifies the text which is displayed in the status bar when the action is focused. The optional "description" attribute specifies the text which is displayed in the status bar when the action is focused.
The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the menu item. --> The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the menu item. -->
<action id="org.jetbrains.tutorials.actions.SimpleAction" class="org.jetbrains.tutorials.actions.SimpleAction" <action id="org.jetbrains.tutorials.actions.SimpleAction" class="org.jetbrains.tutorials.actions.SimpleAction"
text="Simple Action" description="IntelliJ Action System Demo"> text="Simple Action" description="IntelliJ Action System Demo">
<!-- The <keyboard-shortcut> node specifies the keyboard shortcut for the action. An action can have several keyboard shortcuts. <!-- The <keyboard-shortcut> node specifies the keyboard shortcut for the action. An action can have several keyboard shortcuts.
The mandatory "first-keystroke" attribute specifies the first keystroke of the action. The key strokes are specified according to the regular Swing rules. The mandatory "first-keystroke" attribute specifies the first keystroke of the action. The key strokes are specified according to the regular Swing rules.
The optional "second-keystroke" attribute specifies the second keystroke of the action. The optional "second-keystroke" attribute specifies the second keystroke of the action.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. --> constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<keyboard-shortcut first-keystroke="control alt A" second-keystroke="C" keymap="$default"/> <keyboard-shortcut first-keystroke="control alt A" second-keystroke="C" keymap="$default"/>
<!-- The <mouse-shortcut> node specifies the mouse shortcut for the action. An action can have several mouse shortcuts. <!-- The <mouse-shortcut> node specifies the mouse shortcut for the action. An action can have several mouse shortcuts.
The mandatory "keystroke" attribute specifies the clicks and modifiers for the action. It is defined as a sequence of words separated by spaces: The mandatory "keystroke" attribute specifies the clicks and modifiers for the action. It is defined as a sequence of words separated by spaces:
"button1", "button2", "button3" for the mouse buttons; "shift", "control", "meta", "alt", "altGraph" for the modifier keys; "button1", "button2", "button3" for the mouse buttons; "shift", "control", "meta", "alt", "altGraph" for the modifier keys;
"doubleClick" if the action is activated by a double-click of the button. "doubleClick" if the action is activated by a double-click of the button.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. --> constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<mouse-shortcut keystroke="control button3 doubleClick" keymap="$default"/> <mouse-shortcut keystroke="control button3 doubleClick" keymap="$default"/>
<!-- The <add-to-group> node specifies that the action should be added to an existing group. An action can be added to several groups. <!-- The <add-to-group> node specifies that the action should be added to an existing group. An action can be added to several groups.
The mandatory "group-id" attribute specifies the ID of the group to which the action is added. The mandatory "group-id" attribute specifies the ID of the group to which the action is added.
The group must be implemented by an instance of the DefaultActionGroup class. The group must be implemented by an instance of the DefaultActionGroup class.
The mandatory "anchor" attribute specifies the position of the action in the group relative to other actions. It can have the values The mandatory "anchor" attribute specifies the position of the action in the group relative to other actions. It can have the values
"first", "last", "before" and "after". "first", "last", "before" and "after".
The "relative-to-action" attribute is mandatory if the anchor is set to "before" and "after", and specifies the action before or after which The "relative-to-action" attribute is mandatory if the anchor is set to "before" and "after", and specifies the action before or after which
the current action is inserted. --> the current action is inserted. -->
<add-to-group group-id="ToolsMenu" anchor="first"/> <add-to-group group-id="ToolsMenu" anchor="first"/>
</action> </action>
<group id="SimpleGroup" text="Custom Action Group" popup="true"> <group id="SimpleGroup" text="Custom Action Group" popup="true">
<add-to-group group-id="EditorPopupMenu" anchor="first"/> <add-to-group group-id="EditorPopupMenu" anchor="first"/>
<action class="org.jetbrains.tutorials.actions.GroupedAction" id="org.jetbrains.tutorials.actions.GroupedAction" <action class="org.jetbrains.tutorials.actions.GroupedAction" id="org.jetbrains.tutorials.actions.GroupedAction"
text="Grouped Action" description="Grouped Action Demo"> text="Grouped Action" description="Grouped Action Demo">
</action> </action>
</group> </group>
<group id="CustomDefaultActionGroup" class="org.jetbrains.tutorials.actions.CustomDefaultActionGroup" popup="true" <group id="CustomDefaultActionGroup" class="org.jetbrains.tutorials.actions.CustomDefaultActionGroup" popup="true"
text="DefaultActionGroup Inheritor" description="Default Action Group Demo"> text="DefaultActionGroup Inheritor" description="Default Action Group Demo">
<add-to-group group-id="ToolsMenu" anchor="last"/> <add-to-group group-id="ToolsMenu" anchor="last"/>
<action class="org.jetbrains.tutorials.actions.CustomGroupedAction" id="CustomGroupedAction" <action class="org.jetbrains.tutorials.actions.CustomGroupedAction" id="CustomGroupedAction"
text="Custom Grouped Action" description="Custom Grouped Action Demo"/> text="Custom Grouped Action" description="Custom Grouped Action Demo"/>
</group> </group>
<group id="BaseActionGroup" class="org.jetbrains.tutorials.actions.BaseActionGroup" popup="true" <group id="BaseActionGroup" class="org.jetbrains.tutorials.actions.BaseActionGroup" popup="true"
text="ActionGroup Demo" description="Extending AnAction Demo"> text="ActionGroup Demo" description="Extending AnAction Demo">
<add-to-group group-id="ToolsMenu" anchor="first"/> <add-to-group group-id="ToolsMenu" anchor="first"/>
</group> </group>
</actions> </actions>
</idea-plugin> </idea-plugin>

View File

@ -9,18 +9,20 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class BaseActionGroup extends ActionGroup { public class BaseActionGroup extends ActionGroup {
@NotNull @NotNull
@Override
public AnAction[] getChildren(AnActionEvent anActionEvent) {
return new AnAction[]{new MyAction()};
}
class MyAction extends AnAction {
public MyAction() {
super("Dynamically Added Action");
}
@Override @Override
public AnAction[] getChildren(AnActionEvent anActionEvent) { public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
return new AnAction[]{new MyAction()}; //does nothing
}
class MyAction extends AnAction {
public MyAction() {
super("Dynamically Added Action");
}
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
//does nothing
}
} }
}
} }

View File

@ -10,11 +10,11 @@ import com.intellij.openapi.editor.Editor;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class CustomDefaultActionGroup extends DefaultActionGroup { public class CustomDefaultActionGroup extends DefaultActionGroup {
@Override @Override
public void update(AnActionEvent event) { public void update(AnActionEvent event) {
Editor editor = event.getData(CommonDataKeys.EDITOR); Editor editor = event.getData(CommonDataKeys.EDITOR);
event.getPresentation().setVisible(true); event.getPresentation().setVisible(true);
event.getPresentation().setEnabled(editor != null); event.getPresentation().setEnabled(editor != null);
event.getPresentation().setIcon(AllIcons.General.Error); event.getPresentation().setIcon(AllIcons.General.Error);
} }
} }

View File

@ -7,8 +7,8 @@ import com.intellij.openapi.actionSystem.AnActionEvent;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class CustomGroupedAction extends AnAction { public class CustomGroupedAction extends AnAction {
@Override @Override
public void actionPerformed(AnActionEvent anActionEvent) { public void actionPerformed(AnActionEvent anActionEvent) {
//Does nothing //Does nothing
} }
} }

View File

@ -7,13 +7,13 @@ import com.intellij.openapi.actionSystem.AnActionEvent;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class GroupedAction extends AnAction { public class GroupedAction extends AnAction {
@Override @Override
public void update(AnActionEvent event) { public void update(AnActionEvent event) {
event.getPresentation().setEnabledAndVisible(true); event.getPresentation().setEnabledAndVisible(true);
} }
@Override @Override
public void actionPerformed(AnActionEvent event) { public void actionPerformed(AnActionEvent event) {
//Does nothing //Does nothing
} }
} }

View File

@ -10,20 +10,20 @@ import com.intellij.openapi.ui.Messages;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class SimpleAction extends AnAction { public class SimpleAction extends AnAction {
@Override @Override
public void actionPerformed(AnActionEvent anActionEvent) { public void actionPerformed(AnActionEvent anActionEvent) {
Object navigatable = anActionEvent.getData(CommonDataKeys.NAVIGATABLE); Object navigatable = anActionEvent.getData(CommonDataKeys.NAVIGATABLE);
if (navigatable != null) { if (navigatable != null) {
Messages.showDialog(navigatable.toString(), "Selected Element:", new String[]{"OK"}, -1, null); Messages.showDialog(navigatable.toString(), "Selected Element:", new String[]{"OK"}, -1, null);
}
} }
}
@Override @Override
public void update(AnActionEvent anActionEvent) { public void update(AnActionEvent anActionEvent) {
final Project project = anActionEvent.getData(CommonDataKeys.PROJECT); final Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
if (project != null) if (project != null)
return; return;
Object navigatable = anActionEvent.getData(CommonDataKeys.NAVIGATABLE); Object navigatable = anActionEvent.getData(CommonDataKeys.NAVIGATABLE);
anActionEvent.getPresentation().setVisible(navigatable != null); anActionEvent.getPresentation().setVisible(navigatable != null);
} }
} }

View File

@ -1,30 +1,30 @@
<idea-plugin version="2" url="www.jetbrains.com"> <idea-plugin version="2" url="www.jetbrains.com">
<id>org.jetbrains.tutorials.run.configuration</id> <id>org.jetbrains.tutorials.run.configuration</id>
<name>Run Configuration</name> <name>Run Configuration</name>
<version>1.0</version> <version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor> <vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Illustration of working with run configurations</description> <description>Illustration of working with run configurations</description>
<change-notes>Initial commit</change-notes> <change-notes>Initial commit</change-notes>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description --> <!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/> <idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends> <depends>com.intellij.modules.lang</depends>
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<configurationType implementation="org.jetbrains.tutorials.run.configuration.DemoRunConfigurationType"/> <configurationType implementation="org.jetbrains.tutorials.run.configuration.DemoRunConfigurationType"/>
</extensions> </extensions>
<application-components> <application-components>
<!-- Add your application components here --> <!-- Add your application components here -->
</application-components> </application-components>
<project-components> <project-components>
<!-- Add your project components here --> <!-- Add your project components here -->
</project-components> </project-components>
<actions> <actions>
</actions> </actions>
</idea-plugin> </idea-plugin>

View File

@ -9,19 +9,19 @@ import com.intellij.openapi.project.Project;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoConfigurationFactory extends ConfigurationFactory { public class DemoConfigurationFactory extends ConfigurationFactory {
private static final String FACTORY_NAME = "Demo configuration factory"; private static final String FACTORY_NAME = "Demo configuration factory";
protected DemoConfigurationFactory(ConfigurationType type) { protected DemoConfigurationFactory(ConfigurationType type) {
super(type); super(type);
} }
@Override @Override
public RunConfiguration createTemplateConfiguration(Project project) { public RunConfiguration createTemplateConfiguration(Project project) {
return new DemoRunConfiguration(project, this, "Demo"); return new DemoRunConfiguration(project, this, "Demo");
} }
@Override @Override
public String getName() { public String getName() {
return FACTORY_NAME; return FACTORY_NAME;
} }
} }

View File

@ -13,24 +13,25 @@ import org.jetbrains.annotations.Nullable;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoRunConfiguration extends RunConfigurationBase { public class DemoRunConfiguration extends RunConfigurationBase {
protected DemoRunConfiguration(Project project, ConfigurationFactory factory, String name) { protected DemoRunConfiguration(Project project, ConfigurationFactory factory, String name) {
super(project, factory, name); super(project, factory, name);
} }
@NotNull @NotNull
@Override @Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() { public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new DemoSettingsEditor(); return new DemoSettingsEditor();
} }
@Override @Override
public void checkConfiguration() throws RuntimeConfigurationException { public void checkConfiguration() throws RuntimeConfigurationException {
} }
@Nullable @Nullable
@Override @Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException { public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws
return null; ExecutionException {
} return null;
}
} }

View File

@ -11,29 +11,29 @@ import javax.swing.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoRunConfigurationType implements ConfigurationType { public class DemoRunConfigurationType implements ConfigurationType {
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Demo"; return "Demo";
} }
@Override @Override
public String getConfigurationTypeDescription() { public String getConfigurationTypeDescription() {
return "Demo Run Configuration Type"; return "Demo Run Configuration Type";
} }
@Override @Override
public Icon getIcon() { public Icon getIcon() {
return AllIcons.General.Information; return AllIcons.General.Information;
} }
@NotNull @NotNull
@Override @Override
public String getId() { public String getId() {
return "DEMO_RUN_CONFIGURATION"; return "DEMO_RUN_CONFIGURATION";
} }
@Override @Override
public ConfigurationFactory[] getConfigurationFactories() { public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{new DemoConfigurationFactory(this)}; return new ConfigurationFactory[]{new DemoConfigurationFactory(this)};
} }
} }

View File

@ -17,28 +17,28 @@ import javax.swing.*;
* @author Anna Bulenkova * @author Anna Bulenkova
*/ */
public class DemoSettingsEditor extends SettingsEditor<DemoRunConfiguration> { public class DemoSettingsEditor extends SettingsEditor<DemoRunConfiguration> {
private JPanel myPanel; private JPanel myPanel;
private LabeledComponent<ComponentWithBrowseButton> myMainClass; private LabeledComponent<ComponentWithBrowseButton> myMainClass;
@Override @Override
protected void resetEditorFrom(DemoRunConfiguration demoRunConfiguration) { protected void resetEditorFrom(DemoRunConfiguration demoRunConfiguration) {
} }
@Override @Override
protected void applyEditorTo(DemoRunConfiguration demoRunConfiguration) throws ConfigurationException { protected void applyEditorTo(DemoRunConfiguration demoRunConfiguration) throws ConfigurationException {
} }
@NotNull @NotNull
@Override @Override
protected JComponent createEditor() { protected JComponent createEditor() {
return myPanel; return myPanel;
} }
private void createUIComponents() { private void createUIComponents() {
myMainClass = new LabeledComponent<ComponentWithBrowseButton>(); myMainClass = new LabeledComponent<ComponentWithBrowseButton>();
myMainClass.setComponent(new TextFieldWithBrowseButton()); myMainClass.setComponent(new TextFieldWithBrowseButton());
} }
} }

View File

@ -1,15 +1,15 @@
// This is a generated file. Not intended for manual editing. // This is a generated file. Not intended for manual editing.
package com.simpleplugin.parser; package com.simpleplugin.parser;
import com.intellij.lang.ASTNode;
import com.intellij.lang.LightPsiParser;
import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiBuilder.Marker; import com.intellij.lang.PsiBuilder.Marker;
import static com.simpleplugin.psi.SimpleTypes.*;
import static com.intellij.lang.parser.GeneratedParserUtilBase.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.lang.ASTNode;
import com.intellij.psi.tree.TokenSet;
import com.intellij.lang.PsiParser; import com.intellij.lang.PsiParser;
import com.intellij.lang.LightPsiParser; import com.intellij.psi.tree.IElementType;
import static com.intellij.lang.parser.GeneratedParserUtilBase.*;
import static com.simpleplugin.psi.SimpleTypes.*;
@SuppressWarnings({"SimplifiableIfStatement", "UnusedAssignment"}) @SuppressWarnings({"SimplifiableIfStatement", "UnusedAssignment"})
public class SimpleParser implements PsiParser, LightPsiParser { public class SimpleParser implements PsiParser, LightPsiParser {
@ -25,8 +25,7 @@ public class SimpleParser implements PsiParser, LightPsiParser {
Marker m = enter_section_(b, 0, _COLLAPSE_, null); Marker m = enter_section_(b, 0, _COLLAPSE_, null);
if (t == PROPERTY) { if (t == PROPERTY) {
r = property(b, 0); r = property(b, 0);
} } else {
else {
r = parse_root_(t, b, 0); r = parse_root_(t, b, 0);
} }
exit_section_(b, 0, m, t, r, true, TRUE_CONDITION); exit_section_(b, 0, m, t, r, true, TRUE_CONDITION);

View File

@ -1,10 +1,8 @@
// This is a generated file. Not intended for manual editing. // This is a generated file. Not intended for manual editing.
package com.simpleplugin.psi; package com.simpleplugin.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement;
public interface SimpleProperty extends SimpleNamedElement { public interface SimpleProperty extends SimpleNamedElement {

View File

@ -1,10 +1,10 @@
// This is a generated file. Not intended for manual editing. // This is a generated file. Not intended for manual editing.
package com.simpleplugin.psi; package com.simpleplugin.psi;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.PsiElement;
import com.intellij.lang.ASTNode; import com.intellij.lang.ASTNode;
import com.simpleplugin.psi.impl.*; import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.simpleplugin.psi.impl.SimplePropertyImpl;
public interface SimpleTypes { public interface SimpleTypes {
@ -19,7 +19,7 @@ public interface SimpleTypes {
class Factory { class Factory {
public static PsiElement createElement(ASTNode node) { public static PsiElement createElement(ASTNode node) {
IElementType type = node.getElementType(); IElementType type = node.getElementType();
if (type == PROPERTY) { if (type == PROPERTY) {
return new SimplePropertyImpl(node); return new SimplePropertyImpl(node);
} }
throw new AssertionError("Unknown element type: " + type); throw new AssertionError("Unknown element type: " + type);

View File

@ -1,9 +1,9 @@
// This is a generated file. Not intended for manual editing. // This is a generated file. Not intended for manual editing.
package com.simpleplugin.psi; package com.simpleplugin.psi;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import org.jetbrains.annotations.NotNull;
public class SimpleVisitor extends PsiElementVisitor { public class SimpleVisitor extends PsiElementVisitor {

View File

@ -1,15 +1,13 @@
// This is a generated file. Not intended for manual editing. // This is a generated file. Not intended for manual editing.
package com.simpleplugin.psi.impl; package com.simpleplugin.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode; import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil; import com.simpleplugin.psi.SimpleProperty;
import static com.simpleplugin.psi.SimpleTypes.*; import com.simpleplugin.psi.SimpleVisitor;
import com.simpleplugin.psi.*; import org.jetbrains.annotations.NotNull;
import com.intellij.navigation.ItemPresentation;
public class SimplePropertyImpl extends SimpleNamedElementImpl implements SimpleProperty { public class SimplePropertyImpl extends SimpleNamedElementImpl implements SimpleProperty {
@ -18,7 +16,7 @@ public class SimplePropertyImpl extends SimpleNamedElementImpl implements Simple
} }
public void accept(@NotNull PsiElementVisitor visitor) { public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof SimpleVisitor) ((SimpleVisitor)visitor).visitProperty(this); if (visitor instanceof SimpleVisitor) ((SimpleVisitor) visitor).visitProperty(this);
else super.accept(visitor); else super.accept(visitor);
} }

View File

@ -38,23 +38,25 @@
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here --> <!-- Add your extensions here -->
<fileTypeFactory implementation="com.simpleplugin.SimpleFileTypeFactory"/> <fileTypeFactory implementation="com.simpleplugin.SimpleFileTypeFactory"/>
<lang.parserDefinition language="Simple" implementationClass="com.simpleplugin.SimpleParserDefinition"/> <lang.parserDefinition language="Simple" implementationClass="com.simpleplugin.SimpleParserDefinition"/>
<lang.syntaxHighlighterFactory key="Simple" language="Simple" implementationClass="com.simpleplugin.SimpleSyntaxHighlighterFactory"/> <lang.syntaxHighlighterFactory key="Simple"
<colorSettingsPage implementation="com.simpleplugin.SimpleColorSettingsPage"/> language="Simple"
<annotator language="JAVA" implementationClass="com.simpleplugin.SimpleAnnotator"/> implementationClass="com.simpleplugin.SimpleSyntaxHighlighterFactory"/>
<codeInsight.lineMarkerProvider language="JAVA" implementationClass="com.simpleplugin.SimpleLineMarkerProvider"/> <colorSettingsPage implementation="com.simpleplugin.SimpleColorSettingsPage"/>
<completion.contributor language="Simple" implementationClass="com.simpleplugin.SimpleCompletionContributor"/> <annotator language="JAVA" implementationClass="com.simpleplugin.SimpleAnnotator"/>
<psi.referenceContributor implementation="com.simpleplugin.SimpleReferenceContributor"/> <codeInsight.lineMarkerProvider language="JAVA" implementationClass="com.simpleplugin.SimpleLineMarkerProvider"/>
<lang.findUsagesProvider language="Simple" implementationClass="com.simpleplugin.SimpleFindUsagesProvider"/> <completion.contributor language="Simple" implementationClass="com.simpleplugin.SimpleCompletionContributor"/>
<lang.refactoringSupport language="Simple" implementationClass="com.simpleplugin.SimpleRefactoringSupportProvider"/> <psi.referenceContributor implementation="com.simpleplugin.SimpleReferenceContributor"/>
<lang.foldingBuilder language="JAVA" implementationClass="com.simpleplugin.SimpleFoldingBuilder"/> <lang.findUsagesProvider language="Simple" implementationClass="com.simpleplugin.SimpleFindUsagesProvider"/>
<gotoSymbolContributor implementation="com.simpleplugin.SimpleChooseByNameContributor"/> <lang.refactoringSupport language="Simple" implementationClass="com.simpleplugin.SimpleRefactoringSupportProvider"/>
<lang.psiStructureViewFactory language="Simple" implementationClass="com.simpleplugin.SimpleStructureViewFactory"/> <lang.foldingBuilder language="JAVA" implementationClass="com.simpleplugin.SimpleFoldingBuilder"/>
<lang.formatter language="Simple" implementationClass="com.simpleplugin.SimpleFormattingModelBuilder"/> <gotoSymbolContributor implementation="com.simpleplugin.SimpleChooseByNameContributor"/>
<codeStyleSettingsProvider implementation="com.simpleplugin.SimpleCodeStyleSettingsProvider"/> <lang.psiStructureViewFactory language="Simple" implementationClass="com.simpleplugin.SimpleStructureViewFactory"/>
<langCodeStyleSettingsProvider implementation="com.simpleplugin.SimpleLanguageCodeStyleSettingsProvider"/> <lang.formatter language="Simple" implementationClass="com.simpleplugin.SimpleFormattingModelBuilder"/>
<lang.commenter language="Simple" implementationClass="com.simpleplugin.SimpleCommenter"/> <codeStyleSettingsProvider implementation="com.simpleplugin.SimpleCodeStyleSettingsProvider"/>
<todoIndexer filetype="Simple file" implementationClass="com.simpleplugin.SimpleTodoIndexer"/> <langCodeStyleSettingsProvider implementation="com.simpleplugin.SimpleLanguageCodeStyleSettingsProvider"/>
<lang.commenter language="Simple" implementationClass="com.simpleplugin.SimpleCommenter"/>
<todoIndexer filetype="Simple file" implementationClass="com.simpleplugin.SimpleTodoIndexer"/>
</extensions> </extensions>
</idea-plugin> </idea-plugin>

View File

@ -4,7 +4,7 @@ import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.lang.ASTNode; import com.intellij.lang.ASTNode;
import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
@ -27,73 +27,76 @@ import org.jetbrains.annotations.NotNull;
import java.util.Collection; import java.util.Collection;
class CreatePropertyQuickFix extends BaseIntentionAction { class CreatePropertyQuickFix extends BaseIntentionAction {
private String key; private String key;
CreatePropertyQuickFix(String key) { CreatePropertyQuickFix(String key) {
this.key = key; this.key = key;
} }
@NotNull @NotNull
@Override @Override
public String getText() { public String getText() {
return "Create property"; return "Create property";
} }
@NotNull @NotNull
@Override @Override
public String getFamilyName() { public String getFamilyName() {
return "Simple properties"; return "Simple properties";
} }
@Override @Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return true; return true;
} }
@Override @Override
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) throws IncorrectOperationException { public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) throws
ApplicationManager.getApplication().invokeLater(new Runnable() { IncorrectOperationException {
@Override ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() { @Override
Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, SimpleFileType.INSTANCE, public void run() {
GlobalSearchScope.allScope(project)); Collection<VirtualFile> virtualFiles =
if (virtualFiles.size() == 1) { FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, SimpleFileType.INSTANCE,
createProperty(project, virtualFiles.iterator().next()); GlobalSearchScope.allScope(project));
} else { if (virtualFiles.size() == 1) {
final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileDescriptor(SimpleFileType.INSTANCE); createProperty(project, virtualFiles.iterator().next());
descriptor.setRoots(project.getBaseDir()); } else {
final VirtualFile file = FileChooser.chooseFile(descriptor, project, null); final FileChooserDescriptor descriptor =
if (file != null) { FileChooserDescriptorFactory.createSingleFileDescriptor(SimpleFileType.INSTANCE);
createProperty(project, file); descriptor.setRoots(project.getBaseDir());
} final VirtualFile file = FileChooser.chooseFile(descriptor, project, null);
} if (file != null) {
} createProperty(project, file);
}); }
} }
}
});
}
private void createProperty(final Project project, final VirtualFile file) { private void createProperty(final Project project, final VirtualFile file) {
new WriteCommandAction.Simple(project) { new WriteCommandAction.Simple(project) {
@Override @Override
public void run() { public void run() {
SimpleFile simpleFile = (SimpleFile) PsiManager.getInstance(project).findFile(file); SimpleFile simpleFile = (SimpleFile) PsiManager.getInstance(project).findFile(file);
ASTNode lastChildNode = simpleFile.getNode().getLastChildNode(); ASTNode lastChildNode = simpleFile.getNode().getLastChildNode();
if (lastChildNode != null && !lastChildNode.getElementType().equals(SimpleTypes.CRLF)) { if (lastChildNode != null && !lastChildNode.getElementType().equals(SimpleTypes.CRLF)) {
simpleFile.getNode().addChild(SimpleElementFactory.createCRLF(project).getNode()); simpleFile.getNode().addChild(SimpleElementFactory.createCRLF(project).getNode());
} }
// IMPORTANT: change spaces to escaped spaces or the new node will only have the first word for the key // IMPORTANT: change spaces to escaped spaces or the new node will only have the first word for the key
SimpleProperty property = SimpleElementFactory.createProperty(project, key.replaceAll(" ", "\\\\ "), ""); SimpleProperty property = SimpleElementFactory.createProperty(project, key.replaceAll(" ", "\\\\ "), "");
simpleFile.getNode().addChild(property.getNode()); simpleFile.getNode().addChild(property.getNode());
((Navigatable) property.getLastChild().getNavigationElement()).navigate(true); ((Navigatable) property.getLastChild().getNavigationElement()).navigate(true);
FileEditorManager.getInstance(project).getSelectedTextEditor().getCaretModel(). FileEditorManager.getInstance(project).getSelectedTextEditor().getCaretModel().
moveCaretRelatively(2, 0, false, false, false); moveCaretRelatively(2, 0, false, false, false);
// almost the same thing but manipulating plain text of the document instead of PSI // almost the same thing but manipulating plain text of the document instead of PSI
// FileEditorManager.getInstance(project).openFile(file, true); // FileEditorManager.getInstance(project).openFile(file, true);
// final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); // final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
// final Document document = editor.getDocument(); // final Document document = editor.getDocument();
// document.insertString(document.getTextLength(), "\n" + key.replaceAll(" ", "\\\\ ") + " = "); // document.insertString(document.getTextLength(), "\n" + key.replaceAll(" ", "\\\\ ") + " = ");
// editor.getCaretModel().getPrimaryCaret().moveToOffset(document.getTextLength()); // editor.getCaretModel().getPrimaryCaret().moveToOffset(document.getTextLength());
} }
}.execute(); }.execute();
} }
} }

View File

@ -14,28 +14,28 @@ import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
public class SimpleAnnotator implements Annotator { public class SimpleAnnotator implements Annotator {
@Override @Override
public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) { public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof PsiLiteralExpression) { if (element instanceof PsiLiteralExpression) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) element; PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
String value = literalExpression.getValue() instanceof String ? (String)literalExpression.getValue() : null; String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
if (value != null && value.startsWith("simple"+":")) { if (value != null && value.startsWith("simple" + ":")) {
Project project = element.getProject(); Project project = element.getProject();
String key = value.substring(7); String key = value.substring(7);
List<SimpleProperty> properties = SimpleUtil.findProperties(project, key); List<SimpleProperty> properties = SimpleUtil.findProperties(project, key);
if (properties.size() == 1) { if (properties.size() == 1) {
TextRange range = new TextRange(element.getTextRange().getStartOffset() + 7, TextRange range = new TextRange(element.getTextRange().getStartOffset() + 7,
element.getTextRange().getStartOffset() + 7); element.getTextRange().getStartOffset() + 7);
Annotation annotation = holder.createInfoAnnotation(range, null); Annotation annotation = holder.createInfoAnnotation(range, null);
annotation.setTextAttributes(DefaultLanguageHighlighterColors.LINE_COMMENT); annotation.setTextAttributes(DefaultLanguageHighlighterColors.LINE_COMMENT);
} else if (properties.size() == 0) { } else if (properties.size() == 0) {
TextRange range = new TextRange(element.getTextRange().getStartOffset() + 8, TextRange range = new TextRange(element.getTextRange().getStartOffset() + 8,
element.getTextRange().getEndOffset()); element.getTextRange().getEndOffset());
holder.createErrorAnnotation(range, "Unresolved property"). holder.createErrorAnnotation(range, "Unresolved property").
registerFix(new CreatePropertyQuickFix(key)); registerFix(new CreatePropertyQuickFix(key));
}
}
} }
}
} }
}
} }

View File

@ -12,46 +12,46 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class SimpleBlock extends AbstractBlock { public class SimpleBlock extends AbstractBlock {
private SpacingBuilder spacingBuilder; private SpacingBuilder spacingBuilder;
protected SimpleBlock(@NotNull ASTNode node, @Nullable Wrap wrap, @Nullable Alignment alignment, protected SimpleBlock(@NotNull ASTNode node, @Nullable Wrap wrap, @Nullable Alignment alignment,
SpacingBuilder spacingBuilder) { SpacingBuilder spacingBuilder) {
super(node, wrap, alignment); super(node, wrap, alignment);
this.spacingBuilder = spacingBuilder; this.spacingBuilder = spacingBuilder;
} }
@Override @Override
protected List<Block> buildChildren() { protected List<Block> buildChildren() {
List<Block> blocks = new ArrayList<Block>(); List<Block> blocks = new ArrayList<Block>();
ASTNode child = myNode.getFirstChildNode(); ASTNode child = myNode.getFirstChildNode();
ASTNode previousChild = null; ASTNode previousChild = null;
while (child != null) { while (child != null) {
if (child.getElementType() != TokenType.WHITE_SPACE && if (child.getElementType() != TokenType.WHITE_SPACE &&
(previousChild == null || previousChild.getElementType() != SimpleTypes.CRLF || (previousChild == null || previousChild.getElementType() != SimpleTypes.CRLF ||
child.getElementType() != SimpleTypes.CRLF)) { child.getElementType() != SimpleTypes.CRLF)) {
Block block = new SimpleBlock(child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(), Block block = new SimpleBlock(child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(),
spacingBuilder); spacingBuilder);
blocks.add(block); blocks.add(block);
} }
previousChild = child; previousChild = child;
child = child.getTreeNext(); child = child.getTreeNext();
}
return blocks;
} }
return blocks;
}
@Override @Override
public Indent getIndent() { public Indent getIndent() {
return Indent.getNoneIndent(); return Indent.getNoneIndent();
} }
@Nullable @Nullable
@Override @Override
public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) { public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) {
return spacingBuilder.getSpacing(this, child1, child2); return spacingBuilder.getSpacing(this, child1, child2);
} }
@Override @Override
public boolean isLeaf() { public boolean isLeaf() {
return myNode.getFirstChildNode() == null; return myNode.getFirstChildNode() == null;
} }
} }

View File

@ -10,24 +10,24 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class SimpleChooseByNameContributor implements ChooseByNameContributor { public class SimpleChooseByNameContributor implements ChooseByNameContributor {
@NotNull @NotNull
@Override @Override
public String[] getNames(Project project, boolean includeNonProjectItems) { public String[] getNames(Project project, boolean includeNonProjectItems) {
List<SimpleProperty> properties = SimpleUtil.findProperties(project); List<SimpleProperty> properties = SimpleUtil.findProperties(project);
List<String> names = new ArrayList<String>(properties.size()); List<String> names = new ArrayList<String>(properties.size());
for (SimpleProperty property : properties) { for (SimpleProperty property : properties) {
if (property.getKey() != null && property.getKey().length() > 0) { if (property.getKey() != null && property.getKey().length() > 0) {
names.add(property.getKey()); names.add(property.getKey());
} }
}
return names.toArray(new String[names.size()]);
} }
return names.toArray(new String[names.size()]);
}
@NotNull @NotNull
@Override @Override
public NavigationItem[] getItemsByName(String name, String pattern, Project project, boolean includeNonProjectItems) { public NavigationItem[] getItemsByName(String name, String pattern, Project project, boolean includeNonProjectItems) {
// todo include non project items // todo include non project items
List<SimpleProperty> properties = SimpleUtil.findProperties(project, name); List<SimpleProperty> properties = SimpleUtil.findProperties(project, name);
return properties.toArray(new NavigationItem[properties.size()]); return properties.toArray(new NavigationItem[properties.size()]);
} }
} }

View File

@ -4,7 +4,7 @@ import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CustomCodeStyleSettings; import com.intellij.psi.codeStyle.CustomCodeStyleSettings;
public class SimpleCodeStyleSettings extends CustomCodeStyleSettings { public class SimpleCodeStyleSettings extends CustomCodeStyleSettings {
public SimpleCodeStyleSettings(CodeStyleSettings settings) { public SimpleCodeStyleSettings(CodeStyleSettings settings) {
super("SimpleCodeStyleSettings", settings); super("SimpleCodeStyleSettings", settings);
} }
} }

View File

@ -11,37 +11,37 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class SimpleCodeStyleSettingsProvider extends CodeStyleSettingsProvider { public class SimpleCodeStyleSettingsProvider extends CodeStyleSettingsProvider {
@Override @Override
public CustomCodeStyleSettings createCustomSettings(CodeStyleSettings settings) { public CustomCodeStyleSettings createCustomSettings(CodeStyleSettings settings) {
return new SimpleCodeStyleSettings(settings); return new SimpleCodeStyleSettings(settings);
} }
@Nullable @Nullable
@Override @Override
public String getConfigurableDisplayName() { public String getConfigurableDisplayName() {
return "Simple"; return "Simple";
} }
@NotNull @NotNull
@Override @Override
public Configurable createSettingsPage(CodeStyleSettings settings, CodeStyleSettings originalSettings) { public Configurable createSettingsPage(CodeStyleSettings settings, CodeStyleSettings originalSettings) {
return new CodeStyleAbstractConfigurable(settings, originalSettings, "Simple") { return new CodeStyleAbstractConfigurable(settings, originalSettings, "Simple") {
@Override @Override
protected CodeStyleAbstractPanel createPanel(CodeStyleSettings settings) { protected CodeStyleAbstractPanel createPanel(CodeStyleSettings settings) {
return new SimpleCodeStyleMainPanel(getCurrentSettings(), settings); return new SimpleCodeStyleMainPanel(getCurrentSettings(), settings);
} }
@Nullable @Nullable
@Override @Override
public String getHelpTopic() { public String getHelpTopic() {
return null; return null;
} }
}; };
} }
private static class SimpleCodeStyleMainPanel extends TabbedLanguageCodeStylePanel { private static class SimpleCodeStyleMainPanel extends TabbedLanguageCodeStylePanel {
public SimpleCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) { public SimpleCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) {
super(SimpleLanguage.INSTANCE, currentSettings, settings); super(SimpleLanguage.INSTANCE, currentSettings, settings);
}
} }
}
} }

View File

@ -12,62 +12,62 @@ import javax.swing.*;
import java.util.Map; import java.util.Map;
public class SimpleColorSettingsPage implements ColorSettingsPage { public class SimpleColorSettingsPage implements ColorSettingsPage {
private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{
new AttributesDescriptor("Key", SimpleSyntaxHighlighter.KEY), new AttributesDescriptor("Key", SimpleSyntaxHighlighter.KEY),
new AttributesDescriptor("Separator", SimpleSyntaxHighlighter.SEPARATOR), new AttributesDescriptor("Separator", SimpleSyntaxHighlighter.SEPARATOR),
new AttributesDescriptor("Value", SimpleSyntaxHighlighter.VALUE), new AttributesDescriptor("Value", SimpleSyntaxHighlighter.VALUE),
}; };
@Nullable @Nullable
@Override @Override
public Icon getIcon() { public Icon getIcon() {
return SimpleIcons.FILE; return SimpleIcons.FILE;
} }
@NotNull @NotNull
@Override @Override
public SyntaxHighlighter getHighlighter() { public SyntaxHighlighter getHighlighter() {
return new SimpleSyntaxHighlighter(); return new SimpleSyntaxHighlighter();
} }
@NotNull @NotNull
@Override @Override
public String getDemoText() { public String getDemoText() {
return "# You are reading the \".properties\" entry.\n" + return "# You are reading the \".properties\" entry.\n" +
"! The exclamation mark can also mark text as comments.\n" + "! The exclamation mark can also mark text as comments.\n" +
"website = http://en.wikipedia.org/\n" + "website = http://en.wikipedia.org/\n" +
"language = English\n" + "language = English\n" +
"# The backslash below tells the application to continue reading\n" + "# The backslash below tells the application to continue reading\n" +
"# the value onto the next line.\n" + "# the value onto the next line.\n" +
"message = Welcome to \\\n" + "message = Welcome to \\\n" +
" Wikipedia!\n" + " Wikipedia!\n" +
"# Add spaces to the key\n" + "# Add spaces to the key\n" +
"key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" + "key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" +
"# Unicode\n" + "# Unicode\n" +
"tab : \\u0009"; "tab : \\u0009";
} }
@Nullable @Nullable
@Override @Override
public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() {
return null; return null;
} }
@NotNull @NotNull
@Override @Override
public AttributesDescriptor[] getAttributeDescriptors() { public AttributesDescriptor[] getAttributeDescriptors() {
return DESCRIPTORS; return DESCRIPTORS;
} }
@NotNull @NotNull
@Override @Override
public ColorDescriptor[] getColorDescriptors() { public ColorDescriptor[] getColorDescriptors() {
return ColorDescriptor.EMPTY_ARRAY; return ColorDescriptor.EMPTY_ARRAY;
} }
@NotNull @NotNull
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Simple"; return "Simple";
} }
} }

View File

@ -4,33 +4,33 @@ import com.intellij.lang.Commenter;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class SimpleCommenter implements Commenter { public class SimpleCommenter implements Commenter {
@Nullable @Nullable
@Override @Override
public String getLineCommentPrefix() { public String getLineCommentPrefix() {
return "#"; return "#";
} }
@Nullable @Nullable
@Override @Override
public String getBlockCommentPrefix() { public String getBlockCommentPrefix() {
return ""; return "";
} }
@Nullable @Nullable
@Override @Override
public String getBlockCommentSuffix() { public String getBlockCommentSuffix() {
return null; return null;
} }
@Nullable @Nullable
@Override @Override
public String getCommentedBlockCommentPrefix() { public String getCommentedBlockCommentPrefix() {
return null; return null;
} }
@Nullable @Nullable
@Override @Override
public String getCommentedBlockCommentSuffix() { public String getCommentedBlockCommentSuffix() {
return null; return null;
} }
} }

View File

@ -8,16 +8,16 @@ import com.simpleplugin.psi.SimpleTypes;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class SimpleCompletionContributor extends CompletionContributor { public class SimpleCompletionContributor extends CompletionContributor {
public SimpleCompletionContributor() { public SimpleCompletionContributor() {
extend(CompletionType.BASIC, extend(CompletionType.BASIC,
PlatformPatterns.psiElement(SimpleTypes.VALUE).withLanguage(SimpleLanguage.INSTANCE), PlatformPatterns.psiElement(SimpleTypes.VALUE).withLanguage(SimpleLanguage.INSTANCE),
new CompletionProvider<CompletionParameters>() { new CompletionProvider<CompletionParameters>() {
public void addCompletions(@NotNull CompletionParameters parameters, public void addCompletions(@NotNull CompletionParameters parameters,
ProcessingContext context, ProcessingContext context,
@NotNull CompletionResultSet resultSet) { @NotNull CompletionResultSet resultSet) {
resultSet.addElement(LookupElementBuilder.create("Hello")); resultSet.addElement(LookupElementBuilder.create("Hello"));
} }
} }
); );
} }
} }

View File

@ -7,33 +7,33 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*; import javax.swing.*;
public class SimpleFileType extends LanguageFileType { public class SimpleFileType extends LanguageFileType {
public static final SimpleFileType INSTANCE = new SimpleFileType(); public static final SimpleFileType INSTANCE = new SimpleFileType();
private SimpleFileType() { private SimpleFileType() {
super(SimpleLanguage.INSTANCE); super(SimpleLanguage.INSTANCE);
} }
@NotNull @NotNull
@Override @Override
public String getName() { public String getName() {
return "Simple file"; return "Simple file";
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription() {
return "Simple language file"; return "Simple language file";
} }
@NotNull @NotNull
@Override @Override
public String getDefaultExtension() { public String getDefaultExtension() {
return "simple"; return "simple";
} }
@Nullable @Nullable
@Override @Override
public Icon getIcon() { public Icon getIcon() {
return SimpleIcons.FILE; return SimpleIcons.FILE;
} }
} }

View File

@ -4,9 +4,9 @@ import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory; import com.intellij.openapi.fileTypes.FileTypeFactory;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class SimpleFileTypeFactory extends FileTypeFactory{ public class SimpleFileTypeFactory extends FileTypeFactory {
@Override @Override
public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) { public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(SimpleFileType.INSTANCE, "simple"); fileTypeConsumer.consume(SimpleFileType.INSTANCE, "simple");
} }
} }

View File

@ -6,14 +6,14 @@ import com.intellij.psi.impl.cache.impl.OccurrenceConsumer;
import com.intellij.psi.search.UsageSearchContext; import com.intellij.psi.search.UsageSearchContext;
public class SimpleFilterLexer extends BaseFilterLexer { public class SimpleFilterLexer extends BaseFilterLexer {
public SimpleFilterLexer(final Lexer originalLexer, final OccurrenceConsumer table) { public SimpleFilterLexer(final Lexer originalLexer, final OccurrenceConsumer table) {
super(originalLexer, table); super(originalLexer, table);
} }
@Override @Override
public void advance() { public void advance() {
scanWordsInToken(UsageSearchContext.IN_COMMENTS, false, false); scanWordsInToken(UsageSearchContext.IN_COMMENTS, false, false);
advanceTodoItemCountsInToken(); advanceTodoItemCountsInToken();
myDelegate.advance(); myDelegate.advance();
} }
} }

View File

@ -12,51 +12,53 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class SimpleFindUsagesProvider implements FindUsagesProvider { public class SimpleFindUsagesProvider implements FindUsagesProvider {
@Nullable @Nullable
@Override @Override
public WordsScanner getWordsScanner() { public WordsScanner getWordsScanner() {
return new DefaultWordsScanner(new SimpleLexerAdapter(), return new DefaultWordsScanner(new SimpleLexerAdapter(),
TokenSet.create(SimpleTypes.KEY), TokenSet.create(SimpleTypes.COMMENT), TokenSet.EMPTY); TokenSet.create(SimpleTypes.KEY),
} TokenSet.create(SimpleTypes.COMMENT),
TokenSet.EMPTY);
}
@Override @Override
public boolean canFindUsagesFor(@NotNull PsiElement psiElement) { public boolean canFindUsagesFor(@NotNull PsiElement psiElement) {
return psiElement instanceof PsiNamedElement; return psiElement instanceof PsiNamedElement;
} }
@Nullable @Nullable
@Override @Override
public String getHelpId(@NotNull PsiElement psiElement) { public String getHelpId(@NotNull PsiElement psiElement) {
return null; return null;
} }
@NotNull @NotNull
@Override @Override
public String getType(@NotNull PsiElement element) { public String getType(@NotNull PsiElement element) {
if (element instanceof SimpleProperty) { if (element instanceof SimpleProperty) {
return "simple property"; return "simple property";
} else { } else {
return ""; return "";
}
} }
}
@NotNull @NotNull
@Override @Override
public String getDescriptiveName(@NotNull PsiElement element) { public String getDescriptiveName(@NotNull PsiElement element) {
if (element instanceof SimpleProperty) { if (element instanceof SimpleProperty) {
return ((SimpleProperty) element).getKey(); return ((SimpleProperty) element).getKey();
} else { } else {
return ""; return "";
}
} }
}
@NotNull @NotNull
@Override @Override
public String getNodeText(@NotNull PsiElement element, boolean useFullName) { public String getNodeText(@NotNull PsiElement element, boolean useFullName) {
if (element instanceof SimpleProperty) { if (element instanceof SimpleProperty) {
return ((SimpleProperty) element).getKey() + ":" + ((SimpleProperty) element).getValue(); return ((SimpleProperty) element).getKey() + ":" + ((SimpleProperty) element).getValue();
} else { } else {
return ""; return "";
}
} }
}
} }

View File

@ -19,47 +19,50 @@ import java.util.Collection;
import java.util.List; import java.util.List;
public class SimpleFoldingBuilder extends FoldingBuilderEx { public class SimpleFoldingBuilder extends FoldingBuilderEx {
@NotNull @NotNull
@Override @Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) { public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
FoldingGroup group = FoldingGroup.newGroup("simple"); FoldingGroup group = FoldingGroup.newGroup("simple");
List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>(); List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();
Collection<PsiLiteralExpression> literalExpressions = PsiTreeUtil.findChildrenOfType(root, PsiLiteralExpression.class); Collection<PsiLiteralExpression> literalExpressions =
for (final PsiLiteralExpression literalExpression : literalExpressions) { PsiTreeUtil.findChildrenOfType(root, PsiLiteralExpression.class);
String value = literalExpression.getValue() instanceof String ? (String)literalExpression.getValue() : null; for (final PsiLiteralExpression literalExpression : literalExpressions) {
String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
if (value != null && value.startsWith("simple:")) { if (value != null && value.startsWith("simple:")) {
Project project = literalExpression.getProject(); Project project = literalExpression.getProject();
String key = value.substring(7); String key = value.substring(7);
final List<SimpleProperty> properties = SimpleUtil.findProperties(project, key); final List<SimpleProperty> properties = SimpleUtil.findProperties(project, key);
if (properties.size() == 1) { if (properties.size() == 1) {
descriptors.add(new FoldingDescriptor(literalExpression.getNode(), descriptors.add(new FoldingDescriptor(literalExpression.getNode(),
new TextRange(literalExpression.getTextRange().getStartOffset() + 1, new TextRange(literalExpression.getTextRange().getStartOffset() + 1,
literalExpression.getTextRange().getEndOffset() - 1), group) { literalExpression.getTextRange().getEndOffset() - 1),
@Nullable group) {
@Override @Nullable
public String getPlaceholderText() { @Override
// IMPORTANT: keys can come with no values, so a test for null is needed public String getPlaceholderText() {
// IMPORTANT: Convert embedded \n to backslash n, so that the string will look like it has LF embedded in it and embedded " to escaped " // IMPORTANT: keys can come with no values, so a test for null is needed
String valueOf = properties.get(0).getValue(); // IMPORTANT: Convert embedded \n to backslash n, so that the string will look like it has LF embedded
return valueOf == null ? "" : valueOf.replaceAll("\n","\\n").replaceAll("\"","\\\\\""); // in it and embedded " to escaped "
} String valueOf = properties.get(0).getValue();
}); return valueOf == null ? "" : valueOf.replaceAll("\n", "\\n").replaceAll("\"", "\\\\\"");
}
} }
});
} }
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]); }
} }
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
@Nullable @Nullable
@Override @Override
public String getPlaceholderText(@NotNull ASTNode node) { public String getPlaceholderText(@NotNull ASTNode node) {
return "..."; return "...";
} }
@Override @Override
public boolean isCollapsedByDefault(@NotNull ASTNode node) { public boolean isCollapsedByDefault(@NotNull ASTNode node) {
return true; return true;
} }
} }

View File

@ -11,23 +11,30 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class SimpleFormattingModelBuilder implements FormattingModelBuilder { public class SimpleFormattingModelBuilder implements FormattingModelBuilder {
@NotNull @NotNull
@Override @Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) { public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(),
new SimpleBlock(element.getNode(), Wrap.createWrap(WrapType.NONE, false), new SimpleBlock(element.getNode(),
Alignment.createAlignment(), createSpaceBuilder(settings)), settings); Wrap.createWrap(WrapType.NONE,
} false),
Alignment.createAlignment(),
createSpaceBuilder(settings)),
settings);
}
private static SpacingBuilder createSpaceBuilder(CodeStyleSettings settings) { private static SpacingBuilder createSpaceBuilder(CodeStyleSettings settings) {
return new SpacingBuilder(settings, SimpleLanguage.INSTANCE). return new SpacingBuilder(settings, SimpleLanguage.INSTANCE).
around(SimpleTypes.SEPARATOR).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS). around(SimpleTypes.SEPARATOR)
before(SimpleTypes.PROPERTY).none(); .spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
} .
before(SimpleTypes.PROPERTY)
.none();
}
@Nullable @Nullable
@Override @Override
public TextRange getRangeAffectingIndent(PsiFile file, int offset, ASTNode elementAtOffset) { public TextRange getRangeAffectingIndent(PsiFile file, int offset, ASTNode elementAtOffset) {
return null; return null;
} }
} }

View File

@ -5,5 +5,5 @@ import com.intellij.openapi.util.IconLoader;
import javax.swing.*; import javax.swing.*;
public class SimpleIcons { public class SimpleIcons {
public static final Icon FILE = IconLoader.getIcon("/com/simpleplugin/icons/jar-gray.png"); public static final Icon FILE = IconLoader.getIcon("/com/simpleplugin/icons/jar-gray.png");
} }

View File

@ -6,12 +6,12 @@ import com.intellij.psi.impl.cache.impl.id.LexerBasedIdIndexer;
public class SimpleIdIndexer extends LexerBasedIdIndexer { public class SimpleIdIndexer extends LexerBasedIdIndexer {
public static Lexer createIndexingLexer(OccurrenceConsumer consumer) { public static Lexer createIndexingLexer(OccurrenceConsumer consumer) {
return new SimpleFilterLexer(new SimpleLexerAdapter(), consumer); return new SimpleFilterLexer(new SimpleLexerAdapter(), consumer);
} }
@Override @Override
public Lexer createLexer(final OccurrenceConsumer consumer) { public Lexer createLexer(final OccurrenceConsumer consumer) {
return createIndexingLexer(consumer); return createIndexingLexer(consumer);
} }
} }

View File

@ -3,9 +3,9 @@ package com.simpleplugin;
import com.intellij.lang.Language; import com.intellij.lang.Language;
public class SimpleLanguage extends Language { public class SimpleLanguage extends Language {
public static final SimpleLanguage INSTANCE = new SimpleLanguage(); public static final SimpleLanguage INSTANCE = new SimpleLanguage();
private SimpleLanguage() { private SimpleLanguage() {
super("Simple"); super("Simple");
} }
} }

View File

@ -6,38 +6,38 @@ import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class SimpleLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider { public class SimpleLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider {
@NotNull @NotNull
@Override @Override
public Language getLanguage() { public Language getLanguage() {
return SimpleLanguage.INSTANCE; return SimpleLanguage.INSTANCE;
} }
@Override @Override
public void customizeSettings(@NotNull CodeStyleSettingsCustomizable consumer, @NotNull SettingsType settingsType) { public void customizeSettings(@NotNull CodeStyleSettingsCustomizable consumer, @NotNull SettingsType settingsType) {
if (settingsType == SettingsType.SPACING_SETTINGS) { if (settingsType == SettingsType.SPACING_SETTINGS) {
consumer.showStandardOptions("SPACE_AROUND_ASSIGNMENT_OPERATORS"); consumer.showStandardOptions("SPACE_AROUND_ASSIGNMENT_OPERATORS");
consumer.renameStandardOption("SPACE_AROUND_ASSIGNMENT_OPERATORS", "Separator"); consumer.renameStandardOption("SPACE_AROUND_ASSIGNMENT_OPERATORS", "Separator");
} else if (settingsType == SettingsType.BLANK_LINES_SETTINGS) { } else if (settingsType == SettingsType.BLANK_LINES_SETTINGS) {
consumer.showStandardOptions("KEEP_BLANK_LINES_IN_CODE"); consumer.showStandardOptions("KEEP_BLANK_LINES_IN_CODE");
}
} }
}
@Override @Override
public String getCodeSample(@NotNull SettingsType settingsType) { public String getCodeSample(@NotNull SettingsType settingsType) {
return "# You are reading the \".properties\" entry.\n" + return "# You are reading the \".properties\" entry.\n" +
"! The exclamation mark can also mark text as comments.\n" + "! The exclamation mark can also mark text as comments.\n" +
"website = http://en.wikipedia.org/\n" + "website = http://en.wikipedia.org/\n" +
"\n" + "\n" +
"\n" + "\n" +
"\n" + "\n" +
"language = English\n" + "language = English\n" +
"# The backslash below tells the application to continue reading\n" + "# The backslash below tells the application to continue reading\n" +
"# the value onto the next line.\n" + "# the value onto the next line.\n" +
"message = Welcome to \\\n" + "message = Welcome to \\\n" +
" Wikipedia!\n" + " Wikipedia!\n" +
"# Add spaces to the key\n" + "# Add spaces to the key\n" +
"key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" + "key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" +
"# Unicode\n" + "# Unicode\n" +
"tab : \\u0009"; "tab : \\u0009";
} }
} }

View File

@ -3,64 +3,68 @@
package com.simpleplugin; package com.simpleplugin;
import com.intellij.lexer.FlexLexer; import com.intellij.lexer.FlexLexer;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IElementType;
import com.simpleplugin.psi.SimpleTypes; import com.simpleplugin.psi.SimpleTypes;
import com.intellij.psi.TokenType;
/** /**
* This class is a scanner generated by * This class is a scanner generated by
* <a href="http://www.jflex.de/">JFlex</a> 1.4.3 * <a href="http://www.jflex.de/">JFlex</a> 1.4.3
* on 02/09/15 10:04 AM from the specification file * on 02/09/15 10:04 AM from the specification file
* <tt>/Users/vlad/src/SimplePlugin/src/com/simpleplugin/Simple.flex</tt> * <tt>/Users/vlad/src/SimplePlugin/src/com/simpleplugin/Simple.flex</tt>
*/ */
class SimpleLexer implements FlexLexer { class SimpleLexer implements FlexLexer {
/** initial size of the lookahead buffer */ /**
* initial size of the lookahead buffer
*/
private static final int ZZ_BUFFERSIZE = 16384; private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */ /**
* lexical states
*/
public static final int WAITING_VALUE = 2; public static final int WAITING_VALUE = 2;
public static final int YYINITIAL = 0; public static final int YYINITIAL = 0;
/** /**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line * at the beginning of a line
* l is of the form l = 2*k, k a non negative integer * l is of the form l = 2*k, k a non negative integer
*/ */
private static final int ZZ_LEXSTATE[] = { private static final int ZZ_LEXSTATE[] = {
0, 0, 1, 1 0, 0, 1, 1
}; };
/** /**
* Translates characters to character classes * Translates characters to character classes
*/ */
private static final String ZZ_CMAP_PACKED = private static final String ZZ_CMAP_PACKED =
"\11\0\1\3\1\1\1\0\1\6\1\2\22\0\1\5\1\7\1\0"+ "\11\0\1\3\1\1\1\0\1\6\1\2\22\0\1\5\1\7\1\0" +
"\1\7\26\0\1\10\2\0\1\10\36\0\1\4\uffa3\0"; "\1\7\26\0\1\10\2\0\1\10\36\0\1\4\uffa3\0";
/** /**
* Translates characters to character classes * Translates characters to character classes
*/ */
private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); private static final char[] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/** /**
* Translates DFA states to action switch labels. * Translates DFA states to action switch labels.
*/ */
private static final int [] ZZ_ACTION = zzUnpackAction(); private static final int[] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 = private static final String ZZ_ACTION_PACKED_0 =
"\2\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7"+ "\2\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7" +
"\1\3\1\7\2\0\1\6"; "\1\3\1\7\2\0\1\6";
private static int [] zzUnpackAction() { private static int[] zzUnpackAction() {
int [] result = new int[14]; int[] result = new int[14];
int offset = 0; int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result; return result;
} }
private static int zzUnpackAction(String packed, int offset, int [] result) { private static int zzUnpackAction(String packed, int offset, int[] result) {
int i = 0; /* index in packed string */ int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */ int j = offset; /* index in unpacked array */
int l = packed.length(); int l = packed.length();
@ -73,23 +77,23 @@ class SimpleLexer implements FlexLexer {
} }
/** /**
* Translates a state to a row index in the transition table * Translates a state to a row index in the transition table
*/ */
private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final int[] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 = private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\11\0\22\0\33\0\44\0\55\0\66\0\77"+ "\0\0\0\11\0\22\0\33\0\44\0\55\0\66\0\77" +
"\0\110\0\121\0\132\0\44\0\121\0\143"; "\0\110\0\121\0\132\0\44\0\121\0\143";
private static int [] zzUnpackRowMap() { private static int[] zzUnpackRowMap() {
int [] result = new int[14]; int[] result = new int[14];
int offset = 0; int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result; return result;
} }
private static int zzUnpackRowMap(String packed, int offset, int [] result) { private static int zzUnpackRowMap(String packed, int offset, int[] result) {
int i = 0; /* index in packed string */ int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */ int j = offset; /* index in unpacked array */
int l = packed.length(); int l = packed.length();
@ -100,28 +104,28 @@ class SimpleLexer implements FlexLexer {
return j; return j;
} }
/** /**
* The transition table of the DFA * The transition table of the DFA
*/ */
private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final int[] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 = private static final String ZZ_TRANS_PACKED_0 =
"\1\3\3\4\1\5\2\4\1\6\1\7\1\10\2\4"+ "\1\3\3\4\1\5\2\4\1\6\1\7\1\10\2\4" +
"\1\11\1\12\2\13\2\10\1\3\3\0\1\14\2\0"+ "\1\11\1\12\2\13\2\10\1\3\3\0\1\14\2\0" +
"\1\3\2\0\3\4\1\0\2\4\7\0\1\3\3\0"+ "\1\3\2\0\3\4\1\0\2\4\7\0\1\3\3\0" +
"\1\6\2\0\6\6\11\0\1\10\2\0\1\10\1\15"+ "\1\6\2\0\6\6\11\0\1\10\2\0\1\10\1\15" +
"\1\10\1\0\3\10\2\4\1\11\1\15\1\11\1\13"+ "\1\10\1\0\3\10\2\4\1\11\1\15\1\11\1\13" +
"\4\10\1\16\6\10\1\0\2\4\1\13\1\0\2\13"+ "\4\10\1\16\6\10\1\0\2\4\1\13\1\0\2\13" +
"\2\0\2\10\1\0\1\10\1\15\1\10\1\0\2\10"; "\2\0\2\10\1\0\1\10\1\15\1\10\1\0\2\10";
private static int [] zzUnpackTrans() { private static int[] zzUnpackTrans() {
int [] result = new int[108]; int[] result = new int[108];
int offset = 0; int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result; return result;
} }
private static int zzUnpackTrans(String packed, int offset, int [] result) { private static int zzUnpackTrans(String packed, int offset, int[] result) {
int i = 0; /* index in packed string */ int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */ int j = offset; /* index in unpacked array */
int l = packed.length(); int l = packed.length();
@ -145,27 +149,27 @@ class SimpleLexer implements FlexLexer {
/* error messages for the codes above */ /* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = { private static final String ZZ_ERROR_MSG[] = {
"Unkown internal scanner error", "Unkown internal scanner error",
"Error: could not match input", "Error: could not match input",
"Error: pushback value was too large" "Error: pushback value was too large"
}; };
/** /**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/ */
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final int[] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 = private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\2\0\4\1\1\11\4\1\2\0\1\1"; "\2\0\4\1\1\11\4\1\2\0\1\1";
private static int [] zzUnpackAttribute() { private static int[] zzUnpackAttribute() {
int [] result = new int[14]; int[] result = new int[14];
int offset = 0; int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result; return result;
} }
private static int zzUnpackAttribute(String packed, int offset, int [] result) { private static int zzUnpackAttribute(String packed, int offset, int[] result) {
int i = 0; /* index in packed string */ int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */ int j = offset; /* index in unpacked array */
int l = packed.length(); int l = packed.length();
@ -177,33 +181,51 @@ class SimpleLexer implements FlexLexer {
return j; return j;
} }
/** the current state of the DFA */ /**
* the current state of the DFA
*/
private int zzState; private int zzState;
/** the current lexical state */ /**
* the current lexical state
*/
private int zzLexicalState = YYINITIAL; private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is /**
the source of the yytext() string */ * this buffer contains the current text to be matched and is
* the source of the yytext() string
*/
private CharSequence zzBuffer = ""; private CharSequence zzBuffer = "";
/** this buffer may contains the current text array to be matched when it is cheap to acquire it */ /**
* this buffer may contains the current text array to be matched when it is cheap to acquire it
*/
private char[] zzBufferArray; private char[] zzBufferArray;
/** the textposition at the last accepting state */ /**
* the textposition at the last accepting state
*/
private int zzMarkedPos; private int zzMarkedPos;
/** the textposition at the last state to be included in yytext */ /**
* the textposition at the last state to be included in yytext
*/
private int zzPushbackPos; private int zzPushbackPos;
/** the current text position in the buffer */ /**
* the current text position in the buffer
*/
private int zzCurrentPos; private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */ /**
* startRead marks the beginning of the yytext() string in the buffer
*/
private int zzStartRead; private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read /**
from input */ * endRead marks the last character in the buffer, that has been read
* from input
*/
private int zzEndRead; private int zzEndRead;
/** /**
@ -211,10 +233,14 @@ class SimpleLexer implements FlexLexer {
*/ */
private boolean zzAtBOL = true; private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */ /**
* zzAtEOF == true <=> the scanner is at the EOF
*/
private boolean zzAtEOF; private boolean zzAtEOF;
/** denotes if the user-EOF-code has already been executed */ /**
* denotes if the user-EOF-code has already been executed
*/
private boolean zzEOFDone; private boolean zzEOFDone;
@ -226,44 +252,44 @@ class SimpleLexer implements FlexLexer {
* Creates a new scanner. * Creates a new scanner.
* There is also java.io.Reader version of this constructor. * There is also java.io.Reader version of this constructor.
* *
* @param in the java.io.Inputstream to read input from. * @param in the java.io.Inputstream to read input from.
*/ */
SimpleLexer(java.io.InputStream in) { SimpleLexer(java.io.InputStream in) {
this(new java.io.InputStreamReader(in)); this(new java.io.InputStreamReader(in));
} }
/** /**
* Unpacks the compressed character translation table. * Unpacks the compressed character translation table.
* *
* @param packed the packed character translation table * @param packed the packed character translation table
* @return the unpacked character translation table * @return the unpacked character translation table
*/ */
private static char [] zzUnpackCMap(String packed) { private static char[] zzUnpackCMap(String packed) {
char [] map = new char[0x10000]; char[] map = new char[0x10000];
int i = 0; /* index in packed string */ int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */ int j = 0; /* index in unpacked array */
while (i < 36) { while (i < 36) {
int count = packed.charAt(i++); int count = packed.charAt(i++);
char value = packed.charAt(i++); char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0); do map[j++] = value; while (--count > 0);
} }
return map; return map;
} }
public final int getTokenStart(){ public final int getTokenStart() {
return zzStartRead; return zzStartRead;
} }
public final int getTokenEnd(){ public final int getTokenEnd() {
return getTokenStart() + yylength(); return getTokenStart() + yylength();
} }
public void reset(CharSequence buffer, int start, int end,int initialState){ public void reset(CharSequence buffer, int start, int end, int initialState) {
zzBuffer = buffer; zzBuffer = buffer;
zzBufferArray = com.intellij.util.text.CharArrayUtil.fromSequenceWithoutCopying(buffer); zzBufferArray = com.intellij.util.text.CharArrayUtil.fromSequenceWithoutCopying(buffer);
zzCurrentPos = zzMarkedPos = zzStartRead = start; zzCurrentPos = zzMarkedPos = zzStartRead = start;
zzPushbackPos = 0; zzPushbackPos = 0;
zzAtEOF = false; zzAtEOF = false;
zzAtBOL = true; zzAtBOL = true;
zzEndRead = end; zzEndRead = end;
yybegin(initialState); yybegin(initialState);
@ -272,9 +298,8 @@ class SimpleLexer implements FlexLexer {
/** /**
* Refills the input buffer. * Refills the input buffer.
* *
* @return <code>false</code>, iff there was new input. * @return <code>false</code>, iff there was new input.
* * @throws java.io.IOException if any I/O-Error occurs
* @exception java.io.IOException if any I/O-Error occurs
*/ */
private boolean zzRefill() throws java.io.IOException { private boolean zzRefill() throws java.io.IOException {
return true; return true;
@ -310,16 +335,15 @@ class SimpleLexer implements FlexLexer {
/** /**
* Returns the character at position <tt>pos</tt> from the * Returns the character at position <tt>pos</tt> from the
* matched text. * matched text.
* * <p>
* It is equivalent to yytext().charAt(pos), but faster * It is equivalent to yytext().charAt(pos), but faster
* *
* @param pos the position of the character to fetch. * @param pos the position of the character to fetch.
* A value from 0 to yylength()-1. * A value from 0 to yylength()-1.
*
* @return the character at position pos * @return the character at position pos
*/ */
public final char yycharat(int pos) { public final char yycharat(int pos) {
return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos); return zzBufferArray != null ? zzBufferArray[zzStartRead + pos] : zzBuffer.charAt(zzStartRead + pos);
} }
@ -327,30 +351,29 @@ class SimpleLexer implements FlexLexer {
* Returns the length of the matched text region. * Returns the length of the matched text region.
*/ */
public final int yylength() { public final int yylength() {
return zzMarkedPos-zzStartRead; return zzMarkedPos - zzStartRead;
} }
/** /**
* Reports an error that occured while scanning. * Reports an error that occured while scanning.
* * <p>
* In a wellformed scanner (no or only correct usage of * In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method * yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen". * will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong * If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.). * (e.g. a JFlex bug producing a faulty scanner etc.).
* * <p>
* Usual syntax/scanner level error handling should be done * Usual syntax/scanner level error handling should be done
* in error fallback rules. * in error fallback rules.
* *
* @param errorCode the code of the errormessage to display * @param errorCode the code of the errormessage to display
*/ */
private void zzScanError(int errorCode) { private void zzScanError(int errorCode) {
String message; String message;
try { try {
message = ZZ_ERROR_MSG[errorCode]; message = ZZ_ERROR_MSG[errorCode];
} } catch (ArrayIndexOutOfBoundsException e) {
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
} }
@ -360,14 +383,14 @@ class SimpleLexer implements FlexLexer {
/** /**
* Pushes the specified amount of characters back into the input stream. * Pushes the specified amount of characters back into the input stream.
* * <p>
* They will be read again by then next call of the scanning method * They will be read again by then next call of the scanning method
* *
* @param number the number of characters to be read again. * @param number the number of characters to be read again.
* This number must not be greater than yylength()! * This number must not be greater than yylength()!
*/ */
public void yypushback(int number) { public void yypushback(int number) {
if ( number > yylength() ) if (number > yylength())
zzScanError(ZZ_PUSHBACK_2BIG); zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number; zzMarkedPos -= number;
@ -381,7 +404,7 @@ class SimpleLexer implements FlexLexer {
private void zzDoEOF() { private void zzDoEOF() {
if (!zzEOFDone) { if (!zzEOFDone) {
zzEOFDone = true; zzEOFDone = true;
} }
} }
@ -390,8 +413,8 @@ class SimpleLexer implements FlexLexer {
* Resumes scanning until the next regular expression is matched, * Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs. * the end of input is encountered or an I/O-Error occurs.
* *
* @return the next token * @return the next token
* @exception java.io.IOException if any I/O-Error occurs * @throws java.io.IOException if any I/O-Error occurs
*/ */
public IElementType advance() throws java.io.IOException { public IElementType advance() throws java.io.IOException {
int zzInput; int zzInput;
@ -403,11 +426,11 @@ class SimpleLexer implements FlexLexer {
int zzEndReadL = zzEndRead; int zzEndReadL = zzEndRead;
CharSequence zzBufferL = zzBuffer; CharSequence zzBufferL = zzBuffer;
char[] zzBufferArrayL = zzBufferArray; char[] zzBufferArrayL = zzBufferArray;
char [] zzCMapL = ZZ_CMAP; char[] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS; int[] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP; int[] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE; int[] zzAttrL = ZZ_ATTRIBUTE;
while (true) { while (true) {
zzMarkedPosL = zzMarkedPos; zzMarkedPosL = zzMarkedPos;
@ -419,7 +442,8 @@ class SimpleLexer implements FlexLexer {
zzState = ZZ_LEXSTATE[zzLexicalState]; zzState = ZZ_LEXSTATE[zzLexicalState];
zzForAction: { zzForAction:
{
while (true) { while (true) {
if (zzCurrentPosL < zzEndReadL) if (zzCurrentPosL < zzEndReadL)
@ -427,34 +451,32 @@ class SimpleLexer implements FlexLexer {
else if (zzAtEOF) { else if (zzAtEOF) {
zzInput = YYEOF; zzInput = YYEOF;
break zzForAction; break zzForAction;
} } else {
else {
// store back cached positions // store back cached positions
zzCurrentPos = zzCurrentPosL; zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL; zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill(); boolean eof = zzRefill();
// get translated positions and possibly new buffer // get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos; zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos; zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer; zzBufferL = zzBuffer;
zzEndReadL = zzEndRead; zzEndReadL = zzEndRead;
if (eof) { if (eof) {
zzInput = YYEOF; zzInput = YYEOF;
break zzForAction; break zzForAction;
} } else {
else {
zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++)); zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++));
} }
} }
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]];
if (zzNext == -1) break zzForAction; if (zzNext == -1) break zzForAction;
zzState = zzNext; zzState = zzNext;
int zzAttributes = zzAttrL[zzState]; int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) { if ((zzAttributes & 1) == 1) {
zzAction = zzState; zzAction = zzState;
zzMarkedPosL = zzCurrentPosL; zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction; if ((zzAttributes & 8) == 8) break zzForAction;
} }
} }
@ -464,41 +486,53 @@ class SimpleLexer implements FlexLexer {
zzMarkedPos = zzMarkedPosL; zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 6: case 6: {
{ yybegin(YYINITIAL); return SimpleTypes.VALUE; yybegin(YYINITIAL);
} return SimpleTypes.VALUE;
case 8: break; }
case 5: case 8:
{ yybegin(WAITING_VALUE); return SimpleTypes.SEPARATOR; break;
} case 5: {
case 9: break; yybegin(WAITING_VALUE);
case 4: return SimpleTypes.SEPARATOR;
{ yybegin(YYINITIAL); return SimpleTypes.COMMENT; }
} case 9:
case 10: break; break;
case 3: case 4: {
{ return TokenType.BAD_CHARACTER; yybegin(YYINITIAL);
} return SimpleTypes.COMMENT;
case 11: break; }
case 2: case 10:
{ yybegin(YYINITIAL); return TokenType.WHITE_SPACE; break;
} case 3: {
case 12: break; return TokenType.BAD_CHARACTER;
case 7: }
{ yybegin(WAITING_VALUE); return TokenType.WHITE_SPACE; case 11:
} break;
case 13: break; case 2: {
case 1: yybegin(YYINITIAL);
{ yybegin(YYINITIAL); return SimpleTypes.KEY; return TokenType.WHITE_SPACE;
} }
case 14: break; case 12:
break;
case 7: {
yybegin(WAITING_VALUE);
return TokenType.WHITE_SPACE;
}
case 13:
break;
case 1: {
yybegin(YYINITIAL);
return SimpleTypes.KEY;
}
case 14:
break;
default: default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true; zzAtEOF = true;
zzDoEOF(); zzDoEOF();
return null; return null;
} } else {
else {
zzScanError(ZZ_NO_MATCH); zzScanError(ZZ_NO_MATCH);
} }
} }

View File

@ -5,7 +5,7 @@ import com.intellij.lexer.FlexAdapter;
import java.io.Reader; import java.io.Reader;
public class SimpleLexerAdapter extends FlexAdapter { public class SimpleLexerAdapter extends FlexAdapter {
public SimpleLexerAdapter() { public SimpleLexerAdapter() {
super(new SimpleLexer((Reader) null)); super(new SimpleLexer((Reader) null));
} }
} }

View File

@ -13,22 +13,23 @@ import java.util.Collection;
import java.util.List; import java.util.List;
public class SimpleLineMarkerProvider extends RelatedItemLineMarkerProvider { public class SimpleLineMarkerProvider extends RelatedItemLineMarkerProvider {
@Override @Override
protected void collectNavigationMarkers(@NotNull PsiElement element, Collection<? super RelatedItemLineMarkerInfo> result) { protected void collectNavigationMarkers(@NotNull PsiElement element,
if (element instanceof PsiLiteralExpression) { Collection<? super RelatedItemLineMarkerInfo> result) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) element; if (element instanceof PsiLiteralExpression) {
String value = literalExpression.getValue() instanceof String ? (String)literalExpression.getValue() : null; PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
if (value != null && value.startsWith("simple"+":")) { String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
Project project = element.getProject(); if (value != null && value.startsWith("simple" + ":")) {
final List<SimpleProperty> properties = SimpleUtil.findProperties(project, value.substring(7)); Project project = element.getProject();
if (properties.size() > 0) { final List<SimpleProperty> properties = SimpleUtil.findProperties(project, value.substring(7));
NavigationGutterIconBuilder<PsiElement> builder = if (properties.size() > 0) {
NavigationGutterIconBuilder.create(SimpleIcons.FILE). NavigationGutterIconBuilder<PsiElement> builder =
setTargets(properties). NavigationGutterIconBuilder.create(SimpleIcons.FILE).
setTooltipText("Navigate to a simple property"); setTargets(properties).
result.add(builder.createLineMarkerInfo(element)); setTooltipText("Navigate to a simple property");
} result.add(builder.createLineMarkerInfo(element));
}
} }
}
} }
}
} }

View File

@ -17,53 +17,54 @@ import com.simpleplugin.psi.SimpleFile;
import com.simpleplugin.psi.SimpleTypes; import com.simpleplugin.psi.SimpleTypes;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class SimpleParserDefinition implements ParserDefinition{ public class SimpleParserDefinition implements ParserDefinition {
public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE); public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE);
public static final TokenSet COMMENTS = TokenSet.create(SimpleTypes.COMMENT); public static final TokenSet COMMENTS = TokenSet.create(SimpleTypes.COMMENT);
public static final IFileElementType FILE = new IFileElementType(Language.<SimpleLanguage>findInstance(SimpleLanguage.class)); public static final IFileElementType FILE =
new IFileElementType(Language.<SimpleLanguage>findInstance(SimpleLanguage.class));
@NotNull @NotNull
@Override @Override
public Lexer createLexer(Project project) { public Lexer createLexer(Project project) {
return new SimpleLexerAdapter(); return new SimpleLexerAdapter();
} }
@NotNull @NotNull
public TokenSet getWhitespaceTokens() { public TokenSet getWhitespaceTokens() {
return WHITE_SPACES; return WHITE_SPACES;
} }
@NotNull @NotNull
public TokenSet getCommentTokens() { public TokenSet getCommentTokens() {
return COMMENTS; return COMMENTS;
} }
@NotNull @NotNull
public TokenSet getStringLiteralElements() { public TokenSet getStringLiteralElements() {
return TokenSet.EMPTY; return TokenSet.EMPTY;
} }
@NotNull @NotNull
public PsiParser createParser(final Project project) { public PsiParser createParser(final Project project) {
return new SimpleParser(); return new SimpleParser();
} }
@Override @Override
public IFileElementType getFileNodeType() { public IFileElementType getFileNodeType() {
return FILE; return FILE;
} }
public PsiFile createFile(FileViewProvider viewProvider) { public PsiFile createFile(FileViewProvider viewProvider) {
return new SimpleFile(viewProvider); return new SimpleFile(viewProvider);
} }
public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) { public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) {
return SpaceRequirements.MAY; return SpaceRequirements.MAY;
} }
@NotNull @NotNull
public PsiElement createElement(ASTNode node) { public PsiElement createElement(ASTNode node) {
return SimpleTypes.Factory.createElement(node); return SimpleTypes.Factory.createElement(node);
} }
} }

Some files were not shown because too many files have changed in this diff Show More