com.intellij.psi.util.PsiUtilBase Java Examples

The following examples show how to use com.intellij.psi.util.PsiUtilBase. 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: DefaultHighlightInfoProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void repaintTrafficIcon(@Nonnull final PsiFile file, @Nullable Editor editor, double progress) {
  if (ApplicationManager.getApplication().isCommandLine()) return;

  if (repaintIconAlarm.isEmpty() || progress >= 1) {
    repaintIconAlarm.addRequest(() -> {
      Project myProject = file.getProject();
      if (myProject.isDisposed()) return;
      Editor myeditor = editor;
      if (myeditor == null) {
        myeditor = PsiUtilBase.findEditor(file);
      }
      if (myeditor != null && !myeditor.isDisposed()) {
        repaintErrorStripeAndIcon(myeditor, myProject);
      }
    }, 50, null);
  }
}
 
Example #2
Source File: ScopeTreeViewPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private PsiElement[] getSelectedPsiElements() {
  final TreePath[] treePaths = myTree.getSelectionPaths();
  if (treePaths != null) {
    Set<PsiElement> result = new HashSet<PsiElement>();
    for (TreePath path : treePaths) {
      PackageDependenciesNode node = (PackageDependenciesNode)path.getLastPathComponent();
      final PsiElement psiElement = node.getPsiElement();
      if (psiElement != null && psiElement.isValid()) {
        result.add(psiElement);
      }
    }
    return PsiUtilBase.toPsiElementArray(result);
  }
  return PsiElement.EMPTY_ARRAY;
}
 
Example #3
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static WatchingInsertionContext callHandleInsert(CompletionProgressIndicator indicator, LookupElement item, char completionChar) {
  final Editor editor = indicator.getEditor();

  final int caretOffset = indicator.getCaret().getOffset();
  final int idEndOffset = calcIdEndOffset(indicator);
  PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, indicator.getProject());

  WatchingInsertionContext context = createInsertionContext(indicator.getLookup(), item, completionChar, editor, psiFile, caretOffset, idEndOffset, indicator.getOffsetMap());
  try {
    item.handleInsert(context);
  }
  finally {
    context.stopWatching();
  }
  return context;
}
 
Example #4
Source File: AbstractActivityViewAction.java    From idea-android-studio-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if(file == null) {
        return;
    }

    int offset = editor.getCaretModel().getOffset();
    PsiElement psiElement = file.findElementAt(offset);
    if(psiElement == null) {
        return;
    }

    PsiMethodCallExpression psiMethodCallExpression = PsiTreeUtil.getParentOfType(psiElement, PsiMethodCallExpression.class);
    if(psiMethodCallExpression == null) {
        return;
    }

    PsiFile xmlFile = matchInflate(psiMethodCallExpression);
    generate(psiMethodCallExpression, xmlFile, editor, file);
}
 
Example #5
Source File: ScopeTreeViewPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteElement(@Nonnull DataContext dataContext) {
  List<PsiElement> allElements = Arrays.asList(getSelectedPsiElements());
  ArrayList<PsiElement> validElements = new ArrayList<PsiElement>();
  for (PsiElement psiElement : allElements) {
    if (psiElement != null && psiElement.isValid()) validElements.add(psiElement);
  }
  final PsiElement[] elements = PsiUtilBase.toPsiElementArray(validElements);

  LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting"));
  try {
    DeleteHandler.deletePsiElement(elements, myProject);
  }
  finally {
    a.finish();
  }
}
 
Example #6
Source File: AbstractInflateViewAction.java    From idea-android-studio-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if(file == null) {
        return;
    }

    int offset = editor.getCaretModel().getOffset();
    PsiElement psiElement = file.findElementAt(offset);
    if(psiElement == null) {
        return;
    }

    PsiLocalVariable psiLocalVariable = PsiTreeUtil.getParentOfType(psiElement, PsiLocalVariable.class);
    InflateViewAnnotator.InflateContainer inflateContainer = InflateViewAnnotator.matchInflate(psiLocalVariable);
    if(inflateContainer == null) {
        return;
    }

    generate(inflateContainer, editor, file);
}
 
Example #7
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 #8
Source File: DeleteTypeDescriptionLocation.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String getElementDescription(@Nonnull final PsiElement element, @Nonnull final ElementDescriptionLocation location) {
  if (location instanceof DeleteTypeDescriptionLocation) {
    final boolean plural = ((DeleteTypeDescriptionLocation)location).isPlural();
    final int count = plural ? 2 : 1;
    if (element instanceof PsiFileSystemItem && PsiUtilBase.isSymLink((PsiFileSystemItem)element)) {
      return IdeBundle.message("prompt.delete.symlink", count);
    }
    if (element instanceof PsiFile) {
      return IdeBundle.message("prompt.delete.file", count);
    }
    if (element instanceof PsiDirectory) {
      return IdeBundle.message("prompt.delete.directory", count);
    }
    if (!plural) {
      return LanguageFindUsages.INSTANCE.forLanguage(element.getLanguage()).getType(element);
    }
    return "elements";
  }
  return null;
}
 
Example #9
Source File: FilteredIndentsHighlightingPass.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int findCodeConstructStartLine(int startLine) {
  DocumentEx document = myEditor.getDocument();
  CharSequence text = document.getImmutableCharSequence();
  int lineStartOffset = document.getLineStartOffset(startLine);
  int firstNonWsOffset = CharArrayUtil.shiftForward(text, lineStartOffset, " \t");
  FileType type = PsiUtilBase.getPsiFileAtOffset(myFile, firstNonWsOffset).getFileType();
  Language language = PsiUtilCore.getLanguageAtOffset(myFile, firstNonWsOffset);
  BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(type, language);
  HighlighterIterator iterator = myEditor.getHighlighter().createIterator(firstNonWsOffset);
  if (braceMatcher.isLBraceToken(iterator, text, type)) {
    int codeConstructStart = braceMatcher.getCodeConstructStart(myFile, firstNonWsOffset);
    return document.getLineNumber(codeConstructStart);
  }
  else {
    return startLine;
  }
}
 
Example #10
Source File: FilteredIndentsHighlightingPass.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int findCodeConstructStartLine(int startLine) {
  DocumentEx document = myEditor.getDocument();
  CharSequence text = document.getImmutableCharSequence();
  int lineStartOffset = document.getLineStartOffset(startLine);
  int firstNonWsOffset = CharArrayUtil.shiftForward(text, lineStartOffset, " \t");
  FileType type = PsiUtilBase.getPsiFileAtOffset(myFile, firstNonWsOffset).getFileType();
  Language language = PsiUtilCore.getLanguageAtOffset(myFile, firstNonWsOffset);
  BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(type, language);
  HighlighterIterator iterator = myEditor.getHighlighter().createIterator(firstNonWsOffset);
  if (braceMatcher.isLBraceToken(iterator, text, type)) {
    int codeConstructStart = braceMatcher.getCodeConstructStart(myFile, firstNonWsOffset);
    return document.getLineNumber(codeConstructStart);
  }
  else {
    return startLine;
  }
}
 
Example #11
Source File: FavoritesProjectViewPane.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void select(Object object, VirtualFile file, boolean requestFocus) {
  if (!(object instanceof PsiElement)) return;
  /*PsiElement element = (PsiElement)object;
  PsiFile psiFile = element.getContainingFile();
  if (psiFile != null) {
    element = psiFile;
  }

  if (element instanceof PsiJavaFile) {
    final PsiClass[] classes = ((PsiJavaFile)element).getClasses();
    if (classes.length > 0) {
      element = classes[0];
    }
  }

  final PsiElement originalElement = element.getOriginalElement();*/
  final VirtualFile virtualFile = PsiUtilBase.getVirtualFile((PsiElement)object);
  final String list = FavoritesViewSelectInTarget.findSuitableFavoritesList(virtualFile, myProject, getSubId());
  if (list == null) return;
  if (!list.equals(getSubId())) {
    ProjectView.getInstance(myProject).changeView(ID, list);
  }
  myViewPanel.selectElement(object, virtualFile, requestFocus);
}
 
Example #12
Source File: FindUsagesInFileAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static boolean isEnabled(DataContext dataContext) {
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return false;
  }

  Editor editor = dataContext.getData(PlatformDataKeys.EDITOR);
  if (editor == null) {
    UsageTarget[] target = dataContext.getData(UsageView.USAGE_TARGETS_KEY);
    return target != null && target.length > 0;
  }
  else {
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
      return false;
    }

    Language language = PsiUtilBase.getLanguageInEditor(editor, project);
    if (language == null) {
      language = file.getLanguage();
    }
    return !(LanguageFindUsages.INSTANCE.forLanguage(language) instanceof EmptyFindUsagesProvider);
  }
}
 
Example #13
Source File: ServiceGenerateAction.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private boolean invokePhpClass(Project project, Editor editor) {

        PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
        if(file == null) {
            return false;
        }

        int offset = editor.getCaretModel().getOffset();
        if(offset <= 0) {
            return false;
        }

        PsiElement psiElement = file.findElementAt(offset);
        if(psiElement == null) {
            return false;
        }

        PhpClass phpClass = PsiTreeUtil.getParentOfType(psiElement, PhpClass.class);
        if(phpClass == null) {
            return false;
        }

        invokeServiceGenerator(project, file, phpClass, editor);

        return true;
    }
 
Example #14
Source File: EclipseCodeFormatter.java    From EclipseCodeFormatter with Apache License 2.0 6 votes vote down vote up
public void format(PsiFile psiFile, int startOffset, int endOffset) throws FileDoesNotExistsException {
	LOG.debug("#format " + startOffset + "-" + endOffset);
	boolean wholeFile = FileUtils.isWholeFile(startOffset, endOffset, psiFile.getText());
	Range range = new Range(startOffset, endOffset, wholeFile);

	final Editor editor = PsiUtilBase.findEditor(psiFile);
	if (editor != null) {
		TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
		if (templateState != null && !settings.isUseForLiveTemplates()) {
			throw new ReformatItInIntelliJ();
		}
		formatWhenEditorIsOpen(editor, range, psiFile);
	} else {
		formatWhenEditorIsClosed(range, psiFile);
	}
	               
}
 
Example #15
Source File: EclipseCodeStyleManager.java    From EclipseCodeFormatter with Apache License 2.0 6 votes vote down vote up
protected boolean shouldSkipFormatting(PsiFile psiFile, Collection<TextRange> textRanges) {
	VirtualFile virtualFile = psiFile.getVirtualFile();

	if (settings.isFormatSeletedTextInAllFileTypes()) {             
		// when file is being edited, it is important to load text from editor, i think
		final Editor editor = PsiUtilBase.findEditor(psiFile);
		if (editor != null) {
			Document document = editor.getDocument();
			String text = document.getText();
			if (!FileUtils.isWholeFile(textRanges, text)) {
				return false;
			}
		}
	}
	//not else
	if (settings.isFormatOtherFileTypesWithIntelliJ()) {
		return isDisabledFileType(virtualFile);
	}
	return true;
}
 
Example #16
Source File: BackgroundTaskPsiFileTreeNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<AbstractTreeNode> getChildrenImpl() {
  VirtualFile ourVirtualFile = getVirtualFile();
  if(ourVirtualFile == null) {
    return super.getChildrenImpl();
  }
  BackgroundTaskByVfsChangeManager vfsChangeManager = BackgroundTaskByVfsChangeManager.getInstance(getProject());
  List<BackgroundTaskByVfsChangeTask> tasks = vfsChangeManager.findTasks(ourVirtualFile);
  if(tasks.isEmpty()) {
    return super.getChildrenImpl();
  }
  List<VirtualFile> generatedFiles = new ArrayList<VirtualFile>();
  for (BackgroundTaskByVfsChangeTask task : tasks) {
    Collections.addAll(generatedFiles, task.getGeneratedFiles());
  }
  if(generatedFiles.isEmpty()) {
    return super.getChildrenImpl();
  }
  PsiFile[] psiFiles = PsiUtilBase.virtualToPsiFiles(generatedFiles, myProject);
  List<AbstractTreeNode> newChildren = new ArrayList<AbstractTreeNode>(psiFiles.length);
  for (PsiFile psiFile : psiFiles) {
    newChildren.add(new PsiFileNode(getProject(), psiFile, getSettings()));
  }
  return newChildren;
}
 
Example #17
Source File: ANTLRLiveTemplateContext.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
	public boolean isInContext(@NotNull PsiFile file, int offset) {
		// offset is where cursor or insertion point is I guess
		if ( !PsiUtilBase.getLanguageAtOffset(file, offset).isKindOf(ANTLRv4Language.INSTANCE) ) {
			return false;
		}
		if ( offset==file.getTextLength() ) { // allow at EOF
			offset--;
		}
		PsiElement element = file.findElementAt(offset);

//		String trace = DebugUtil.currentStackTrace();
//		System.out.println("isInContext: element " + element +", text="+element.getText());
//		System.out.println(trace);

		if ( element==null ) {
			return false;
		}

		return isInContext(file, element, offset);
	}
 
Example #18
Source File: IntentionListStep.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void applyAction(@Nonnull IntentionActionWithTextCaching cachedAction) {
  myFinalRunnable = () -> {
    HintManager.getInstance().hideAllHints();
    if (myProject.isDisposed()) return;
    if (myEditor != null && (myEditor.isDisposed() || (!myEditor.getComponent().isShowing() && !ApplicationManager.getApplication().isUnitTestMode()))) return;

    if (DumbService.isDumb(myProject) && !DumbService.isDumbAware(cachedAction)) {
      DumbService.getInstance(myProject).showDumbModeNotification(cachedAction.getText() + " is not available during indexing");
      return;
    }

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiFile file = myEditor != null ? PsiUtilBase.getPsiFileInEditor(myEditor, myProject) : myFile;
    if (file == null) {
      return;
    }

    ShowIntentionActionsHandler.chooseActionAndInvoke(file, myEditor, cachedAction.getAction(), cachedAction.getText(), myProject);
  };
}
 
Example #19
Source File: HighlightingSettingsPerFile.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void setHighlightingSettingForRoot(@Nonnull PsiElement root, @Nonnull FileHighlightingSetting setting) {
  final PsiFile containingFile = root.getContainingFile();
  final VirtualFile virtualFile = containingFile.getVirtualFile();
  if (virtualFile == null) return;
  FileHighlightingSetting[] defaults = myHighlightSettings.get(virtualFile);
  int rootIndex = PsiUtilBase.getRootIndex(root);
  if (defaults != null && rootIndex >= defaults.length) defaults = null;
  if (defaults == null) defaults = getDefaults(containingFile);
  defaults[rootIndex] = setting;
  boolean toRemove = true;
  for (FileHighlightingSetting aDefault : defaults) {
    if (aDefault != FileHighlightingSetting.NONE) toRemove = false;
  }
  if (toRemove) {
    myHighlightSettings.remove(virtualFile);
  }
  else {
    myHighlightSettings.put(virtualFile, defaults);
  }

  myBus.syncPublisher(FileHighlightingSettingListener.SETTING_CHANGE).settingChanged(root, setting);
}
 
Example #20
Source File: MultiCaretCodeInsightAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void iterateOverCarets(@Nonnull final Project project,
                                      @Nonnull final Editor hostEditor,
                                      @Nonnull final MultiCaretCodeInsightActionHandler handler) {
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  final PsiFile psiFile = documentManager.getCachedPsiFile(hostEditor.getDocument());
  documentManager.commitAllDocuments();

  hostEditor.getCaretModel().runForEachCaret(new CaretAction() {
    @Override
    public void perform(Caret caret) {
      Editor editor = hostEditor;
      if (psiFile != null) {
        Caret injectedCaret = InjectedLanguageUtil.getCaretForInjectedLanguageNoCommit(caret, psiFile);
        if (injectedCaret != null) {
          caret = injectedCaret;
          editor = caret.getEditor();
        }
      }
      final PsiFile file = PsiUtilBase.getPsiFileInEditor(caret, project);
      if (file != null) {
        handler.invoke(project, editor, caret, file);
      }
    }
  });
}
 
Example #21
Source File: InjectAction.java    From android-butterknife-zelezny with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformedImpl(Project project, Editor editor) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    PsiFile layout = Utils.getLayoutFileFromCaret(editor, file);

    if (layout == null) {
        Utils.showErrorNotification(project, "No layout found");
        return; // no layout found
    }

    log.info("Layout file: " + layout.getVirtualFile());

    ArrayList<Element> elements = Utils.getIDsFromLayout(layout);
    if (!elements.isEmpty()) {
        showDialog(project, editor, elements);
    } else {
        Utils.showErrorNotification(project, "No IDs found in layout");
    }
}
 
Example #22
Source File: InjectAction.java    From android-butterknife-zelezny with Apache License 2.0 6 votes vote down vote up
public void onConfirm(Project project, Editor editor, ArrayList<Element> elements, String fieldNamePrefix, boolean createHolder, boolean splitOnclickMethods) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (file == null) {
        return;
    }
    PsiFile layout = Utils.getLayoutFileFromCaret(editor, file);

    closeDialog();


    if (Utils.getInjectCount(elements) > 0 || Utils.getClickCount(elements) > 0) { // generate injections
        new InjectWriter(file, getTargetClass(editor, file), "Generate Injections", elements, layout.getName(), fieldNamePrefix, createHolder, splitOnclickMethods).execute();
    } else { // just notify user about no element selected
        Utils.showInfoNotification(project, "No injection was selected");
    }

}
 
Example #23
Source File: BaseMoveHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static PsiFile getRoot(final PsiFile file, final Editor editor) {
  if (file == null) return null;
  int offset = editor.getCaretModel().getOffset();
  if (offset == editor.getDocument().getTextLength()) offset--;
  if (offset<0) return null;
  PsiElement leafElement = file.findElementAt(offset);
  if (leafElement == null) return null;
  if (leafElement.getLanguage() instanceof DependentLanguage) {
    leafElement = file.getViewProvider().findElementAt(offset, file.getViewProvider().getBaseLanguage());
    if (leafElement == null) return null;
  }
  ASTNode node = leafElement.getNode();
  if (node == null) return null;
  return (PsiFile)PsiUtilBase.getRoot(node).getPsi();
}
 
Example #24
Source File: CodeInsightAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void update(@Nonnull AnActionEvent e) {
  Presentation presentation = e.getPresentation();

  Project project = e.getProject();
  if (project == null) {
    presentation.setEnabled(false);
    return;
  }

  final DataContext dataContext = e.getDataContext();
  Editor editor = getEditor(dataContext, project, true);
  if (editor == null) {
    presentation.setEnabled(false);
    return;
  }

  final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (file == null) {
    presentation.setEnabled(false);
    return;
  }

  update(presentation, project, editor, file, dataContext, e.getPlace());
}
 
Example #25
Source File: CodeInsightAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
public void actionPerformedImpl(@Nonnull final Project project, final Editor editor) {
  if (editor == null) return;
  //final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (psiFile == null) return;
  final CodeInsightActionHandler handler = getHandler();
  PsiElement elementToMakeWritable = handler.getElementToMakeWritable(psiFile);
  if (elementToMakeWritable != null && !(EditorModificationUtil.checkModificationAllowed(editor) && FileModificationService.getInstance().preparePsiElementsForWrite(elementToMakeWritable))) {
    return;
  }

  CommandProcessor.getInstance().executeCommand(project, () -> {
    final Runnable action = () -> {
      if (!ApplicationManager.getApplication().isHeadlessEnvironment() && !editor.getContentComponent().isShowing()) return;
      handler.invoke(project, editor, psiFile);
    };
    if (handler.startInWriteAction()) {
      ApplicationManager.getApplication().runWriteAction(action);
    }
    else {
      action.run();
    }
  }, getCommandName(), DocCommandGroupId.noneGroupId(editor.getDocument()), editor.getDocument());
}
 
Example #26
Source File: HighlightUsagesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static TextRange getNameIdentifierRange(PsiFile file, PsiElement element) {
  final InjectedLanguageManager injectedManager = InjectedLanguageManager.getInstance(element.getProject());
  if (element instanceof PomTargetPsiElement) {
    final PomTarget target = ((PomTargetPsiElement)element).getTarget();
    if (target instanceof PsiDeclaredTarget) {
      final PsiDeclaredTarget declaredTarget = (PsiDeclaredTarget)target;
      final TextRange range = declaredTarget.getNameIdentifierRange();
      if (range != null) {
        if (range.getStartOffset() < 0 || range.getLength() <= 0) {
          return null;
        }
        final PsiElement navElement = declaredTarget.getNavigationElement();
        if (PsiUtilBase.isUnderPsiRoot(file, navElement)) {
          return injectedManager.injectedToHost(navElement, range.shiftRight(navElement.getTextRange().getStartOffset()));
        }
      }
    }
  }

  if (!PsiUtilBase.isUnderPsiRoot(file, element)) {
    return null;
  }

  PsiElement identifier = IdentifierUtil.getNameIdentifier(element);
  if (identifier != null && PsiUtilBase.isUnderPsiRoot(file, identifier)) {
    return injectedManager.injectedToHost(identifier, identifier.getTextRange());
  }
  return null;
}
 
Example #27
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static WatchingInsertionContext insertItemHonorBlockSelection(CompletionProcessEx indicator, LookupElement item, char completionChar, StatisticsUpdate update) {
  final Editor editor = indicator.getEditor();

  final int caretOffset = indicator.getCaret().getOffset();
  final int idEndOffset = calcIdEndOffset(indicator);
  final int idEndOffsetDelta = idEndOffset - caretOffset;

  WatchingInsertionContext context;
  if (editor.getCaretModel().supportsMultipleCarets()) {
    Ref<WatchingInsertionContext> lastContext = Ref.create();
    Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(editor);
    boolean wasInjected = hostEditor != editor;
    OffsetsInFile topLevelOffsets = indicator.getHostOffsets();
    hostEditor.getCaretModel().runForEachCaret(caret -> {
      OffsetsInFile targetOffsets = findInjectedOffsetsIfAny(caret, wasInjected, topLevelOffsets, hostEditor);
      PsiFile targetFile = targetOffsets.getFile();
      Editor targetEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, targetFile);
      int targetCaretOffset = targetEditor.getCaretModel().getOffset();
      int idEnd = targetCaretOffset + idEndOffsetDelta;
      if (idEnd > targetEditor.getDocument().getTextLength()) {
        idEnd = targetCaretOffset; // no replacement by Tab when offsets gone wrong for some reason
      }
      WatchingInsertionContext currentContext = insertItem(indicator.getLookup(), item, completionChar, update, targetEditor, targetFile, targetCaretOffset, idEnd, targetOffsets.getOffsets());
      lastContext.set(currentContext);
    });
    context = lastContext.get();
  }
  else {
    PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, indicator.getProject());
    context = insertItem(indicator.getLookup(), item, completionChar, update, editor, psiFile, caretOffset, idEndOffset, indicator.getOffsetMap());
  }
  if (context.shouldAddCompletionChar()) {
    WriteAction.run(() -> addCompletionChar(context, item));
  }
  checkPsiTextConsistency(indicator);

  return context;
}
 
Example #28
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void addCompletionChar(InsertionContext context, LookupElement item) {
  if (!context.getOffsetMap().containsOffset(InsertionContext.TAIL_OFFSET)) {
    String message = "tailOffset<0 after inserting " + item + " of " + item.getClass();
    if (context instanceof WatchingInsertionContext) {
      message += "; invalidated at: " + ((WatchingInsertionContext)context).invalidateTrace + "\n--------";
    }
    LOG.info(message);
  }
  else if (!CompletionAssertions.isEditorValid(context.getEditor())) {
    LOG.info("Injected editor invalidated " + context.getEditor());
  }
  else {
    context.getEditor().getCaretModel().moveToOffset(context.getTailOffset());
  }
  if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
    Language language = PsiUtilBase.getLanguageInEditor(context.getEditor(), context.getFile().getProject());
    if (language != null) {
      for (SmartEnterProcessor processor : SmartEnterProcessors.INSTANCE.allForLanguage(language)) {
        if (processor.processAfterCompletion(context.getEditor(), context.getFile())) break;
      }
    }
  }
  else {
    DataContext dataContext = DataManager.getInstance().getDataContext(context.getEditor().getContentComponent());
    EditorActionManager.getInstance().getTypedAction().getHandler().execute(context.getEditor(), context.getCompletionChar(), dataContext);
  }
}
 
Example #29
Source File: CodeMakerUtil.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
/**
 * save the current change
 */
public static void pushPostponedChanges(PsiElement element) {
    Editor editor = PsiUtilBase.findEditor(element.getContainingFile());
    if (editor != null) {
        PsiDocumentManager.getInstance(element.getProject())
            .doPostponedOperationsAndUnblockDocument(editor.getDocument());
    }
}
 
Example #30
Source File: HighlightingSettingsPerFile.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public FileHighlightingSetting getHighlightingSettingForRoot(@Nonnull PsiElement root){
  final PsiFile containingFile = root.getContainingFile();
  final VirtualFile virtualFile = containingFile.getVirtualFile();
  FileHighlightingSetting[] fileHighlightingSettings = myHighlightSettings.get(virtualFile);
  final int index = PsiUtilBase.getRootIndex(root);

  if(fileHighlightingSettings == null || fileHighlightingSettings.length <= index) {
    return getDefaultHighlightingSetting(root.getProject(), virtualFile);
  }
  return fileHighlightingSettings[index];
}