com.intellij.psi.util.PsiUtilBase#findEditor ( )源码实例Demo

下面列出了com.intellij.psi.util.PsiUtilBase#findEditor ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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);
	}
	               
}
 
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;
}
 
源代码3 项目: CodeMaker   文件: CodeMakerUtil.java
/**
 * 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());
    }
}
 
源代码4 项目: consulo   文件: LossyEncodingInspection.java
@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);
  }
}
 
源代码5 项目: consulo   文件: CodeStyleManagerImpl.java
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();
  }
}
 
源代码6 项目: consulo   文件: CodeFormatterFacade.java
/**
 * 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);
    }
  }
}
 
/**
 * 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);
}