com.intellij.injected.editor.EditorWindow Java Examples

The following examples show how to use com.intellij.injected.editor.EditorWindow. 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: DocumentWindowImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public int injectedToHost(int offset) {
  int offsetInLeftFragment = injectedToHost(offset, true, false);
  int offsetInRightFragment = injectedToHost(offset, false, false);
  if (offsetInLeftFragment == offsetInRightFragment) return offsetInLeftFragment;

  // heuristics: return offset closest to the caret
  Editor[] editors = EditorFactory.getInstance().getEditors(getDelegate());
  Editor editor = editors.length == 0 ? null : editors[0];
  if (editor != null) {
    if (editor instanceof EditorWindow) editor = ((EditorWindow)editor).getDelegate();
    int caret = editor.getCaretModel().getOffset();
    return Math.abs(caret - offsetInLeftFragment) < Math.abs(caret - offsetInRightFragment) ? offsetInLeftFragment : offsetInRightFragment;
  }
  return offsetInLeftFragment;
}
 
Example #2
Source File: HighlightManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void addOccurrenceHighlights(@Nonnull Editor editor,
                                    @Nonnull PsiElement[] elements,
                                    @Nonnull TextAttributes attributes,
                                    boolean hideByTextChange,
                                    Collection<RangeHighlighter> outHighlighters) {
  if (elements.length == 0) return;
  int flags = HIDE_BY_ESCAPE;
  if (hideByTextChange) {
    flags |= HIDE_BY_TEXT_CHANGE;
  }

  Color scrollmarkColor = getScrollMarkColor(attributes);
  if (editor instanceof EditorWindow) {
    editor = ((EditorWindow)editor).getDelegate();
  }

  for (PsiElement element : elements) {
    TextRange range = element.getTextRange();
    range = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, range);
    addOccurrenceHighlight(editor, range.getStartOffset(), range.getEndOffset(), attributes, flags, outHighlighters, scrollmarkColor);
  }
}
 
Example #3
Source File: ShowAutoImportPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void showImports() {
  Application application = ApplicationManager.getApplication();
  application.assertIsDispatchThread();
  if (!application.isHeadlessEnvironment() && !myEditor.getContentComponent().hasFocus()) return;
  if (DumbService.isDumb(myProject) || !myFile.isValid()) return;
  if (myEditor.isDisposed() || myEditor instanceof EditorWindow && !((EditorWindow)myEditor).isValid()) return;

  int caretOffset = myEditor.getCaretModel().getOffset();
  importUnambiguousImports(caretOffset);
  List<HighlightInfo> visibleHighlights = getVisibleHighlights(myStartOffset, myEndOffset, myProject, myEditor, hasDirtyTextRange);

  for (int i = visibleHighlights.size() - 1; i >= 0; i--) {
    HighlightInfo info = visibleHighlights.get(i);
    if (info.startOffset <= caretOffset && showAddImportHint(info)) return;
  }

  for (HighlightInfo visibleHighlight : visibleHighlights) {
    if (visibleHighlight.startOffset > caretOffset && showAddImportHint(visibleHighlight)) return;
  }
}
 
Example #4
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Invocation of this method on uncommitted {@code file} can lead to unexpected results, including throwing an exception!
 */
public static Caret getCaretForInjectedLanguageNoCommit(@Nullable Caret caret, @Nullable PsiFile file) {
  if (caret == null || file == null || caret instanceof InjectedCaret) return caret;

  PsiFile injectedFile = findInjectedPsiNoCommit(file, caret.getOffset());
  Editor injectedEditor = getInjectedEditorForInjectedFile(caret.getEditor(), injectedFile);
  if (!(injectedEditor instanceof EditorWindow)) {
    return caret;
  }
  for (Caret injectedCaret : injectedEditor.getCaretModel().getAllCarets()) {
    if (((InjectedCaret)injectedCaret).getDelegate() == caret) {
      return injectedCaret;
    }
  }
  return null;
}
 
Example #5
Source File: TabOutScopesTrackerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void registerEmptyScope(@Nonnull Editor editor, int offset, int tabOutOffset) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  if (editor.isDisposed()) throw new IllegalArgumentException("Editor is already disposed");
  if (tabOutOffset <= offset) throw new IllegalArgumentException("tabOutOffset should be larger than offset");

  if (!CodeInsightSettings.getInstance().TAB_EXITS_BRACKETS_AND_QUOTES) return;

  if (editor instanceof EditorWindow) {
    DocumentWindow documentWindow = ((EditorWindow)editor).getDocument();
    offset = documentWindow.injectedToHost(offset);
    editor = ((EditorWindow)editor).getDelegate();
  }
  if (!(editor instanceof DesktopEditorImpl)) return;

  Tracker tracker = Tracker.forEditor((DesktopEditorImpl)editor, true);
  tracker.registerScope(offset, tabOutOffset - offset);
}
 
Example #6
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int adjustOffsetToInlay(int offset) {
  CharSequence text = myEditor.getDocument().getImmutableCharSequence();
  int hostWhitespaceStart = CharArrayUtil.shiftBackward(text, offset, WHITESPACE) + 1;
  int hostWhitespaceEnd = CharArrayUtil.shiftForward(text, offset, WHITESPACE);
  Editor hostEditor = myEditor;
  if (myEditor instanceof EditorWindow) {
    hostEditor = ((EditorWindow)myEditor).getDelegate();
    hostWhitespaceStart = ((EditorWindow)myEditor).getDocument().injectedToHost(hostWhitespaceStart);
    hostWhitespaceEnd = ((EditorWindow)myEditor).getDocument().injectedToHost(hostWhitespaceEnd);
  }
  List<Inlay> inlays = ParameterHintsPresentationManager.getInstance().getParameterHintsInRange(hostEditor, hostWhitespaceStart, hostWhitespaceEnd);
  for (Inlay inlay : inlays) {
    int inlayOffset = inlay.getOffset();
    if (myEditor instanceof EditorWindow) {
      if (((EditorWindow)myEditor).getDocument().getHostRange(inlayOffset) == null) continue;
      inlayOffset = ((EditorWindow)myEditor).getDocument().hostToInjected(inlayOffset);
    }
    return inlayOffset;
  }
  return offset;
}
 
Example #7
Source File: TabOutScopesTrackerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static int checkOrRemoveScopeEndingAt(@Nonnull Editor editor, int offset, boolean removeScope) {
  ApplicationManager.getApplication().assertIsDispatchThread();

  if (!CodeInsightSettings.getInstance().TAB_EXITS_BRACKETS_AND_QUOTES) return 0;

  if (editor instanceof EditorWindow) {
    DocumentWindow documentWindow = ((EditorWindow)editor).getDocument();
    offset = documentWindow.injectedToHost(offset);
    editor = ((EditorWindow)editor).getDelegate();
  }
  if (!(editor instanceof DesktopEditorImpl)) return 0;

  Tracker tracker = Tracker.forEditor((DesktopEditorImpl)editor, false);
  if (tracker == null) return 0;

  return tracker.getCaretShiftForScopeEndingAt(offset, removeScope);
}
 
Example #8
Source File: EditorUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Performs inlay-aware conversion of offset to visual position in editor. If there are inlays at given position, their
 * 'related to preceding text' property will be taken account to determine resulting position. Specifically, resulting position will
 * match caret's visual position if it's moved to the given offset using {@link Caret#moveToOffset(int)} call.
 * <p>
 * NOTE: if editor is an {@link EditorWindow}, corresponding offset is treated as an offset in injected editor, but returned position
 * is always related to host editor.
 *
 * @see Inlay#isRelatedToPrecedingText()
 */
@Nonnull
public static VisualPosition inlayAwareOffsetToVisualPosition(@Nonnull Editor editor, int offset) {
  LogicalPosition logicalPosition = editor.offsetToLogicalPosition(offset);
  if (editor instanceof EditorWindow) {
    logicalPosition = ((EditorWindow)editor).injectedToHost(logicalPosition);
    editor = ((EditorWindow)editor).getDelegate();
  }
  VisualPosition pos = editor.logicalToVisualPosition(logicalPosition);
  Inlay inlay;
  while ((inlay = editor.getInlayModel().getInlineElementAt(pos)) != null) {
    if (inlay.isRelatedToPrecedingText()) break;
    pos = new VisualPosition(pos.line, pos.column + 1);
  }
  return pos;
}
 
Example #9
Source File: EditorUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void disposeWithEditor(@Nonnull Editor editor, @Nonnull Disposable disposable) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  if (Disposer.isDisposed(disposable)) return;
  if (editor.isDisposed()) {
    Disposer.dispose(disposable);
    return;
  }
  // for injected editors disposal will happen only when host editor is disposed,
  // but this seems to be the best we can do (there are no notifications on disposal of injected editor)
  Editor hostEditor = editor instanceof EditorWindow ? ((EditorWindow)editor).getDelegate() : editor;
  EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() {
    @Override
    public void editorReleased(@Nonnull EditorFactoryEvent event) {
      if (event.getEditor() == hostEditor) {
        Disposer.dispose(disposable);
      }
    }
  }, disposable);
}
 
Example #10
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 #11
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Editor getInjectedEditorForInjectedFile(@Nonnull Editor hostEditor, @Nonnull Caret hostCaret, @Nullable final PsiFile injectedFile) {
  if (injectedFile == null || hostEditor instanceof EditorWindow || hostEditor.isDisposed()) return hostEditor;
  Project project = hostEditor.getProject();
  if (project == null) project = injectedFile.getProject();
  Document document = PsiDocumentManager.getInstance(project).getDocument(injectedFile);
  if (!(document instanceof DocumentWindowImpl)) return hostEditor;
  DocumentWindowImpl documentWindow = (DocumentWindowImpl)document;
  if (hostCaret.hasSelection()) {
    int selstart = hostCaret.getSelectionStart();
    if (selstart != -1) {
      int selend = Math.max(selstart, hostCaret.getSelectionEnd());
      if (!documentWindow.containsRange(selstart, selend)) {
        // selection spreads out the injected editor range
        return hostEditor;
      }
    }
  }
  if (!documentWindow.isValid()) {
    return hostEditor; // since the moment we got hold of injectedFile and this moment call, document may have been dirtied
  }
  return EditorWindowImpl.create(documentWindow, (DesktopEditorImpl)hostEditor, injectedFile);
}
 
Example #12
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static Editor openEditorFor(@Nonnull PsiFile file, @Nonnull Project project) {
  Document document = PsiDocumentManager.getInstance(project).getDocument(file);
  // may return editor injected in current selection in the host editor, not for the file passed as argument
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) {
    return null;
  }
  if (virtualFile instanceof VirtualFileWindow) {
    virtualFile = ((VirtualFileWindow)virtualFile).getDelegate();
  }
  Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, virtualFile, -1), false);
  if (editor == null || editor instanceof EditorWindow || editor.isDisposed()) return editor;
  if (document instanceof DocumentWindowImpl) {
    return EditorWindowImpl.create((DocumentWindowImpl)document, (DesktopEditorImpl)editor, file);
  }
  return editor;
}
 
Example #13
Source File: LookupUi.java    From consulo with Apache License 2.0 6 votes vote down vote up
void refreshUi(boolean selectionVisible, boolean itemsChanged, boolean reused, boolean onExplicitAction) {
  Editor editor = myLookup.getTopLevelEditor();
  if (editor.getComponent().getRootPane() == null || editor instanceof EditorWindow && !((EditorWindow)editor).isValid()) {
    return;
  }

  if (myLookup.myResizePending || itemsChanged) {
    myMaximumHeight = Integer.MAX_VALUE;
  }
  Rectangle rectangle = calculatePosition();
  myMaximumHeight = rectangle.height;

  if (myLookup.myResizePending || itemsChanged) {
    myLookup.myResizePending = false;
    myLookup.pack();
  }
  HintManagerImpl.updateLocation(myLookup, editor, rectangle.getLocation());

  if (reused || selectionVisible || onExplicitAction) {
    myLookup.ensureSelectionVisible(false);
  }
}
 
Example #14
Source File: QueryToXMLConverter.java    From dbunit-extractor with MIT License 6 votes vote down vote up
@Override
public boolean isAvailable(@NotNull final Project project,
                           final Editor editor,
                           @NotNull final PsiElement psiElement) {
    final boolean isDataSetFile;
    if (editor instanceof EditorWindow) {
        isDataSetFile = ((EditorWindow) editor).getDelegate()
                                               .getDocument()
                                               .getText()
                                               .startsWith("<dataset>");
    } else {
        isDataSetFile = editor.getDocument().getText().startsWith("<dataset>");
    }
    SmartPsiElementPointer<SqlSelectStatement> pointer = getNearestPointer(project, psiElement);
    final String selectedText = editor.getSelectionModel().getSelectedText();
    final boolean hasSelectedQuery = editor.getSelectionModel().hasSelection() && selectedText.trim().toUpperCase().startsWith("SELECT");
    return isDataSetFile && (hasSelectedQuery || pointer != null);
}
 
Example #15
Source File: TextEditorPsiDataProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Caret getInjectedCaret(@Nonnull Editor editor, @Nonnull Caret hostCaret) {
  if (!(editor instanceof EditorWindow) || hostCaret instanceof InjectedCaret) {
    return hostCaret;
  }
  for (Caret caret : editor.getCaretModel().getAllCarets()) {
    if (((InjectedCaret)caret).getDelegate() == hostCaret) {
      return caret;
    }
  }
  throw new IllegalArgumentException("Cannot find injected caret corresponding to " + hostCaret);
}
 
Example #16
Source File: HighlightUsagesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void clearHighlights(Editor editor,
                                    HighlightManager highlightManager,
                                    List<TextRange> rangesToHighlight,
                                    TextAttributes attributes) {
  if (editor instanceof EditorWindow) editor = ((EditorWindow)editor).getDelegate();
  RangeHighlighter[] highlighters = ((HighlightManagerImpl)highlightManager).getHighlighters(editor);
  Arrays.sort(highlighters, (o1, o2) -> o1.getStartOffset() - o2.getStartOffset());
  Collections.sort(rangesToHighlight, (o1, o2) -> o1.getStartOffset() - o2.getStartOffset());
  int i = 0;
  int j = 0;
  while (i < highlighters.length && j < rangesToHighlight.size()) {
    RangeHighlighter highlighter = highlighters[i];
    TextRange highlighterRange = TextRange.create(highlighter);
    TextRange refRange = rangesToHighlight.get(j);
    if (refRange.equals(highlighterRange) && attributes.equals(highlighter.getTextAttributes()) &&
        highlighter.getLayer() == HighlighterLayer.SELECTION - 1) {
      highlightManager.removeSegmentHighlighter(editor, highlighter);
      i++;
    }
    else if (refRange.getStartOffset() > highlighterRange.getEndOffset()) {
      i++;
    }
    else if (refRange.getEndOffset() < highlighterRange.getStartOffset()) {
      j++;
    }
    else {
      i++;
      j++;
    }
  }
}
 
Example #17
Source File: HighlightManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public Map<RangeHighlighter, HighlightInfo> getHighlightInfoMap(@Nonnull Editor editor, boolean toCreate) {
  if (editor instanceof EditorWindow) return getHighlightInfoMap(((EditorWindow)editor).getDelegate(), toCreate);
  Map<RangeHighlighter, HighlightInfo> map = editor.getUserData(HIGHLIGHT_INFO_MAP_KEY);
  if (map == null && toCreate) {
    map = ((UserDataHolderEx)editor).putUserDataIfAbsent(HIGHLIGHT_INFO_MAP_KEY, new HashMap<RangeHighlighter, HighlightInfo>());
  }
  return map;
}
 
Example #18
Source File: HighlightManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private RangeHighlighter addSegmentHighlighter(@Nonnull Editor editor, int startOffset, int endOffset, TextAttributes attributes, @HideFlags int flags) {
  RangeHighlighter highlighter = editor.getMarkupModel()
    .addRangeHighlighter(startOffset, endOffset, HighlighterLayer.SELECTION - 1, attributes, HighlighterTargetArea.EXACT_RANGE);
  HighlightInfo info = new HighlightInfo(editor instanceof EditorWindow ? ((EditorWindow)editor).getDelegate() : editor, flags);
  Map<RangeHighlighter, HighlightInfo> map = getHighlightInfoMap(editor, true);
  map.put(highlighter, info);
  return highlighter;
}
 
Example #19
Source File: BraceHighlightingHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private List<RangeHighlighter> getHighlightersList() {
  // braces are highlighted across the whole editor, not in each injected editor separately
  Editor editor = myEditor instanceof EditorWindow ? ((EditorWindow)myEditor).getDelegate() : myEditor;
  List<RangeHighlighter> highlighters = editor.getUserData(BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY);
  if (highlighters == null) {
    highlighters = new ArrayList<>();
    editor.putUserData(BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY, highlighters);
  }
  return highlighters;
}
 
Example #20
Source File: BackspaceHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isOffsetInsideInjected(Editor injectedEditor, int injectedOffset) {
  if (injectedOffset == 0 || injectedOffset >= injectedEditor.getDocument().getTextLength()) {
    return false;
  }
  PsiFile injectedFile = ((EditorWindow)injectedEditor).getInjectedFile();
  InjectedLanguageManager ilm = InjectedLanguageManager.getInstance(injectedFile.getProject());
  TextRange rangeToEdit = new TextRange(injectedOffset - 1, injectedOffset+1);
  List<TextRange> editables = ilm.intersectWithAllEditableFragments(injectedFile, rangeToEdit);

  return editables.size() == 1 && editables.get(0).equals(rangeToEdit);
}
 
Example #21
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 #22
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean availableFor(@Nonnull PsiFile psiFile, @Nonnull Editor editor, @Nonnull IntentionAction action) {
  if (!psiFile.isValid()) return false;

  try {
    Project project = psiFile.getProject();
    action = IntentionActionDelegate.unwrap(action);
    if (action instanceof SuppressIntentionActionFromFix) {
      final ThreeState shouldBeAppliedToInjectionHost = ((SuppressIntentionActionFromFix)action).isShouldBeAppliedToInjectionHost();
      if (editor instanceof EditorWindow && shouldBeAppliedToInjectionHost == ThreeState.YES) {
        return false;
      }
      if (!(editor instanceof EditorWindow) && shouldBeAppliedToInjectionHost == ThreeState.NO) {
        return false;
      }
    }

    if (action instanceof PsiElementBaseIntentionAction) {
      PsiElementBaseIntentionAction psiAction = (PsiElementBaseIntentionAction)action;
      if (!psiAction.checkFile(psiFile)) {
        return false;
      }
      PsiElement leaf = psiFile.findElementAt(editor.getCaretModel().getOffset());
      if (leaf == null || !psiAction.isAvailable(project, editor, leaf)) {
        return false;
      }
    }
    else if (!action.isAvailable(project, editor, psiFile)) {
      return false;
    }
  }
  catch (IndexNotReadyException e) {
    return false;
  }
  return true;
}
 
Example #23
Source File: SelectionQuotingTypedHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Result beforeCharTyped(final char charTyped, final Project project, final Editor editor, final PsiFile file, final FileType fileType) {
  // TODO[oleg] remove this hack when API changes
  if (myReplacedTextRange != null) {
    if (myReplacedTextRange.getEndOffset() <= editor.getDocument().getTextLength()) {
      if (myRestoreStickySelection && editor instanceof EditorEx) {
        EditorEx editorEx = (EditorEx)editor;
        CaretModel caretModel = editorEx.getCaretModel();
        caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getStartOffset() : myReplacedTextRange.getEndOffset());
        editorEx.setStickySelection(true);
        caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
      }
      else {
        if (myLtrSelection || editor instanceof EditorWindow) {
          editor.getSelectionModel().setSelection(myReplacedTextRange.getStartOffset(), myReplacedTextRange.getEndOffset());
        }
        else {
          editor.getSelectionModel().setSelection(myReplacedTextRange.getEndOffset(), myReplacedTextRange.getStartOffset());
        }
        if (Registry.is("editor.smarterSelectionQuoting")) {
          editor.getCaretModel().moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
        }
      }
    }
    myReplacedTextRange = null;
    return Result.STOP;
  }
  return Result.CONTINUE;
}
 
Example #24
Source File: SelectWordHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(@Nonnull Editor editor, DataContext dataContext) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("enter: execute(editor='" + editor + "')");
  }
  Project project = DataManager.getInstance().getDataContext(editor.getComponent()).getData(CommonDataKeys.PROJECT);
  if (project == null) {
    if (myOriginalHandler != null) {
      myOriginalHandler.execute(editor, dataContext);
    }
    return;
  }
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  TextRange range = selectWord(editor, project);
  if (editor instanceof EditorWindow) {
    if (range == null || !isInsideEditableInjection((EditorWindow)editor, range, project) || TextRange.from(0, editor.getDocument().getTextLength()).equals(
            new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd()))) {
      editor = ((EditorWindow)editor).getDelegate();
      range = selectWord(editor, project);
    }
  }
  if (range == null) {
    if (myOriginalHandler != null) {
      myOriginalHandler.execute(editor, dataContext);
    }
  }
  else {
    editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
  }
}
 
Example #25
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void invoke(@Nonnull final Project project, @Nonnull Editor editor, @Nonnull PsiFile file, boolean showFeedbackOnEmptyMenu) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  if (editor instanceof EditorWindow) {
    editor = ((EditorWindow)editor).getDelegate();
    file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
  }

  final LookupEx lookup = LookupManager.getActiveLookup(editor);
  if (lookup != null) {
    lookup.showElementActions(null);
    return;
  }

  final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project);
  letAutoImportComplete(editor, file, codeAnalyzer);

  ShowIntentionsPass.IntentionsInfo intentions = ShowIntentionsPass.getActionsToShow(editor, file, true);
  IntentionsUI.getInstance(project).hide();

  if (HintManagerImpl.getInstanceImpl().performCurrentQuestionAction()) return;

  //intentions check isWritable before modification: if (!file.isWritable()) return;

  TemplateState state = TemplateManagerImpl.getTemplateState(editor);
  if (state != null && !state.isFinished()) {
    return;
  }

  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  Editor finalEditor = editor;
  PsiFile finalFile = file;
  showIntentionHint(project, finalEditor, finalFile, intentions, showFeedbackOnEmptyMenu);
}
 
Example #26
Source File: SelectWordHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isInsideEditableInjection(EditorWindow editor, TextRange range, Project project) {
  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null) return true;
  List<TextRange> editables = InjectedLanguageManager.getInstance(project).intersectWithAllEditableFragments(file, range);

  return editables.size() == 1 && range.equals(editables.get(0));
}
 
Example #27
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public PsiElement getPsiElement() {
  PsiFile file = getPsiFile();
  if (file == null) return null;

  int offset = getLookupStart();
  Editor editor = getEditor();
  if (editor instanceof EditorWindow) {
    offset = editor.logicalPositionToOffset(((EditorWindow)editor).hostToInjected(myEditor.offsetToLogicalPosition(offset)));
  }
  if (offset > 0) return file.findElementAt(offset - 1);

  return file.findElementAt(0);
}
 
Example #28
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void showHint(boolean requestFocus, boolean singleParameterInfo) {
  if (myHint.isVisible()) {
    JComponent myHintComponent = myHint.getComponent();
    myHintComponent.removeAll();
    hideHint();
    myHint = createHint();
  }

  mySingleParameterInfo = singleParameterInfo && myKeepOnHintHidden;

  int caretOffset = myEditor.getCaretModel().getOffset();
  Pair<Point, Short> pos = myProvider.getBestPointPosition(myHint, myComponent.getParameterOwner(), caretOffset, null, HintManager.ABOVE);
  HintHint hintHint = HintManagerImpl.createHintHint(myEditor, pos.getFirst(), myHint, pos.getSecond());
  hintHint.setExplicitClose(true);
  hintHint.setRequestFocus(requestFocus);
  hintHint.setShowImmediately(true);
  hintHint.setBorderColor(ParameterInfoComponent.BORDER_COLOR);
  hintHint.setBorderInsets(JBUI.insets(4, 1, 4, 1));
  hintHint.setComponentBorder(JBUI.Borders.empty());

  int flags = HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING;
  if (!singleParameterInfo && myKeepOnHintHidden) flags |= HintManager.HIDE_BY_TEXT_CHANGE;

  Editor editorToShow = myEditor instanceof EditorWindow ? ((EditorWindow)myEditor).getDelegate() : myEditor;

  //update presentation of descriptors synchronously
  myComponent.update(mySingleParameterInfo);

  // is case of injection we need to calculate position for EditorWindow
  // also we need to show the hint in the main editor because of intention bulb
  HintManagerImpl.getInstanceImpl().showEditorHint(myHint, editorToShow, pos.getFirst(), flags, 0, false, hintHint);

  updateComponent();
}
 
Example #29
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 #30
Source File: HaxeIntroduceHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
protected void performInplaceIntroduce(HaxeIntroduceOperation operation) {
  final PsiElement statement = performRefactoring(operation);
  final HaxeComponent target = statement instanceof HaxeComponent ? (HaxeComponent)statement : PsiTreeUtil.findChildOfType(statement, HaxeComponent.class);
  if (target == null) {
    return;
  }

  final LinkedHashSet<String> names = new LinkedHashSet<>();
  if (operation.getName() != null && !operation.isNameSuggested()) {
    names.add(operation.getName());
  } else {
    names.addAll(operation.getSuggestedNames());
  }

  final List<PsiElement> occurrences = operation.getOccurrences();
  final PsiElement occurrence = HaxeRefactoringUtil.findOccurrenceUnderCaret(occurrences, operation.getEditor());
  final PsiElement elementForCaret = occurrence != null ? occurrence : target;

  // The editor can get swapped if the initial element that we are moving was in an embedded file
  // (for instance, when the caret is in a regular expression, thus a dummy REGEXP_FILE).  In this
  // case, when we move the parent element, the operation's file and editor are the parent, not the
  // embedded file. If we continue the renaming process in the original embedded editor, then elements
  // are not found in it, and the process aborts.
  if (elementForCaret.getContainingFile() != operation.getFile() && operation.getEditor() instanceof EditorWindow) {
    EditorWindow editorWindow = ((EditorWindow)operation.getEditor());
    Editor parentEditor = editorWindow.getDelegate();

    operation.updateEditor(parentEditor);
    operation.updateFile(elementForCaret.getContainingFile());
  }

  operation.getEditor().getCaretModel().moveToOffset(elementForCaret.getTextRange().getStartOffset());
  final InplaceVariableIntroducer<PsiElement> introducer =
    new HaxeInplaceVariableIntroducer(target.getComponentName(), operation, occurrences);
  introducer.performInplaceRefactoring(names);
}