com.intellij.psi.PsiDocumentManager Java Examples

The following examples show how to use com.intellij.psi.PsiDocumentManager. 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: JavaImportsUtil.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
public final Map<String, Set<String>> getImportInLines(final Editor projectEditor,
                                                       final Pair<Integer, Integer> pair) {
    PsiDocumentManager psiInstance =
            PsiDocumentManager.getInstance(windowObjects.getProject());
    PsiJavaFile psiJavaFile =
            (PsiJavaFile) psiInstance.getPsiFile(projectEditor.getDocument());
    PsiJavaElementVisitor psiJavaElementVisitor =
            new PsiJavaElementVisitor(pair.getFirst(), pair.getSecond());
    Map<String, Set<String>> finalImports = new HashMap<>();
    if (psiJavaFile != null && psiJavaFile.findElementAt(pair.getFirst()) != null) {
        PsiElement psiElement = psiJavaFile.findElementAt(pair.getFirst());
        final PsiElement psiMethod = PsiTreeUtil.getParentOfType(psiElement, PsiMethod.class);
        if (psiMethod != null) {
            psiMethod.accept(psiJavaElementVisitor);
        } else {
            final PsiClass psiClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass.class);
            if (psiClass != null) {
                psiClass.accept(psiJavaElementVisitor);
            }
        }
        Map<String, Set<String>> importVsMethods = psiJavaElementVisitor.getImportVsMethods();
        finalImports = getImportsAndMethodsAfterValidation(psiJavaFile, importVsMethods);
    }
    return removeImplicitImports(finalImports);
}
 
Example #2
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 #3
Source File: DiffContentFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static Document createPsiDocument(@Nonnull Project project,
                                          @Nonnull String content,
                                          @Nonnull FileType fileType,
                                          @Nonnull String fileName,
                                          boolean readOnly) {
  ThrowableComputable<Document,RuntimeException> action = () -> {
    LightVirtualFile file = new LightVirtualFile(fileName, fileType, content);
    file.setWritable(!readOnly);

    file.putUserData(DiffPsiFileSupport.KEY, true);

    Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document == null) return null;

    PsiDocumentManager.getInstance(project).getPsiFile(document);

    return document;
  };
  return AccessRule.read(action);
}
 
Example #4
Source File: EditorHighlighterCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Lexer getLexerBasedOnLexerHighlighter(CharSequence text, VirtualFile virtualFile, Project project) {
  EditorHighlighter highlighter = null;

  PsiFile psiFile = virtualFile != null ? PsiManager.getInstance(project).findFile(virtualFile) : null;
  final Document document = psiFile != null ? PsiDocumentManager.getInstance(project).getDocument(psiFile) : null;
  final EditorHighlighter cachedEditorHighlighter;
  boolean alreadyInitializedHighlighter = false;

  if (document != null &&
      (cachedEditorHighlighter = getEditorHighlighterForCachesBuilding(document)) != null &&
      PlatformIdTableBuilding.checkCanUseCachedEditorHighlighter(text, cachedEditorHighlighter)) {
    highlighter = cachedEditorHighlighter;
    alreadyInitializedHighlighter = true;
  }
  else if (virtualFile != null) {
    highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, virtualFile);
  }

  if (highlighter != null) {
    return new LexerEditorHighlighterLexer(highlighter, alreadyInitializedHighlighter);
  }
  return null;
}
 
Example #5
Source File: PerFileMappingsBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void handleMappingChange(Collection<VirtualFile> files, Collection<VirtualFile> oldFiles, boolean includeOpenFiles) {
  Project project = getProject();
  FilePropertyPusher<T> pusher = getFilePropertyPusher();
  if (project != null && pusher != null) {
    for (VirtualFile oldFile : oldFiles) {
      if (oldFile == null) continue; // project
      oldFile.putUserData(pusher.getFileDataKey(), null);
    }
    if (!project.isDefault()) {
      PushedFilePropertiesUpdater.getInstance(project).pushAll(pusher);
    }
  }
  if (shouldReparseFiles()) {
    Project[] projects = project == null ? ProjectManager.getInstance().getOpenProjects() : new Project[] { project };
    for (Project p : projects) {
      PsiDocumentManager.getInstance(p).reparseFiles(files, includeOpenFiles);
    }
  }
}
 
Example #6
Source File: GoogleJavaFormatCodeStyleManager.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
private void performReplacements(
    final Document document, final Map<TextRange, String> replacements) {

  if (replacements.isEmpty()) {
    return;
  }

  TreeMap<TextRange, String> sorted = new TreeMap<>(comparing(TextRange::getStartOffset));
  sorted.putAll(replacements);
  WriteCommandAction.runWriteCommandAction(
      getProject(),
      () -> {
        for (Entry<TextRange, String> entry : sorted.descendingMap().entrySet()) {
          document.replaceString(
              entry.getKey().getStartOffset(), entry.getKey().getEndOffset(), entry.getValue());
        }
        PsiDocumentManager.getInstance(getProject()).commitDocument(document);
      });
}
 
Example #7
Source File: AbstractUploadCloudActionTest.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * 获取 document 的几种方式
 *
 * @param e the e
 */
private void getDocument(AnActionEvent e) {
    // 从当前编辑器中获取
    Document documentFromEditor = Objects.requireNonNull(e.getData(PlatformDataKeys.EDITOR)).getDocument();
    // 从 VirtualFile 获取 (如果之前未加载文档内容,则此调用会强制从磁盘加载文档内容)
    VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    if (virtualFile != null) {
        Document documentFromVirtualFile = FileDocumentManager.getInstance().getDocument(virtualFile);
        // 从缓存中获取
        Document documentFromVirtualFileCache = FileDocumentManager.getInstance().getCachedDocument(virtualFile);

        // 从 PSI 中获取
        Project project = e.getProject();
        if (project != null) {
            // 获取 PSI (一)
            PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
            // 获取 PSI (二)
            psiFile = e.getData(CommonDataKeys.PSI_FILE);
            if (psiFile != null) {
                Document documentFromPsi = PsiDocumentManager.getInstance(project).getDocument(psiFile);
                // 从缓存中获取
                Document documentFromPsiCache = PsiDocumentManager.getInstance(project).getCachedDocument(psiFile);
            }
        }
    }
}
 
Example #8
Source File: PasteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
static void indentBlock(Project project, Editor editor, final int startOffset, final int endOffset, int originalCaretCol) {
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitAllDocuments();
  final Document document = editor.getDocument();
  PsiFile file = documentManager.getPsiFile(document);
  if (file == null) {
    return;
  }

  if (LanguageFormatting.INSTANCE.forContext(file) != null) {
    indentBlockWithFormatter(project, document, startOffset, endOffset, file);
  }
  else {
    indentPlainTextBlock(document, startOffset, endOffset, originalCaretCol);
  }
}
 
Example #9
Source File: DefaultHighlightInfoProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void highlightsOutsideVisiblePartAreProduced(@Nonnull final HighlightingSession session,
                                                    @Nullable Editor editor,
                                                    @Nonnull final List<? extends HighlightInfo> infos,
                                                    @Nonnull final TextRange priorityRange,
                                                    @Nonnull final TextRange restrictedRange, final int groupId) {
  final PsiFile psiFile = session.getPsiFile();
  final Project project = psiFile.getProject();
  final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
  if (document == null) return;
  final long modificationStamp = document.getModificationStamp();
  ((HighlightingSessionImpl)session).applyInEDT(() -> {
    if (project.isDisposed() || modificationStamp != document.getModificationStamp()) return;

    EditorColorsScheme scheme = session.getColorsScheme();

    UpdateHighlightersUtil
            .setHighlightersOutsideRange(project, document, psiFile, infos, scheme, restrictedRange.getStartOffset(), restrictedRange.getEndOffset(), ProperTextRange.create(priorityRange), groupId);
    if (editor != null) {
      repaintErrorStripeAndIcon(editor, project);
    }
  });
}
 
Example #10
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the given edits to the document
 *
 * @param version    The version of the edits (will be discarded if older than current version)
 * @param edits      The edits to apply
 * @param name       The name of the edits (Rename, for example)
 * @param closeAfter will close the file after edits if set to true
 * @return True if the edits were applied, false otherwise
 */
boolean applyEdit(int version, List<TextEdit> edits, String name, boolean closeAfter, boolean setCaret) {
    Runnable runnable = getEditsRunnable(version, edits, name, setCaret);
    writeAction(() -> {
        if (runnable != null) {
            CommandProcessor.getInstance()
                    .executeCommand(project, runnable, name, "LSPPlugin", editor.getDocument());
        }
        if (closeAfter) {
            PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
            if (file != null) {
                FileEditorManager.getInstance(project).closeFile(file.getVirtualFile());
            }
        }
    });
    return runnable != null;
}
 
Example #11
Source File: FileContentUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void setFileText(@javax.annotation.Nullable Project project, final VirtualFile virtualFile, final String text) throws IOException {
  if (project == null) {
    project = ProjectUtil.guessProjectForFile(virtualFile);
  }
  if (project != null) {
    final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document document = psiFile == null? null : psiDocumentManager.getDocument(psiFile);
    if (document != null) {
      document.setText(text != null ? text : "");
      psiDocumentManager.commitDocument(document);
      FileDocumentManager.getInstance().saveDocument(document);
      return;
    }
  }
  VfsUtil.saveText(virtualFile, text != null ? text : "");
  virtualFile.refresh(false, false);
}
 
Example #12
Source File: TextEditorBackgroundHighlighter.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void renewFile() {
  if (myFile == null || !myFile.isValid()) {
    myFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myDocument);
    myCompiled = myFile instanceof PsiCompiledFile;
    if (myCompiled) {
      myFile = ((PsiCompiledFile)myFile).getDecompiledPsiFile();
    }
    if (myFile != null && !myFile.isValid()) {
      myFile = null;
    }
  }

  if (myFile != null) {
    myFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE);
  }
}
 
Example #13
Source File: GaugeConsoleProperties.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public SMTestLocator getTestLocator() {
    return (protocol, path, project, globalSearchScope) -> {
        try {
            String[] fileInfo = path.split(Constants.SPEC_SCENARIO_DELIMITER);
            VirtualFile file = LocalFileSystem.getInstance().findFileByPath(fileInfo[0]);
            if (file == null) return new ArrayList<>();
            PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
            if (psiFile == null) return new ArrayList<>();
            Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
            if (document == null) return new ArrayList<>();
            int line = Integer.parseInt(fileInfo[1]);
            PsiElement element = psiFile.findElementAt(document.getLineStartOffset(line));
            if (element == null) return new ArrayList<>();
            return Collections.singletonList(new PsiLocation<>(element));
        } catch (Exception e) {
            return new ArrayList<>();
        }
    };
}
 
Example #14
Source File: GoogleJavaFormatCodeStyleManager.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
private void formatInternal(PsiFile file, Collection<TextRange> ranges) {
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
  documentManager.commitAllDocuments();
  CheckUtil.checkWritable(file);

  Document document = documentManager.getDocument(file);

  if (document == null) {
    return;
  }
  // If there are postponed PSI changes (e.g., during a refactoring), just abort.
  // If we apply them now, then the incoming text ranges may no longer be valid.
  if (documentManager.isDocumentBlockedByPsi(document)) {
    return;
  }

  format(document, ranges);
}
 
Example #15
Source File: DebugInlinePostfixTemplate.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    FluidInlineStatement expression = (FluidInlineStatement) PsiTreeUtil.findFirstParent(context, psiElement -> psiElement instanceof FluidInlineStatement);
    if (expression == null) {
        return;
    }

    Template tagTemplate = LiveTemplateFactory.createInlinePipeToDebugTemplate(expression);
    tagTemplate.addVariable("EXPR", new TextExpression(expression.getInlineChain().getText()), true);

    int textOffset = expression.getTextOffset() + expression.getTextLength();
    editor.getCaretModel().moveToOffset(textOffset);

    TemplateManager.getInstance(context.getProject()).startTemplate(editor, tagTemplate);
    PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());

    expression.delete();
}
 
Example #16
Source File: AttrMacroInsertHandler.java    From intellij-latte with MIT License 6 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE && element.getNode().getElementType() == LatteTypes.T_HTML_TAG_NATTR_NAME) {
		Editor editor = context.getEditor();
		CaretModel caretModel = editor.getCaretModel();
		int offset = caretModel.getOffset();
		if (LatteUtil.isStringAtCaret(editor, "=")) {
			caretModel.moveToOffset(offset + 2);
			return;
		}

		String attrName = LatteUtil.normalizeNAttrNameModifier(element.getText());
		LatteTagSettings macro = LatteConfiguration.getInstance(element.getProject()).getTag(attrName);
		if (macro != null && !macro.hasParameters()) {
			return;
		}

		editor.getDocument().insertString(offset, "=\"\"");
		caretModel.moveToOffset(offset + 2);

		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example #17
Source File: AddUsingAction.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
private void execute0(final NamespaceReference namespaceReference)
{
	PsiDocumentManager.getInstance(myProject).commitAllDocuments();

	WriteCommandAction.runWriteCommandAction(myProject, () ->
	{
		addUsing(namespaceReference.getNamespace());

		String libraryName = namespaceReference.getLibraryName();
		if(libraryName != null)
		{
			Module moduleForFile = ModuleUtilCore.findModuleForPsiElement(myFile);
			if(moduleForFile != null)
			{
				ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(moduleForFile);

				final ModifiableRootModel modifiableModel = moduleRootManager.getModifiableModel();

				modifiableModel.addOrderEntry(new DotNetLibraryOrderEntryImpl((ModuleRootLayerImpl) moduleRootManager.getCurrentLayer(), libraryName));

				WriteAction.run(modifiableModel::commit);
			}
		}
	});
}
 
Example #18
Source File: IndentSelectionAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void indentSelection(Editor editor, Project project) {
  int oldSelectionStart = editor.getSelectionModel().getSelectionStart();
  int oldSelectionEnd = editor.getSelectionModel().getSelectionEnd();
  if(!editor.getSelectionModel().hasSelection()) {
    oldSelectionStart = editor.getCaretModel().getOffset();
    oldSelectionEnd = oldSelectionStart;
  }

  Document document = editor.getDocument();
  int startIndex = document.getLineNumber(oldSelectionStart);
  if(startIndex == -1) {
    startIndex = document.getLineCount() - 1;
  }
  int endIndex = document.getLineNumber(oldSelectionEnd);
  if(endIndex > 0 && document.getLineStartOffset(endIndex) == oldSelectionEnd && editor.getSelectionModel().hasSelection()) {
    endIndex --;
  }
  if(endIndex == -1) {
    endIndex = document.getLineCount() - 1;
  }

  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
  int blockIndent = CodeStyleSettingsManager.getSettings(project).getIndentOptionsByFile(file).INDENT_SIZE;
  doIndent(endIndex, startIndex, document, project, editor, blockIndent);
}
 
Example #19
Source File: CustomizableLanguageCodeStylePanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected PsiFile doReformat(final Project project, final PsiFile psiFile) {
  final String text = psiFile.getText();
  final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
  final Document doc = manager.getDocument(psiFile);
  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    if (doc != null) {
      doc.replaceString(0, doc.getTextLength(), text);
      manager.commitDocument(doc);
    }
    try {
      CodeStyleManager.getInstance(project).reformat(psiFile);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }), "", "");
  if (doc != null) {
    manager.commitDocument(doc);
  }
  return psiFile;
}
 
Example #20
Source File: ReformatAction.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    PsiFile file = e.getData(PSI_FILE);
    Project project = e.getProject();
    if (project != null && file != null) {
        String format = ReformatUtil.getFormat(file);
        if (format != null) {
            Document document = PsiDocumentManager.getInstance(project).getCachedDocument(file);
            if (document != null) {
                ServiceManager.
                        getService(project, BsCompiler.class).
                        refmt(file.getVirtualFile(), FileHelper.isInterface(file.getFileType()), format, document);
            }
        }
    }
}
 
Example #21
Source File: PasteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void reformatBlock(final Project project, final Editor editor, final int startOffset, final int endOffset) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  Runnable task = new Runnable() {
    @Override
    public void run() {
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      try {
        CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true);
      }
      catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  };

  if (endOffset - startOffset > 1000) {
    DocumentUtil.executeInBulk(editor.getDocument(), true, task);
  }
  else {
    task.run();
  }
}
 
Example #22
Source File: ExternalFormatterCodeStyleManager.java    From intellij with Apache License 2.0 6 votes vote down vote up
protected void formatAsync(FileContentsProvider fileContents, ListenableFuture<String> future) {
  future.addListener(
      () -> {
        String text = fileContents.getFileContentsIfUnchanged();
        if (text == null) {
          return;
        }
        Document document = getDocument(fileContents.file);
        if (!FormatUtils.canApplyChanges(getProject(), document)) {
          return;
        }
        String formattedFile = getFormattingFuture(future);
        if (formattedFile == null || formattedFile.equals(text)) {
          return;
        }
        FormatUtils.runWriteActionIfUnchanged(
            getProject(),
            document,
            text,
            () -> {
              document.setText(formattedFile);
              PsiDocumentManager.getInstance(getProject()).commitDocument(document);
            });
      },
      MoreExecutors.directExecutor());
}
 
Example #23
Source File: FormatterTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"UNUSED_SYMBOL"})
private void restoreFileContent(final PsiFile file, final String text) {
  CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(file);
          document.replaceString(0, document.getTextLength(), text);
          PsiDocumentManager.getInstance(getProject()).commitDocument(document);
        }
      });

    }
  }, "test", null);
}
 
Example #24
Source File: JSGraphQLSchemaGraphQLConfigCodeInsightTest.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
private void doTestCompletion(String sourceFile, List<String> expectedCompletions) {
    for (PsiFile file : this.files) {
        if (file.getVirtualFile().getPath().endsWith(sourceFile)) {
            myFixture.configureFromExistingVirtualFile(file.getVirtualFile());
            break;
        }
    }
    final Lock readLock = GraphQLConfigManager.getService(getProject()).getReadLock();
    try {
        readLock.lock();
        myFixture.complete(CompletionType.BASIC, 1);
        final List<String> completions = myFixture.getLookupElementStrings();
        assertEquals("Wrong completions", expectedCompletions, completions);
    } finally {
        readLock.unlock();
    }
    ApplicationManager.getApplication().runWriteAction(() -> {
        myFixture.getEditor().getDocument().setText(""); // blank out the file so it doesn't affect other tests
        PsiDocumentManager.getInstance(myFixture.getProject()).commitAllDocuments();
    });
}
 
Example #25
Source File: EditorActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
static boolean ensureInjectionUpToDate(@Nonnull Caret hostCaret) {
  Editor editor = hostCaret.getEditor();
  Project project = editor.getProject();
  if (project != null && InjectedLanguageManager.getInstance(project).mightHaveInjectedFragmentAtOffset(editor.getDocument(), hostCaret.getOffset())) {
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    return true;
  }
  return false;
}
 
Example #26
Source File: XQuickEvaluateHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public AbstractValueHint createValueHint(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final Point point, final ValueHintType type) {
  final XDebugSession session = XDebuggerManager.getInstance(project).getCurrentSession();
  if (session == null) {
    return null;
  }

  final XDebuggerEvaluator evaluator = session.getDebugProcess().getEvaluator();
  if (evaluator == null) {
    return null;
  }

  return PsiDocumentManager.getInstance(project).commitAndRunReadAction(new Computable<XValueHint>() {
    @Override
    public XValueHint compute() {
      int offset = AbstractValueHint.calculateOffset(editor, point);
      ExpressionInfo expressionInfo = getExpressionInfo(evaluator, project, type, editor, offset);
      if (expressionInfo == null) {
        return null;
      }

      int textLength = editor.getDocument().getTextLength();
      TextRange range = expressionInfo.getTextRange();
      if (range.getStartOffset() > range.getEndOffset() || range.getStartOffset() < 0 || range.getEndOffset() > textLength) {
        LOG.error("invalid range: " + range + ", text length = " + textLength + ", evaluator: " + evaluator);
        return null;
      }

      return new XValueHint(project, editor, point, type, expressionInfo, evaluator, session);
    }
  });
}
 
Example #27
Source File: InplaceChangeSignature.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void temporallyRevertChanges(final TextRange signatureRange,
                                           final Document document,
                                           final String initialSignature,
                                           Project project) {
  WriteCommandAction.runWriteCommandAction(project, () -> {
    document.replaceString(signatureRange.getStartOffset(), signatureRange.getEndOffset(), initialSignature);
    PsiDocumentManager.getInstance(project).commitDocument(document);
  });
}
 
Example #28
Source File: EvaluateExpansionQuickfix.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    TextRange r = startElement.getTextRange();

    Document document = PsiDocumentManager.getInstance(project).getDocument(file);

    String replacement = ValueExpansionUtil.expand(startElement.getText(), enableBash4);
    if (replacement != null && document != null) {
        editor.getDocument().replaceString(r.getStartOffset(), r.getEndOffset(), replacement);
        PsiDocumentManager.getInstance(project).commitDocument(document);
    }
}
 
Example #29
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 #30
Source File: LineMarkersPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void queryLineMarkersForInjected(@Nonnull PsiElement element,
                                                @Nonnull final PsiFile containingFile,
                                                @Nonnull Set<? super PsiFile> visitedInjectedFiles,
                                                @Nonnull final PairConsumer<? super PsiElement, ? super LineMarkerInfo<PsiElement>> consumer) {
  final InjectedLanguageManager manager = InjectedLanguageManager.getInstance(containingFile.getProject());
  if (manager.isInjectedFragment(containingFile)) return;

  InjectedLanguageManager.getInstance(containingFile.getProject()).enumerateEx(element, containingFile, false, (injectedPsi, places) -> {
    if (!visitedInjectedFiles.add(injectedPsi)) return; // there may be several concatenated literals making the one injected file
    final Project project = injectedPsi.getProject();
    Document document = PsiDocumentManager.getInstance(project).getCachedDocument(injectedPsi);
    if (!(document instanceof DocumentWindow)) return;
    List<PsiElement> injElements = CollectHighlightsUtil.getElementsInRange(injectedPsi, 0, injectedPsi.getTextLength());
    final List<LineMarkerProvider> providers = getMarkerProviders(injectedPsi.getLanguage(), project);

    queryProviders(injElements, injectedPsi, providers, (injectedElement, injectedMarker) -> {
      GutterIconRenderer gutterRenderer = injectedMarker.createGutterRenderer();
      TextRange injectedRange = new TextRange(injectedMarker.startOffset, injectedMarker.endOffset);
      List<TextRange> editables = manager.intersectWithAllEditableFragments(injectedPsi, injectedRange);
      for (TextRange editable : editables) {
        TextRange hostRange = manager.injectedToHost(injectedPsi, editable);
        Image icon = gutterRenderer == null ? null : gutterRenderer.getIcon();
        GutterIconNavigationHandler<PsiElement> navigationHandler = injectedMarker.getNavigationHandler();
        LineMarkerInfo<PsiElement> converted =
                new LineMarkerInfo<>(injectedElement, hostRange, icon, injectedMarker.updatePass, e -> injectedMarker.getLineMarkerTooltip(), navigationHandler, GutterIconRenderer.Alignment.RIGHT);
        consumer.consume(injectedElement, converted);
      }
    });
  });
}