Java 类com.intellij.openapi.editor.actions.EnterAction 实例源码

项目:tools-idea    文件:GenerateMembersHandlerBase.java   
private void doGenerate(final Project project, final Editor editor, PsiClass aClass, ClassMember[] members) {
  int offset = editor.getCaretModel().getOffset();

  int col = editor.getCaretModel().getLogicalPosition().column;
  int line = editor.getCaretModel().getLogicalPosition().line;
  final Document document = editor.getDocument();
  int lineStartOffset = document.getLineStartOffset(line);
  CharSequence docText = document.getCharsSequence();
  String textBeforeCaret = docText.subSequence(lineStartOffset, offset).toString();
  final String afterCaret = docText.subSequence(offset, document.getLineEndOffset(line)).toString();
  if (textBeforeCaret.trim().length() > 0 && StringUtil.isEmptyOrSpaces(afterCaret) && !editor.getSelectionModel().hasSelection()) {
    EnterAction.insertNewLineAtCaret(editor);
    PsiDocumentManager.getInstance(project).commitDocument(document);
    offset = editor.getCaretModel().getOffset();
    col = editor.getCaretModel().getLogicalPosition().column;
    line = editor.getCaretModel().getLogicalPosition().line;
  }

  editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(0, 0));

  List<? extends GenerationInfo> newMembers;
  try{
    List<? extends GenerationInfo> prototypes = generateMemberPrototypes(aClass, members);
    newMembers = GenerateMembersUtil.insertMembersAtOffset(aClass.getContainingFile(), offset, prototypes);
  }
  catch(IncorrectOperationException e){
    LOG.error(e);
    return;
  }

  editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(line, col));

  if (newMembers.isEmpty()) {
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
      HintManager.getInstance().showErrorHint(editor, getNothingFoundMessage());
    }
    return;
  }

  final ArrayList<TemplateGenerationInfo> templates = new ArrayList<TemplateGenerationInfo>();
  for (GenerationInfo member : newMembers) {
    if (member instanceof TemplateGenerationInfo) {
      templates.add((TemplateGenerationInfo) member);
    }
  }

  if (!templates.isEmpty()){
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
    runTemplates(project, editor, templates, 0);
  }
  else if (!newMembers.isEmpty()){
    newMembers.get(0).positionCaret(editor, false);
  }
}