Java Code Examples for com.intellij.openapi.editor.Document

The following are top voted examples for showing how to use com.intellij.openapi.editor.Document. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: yii2support   File: ValidationCompletionProvider.java   View source code 6 votes vote down vote up
@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;
}
 
Example 2
Project: yii2support   File: FieldAttributesCompletionProvider.java   View source code 6 votes vote down vote up
@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;
}
 
Example 3
Project: yii2support   File: ObjectFactoryCompletionProvider.java   View source code 6 votes vote down vote up
@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;
}
 
Example 4
Project: intellij-csv-validator   File: CsvIntentionHelper.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 5
Project: reasonml-idea-plugin   File: FoldingBuilder.java   View source code 6 votes vote down vote up
@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()]);
}
 
Example 6
Project: idea-php-typo3-plugin   File: RouteFoldingBuilder.java   View source code 6 votes vote down vote up
@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()]);
}
 
Example 7
Project: laravel-insight   File: BladeFoldingBuilder.java   View source code 6 votes vote down vote up
@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()]);
}
 
Example 8
Project: intellij-csv-validator   File: CsvIntentionHelper.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 9
Project: Gherkin-TS-Runner   File: GherkinIconUtils.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 10
Project: bamboo-soy   File: SoyDocumentationProvider.java   View source code 6 votes vote down vote up
@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();
}
 
Example 11
Project: bamboo-soy   File: ClosingTagHandler.java   View source code 6 votes vote down vote up
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());

}
 
Example 12
Project: bamboo-soy   File: EnterHandler.java   View source code 6 votes vote down vote up
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());
  }
}
 
Example 13
Project: bamboo-soy   File: EnterHandler.java   View source code 6 votes vote down vote up
@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;
}
 
Example 14
Project: GravSupport   File: LanguageFileStrategy.java   View source code 6 votes vote down vote up
@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());
        }
    }
}
 
Example 15
Project: manifold-ij   File: FakeTargetElement.java   View source code 6 votes vote down vote up
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();
}
 
Example 16
Project: intellij-randomness   File: DataInsertAction.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 17
Project: EmojiPrefix   File: EmojiResourceCompletionContributor.java   View source code 6 votes vote down vote up
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);
								}
							}));
				}
			}
		}
	});
}
 
Example 18
Project: AndroidSourceViewer   File: DiffSourceAction.java   View source code 6 votes vote down vote up
/**
 * 调用 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());
            }
        }
    });
}
 
Example 19
Project: SearchResourcePlugin   File: SearchResourcesAction.java   View source code 6 votes vote down vote up
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);
}
 
Example 20
Project: manifold-ij   File: IjFile.java   View source code 6 votes vote down vote up
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;
}
 
Example 21
Project: educational-plugin   File: StudyUtils.java   View source code 6 votes vote down vote up
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);
}
 
Example 22
Project: educational-plugin   File: Task.java   View source code 6 votes vote down vote up
@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 "";
}
 
Example 23
Project: educational-plugin   File: StudyFillPlaceholdersAction.java   View source code 6 votes vote down vote up
@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);
    }
  }
}
 
Example 24
Project: educational-plugin   File: StudyAnswerPlaceholderExtendWordHandler.java   View source code 6 votes vote down vote up
@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);
}
 
Example 25
Project: educational-plugin   File: StudySerializationUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 26
Project: manifold-ij   File: FileModificationManager.java   View source code 6 votes vote down vote up
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 ) );
//    }
  }
 
Example 27
Project: educational-plugin   File: EduAnswerPlaceholderPainter.java   View source code 6 votes vote down vote up
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);
    }
  }
}
 
Example 28
Project: MultiHighlight   File: ColorPreviewPanel.java   View source code 6 votes vote down vote up
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);
        }
    });
}
 
Example 29
Project: educational-plugin   File: CCChangePlaceholderVisibility.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 30
Project: educational-plugin   File: CCShowPreviewTest.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 31
Project: educational-plugin   File: CCTestCase.java   View source code 6 votes vote down vote up
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));
    }
  }
}
 
Example 32
Project: educational-plugin   File: CCTestCase.java   View source code 6 votes vote down vote up
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;
}
 
Example 33
Project: yii2support   File: MissingPropertiesQuickFix.java   View source code 5 votes vote down vote up
@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);
}
 
Example 34
Project: GravSupport   File: LanguageFolderStrategy.java   View source code 5 votes vote down vote up
@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());
            }
        }
    }
}
 
Example 35
Project: CodeGenerate   File: TemplateEditPane.java   View source code 5 votes vote down vote up
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);
}
 
Example 36
Project: reasonml-idea-plugin   File: RefmtManager.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 37
Project: laravel-insight   File: ScopeCompletionContributor.java   View source code 5 votes vote down vote up
@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);
    }
}
 
Example 38
Project: greycat-idea-plugin   File: GCMFoldingBuilder.java   View source code 5 votes vote down vote up
@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()]);
}
 
Example 39
Project: Gherkin-TS-Runner   File: GherkinIconUtils.java   View source code 5 votes vote down vote up
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
    );
}
 
Example 40
Project: Gherkin-TS-Runner   File: GherkinFileEditorManagerListener.java   View source code 5 votes vote down vote up
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);
        }
    }
}