Java 类com.intellij.openapi.editor.Document 实例源码

项目:yii2support    文件:ValidationCompletionProvider.java   
@NotNull
private LookupElementBuilder buildLookup(PhpClassMember field, PhpExpression position, boolean autoValue) {
    String lookupString = field instanceof Method ? ClassUtils.getAsPropertyName((Method) field) : field.getName();
    LookupElementBuilder builder = LookupElementBuilder.create(field, lookupString).withIcon(field.getIcon());
    if (autoValue) {
        builder = builder.withInsertHandler((insertionContext, lookupElement) -> {

            Document document = insertionContext.getDocument();
            int insertPosition = insertionContext.getSelectionEndOffset();

            if (position.getParent().getParent() instanceof ArrayCreationExpression) {
                document.insertString(insertPosition + 1, " => ");
                insertPosition += 5;
                insertionContext.getEditor().getCaretModel().getCurrentCaret().moveToOffset(insertPosition);
            }
        });
    }
    if (field instanceof Field) {
        builder = builder.withTypeText(field.getType().toString());
    }
    return builder;
}
项目:yii2support    文件:FieldAttributesCompletionProvider.java   
@NotNull
private LookupElementBuilder buildLookup(PhpClassMember field, PhpExpression position) {
    String lookupString = field instanceof Method ? ClassUtils.getAsPropertyName((Method) field) : field.getName();
    LookupElementBuilder builder =  LookupElementBuilder.create(field, lookupString).withIcon(field.getIcon())
            .withInsertHandler((insertionContext, lookupElement) -> {

                Document document = insertionContext.getDocument();
                int insertPosition = insertionContext.getSelectionEndOffset();

                if (position.getParent().getParent() instanceof ArrayCreationExpression) {
                    document.insertString(insertPosition + 1, " => ");
                    insertPosition += 5;
                    insertionContext.getEditor().getCaretModel().getCurrentCaret().moveToOffset(insertPosition);
                }
            });
    if (field instanceof Field) {
        builder = builder.withTypeText(field.getType().toString());
    }
    return builder;
}
项目:yii2support    文件:ObjectFactoryCompletionProvider.java   
@NotNull
private LookupElementBuilder buildLookup(PhpClassMember field, PhpExpression position) {
    String lookupString = field instanceof Method ? ClassUtils.getAsPropertyName((Method) field) : field.getName();
    LookupElementBuilder builder =  LookupElementBuilder.create(field, lookupString).withIcon(field.getIcon())
            .withInsertHandler((insertionContext, lookupElement) -> {

                Document document = insertionContext.getDocument();
                int insertPosition = insertionContext.getSelectionEndOffset();

                if (position.getParent().getParent() instanceof ArrayCreationExpression) {
                    document.insertString(insertPosition + 1, " => ");
                    insertPosition += 5;
                    insertionContext.getEditor().getCaretModel().getCurrentCaret().moveToOffset(insertPosition);
                }
            });
    if (field instanceof Field) {
        builder = builder.withTypeText(field.getType().toString());
    }
    return builder;
}
项目:intellij-csv-validator    文件:CsvIntentionHelper.java   
public static void unquoteAll(@NotNull Project project, @NotNull PsiFile psiFile) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
        List<Integer> quotePositions = new ArrayList<>();
        Collection<PsiElement> fields = getAllFields(psiFile);
        for (PsiElement field : fields) {
            if (getChildren(field).stream().anyMatch(element -> getElementType(element) == CsvTypes.ESCAPED_TEXT)) {
                continue;
            }
            if (getElementType(field.getFirstChild()) == CsvTypes.QUOTE) {
                quotePositions.add(field.getFirstChild().getTextOffset());
            }
            if (getElementType(field.getLastChild()) == CsvTypes.QUOTE) {
                quotePositions.add(field.getLastChild().getTextOffset());
            }
        }
        String text = removeQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
项目:reasonml-idea-plugin    文件:FoldingBuilder.java   
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
    List<FoldingDescriptor> descriptors = new ArrayList<>();

    PsiTreeUtil.processElements(root, element -> {
        IElementType elementType = element.getNode().getElementType();
        MlTypes types = elementType.getLanguage() == RmlLanguage.INSTANCE ? RmlTypes.INSTANCE : OclTypes.INSTANCE;
        if (types.COMMENT == elementType) {
            FoldingDescriptor fold = fold(element);
            if (fold != null) {
                descriptors.add(fold);
            }
        } else if (types.TYPE_EXPRESSION == elementType) {
            foldType(descriptors, (PsiType) element);
        } else if (types.LET_EXPRESSION == elementType) {
            foldLet(descriptors, (PsiLet) element);
        } else if (types.MODULE_EXPRESSION == elementType) {
            foldModule(descriptors, (PsiModule) element);
        }
        return true;
    });

    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
项目:idea-php-typo3-plugin    文件:RouteFoldingBuilder.java   
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
    FoldingGroup group = FoldingGroup.newGroup("TYPO3Route");

    List<FoldingDescriptor> descriptors = new ArrayList<>();
    Collection<StringLiteralExpression> literalExpressions = PsiTreeUtil.findChildrenOfType(root, StringLiteralExpression.class);

    for (final StringLiteralExpression literalExpression : literalExpressions) {
        for (PsiReference reference : literalExpression.getReferences()) {
            if (reference instanceof RouteReference) {
                String value = literalExpression.getContents();

                FoldingDescriptor descriptor = foldRouteReferenceString(reference, value, group);
                if (descriptor != null) {
                    descriptors.add(descriptor);
                }
            }
        }


    }

    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
项目:laravel-insight    文件:BladeFoldingBuilder.java   
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(
    @NotNull final PsiElement root,
    @NotNull final Document document,
    final boolean quick
) {
    if (!(root instanceof BladeFileImpl)) {
        return FoldingDescriptor.EMPTY.clone();
    }

    final Queue<BladePsiDirective> directives         = new LinkedBlockingQueue(Arrays.asList(((BladeFileImpl) root).getDirectives()));
    final List<FoldingDescriptor>  foldingDescriptors = new ArrayList<>();

    processDirectives(null, directives, foldingDescriptors, document);

    return foldingDescriptors.toArray(new FoldingDescriptor[foldingDescriptors.size()]);
}
项目:intellij-csv-validator    文件:CsvIntentionHelper.java   
public static void unquoteValue(@NotNull Project project, @NotNull PsiElement element) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        List<Integer> quotePositions = new ArrayList<>();

        element = getParentFieldElement(element);
        if (getElementType(element.getFirstChild()) == CsvTypes.QUOTE) {
            quotePositions.add(element.getFirstChild().getTextOffset());
        }
        if (getElementType(element.getLastChild()) == CsvTypes.QUOTE) {
            quotePositions.add(element.getLastChild().getTextOffset());
        }
        String text = removeQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
项目:Gherkin-TS-Runner    文件:GherkinIconUtils.java   
public void generateGherkinRunIcons(Document rootDocument, Editor rootEditor) {
    for (int i = 0; i < rootDocument.getLineCount(); i++) {
        int startOffset = rootDocument.getLineStartOffset(i);
        int endOffset = rootDocument.getLineEndOffset(i);

        String lineText = rootDocument.getText(new TextRange(startOffset, endOffset)).trim();

        Icon icon;
        if (lineText.matches(SCENARIO_REGEX)) {
            icon = GherkinIconRenderer.SCENARIO_ICON;
        } else if (lineText.matches(FEATURE_REGEX)) {
            icon = GherkinIconRenderer.FEATURE_ICON;
        } else {
            // System.out.println();
             continue;
        }
        GherkinIconRenderer gherkinIconRenderer = new GherkinIconRenderer(rootEditor.getProject(), fileName);
        gherkinIconRenderer.setLine(i);
        gherkinIconRenderer.setIcon(icon);

        RangeHighlighter rangeHighlighter = createRangeHighlighter(rootDocument, rootEditor, i, i, new TextAttributes());
        rangeHighlighter.setGutterIconRenderer(gherkinIconRenderer);
    }
}
项目:bamboo-soy    文件:SoyDocumentationProvider.java   
@Nullable
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
  Document document =
      FileDocumentManager.getInstance().getDocument(element.getContainingFile().getVirtualFile());
  if (document == null) return "";

  int lineNum = document.getLineNumber(element.getTextOffset()) + 1 /* count starts at zero */;
  String path = element.getContainingFile().getVirtualFile().getName();
  StringBuilder navigateInfo = new StringBuilder("Defined at ");
  navigateInfo.append(path);
  navigateInfo.append(":");
  navigateInfo.append(lineNum);
  String optDoc = getDocCommentForEnclosingTag(element);
  if (optDoc != null) {
    navigateInfo.append("\n");
    navigateInfo.append(produceCommentPreview(optDoc));
  }
  return navigateInfo.toString();
}
项目:bamboo-soy    文件:ClosingTagHandler.java   
private static void insertClosingTag(@NotNull Editor editor, int offset, String tag) {
  Document document = editor.getDocument();
  CharSequence charSequence = document.getImmutableCharSequence();
  int startPosition = offset - 2;
  // Consume second left brace if present.
  if (offset > 0 && charSequence.charAt(startPosition - 1) == '{') {
    startPosition--;
  }
  int endPosition = offset;
  // Consume at most 2 right braces if present.
  while (endPosition < charSequence.length()
      && charSequence.charAt(endPosition) == '}'
      && endPosition < offset + 2) {
    endPosition++;
  }
  editor.getDocument().replaceString(startPosition, endPosition, tag);
  editor.getCaretModel().moveToOffset(startPosition + tag.length());

}
项目:bamboo-soy    文件:EnterHandler.java   
private static void handleEnterInComment(
    PsiElement element, @NotNull PsiFile file, @NotNull Editor editor) {
  if (element.getText().startsWith("/*")) {
    Document document = editor.getDocument();

    int caretOffset = editor.getCaretModel().getOffset();
    int lineNumber = document.getLineNumber(caretOffset);

    String lineTextBeforeCaret =
        document.getText(new TextRange(document.getLineStartOffset(lineNumber), caretOffset));
    String lineTextAfterCaret =
        document.getText(new TextRange(caretOffset, document.getLineEndOffset(lineNumber)));

    if (lineTextAfterCaret.equals("*/")) {
      return;
    }

    String toInsert = lineTextBeforeCaret.equals("") ? " * " : "* ";
    insertText(file, editor, toInsert, toInsert.length());
  }
}
项目:bamboo-soy    文件:EnterHandler.java   
@Override
public Result postProcessEnter(
    @NotNull PsiFile file, @NotNull Editor editor, @NotNull DataContext dataContext) {
  if (file.getFileType() != SoyFileType.INSTANCE) {
    return Result.Continue;
  }

  int caretOffset = editor.getCaretModel().getOffset();
  PsiElement element = file.findElementAt(caretOffset);
  Document document = editor.getDocument();

  int lineNumber = document.getLineNumber(caretOffset) - 1;
  int lineStartOffset = document.getLineStartOffset(lineNumber);
  String lineTextBeforeCaret = document.getText(new TextRange(lineStartOffset, caretOffset));

  if (element instanceof PsiComment && element.getTextOffset() < caretOffset) {
    handleEnterInComment(element, file, editor);
  } else if (lineTextBeforeCaret.startsWith("/*")) {
    insertText(file, editor, " * \n ", 3);
  }

  return Result.Continue;
}
项目:GravSupport    文件:LanguageFileStrategy.java   
@Override
public void actionPerformed(ActionEvent e) {
    super.actionPerformed(e);
    dialog.show();
    int exitCode = dialog.getExitCode();
    if (exitCode != CANCEL_EXIT_CODE) {
        String key = dialog.getKeyText();
        String value = dialog.getValueText();
        currentLang = dialog.getSelectedLangauge();
        if (currentLang != null && !currentLang.isEmpty()) {
            Editor ieditor = editorMap.get(currentLang);
            Document document = ieditor.getDocument();
            WriteCommandAction.runWriteCommandAction(fileEditor.getProject(), () -> updateDocumentHook(document, ieditor.getProject(), currentLang, key, value, model));
        } else {
            NotificationHelper.showBaloon("No language file available", MessageType.WARNING, fileEditor.getProject());
        }
    }
}
项目:manifold-ij    文件:FakeTargetElement.java   
private Document findDocument()
{
  Editor editor = ResourceToManifoldUtil.getActiveEditor( getProject() );
  if( editor instanceof EditorImpl )
  {
    EditorImpl editorImpl = (EditorImpl)editor;
    if( editorImpl.getVirtualFile().getPath().equals( _file.getVirtualFile().getPath() ) )
    {
      // get document from current editor
      return editorImpl.getDocument();
    }
  }

  // get document from file
  return _file.getViewProvider().getDocument();
}
项目:intellij-randomness    文件:DataInsertAction.java   
/**
 * Inserts the string generated by {@link #generateString()} at the caret(s) in the editor.
 *
 * @param event the performed action
 */
@Override
public final void actionPerformed(final AnActionEvent event) {
    final Editor editor = event.getData(CommonDataKeys.EDITOR);
    if (editor == null) {
        return;
    }
    final Project project = event.getData(CommonDataKeys.PROJECT);
    final Document document = editor.getDocument();
    final CaretModel caretModel = editor.getCaretModel();

    final Runnable replaceCaretSelections = () -> caretModel.getAllCarets().forEach(caret -> {
        final int start = caret.getSelectionStart();
        final int end = caret.getSelectionEnd();

        final String string = generateString();
        final int newEnd = start + string.length();

        document.replaceString(start, end, string);
        caret.setSelection(start, newEnd);
    });

    WriteCommandAction.runWriteCommandAction(project, replaceCaretSelections);
}
项目:EmojiPrefix    文件:EmojiResourceCompletionContributor.java   
public EmojiResourceCompletionContributor() {
    extend(CompletionType.BASIC, PlatformPatterns.psiElement(PsiElement.class), new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull CompletionParameters completionParameters,
                                      ProcessingContext processingContext,
                                      @NotNull CompletionResultSet completionResultSet) {
            Document document = completionParameters.getEditor().getDocument();
            int lineStart = document.getLineStartOffset(document.getLineNumber(completionParameters.getOffset()));
            String lineText = document.getText(new TextRange(lineStart, completionParameters.getOffset()));
            if (includeCount(lineText) == 1) {
                for (Map.Entry<String, Icon> iconEntry : EmojiUtil.getEmojiMap().entrySet()) {
                    completionResultSet.addElement(LookupElementBuilder.create(iconEntry.getKey(), ":" + iconEntry.getKey() + ":")
                            .withIcon(iconEntry.getValue())
                            .withInsertHandler((insertionContext, lookupElement) -> {
                                int startOffset = insertionContext.getStartOffset();
                                Document insertDocument = insertionContext.getDocument();
                                if (startOffset > 0 && insertDocument.getCharsSequence().charAt(startOffset - 1) == ':') {
                                    insertDocument.deleteString(startOffset - 1, startOffset);
                                }
                            }));
                }
            }
        }
    });
}
项目:AndroidSourceViewer    文件:DiffSourceAction.java   
/**
 * 调用 Android 文件对比
 * @param project
 * @param f1
 * @param f2
 */
public static void diff(final Project project, final File f1, final File f2) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                VirtualFile v1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f1);
                Document document1 = FileDocumentManager.getInstance().getDocument(v1);
                FileDocumentContentImpl fileDocumentContent1 = new FileDocumentContentImpl(project, document1, v1);
                VirtualFile v2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f2);
                Document document2 = FileDocumentManager.getInstance().getDocument(v2);
                FileDocumentContentImpl fileDocumentContent2 = new FileDocumentContentImpl(project, document2, v2);
                SimpleDiffRequest simpleDiffRequest = new SimpleDiffRequest(Constant.TITLE, fileDocumentContent1, fileDocumentContent2,
                        f1.getName(), f2.getName());
                DiffManager.getInstance().showDiff(project, simpleDiffRequest);
            } catch (Exception e) {
                NotificationUtils.errorNotification("Diff Source Error:" + e.getMessage());
            }
        }
    });
}
项目:SearchResourcePlugin    文件:SearchResourcesAction.java   
public void insertToEditor(Project project, SearchResultElement element) {
    CommandProcessor.getInstance().executeCommand(project, () -> getApplication().runWriteAction(() -> {
        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor != null) {
            int offset = editor.getCaretModel().getOffset();
            Document document = editor.getDocument();
            String key = isXmlFile ?
                    "@" + element.getTag() + "/" + element.getName()
                    : "R." + element.getTag() + "." + element.getName();
            if (key != null) {
                document.insertString(offset, key);
                editor.getCaretModel().moveToOffset(offset + key.length());
            }
        }
    }), "InsertResultToEditor", "", UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION);
}
项目:manifold-ij    文件:IjFile.java   
private String getTemporaryBuffer( IjFile file )
{
  final VirtualFile virtualFile = file.getVirtualFile();

  // we're getting the cached documents since getDocument() forces PSI creating which will cause deadlock !!!
  if( virtualFile != null && !virtualFile.getFileType().isBinary() )
  {
    final Document document = FileDocumentManager.getInstance().getCachedDocument( virtualFile );
    final String[] result = new String[1];
    if( document != null )
    {
      if( ApplicationManagerEx.getApplicationEx().tryRunReadAction( () -> result[0] = document.getText() ) )
      {
        return result[0];
      }
      else
      {
        return document.getCharsSequence().toString();
      }
    }
  }

  return null;
}
项目:educational-plugin    文件:StudyUtils.java   
public static void drawAllAnswerPlaceholders(Editor editor, TaskFile taskFile) {
  editor.getMarkupModel().removeAllHighlighters();
  final Project project = editor.getProject();
  if (project == null) return;
  final StudyTaskManager taskManager = StudyTaskManager.getInstance(project);
  for (AnswerPlaceholder answerPlaceholder : taskFile.getAnswerPlaceholders()) {
    final JBColor color = taskManager.getColor(answerPlaceholder);
    EduAnswerPlaceholderPainter.drawAnswerPlaceholder(editor, answerPlaceholder, color);
  }

  final Document document = editor.getDocument();
  EditorActionManager.getInstance()
    .setReadonlyFragmentModificationHandler(document, new EduAnswerPlaceholderDeleteHandler(editor));
  EduAnswerPlaceholderPainter.createGuardedBlocks(editor, taskFile);
  editor.getColorsScheme().setColor(EditorColors.READONLY_FRAGMENT_BACKGROUND_COLOR, null);
}
项目:educational-plugin    文件:Task.java   
@NotNull
public String getTestsText(@NotNull final Project project) {
  final Course course = getLesson().getCourse();
  final Language language = course.getLanguageById();
  final EduPluginConfigurator configurator = EduPluginConfigurator.INSTANCE.forLanguage(language);
  final VirtualFile taskDir = getTaskDir(project);
  if (taskDir != null) {
    final VirtualFile file = taskDir.findChild(configurator.getTestFileName());
    if (file == null) return "";
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document != null) {
      return document.getImmutableCharSequence().toString();
    }
  }

  return "";
}
项目:educational-plugin    文件:StudyFillPlaceholdersAction.java   
@Override
public void actionPerformed(AnActionEvent e) {
  final Project project = e.getProject();
  if (project != null) {
    StudyEditor studyEditor = StudyUtils.getSelectedStudyEditor(project);
    StudyState studyState = new StudyState(studyEditor);
    if (!studyState.isValid()) {
      return;
    }
    TaskFile taskFile = studyState.getTaskFile();
    final Document document = studyState.getEditor().getDocument();
    for (AnswerPlaceholder placeholder : taskFile.getActivePlaceholders()) {
      String answer = placeholder.getPossibleAnswer();
      if (answer == null) {
        continue;
      }
      EduUtils.replaceAnswerPlaceholder(document, placeholder, placeholder.getRealLength(), answer);
    }
  }
}
项目:educational-plugin    文件:StudyAnswerPlaceholderExtendWordHandler.java   
@Nullable
private static AnswerPlaceholder getAnswerPlaceholder(PsiElement e, int offset) {
  PsiFile file = e.getContainingFile();
  if (file == null) {
    return null;
  }
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) {
    return null;
  }
  TaskFile taskFile = StudyUtils.getTaskFile(e.getProject(), virtualFile);
  if (taskFile == null) {
    return null;
  }
  Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
  if (document == null) {
    return null;
  }
  Editor editor = FileEditorManager.getInstance(e.getProject()).getSelectedTextEditor();
  return editor == null ? null : taskFile.getAnswerPlaceholder(offset);
}
项目:educational-plugin    文件:StudySerializationUtils.java   
public static Element convertToThirdVersion(Element state, Project project) throws StudyUnrecognizedFormatException {
  Element taskManagerElement = state.getChild(MAIN_ELEMENT);
  XMLOutputter outputter = new XMLOutputter();

  Map<String, String> placeholderTextToStatus = fillStatusMap(taskManagerElement, STUDY_STATUS_MAP, outputter);
  Map<String, String> taskFileToStatusMap = fillStatusMap(taskManagerElement, TASK_STATUS_MAP, outputter);

  Element courseElement = getChildWithName(taskManagerElement, COURSE).getChild(COURSE_TITLED);
  for (Element lesson : getChildList(courseElement, LESSONS)) {
    int lessonIndex = getAsInt(lesson, INDEX);
    for (Element task : getChildList(lesson, TASK_LIST)) {
      String taskStatus = null;
      int taskIndex = getAsInt(task, INDEX);
      Map<String, Element> taskFiles = getChildMap(task, TASK_FILES);
      for (Map.Entry<String, Element> entry : taskFiles.entrySet()) {
        Element taskFileElement = entry.getValue();
        String taskFileText = outputter.outputString(taskFileElement);
        String taskFileStatus = taskFileToStatusMap.get(taskFileText);
        if (taskFileStatus != null && (taskStatus == null || taskFileStatus.equals(StudyStatus.Failed.toString()))) {
          taskStatus = taskFileStatus;
        }
        Document document = StudyUtils.getDocument(project.getBasePath(), lessonIndex, taskIndex, entry.getKey());
        if (document == null) {
          continue;
        }
        for (Element placeholder : getChildList(taskFileElement, ANSWER_PLACEHOLDERS)) {
          taskStatus = addStatus(outputter, placeholderTextToStatus, taskStatus, placeholder);
          addOffset(document, placeholder);
          addInitialState(document, placeholder);
        }
      }
      if (taskStatus != null) {
        addChildWithName(task, STATUS, taskStatus);
      }
    }
  }
  return state;
}
项目:manifold-ij    文件:FileModificationManager.java   
public void transactionCompleted( final Document doc, final PsiFile psiFile )
  {
    VirtualFile file = FileUtil.toVirtualFile( psiFile );
    //System.out.println( psiFile.getText() );
    if( file instanceof VirtualFileWindow )
    {
      file = ((VirtualFileWindow)file).getDelegate();
    }

    final Runnable refresher = new Refresher( _project, file );
    if( TYPE_REFRESH_DELAY_MS == 0 )
    {
      refresher.run();
    }
    else
    {
      _typeRefresher.scheduleTask( getRefreshTaskId( file ), TYPE_REFRESH_DELAY_MS, refresher );
    }

//    // process inner class changes
//    if( psiFile instanceof PsiClassOwner )
//    {
//      _manRefresher.modified( getIFile( psiFile, file ) );
//    }
  }
项目:educational-plugin    文件:EduAnswerPlaceholderPainter.java   
public static void createGuardedBlocks(@NotNull final Editor editor, AnswerPlaceholder placeholder) {
  Document document = editor.getDocument();
  if (document instanceof DocumentImpl) {
    DocumentImpl documentImpl = (DocumentImpl)document;
    List<RangeMarker> blocks = documentImpl.getGuardedBlocks();
    Pair<Integer, Integer> offsets = StudyUtils.getPlaceholderOffsets(placeholder, editor.getDocument());
    Integer start = offsets.first;
    Integer end = offsets.second;
    if (start != 0) {
      createGuardedBlock(editor, blocks, start - 1, start);
    }
    if (end != document.getTextLength()) {
      createGuardedBlock(editor, blocks, end, end + 1);
    }
  }
}
项目:MultiHighlight    文件:ColorPreviewPanel.java   
private void highlightLine(int index, NamedTextAttr namedTextAttr) {
    UIUtil.invokeAndWaitIfNeeded((Runnable) () -> {
        try {
            MarkupModelEx markupModel = myEditor.getMarkupModel();
            final Document doc = markupModel.getDocument();
            final int lineStartOffset = doc.getLineStartOffset(index);
            final int lineEndOffset = doc.getLineEndOffset(index);
            // IDEA-53203: add ERASE_MARKER for manually defined attributes
            markupModel.addRangeHighlighter(lineStartOffset, lineEndOffset,
                    HighlighterLayer.SELECTION - 1, TextAttributes.ERASE_MARKER,
                    HighlighterTargetArea.EXACT_RANGE);
            RangeHighlighter rangeHighlight =
                    markupModel.addRangeHighlighter(lineStartOffset, lineEndOffset,
                            HighlighterLayer.SELECTION - 1, namedTextAttr,
                            HighlighterTargetArea.EXACT_RANGE);
            rangeHighlight.setErrorStripeMarkColor(namedTextAttr.getErrorStripeColor());
            rangeHighlight.setErrorStripeTooltip(namedTextAttr.getName());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
}
项目:educational-plugin    文件:CCChangePlaceholderVisibility.java   
private static void saveIndent(AnswerPlaceholder placeholder, CCState state, boolean visible) {
  Document document = state.getEditor().getDocument();
  int offset = placeholder.getOffset();
  int lineNumber = document.getLineNumber(offset);
  int nonSpaceCharOffset = DocumentUtil.getFirstNonSpaceCharOffset(document, lineNumber);
  int newOffset = offset;
  int endOffset = offset + placeholder.getRealLength();
  if (!visible && nonSpaceCharOffset == offset) {
    newOffset = document.getLineStartOffset(lineNumber);
  }
  if (visible) {
    newOffset = DocumentUtil.getFirstNonSpaceCharOffset(document, offset, endOffset);
  }
  placeholder.setOffset(newOffset);
  int delta = offset - newOffset;
  placeholder.setPossibleAnswer(document.getText(TextRange.create(newOffset, newOffset + delta + placeholder.getRealLength())));
  String oldTaskText = placeholder.getTaskText();
  if (delta >= 0) {
    placeholder.setTaskText(StringUtil.repeat(" ", delta) + oldTaskText);
  }
  else {
    String newTaskText = oldTaskText.substring(Math.abs(delta));
    placeholder.setTaskText(newTaskText);
  }
}
项目:educational-plugin    文件:CCShowPreviewTest.java   
private void doTest(String name) {
  VirtualFile file = configureByTaskFile(name + CCTestsUtil.BEFORE_POSTFIX);
  CCShowPreview action = new CCShowPreview();
  TestActionEvent e = getActionEvent(action,PsiManager.getInstance(getProject()).findFile(file));
  action.beforeActionPerformedUpdate(e);
  assertTrue(e.getPresentation().isEnabled() && e.getPresentation().isVisible());
  action.actionPerformed(e);
  Editor editor = EditorFactory.getInstance().getAllEditors()[1];
  try {
    Pair<Document, List<AnswerPlaceholder>> pair = getPlaceholders(name + CCTestsUtil.AFTER_POSTFIX);
    assertEquals("Files don't match", pair.getFirst().getText(), editor.getDocument().getText());
    for (AnswerPlaceholder placeholder : pair.getSecond()) {
      assertNotNull("No highlighter for placeholder:" + CCTestsUtil.getPlaceholderPresentation(placeholder),
                    getHighlighter(editor.getMarkupModel(), placeholder));
    }
  }
  finally {
    EditorFactory.getInstance().releaseEditor(editor);
  }
}
项目:educational-plugin    文件:CCTestCase.java   
public void checkByFile(TaskFile taskFile, String fileName, boolean useLength) {
  Pair<Document, List<AnswerPlaceholder>> placeholders = getPlaceholders(fileName, useLength, true);
  String message = "Placeholders don't match";
  if (taskFile.getActivePlaceholders().size() != placeholders.second.size()) {
    throw new ComparisonFailure(message,
                                CCTestsUtil.getPlaceholdersPresentation(taskFile.getActivePlaceholders()),
                                CCTestsUtil.getPlaceholdersPresentation(placeholders.second));
  }
  for (AnswerPlaceholder answerPlaceholder : placeholders.getSecond()) {
    AnswerPlaceholder placeholder = taskFile.getAnswerPlaceholder(answerPlaceholder.getOffset());
    if (!CCTestsUtil.comparePlaceholders(placeholder, answerPlaceholder)) {
      throw new ComparisonFailure(message,
                                  CCTestsUtil.getPlaceholdersPresentation(taskFile.getActivePlaceholders()),
                                  CCTestsUtil.getPlaceholdersPresentation(placeholders.second));
    }
  }
}
项目:educational-plugin    文件:CCTestCase.java   
protected VirtualFile configureByTaskFile(String name) {
  Task task = StudyTaskManager.getInstance(getProject()).getCourse().getLessons().get(0).getTaskList().get(0);
  TaskFile taskFile = new TaskFile();
  taskFile.setTask(task);
  task.getTaskFiles().put(name, taskFile);
  VirtualFile file = copyFileToTask(name);

  taskFile.name = name;
  myFixture.configureFromExistingVirtualFile(file);
  Document document = FileDocumentManager.getInstance().getDocument(file);
  for (AnswerPlaceholder placeholder : getPlaceholders(document, false)) {
    taskFile.addAnswerPlaceholder(placeholder);
  }
  taskFile.sortAnswerPlaceholders();
  StudyUtils.drawAllAnswerPlaceholders(myFixture.getEditor(), taskFile);
  return file;
}
项目:yii2support    文件:MissingPropertiesQuickFix.java   
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor problemDescriptor) {
        List<PhpDocPropertyTag> propertyTags = this.comment.getPropertyTags();

        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor == null)
            return;
        Document document = editor.getDocument();
        PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
        TemplateManager templateManager = TemplateManager.getInstance(project);
        Template template = templateManager.createTemplate("", "");
        template.setToReformat(true);
        for (VirtualProperty missingProperty: this.missingProperties)
        {

            String propertyText = "* @property "+ (missingProperty.getType() != null ? missingProperty.getType() : "") + " $" +missingProperty.getName();
            if ( missingProperty.getComment() != null) {
                propertyText += " " + missingProperty.getComment();
            }
            template.addTextSegment("\n" + propertyText);
        }
        template.addTextSegment("\n");

        int offset =  comment.getLastChild().getTextOffset();
        if (propertyTags.size() > 0) {
            PhpDocPropertyTag phpDocPropertyTag = propertyTags.get(comment.getPropertyTags().size() - 1);
            offset = phpDocPropertyTag.getTextOffset() + phpDocPropertyTag.getTextLength();
        }
        editor.getCaretModel().moveToOffset(offset);
        PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
        templateManager.startTemplate(editor, template);
}
项目:GravSupport    文件:LanguageFolderStrategy.java   
@Override
public void initTab(LanguageFileEditorGUI gui) {
    for (VirtualFile file : fileMap.values()) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
        if (psiFile != null) {
            Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
            if (document != null) {
                Editor editorTextField = gui.createEditor(document, project, psiFile.getFileType());
                editorMap.put(psiFile.getVirtualFile().getNameWithoutExtension(), editorTextField);
                gui.addTab(psiFile.getVirtualFile().getNameWithoutExtension(), editorTextField.getComponent());
            }
        }
    }
}
项目:CodeGenerate    文件:TemplateEditPane.java   
private void addVmEditor(String template) {
    EditorFactory factory = EditorFactory.getInstance();
    Document velocityTemplate = factory.createDocument(template);
    editor = factory.createEditor(velocityTemplate, null, FileTypeManager.getInstance()
        .getFileTypeByExtension("vm"), false);
    GridConstraints constraints = new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST,
        GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
        GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(300, 300), null, 0, true);
    editorPane.add(editor.getComponent(), constraints);
}
项目:reasonml-idea-plugin    文件:RefmtManager.java   
void refmt(Project project, String format, Document document) {
    String oldText = document.getText();
    String newText = m_refmtProcess.run(project, format, oldText);
    if (!oldText.isEmpty() && !newText.isEmpty()) { // additional protection
        document.setText(newText);
    }
}
项目:laravel-insight    文件:ScopeCompletionContributor.java   
@Override
public void handleInsert(final InsertionContext context) {
    if (element.getParent() instanceof FieldReference) {
        final Editor     editor     = context.getEditor();
        final CaretModel caretModel = editor.getCaretModel();
        final Document   document   = editor.getDocument();

        document.insertString(caretModel.getOffset(), "()");
        caretModel.moveCaretRelatively(1, 0, false, false, false);
    }
}
项目:greycat-idea-plugin    文件:GCMFoldingBuilder.java   
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull ASTNode node, @NotNull Document document) {
    List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();

    appendDescriptors(node, document, descriptors);
    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
项目:Gherkin-TS-Runner    文件:GherkinIconUtils.java   
private RangeHighlighter createRangeHighlighter(Document document, Editor editor, int fromLine, int toLine, TextAttributes attributes) {
    int lineStartOffset = document.getLineStartOffset(Math.max(0, fromLine));
    int lineEndOffset = document.getLineEndOffset(Math.max(0, toLine));

    return editor.getMarkupModel().addRangeHighlighter(
            lineStartOffset, lineEndOffset, 3333, attributes, HighlighterTargetArea.LINES_IN_RANGE
    );
}
项目:Gherkin-TS-Runner    文件:GherkinFileEditorManagerListener.java   
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
    VirtualFile fileNew = event.getNewFile();
    Editor rootEditor = event.getManager().getSelectedTextEditor();
    if (rootEditor == null) {
        return;
    }

    Document rootDocument = rootEditor.getDocument();
    if (fileNew != null) {
        if (!isFeatureFile(fileNew))
            return;

        String pathNewFile = getRelativePath(fileNew.getPath());

        if (openedGherkinFiles.stream().noneMatch(f -> f.equals(pathNewFile))) {
            openedGherkinFiles.add(pathNewFile);

            GherkinIconUtils gherkinIconUtils = new GherkinIconUtils(pathNewFile);
            gherkinIconUtils.generateGherkinRunIcons(rootDocument, rootEditor);

            GherkinDocumentListener listener = new GherkinDocumentListener(pathNewFile, rootEditor);
            rootDocument.addDocumentListener(listener);

            documentListeners.add(listener);
        }
    }
}