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: educational-plugin   File: EduAnswerPlaceholderPainter.java   Source Code and License 7 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 2
Project: yii2support   File: ValidationCompletionProvider.java   Source Code and License 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 3
Project: yii2support   File: FieldAttributesCompletionProvider.java   Source Code and License 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: yii2support   File: ObjectFactoryCompletionProvider.java   Source Code and License 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 5
Project: intellij-csv-validator   File: CsvIntentionHelper.java   Source Code and License 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 6
Project: reasonml-idea-plugin   File: FoldingBuilder.java   Source Code and License 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 7
Project: idea-php-typo3-plugin   File: RouteFoldingBuilder.java   Source Code and License 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 8
Project: laravel-insight   File: BladeFoldingBuilder.java   Source Code and License 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 9
Project: intellij-csv-validator   File: CsvIntentionHelper.java   Source Code and License 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 10
Project: Gherkin-TS-Runner   File: GherkinIconUtils.java   Source Code and License 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 11
Project: bamboo-soy   File: SoyDocumentationProvider.java   Source Code and License 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 12
Project: bamboo-soy   File: ClosingTagHandler.java   Source Code and License 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 13
Project: bamboo-soy   File: EnterHandler.java   Source Code and License 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 14
Project: bamboo-soy   File: EnterHandler.java   Source Code and License 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 15
Project: GravSupport   File: LanguageFileStrategy.java   Source Code and License 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 16
Project: manifold-ij   File: FakeTargetElement.java   Source Code and License 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 17
Project: intellij-randomness   File: DataInsertAction.java   Source Code and License 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 18
Project: EmojiPrefix   File: EmojiResourceCompletionContributor.java   Source Code and License 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 19
Project: AndroidSourceViewer   File: DiffSourceAction.java   Source Code and License 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 20
Project: SearchResourcePlugin   File: SearchResourcesAction.java   Source Code and License 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 21
Project: manifold-ij   File: IjFile.java   Source Code and License 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 22
Project: educational-plugin   File: StudyUtils.java   Source Code and License 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 23
Project: educational-plugin   File: Task.java   Source Code and License 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 24
Project: educational-plugin   File: StudyFillPlaceholdersAction.java   Source Code and License 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 25
Project: educational-plugin   File: StudyAnswerPlaceholderExtendWordHandler.java   Source Code and License 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 26
Project: educational-plugin   File: StudySerializationUtils.java   Source Code and License 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 27
Project: manifold-ij   File: FileModificationManager.java   Source Code and License 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 28
Project: MultiHighlight   File: ColorPreviewPanel.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
        }
    }
}
 
Example 41
Project: GravSupport   File: LanguageFolderStrategy.java   Source Code and License 5 votes vote down vote up
@Override
protected void updateDocumentHook(Document document, Project project, String lang, String key, String value, TranslationTableModel model) {
    if (!document.isWritable()) {
        return;
    }
    PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (psiFile != null) {
        YAMLKeyValue yamlKeyValue = yamlUtil.createI18nRecord((YAMLFile) psiFile, key, value);
        model.addElement(lang, yamlKeyValue, key);
        PsiDocumentManager.getInstance(project).commitDocument(document);
    }
}
 
Example 42
Project: idea-php-dotenv-plugin   File: DotEnvCommenter.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public CommenterDataHolder createBlockCommentingState(int selectionStart,
                                                      int selectionEnd,
                                                      @NotNull Document document,
                                                      @NotNull PsiFile file) {
    return null;
}
 
Example 43
Project: idea-php-dotenv-plugin   File: DotEnvCommenter.java   Source Code and License 5 votes vote down vote up
@Override
public void uncommentLine(int line, int offset, @NotNull Document document, @NotNull CommenterDataHolder data) {
    if(document.getText().charAt(offset) == '#') {
        document.deleteString(offset, offset + HASH_COMMENT_PREFIX.length());
    } else {
        document.deleteString(offset, offset + SLASH_COMMENT_PREFIX.length());
    }
}
 
Example 44
Project: idea-php-dotenv-plugin   File: DotEnvCommenter.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public TextRange getBlockCommentRange(int selectionStart,
                                      int selectionEnd,
                                      @NotNull Document document,
                                      @NotNull CommenterDataHolder data) {
    throw new UnsupportedOperationException();
}
 
Example 45
Project: sercapnp   File: GenerateCapnpID.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    //Get all the required data from data keys
    final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
    final Project project = e.getRequiredData(CommonDataKeys.PROJECT);
    //Access document, caret, and selection
    final Document document = editor.getDocument();
    final SelectionModel selectionModel = editor.getSelectionModel();

    final int start = selectionModel.getSelectionStart();
    final int end = selectionModel.getSelectionEnd();
    //New instance of Runnable to make a replacement
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //  return hex(random.randint(0, 2 ** 64) | 1 << 63)
            // from 0 to 64
            BigInteger rand = new BigInteger(64, new Random());
            rand = rand.or(new BigInteger("1").shiftLeft(63));
            String capnpId = rand.toString(16);
            document.setText( String.format("@0x%s; \n\n", capnpId) + document.getText());
        }
    };
    //Making the replacement
    WriteCommandAction.runWriteCommandAction(project, runnable);
    selectionModel.removeSelection();
}
 
Example 46
Project: GoogleTranslation   File: GoogleTranslation.java   Source Code and License 5 votes vote down vote up
private String getCurrentWords(Editor editor) {
    Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    int caretOffset = caretModel.getOffset();
    int lineNum = document.getLineNumber(caretOffset);
    int lineStartOffset = document.getLineStartOffset(lineNum);
    int lineEndOffset = document.getLineEndOffset(lineNum);
    String lineContent = document.getText(new TextRange(lineStartOffset, lineEndOffset));
    char[] chars = lineContent.toCharArray();
    int start = 0, end = 0, cursor = caretOffset - lineStartOffset;

    if (!Character.isLetter(chars[cursor])) {
        return null;
    }

    for (int ptr = cursor; ptr >= 0; ptr--) {
        if (!Character.isLetter(chars[ptr])) {
            start = ptr + 1;
            break;
        }
    }

    int lastLetter = 0;
    for (int ptr = cursor; ptr < lineEndOffset - lineStartOffset; ptr++) {
        lastLetter = ptr;
        if (!Character.isLetter(chars[ptr])) {
            end = ptr;
            break;
        }
    }
    if (end == 0) {
        end = lastLetter + 1;
    }

    return new String(chars, start, end - start);
}
 
Example 47
Project: idea-onescript   File: OneScriptFoldingBuilder.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement psiElement, @NotNull Document document, boolean b) {
    List<FoldingDescriptor> descriptors = new ArrayList<>();
    Collection<OneScriptSubdeclaration> subs = PsiTreeUtil.findChildrenOfType(psiElement, OneScriptSubdeclaration.class);
    for (final OneScriptSubdeclaration sub : subs) {
        final String subName = sub.getSubName().getText();

        PsiElement endOfSub = sub.getNextSibling();
        while (endOfSub != null && !(endOfSub instanceof OneScriptEndOfSub)) {
            endOfSub = endOfSub.getNextSibling();
        }

        if (endOfSub == null) {
            continue;
        }

        TextRange r = new TextRange(sub.getTextRange().getStartOffset(), endOfSub.getTextRange().getEndOffset());
        FoldingDescriptor d = new FoldingDescriptor(sub.getNode(), r) {
            @Nullable
            @Override
            public String getPlaceholderText() {
                return subName;
            }
        };
        descriptors.add(d);
    }
    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
 
Example 48
Project: deps-checker   File: VirtualFileHelper.java   Source Code and License 5 votes vote down vote up
public static void save(VirtualFile file, String content)
{
    FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
    Document document = fileDocumentManager.getDocument(file);
    if (document != null)
    {
        document.setText(content);
        fileDocumentManager.saveDocument(document);
    }
}
 
Example 49
Project: hybris-integration-intellij-idea-plugin   File: ImpexFoldingBuilder.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(
    @NotNull final PsiElement root,
    @NotNull final Document document,
    final boolean quick
) {
    if (this.isFoldingDisabled()) {
        return EMPTY_ARRAY;
    }

    Validate.notNull(root);
    Validate.notNull(document);

    final Collection<PsiElement> psiElements = this.findFoldingBlocksAndLineBreaks(root);

    FoldingGroup currentLineGroup = FoldingGroup.newGroup(GROUP_NAME);

    /* Avoid spawning a lot of unnecessary objects for each line break. */
    boolean groupIsNotFresh = false;

    final List<FoldingDescriptor> descriptors = newArrayList();
    for (final PsiElement psiElement : psiElements) {

        if (isLineBreak(psiElement)) {
            if (groupIsNotFresh) {
                currentLineGroup = FoldingGroup.newGroup(GROUP_NAME);
                groupIsNotFresh = false;
            }
        } else {
            descriptors.add(new ImpexFoldingDescriptor(psiElement, currentLineGroup));
            groupIsNotFresh = true;
        }
    }

    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
 
Example 50
Project: educational-plugin   File: PyStudySmartChecker.java   Source Code and License 5 votes vote down vote up
static void runSmartTestProcess(@NotNull final VirtualFile taskDir,
                                       @NotNull final PyStudyTestRunner testRunner,
                                       @NotNull final String taskFileName,
                                       @NotNull final TaskFile taskFile,
                                       @NotNull final Project project) {
  final VirtualFile virtualFile = taskDir.findFileByRelativePath(taskFileName);
  if (virtualFile == null) {
    return;
  }
  Pair<VirtualFile, TaskFile> pair = getCopyWithAnswers(taskDir, virtualFile, taskFile);
  if (pair == null) {
    return;
  }
  VirtualFile answerFile = pair.getFirst();
  TaskFile answerTaskFile = pair.getSecond();
  try {
    for (final AnswerPlaceholder answerPlaceholder : answerTaskFile.getActivePlaceholders()) {
      final Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
      if (document == null) {
        continue;
      }
      smartCheck(answerPlaceholder, project, answerFile, answerTaskFile, taskFile, testRunner,
                 virtualFile, document);
    }
  }
  finally {
    StudyUtils.deleteFile(answerFile);
  }
}
 
Example 51
Project: intellij-csv-validator   File: CsvIntentionHelper.java   Source Code and License 5 votes vote down vote up
public static void quoteAll(@NotNull Project project, @NotNull PsiFile psiFile) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
        List<Integer> quotePositions = new ArrayList<>();
        Collection<PsiElement> fields = getAllFields(psiFile);
        PsiElement separator;
        for (PsiElement field : fields) {
            if (field.getFirstChild() == null || getElementType(field.getFirstChild()) != CsvTypes.QUOTE) {
                separator = getPreviousSeparator(field);
                if (separator == null) {
                    quotePositions.add(field.getParent().getTextOffset());
                } else {
                    quotePositions.add(separator.getTextOffset() + separator.getTextLength());
                }
            }
            if (field.getLastChild() == null || getElementType(field.getLastChild()) != CsvTypes.QUOTE) {
                separator = getNextSeparator(field);
                if (separator == null) {
                    quotePositions.add(field.getParent().getTextOffset() + field.getParent().getTextLength());
                } else {
                    quotePositions.add(separator.getTextOffset());
                }
            }
        }
        String text = addQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 52
Project: educational-plugin   File: StudyUtils.java   Source Code and License 5 votes vote down vote up
public static void deleteGuardedBlocks(@NotNull final Document document) {
  if (document instanceof DocumentImpl) {
    final DocumentImpl documentImpl = (DocumentImpl)document;
    List<RangeMarker> blocks = documentImpl.getGuardedBlocks();
    for (final RangeMarker block : blocks) {
      ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> document.removeGuardedBlock(block)));
    }
  }
}
 
Example 53
Project: educational-plugin   File: StudyUtils.java   Source Code and License 5 votes vote down vote up
@Nullable
public static Document getDocument(String basePath, int lessonIndex, int taskIndex, String fileName) {
  String taskPath = FileUtil.join(basePath, EduNames.LESSON + lessonIndex, EduNames.TASK + taskIndex);
  VirtualFile taskFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.join(taskPath, fileName));
  if (taskFile == null) {
    taskFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.join(taskPath, EduNames.SRC, fileName));
  }
  if (taskFile == null) {
    return null;
  }
  return FileDocumentManager.getInstance().getDocument(taskFile);
}
 
Example 54
Project: educational-plugin   File: StudyUtils.java   Source Code and License 5 votes vote down vote up
public static Pair<Integer, Integer> getPlaceholderOffsets(@NotNull final AnswerPlaceholder answerPlaceholder,
                                                           @NotNull final Document document) {
  int startOffset = answerPlaceholder.getOffset();
  int delta = 0;
  final int length = answerPlaceholder.getRealLength();
  int nonSpaceCharOffset = DocumentUtil.getFirstNonSpaceCharOffset(document, startOffset, startOffset + length);
  if (nonSpaceCharOffset != startOffset) {
    delta = startOffset - nonSpaceCharOffset;
    startOffset = nonSpaceCharOffset;
  }
  final int endOffset = startOffset + length + delta;
  return Pair.create(startOffset, endOffset);
}
 
Example 55
Project: intellij-csv-validator   File: CsvValidationInspection.java   Source Code and License 5 votes vote down vote up
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        document.setText(document.getText() + "\"");
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 56
Project: educational-plugin   File: EduStepicConnector.java   Source Code and License 5 votes vote down vote up
public static void postSolution(@NotNull final Task task, boolean passed, @NotNull final Project project) {
  if (task.getStepId() <= 0) {
    return;
  }

  try {
    final String response = postAttempt(task.getStepId());
    if (response.isEmpty()) return;
    final StepicWrappers.AttemptWrapper.Attempt attempt =
      new Gson().fromJson(response, StepicWrappers.AttemptContainer.class).attempts.get(0);
    final Map<String, TaskFile> taskFiles = task.getTaskFiles();
    final ArrayList<StepicWrappers.SolutionFile> files = new ArrayList<>();
    final VirtualFile taskDir = task.getTaskDir(project);
    if (taskDir == null) {
      LOG.error("Failed to find task directory " + task.getName());
      return;
    }
    for (TaskFile fileEntry : taskFiles.values()) {
      final String fileName = fileEntry.name;
      final VirtualFile virtualFile = taskDir.findFileByRelativePath(fileName);
      if (virtualFile != null) {
        ApplicationManager.getApplication().runReadAction(() -> {
          final Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
          if (document != null) {
            files.add(new StepicWrappers.SolutionFile(fileName, document.getCharsSequence().toString()));
          }
        });
      }
    }

    postSubmission(passed, attempt, files);
  }
  catch (IOException e) {
    LOG.error(e.getMessage());
  }
}
 
Example 57
Project: educational-plugin   File: StudyRefreshTaskFileAction.java   Source Code and License 5 votes vote down vote up
private static boolean resetTaskFile(@NotNull final Document document,
                                     @NotNull final Project project,
                                     TaskFile taskFile) {
  resetDocument(document, taskFile);
  final Task task = taskFile.getTask();
  task.setStatus(StudyStatus.Unchecked);
  if (task instanceof ChoiceTask) {
    ((ChoiceTask)task).setSelectedVariants(new ArrayList<>());
  }
  resetAnswerPlaceholders(taskFile, project);
  ProjectView.getInstance(project).refresh();
  StudyUtils.updateToolWindows(project);
  return true;
}
 
Example 58
Project: educational-plugin   File: StudyRefreshTaskFileAction.java   Source Code and License 5 votes vote down vote up
private static void resetDocument(@NotNull final Document document,
                                     @NotNull final TaskFile taskFile) {
  StudyUtils.deleteGuardedBlocks(document);
  taskFile.setTrackChanges(false);
  clearDocument(document);

  document.setText(taskFile.text);
  taskFile.setTrackChanges(true);
}
 
Example 59
Project: intellij-csv-validator   File: CsvValidationInspection.java   Source Code and License 5 votes vote down vote up
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        String text = document.getText();
        document.setText(text.substring(0, element.getTextOffset()) + CsvCodeStyleSettings.getCurrentSeparator(project) + text.substring(element.getTextOffset()));
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 60
Project: educational-plugin   File: StudySerializationUtils.java   Source Code and License 5 votes vote down vote up
private static void convertToAbsoluteOffset(JsonObject taskFileObject, JsonObject placeholderObject) {
  int line = placeholderObject.getAsJsonPrimitive(LINE).getAsInt();
  int start = placeholderObject.getAsJsonPrimitive(START).getAsInt();
  if (line == -1) {
    placeholderObject.addProperty(OFFSET, start);
  }
  else {
    Document document = EditorFactory.getInstance().createDocument(taskFileObject.getAsJsonPrimitive(TEXT).getAsString());
    placeholderObject.addProperty(OFFSET, document.getLineStartOffset(line) + start);
  }
}