com.intellij.injected.editor.DocumentWindow Java Examples

The following examples show how to use com.intellij.injected.editor.DocumentWindow. 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: TodoFileNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static TodoItem[] findAllTodos(final PsiFile psiFile, final PsiTodoSearchHelper helper) {
  final List<TodoItem> todoItems = new ArrayList<>(Arrays.asList(helper.findTodoItems(psiFile)));

  psiFile.accept(new PsiRecursiveElementWalkingVisitor() {
    @Override
    public void visitElement(PsiElement element) {
      if (element instanceof PsiLanguageInjectionHost) {
        InjectedLanguageManager.getInstance(psiFile.getProject()).enumerate(element, (injectedPsi, places) -> {
          if (places.size() == 1) {
            Document document = PsiDocumentManager.getInstance(injectedPsi.getProject()).getCachedDocument(injectedPsi);
            if (!(document instanceof DocumentWindow)) return;
            for (TodoItem item : helper.findTodoItems(injectedPsi)) {
              TextRange rangeInHost = ((DocumentWindow)document).injectedToHost(item.getTextRange());
              List<TextRange> additionalRanges = ContainerUtil.map(item.getAdditionalTextRanges(), ((DocumentWindow)document)::injectedToHost);
              TodoItemImpl hostItem = new TodoItemImpl(psiFile, rangeInHost.getStartOffset(), rangeInHost.getEndOffset(), item.getPattern(), additionalRanges);
              todoItems.add(hostItem);
            }
          }
        });
      }
      super.visitElement(element);
    }
  });
  return todoItems.toArray(new TodoItem[0]);
}
 
Example #2
Source File: TypedHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Editor injectedEditorIfCharTypedIsSignificant(final int charTyped, @Nonnull Editor editor, @Nonnull PsiFile oldFile) {
  int offset = editor.getCaretModel().getOffset();
  // even for uncommitted document try to retrieve injected fragment that has been there recently
  // we are assuming here that when user is (even furiously) typing, injected language would not change
  // and thus we can use its lexer to insert closing braces etc
  List<DocumentWindow> injected = InjectedLanguageManager.getInstance(oldFile.getProject()).getCachedInjectedDocumentsInRange(oldFile, ProperTextRange.create(offset, offset));
  for (DocumentWindow documentWindow : injected) {
    if (documentWindow.isValid() && documentWindow.containsRange(offset, offset)) {
      PsiFile injectedFile = PsiDocumentManager.getInstance(oldFile.getProject()).getPsiFile(documentWindow);
      if (injectedFile != null) {
        Editor injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injectedFile);
        // IDEA-52375/WEB-9105 fix: last quote in editable fragment should be handled by outer language quote handler
        TextRange hostRange = documentWindow.getHostRange(offset);
        CharSequence sequence = editor.getDocument().getCharsSequence();
        if (sequence.length() > offset && charTyped != Character.codePointAt(sequence, offset) || hostRange != null && hostRange.contains(offset)) {
          return injectedEditor;
        }
      }
    }
  }

  return editor;
}
 
Example #3
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 #4
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 #5
Source File: LookupImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static int insertLookupInDocumentWindowIfNeeded(Project project, Editor editor, int caretOffset, int prefix, String lookupString) {
  DocumentWindow document = getInjectedDocument(project, editor, caretOffset);
  if (document == null) return insertLookupInDocument(caretOffset, editor.getDocument(), prefix, lookupString);
  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
  int offset = document.hostToInjected(caretOffset);
  int lookupStart = Math.min(offset, Math.max(offset - prefix, 0));
  int diff = -1;
  if (file != null) {
    List<TextRange> ranges = InjectedLanguageManager.getInstance(project).intersectWithAllEditableFragments(file, TextRange.create(lookupStart, offset));
    if (!ranges.isEmpty()) {
      diff = ranges.get(0).getStartOffset() - lookupStart;
      if (ranges.size() == 1 && diff == 0) diff = -1;
    }
  }
  if (diff == -1) return insertLookupInDocument(caretOffset, editor.getDocument(), prefix, lookupString);
  return document.injectedToHost(insertLookupInDocument(offset, document, prefix - diff, diff == 0 ? lookupString : lookupString.substring(diff)));
}
 
Example #6
Source File: CompletionInitializationUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
static OffsetsInFile toInjectedIfAny(PsiFile originalFile, OffsetsInFile hostCopyOffsets) {
  CompletionAssertions.assertHostInfo(hostCopyOffsets.getFile(), hostCopyOffsets.getOffsets());

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

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

  return hostCopyOffsets;
}
 
Example #7
Source File: PsiDocumentManagerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public PsiFile getPsiFile(@Nonnull Document document) {
  if (document instanceof DocumentWindow && !((DocumentWindow)document).isValid()) {
    return null;
  }

  PsiFile psiFile = getCachedPsiFile(document);
  if (psiFile != null) {
    return ensureValidFile(psiFile, "Cached PSI");
  }

  final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
  if (virtualFile == null || !virtualFile.isValid()) return null;

  psiFile = getPsiFile(virtualFile);
  if (psiFile == null) return null;

  fireFileCreated(document, psiFile);

  return psiFile;
}
 
Example #8
Source File: DocumentWindowImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean areRangesEqual(@Nonnull DocumentWindow other) {
  DocumentWindowImpl window = (DocumentWindowImpl)other;
  Place shreds = getShreds();
  Place otherShreds = window.getShreds();
  if (shreds.size() != otherShreds.size()) return false;
  for (int i = 0; i < shreds.size(); i++) {
    PsiLanguageInjectionHost.Shred shred = shreds.get(i);
    PsiLanguageInjectionHost.Shred otherShred = otherShreds.get(i);
    if (!shred.getPrefix().equals(otherShred.getPrefix())) return false;
    if (!shred.getSuffix().equals(otherShred.getSuffix())) return false;

    Segment hostRange = shred.getHostRangeMarker();
    Segment otherRange = otherShred.getHostRangeMarker();
    if (hostRange == null || otherRange == null || !TextRange.areSegmentsEqual(hostRange, otherRange)) return false;
  }
  return true;
}
 
Example #9
Source File: InjectedLanguageManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public List<TextRange> getNonEditableFragments(@Nonnull DocumentWindow window) {
  List<TextRange> result = new ArrayList<>();
  int offset = 0;
  for (PsiLanguageInjectionHost.Shred shred : ((DocumentWindowImpl)window).getShreds()) {
    Segment hostRange = shred.getHostRangeMarker();
    if (hostRange == null) continue;

    offset = appendRange(result, offset, shred.getPrefix().length());
    offset += hostRange.getEndOffset() - hostRange.getStartOffset();
    offset = appendRange(result, offset, shred.getSuffix().length());
  }

  return result;
}
 
Example #10
Source File: EditorFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Editor createEditor(@Nonnull Document document, boolean isViewer, Project project, @Nonnull EditorKind kind) {
  Document hostDocument = document instanceof DocumentWindow ? ((DocumentWindow)document).getDelegate() : document;
  DesktopEditorImpl editor = new DesktopEditorImpl(hostDocument, isViewer, project, kind);
  myEditors.add(editor);
  myEditorEventMulticaster.registerEditor(editor);

  EditorFactoryEvent event = new EditorFactoryEvent(this, editor);
  myEditorFactoryEventDispatcher.getMulticaster().editorCreated(event);
  EP.forEachExtensionSafe(it -> it.editorCreated(event));

  if (LOG.isDebugEnabled()) {
    LOG.debug("number of Editors after create: " + myEditors.size());
  }

  return editor;
}
 
Example #11
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
static void clearCaches(@Nonnull PsiFile injected, @Nonnull DocumentWindowImpl documentWindow) {
  VirtualFileWindowImpl virtualFile = (VirtualFileWindowImpl)injected.getVirtualFile();
  PsiManagerEx psiManagerEx = (PsiManagerEx)injected.getManager();
  if (psiManagerEx.getProject().isDisposed()) return;

  DebugUtil.performPsiModification("injected clearCaches", () -> psiManagerEx.getFileManager().setViewProvider(virtualFile, null));

  VirtualFile delegate = virtualFile.getDelegate();
  if (!delegate.isValid()) return;

  FileViewProvider viewProvider = psiManagerEx.getFileManager().findCachedViewProvider(delegate);
  if (viewProvider == null) return;

  for (PsiFile hostFile : ((AbstractFileViewProvider)viewProvider).getCachedPsiFiles()) {
    // modification of cachedInjectedDocuments must be under InjectedLanguageManagerImpl.ourInjectionPsiLock
    synchronized (InjectedLanguageManagerImpl.ourInjectionPsiLock) {
      List<DocumentWindow> cachedInjectedDocuments = getCachedInjectedDocuments(hostFile);
      for (int i = cachedInjectedDocuments.size() - 1; i >= 0; i--) {
        DocumentWindow cachedInjectedDocument = cachedInjectedDocuments.get(i);
        if (cachedInjectedDocument == documentWindow) {
          cachedInjectedDocuments.remove(i);
        }
      }
    }
  }
}
 
Example #12
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static BooleanRunnable reparse(@Nonnull PsiFile injectedPsiFile,
                                      @Nonnull DocumentWindow injectedDocument,
                                      @Nonnull PsiFile hostPsiFile,
                                      @Nonnull Document hostDocument,
                                      @Nonnull FileViewProvider hostViewProvider,
                                      @Nonnull ProgressIndicator indicator,
                                      @Nonnull ASTNode oldRoot,
                                      @Nonnull ASTNode newRoot,
                                      @Nonnull PsiDocumentManagerBase documentManager) {
  LanguageVersion languageVersion = injectedPsiFile.getLanguageVersion();
  InjectedFileViewProvider provider = (InjectedFileViewProvider)injectedPsiFile.getViewProvider();
  VirtualFile oldInjectedVFile = provider.getVirtualFile();
  VirtualFile hostVirtualFile = hostViewProvider.getVirtualFile();
  BooleanRunnable runnable = InjectionRegistrarImpl
          .reparse(languageVersion, (DocumentWindowImpl)injectedDocument, injectedPsiFile, (VirtualFileWindow)oldInjectedVFile, hostVirtualFile, hostPsiFile, (DocumentEx)hostDocument, indicator, oldRoot,
                   newRoot, documentManager);
  if (runnable == null) {
    EditorWindowImpl.disposeEditorFor(injectedDocument);
  }
  return runnable;
}
 
Example #13
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static DocumentWindow getDocumentWindow(@Nonnull PsiElement element) {
  PsiFile file = element.getContainingFile();
  if (file == null) return null;
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile instanceof VirtualFileWindow) return ((VirtualFileWindow)virtualFile).getDocumentWindow();
  return null;
}
 
Example #14
Source File: EditorActionManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void setReadonlyFragmentModificationHandler(@Nonnull final Document document, final ReadonlyFragmentModificationHandler handler) {
  final Document doc = document instanceof DocumentWindow ? ((DocumentWindow)document).getDelegate() : document;
  if (doc instanceof DocumentImpl) {
    ((DocumentImpl)document).setReadonlyFragmentModificationHandler(handler);
  }
}
 
Example #15
Source File: AbstractFileViewProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void checkLengthConsistency() {
  Document document = getCachedDocument();
  if (document instanceof DocumentWindow) {
    return;
  }
  if (document != null && ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(myManager.getProject())).getSynchronizer().isInSynchronization(document)) {
    return;
  }

  List<FileElement> knownTreeRoots = getKnownTreeRoots();
  if (knownTreeRoots.isEmpty()) return;

  int fileLength = myContent.getTextLength();
  for (FileElement fileElement : knownTreeRoots) {
    int nodeLength = fileElement.getTextLength();
    if (!isDocumentConsistentWithPsi(fileLength, fileElement, nodeLength)) {
      PsiUtilCore.ensureValid(fileElement.getPsi());
      List<Attachment> attachments = ContainerUtil
              .newArrayList(new Attachment(myVirtualFile.getName(), myContent.getText().toString()), new Attachment(myVirtualFile.getNameWithoutExtension() + ".tree.txt", fileElement.getText()));
      if (document != null) {
        attachments.add(new Attachment(myVirtualFile.getNameWithoutExtension() + ".document.txt", document.getText()));
      }
      // exceptions here should be assigned to peter
      LOG.error("Inconsistent " + fileElement.getElementType() + " tree in " + this + "; nodeLength=" + nodeLength + "; fileLength=" + fileLength, attachments.toArray(Attachment.EMPTY_ARRAY));
    }
  }
}
 
Example #16
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Editor getEditor() {
  DocumentWindow documentWindow = getInjectedDocument(myProject, myEditor, myEditor.getCaretModel().getOffset());
  if (documentWindow != null) {
    PsiFile injectedFile = PsiDocumentManager.getInstance(myProject).getPsiFile(documentWindow);
    return InjectedLanguageUtil.getInjectedEditorForInjectedFile(myEditor, injectedFile);
  }
  return myEditor;
}
 
Example #17
Source File: PsiDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
List<BooleanRunnable> reparseChangedInjectedFragments(@Nonnull Document hostDocument,
                                                      @Nonnull PsiFile hostPsiFile,
                                                      @Nonnull TextRange hostChangedRange,
                                                      @Nonnull ProgressIndicator indicator,
                                                      @Nonnull ASTNode oldRoot,
                                                      @Nonnull ASTNode newRoot) {
  List<DocumentWindow> changedInjected = InjectedLanguageManager.getInstance(myProject).getCachedInjectedDocumentsInRange(hostPsiFile, hostChangedRange);
  if (changedInjected.isEmpty()) return Collections.emptyList();
  FileViewProvider hostViewProvider = hostPsiFile.getViewProvider();
  List<DocumentWindow> fromLast = new ArrayList<>(changedInjected);
  // make sure modifications do not ruin all document offsets after
  fromLast.sort(Collections.reverseOrder(Comparator.comparingInt(doc -> ArrayUtil.getLastElement(doc.getHostRanges()).getEndOffset())));
  List<BooleanRunnable> result = new ArrayList<>(changedInjected.size());
  for (DocumentWindow document : fromLast) {
    Segment[] ranges = document.getHostRanges();
    if (ranges.length != 0) {
      // host document change has left something valid in this document window place. Try to reparse.
      PsiFile injectedPsiFile = getCachedPsiFile(document);
      if (injectedPsiFile == null || !injectedPsiFile.isValid()) continue;

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

  return result;
}
 
Example #18
Source File: PsiDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void doPostponedOperationsAndUnblockDocument(@Nonnull Document doc) {
  if (doc instanceof DocumentWindow) doc = ((DocumentWindow)doc).getDelegate();
  final PostprocessReformattingAspect component = myProject.getComponent(PostprocessReformattingAspect.class);
  final FileViewProvider viewProvider = getCachedViewProvider(doc);
  if (viewProvider != null && component != null) component.doPostponedFormatting(viewProvider);
}
 
Example #19
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static DocumentWindow getInjectedDocument(Project project, Editor editor, int offset) {
  PsiFile hostFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (hostFile != null) {
    // inspired by com.intellij.codeInsight.editorActions.TypedHandler.injectedEditorIfCharTypedIsSignificant()
    List<DocumentWindow> injected = InjectedLanguageManager.getInstance(project).getCachedInjectedDocumentsInRange(hostFile, TextRange.create(offset, offset));
    for (DocumentWindow documentWindow : injected) {
      if (documentWindow.isValid() && documentWindow.containsRange(offset, offset)) {
        return documentWindow;
      }
    }
  }
  return null;
}
 
Example #20
Source File: QuickEditAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public QuickEditHandler invokeImpl(@Nonnull final Project project, final Editor editor, PsiFile file) throws IncorrectOperationException {
  int offset = editor.getCaretModel().getOffset();
  Pair<PsiElement, TextRange> pair = ObjectUtils.assertNotNull(getRangePair(file, editor));

  PsiFile injectedFile = (PsiFile)pair.first;
  QuickEditHandler handler = getHandler(project, injectedFile, editor, file);

  if (!ApplicationManager.getApplication().isUnitTestMode()) {
    DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injectedFile);
    if (documentWindow != null) {
      handler.navigate(InjectedLanguageUtil.hostToInjectedUnescaped(documentWindow, offset));
    }
  }
  return handler;
}
 
Example #21
Source File: QuickEditAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static QuickEditHandler getExistingHandler(@Nonnull PsiFile injectedFile) {
  Place shreds = InjectedLanguageUtil.getShreds(injectedFile);
  DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injectedFile);
  if (shreds == null || documentWindow == null) return null;

  TextRange hostRange = TextRange.create(shreds.get(0).getHostRangeMarker().getStartOffset(),
                                         shreds.get(shreds.size() - 1).getHostRangeMarker().getEndOffset());
  for (Editor editor : EditorFactory.getInstance().getAllEditors()) {
    if (editor.getDocument() != documentWindow.getDelegate()) continue;
    QuickEditHandler handler = editor.getUserData(QUICK_EDIT_HANDLER);
    if (handler != null && handler.changesRange(hostRange)) return handler;
  }
  return null;
}
 
Example #22
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void enumerate(@Nonnull DocumentWindow documentWindow, @Nonnull PsiFile hostPsiFile, @Nonnull PsiLanguageInjectionHost.InjectedPsiVisitor visitor) {
  Segment[] ranges = documentWindow.getHostRanges();
  Segment rangeMarker = ranges.length > 0 ? ranges[0] : null;
  PsiElement element = rangeMarker == null ? null : hostPsiFile.findElementAt(rangeMarker.getStartOffset());
  if (element != null) {
    enumerate(element, hostPsiFile, true, visitor);
  }
}
 
Example #23
Source File: PsiBasedFormattingModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private String replaceWithPSI(final TextRange textRange, final String whiteSpace) {
  final int offset = textRange.getEndOffset();
  ASTNode leafElement = findElementAt(offset);

  if (leafElement != null) {
    PsiFile hostFile = myASTNode.getPsi().getContainingFile();
    TextRange effectiveRange = textRange;
    List<DocumentWindow> injections = InjectedLanguageManager.getInstance(hostFile.getProject()).getCachedInjectedDocumentsInRange(hostFile, TextRange.from(offset, 0));
    if (!injections.isEmpty()) {
      PsiElement injectedElement = PsiDocumentManager.getInstance(myProject).getPsiFile(injections.get(0));
      PsiLanguageInjectionHost host = InjectedLanguageUtil.findInjectionHost(injectedElement);
      TextRange corrected = host == null ? null : correctRangeByInjection(textRange, host);
      if (corrected != null) {
        effectiveRange = corrected;
      }
    }

    if (leafElement.getPsi() instanceof PsiFile) {
      return null;
    }
    else {
      LOG.assertTrue(leafElement.getPsi().isValid());
      return replaceWithPsiInLeaf(effectiveRange, whiteSpace, leafElement);
    }
  }
  else if (textRange.getEndOffset() == myASTNode.getTextLength()) {
    CodeStyleManager.getInstance(myProject).performActionWithFormatterDisabled((Runnable)() -> FormatterUtil.replaceLastWhiteSpace(myASTNode, whiteSpace, textRange));
    return whiteSpace;
  }
  else {
    return null;
  }
}
 
Example #24
Source File: AbstractBlock.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private List<Block> buildInjectedBlocks() {
  if (myBuildIndentsOnly) {
    return EMPTY;
  }
  if (!(this instanceof SettingsAwareBlock)) {
    return EMPTY;
  }
  PsiElement psi = myNode.getPsi();
  if (psi == null) {
    return EMPTY;
  }
  PsiFile file = psi.getContainingFile();
  if (file == null) {
    return EMPTY;
  }

  if (InjectedLanguageUtil.getCachedInjectedDocuments(file).isEmpty()) {
    return EMPTY;
  }

  TextRange blockRange = myNode.getTextRange();
  List<DocumentWindow> documentWindows = InjectedLanguageUtil.getCachedInjectedDocuments(file);
  for (DocumentWindow documentWindow : documentWindows) {
    int startOffset = documentWindow.injectedToHost(0);
    int endOffset = startOffset + documentWindow.getTextLength();
    if (blockRange.containsRange(startOffset, endOffset)) {
      PsiFile injected = PsiDocumentManager.getInstance(psi.getProject()).getCachedPsiFile(documentWindow);
      if (injected != null) {
        List<Block> result = ContainerUtilRt.newArrayList();
        DefaultInjectedLanguageBlockBuilder builder = new DefaultInjectedLanguageBlockBuilder(((SettingsAwareBlock)this).getSettings());
        builder.addInjectedBlocks(result, myNode, getWrap(), getAlignment(), getIndent());
        return result;
      }
    }
  }
  return EMPTY;
}
 
Example #25
Source File: EditorWindowImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
static void disposeEditorFor(@Nonnull DocumentWindow documentWindow) {
  synchronized (allEditors) {
    for (Iterator<EditorWindowImpl> iterator = allEditors.iterator(); iterator.hasNext(); ) {
      EditorWindowImpl editor = iterator.next();
      if (InjectionRegistrarImpl.intersect(editor.getDocument(), (DocumentWindowImpl)documentWindow)) {
        disposeEditor(editor);
        iterator.remove();
        break;
      }
    }
  }
}
 
Example #26
Source File: EditorWindowImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(final Object o) {
  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;

  final EditorWindowImpl that = (EditorWindowImpl)o;

  DocumentWindow thatWindow = that.getDocument();
  return myDelegate.equals(that.myDelegate) && myDocumentWindow.equals(thatWindow);
}
 
Example #27
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static int hostToInjectedUnescaped(DocumentWindow window, int hostOffset) {
  Place shreds = ((DocumentWindowImpl)window).getShreds();
  Segment hostRangeMarker = shreds.get(0).getHostRangeMarker();
  if (hostRangeMarker == null || hostOffset < hostRangeMarker.getStartOffset()) {
    return shreds.get(0).getPrefix().length();
  }
  StringBuilder chars = new StringBuilder();
  int unescaped = 0;
  for (int i = 0; i < shreds.size(); i++, chars.setLength(0)) {
    PsiLanguageInjectionHost.Shred shred = shreds.get(i);
    int prefixLength = shred.getPrefix().length();
    int suffixLength = shred.getSuffix().length();
    PsiLanguageInjectionHost host = shred.getHost();
    TextRange rangeInsideHost = shred.getRangeInsideHost();
    LiteralTextEscaper<? extends PsiLanguageInjectionHost> escaper = host == null ? null : host.createLiteralTextEscaper();
    unescaped += prefixLength;
    Segment currentRange = shred.getHostRangeMarker();
    if (currentRange == null) continue;
    Segment nextRange = i == shreds.size() - 1 ? null : shreds.get(i + 1).getHostRangeMarker();
    if (nextRange == null || hostOffset < nextRange.getStartOffset()) {
      hostOffset = Math.min(hostOffset, currentRange.getEndOffset());
      int inHost = hostOffset - currentRange.getStartOffset();
      if (escaper != null && escaper.decode(rangeInsideHost, chars)) {
        int found = ObjectUtil.binarySearch(0, inHost, index -> Comparing.compare(escaper.getOffsetInHost(index, TextRange.create(0, host.getTextLength())), inHost));
        return unescaped + (found >= 0 ? found : -found - 1);
      }
      return unescaped + inHost;
    }
    if (escaper != null && escaper.decode(rangeInsideHost, chars)) {
      unescaped += chars.length();
    }
    else {
      unescaped += currentRange.getEndOffset() - currentRange.getStartOffset();
    }
    unescaped += suffixLength;
  }
  return unescaped - shreds.get(shreds.size() - 1).getSuffix().length();
}
 
Example #28
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated use {@link InjectedLanguageManager#getCachedInjectedDocumentsInRange(PsiFile, TextRange)} instead
 */
@Nonnull
@Deprecated
public static ConcurrentList<DocumentWindow> getCachedInjectedDocuments(@Nonnull PsiFile hostPsiFile) {
  // modification of cachedInjectedDocuments must be under InjectedLanguageManagerImpl.ourInjectionPsiLock only
  List<DocumentWindow> injected = hostPsiFile.getUserData(INJECTED_DOCS_KEY);
  if (injected == null) {
    injected = ((UserDataHolderEx)hostPsiFile).putUserDataIfAbsent(INJECTED_DOCS_KEY, ContainerUtil.createConcurrentList());
  }
  return (ConcurrentList<DocumentWindow>)injected;
}
 
Example #29
Source File: InjectedLanguageManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public DocumentWindow freezeWindow(@Nonnull DocumentWindow document) {
  Place shreds = ((DocumentWindowImpl)document).getShreds();
  Project project = shreds.getHostPointer().getProject();
  DocumentEx delegate = ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(project)).getLastCommittedDocument(document.getDelegate());
  Place place = new Place();
  place.addAll(ContainerUtil.map(shreds, shred -> ((ShredImpl)shred).withPsiRange()));
  return new DocumentWindowImpl(delegate, place);
}
 
Example #30
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * This is a quick check, that can be performed before committing document and invoking
 * {@link #getEditorForInjectedLanguageNoCommit(Editor, Caret, PsiFile)} or other methods here, which don't work
 * for uncommitted documents.
 */
static boolean mightHaveInjectedFragmentAtCaret(@Nonnull Project project, @Nonnull Document hostDocument, int hostOffset) {
  PsiFile hostPsiFile = PsiDocumentManager.getInstance(project).getCachedPsiFile(hostDocument);
  if (hostPsiFile == null || !hostPsiFile.isValid()) return false;
  List<DocumentWindow> documents = InjectedLanguageManager.getInstance(project).getCachedInjectedDocumentsInRange(hostPsiFile, TextRange.create(hostOffset, hostOffset));
  for (DocumentWindow document : documents) {
    if (document.isValid() && document.getHostRange(hostOffset) != null) return true;
  }
  return false;
}