com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil Java Examples

The following examples show how to use com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil. 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: CompletionInitializationUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
static OffsetsInFile toInjectedIfAny(PsiFile originalFile, OffsetsInFile hostCopyOffsets) {
  CompletionAssertions.assertHostInfo(hostCopyOffsets.getFile(), hostCopyOffsets.getOffsets());

  int hostStartOffset = hostCopyOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET);
  OffsetsInFile translatedOffsets = hostCopyOffsets.toInjectedIfAny(hostStartOffset);
  if (translatedOffsets != hostCopyOffsets) {
    PsiFile injected = translatedOffsets.getFile();
    if (originalFile != injected && injected instanceof PsiFileImpl && InjectedLanguageManager.getInstance(originalFile.getProject()).isInjectedFragment(originalFile)) {
      ((PsiFileImpl)injected).setOriginalFile(originalFile);
    }
    DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injected);
    CompletionAssertions.assertInjectedOffsets(hostStartOffset, injected, documentWindow);

    if (injected.getTextRange().contains(translatedOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET))) {
      return translatedOffsets;
    }
  }

  return hostCopyOffsets;
}
 
Example #2
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Pair<PsiFile, Editor> chooseBetweenHostAndInjected(@Nonnull PsiFile hostFile,
                                                                 @Nonnull Editor hostEditor,
                                                                 @Nullable PsiFile injectedFile,
                                                                 @Nonnull PairProcessor<? super PsiFile, ? super Editor> predicate) {
  Editor editorToApply = null;
  PsiFile fileToApply = null;

  Editor injectedEditor = null;
  if (injectedFile != null) {
    injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, injectedFile);
    if (predicate.process(injectedFile, injectedEditor)) {
      editorToApply = injectedEditor;
      fileToApply = injectedFile;
    }
  }

  if (editorToApply == null && hostEditor != injectedEditor && predicate.process(hostFile, hostEditor)) {
    editorToApply = hostEditor;
    fileToApply = hostFile;
  }
  if (editorToApply == null) return null;
  return Pair.create(fileToApply, editorToApply);
}
 
Example #3
Source File: PsiViewerDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void caretPositionChanged(CaretEvent e) {
  if (!available() || myEditor.getSelectionModel().hasSelection()) return;
  final ViewerTreeStructure treeStructure = (ViewerTreeStructure)myPsiTreeBuilder.getTreeStructure();
  final PsiElement rootPsiElement = treeStructure.getRootPsiElement();
  if (rootPsiElement == null) return;
  final PsiElement rootElement = ((ViewerTreeStructure)myPsiTreeBuilder.getTreeStructure()).getRootPsiElement();
  int baseOffset = rootPsiElement.getTextRange().getStartOffset();
  final int offset = myEditor.getCaretModel().getOffset() + baseOffset;
  final PsiElement element = InjectedLanguageUtil.findElementAtNoCommit(rootElement.getContainingFile(), offset);
  if (element != null && myBlockTreeBuilder != null) {
    TextRange rangeInHostFile = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, element.getTextRange());
    selectBlockNode(findBlockNode(rangeInHostFile, true));
  }
  myPsiTreeBuilder.select(element);
}
 
Example #4
Source File: LightPlatformCodeInsightTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Object getData(@Nonnull Key<?> dataId) {
  if (PlatformDataKeys.EDITOR == dataId) {
    return myEditor;
  }
  if (dataId == AnActionEvent.injectedId(PlatformDataKeys.EDITOR)) {
    return InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(getEditor(), getFile());
  }
  if (LangDataKeys.PSI_FILE == dataId) {
    return myFile;
  }
  if (dataId == AnActionEvent.injectedId(LangDataKeys.PSI_FILE)) {
    Editor editor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(getEditor(), getFile());
    return editor instanceof EditorWindow ? ((EditorWindow)editor).getInjectedFile() : getFile();
  }
  return super.getData(dataId);
}
 
Example #5
Source File: PsiViewerDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void selectionChanged(SelectionEvent e) {
  if (!available() || !myEditor.getSelectionModel().hasSelection()) return;
  ViewerTreeStructure treeStructure = (ViewerTreeStructure)myPsiTreeBuilder.getTreeStructure();
  if (treeStructure == null) return;
  final PsiElement rootElement = treeStructure.getRootPsiElement();
  if (rootElement == null) return;
  final SelectionModel selection = myEditor.getSelectionModel();
  final TextRange textRange = rootElement.getTextRange();
  int baseOffset = textRange != null ? textRange.getStartOffset() : 0;
  final int start = selection.getSelectionStart()+baseOffset;
  final int end = selection.getSelectionEnd()+baseOffset - 1;
  final PsiElement element =
    findCommonParent(InjectedLanguageUtil.findElementAtNoCommit(rootElement.getContainingFile(), start),
                     InjectedLanguageUtil.findElementAtNoCommit(rootElement.getContainingFile(), end));
  if (element != null  && myBlockTreeBuilder != null) {
    if (myEditor.getContentComponent().hasFocus()) {
      TextRange rangeInHostFile = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, element.getTextRange());
      selectBlockNode(findBlockNode(rangeInHostFile, true));
      updateIntersectHighlighter(myHighlighter.getStartOffset(), myHighlighter.getEndOffset());
    }
  }
  myPsiTreeBuilder.select(element);
}
 
Example #6
Source File: FormattingDocumentModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean containsWhiteSpaceSymbolsOnly(int startOffset, int endOffset) {
  WhiteSpaceFormattingStrategy strategy = myWhiteSpaceStrategy;
  if (strategy.check(myDocument.getCharsSequence(), startOffset, endOffset) >= endOffset) {
    return true;
  }
  PsiElement injectedElement = myFile != null ? InjectedLanguageUtil.findElementAtNoCommit(myFile, startOffset) : null;
  if (injectedElement != null) {
    Language injectedLanguage = injectedElement.getLanguage();
    if (!injectedLanguage.equals(myFile.getLanguage())) {
      WhiteSpaceFormattingStrategy localStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy(injectedLanguage);
      if (localStrategy != null) {
        return localStrategy.check(myDocument.getCharsSequence(), startOffset, endOffset) >= endOffset;
      }
    }
  }
  return false;
}
 
Example #7
Source File: CompletionLookupArrangerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private List<LookupElement> getExactMatches(List<? extends LookupElement> items) {
  String selectedText = InjectedLanguageUtil.getTopLevelEditor(myProcess.getParameters().getEditor()).getSelectionModel().getSelectedText();
  List<LookupElement> exactMatches = new SmartList<>();
  for (int i = 0; i < items.size(); i++) {
    LookupElement item = items.get(i);
    boolean isSuddenLiveTemplate = isSuddenLiveTemplate(item);
    if (isPrefixItem(item, true) && !isSuddenLiveTemplate || item.getLookupString().equals(selectedText)) {
      if (item instanceof LiveTemplateLookupElement) {
        // prefer most recent live template lookup item
        return Collections.singletonList(item);
      }
      exactMatches.add(item);
    }
    else if (i == 0 && isSuddenLiveTemplate && items.size() > 1 && !CompletionServiceImpl.isStartMatch(items.get(1), this)) {
      return Collections.singletonList(item);
    }
  }
  return exactMatches;
}
 
Example #8
Source File: LookupDocumentSavingVetoer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean maySaveDocument(@Nonnull Document document, boolean isSaveExplicit) {
  if (ApplicationManager.getApplication().isDisposed() || isSaveExplicit) {
    return true;
  }

  for (Project project : ProjectManager.getInstance().getOpenProjects()) {
    if (!project.isInitialized() || project.isDisposed()) {
      continue;
    }
    LookupEx lookup = LookupManager.getInstance(project).getActiveLookup();
    if (lookup != null) {
      Editor editor = InjectedLanguageUtil.getTopLevelEditor(lookup.getEditor());
      if (editor.getDocument() == document) {
        return false;
      }
    }
  }
  return true;
}
 
Example #9
Source File: PsiElementRenameHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(@Nonnull Project project, Editor editor, PsiFile file, DataContext dataContext) {
  PsiElement element = getElement(dataContext);
  if (element == null) {
    element = BaseRefactoringAction.getElementAtCaret(editor, file);
  }

  if (ApplicationManager.getApplication().isUnitTestMode()) {
    final String newName = dataContext.getData(DEFAULT_NAME);
    if (newName != null) {
      rename(element, project, element, editor, newName);
      return;
    }
  }

  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  final PsiElement nameSuggestionContext = InjectedLanguageUtil.findElementAtNoCommit(file, editor.getCaretModel().getOffset());
  invoke(element, project, nameSuggestionContext, editor);
}
 
Example #10
Source File: InplaceRefactoring.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void templateFinished(Template template, final boolean brokenOff) {
  boolean bind = false;
  try {
    super.templateFinished(template, brokenOff);
    if (!brokenOff) {
      bind = performRefactoring();
    }
    moveOffsetAfter(!brokenOff);
  }
  finally {
    if (!bind) {
      try {
        ((DesktopEditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater();
      }
      finally {
        FinishMarkAction.finish(myProject, myEditor, myMarkAction);
        if (myBeforeRevert != null) {
          myBeforeRevert.dispose();
        }
      }
    }
  }
}
 
Example #11
Source File: ShaderLabCGCompletionContributor.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
public ShaderLabCGCompletionContributor()
{
	extend(CompletionType.BASIC, StandardPatterns.psiElement().withLanguage(CGLanguage.INSTANCE), new CompletionProvider()
	{
		@RequiredReadAction
		@Override
		public void addCompletions(@Nonnull CompletionParameters parameters, ProcessingContext context, @Nonnull final CompletionResultSet result)
		{
			Place shreds = InjectedLanguageUtil.getShreds(parameters.getOriginalFile());

			for(PsiLanguageInjectionHost.Shred shred : shreds)
			{
				PsiLanguageInjectionHost host = shred.getHost();
				if(host instanceof ShaderCGScript)
				{
					ShaderLabFile containingFile = (ShaderLabFile) host.getContainingFile();
					ShaderReference.consumeProperties(containingFile, result::addElement);
				}
			}
		}
	});
}
 
Example #12
Source File: LocalInspectionsPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
void inspectInjectedPsi(@Nonnull final List<PsiElement> elements,
                        final boolean onTheFly,
                        @Nonnull final ProgressIndicator indicator,
                        @Nonnull final InspectionManager iManager,
                        final boolean inVisibleRange,
                        @Nonnull final List<LocalInspectionToolWrapper> wrappers) {
  final Set<PsiFile> injected = new THashSet<>();
  for (PsiElement element : elements) {
    InjectedLanguageUtil.enumerate(element, getFile(), false, (injectedPsi, places) -> injected.add(injectedPsi));
  }
  if (injected.isEmpty()) return;
  Processor<PsiFile> processor = injectedPsi -> {
    doInspectInjectedPsi(injectedPsi, onTheFly, indicator, iManager, inVisibleRange, wrappers);
    return true;
  };
  if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(new ArrayList<>(injected), indicator, myFailFastOnAcquireReadAction, processor)) {
    throw new ProcessCanceledException();
  }
}
 
Example #13
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void scheduleContributorsAfterAsyncCommit(CompletionInitializationContextImpl initContext, CompletionProgressIndicator indicator, OffsetsInFile hostCopyOffsets, boolean hasModifiers) {
  CompletionPhase phase;
  if (synchronous) {
    phase = new CompletionPhase.BgCalculation(indicator);
    indicator.makeSureLookupIsShown(0);
  }
  else {
    phase = new CompletionPhase.CommittingDocuments(indicator, InjectedLanguageUtil.getTopLevelEditor(indicator.getEditor()));
  }
  CompletionServiceImpl.setCompletionPhase(phase);

  AppUIExecutor.onUiThread().withDocumentsCommitted(initContext.getProject()).expireWith(phase).execute(() -> {
    if (phase instanceof CompletionPhase.CommittingDocuments) {
      ((CompletionPhase.CommittingDocuments)phase).replaced = true;
    }
    CompletionServiceImpl.setCompletionPhase(new CompletionPhase.BgCalculation(indicator));
    startContributorThread(initContext, indicator, hostCopyOffsets, hasModifiers);
  });
}
 
Example #14
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 #15
Source File: TypedHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Editor injectedEditorIfCharTypedIsSignificant(final int charTyped, @Nonnull Editor editor, @Nonnull PsiFile oldFile) {
  int offset = editor.getCaretModel().getOffset();
  // even for uncommitted document try to retrieve injected fragment that has been there recently
  // we are assuming here that when user is (even furiously) typing, injected language would not change
  // and thus we can use its lexer to insert closing braces etc
  List<DocumentWindow> injected = InjectedLanguageManager.getInstance(oldFile.getProject()).getCachedInjectedDocumentsInRange(oldFile, ProperTextRange.create(offset, offset));
  for (DocumentWindow documentWindow : injected) {
    if (documentWindow.isValid() && documentWindow.containsRange(offset, offset)) {
      PsiFile injectedFile = PsiDocumentManager.getInstance(oldFile.getProject()).getPsiFile(documentWindow);
      if (injectedFile != null) {
        Editor injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injectedFile);
        // IDEA-52375/WEB-9105 fix: last quote in editable fragment should be handled by outer language quote handler
        TextRange hostRange = documentWindow.getHostRange(offset);
        CharSequence sequence = editor.getDocument().getCharsSequence();
        if (sequence.length() > offset && charTyped != Character.codePointAt(sequence, offset) || hostRange != null && hostRange.contains(offset)) {
          return injectedEditor;
        }
      }
    }
  }

  return editor;
}
 
Example #16
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static Runnable rememberDocumentState(final Editor _editor) {
  final Editor editor = InjectedLanguageUtil.getTopLevelEditor(_editor);
  final String documentText = editor.getDocument().getText();
  final int caret = editor.getCaretModel().getOffset();
  final int selStart = editor.getSelectionModel().getSelectionStart();
  final int selEnd = editor.getSelectionModel().getSelectionEnd();

  final int vOffset = editor.getScrollingModel().getVerticalScrollOffset();
  final int hOffset = editor.getScrollingModel().getHorizontalScrollOffset();

  return () -> {
    DocumentEx document = (DocumentEx)editor.getDocument();

    document.replaceString(0, document.getTextLength(), documentText);
    editor.getCaretModel().moveToOffset(caret);
    editor.getSelectionModel().setSelection(selStart, selEnd);

    editor.getScrollingModel().scrollHorizontally(hOffset);
    editor.getScrollingModel().scrollVertically(vOffset);
  };
}
 
Example #17
Source File: MemberInplaceRenamer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void revertStateOnFinish() {
  final Editor editor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
  if (editor == FileEditorManager.getInstance(myProject).getSelectedTextEditor()) {
    ((DesktopEditorImpl)editor).startDumb();
  }
  revertState();
}
 
Example #18
Source File: PsiDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
List<BooleanRunnable> reparseChangedInjectedFragments(@Nonnull Document hostDocument,
                                                      @Nonnull PsiFile hostPsiFile,
                                                      @Nonnull TextRange hostChangedRange,
                                                      @Nonnull ProgressIndicator indicator,
                                                      @Nonnull ASTNode oldRoot,
                                                      @Nonnull ASTNode newRoot) {
  List<DocumentWindow> changedInjected = InjectedLanguageManager.getInstance(myProject).getCachedInjectedDocumentsInRange(hostPsiFile, hostChangedRange);
  if (changedInjected.isEmpty()) return Collections.emptyList();
  FileViewProvider hostViewProvider = hostPsiFile.getViewProvider();
  List<DocumentWindow> fromLast = new ArrayList<>(changedInjected);
  // make sure modifications do not ruin all document offsets after
  fromLast.sort(Collections.reverseOrder(Comparator.comparingInt(doc -> ArrayUtil.getLastElement(doc.getHostRanges()).getEndOffset())));
  List<BooleanRunnable> result = new ArrayList<>(changedInjected.size());
  for (DocumentWindow document : fromLast) {
    Segment[] ranges = document.getHostRanges();
    if (ranges.length != 0) {
      // host document change has left something valid in this document window place. Try to reparse.
      PsiFile injectedPsiFile = getCachedPsiFile(document);
      if (injectedPsiFile == null || !injectedPsiFile.isValid()) continue;

      BooleanRunnable runnable = InjectedLanguageUtil.reparse(injectedPsiFile, document, hostPsiFile, hostDocument, hostViewProvider, indicator, oldRoot, newRoot, this);
      ContainerUtil.addIfNotNull(result, runnable);
    }
  }

  return result;
}
 
Example #19
Source File: MemberInplaceRenamer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRefactoringRename(final String newName,
                                        final StartMarkAction markAction) {
  try {
    final PsiNamedElement variable = getVariable();
    if (variable != null && !newName.equals(myOldName)) {
      if (isIdentifier(newName, variable.getLanguage())) {
        final PsiElement substituted = getSubstituted();
        if (substituted == null) {
          return;
        }

        final String commandName = RefactoringBundle
          .message("renaming.0.1.to.2", UsageViewUtil.getType(variable), DescriptiveNameUtil.getDescriptiveName(variable), newName);
        CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
          @Override
          public void run() {
            performRenameInner(substituted, newName);
            PsiDocumentManager.getInstance(myProject).commitAllDocuments();
          }
        }, commandName, null);
      }
    }
  }
  finally {
    try {
      ((DesktopEditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater();
    }
    finally {
      FinishMarkAction.finish(myProject, myEditor, markAction);
    }
  }
}
 
Example #20
Source File: VariableInplaceRenamer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void finish(boolean success) {
  super.finish(success);
  if (success) {
    revertStateOnFinish();
  }
  else {
    ((DesktopEditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater();
  }
}
 
Example #21
Source File: CodeStyleManagerRunnable.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isInsidePlainComment(int offset, @Nullable PsiElement element) {
  if (!(element instanceof PsiComment) || element instanceof PsiDocCommentBase || !element.getTextRange().contains(offset - 1)) {
    return false;
  }

  if (element instanceof PsiLanguageInjectionHost && InjectedLanguageUtil.hasInjections((PsiLanguageInjectionHost)element)) {
    return false;
  }

  return true;
}
 
Example #22
Source File: MemberInplaceRenameHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public InplaceRefactoring doRename(@Nonnull final PsiElement elementToRename, final Editor editor, final DataContext dataContext) {
  if (elementToRename instanceof PsiNameIdentifierOwner) {
    final RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(elementToRename);
    if (processor.isInplaceRenameSupported()) {
      final StartMarkAction startMarkAction = StartMarkAction.canStart(elementToRename.getProject());
      if (startMarkAction == null || processor.substituteElementToRename(elementToRename, editor) == elementToRename) {
        processor.substituteElementToRename(elementToRename, editor, new Pass<PsiElement>() {
          @Override
          public void pass(PsiElement element) {
            final MemberInplaceRenamer renamer = createMemberRenamer(element, (PsiNameIdentifierOwner)elementToRename, editor);
            boolean startedRename = renamer.performInplaceRename();
            if (!startedRename) {
              performDialogRename(elementToRename, editor, dataContext);
            }
          }
        });
        return null;
      }
      else {
        final InplaceRefactoring inplaceRefactoring = editor.getUserData(InplaceRefactoring.INPLACE_RENAMER);
        if (inplaceRefactoring != null && inplaceRefactoring.getClass() == MemberInplaceRenamer.class) {
          final TemplateState templateState = TemplateManagerImpl.getTemplateState(InjectedLanguageUtil.getTopLevelEditor(editor));
          if (templateState != null) {
            templateState.gotoEnd(true);
          }
        }
      }
    }
  }
  performDialogRename(elementToRename, editor, dataContext);
  return null;
}
 
Example #23
Source File: LanguageConsoleImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String printWithHighlighting(@Nonnull LanguageConsoleView console, @Nonnull Editor inputEditor, @Nonnull TextRange textRange) {
  String text;
  EditorHighlighter highlighter;
  if (inputEditor instanceof EditorWindow) {
    PsiFile file = ((EditorWindow)inputEditor).getInjectedFile();
    highlighter = HighlighterFactory.createHighlighter(file.getVirtualFile(), EditorColorsManager.getInstance().getGlobalScheme(), console.getProject());
    String fullText = InjectedLanguageUtil.getUnescapedText(file, null, null);
    highlighter.setText(fullText);
    text = textRange.substring(fullText);
  }
  else {
    text = inputEditor.getDocument().getText(textRange);
    highlighter = ((EditorEx)inputEditor).getHighlighter();
  }
  SyntaxHighlighter syntax = highlighter instanceof LexerEditorHighlighter ? ((LexerEditorHighlighter)highlighter).getSyntaxHighlighter() : null;
  LanguageConsoleImpl consoleImpl = (LanguageConsoleImpl)console;
  consoleImpl.doAddPromptToHistory();
  if (syntax != null) {
    ConsoleViewUtil.printWithHighlighting(console, text, syntax, () -> {
      String identPrompt = consoleImpl.myConsoleExecutionEditor.getConsolePromptDecorator().getIndentPrompt();
      if (StringUtil.isNotEmpty(identPrompt)) {
        consoleImpl.addPromptToHistoryImpl(identPrompt);
      }
    });
  }
  else {
    console.print(text, ConsoleViewContentType.USER_INPUT);
  }
  console.print("\n", ConsoleViewContentType.NORMAL_OUTPUT);
  return text;
}
 
Example #24
Source File: MyLookupExpression.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static LookupElement[] initLookupItems(LinkedHashSet<String> names,
                                               PsiNamedElement elementToRename, 
                                               PsiElement nameSuggestionContext,
                                               final boolean shouldSelectAll) {
  if (names == null) {
    names = new LinkedHashSet<String>();
    for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
      final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(elementToRename, nameSuggestionContext, names);
      if (suggestedNameInfo != null &&
          provider instanceof PreferrableNameSuggestionProvider &&
          !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) {
        break;
      }
    }
  }
  final LookupElement[] lookupElements = new LookupElement[names.size()];
  final Iterator<String> iterator = names.iterator();
  for (int i = 0; i < lookupElements.length; i++) {
    final String suggestion = iterator.next();
    lookupElements[i] = LookupElementBuilder.create(suggestion).withInsertHandler(new InsertHandler<LookupElement>() {
      @Override
      public void handleInsert(InsertionContext context, LookupElement item) {
        if (shouldSelectAll) return;
        final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(context.getEditor());
        final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor);
        if (templateState != null) {
          final TextRange range = templateState.getCurrentVariableRange();
          if (range != null) {
            topLevelEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), suggestion);
          }
        }
      }
    });
  }
  return lookupElements;
}
 
Example #25
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static Pair<PsiFile, Editor> chooseFileForAction(@Nonnull PsiFile hostFile, @Nullable Editor hostEditor, @Nonnull IntentionAction action) {
  if (hostEditor == null) {
    return Pair.create(hostFile, null);
  }

  PsiFile injectedFile = InjectedLanguageUtil.findInjectedPsiNoCommit(hostFile, hostEditor.getCaretModel().getOffset());
  return chooseBetweenHostAndInjected(hostFile, hostEditor, injectedFile, (psiFile, editor) -> availableFor(psiFile, editor, action));
}
 
Example #26
Source File: AutoPopupControllerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void autoPopupParameterInfo(@Nonnull final Editor editor, @Nullable final Object highlightedMethod) {
  if (DumbService.isDumb(myProject)) return;
  if (PowerSaveMode.isEnabled()) return;

  ApplicationManager.getApplication().assertIsDispatchThread();
  final CodeInsightSettings settings = CodeInsightSettings.getInstance();
  if (settings.AUTO_POPUP_PARAMETER_INFO) {
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    PsiFile file = documentManager.getPsiFile(editor.getDocument());
    if (file == null) return;

    if (!documentManager.isUncommited(editor.getDocument())) {
      file = documentManager.getPsiFile(InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, file).getDocument());
      if (file == null) return;
    }

    Runnable request = () -> {
      if (!myProject.isDisposed() && !DumbService.isDumb(myProject) && !editor.isDisposed() && (EditorActivityManager.getInstance().isVisible(editor))) {
        int lbraceOffset = editor.getCaretModel().getOffset() - 1;
        try {
          PsiFile file1 = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument());
          if (file1 != null) {
            ShowParameterInfoHandler.invoke(myProject, editor, file1, lbraceOffset, highlightedMethod, false, true, null, e -> {
            });
          }
        }
        catch (IndexNotReadyException ignored) { //anything can happen on alarm
        }
      }
    };

    addRequest(() -> documentManager.performLaterWhenAllCommitted(request), settings.PARAMETER_INFO_DELAY);
  }
}
 
Example #27
Source File: ImageOrColorPreviewManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Collection<PsiElement> getPsiElementsAt(Point point, Editor editor) {
  if (editor.isDisposed()) {
    return Collections.emptySet();
  }

  Project project = editor.getProject();
  if (project == null || project.isDisposed()) {
    return Collections.emptySet();
  }

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  final Document document = editor.getDocument();
  PsiFile psiFile = documentManager.getPsiFile(document);
  if (psiFile == null || psiFile instanceof PsiCompiledElement || !psiFile.isValid()) {
    return Collections.emptySet();
  }

  final Set<PsiElement> elements = Collections.newSetFromMap(ContainerUtil.createWeakMap());
  final int offset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(point));
  if (documentManager.isCommitted(document)) {
    ContainerUtil.addIfNotNull(elements, InjectedLanguageUtil.findElementAtNoCommit(psiFile, offset));
  }
  for (PsiFile file : psiFile.getViewProvider().getAllFiles()) {
    ContainerUtil.addIfNotNull(elements, file.findElementAt(offset));
  }

  return elements;
}
 
Example #28
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Editor getEditor() {
  DocumentWindow documentWindow = getInjectedDocument(myProject, myEditor, myEditor.getCaretModel().getOffset());
  if (documentWindow != null) {
    PsiFile injectedFile = PsiDocumentManager.getInstance(myProject).getPsiFile(documentWindow);
    return InjectedLanguageUtil.getInjectedEditorForInjectedFile(myEditor, injectedFile);
  }
  return myEditor;
}
 
Example #29
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public LookupImpl(Project project, Editor editor, @Nonnull LookupArranger arranger) {
  super(new JPanel(new BorderLayout()));
  setForceShowAsPopup(true);
  setCancelOnClickOutside(false);
  setResizable(true);

  myProject = project;
  myEditor = InjectedLanguageUtil.getTopLevelEditor(editor);
  myArranger = arranger;
  myPresentableArranger = arranger;
  myEditor.getColorsScheme().getFontPreferences().copyTo(myFontPreferences);

  DaemonCodeAnalyzer.getInstance(myProject).disableUpdateByTimer(this);

  myCellRenderer = new LookupCellRenderer(this);
  myList.setCellRenderer(myCellRenderer);

  myList.setFocusable(false);
  myList.setFixedCellWidth(50);
  myList.setBorder(null);

  // a new top level frame just got the focus. This is important to prevent screen readers
  // from announcing the title of the top level frame when the list is shown (or hidden),
  // as they usually do when a new top-level frame receives the focus.
  AccessibleContextUtil.setParent((Component)myList, myEditor.getContentComponent());

  myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  myList.setBackground(LookupCellRenderer.BACKGROUND_COLOR);

  myAdComponent = new Advertiser();
  myAdComponent.setBackground(LookupCellRenderer.BACKGROUND_COLOR);

  myOffsets = new LookupOffsets(myEditor);

  final CollectionListModel<LookupElement> model = getListModel();
  addEmptyItem(model);
  updateListHeight(model);

  addListeners();
}
 
Example #30
Source File: LookupManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static LookupEx getActiveLookup(@Nullable Editor editor) {
  if (editor == null) return null;

  final Project project = editor.getProject();
  if (project == null || project.isDisposed()) return null;

  final LookupEx lookup = getInstance(project).getActiveLookup();
  if (lookup == null) return null;

  return lookup.getTopLevelEditor() == InjectedLanguageUtil.getTopLevelEditor(editor) ? lookup : null;
}