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

The following examples show how to use com.intellij.openapi.util.TextRange. These examples are extracted from open source projects. 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 Project: consulo   Source File: PsiTreeUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static <T extends PsiElement> T findElementOfClassAtOffset(@Nonnull PsiFile file, int offset, @Nonnull Class<T> clazz, boolean strictStart) {
  final List<PsiFile> psiRoots = file.getViewProvider().getAllFiles();
  T result = null;
  for (PsiElement root : psiRoots) {
    final PsiElement elementAt = root.findElementAt(offset);
    if (elementAt != null) {
      final T parent = getParentOfType(elementAt, clazz, strictStart);
      if (parent != null) {
        final TextRange range = parent.getTextRange();
        if (!strictStart || range.getStartOffset() == offset) {
          if (result == null || result.getTextRange().getEndOffset() > range.getEndOffset()) {
            result = parent;
          }
        }
      }
    }
  }

  return result;
}
 
Example 2
Source Project: intellij-latte   Source File: LatteFoldingBuilder.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
	List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();

	if (!quick) {
		Collection<LatteMacroClassic> nodes = PsiTreeUtil.findChildrenOfAnyType(root, LatteMacroClassic.class);
		for (PsiElement node : nodes) {
			int start = node.getFirstChild().getTextRange().getEndOffset();
			int end = node.getLastChild().getTextRange().getEndOffset();
			if (end == start) {
				continue;
			}
			if (node instanceof LatteMacroClassic) {
				start--;
				end--;
			}

			descriptors.add(new FoldingDescriptor(node, TextRange.create(start, end)));

		}
	}

	return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
 
Example 3
Source Project: intellij-haxe   Source File: SelectionUtil.java    License: Apache License 2.0 6 votes vote down vote up
static private TextRange findTokenLimits(PsiElement e, int offset, boolean useWhitespace) {
  final int tokenOffset = e.getTextOffset();
  int startPos = offset - tokenOffset;
  int endPos = startPos;
  final String text = e.getText();
  final int length = text.length();

  // While scanning for the beginning and end of a word, we don't have to
  // worry about escaped characters ("\n") because they are split apart into
  // separate REGULAR_STRING_PART lexemes.  Thus, they are automatically string
  // separators.

  // Scan backward for the start of the word.  If the offset is a space, then
  // we want the word before the startPos.
  while (startPos > 0 && !isDelimiter(text.charAt(startPos - 1), useWhitespace)) {
    --startPos;
  }

  // Scan forward to find the end of the word.  If this offset is whitespace, then
  // we are done.
  while (endPos < length && !isDelimiter(text.charAt(endPos), useWhitespace)) {
    ++endPos;
  }
  return new TextRange(startPos + tokenOffset, endPos + tokenOffset);
}
 
Example 4
Source Project: consulo   Source File: BlockUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
public static List<DataLanguageBlockWrapper> filterBlocksByRange(@Nonnull List<DataLanguageBlockWrapper> list, @Nonnull TextRange textRange) {
  int i = 0;
  while (i < list.size()) {
    final DataLanguageBlockWrapper wrapper = list.get(i);
    final TextRange range = wrapper.getTextRange();
    if (textRange.contains(range)) {
      i++;
    }
    else if (range.intersectsStrict(textRange)) {
      list.remove(i);
      list.addAll(i, buildChildWrappers(wrapper.getOriginal()));
    }
    else {
      list.remove(i);
    }
  }
  return list;
}
 
Example 5
Source Project: consulo   Source File: CodeFormatterFacade.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
static ASTNode findContainingNode(@Nonnull PsiFile file, @Nullable TextRange range) {
  Language language = file.getLanguage();
  if (range == null) return null;
  final FileViewProvider viewProvider = file.getViewProvider();
  final PsiElement startElement = viewProvider.findElementAt(range.getStartOffset(), language);
  final PsiElement endElement = viewProvider.findElementAt(range.getEndOffset() - 1, language);
  final PsiElement commonParent = startElement != null && endElement != null ? PsiTreeUtil.findCommonParent(startElement, endElement) : null;
  ASTNode node = null;
  if (commonParent != null) {
    node = commonParent.getNode();
    // Find the topmost parent with the same range.
    ASTNode parent = node.getTreeParent();
    while (parent != null && parent.getTextRange().equals(commonParent.getTextRange())) {
      node = parent;
      parent = parent.getTreeParent();
    }
  }
  if (node == null) {
    node = file.getNode();
  }
  return node;
}
 
Example 6
Source Project: consulo   Source File: OffsetsElementSignatureProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getSignature(@Nonnull PsiElement element) {
  TextRange range = element.getTextRange();
  if (range.isEmpty()) {
    return null;
  }
  StringBuilder buffer = new StringBuilder();
  buffer.append(TYPE_MARKER).append("#");
  buffer.append(range.getStartOffset());
  buffer.append(ELEMENT_TOKENS_SEPARATOR);
  buffer.append(range.getEndOffset());
  
  // There is a possible case that given PSI element has a parent or child that targets the same range. So, we remember
  // not only target range offsets but 'hierarchy index' as well.
  int index = 0;
  for (PsiElement e = element.getParent(); e != null && range.equals(e.getTextRange()); e = e.getParent()) {
    index++;
  }
  buffer.append(ELEMENT_TOKENS_SEPARATOR).append(index);
  return buffer.toString();
}
 
Example 7
Source Project: consulo   Source File: DocumentFoldingInfo.java    License: Apache License 2.0 6 votes vote down vote up
void loadFromEditor(@Nonnull Editor editor) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  LOG.assertTrue(!editor.isDisposed());
  clear();

  FoldRegion[] foldRegions = editor.getFoldingModel().getAllFoldRegions();
  for (FoldRegion region : foldRegions) {
    if (!region.isValid()) continue;
    boolean expanded = region.isExpanded();
    String signature = region.getUserData(UpdateFoldRegionsOperation.SIGNATURE);
    if (signature == UpdateFoldRegionsOperation.NO_SIGNATURE) continue;
    Boolean storedCollapseByDefault = region.getUserData(UpdateFoldRegionsOperation.COLLAPSED_BY_DEFAULT);
    boolean collapseByDefault = storedCollapseByDefault != null && storedCollapseByDefault && !FoldingUtil.caretInsideRange(editor, TextRange.create(region));
    if (collapseByDefault == expanded || signature == null) {
      if (signature != null) {
        myInfos.add(new Info(signature, expanded));
      }
      else {
        RangeMarker marker = editor.getDocument().createRangeMarker(region.getStartOffset(), region.getEndOffset());
        myRangeMarkers.add(marker);
        marker.putUserData(FOLDING_INFO_KEY, new FoldingInfo(region.getPlaceholderText(), expanded));
      }
    }
  }
}
 
Example 8
@Override
public void updateUI(DotNetGenericParameterListOwner p, ParameterInfoUIContext context)
{
	if(p == null)
	{
		context.setUIComponentEnabled(false);
		return;
	}
	CSharpGenericParametersInfo build = CSharpGenericParametersInfo.build(p);
	if(build == null)
	{
		context.setUIComponentEnabled(false);
		return;
	}

	String text = build.getText();

	TextRange parameterRange = build.getParameterRange(context.getCurrentParameterIndex());

	context.setupUIComponentPresentation(text, parameterRange.getStartOffset(), parameterRange.getEndOffset(), !context.isUIComponentEnabled(),
			false, false, context.getDefaultParameterColor());
}
 
Example 9
Source Project: consulo   Source File: RangeMarkerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testPsi2DocSurround() throws Exception {
  StringBuilder buffer = new StringBuilder("0123456789");
  RangeMarker marker = createMarker(buffer.toString(), 2, 5);
  synchronizer.startTransaction(getProject(), document, psiFile);

  synchronizer.replaceString(document, 3, 5, "3a4");
  buffer.replace(3, 5, "3a4");

  synchronizer.insertString(document, 3, "b");
  buffer.insert(3, "b");

  synchronizer.insertString(document, 7, "d");
  buffer.insert(7, "d");

  final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
  final Map<TextRange, CharSequence> affectedFragments = transaction.getAffectedFragments();
  assertEquals(3, affectedFragments.size());

  synchronizer.commitTransaction(document);

  assertEquals(buffer.toString(), document.getText());

  assertValidMarker(marker, 2, 7);
}
 
Example 10
Source Project: intellij-haxe   Source File: HaxeDocumentModel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Replace the text within the given range and reformat it according to the user's
 * code style/formatting rules.
 *
 * NOTE: The PSI may be entirely invalidated and re-created by this call.
 *
 * @param range Range of text or PsiElements to replace.
 * @param text Replacement text (may be null).
 */
public void replaceAndFormat(@NotNull final TextRange range, @Nullable String text) {
  if (null == text) {
    text = "";
  }

  // Mark the beginning and end so that we have the proper range after adding text.
  // Greedy means that the text immediately added at the beginning/end of the marker are included.
  RangeMarker marker = document.createRangeMarker(range);
  marker.setGreedyToLeft(true);
  marker.setGreedyToRight(true);

  try {

    document.replaceString(range.getStartOffset(), range.getEndOffset(), text);

    //PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); // force update PSI.

    if (marker.isValid()) { // If the range wasn't reduced to zero.
      CodeStyleManager.getInstance(file.getProject()).reformatText(file, marker.getStartOffset(), marker.getEndOffset());
    }
  }
  finally {
    marker.dispose();
  }
}
 
Example 11
Source Project: bamboo-soy   Source File: UnterminatedCommentAnnotator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder annotationHolder) {
  if (element instanceof PsiComment) {
    IElementType commentTokenType = ((PsiComment) element).getTokenType();
    if (commentTokenType != SoyTypes.DOC_COMMENT_BLOCK
        && commentTokenType != SoyTypes.COMMENT_BLOCK) {
      return;
    }
    if (!element.getText().endsWith("*/")) {
      int start = element.getTextRange().getEndOffset() - 1;
      int end = start + 1;
      annotationHolder
          .createErrorAnnotation(TextRange.create(start, end), "Unterminated comment");
    }
  }
}
 
Example 12
Source Project: intellij   Source File: ProjectViewRearranger.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Entry> parse(
    PsiElement root,
    @Nullable Document document,
    Collection<TextRange> ranges,
    ArrangementSettings settings) {
  if (root instanceof ProjectViewPsiListSection) {
    Entry entry = fromListSection(ranges, (ProjectViewPsiListSection) root);
    return entry != null ? ImmutableList.of(entry) : ImmutableList.of();
  }
  if (root instanceof ProjectViewPsiFile) {
    return Arrays.stream(
            ((ProjectViewPsiFile) root).findChildrenByClass(ProjectViewPsiListSection.class))
        .map(section -> fromListSection(ranges, section))
        .filter(Objects::nonNull)
        .collect(toImmutableList());
  }
  return ImmutableList.of();
}
 
Example 13
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) {
    RequirejsProjectComponent projectComponent = psiElement.getProject().getComponent(RequirejsProjectComponent.class);

    if (!projectComponent.isEnabled()) {
        return PsiReference.EMPTY_ARRAY;
    }

    String path = psiElement.getText();
    if (isRequireCall(psiElement) || isDefineFirstCollection(psiElement)) {
        PsiReference ref = new RequirejsReference(psiElement, new TextRange(1, path.length() - 1));
        return new PsiReference[] {ref};
    }

    return new PsiReference[0];
}
 
Example 14
public void appendColoredFragments(final MultiIconSimpleColoredComponent simpleColoredComponent,
                                   final String text,
                                   Iterable<TextRange> colored,
                                   final SimpleTextAttributes plain, final SimpleTextAttributes highlighted) {
  final List<Pair<String, Integer>> searchTerms = new ArrayList<>();
  for (TextRange fragment : colored) {
    searchTerms.add(Pair.create(fragment.substring(text), fragment.getStartOffset()));
  }

  int lastOffset = 0;
  for (Pair<String, Integer> pair : searchTerms) {
    if (pair.second > lastOffset) {
      simpleColoredComponent.append(text.substring(lastOffset, pair.second), plain);
    }

    simpleColoredComponent.append(text.substring(pair.second, pair.second + pair.first.length()), highlighted);
    lastOffset = pair.second + pair.first.length();
  }

  if (lastOffset < text.length()) {
    simpleColoredComponent.append(text.substring(lastOffset), plain);
  }
}
 
Example 15
Source Project: consulo   Source File: CodeStyleManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private static PsiElement reformatRangeImpl(final @Nonnull PsiElement element, final int startOffset, final int endOffset, boolean canChangeWhiteSpacesOnly) throws IncorrectOperationException {
  LOG.assertTrue(element.isValid());
  CheckUtil.checkWritable(element);
  if (!SourceTreeToPsiMap.hasTreeElement(element)) {
    return element;
  }

  ASTNode treeElement = element.getNode();
  final PsiFile file = element.getContainingFile();
  if (ExternalFormatProcessor.useExternalFormatter(file)) {
    return ExternalFormatProcessor.formatElement(element, TextRange.create(startOffset, endOffset), canChangeWhiteSpacesOnly);
  }

  final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(getSettings(file), element.getLanguage());
  final PsiElement formatted = codeFormatter.processRange(treeElement, startOffset, endOffset).getPsi();
  return canChangeWhiteSpacesOnly ? formatted : postProcessElement(file, formatted);
}
 
Example 16
Source Project: consulo   Source File: Identikit.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private PsiElement findParent(int startOffset, int endOffset, PsiElement anchor) {
  TextRange range = anchor.getTextRange();

  if (range.getStartOffset() != startOffset) return null;
  while (range.getEndOffset() < endOffset) {
    anchor = anchor.getParent();
    if (anchor == null || anchor instanceof PsiDirectory) {
      return null;
    }
    range = anchor.getTextRange();
  }

  while (range.getEndOffset() == endOffset) {
    if (isAcceptable(anchor)) {
      return anchor;
    }
    anchor = anchor.getParent();
    if (anchor == null || anchor instanceof PsiDirectory) break;
    range = anchor.getTextRange();
  }

  return null;
}
 
Example 17
Source Project: consulo   Source File: DeleteLineAction.java    License: Apache License 2.0 6 votes vote down vote up
private static TextRange getRangeToDelete(Editor editor, Caret caret) {
  int selectionStart = caret.getSelectionStart();
  int selectionEnd = caret.getSelectionEnd();
  int startOffset = EditorUtil.getNotFoldedLineStartOffset(editor, selectionStart);
  // There is a possible case that selection ends at the line start, i.e. something like below ([...] denotes selected text,
  // '|' is a line start):
  //   |line 1
  //   |[line 2
  //   |]line 3
  // We don't want to delete line 3 here. However, the situation below is different:
  //   |line 1
  //   |[line 2
  //   |line] 3
  // Line 3 must be removed here.
  int endOffset = EditorUtil.getNotFoldedLineEndOffset(editor, selectionEnd > 0 && selectionEnd != selectionStart ? selectionEnd - 1 : selectionEnd);
  if (endOffset < editor.getDocument().getTextLength()) {
    endOffset++;
  }
  else if (startOffset > 0) {
    startOffset--;
  }
  return new TextRange(startOffset, endOffset);
}
 
Example 18
Source Project: consulo   Source File: FileStatusMap.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static RangeMarker combineScopes(RangeMarker old, @Nonnull TextRange scope, int textLength, @Nonnull Document document) {
  if (old == null) {
    if (scope.equalsToRange(0, textLength)) return WHOLE_FILE_DIRTY_MARKER;
    return document.createRangeMarker(scope);
  }
  if (old == WHOLE_FILE_DIRTY_MARKER) return old;
  TextRange oldRange = TextRange.create(old);
  TextRange union = scope.union(oldRange);
  if (old.isValid() && union.equals(oldRange)) {
    return old;
  }
  if (union.getEndOffset() > textLength) {
    union = union.intersection(new TextRange(0, textLength));
  }
  assert union != null;
  return document.createRangeMarker(union);
}
 
Example 19
Source Project: consulo   Source File: FoldingUpdate.java    License: Apache License 2.0 5 votes vote down vote up
private static void getFoldingsFor(@Nonnull PsiFile file, @Nonnull Document document, @Nonnull List<? super RegionInfo> elementsToFold, boolean quick) {
  final FileViewProvider viewProvider = file.getViewProvider();
  TextRange docRange = TextRange.from(0, document.getTextLength());
  Comparator<Language> preferBaseLanguage = Comparator.comparing((Language l) -> l != viewProvider.getBaseLanguage());
  List<Language> languages = ContainerUtil.sorted(viewProvider.getLanguages(), preferBaseLanguage.thenComparing(Language::getID));

  DocumentEx copyDoc = languages.size() > 1 ? new DocumentImpl(document.getImmutableCharSequence()) : null;
  List<RangeMarker> hardRefToRangeMarkers = new ArrayList<>();

  for (Language language : languages) {
    final PsiFile psi = viewProvider.getPsi(language);
    final FoldingBuilder foldingBuilder = LanguageFolding.INSTANCE.forLanguage(language);
    if (psi != null && foldingBuilder != null) {
      for (FoldingDescriptor descriptor : LanguageFolding.buildFoldingDescriptors(foldingBuilder, psi, document, quick)) {
        PsiElement psiElement = descriptor.getElement().getPsi();
        if (psiElement == null) {
          LOG.error("No PSI for folding descriptor " + descriptor);
          continue;
        }
        TextRange range = descriptor.getRange();
        if (!docRange.contains(range)) {
          diagnoseIncorrectRange(psi, document, language, foldingBuilder, descriptor, psiElement);
          continue;
        }

        if (copyDoc != null && !addNonConflictingRegion(copyDoc, range, hardRefToRangeMarkers)) {
          continue;
        }

        RegionInfo regionInfo = new RegionInfo(descriptor, psiElement, foldingBuilder);
        elementsToFold.add(regionInfo);
      }
    }
  }
}
 
Example 20
Source Project: consulo   Source File: TwoSideChange.java    License: Apache License 2.0 5 votes vote down vote up
protected SideChange(@Nonnull V twoSideChange,
                     @Nonnull ChangeList changeList,
                     @Nonnull ChangeType type,
                     @Nonnull FragmentSide mergeSide,
                     @Nonnull TextRange versionRange) {
  myTwoSideChange = twoSideChange;
  myChangeList = changeList;
  myOriginalSide =
          new SimpleChangeSide(mergeSide, new DiffRangeMarker((DocumentEx)twoSideChange.getOriginalDocument(mergeSide), versionRange, this));
  myType = type;
}
 
Example 21
Source Project: consulo   Source File: IdentifierHighlighterPass.java    License: Apache License 2.0 5 votes vote down vote up
private HighlightInfo createHighlightInfo(TextRange range, HighlightInfoType type, Set<Pair<Object, TextRange>> existingMarkupTooltips) {
  int start = range.getStartOffset();
  String tooltip = start <= myDocument.getTextLength() ? HighlightHandlerBase.getLineTextErrorStripeTooltip(myDocument, start, false) : null;
  String unescapedTooltip = existingMarkupTooltips.contains(new Pair<Object, TextRange>(tooltip, range)) ? null : tooltip;
  HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(type).range(range);
  if (unescapedTooltip != null) {
    builder.unescapedToolTip(unescapedTooltip);
  }
  return builder.createUnconditionally();
}
 
Example 22
Source Project: markdown-image-kit   Source File: IntentionActionBase.java    License: MIT License 5 votes vote down vote up
/**
 * 获取光标所在行文本
 *
 * @param editor the editor
 * @return the string
 */
private String getLineText(@NotNull Editor editor) {
    int documentLine = editor.getDocument().getLineNumber(editor.getCaretModel().getOffset());
    int linestartoffset = editor.getDocument().getLineStartOffset(documentLine);
    int lineendoffset = editor.getDocument().getLineEndOffset(documentLine);

    log.trace("documentLine = {}, linestartoffset = {}, lineendoffset = {}", documentLine, linestartoffset, lineendoffset);

    String text = editor.getDocument().getText(new TextRange(linestartoffset, lineendoffset));
    log.trace("text = {}", text);
    return text;
}
 
Example 23
Source Project: consulo   Source File: MergeableLineMarkerInfo.java    License: Apache License 2.0 5 votes vote down vote up
public MergeableLineMarkerInfo(@Nonnull T element,
                               @Nonnull TextRange textRange,
                               Image icon,
                               int updatePass,
                               @Nullable Function<? super T, String> tooltipProvider,
                               @Nullable GutterIconNavigationHandler<T> navHandler,
                               @Nonnull GutterIconRenderer.Alignment alignment) {
  super(element, textRange, icon, updatePass, tooltipProvider, navHandler, alignment);
}
 
Example 24
Source Project: intellij-xquery   Source File: TextRangeCalculator.java    License: Apache License 2.0 5 votes vote down vote up
public TextRange calculateTextRange(XQueryFunctionDecl functionDeclaration) {
    int startOffset = functionDeclaration.getTextRange().getStartOffset();
    int endOffset = functionDeclaration.getParamList() != null ?
            functionDeclaration.getParamList().getTextRange().getEndOffset()
            : functionDeclaration.getTextRange().getEndOffset();
    return new TextRange(startOffset, endOffset);
}
 
Example 25
Source Project: consulo   Source File: LivePreviewController.java    License: Apache License 2.0 5 votes vote down vote up
public void performReplace() throws FindManager.MalformedReplacementStringException {
  mySuppressUpdate = true;
  String replacement = getStringToReplace(getEditor(), mySearchResults.getCursor());
  if (replacement == null) {
    return;
  }
  final TextRange textRange = performReplace(mySearchResults.getCursor(), replacement, getEditor());
  if (textRange == null) {
    mySuppressUpdate = false;
  }
  if (myComponent != null) {
    myComponent.addTextToRecent(myComponent.getComponent().getReplaceTextComponent());
    myComponent.clearUndoInTextFields();
  }
}
 
Example 26
Source Project: intellij-haxe   Source File: HaxeFoldingBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static TextRange buildImportsFoldingTextRange(ASTNode firstNode, ASTNode lastNode) {
  ASTNode nodeStartFrom = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(firstNode.getFirstChildNode());
  if (nodeStartFrom == null) {
    nodeStartFrom = firstNode;
  }
  return new TextRange(nodeStartFrom.getStartOffset(), lastNode.getTextRange().getEndOffset());
}
 
Example 27
Source Project: emacsIDEAs   Source File: QuoteSelector.java    License: Apache License 2.0 5 votes vote down vote up
private TextRange findQuotedTextRange(String docText, char quoteChar) {
    final int caretOffset = _editor.getCaretModel().getOffset();
    final int startQuoteOffset = docText.lastIndexOf(quoteChar, caretOffset-1);
    if (startQuoteOffset == -1) {
        return null;
    }

    int start = startQuoteOffset + 1;
    int end = docText.indexOf(quoteChar, caretOffset);

    return end > start ? new TextRange(start, end) : null;
}
 
Example 28
Source Project: consulo   Source File: MarkupModelWindow.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RangeHighlighterEx addRangeHighlighterAndChangeAttributes(int startOffset,
                                                                 int endOffset,
                                                                 int layer,
                                                                 TextAttributes textAttributes,
                                                                 @Nonnull HighlighterTargetArea targetArea,
                                                                 boolean isPersistent,
                                                                 Consumer<? super RangeHighlighterEx> changeAttributesAction) {
  TextRange hostRange = myDocument.injectedToHost(new ProperTextRange(startOffset, endOffset));
  return myHostModel.addRangeHighlighterAndChangeAttributes(hostRange.getStartOffset(), hostRange.getEndOffset(), layer, textAttributes, targetArea, isPersistent, changeAttributesAction);
}
 
Example 29
Source Project: consulo   Source File: ExpandMacroToPathMap.java    License: Apache License 2.0 5 votes vote down vote up
private static String replaceMacro(String text, String macroName, String replacement) {
  while (true) {
    int start = findMacroIndex(text, macroName);
    if (start < 0) {
      break;
    }

    int end = start + macroName.length() + 2;
    int slashCount = getSlashCount(text, end);
    String actualReplacement = slashCount > 0 && !replacement.endsWith("/") ? replacement + "/" : replacement;
    text = StringUtil.replaceSubstring(text, new TextRange(start, end + slashCount), actualReplacement);
  }
  return text;
}
 
Example 30
Source Project: spring-javaformat   Source File: SpringReformatter.java    License: Apache License 2.0 5 votes vote down vote up
private void reformat(PsiFile file, Collection<TextRange> ranges, Document document) {
	if (document != null) {
		Formatter formatter = new Formatter();
		String source = document.getText();
		IRegion[] regions = EclipseRegionAdapter.asArray(ranges);
		TextEdit edit = formatter.format(source, regions, NORMALIZED_LINE_SEPARATOR);
		applyEdit(document, edit);
	}
}