Java Code Examples for com.intellij.openapi.util.TextRange

The following are top voted examples for showing how to use com.intellij.openapi.util.TextRange. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: manifold-ij   File: ExtensionClassAnnotator.java   View source code 6 votes vote down vote up
private void errrantThisOrExtension( PsiElement element, AnnotationHolder holder )
{
  if( element instanceof PsiModifierList )
  {
    PsiModifierList mods = (PsiModifierList)element;
    PsiAnnotation annotation;
    if( (annotation = mods.findAnnotation( Extension.class.getName() )) != null ||
        (annotation = mods.findAnnotation( This.class.getName() )) != null)
    {
      TextRange range = new TextRange( annotation.getTextRange().getStartOffset(),
                                       annotation.getTextRange().getEndOffset() );
      //noinspection ConstantConditions
      holder.createErrorAnnotation( range, ExtIssueMsg.MSG_NOT_IN_EXTENSION_CLASS.get( ClassUtil.extractClassName( annotation.getQualifiedName() ) ) );
    }
  }
}
 
Example 2
Project: AppleScript-IDEA   File: AbstractAppleScriptHandlerCall.java   View source code 6 votes vote down vote up
@NotNull
@Override
public List<TextRange> getRanges() {
  List<TextRange> result = new ArrayList<>();
  final int parentOffset = -getElement().getTextRange().getStartOffset();
  List<AppleScriptHandlerArgument> arguments = getArguments();
  for (AppleScriptHandlerArgument argument : arguments) {
    PsiElement id = argument.getArgumentSelector().getSelectorIdentifier();
    if (id != null) {
      TextRange argumentRange = id.getTextRange();
      if (!argumentRange.isEmpty()) {
        result.add(argumentRange.shiftRight(parentOffset));
      }
    }
  }
  return result;
}
 
Example 3
Project: manifold-ij   File: ExtensionClassAnnotator.java   View source code 6 votes vote down vote up
private void verifyExtensionInterfaces( PsiElement element, AnnotationHolder holder )
{
  if( element instanceof PsiJavaCodeReferenceElementImpl &&
      ((PsiJavaCodeReferenceElementImpl)element).getTreeParent() instanceof ReferenceListElement &&
      ((PsiJavaCodeReferenceElementImpl)element).getTreeParent().getText().startsWith( PsiKeyword.IMPLEMENTS ) )
  {
    final PsiElement resolve = element.getReference().resolve();
    if( resolve instanceof PsiExtensibleClass )
    {
      PsiExtensibleClass iface = (PsiExtensibleClass)resolve;
      if( !isStructuralInterface( iface ) )
      {
        TextRange range = new TextRange( element.getTextRange().getStartOffset(),
                                         element.getTextRange().getEndOffset() );
        holder.createErrorAnnotation( range, ExtIssueMsg.MSG_ONLY_STRUCTURAL_INTERFACE_ALLOWED_HERE.get( iface.getName() ) );
      }
    }
  }
}
 
Example 4
Project: ReactPropTypes-Plugin   File: CommonAction.java   View source code 6 votes vote down vote up
@Nullable
String getSelectedText(Editor editor) {
  SelectionModel selectionModel = editor.getSelectionModel();
  if(selectionModel.hasSelection()){
    return selectionModel.getSelectedText();
  }else {
    final ArrayList<TextRange> ranges = new ArrayList<>();
    final int offset = editor.getCaretModel().getOffset();
    SelectWordUtilCompat.addWordOrLexemeSelection(false, editor, offset, ranges, SelectWordUtilCompat.JAVASCRIPT_IDENTIFIER_PART_CONDITION);
    if(ranges.size()>0){
      return  editor.getDocument().getText(ranges.get(0));
    }else {
      return null;
    }
  }
}
 
Example 5
Project: greycat-idea-plugin   File: GCMFoldingBuilder.java   View source code 6 votes vote down vote up
private void appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) {
    if (node.getElementType() == GCMTypes.CLASS_DECLARATION || node.getElementType() == GCMTypes.CUSTOM_TYPE_DECLARATION) {
        TextRange fullRange = node.getTextRange();
        if (fullRange.getEndOffset() - fullRange.getStartOffset() > 0) {

            try {
                int startOffset = fullRange.getStartOffset() + document.getText(fullRange).indexOf("{") + 1;
                int endOffset = fullRange.getEndOffset() - 1;
                if (startOffset < endOffset) {
                    TextRange shortRange = new TextRange(startOffset, fullRange.getEndOffset() - 1);
                    if (shortRange.getEndOffset() - shortRange.getStartOffset() > 1) {
                        descriptors.add(new FoldingDescriptor(node, shortRange));
                    }
                }
            } catch (Throwable e) {

            }
        }
    }
    ASTNode child = node.getFirstChildNode();
    while (child != null) {
        appendDescriptors(child, document, descriptors);
        child = child.getTreeNext();
    }
}
 
Example 6
Project: Gherkin-TS-Runner   File: GherkinIconUtils.java   View source code 6 votes vote down vote up
public void generateGherkinRunIcons(Document rootDocument, Editor rootEditor) {
    for (int i = 0; i < rootDocument.getLineCount(); i++) {
        int startOffset = rootDocument.getLineStartOffset(i);
        int endOffset = rootDocument.getLineEndOffset(i);

        String lineText = rootDocument.getText(new TextRange(startOffset, endOffset)).trim();

        Icon icon;
        if (lineText.matches(SCENARIO_REGEX)) {
            icon = GherkinIconRenderer.SCENARIO_ICON;
        } else if (lineText.matches(FEATURE_REGEX)) {
            icon = GherkinIconRenderer.FEATURE_ICON;
        } else {
            // System.out.println();
             continue;
        }
        GherkinIconRenderer gherkinIconRenderer = new GherkinIconRenderer(rootEditor.getProject(), fileName);
        gherkinIconRenderer.setLine(i);
        gherkinIconRenderer.setIcon(icon);

        RangeHighlighter rangeHighlighter = createRangeHighlighter(rootDocument, rootEditor, i, i, new TextAttributes());
        rangeHighlighter.setGutterIconRenderer(gherkinIconRenderer);
    }
}
 
Example 7
Project: bamboo-soy   File: IdentifierMixin.java   View source code 6 votes vote down vote up
@Override
public PsiReference[] getReferences() {
  PsiElement element = getNode().getPsi();
  String maybeEmbeddedExpression = this.getText();
  if (!maybeEmbeddedExpression.startsWith("\"")) {
    PsiReference singleReference = getReference();
    return singleReference == null ? new PsiReference[] {} : new PsiReference[] {singleReference};
  }

  Matcher identifierMatcher = identifierPattern.matcher(maybeEmbeddedExpression);
  List<PsiReference> variableReferenceList = new ArrayList<>();
  while (identifierMatcher.find()) {
    variableReferenceList.add(
        new VariableReference(
            element,
            maybeEmbeddedExpression.substring(
                identifierMatcher.start() + 1, identifierMatcher.end()),
            new TextRange(
                element.getTextRange().getStartOffset() + identifierMatcher.start(),
                element.getTextRange().getStartOffset() + identifierMatcher.end()),
            new TextRange(identifierMatcher.start(), identifierMatcher.end())));
  }
  return variableReferenceList.toArray(new PsiReference[variableReferenceList.size()]);
}
 
Example 8
Project: bamboo-soy   File: EnterHandler.java   View source code 6 votes vote down vote up
private static void handleEnterInComment(
    PsiElement element, @NotNull PsiFile file, @NotNull Editor editor) {
  if (element.getText().startsWith("/*")) {
    Document document = editor.getDocument();

    int caretOffset = editor.getCaretModel().getOffset();
    int lineNumber = document.getLineNumber(caretOffset);

    String lineTextBeforeCaret =
        document.getText(new TextRange(document.getLineStartOffset(lineNumber), caretOffset));
    String lineTextAfterCaret =
        document.getText(new TextRange(caretOffset, document.getLineEndOffset(lineNumber)));

    if (lineTextAfterCaret.equals("*/")) {
      return;
    }

    String toInsert = lineTextBeforeCaret.equals("") ? " * " : "* ";
    insertText(file, editor, toInsert, toInsert.length());
  }
}
 
Example 9
Project: bamboo-soy   File: EnterHandler.java   View source code 6 votes vote down vote up
@Override
public Result postProcessEnter(
    @NotNull PsiFile file, @NotNull Editor editor, @NotNull DataContext dataContext) {
  if (file.getFileType() != SoyFileType.INSTANCE) {
    return Result.Continue;
  }

  int caretOffset = editor.getCaretModel().getOffset();
  PsiElement element = file.findElementAt(caretOffset);
  Document document = editor.getDocument();

  int lineNumber = document.getLineNumber(caretOffset) - 1;
  int lineStartOffset = document.getLineStartOffset(lineNumber);
  String lineTextBeforeCaret = document.getText(new TextRange(lineStartOffset, caretOffset));

  if (element instanceof PsiComment && element.getTextOffset() < caretOffset) {
    handleEnterInComment(element, file, editor);
  } else if (lineTextBeforeCaret.startsWith("/*")) {
    insertText(file, editor, " * \n ", 3);
  }

  return Result.Continue;
}
 
Example 10
Project: JNomad-Plugin   File: JNomadQueryVisitor.java   View source code 6 votes vote down vote up
private static int getLineNumber(VirtualFile virtualFile, TextRange textRange) {
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(virtualFile.getInputStream()));
        String line;
        int pos = 0;
        int lineNumber = 0;

        while ((line = br.readLine()) != null) {
            pos += line.length() + 1; //+1 for new line
            lineNumber++;

            if (pos >= textRange.getStartOffset()) {
                return lineNumber;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return -1;
}
 
Example 11
Project: EmojiPrefix   File: EmojiResourceCompletionContributor.java   View source code 6 votes vote down vote up
public EmojiResourceCompletionContributor() {
	extend(CompletionType.BASIC, PlatformPatterns.psiElement(PsiElement.class), new CompletionProvider<CompletionParameters>() {
		@Override
		protected void addCompletions(@NotNull CompletionParameters completionParameters,
									  ProcessingContext processingContext,
									  @NotNull CompletionResultSet completionResultSet) {
			Document document = completionParameters.getEditor().getDocument();
			int lineStart = document.getLineStartOffset(document.getLineNumber(completionParameters.getOffset()));
			String lineText = document.getText(new TextRange(lineStart, completionParameters.getOffset()));
			if (includeCount(lineText) == 1) {
				for (Map.Entry<String, Icon> iconEntry : EmojiUtil.getEmojiMap().entrySet()) {
					completionResultSet.addElement(LookupElementBuilder.create(iconEntry.getKey(), ":" + iconEntry.getKey() + ":")
							.withIcon(iconEntry.getValue())
							.withInsertHandler((insertionContext, lookupElement) -> {
								int startOffset = insertionContext.getStartOffset();
								Document insertDocument = insertionContext.getDocument();
								if (startOffset > 0 && insertDocument.getCharsSequence().charAt(startOffset - 1) == ':') {
									insertDocument.deleteString(startOffset - 1, startOffset);
								}
							}));
				}
			}
		}
	});
}
 
Example 12
Project: intellij-postfix-templates   File: CptReferenceContributor.java   View source code 6 votes vote down vote up
@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
	// TODO
	registrar.registerReferenceProvider(PlatformPatterns.psiElement(PsiLiteralExpression.class),
		new PsiReferenceProvider() {
			@NotNull
			@Override
			public PsiReference[] getReferencesByElement(@NotNull PsiElement element,
			                                             @NotNull ProcessingContext
				                                             context) {
				PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
				String value = literalExpression.getValue() instanceof String ?
					(String) literalExpression.getValue() : null;
				if (value != null && value.startsWith("simple" + ":")) {
					return new PsiReference[]{
						new CptReference(element, new TextRange(8, value.length() + 1))};
				}
				return PsiReference.EMPTY_ARRAY;
			}
		});
}
 
Example 13
Project: educational-plugin   File: CCChangePlaceholderVisibility.java   View source code 6 votes vote down vote up
private static void saveIndent(AnswerPlaceholder placeholder, CCState state, boolean visible) {
  Document document = state.getEditor().getDocument();
  int offset = placeholder.getOffset();
  int lineNumber = document.getLineNumber(offset);
  int nonSpaceCharOffset = DocumentUtil.getFirstNonSpaceCharOffset(document, lineNumber);
  int newOffset = offset;
  int endOffset = offset + placeholder.getRealLength();
  if (!visible && nonSpaceCharOffset == offset) {
    newOffset = document.getLineStartOffset(lineNumber);
  }
  if (visible) {
    newOffset = DocumentUtil.getFirstNonSpaceCharOffset(document, offset, endOffset);
  }
  placeholder.setOffset(newOffset);
  int delta = offset - newOffset;
  placeholder.setPossibleAnswer(document.getText(TextRange.create(newOffset, newOffset + delta + placeholder.getRealLength())));
  String oldTaskText = placeholder.getTaskText();
  if (delta >= 0) {
    placeholder.setTaskText(StringUtil.repeat(" ", delta) + oldTaskText);
  }
  else {
    String newTaskText = oldTaskText.substring(Math.abs(delta));
    placeholder.setTaskText(newTaskText);
  }
}
 
Example 14
Project: intellij-plugin   File: CoffigBaseReferenceContributor.java   View source code 6 votes vote down vote up
@NotNull
protected List<PsiReference> resolvePsiReferences(@NotNull PsiElement element, String value, int rangeOffset) {
    if (value != null) {
        String[] split = value.split("\\.");
        List<PsiReference> psiReferences = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        int startIndex = 0;
        for (int i = 0; i < split.length; i++) {
            if (i > 0) {
                sb.append(".");
                startIndex = sb.length();
            }
            sb.append(split[i]);
            psiReferences.add(new CoffigReference(element, new TextRange(rangeOffset + startIndex, rangeOffset + sb.length()), sb.toString()));
        }
        return psiReferences;
    } else {
        return new ArrayList<>();
    }
}
 
Example 15
Project: intellij-crystal   File: CrystalReferenceContributor.java   View source code 6 votes vote down vote up
@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(PlatformPatterns.psiElement(PsiLiteralExpression.class),
            new PsiReferenceProvider() {
                @NotNull
                @Override
                public PsiReference[] getReferencesByElement(@NotNull PsiElement element,
                                                             @NotNull ProcessingContext
                                                                     context) {
                    PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
                    String value = literalExpression.getValue() instanceof String ?
                            (String) literalExpression.getValue() : null;
                    if (value != null && value.startsWith("simple" + ":")) {
                        return new PsiReference[]{
                                new CrystalReference(element, new TextRange(8, value.length() + 1))};
                    }
                    return PsiReference.EMPTY_ARRAY;
                }
            });
}
 
Example 16
Project: ReciteWords   File: ReciteWords.java   View source code 5 votes vote down vote up
public String getCurrentWords(Editor editor) {
    Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    int caretOffset = caretModel.getOffset();
    int lineNum = document.getLineNumber(caretOffset);
    int lineStartOffset = document.getLineStartOffset(lineNum);
    int lineEndOffset = document.getLineEndOffset(lineNum);
    String lineContent = document.getText(new TextRange(lineStartOffset, lineEndOffset));
    char[] chars = lineContent.toCharArray();
    int start = 0, end = 0, cursor = caretOffset - lineStartOffset;

    if (!Character.isLetter(chars[cursor])) {
        Logger.warn("Caret not in a word");
        return null;
    }

    for (int ptr = cursor; ptr >= 0; ptr--) {
        if (!Character.isLetter(chars[ptr])) {
            start = ptr + 1;
            break;
        }
    }

    int lastLetter = 0;
    for (int ptr = cursor; ptr < lineEndOffset - lineStartOffset; ptr++) {
        lastLetter = ptr;
        if (!Character.isLetter(chars[ptr])) {
            end = ptr;
            break;
        }
    }
    if (end == 0) {
        end = lastLetter + 1;
    }

    String ret = new String(chars, start, end-start);
    Logger.info("Selected words: " + ret);
    return ret;
}
 
Example 17
Project: AppleScript-IDEA   File: AppleScriptFormattingModelBuilder.java   View source code 5 votes vote down vote up
@Override
protected String replaceWithPsiInLeaf(TextRange textRange, String whiteSpace, ASTNode leafElement) {
  if (!myCanModifyAllWhiteSpaces) {
    if (AppleScriptPsiImplUtil.isWhiteSpaceOrNls(leafElement)) return null;
  }

  IElementType elementTypeToUse = TokenType.WHITE_SPACE;
  ASTNode prevNode = TreeUtil.prevLeaf(leafElement);
  if (prevNode != null && AppleScriptPsiImplUtil.isWhiteSpaceOrNls(prevNode)) {
    elementTypeToUse = prevNode.getElementType();
  }
  FormatterUtil.replaceWhiteSpace(whiteSpace, leafElement, elementTypeToUse, textRange);
  return whiteSpace;
}
 
Example 18
Project: AppleScript-IDEA   File: AppleScriptJSInjector.java   View source code 5 votes vote down vote up
@Override
public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
  if (context instanceof AppleScriptStringLiteralExpression) {
    AppleScriptCommandHandlerCall asCommand = PsiTreeUtil.getContextOfType(context, AppleScriptCommandHandlerCall.class);
    if (asCommand != null && asCommand.getCommandName().equalsIgnoreCase("do javascript")) {
      Collection<Language> javascript = Language.findInstancesByMimeType("javascript");
      if (javascript.isEmpty()) return;

      registrar.startInjecting(javascript.iterator().next()).addPlace(null, null, (PsiLanguageInjectionHost) context, new TextRange(1, context.getTextLength() - 1)).doneInjecting();
    }
  }
}
 
Example 19
Project: AppleScript-IDEA   File: AbstractDictionaryReferenceElement.java   View source code 5 votes vote down vote up
@NotNull
@Override
public List<TextRange> getRanges() {
  List<TextRange> result = new ArrayList<>();
  final int parentOffset = -getElement().getTextRange().getStartOffset();
  for (PsiElement id : getElement().getCompositeNameElement().getIdentifiers()) {
    TextRange argumentRange = id.getTextRange();
    if (!argumentRange.isEmpty()) {
      result.add(argumentRange.shiftRight(parentOffset));
    }
  }
  return result;
}
 
Example 20
Project: AppleScript-IDEA   File: AppleScriptReferenceElementImpl.java   View source code 5 votes vote down vote up
@Override
public TextRange getRangeInElement() {
  final TextRange textRange = getTextRange();

  AppleScriptReferenceElement[] appleScriptReferences = PsiTreeUtil.getChildrenOfType(this, AppleScriptReferenceElement.class);
  if (appleScriptReferences != null && appleScriptReferences.length > 0) {
    TextRange lastReferenceRange = appleScriptReferences[appleScriptReferences.length - 1].getTextRange();
    return new UnfairTextRange(
        lastReferenceRange.getStartOffset() - textRange.getStartOffset(),
        lastReferenceRange.getEndOffset() - textRange.getEndOffset()
    );
  }
  return new UnfairTextRange(0, textRange.getEndOffset() - textRange.getStartOffset());
}
 
Example 21
Project: reasonml-idea-plugin   File: RmlPsiUtil.java   View source code 5 votes vote down vote up
@NotNull
private static TextRange rangeInParent(@NotNull TextRange parent, @NotNull TextRange child) {
    int start = child.getStartOffset() - parent.getStartOffset();
    if (start < 0) {
        return TextRange.EMPTY_RANGE;
    }

    return TextRange.create(start, start + child.getLength());
}
 
Example 22
Project: idea-php-typo3-plugin   File: RouteFoldingBuilder.java   View source code 5 votes vote down vote up
@Nullable
private FoldingDescriptor foldRouteReferenceString(PsiReference reference, String value, FoldingGroup group) {
    PsiElement element = reference.getElement();
    TextRange foldingRange = new TextRange(element.getTextRange().getStartOffset() + 1, element.getTextRange().getEndOffset() - 1);

    if (!RouteIndex.hasRoute(element.getProject(), value)) {
        return null;
    }

    Collection<RouteStub> route = RouteIndex.getRoute(element.getProject(), value);
    if (route.size() == 0) {
        return null;
    }

    RouteStub routeDef = route.iterator().next();

    return new FoldingDescriptor(element.getNode(), foldingRange, group) {
        @Nullable
        @Override
        public String getPlaceholderText() {
            if (routeDef.getPath() == null) {
                return routeDef.getController() + "::" + routeDef.getMethod();
            }

            return routeDef.getPath();
        }
    };
}
 
Example 23
Project: idea-php-typo3-plugin   File: TablenameFileIndex.java   View source code 5 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, TextRange, FileContent> getIndexer() {
    return inputData -> {
        Map<String, TextRange> map = new THashMap<>();

        CharSequence charSequence = LoadTextUtil.loadText(inputData.getFile());

        final Matcher matcher = Pattern
                .compile("create\\s+table\\s+(if\\s+not\\s+exists\\s+)?([a-zA-Z_0-9]+)", Pattern.CASE_INSENSITIVE)
                .matcher(charSequence);

        try {
            while (matcher.find()) {
                if (matcher.groupCount() < 2) {
                    return map;
                }

                map.put(matcher.group(2), new TextRange(matcher.start(), matcher.end()));
            }
        } catch (IllegalStateException e) {
            // no matches
        }

        return map;
    };
}
 
Example 24
Project: MultiHighlight   File: MultiHighlightHandler.java   View source code 5 votes vote down vote up
private static void highlight(@NotNull HighlightManager highlightManager,
        @NotNull Collection<TextRange> textRanges, @NotNull Editor editor,
        @NotNull TextAttributes ta, @Nullable Collection<RangeHighlighter> holder,
        @Nullable Color scrollMarkColor) {
    for (TextRange range : textRanges) {
        highlightManager.addOccurrenceHighlight(editor, range.getStartOffset(),
                range.getEndOffset(), ta, 0, holder, scrollMarkColor);
    }
}
 
Example 25
Project: idea-onescript   File: OneScriptFoldingBuilder.java   View source code 5 votes vote down vote up
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement psiElement, @NotNull Document document, boolean b) {
    List<FoldingDescriptor> descriptors = new ArrayList<>();
    Collection<OneScriptSubdeclaration> subs = PsiTreeUtil.findChildrenOfType(psiElement, OneScriptSubdeclaration.class);
    for (final OneScriptSubdeclaration sub : subs) {
        final String subName = sub.getSubName().getText();

        PsiElement endOfSub = sub.getNextSibling();
        while (endOfSub != null && !(endOfSub instanceof OneScriptEndOfSub)) {
            endOfSub = endOfSub.getNextSibling();
        }

        if (endOfSub == null) {
            continue;
        }

        TextRange r = new TextRange(sub.getTextRange().getStartOffset(), endOfSub.getTextRange().getEndOffset());
        FoldingDescriptor d = new FoldingDescriptor(sub.getNode(), r) {
            @Nullable
            @Override
            public String getPlaceholderText() {
                return subName;
            }
        };
        descriptors.add(d);
    }
    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
 
Example 26
Project: magento2-phpstorm-plugin   File: LineMarkerXmlTagDecorator.java   View source code 5 votes vote down vote up
@Override
@Contract(
        pure = true
)
public TextRange getTextRange() {
    return xmlTag.getTextRange();
}
 
Example 27
Project: magento2-phpstorm-plugin   File: PhpClassMemberReferenceProvider.java   View source code 5 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    List<PsiReference> psiReferences = new ArrayList<>();
    final Collection<PhpClassMember> members = new THashSet<>();

    String origValue = element.getText();
    String value = StringUtil.unquoteString(element.getText());

    Matcher matcher = Pattern.compile(PhpRegex.Xml.CLASS_MEMBER_NAME).matcher(value);
    if (!matcher.find()) {
        return PsiReference.EMPTY_ARRAY;
    }

    String elementName = matcher.group(1);
    String classFQN = value.substring(0, value.lastIndexOf("::"));

    PhpIndex phpIndex = PhpIndex.getInstance(element.getProject());
    for (final PhpClass phpClass : phpIndex.getAnyByFQN(classFQN)) {
        members.addAll(phpClass.getFields());
        members.addAll(phpClass.getMethods());
        members.removeIf(c -> !c.getName().equals(elementName));
    }

    if (members.size() > 0) {
        TextRange range = new TextRange(
                origValue.indexOf(elementName),
                origValue.indexOf(elementName) + elementName.length()
        );
        psiReferences.add(new PolyVariantReferenceBase(element, range, members));
    }
    return psiReferences.toArray(new PsiReference[psiReferences.size()]);
}
 
Example 28
Project: ReactPropTypes-Plugin   File: SelectWordUtilCompat.java   View source code 5 votes vote down vote up
public static void addWordOrLexemeSelection(boolean camel,
                                            @NotNull Editor editor,
                                            int cursorOffset,
                                            @NotNull List<TextRange> ranges,
                                            @NotNull SelectWordUtil.CharCondition isWordPartCondition) {
    if (IdeaCompat.BUILD_NUMBER >= IdeaCompat.Version.IDEA2016_2) {
        SelectWordUtil.addWordOrLexemeSelection(camel, editor, cursorOffset, ranges, isWordPartCondition);
    } else {
        CharSequence editorText = editor.getDocument().getImmutableCharSequence();
        SelectWordUtil.addWordSelection(camel, editorText, cursorOffset, ranges, isWordPartCondition);
    }

}
 
Example 29
Project: bamboo-soy   File: IdentifierMixin.java   View source code 5 votes vote down vote up
@Override
public PsiReference getReference() {
  PsiElement element = getNode().getPsi();
  String identifier = element.getText();

  if (identifier.startsWith("$")) {
    String fullIdentifier = identifier.substring(1);
    String[] fragments = fullIdentifier.split("\\.");

    return new VariableReference(
        element,
        fragments[0],
        new TextRange(
            element.getTextRange().getStartOffset(),
            element.getTextRange().getStartOffset() + fragments[0].length()),
        new TextRange(0, fragments[0].length() + 1));
  } else if (identifier.startsWith(".")) {
    return new TemplateDefinitionReference(element, element.getTextRange());
  } else {
    if (identifier.split("\\.").length >= 2) {
      // Fully qualified template identifier.
      return new TemplateDefinitionReference(element, element.getTextRange());
    }
  }

  return null;
}
 
Example 30
Project: idea-php-dotenv-plugin   File: DotEnvCommenter.java   View source code 5 votes vote down vote up
@Nullable
@Override
public TextRange getBlockCommentRange(int selectionStart,
                                      int selectionEnd,
                                      @NotNull Document document,
                                      @NotNull CommenterDataHolder data) {
    throw new UnsupportedOperationException();
}
 
Example 31
Project: idea-php-dotenv-plugin   File: DotEnvLightCodeInsightFixtureTestCase.java   View source code 5 votes vote down vote up
public void assertLocalInspectionContains(String filename, String content, String contains) {
    Set<String> matches = new HashSet<String>();

    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);
    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond()) && result.toString().equals(contains)) {
            return;
        }

        matches.add(result.toString());
    }

    fail(String.format("Fail matches '%s' with one of %s", contains, matches));
}
 
Example 32
Project: idea-php-dotenv-plugin   File: DotEnvLightCodeInsightFixtureTestCase.java   View source code 5 votes vote down vote up
public void assertLocalInspectionContainsNotContains(String filename, String content, String contains) {
    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);

    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond())) {
            fail(String.format("Fail inspection not contains '%s'", contains));
        }
    }
}
 
Example 33
Project: idea-php-dotenv-plugin   File: DotEnvLightCodeInsightFixtureTestCase.java   View source code 5 votes vote down vote up
protected void assertLocalInspectionIsEmpty(String filename, String content) {
    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);

    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond())) {
            fail("Fail that matches is empty");
        }
    }
}
 
Example 34
Project: IntellijMethodHierarchyHighlighter   File: MethodFolder.java   View source code 5 votes vote down vote up
private Optional<FoldRegion> getFoldRegionOfMethod(Editor editor, PsiMethod psiMethod) {
	TextRange textRange = psiMethod.getTextRange();
	for (FoldRegion foldRegion : editor.getFoldingModel().getAllFoldRegions()) {
		if (textRange.getEndOffset() == foldRegion.getEndOffset()) {
			return Optional.of(foldRegion);
		}
	}
	return Optional.empty();
}
 
Example 35
Project: IntellijMethodHierarchyHighlighter   File: MethodBackgroundPainter.java   View source code 5 votes vote down vote up
@NotNull
private RangeHighlighter applyHighlight(Editor editor, TextAttributes attributes, PsiMethod psiMethod) {
	TextRange textRange = psiMethod.getTextRange();
	int start = textRange.getStartOffset();
	int end = textRange.getEndOffset();
	MarkupModel markupModel = editor.getMarkupModel();
	return markupModel.addRangeHighlighter(start, end, COLOR_Z_INDEX, attributes, TARGET_AREA);
}
 
Example 36
Project: GoogleTranslation   File: GoogleTranslation.java   View source code 5 votes vote down vote up
private String getCurrentWords(Editor editor) {
    Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    int caretOffset = caretModel.getOffset();
    int lineNum = document.getLineNumber(caretOffset);
    int lineStartOffset = document.getLineStartOffset(lineNum);
    int lineEndOffset = document.getLineEndOffset(lineNum);
    String lineContent = document.getText(new TextRange(lineStartOffset, lineEndOffset));
    char[] chars = lineContent.toCharArray();
    int start = 0, end = 0, cursor = caretOffset - lineStartOffset;

    if (!Character.isLetter(chars[cursor])) {
        return null;
    }

    for (int ptr = cursor; ptr >= 0; ptr--) {
        if (!Character.isLetter(chars[ptr])) {
            start = ptr + 1;
            break;
        }
    }

    int lastLetter = 0;
    for (int ptr = cursor; ptr < lineEndOffset - lineStartOffset; ptr++) {
        lastLetter = ptr;
        if (!Character.isLetter(chars[ptr])) {
            end = ptr;
            break;
        }
    }
    if (end == 0) {
        end = lastLetter + 1;
    }

    return new String(chars, start, end - start);
}
 
Example 37
Project: hybris-integration-intellij-idea-plugin   File: FlexibleSearchFormattingModelBuilder.java   View source code 5 votes vote down vote up
@Nullable
@Override
public TextRange getRangeAffectingIndent(
    final PsiFile file, final int offset, final ASTNode elementAtOffset
) {
    return null;
}
 
Example 38
Project: hybris-integration-intellij-idea-plugin   File: DefaultImpexColumnHighlighterService.java   View source code 5 votes vote down vote up
@Contract
protected void modifyHighlightedArea(
    @NotNull final Editor editor,
    @NotNull final List<PsiElement> column,
    final boolean clear
) {
    Validate.notNull(editor);
    Validate.notNull(column);

    if (null == editor.getProject()) {
        return;
    }

    if (editor.getProject().isDisposed()) {
        return;
    }

    // This list must be modifiable
    // https://bitbucket.org/AlexanderBartash/impex-editor-intellij-idea-plugin/issue/11/unsupportedoperationexception-null
    final List<TextRange> ranges = newArrayList();
    column.forEach((cell) -> ranges.add(cell.getTextRange()));

    HighlightUsagesHandler.highlightRanges(
        HighlightManager.getInstance(editor.getProject()),
        editor,
        EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES),
        clear,
        ranges
    );
}
 
Example 39
Project: hybris-integration-intellij-idea-plugin   File: DefaultImpexHeaderNameHighlighterService.java   View source code 5 votes vote down vote up
@Contract(pure = false)
protected void modifyHighlightedArea(
    @NotNull final Editor editor,
    @NotNull final PsiElement impexFullHeaderParameter,
    final boolean clear
) {
    Validate.notNull(editor);
    Validate.notNull(impexFullHeaderParameter);

    if (null == editor.getProject()) {
        return;
    }

    if (editor.getProject().isDisposed()) {
        return;
    }

    // This list must be modifiable
    // https://bitbucket.org/AlexanderBartash/impex-editor-intellij-idea-plugin/issue/11/unsupportedoperationexception-null
    final List<TextRange> ranges = new ArrayList<TextRange>();
    ranges.add(impexFullHeaderParameter.getTextRange());

    HighlightUsagesHandler.highlightRanges(
        HighlightManager.getInstance(editor.getProject()),
        editor,
        EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES),
        clear,
        ranges
    );
}
 
Example 40
Project: hybris-integration-intellij-idea-plugin   File: ImpexFoldingDescriptor.java   View source code 5 votes vote down vote up
public ImpexFoldingDescriptor(
    @NotNull final PsiElement psiElement,
    @NotNull final FoldingGroup group
) {
    super(
        psiElement.getNode(),
        new TextRange(
            psiElement.getTextRange().getStartOffset(),
            psiElement.getTextRange().getEndOffset()
        ),
        group
    );

    placeholder = ImpexFoldingPlaceholderBuilderFactory.getPlaceholderBuilder().getPlaceholder(psiElement);
}