Java Code Examples for com.intellij.openapi.util.TextRange#getLength()

The following examples show how to use com.intellij.openapi.util.TextRange#getLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TemplateState.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void considerNextTabOnLookupItemSelected(LookupElement item) {
  if (item != null) {
    ExpressionContext context = getCurrentExpressionContext();
    for (TemplateCompletionProcessor processor : Extensions.getExtensions(TemplateCompletionProcessor.EP_NAME)) {
      if (!processor.nextTabOnItemSelected(context, item)) {
        return;
      }
    }
  }
  TextRange range = getCurrentVariableRange();
  if (range != null && range.getLength() > 0) {
    int caret = myEditor.getCaretModel().getOffset();
    if (caret == range.getEndOffset() || isCaretInsideNextVariable()) {
      nextTab();
    }
    else if (caret > range.getEndOffset()) {
      gotoEnd(true);
    }
  }
}
 
Example 2
Source File: PsiToDocumentSynchronizer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int documentToPsiOffset(int offset, boolean greedyRight) {
  int delta = 0;
  for (Map.Entry<TextRange, CharSequence> entry : myAffectedFragments.entrySet()) {
    int lengthAfter = entry.getValue().length();
    TextRange range = entry.getKey();
    // for offsets inside affected fragments, return either start or end of the updated range
    if (range.containsOffset(offset)) {
      return range.getStartOffset() + delta + (greedyRight ? lengthAfter : 0);
    }
    if (range.getStartOffset() > offset) {
      break;
    }
    delta += lengthAfter - range.getLength();
  }
  return offset + delta;
}
 
Example 3
Source File: GLSLFoldingBuilder.java    From glsl4idea with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void appendDescriptors(final ASTNode node, final List<FoldingDescriptor> descriptors) {
    IElementType type = node.getElementType();

    final TextRange textRange = node.getTextRange();
    //Don't add folding to 0-length nodes, crashes in new FoldingDescriptor
    if(textRange.getLength() <= 0)return;

    if (type == GLSLTokenTypes.COMMENT_BLOCK || type == GLSLElementTypes.COMPOUND_STATEMENT) {
        descriptors.add(new FoldingDescriptor(node, textRange));
    }

    ASTNode child = node.getFirstChildNode();
    while (child != null) {
        appendDescriptors(child, descriptors);
        child = child.getTreeNext();
    }
}
 
Example 4
Source File: AbstractCaseConvertingAction.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
private boolean propertiesHandling(Editor editor, DataContext dataContext, SelectionModel selectionModel,
		PsiFile psiFile) {
	PsiElement elementAtCaret = PsiUtilBase.getElementAtCaret(editor);
	if (elementAtCaret instanceof PsiWhiteSpace) {
		return false;
	} else if (elementAtCaret instanceof LeafPsiElement) {
		IElementType elementType = ((LeafPsiElement) elementAtCaret).getElementType();
		if (elementType.toString().equals("Properties:VALUE_CHARACTERS")
				|| elementType.toString().equals("Properties:KEY_CHARACTERS")) {
			TextRange textRange = elementAtCaret.getTextRange();
			if (textRange.getLength() == 0) {
				return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
			}
			selectionModel.setSelection(textRange.getStartOffset(), textRange.getEndOffset());
			return true;
		}
	}
	return false;
}
 
Example 5
Source File: MergeOperations.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ArrayList<Operation> getOperations() {
  Fragment fragment = getCurrentFragment();
  if (fragment == null) return NO_OPERATIONS;
  ArrayList<Operation> operations = new ArrayList<Operation>(3);
  TextRange range = fragment.getRange(mySide);
  if (range.getLength() > 0) {
    if (isWritable(mySide)) operations.add(removeOperation(range, getDocument()));
    TextRange otherRange = fragment.getRange(mySide.otherSide());
    boolean otherIsWritable = isWritable(mySide.otherSide());
    if (otherIsWritable) operations.add(insertOperation(range, otherRange.getEndOffset(), getDocument(), getOtherDocument()));
    if (otherRange.getLength() > 0 && otherIsWritable) operations.add(replaceOperation(range, otherRange, getDocument(), getOtherDocument()));
  }
  return operations;
}
 
Example 6
Source File: FormatProcessorUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static int replaceWhiteSpace(final FormattingModel model,
                                    @Nonnull final LeafBlockWrapper block,
                                    int shift,
                                    final CharSequence _newWhiteSpace,
                                    final CommonCodeStyleSettings.IndentOptions options
) {
  final WhiteSpace whiteSpace = block.getWhiteSpace();
  final TextRange textRange = whiteSpace.getTextRange();
  final TextRange wsRange = textRange.shiftRight(shift);
  final String newWhiteSpace = _newWhiteSpace.toString();
  TextRange newWhiteSpaceRange = model instanceof FormattingModelEx
                                 ? ((FormattingModelEx) model).replaceWhiteSpace(wsRange, block.getNode(), newWhiteSpace)
                                 : model.replaceWhiteSpace(wsRange, newWhiteSpace);

  shift += newWhiteSpaceRange.getLength() - textRange.getLength();

  if (block.isLeaf() && whiteSpace.containsLineFeeds() && block.containsLineFeeds()) {
    final TextRange currentBlockRange = block.getTextRange().shiftRight(shift);

    IndentInside oldBlockIndent = whiteSpace.getInitialLastLineIndent();
    IndentInside whiteSpaceIndent = IndentInside.createIndentOn(IndentInside.getLastLine(newWhiteSpace));
    final int shiftInside = calcShift(oldBlockIndent, whiteSpaceIndent, options);

    if (shiftInside != 0 || !oldBlockIndent.equals(whiteSpaceIndent)) {
      final TextRange newBlockRange = model.shiftIndentInsideRange(block.getNode(), currentBlockRange, shiftInside);
      shift += newBlockRange.getLength() - block.getLength();
    }
  }
  return shift;
}
 
Example 7
Source File: FragmentedEditorHighlighter.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void translate(HighlighterIterator iterator, List<TextRange> ranges) {
  if (iterator.atEnd()) return;
  int offset = 0;
  for (TextRange range : ranges) {
    while (range.getStartOffset() > iterator.getStart()) {
      iterator.advance();
      if (iterator.atEnd()) return;
    }
    while (range.getEndOffset() >= iterator.getEnd()) {
      int relativeStart = iterator.getStart() - range.getStartOffset();
      boolean merged = false;
      if (myMergeByTextAttributes && ! myPieces.isEmpty()) {
        final Integer first = myPieces.descendingKeySet().first();
        final Element element = myPieces.get(first);
        if (element.getEnd() >= offset + relativeStart && myPieces.get(first).getAttributes().equals(iterator.getTextAttributes())) {
          // merge
          merged = true;
          myPieces.put(element.getStart(), new Element(element.getStart(),
                                                       offset + (iterator.getEnd() - range.getStartOffset()), iterator.getTokenType(),
                                                       iterator.getTextAttributes()));
        }
      }
      if (! merged) {
        myPieces.put(offset + relativeStart, new Element(offset + relativeStart,
                                                         offset + (iterator.getEnd() - range.getStartOffset()), iterator.getTokenType(),
                                                         iterator.getTextAttributes()));
      }
      iterator.advance();
      if (iterator.atEnd()) return;
    }
    offset += range.getLength() + 1 + myAdditionalOffset;  // myAdditionalOffset because of extra line - for shoene separators
  }
}
 
Example 8
Source File: CSharpStringLiteralEscaper.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
public int getOffsetInHost(int offsetInDecoded, @Nonnull final TextRange rangeInsideHost)
{
	int result = offsetInDecoded < myOutSourceOffsets.length ? myOutSourceOffsets[offsetInDecoded] : -1;
	if(result == -1)
	{
		return -1;
	}
	return (result <= rangeInsideHost.getLength() ? result : rangeInsideHost.getLength()) + rangeInsideHost.getStartOffset();
}
 
Example 9
Source File: MergeOperations.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static Operation mostSensible(Document document, Document otherDocument, TextRange range, TextRange otherRange) {
  if (!canMakeWritable(document) && !canMakeWritable(otherDocument)) return null;
  if (range.getLength() != 0) {
    if (canMakeWritable(otherDocument))
      return otherRange.getLength() != 0 ?
             replaceOperation(range, otherRange, document, otherDocument) :
             insertOperation(range, otherRange.getEndOffset(), document, otherDocument);
    else return otherRange.getLength() == 0 ? removeOperation(range, document) : null;
  }
  return null;
}
 
Example 10
Source File: BaseCompleteMacro.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void considerNextTab(Editor editor) {
  TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (templateState != null) {
    TextRange range = templateState.getCurrentVariableRange();
    if (range != null && range.getLength() > 0) {
      int caret = editor.getCaretModel().getOffset();
      if (caret == range.getEndOffset()) {
        templateState.nextTab();
      }
      else if (caret > range.getEndOffset()) {
        templateState.cancelTemplate();
      }
    }
  }
}
 
Example 11
Source File: BashEnhancedLiteralTextEscaper.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
public int getOffsetInHost(int offsetInDecoded, @NotNull final TextRange rangeInsideHost) {
    int result = offsetInDecoded < outSourceOffsets.length ? outSourceOffsets[offsetInDecoded] : -1;
    if (result == -1) {
        return -1;
    }

    return (result <= rangeInsideHost.getLength() ? result : rangeInsideHost.getLength()) + rangeInsideHost.getStartOffset();
}
 
Example 12
Source File: CsvHighlightUsagesHandler.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
protected void addOccurrence(CsvColumnInfo<PsiElement>.RowInfo rowInfo) {
    if (rowInfo == null) {
        return;
    }
    TextRange range = rowInfo.getTextRange();
    if (range != null && range.getLength() > 0) {
        this.myReadUsages.add(range);
    }
}
 
Example 13
Source File: FoldingBuilder.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
private void foldType(@NotNull List<FoldingDescriptor> descriptors, @NotNull PsiType typeExpression) {
    PsiElement constrName = PsiTreeUtil.findChildOfType(typeExpression, PsiTypeConstrName.class);
    if (constrName != null) {
        ORTypes types = ORTypesUtil.getInstance(typeExpression.getLanguage());
        PsiElement eqElement = ORUtil.nextSiblingWithTokenType(constrName, types.EQ);
        if (eqElement != null) {
            TextRange eqRange = eqElement.getTextRange();
            TextRange typeRange = typeExpression.getTextRange();
            TextRange textRange = TextRange.create(eqRange.getStartOffset(), typeRange.getEndOffset());
            if (textRange.getLength() > 5) {
                descriptors.add(new FoldingDescriptor(typeExpression, textRange));
            }
        }
    }
}
 
Example 14
Source File: ANTLRv4FoldingBuilder.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static void addHeaderFoldingDescriptor(List<FoldingDescriptor> descriptors, PsiElement root, Document document) {
    TextRange range = getFileHeader(root);
    if (range != null && range.getLength() > 1 && document.getLineNumber(range.getEndOffset()) > document.getLineNumber(range.getStartOffset())) {
        descriptors.add(new FoldingDescriptor(root, range));
    }
}
 
Example 15
Source File: WidgetRenderViewReferenceProvider.java    From yiistorm with MIT License 4 votes vote down vote up
public static PsiReference[] getReference(String path, @NotNull PsiElement element) {
    try {
        String currentPath = path.replace(YiiPsiReferenceProvider.projectPath, "").replaceAll("/[a-zA-Z0-9_]+?.(php|tpl)+$", "");
        String protectedPath = CommonHelper.searchCurrentProtected(path).replace(YiiPsiReferenceProvider.projectPath, "");
        String viewAbsolutePath = protectedPath + "/views";
        String viewPath = currentPath + "/views";

        String str = element.getText();
        TextRange textRange = CommonHelper.getTextRange(element, str);
        String uri = str.substring(textRange.getStartOffset(), textRange.getEndOffset());
        int start = textRange.getStartOffset();
        int len = textRange.getLength();

        if (!uri.endsWith(".tpl") && !uri.startsWith("smarty:")) {
            uri += ".php";
        }

        VirtualFile baseDir = YiiPsiReferenceProvider.project.getBaseDir();
        if (baseDir != null) {
            VirtualFile appDir = baseDir.findFileByRelativePath(viewPath);
            VirtualFile protectedPathDir = (!protectedPath.equals("")) ? baseDir.findFileByRelativePath(protectedPath) : null;

            String filepath = viewPath + "/" + uri;
            if (uri.matches("^//.+")) {
                filepath = viewAbsolutePath + "/" + uri.replace("//", "");
            }
            VirtualFile file = baseDir.findFileByRelativePath(filepath);

            if (file != null && appDir != null) {
                PsiReference ref = new FileReference(file, uri, element,
                        new TextRange(start, start + len), YiiPsiReferenceProvider.project, protectedPathDir, appDir);
                return new PsiReference[]{ref};
            }
        }
        return PsiReference.EMPTY_ARRAY;

    } catch (Exception e) {
        System.err.println("error" + e.getMessage());
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 16
Source File: ChangeType.java    From consulo with Apache License 2.0 4 votes vote down vote up
static ChangeType fromRanges(@Nonnull TextRange left, @Nonnull TextRange right) {
  if (left.getLength() == 0) return INSERT;
  if (right.getLength() == 0) return DELETED;
  return CHANGE;
}
 
Example 17
Source File: ViewRenderViewReferenceProvider.java    From yiistorm with MIT License 4 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
    project = element.getProject();
    String elname = element.getClass().getName();
    properties = PropertiesComponent.getInstance(project);
    if (elname.endsWith("StringLiteralExpressionImpl")) {
        try {
            PsiFile file = element.getContainingFile();
            VirtualFile vfile = file.getVirtualFile();
            if (vfile != null) {
                String path = vfile.getPath();
                VirtualFile baseDir = project.getBaseDir();
                if (baseDir == null) {
                    return PsiReference.EMPTY_ARRAY;
                }
                String basePath = baseDir.getCanonicalPath();
                if (basePath != null) {
                    String viewPath = path.replace(basePath, "")
                            .replaceAll("/[a-zA-Z0-9_]+?.(php|tpl)+", "");
                    String viewAbsolutePath = YiiRefsHelper.getViewParentPath(path
                            .replace(basePath, ""));
                    String protectedPath = YiiRefsHelper.getCurrentProtected(path);
                    protectedPath = protectedPath.replace(basePath, "");

                    String str = element.getText();
                    TextRange textRange = CommonHelper.getTextRange(element, str);
                    String uri = str.substring(textRange.getStartOffset(), textRange.getEndOffset());
                    int start = textRange.getStartOffset();
                    int len = textRange.getLength();

                    if (!uri.endsWith(".tpl") && !uri.startsWith("smarty:")) {
                        uri += ".php";
                    }

                    VirtualFile appDir = baseDir.findFileByRelativePath(viewPath);
                    VirtualFile protectedPathDir = (!protectedPath.equals(""))
                            ? baseDir.findFileByRelativePath(protectedPath) : null;

                    String filepath = viewPath + "/" + uri;
                    if (uri.matches("^//.+")) {
                        filepath = viewAbsolutePath + "/" + uri.replace("//", "");
                    }
                    VirtualFile viewfile = baseDir.findFileByRelativePath(filepath);

                    if (viewfile != null && appDir != null) {
                        PsiReference ref = new FileReference(
                                viewfile,
                                uri,
                                element,
                                new TextRange(start, start + len),
                                project,
                                protectedPathDir,
                                appDir);
                        return new PsiReference[]{ref};
                    }

                }
            }
        } catch (Exception e) {
            System.err.println("error" + e.getMessage());
        }
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 18
Source File: MergeOperations.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void setSelection(Fragment fragment, FragmentSide side) {
  TextRange range = fragment.getRange(side);
  if (range.getLength() > 0)
  myDiffPanel.getEditor(side).getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
}
 
Example 19
Source File: CodeStyleAbstractPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void blinkHighlighters() {
  MarkupModel markupModel = myEditor.getMarkupModel();
  if (myShowsPreviewHighlighters) {
    Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea();
    VisualPosition visualStart = myEditor.xyToVisualPosition(visibleArea.getLocation());
    VisualPosition visualEnd = myEditor.xyToVisualPosition(new Point(visibleArea.x + visibleArea.width, visibleArea.y + visibleArea.height));

    // There is a possible case that viewport is located at its most bottom position and last document symbol
    // is located at the start of the line, hence, resulting visual end column has a small value and doesn't actually
    // indicates target visible rectangle. Hence, we need to correct that if necessary.
    int endColumnCandidate = visibleArea.width / EditorUtil.getSpaceWidth(Font.PLAIN, myEditor) + visualStart.column;
    if (endColumnCandidate > visualEnd.column) {
      visualEnd = new VisualPosition(visualEnd.line, endColumnCandidate);
    }
    int offsetToScroll = -1;
    CharSequence text = myEditor.getDocument().getCharsSequence();
    TextAttributes backgroundAttributes = myEditor.getColorsScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    TextAttributes borderAttributes = new TextAttributes(
            null, null, backgroundAttributes.getBackgroundColor(), EffectType.BOXED, Font.PLAIN
    );
    boolean scrollToChange = true;
    for (TextRange range : myPreviewRangesToHighlight) {
      if (scrollToChange) {
        boolean rangeVisible = isWithinBounds(myEditor.offsetToVisualPosition(range.getStartOffset()), visualStart, visualEnd)
                               || isWithinBounds(myEditor.offsetToVisualPosition(range.getEndOffset()), visualStart, visualEnd);
        scrollToChange = !rangeVisible;
        if (offsetToScroll < 0) {
          if (offsetToScroll < 0) {
            if (text.charAt(range.getStartOffset()) != '\n') {
              offsetToScroll = range.getStartOffset();
            }
            else if (range.getEndOffset() > 0 && text.charAt(range.getEndOffset() - 1) != '\n') {
              offsetToScroll = range.getEndOffset() - 1;
            }
          }
        }
      }

      TextAttributes attributesToUse = range.getLength() > 0 ? backgroundAttributes : borderAttributes;
      markupModel.addRangeHighlighter(
              range.getStartOffset(), range.getEndOffset(), HighlighterLayer.SELECTION, attributesToUse, HighlighterTargetArea.EXACT_RANGE
      );
    }

    if (scrollToChange) {
      if (offsetToScroll < 0 && !myPreviewRangesToHighlight.isEmpty()) {
        offsetToScroll = myPreviewRangesToHighlight.get(0).getStartOffset();
      }
      if (offsetToScroll >= 0 && offsetToScroll < text.length() - 1 && text.charAt(offsetToScroll) != '\n') {
        // There is a possible case that target offset is located too close to the right edge. However, our point is to show
        // highlighted region at target offset, hence, we need to scroll to the visual symbol end. Hence, we're trying to ensure
        // that by scrolling to the symbol's end over than its start.
        offsetToScroll++;
      }
      if (offsetToScroll >= 0 && offsetToScroll < myEditor.getDocument().getTextLength()) {
        myEditor.getScrollingModel().scrollTo(
                myEditor.offsetToLogicalPosition(offsetToScroll), ScrollType.RELATIVE
        );
      }
    }
  }
  else {
    markupModel.removeAllHighlighters();
  }
  myShowsPreviewHighlighters = !myShowsPreviewHighlighters;
}
 
Example 20
Source File: EclipseRegionAdapter.java    From spring-javaformat with Apache License 2.0 4 votes vote down vote up
public EclipseRegionAdapter(TextRange range) {
	super(range.getStartOffset(), range.getLength());
}