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

The following examples show how to use com.intellij.openapi.editor.Editor#getProject() . 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: TooltipActionProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
static TooltipAction calcTooltipAction(@Nonnull final HighlightInfo info, @Nonnull Editor editor) {
  if (!Registry.is("ide.tooltip.show.with.actions")) return null;

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

  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null) return null;

  for (TooltipActionProvider extension : EXTENSION_POINT_NAME.getExtensionList()) {
    TooltipAction action = extension.getTooltipAction(info, editor, file);
    if (action != null) return action;
  }

  return null;
}
 
Example 2
Source File: ActionTracker.java    From consulo with Apache License 2.0 6 votes vote down vote up
ActionTracker(Editor editor, Disposable parentDisposable) {
  myEditor = editor;
  myProject = editor.getProject();
  ActionManager.getInstance().addAnActionListener(new AnActionListener.Adapter() {
    @Override
    public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
      myActionsHappened = true;
    }
  }, parentDisposable);
  myEditor.getDocument().addDocumentListener(new DocumentAdapter() {
    @Override
    public void documentChanged(DocumentEvent e) {
      if (!myIgnoreDocumentChanges) {
        myActionsHappened = true;
      }
    }
  }, parentDisposable);
}
 
Example 3
Source File: MergePanel2.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void initEditorSettings(@Nonnull Editor editor) {
  Project project = editor.getProject();
  DiffMergeSettings settings = project == null ? null : ServiceManager.getService(project, MergeToolSettings.class);
  for (DiffMergeEditorSetting property : DiffMergeEditorSetting.values()) {
    property.apply(editor, settings == null ? property.getDefault() : settings.getPreference(property));
  }
  editor.getSettings().setLineMarkerAreaShown(true);
}
 
Example 4
Source File: ImageOrColorPreviewManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void registerListeners(final Editor editor) {
  if (editor.isOneLineMode()) {
    return;
  }

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

  PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (psiFile == null || psiFile instanceof PsiCompiledElement || !isSupportedFile(psiFile)) {
    return;
  }

  editor.addEditorMouseMotionListener(this);

  KeyListener keyListener = new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
      if (e.getKeyCode() == KeyEvent.VK_SHIFT && !editor.isOneLineMode()) {
        PointerInfo pointerInfo = MouseInfo.getPointerInfo();
        if (pointerInfo != null) {
          Point location = pointerInfo.getLocation();
          SwingUtilities.convertPointFromScreen(location, editor.getContentComponent());
          alarm.cancelAllRequests();
          alarm.addRequest(new PreviewRequest(location, editor, true), 100);
        }
      }
    }
  };
  editor.getContentComponent().addKeyListener(keyListener);

  EDITOR_LISTENER_ADDED.set(editor, keyListener);
}
 
Example 5
Source File: SmartEnterProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void commit(@Nonnull final Editor editor) {
  final Project project = editor.getProject();
  PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());

  //some psi operations may block the document, unblock here
  PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
}
 
Example 6
Source File: SelectAllOccurrencesAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void doExecute(Editor editor, @Nullable Caret c, DataContext dataContext) {
  Caret caret = c == null ? editor.getCaretModel().getPrimaryCaret() : c;

  if (!caret.hasSelection()) {
    TextRange wordSelectionRange = getSelectionRange(editor, caret);
    if (wordSelectionRange != null) {
      setSelection(editor, caret, wordSelectionRange);
    }
  }

  String selectedText = caret.getSelectedText();
  Project project = editor.getProject();
  if (project == null || selectedText == null) {
    return;
  }

  int caretShiftFromSelectionStart = caret.getOffset() - caret.getSelectionStart();
  FindManager findManager = FindManager.getInstance(project);

  FindModel model = new FindModel();
  model.setStringToFind(selectedText);
  model.setCaseSensitive(true);
  model.setWholeWordsOnly(true);

  int searchStartOffset = 0;
  FindResult findResult = findManager.findString(editor.getDocument().getCharsSequence(), searchStartOffset, model);
  while (findResult.isStringFound()) {
    int newCaretOffset = caretShiftFromSelectionStart + findResult.getStartOffset();
    EditorActionUtil.makePositionVisible(editor, newCaretOffset);
    Caret newCaret = editor.getCaretModel().addCaret(editor.offsetToVisualPosition(newCaretOffset));
    if (newCaret != null) {
      setSelection(editor, newCaret, findResult);
    }
    findResult = findManager.findString(editor.getDocument().getCharsSequence(), findResult.getEndOffset(), model);
  }
  editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
 
Example 7
Source File: JSGraphQLQueryContextHighlightVisitor.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Uses a range highlighter to show a range of unused text as dimmed
 */
private static void highlightUnusedRange(Editor editor, TextAttributes unusedTextAttributes, TextRange textRange) {
    final Project project = editor.getProject();
    if (project != null) {
        HighlightManager.getInstance(project).addRangeHighlight(
                editor,
                textRange.getStartOffset(),
                textRange.getEndOffset(),
                unusedTextAttributes, true, true, null);
    }
}
 
Example 8
Source File: TextEditorPsiDataProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiFile getPsiFile(@Nonnull Editor e, @Nonnull VirtualFile file) {
  if (!file.isValid()) {
    return null; // fix for SCR 40329
  }
  final Project project = e.getProject();
  if (project == null) {
    return null;
  }
  PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
  return psiFile != null && psiFile.isValid() ? psiFile : null;
}
 
Example 9
Source File: ListTemplatesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void showLookup(LookupImpl lookup, @Nonnull PsiFile file) {
  Editor editor = lookup.getEditor();
  Project project = editor.getProject();
  lookup.addLookupListener(new MyLookupAdapter(project, editor, file));
  lookup.refreshUi(false, true);
  lookup.showLookup();
}
 
Example 10
Source File: ValueLookupManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void mouseMoved(EditorMouseEvent e) {
  if (e.isConsumed()) {
    return;
  }

  Editor editor = e.getEditor();
  if (editor.getProject() != null && editor.getProject() != myProject) {
    return;
  }

  ValueHintType type = AbstractValueHint.getHintType(e);
  if (e.getArea() != EditorMouseEventArea.EDITING_AREA ||
      DISABLE_VALUE_LOOKUP.get(editor) == Boolean.TRUE ||
      type == null) {
    myAlarm.cancelAllRequests();
    return;
  }

  Point point = e.getMouseEvent().getPoint();
  if (myRequest != null && !myRequest.isKeepHint(editor, point)) {
    hideHint();
  }

  for (DebuggerSupport support : mySupports) {
    QuickEvaluateHandler handler = support.getQuickEvaluateHandler();
    if (handler.isEnabled(myProject)) {
      requestHint(handler, editor, point, type);
      break;
    }
  }
}
 
Example 11
Source File: PostfixInsertHandler.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
public void handleInsert(InsertionContext context, LookupElement item) {
  Editor editor = context.getEditor();
  Project project = editor.getProject();

  if (project != null) {
    EditorModificationUtil.insertStringAtCaret(
        editor, closingTagBeforeCaret + closingTagAfterCaret);
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    EditorModificationUtil.moveCaretRelatively(editor, -closingTagAfterCaret.length());
  }
}
 
Example 12
Source File: DebuggerUIUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void showPopupForEditorLine(@Nonnull JBPopup popup, @Nonnull Editor editor, int line) {
  RelativePoint point = getPositionForPopup(editor, line);
  if (point != null) {
    popup.show(point);
  }
  else {
    Project project = editor.getProject();
    if (project != null) {
      popup.showCenteredInCurrentWindow(project);
    }
    else {
      popup.showInFocusCenter();
    }
  }
}
 
Example 13
Source File: WorkspaceEditHandler.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Opens an editor when needed and gets the Runnable
 *
 * @param edits         The text edits
 * @param uri           The uri of the file
 * @param version       The version of the file
 * @param openedEditors
 * @param curProject
 * @param name
 * @return The runnable containing the edits
 */
private static Runnable manageUnopenedEditor(List<TextEdit> edits, String uri, int version,
                                             List<VirtualFile> openedEditors, Project[] curProject, String name) {
    Project[] projects = ProjectManager.getInstance().getOpenProjects();
    //Infer the project from the uri
    Project project = Stream.of(projects)
            .map(p -> new ImmutablePair<>(FileUtils.VFSToURI(ProjectUtil.guessProjectDir(p)), p))
            .filter(p -> uri.startsWith(p.getLeft())).sorted(Collections.reverseOrder())
            .map(ImmutablePair::getRight).findFirst().orElse(projects[0]);
    VirtualFile file = null;
    try {
        file = LocalFileSystem.getInstance().findFileByIoFile(new File(new URI(FileUtils.sanitizeURI(uri))));
    } catch (URISyntaxException e) {
        LOG.warn(e);
    }
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
    OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file);
    Editor editor = ApplicationUtils
            .computableWriteAction(() -> fileEditorManager.openTextEditor(descriptor, false));
    openedEditors.add(file);
    curProject[0] = editor.getProject();
    Runnable runnable = null;
    EditorEventManager manager = EditorEventManagerBase.forEditor(editor);
    if (manager != null) {
        runnable = manager.getEditsRunnable(version, edits, name, true);
    }
    return runnable;
}
 
Example 14
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
public EditorEventManager(Editor editor, DocumentListener documentListener, EditorMouseListener mouseListener,
                          EditorMouseMotionListener mouseMotionListener, LSPCaretListenerImpl caretListener,
                          RequestManager requestManager, ServerOptions serverOptions, LanguageServerWrapper wrapper) {

    this.editor = editor;
    this.documentListener = documentListener;
    this.mouseListener = mouseListener;
    this.mouseMotionListener = mouseMotionListener;
    this.requestManager = requestManager;
    this.wrapper = wrapper;
    this.caretListener = caretListener;

    this.identifier = new TextDocumentIdentifier(FileUtils.editorToURIString(editor));
    this.changesParams = new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(),
            Collections.singletonList(new TextDocumentContentChangeEvent()));
    this.syncKind = serverOptions.syncKind;

    this.completionTriggers = (serverOptions.completionOptions != null
            && serverOptions.completionOptions.getTriggerCharacters() != null) ?
            serverOptions.completionOptions.getTriggerCharacters() :
            new ArrayList<>();

    this.signatureTriggers = (serverOptions.signatureHelpOptions != null
            && serverOptions.signatureHelpOptions.getTriggerCharacters() != null) ?
            serverOptions.signatureHelpOptions.getTriggerCharacters() :
            new ArrayList<>();

    this.project = editor.getProject();

    EditorEventManagerBase.uriToManager.put(FileUtils.editorToURIString(editor), this);
    EditorEventManagerBase.editorToManager.put(editor, this);
    changesParams.getTextDocument().setUri(identifier.getUri());

    this.currentHint = null;
}
 
Example 15
Source File: CppSupportLoader.java    From CppTools with Apache License 2.0 5 votes vote down vote up
public void projectClosed() {
  EditorFactory.getInstance().removeEditorFactoryListener(myEditorFactoryListener);
  myEditorFactoryListener = null;

  VirtualFileManager.getInstance().removeVirtualFileListener(myFileListener);
  myFileListener = null;

  for(Editor editor:EditorFactory.getInstance().getAllEditors()) {
    if (editor.getProject() == project) {
      removeDocumentListener(editor.getDocument());
    }
  }
  myDocumentListener = null;
}
 
Example 16
Source File: QuoteHandler.java    From bamboo-soy with Apache License 2.0 4 votes vote down vote up
@Override
public Result beforeCharTyped(char charTyped, final Project project, final Editor editor,
    final PsiFile file, final FileType fileType) {
  if (file.getFileType() != SoyFileType.INSTANCE && file.getFileType() != HtmlFileType.INSTANCE) {
    return Result.CONTINUE;
  }

  Document document = editor.getDocument();
  int caretOffset = editor.getCaretModel().getOffset();

  String prevChar = getPreviousChar(document, caretOffset);
  String nextChar = getNextChar(document, caretOffset);

  int lineNumber = document.getLineNumber(caretOffset);
  String textBeforeCaret =
      document.getText(new TextRange(document.getLineStartOffset(lineNumber),
          caretOffset));
  String textAfterCaret =
      document.getText(new TextRange(caretOffset,
          document.getLineEndOffset(lineNumber)));

  Pair<Character, Character> matchingPairReverse = getMatchingPair(charTyped,
      p -> p.getSecond());
  if (matchingPairReverse != null && nextChar.equals(charTyped + "")) {
    boolean pairOfEqualChars = (matchingPairReverse.first == matchingPairReverse.second);

    // Number of opens on the left of the caret.
    int countLeft = computeCount(textBeforeCaret, matchingPairReverse.first,
        matchingPairReverse.second);

    // Number of closes on the right of the caret.
    int countRight = computeCount(textAfterCaret, matchingPairReverse.second,
        matchingPairReverse.first);

    // When the pair is made of equal characters (like quotes) then only trigger if there is
    // a balance of 1-1 around the caret, which means that the quote is already closed and
    // inserting a new quote would create an imbalance.
    if (((!pairOfEqualChars && countLeft <= countRight) || (pairOfEqualChars
        && countLeft == countRight)) && countRight > 0) {
      editor.getCaretModel().moveToOffset(caretOffset + 1);
      return Result.STOP;
    }
  } else {
    Pair<Character, Character> matchingPair = getMatchingPair(charTyped,
        p -> p.getFirst());
    if (matchingPair != null) {
      if ((alwaysCloseCharacters.contains(matchingPair.first) || (allowedPreviousCharacters
          .contains(prevChar)) && allowedNextCharacters.contains(nextChar)
          && !nextChar.equals(matchingPair.second + ""))) {
        document.insertString(editor.getCaretModel().getOffset(), matchingPair.second + "");

        if (editor.getProject() != null) {
          PsiDocumentManager.getInstance(editor.getProject()).commitDocument(document);
        }
      }
    }
  }

  return Result.CONTINUE;
}
 
Example 17
Source File: EditorEventServiceBase.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
EditorEx getIfValidForProject(Editor editor) {
  if (editor.getProject() != project) return null;
  if (editor.isDisposed() || project.isDisposed()) return null;
  if (!(editor instanceof EditorEx)) return null;
  return (EditorEx)editor;
}
 
Example 18
Source File: BaseFoldingHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean isEnabledForCaret(@Nonnull Editor editor, @Nonnull Caret caret, DataContext dataContext) {
  return editor.getProject() != null;
}
 
Example 19
Source File: SortAction.java    From StringManipulation with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("Duplicates")
@Nullable
protected SortSettings getSortSettings(final Editor editor) {
	final SortTypeDialog dialog = new SortTypeDialog(getSortSettings(storeKey), true, editor);
	DialogWrapper dialogWrapper = new DialogWrapper(editor.getProject()) {
		{
			init();
			setTitle("Sort Lines");
		}

		@Nullable
		@Override
		public JComponent getPreferredFocusedComponent() {
			return dialog.insensitive;
		}

		@Nullable
		@Override
		protected String getDimensionServiceKey() {
			return "StringManipulation.SortTypeDialog";
		}

		@Nullable
		@Override
		protected JComponent createCenterPanel() {
			return dialog.contentPane;
		}


		@Override
		protected void doOKAction() {
			super.doOKAction();
		}
	};

	boolean b = dialogWrapper.showAndGet();
	if (!b) {
		return null;
	}
	SortSettings settings = dialog.getSettings();
	PluginPersistentStateComponent.getInstance().setSortSettings(settings);
	return settings;
}
 
Example 20
Source File: SortLinesBySubSelectionAction.java    From StringManipulation with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("Duplicates")
@Nullable
protected SortSettings getSortSettings(final Editor editor) {
	final SortTypeDialog dialog = new SortTypeDialog(PluginPersistentStateComponent.getInstance().getSortSettings(), false, editor) {
		@Override
		protected List<String> sort(Editor editor1, SortSettings settings) {
			List<CaretState> caretsAndSelections = editor1.getCaretModel().getCaretsAndSelections();
			IdeUtils.sort(caretsAndSelections);
			List<SubSelectionSortLine> lines = getLines(editor, getSettings(), caretsAndSelections);

			List<SubSelectionSortLine> sortedLines = settings.getSortType().sortLines(lines, settings.getBaseComparator(), settings.getCollatorLanguageTag());

			List<String> result = new ArrayList<>();
			for (SubSelectionSortLine sortedLine : sortedLines) {
				result.add(sortedLine.line);
			}
			return result;
		}
	};
	DialogWrapper dialogWrapper = new DialogWrapper(editor.getProject()) {
		{
			init();
			setTitle("Sort Lines by Subselection");
		}

		@Nullable
		@Override
		public JComponent getPreferredFocusedComponent() {
			return dialog.insensitive;
		}

		@Nullable
		@Override
		protected String getDimensionServiceKey() {
			return "StringManipulation.SortLinesBySubSelection";
		}

		@Nullable
		@Override
		protected JComponent createCenterPanel() {
			return dialog.contentPane;
		}

		@Override
		protected void doOKAction() {
			super.doOKAction();
		}

	};

	boolean b = dialogWrapper.showAndGet();
	if (!b) {
		return null;
	}
	SortSettings sortSettings = dialog.getSettings().preserveLeadingSpaces(false).preserveTrailingSpecialCharacters(false);
	PluginPersistentStateComponent.getInstance().setSortSettings(sortSettings);
	return sortSettings;
}