Java Code Examples for com.intellij.openapi.editor.Editor#getDocument()

The following examples show how to use com.intellij.openapi.editor.Editor#getDocument() . 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: BackgroundEditorPool.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected boolean removeEldestEntry(Entry<IFile, Editor> eldest) {
  if (size() >= capacity) {
    Editor editor = eldest.getValue();

    releaseBackgroundEditor(editor);

    IFile file = eldest.getKey();
    Document document = editor.getDocument();
    log.debug("Evicting least recently used entry from cache: " + file + " - " + document);

    return true;
  }

  return false;
}
 
Example 2
Source File: FoldingUpdate.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
static Runnable updateFoldRegions(@Nonnull final Editor editor, @Nonnull PsiFile file, final boolean applyDefaultState, final boolean quick) {
  ApplicationManager.getApplication().assertReadAccessAllowed();

  final Project project = file.getProject();
  final Document document = editor.getDocument();
  LOG.assertTrue(!PsiDocumentManager.getInstance(project).isUncommited(document));

  CachedValue<Runnable> value = editor.getUserData(CODE_FOLDING_KEY);

  if (value != null && !applyDefaultState) {
    Getter<Runnable> cached = value.getUpToDateOrNull();
    if (cached != null) {
      return cached.get();
    }
  }
  if (quick || applyDefaultState) return getUpdateResult(file, document, quick, project, editor, applyDefaultState).getValue();

  return CachedValuesManager.getManager(project).getCachedValue(editor, CODE_FOLDING_KEY, () -> {
    PsiFile file1 = PsiDocumentManager.getInstance(project).getPsiFile(document);
    return getUpdateResult(file1, document, false, project, editor, false);
  }, false);
}
 
Example 3
Source File: CSharpStatementMover.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
private static PsiElement itIsTheClosingCurlyBraceWeAreMoving(final PsiFile file, final Editor editor)
{
	LineRange range = getLineRangeFromSelection(editor);
	if(range.endLine - range.startLine != 1)
	{
		return null;
	}
	int offset = editor.getCaretModel().getOffset();
	Document document = editor.getDocument();
	int line = document.getLineNumber(offset);
	int lineStartOffset = document.getLineStartOffset(line);
	String lineText = document.getText().substring(lineStartOffset, document.getLineEndOffset(line));
	if(!lineText.trim().equals("}"))
	{
		return null;
	}

	return file.findElementAt(lineStartOffset + lineText.indexOf('}'));
}
 
Example 4
Source File: ProjectViewEnterHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public Result preprocessEnter(
    PsiFile file,
    Editor editor,
    Ref<Integer> caretOffset,
    Ref<Integer> caretAdvance,
    DataContext dataContext,
    EditorActionHandler originalHandler) {
  int offset = caretOffset.get();
  if (editor instanceof EditorWindow) {
    file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
    editor = InjectedLanguageUtil.getTopLevelEditor(editor);
    offset = editor.getCaretModel().getOffset();
  }
  if (!isApplicable(file, dataContext) || !insertIndent(file, offset)) {
    return Result.Continue;
  }
  int indent = SectionParser.INDENT;

  editor.getCaretModel().moveToOffset(offset);
  Document doc = editor.getDocument();
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(doc);

  originalHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
  LogicalPosition position = editor.getCaretModel().getLogicalPosition();
  if (position.column < indent) {
    String spaces = StringUtil.repeatSymbol(' ', indent - position.column);
    doc.insertString(editor.getCaretModel().getOffset(), spaces);
  }
  editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(position.line, indent));
  return Result.Stop;
}
 
Example 5
Source File: QueryHighlighterCaretListener.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
private void processEvent(CaretEvent e) {
    Editor editor = e.getEditor();
    Project project = editor.getProject();
    if (project == null) {
        return;
    }

    Document document = editor.getDocument();
    PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);

    syncedElementHighlighter.highlightStatement(editor, psiFile);
}
 
Example 6
Source File: CompletionInitializationContext.java    From consulo with Apache License 2.0 5 votes vote down vote up
public CompletionInitializationContext(final Editor editor, final @Nonnull Caret caret, Language language, final PsiFile file, final CompletionType completionType, int invocationCount) {
  myEditor = editor;
  myCaret = caret;
  myPositionLanguage = language;
  myFile = file;
  myCompletionType = completionType;
  myInvocationCount = invocationCount;
  myOffsetMap = new OffsetMap(editor.getDocument());

  myOffsetMap.addOffset(START_OFFSET, calcStartOffset(caret));
  myOffsetMap.addOffset(SELECTION_END_OFFSET, calcSelectionEnd(caret));
  myOffsetMap.addOffset(IDENTIFIER_END_OFFSET, calcDefaultIdentifierEnd(editor, calcSelectionEnd(caret)));
}
 
Example 7
Source File: QuickDocOnMouseOverManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void registerListeners(@Nonnull Editor editor) {
  editor.addEditorMouseListener(myMouseListener);
  editor.addEditorMouseMotionListener(myMouseListener);
  editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener);
  editor.getCaretModel().addCaretListener(myCaretListener);

  Document document = editor.getDocument();
  if (myMonitoredDocuments.put(document, Boolean.TRUE) == null) {
    document.addDocumentListener(myDocumentListener);
  }
}
 
Example 8
Source File: EditorUtils.java    From emacsIDEAs with Apache License 2.0 5 votes vote down vote up
public static ArrayList<Integer> getVisibleLineStartOffsets(Editor editor) {
    Document document = editor.getDocument();
    ArrayList<Integer> offsets = new ArrayList<Integer>();

    TextRange visibleTextRange = getVisibleTextRange(editor);
    int startLine = document.getLineNumber(visibleTextRange.getStartOffset());
    int endLine = document.getLineNumber(visibleTextRange.getEndOffset());

    for (int i = startLine; i < endLine; i++) {
        offsets.add(document.getLineStartOffset(i));
    }

    return offsets;
}
 
Example 9
Source File: WholeFileLocalInspectionsPassFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public TextEditorHighlightingPass createHighlightingPass(@Nonnull final PsiFile file, @Nonnull final Editor editor) {
  final long psiModificationCount = PsiManager.getInstance(myProject).getModificationTracker().getModificationCount();
  if (psiModificationCount == myPsiModificationCount) {
    return null; //optimization
  }

  if (myFileToolsCache.containsKey(file) && !myFileToolsCache.get(file)) {
    return null;
  }
  ProperTextRange visibleRange = VisibleHighlightingPassFactory.calculateVisibleRange(editor);
  return new LocalInspectionsPass(file, editor.getDocument(), 0, file.getTextLength(), visibleRange, true, new DefaultHighlightInfoProcessor()) {
    @Nonnull
    @Override
    List<LocalInspectionToolWrapper> getInspectionTools(@Nonnull InspectionProfileWrapper profile) {
      List<LocalInspectionToolWrapper> tools = super.getInspectionTools(profile);
      List<LocalInspectionToolWrapper> result = tools.stream().filter(LocalInspectionToolWrapper::runForWholeFile).collect(Collectors.toList());
      myFileToolsCache.put(file, !result.isEmpty());
      return result;
    }

    @Override
    protected String getPresentableName() {
      return DaemonBundle.message("pass.whole.inspections");
    }

    @Override
    void inspectInjectedPsi(@Nonnull List<PsiElement> elements,
                            boolean onTheFly,
                            @Nonnull ProgressIndicator indicator,
                            @Nonnull InspectionManager iManager,
                            boolean inVisibleRange,
                            @Nonnull List<LocalInspectionToolWrapper> wrappers) {
      // already inspected in LIP
    }

    @Override
    protected void applyInformationWithProgress() {
      super.applyInformationWithProgress();
      myPsiModificationCount = PsiManager.getInstance(myProject).getModificationTracker().getModificationCount();
    }
  };
}
 
Example 10
Source File: BaseIndentEnterHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(
        @Nonnull final PsiFile file,
        @Nonnull final Editor editor,
        @Nonnull final Ref<Integer> caretOffset,
        @Nonnull final Ref<Integer> caretAdvance,
        @Nonnull final DataContext dataContext,
        final EditorActionHandler originalHandler)
{
  Result res = shouldSkipWithResult(file, editor, dataContext);
  if (res != null) {
    return res;
  }

  final Document document = editor.getDocument();
  int caret = editor.getCaretModel().getOffset();
  final int lineNumber = document.getLineNumber(caret);

  final int lineStartOffset = document.getLineStartOffset(lineNumber);
  final int previousLineStartOffset = lineNumber > 0 ? document.getLineStartOffset(lineNumber - 1) : lineStartOffset;
  final EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter();
  final HighlighterIterator iterator = highlighter.createIterator(caret - 1);
  final IElementType type = getNonWhitespaceElementType(iterator, lineStartOffset, previousLineStartOffset);

  final CharSequence editorCharSequence = document.getCharsSequence();
  final CharSequence lineIndent =
          editorCharSequence.subSequence(lineStartOffset, EditorActionUtil.findFirstNonSpaceOffsetOnTheLine(document, lineNumber));

  // Enter in line comment
  if (type == myLineCommentType) {
    final String restString = editorCharSequence.subSequence(caret, document.getLineEndOffset(lineNumber)).toString();
    if (!StringUtil.isEmptyOrSpaces(restString)) {
      final String linePrefix = lineIndent + myLineCommentPrefix;
      EditorModificationUtil.insertStringAtCaret(editor, "\n" + linePrefix);
      editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber + 1, linePrefix.length()));
      return Result.Stop;
    }
    else if (iterator.getStart() < lineStartOffset) {
      EditorModificationUtil.insertStringAtCaret(editor, "\n" + lineIndent);
      return Result.Stop;
    }
  }

  if (!myWorksWithFormatter && LanguageFormatting.INSTANCE.forLanguage(myLanguage) != null) {
    return Result.Continue;
  }
  else {
    if (myIndentTokens.contains(type)) {
      final String newIndent = getNewIndent(file, document, lineIndent);
      EditorModificationUtil.insertStringAtCaret(editor, "\n" + newIndent);
      return Result.Stop;
    }

    EditorModificationUtil.insertStringAtCaret(editor, "\n" + lineIndent);
    editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber + 1, calcLogicalLength(editor, lineIndent)));
    return Result.Stop;
  }
}
 
Example 11
Source File: ActionPerformer.java    From dummytext-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * @param   event    ActionSystem event
 */
void write(final AnActionEvent event) {
    Editor editor = event.getData(PlatformDataKeys.EDITOR);

    if (editor != null) {
        final Document document = editor.getDocument();

        CaretModel caretModel = editor.getCaretModel();

        for (Caret caret : caretModel.getAllCarets()) {
            boolean hasSelection = caret.hasSelection();
            String selectedText  = caret.getSelectedText();

            String trailingCharacter    = TextualHelper.getTrailingPunctuationMark(selectedText);
            String leadingCharacters    = TextualHelper.getLeadingPreservation(selectedText);

            int amountLines     = 1;
            // applies only when replacing a single-lined selection, can be rounded up
            Integer amountWords = null;

            // Generated dummy text will replace the current selected text
            if (hasSelection && selectedText != null ) {
                int selectionLength = selectedText.length();
                if (selectionLength > 0) {
                    amountLines = TextualHelper.countLines(selectedText);
                    if (amountLines == 1) {
                        amountWords = TextualHelper.getWordCount(selectedText);
                    }
                }
            }

            // Generate and insert / replace selection with dummy text
            String dummyText  = generateText(amountLines, amountWords, leadingCharacters, trailingCharacter, selectedText).toString();

            Integer dummyTextLength = dummyText.length();
            Integer offsetStart;

            if (hasSelection) {
                // Move caret to end of selection
                offsetStart = caret.getSelectionStart();
                int offsetEnd = caret.getSelectionEnd();

                document.replaceString(offsetStart, offsetEnd, dummyText);
                caret.setSelection(offsetStart, offsetStart + dummyTextLength);
            } else {
                // Move caret to end of inserted text
                offsetStart  = caretModel.getOffset();
                dummyText   = dummyText.trim();
                document.insertString(offsetStart, dummyText);
            }
        }

    }
}
 
Example 12
Source File: AddSpaceInsertHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean isCharAtSpace(Editor editor) {
  final int startOffset = editor.getCaretModel().getOffset();
  final Document document = editor.getDocument();
  return document.getTextLength() > startOffset && document.getCharsSequence().charAt(startOffset) == ' ';
}
 
Example 13
Source File: ParagraphFillHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected void performOnElement(@Nonnull final PsiElement element, @Nonnull final Editor editor) {
  final Document document = editor.getDocument();

  final TextRange textRange = getTextRange(element, editor);
  if (textRange.isEmpty()) return;
  final String text = textRange.substring(element.getContainingFile().getText());

  final List<String> subStrings = StringUtil.split(text, "\n", true);
  final String prefix = getPrefix(element);
  final String postfix = getPostfix(element);

  final StringBuilder stringBuilder = new StringBuilder();
  appendPrefix(element, text, stringBuilder);

  for (String string : subStrings) {
    final String startTrimmed = StringUtil.trimStart(string.trim(), prefix.trim());
    final String str = StringUtil.trimEnd(startTrimmed, postfix.trim());
    final String finalString = str.trim();
    if (!StringUtil.isEmptyOrSpaces(finalString))
      stringBuilder.append(finalString).append(" ");
  }
  appendPostfix(element, text, stringBuilder);

  final String replacementText = stringBuilder.toString();

  CommandProcessor.getInstance().executeCommand(element.getProject(), () -> {
    document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(),
                           replacementText);
    final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(
            CodeStyleSettingsManager.getSettings(element.getProject()), element.getLanguage());

    final PsiFile file = element.getContainingFile();
    FormatterTagHandler formatterTagHandler = new FormatterTagHandler(CodeStyleSettingsManager.getSettings(file.getProject()));
    List<TextRange> enabledRanges = formatterTagHandler.getEnabledRanges(file.getNode(), TextRange.create(0, document.getTextLength()));

    codeFormatter.doWrapLongLinesIfNecessary(editor, element.getProject(), document,
                                             textRange.getStartOffset(),
                                             textRange.getStartOffset() + replacementText.length() + 1,
                                             enabledRanges);
  }, null, document);

}
 
Example 14
Source File: SaveDocumentAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static Document getDocument(AnActionEvent e) {
  Editor editor = e.getData(PlatformDataKeys.EDITOR);
  return editor != null ? editor.getDocument() : null;
}
 
Example 15
Source File: InsertHandlerUtils.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
public static void removePreviousNamespaceAndColonIfPresent(InsertionContext context) {
    final Editor editor = context.getEditor();
    final Document document = editor.getDocument();
    PsiElement elementBeforeColon = findElementBeforeColon(context);
    removeNamespaceAndColon(context, document, elementBeforeColon);
}
 
Example 16
Source File: BracesInsertHandler.java    From consulo-unity3d with Apache License 2.0 4 votes vote down vote up
@Override
public void handleInsert(final InsertionContext context, final T item)
{
	final Editor editor = context.getEditor();
	final Document document = editor.getDocument();
	context.commitDocument();
	PsiElement element = findNextToken(context);

	final char completionChar = context.getCompletionChar();
	final boolean putCaretInside = completionChar == '{' || placeCaretInsideParentheses(context, item);

	if(completionChar == '{')
	{
		context.setAddCompletionChar(false);
	}

	if(isToken(element, "{"))
	{
		int lparenthOffset = element.getTextRange().getStartOffset();
		if(mySpaceBeforeParentheses && lparenthOffset == context.getTailOffset())
		{
			document.insertString(context.getTailOffset(), " ");
			lparenthOffset++;
		}

		if(completionChar == '{' || completionChar == '\t')
		{
			editor.getCaretModel().moveToOffset(lparenthOffset + 1);
		}
		else
		{
			editor.getCaretModel().moveToOffset(context.getTailOffset());
		}

		context.setTailOffset(lparenthOffset + 1);

		PsiElement list = element.getParent();
		PsiElement last = list.getLastChild();
		if(isToken(last, "}"))
		{
			int rparenthOffset = last.getTextRange().getStartOffset();
			context.setTailOffset(rparenthOffset + 1);
			if(!putCaretInside)
			{
				for(int i = lparenthOffset + 1; i < rparenthOffset; i++)
				{
					if(!Character.isWhitespace(document.getCharsSequence().charAt(i)))
					{
						return;
					}
				}
				editor.getCaretModel().moveToOffset(context.getTailOffset());
			}
			else if(mySpaceBetweenParentheses && document.getCharsSequence().charAt(lparenthOffset) == ' ')
			{
				editor.getCaretModel().moveToOffset(lparenthOffset + 2);
			}
			else
			{
				editor.getCaretModel().moveToOffset(lparenthOffset + 1);
			}
			return;
		}
	}
	else
	{
		document.insertString(context.getTailOffset(), getSpace(mySpaceBeforeParentheses) + '{' + getSpace(mySpaceBetweenParentheses));
		editor.getCaretModel().moveToOffset(context.getTailOffset());
	}

	if(!myMayInsertRightParenthesis)
	{
		return;
	}

	if(context.getCompletionChar() == '{')
	{
		int tail = context.getTailOffset();
		if(tail < document.getTextLength() && StringUtil.isJavaIdentifierPart(document.getCharsSequence().charAt(tail)))
		{
			return;
		}
	}

	document.insertString(context.getTailOffset(), getSpace(mySpaceBetweenParentheses) + "}");
	if(!putCaretInside)
	{
		editor.getCaretModel().moveToOffset(context.getTailOffset());
	}
}
 
Example 17
Source File: JSGraphQLEndpointCreateDefinitionIntention.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {

    final JSGraphQLEndpointNamedTypePsiElement unknownNamedType = getUnknownNamedType(element);
    if (unknownNamedType != null) {
        JSGraphQLEndpointNamedTypeDefinition definition = PsiTreeUtil.getParentOfType(element, JSGraphQLEndpointNamedTypeDefinition.class);
        if (definition == null) {
            // nearest type before cursor if not inside a type definition
            definition = PsiTreeUtil.getPrevSiblingOfType(unknownNamedType, JSGraphQLEndpointNamedTypeDefinition.class);
        }
        if (definition != null) {
            final IElementType type = getSupportedDefinitionType();
            final String definitionText;
            final boolean insertBefore = (type == JSGraphQLEndpointTokenTypes.INPUT);
            Ref<Integer> caretOffsetAfterInsert = new Ref<>();
            boolean indent = false;
            if (type == JSGraphQLEndpointTokenTypes.UNION) {
                definitionText = "\n\nunion " + unknownNamedType.getText() + " = \n";
                caretOffsetAfterInsert.set(definitionText.length() - 1);
            } else if (type == JSGraphQLEndpointTokenTypes.SCALAR) {
                definitionText = "\n\nscalar " + unknownNamedType.getText() + "\n";
            } else {
                // all other types are <name> { ... }
                final String beforeLines = insertBefore ? "" : "\n\n";
                final String afterLines = insertBefore ? "\n\n" : "\n";
                final int caretOffsetDelta = insertBefore ? 4 : 3; // we want the caret to be placed before closing '}' and the trailing newlines
                definitionText = beforeLines + type.toString().toLowerCase() + " " + unknownNamedType.getText() + " {\n\n}" + afterLines;
                caretOffsetAfterInsert.set(definitionText.length() - caretOffsetDelta);
                indent = true;
            }
            final Document document = editor.getDocument();
            final int insertOffset;
            if(insertBefore) {
                final PsiComment documentationStartElement = JSGraphQLEndpointDocPsiUtil.getDocumentationStartElement(definition);
                if(documentationStartElement != null) {
                    insertOffset = documentationStartElement.getTextRange().getStartOffset();
                } else {
                    insertOffset = definition.getTextRange().getStartOffset();
                }
            } else {
                insertOffset = definition.getTextRange().getEndOffset();
            }
            document.insertString(insertOffset, definitionText);
            if (caretOffsetAfterInsert.get() != null) {
                // move caret to new position
                PsiDocumentManager.getInstance(element.getProject()).commitDocument(document);
                editor.getCaretModel().moveToOffset(insertOffset + caretOffsetAfterInsert.get());
                if (indent) {
                    AnAction editorLineEnd = ActionManager.getInstance().getAction("EditorLineEnd");
                    if (editorLineEnd != null) {
                        final AnActionEvent actionEvent = AnActionEvent.createFromDataContext(
                                ActionPlaces.UNKNOWN,
                                null,
                                new DataManagerImpl.MyDataContext(editor.getComponent())
                        );
                        editorLineEnd.actionPerformed(actionEvent);
                    }
                }
            }
        }
    }
}
 
Example 18
Source File: CompilerAction.java    From reasonml-idea-plugin with MIT License 4 votes vote down vote up
private static Optional<PsiFile> getActiveFile(@NotNull Project project, @NotNull Editor editor) {
    Document document = editor.getDocument();
    PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    return Optional.ofNullable(psiDocumentManager.getPsiFile(document));
}
 
Example 19
Source File: ShowIntentionsPass.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void getActionsToShow(@Nonnull final Editor hostEditor,
                                     @Nonnull final PsiFile hostFile,
                                     @Nonnull final IntentionsInfo intentions,
                                     int passIdToShowIntentionsFor,
                                     boolean queryIntentionActions) {
  int offset = hostEditor.getCaretModel().getOffset();
  final PsiElement psiElement = hostFile.findElementAt(offset);
  if (psiElement != null) PsiUtilCore.ensureValid(psiElement);

  intentions.setOffset(offset);
  final Project project = hostFile.getProject();

  List<HighlightInfo.IntentionActionDescriptor> fixes = getAvailableFixes(hostEditor, hostFile, passIdToShowIntentionsFor, offset);
  final DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(project);
  final Document hostDocument = hostEditor.getDocument();
  HighlightInfo infoAtCursor = ((DaemonCodeAnalyzerImpl)codeAnalyzer).findHighlightByOffset(hostDocument, offset, true);
  if (infoAtCursor == null) {
    intentions.errorFixesToShow.addAll(fixes);
  }
  else {
    fillIntentionsInfoForHighlightInfo(infoAtCursor, intentions, fixes);
  }

  if (queryIntentionActions) {
    PsiFile injectedFile = InjectedLanguageUtil.findInjectedPsiNoCommit(hostFile, offset);
    for (final IntentionAction action : IntentionManager.getInstance().getAvailableIntentionActions()) {
      Pair<PsiFile, Editor> place =
              ShowIntentionActionsHandler.chooseBetweenHostAndInjected(hostFile, hostEditor, injectedFile, (psiFile, editor) -> ShowIntentionActionsHandler.availableFor(psiFile, editor, action));

      if (place != null) {
        List<IntentionAction> enableDisableIntentionAction = new ArrayList<>();
        enableDisableIntentionAction.add(new EnableDisableIntentionAction(action));
        enableDisableIntentionAction.add(new EditIntentionSettingsAction(action));
        HighlightInfo.IntentionActionDescriptor descriptor = new HighlightInfo.IntentionActionDescriptor(action, enableDisableIntentionAction, null);
        if (!fixes.contains(descriptor)) {
          intentions.intentionsToShow.add(descriptor);
        }
      }
    }

    for (IntentionMenuContributor extension : IntentionMenuContributor.EP_NAME.getExtensionList()) {
      extension.collectActions(hostEditor, hostFile, intentions, passIdToShowIntentionsFor, offset);
    }
  }

  intentions.filterActions(hostFile);
}
 
Example 20
Source File: OnCodeAnalysisFinishedListener.java    From litho with Apache License 2.0 4 votes vote down vote up
@Override
public void daemonFinished() {
  LOG.debug("Daemon finished");
  final AppSettingsState.Model state = AppSettingsState.getInstance(project).getState();
  if (!state.resolveRedSymbols) return;

  // As in com.intellij.codeInsight.daemon.impl.StatusBarUpdater.java
  Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
  if (editor == null) return;

  final Document document = editor.getDocument();
  final VirtualFile vf = FileDocumentManager.getInstance().getFile(document);
  if (vf == null) return;

  final String path = vf.getPath();
  boolean stopProcessing;
  synchronized (analyzedFilesLock) {
    stopProcessing = analyzedFiles.contains(path) || pendingFiles.contains(path);
  }
  if (stopProcessing) return;

  final PsiFile pf = PsiManager.getInstance(project).findFile(vf);
  if (!(pf instanceof PsiJavaFile)) return;

  synchronized (analyzedFilesLock) {
    pendingFiles.add(path);
  }
  final Map<String, String> eventMetadata = new HashMap<>();
  ResolveRedSymbolsAction.resolveRedSymbols(
      (PsiJavaFile) pf,
      vf,
      editor,
      project,
      eventMetadata,
      finished -> {
        synchronized (analyzedFilesLock) {
          pendingFiles.remove(path);
        }
        if (finished) {
          synchronized (analyzedFilesLock) {
            analyzedFiles.add(path);
          }
        }
        eventMetadata.put(EventLogger.KEY_TYPE, "daemon");
        eventMetadata.put(EventLogger.KEY_RESULT, finished ? "success" : "fail");
        LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_RED_SYMBOLS, eventMetadata);
      });
}