Java Code Examples for com.intellij.psi.util.PsiUtilBase#findEditor()

The following examples show how to use com.intellij.psi.util.PsiUtilBase#findEditor() . 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: EclipseCodeFormatter.java    From EclipseCodeFormatter with Apache License 2.0 6 votes vote down vote up
public void format(PsiFile psiFile, int startOffset, int endOffset) throws FileDoesNotExistsException {
	LOG.debug("#format " + startOffset + "-" + endOffset);
	boolean wholeFile = FileUtils.isWholeFile(startOffset, endOffset, psiFile.getText());
	Range range = new Range(startOffset, endOffset, wholeFile);

	final Editor editor = PsiUtilBase.findEditor(psiFile);
	if (editor != null) {
		TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
		if (templateState != null && !settings.isUseForLiveTemplates()) {
			throw new ReformatItInIntelliJ();
		}
		formatWhenEditorIsOpen(editor, range, psiFile);
	} else {
		formatWhenEditorIsClosed(range, psiFile);
	}
	               
}
 
Example 2
Source File: EclipseCodeStyleManager.java    From EclipseCodeFormatter with Apache License 2.0 6 votes vote down vote up
protected boolean shouldSkipFormatting(PsiFile psiFile, Collection<TextRange> textRanges) {
	VirtualFile virtualFile = psiFile.getVirtualFile();

	if (settings.isFormatSeletedTextInAllFileTypes()) {             
		// when file is being edited, it is important to load text from editor, i think
		final Editor editor = PsiUtilBase.findEditor(psiFile);
		if (editor != null) {
			Document document = editor.getDocument();
			String text = document.getText();
			if (!FileUtils.isWholeFile(textRanges, text)) {
				return false;
			}
		}
	}
	//not else
	if (settings.isFormatOtherFileTypesWithIntelliJ()) {
		return isDisabledFileType(virtualFile);
	}
	return true;
}
 
Example 3
Source File: CodeMakerUtil.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
/**
 * save the current change
 */
public static void pushPostponedChanges(PsiElement element) {
    Editor editor = PsiUtilBase.findEditor(element.getContainingFile());
    if (editor != null) {
        PsiDocumentManager.getInstance(element.getProject())
            .doPostponedOperationsAndUnblockDocument(editor.getDocument());
    }
}
 
Example 4
Source File: LossyEncodingInspection.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) {
  PsiFile psiFile = descriptor.getPsiElement().getContainingFile();
  VirtualFile virtualFile = psiFile.getVirtualFile();

  Editor editor = PsiUtilBase.findEditor(psiFile);
  DataContext dataContext = createDataContext(editor, editor == null ? null : editor.getComponent(), virtualFile, project);
  ListPopup popup = new ChangeFileEncodingAction().createPopup(dataContext);
  if (popup != null) {
    popup.showInBestPositionFor(dataContext);
  }
}
 
Example 5
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void reformatText(@Nonnull PsiFile file, @Nonnull FormatTextRanges ranges, @Nullable Editor editor) throws IncorrectOperationException {
  if (ranges.isEmpty()) {
    return;
  }
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();

  CheckUtil.checkWritable(file);
  if (!SourceTreeToPsiMap.hasTreeElement(file)) {
    return;
  }

  ASTNode treeElement = SourceTreeToPsiMap.psiElementToTree(file);
  transformAllChildren(treeElement);

  LOG.assertTrue(file.isValid(), "File name: " + file.getName() + " , class: " + file.getClass().getSimpleName());

  if (editor == null) {
    editor = PsiUtilBase.findEditor(file);
  }

  CaretPositionKeeper caretKeeper = null;
  if (editor != null) {
    caretKeeper = new CaretPositionKeeper(editor, getSettings(file), file.getLanguage());
  }

  if (FormatterUtil.isFormatterCalledExplicitly()) {
    removeEndingWhiteSpaceFromEachRange(file, ranges);
  }

  formatRanges(file, ranges, ExternalFormatProcessor.useExternalFormatter(file) ? null  // do nothing, delegate the external formatting activity to post-processor
                                                                                : () -> {
                                                                                  final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(getSettings(file), file.getLanguage());
                                                                                  codeFormatter.processText(file, ranges, true);
                                                                                });

  if (caretKeeper != null) {
    caretKeeper.restoreCaretPosition();
  }
}
 
Example 6
Source File: CodeFormatterFacade.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Inspects all lines of the given document and wraps all of them that exceed {@link CodeStyleSettings#getRightMargin(Language)}
 * right margin}.
 * <p/>
 * I.e. the algorithm is to do the following for every line:
 * <p/>
 * <pre>
 * <ol>
 *   <li>
 *      Check if the line exceeds {@link CodeStyleSettings#getRightMargin(Language)}  right margin}. Go to the next line in the case of
 *      negative answer;
 *   </li>
 *   <li>Determine line wrap position; </li>
 *   <li>
 *      Perform 'smart wrap', i.e. not only wrap the line but insert additional characters over than line feed if necessary.
 *      For example consider that we wrap a single-line comment - we need to insert comment symbols on a start of the wrapped
 *      part as well. Generally, we get the same behavior as during pressing 'Enter' at wrap position during editing document;
 *   </li>
 * </ol>
 * </pre>
 *
 * @param file        file that holds parsed document tree
 * @param document    target document
 * @param startOffset start offset of the first line to check for wrapping (inclusive)
 * @param endOffset   end offset of the first line to check for wrapping (exclusive)
 */
private void wrapLongLinesIfNecessary(@Nonnull final PsiFile file, @Nullable final Document document, final int startOffset, final int endOffset) {
  if (!mySettings.getCommonSettings(file.getLanguage()).WRAP_LONG_LINES ||
      PostprocessReformattingAspect.getInstance(file.getProject()).isViewProviderLocked(file.getViewProvider()) ||
      document == null) {
    return;
  }

  FormatterTagHandler formatterTagHandler = new FormatterTagHandler(CodeStyle.getSettings(file));
  List<TextRange> enabledRanges = formatterTagHandler.getEnabledRanges(file.getNode(), new TextRange(startOffset, endOffset));

  final VirtualFile vFile = FileDocumentManager.getInstance().getFile(document);
  if ((vFile == null || vFile instanceof LightVirtualFile) && !ApplicationManager.getApplication().isUnitTestMode()) {
    // we assume that control flow reaches this place when the document is backed by a "virtual" file so any changes made by
    // a formatter affect only PSI and it is out of sync with a document text
    return;
  }

  Editor editor = PsiUtilBase.findEditor(file);
  EditorFactory editorFactory = null;
  if (editor == null) {
    if (!ApplicationManager.getApplication().isDispatchThread()) {
      return;
    }
    editorFactory = EditorFactory.getInstance();
    editor = editorFactory.createEditor(document, file.getProject(), file.getVirtualFile(), false);
  }
  try {
    final Editor editorToUse = editor;
    ApplicationManager.getApplication().runWriteAction(() -> {
      final CaretModel caretModel = editorToUse.getCaretModel();
      final int caretOffset = caretModel.getOffset();
      final RangeMarker caretMarker = editorToUse.getDocument().createRangeMarker(caretOffset, caretOffset);
      doWrapLongLinesIfNecessary(editorToUse, file.getProject(), editorToUse.getDocument(), startOffset, endOffset, enabledRanges);
      if (caretMarker.isValid() && caretModel.getOffset() != caretMarker.getStartOffset()) {
        caretModel.moveToOffset(caretMarker.getStartOffset());
      }
    });
  }
  finally {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject());
    if (documentManager.isUncommited(document)) documentManager.commitDocument(document);
    if (editorFactory != null) {
      editorFactory.releaseEditor(editor);
    }
  }
}
 
Example 7
Source File: TextEditorBasedStructureViewModel.java    From consulo with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a structure view model instance linked to a text editor displaying the specified
 * file.
 *
 * @param psiFile the file for which the structure view model is requested.
 */
protected TextEditorBasedStructureViewModel(@Nonnull PsiFile psiFile) {
  this(PsiUtilBase.findEditor(psiFile), psiFile);
}