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); }
public static void drawAnswerPlaceholder(@NotNull final Editor editor, @NotNull final AnswerPlaceholder placeholder, @NotNull final JBColor color) { EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); final TextAttributes textAttributes = new TextAttributes(scheme.getDefaultForeground(), scheme.getDefaultBackground(), null, EffectType.BOXED, Font.PLAIN); textAttributes.setEffectColor(color); int startOffset = placeholder.getOffset(); if (startOffset == -1) { return; } final int length = placeholder.isActive() ? placeholder.getRealLength() : placeholder.getVisibleLength(placeholder.getActiveSubtaskIndex()); Pair<Integer, Integer> offsets = StudyUtils.getPlaceholderOffsets(placeholder, editor.getDocument()); startOffset = offsets.first; int endOffset = offsets.second; if (placeholder.isActive()) { drawAnswerPlaceholder(editor, startOffset, endOffset, textAttributes, PLACEHOLDERS_LAYER); } else if (!placeholder.getUseLength() && length != 0) { drawAnswerPlaceholderFromPrevStep(editor, startOffset, endOffset); } }
private void build(int type, PsiFile psiFile, Project project, Editor editor) { switch (type){ case 1: new ParamsStringBuilder().build(psiFile, project, editor); break; case 2: new ParamsFileMapBuilder().build(psiFile, project, editor); break; case 3: new ParamsFilePartBuilder().build(psiFile, project, editor); break; case 4: new ParamsFileBodyBuilder().build(psiFile, project, editor); break; } }
@Override public RenameDialog createRenameDialog( Project project, PsiElement element, PsiElement nameSuggestionContext, Editor editor ) { return new PsiFileRenameDialog( project, element, nameSuggestionContext, editor ) { protected void createNewNameComponent() { super.createNewNameComponent(); getNameSuggestionsField().selectNameWithoutExtension(); } @Override protected NameSuggestionsField getNameSuggestionsField() { return super.getNameSuggestionsField(); } }; }
@Override public void actionPerformed(AnActionEvent e) { final Project project = e.getRequiredData(CommonDataKeys.PROJECT); final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR); final HighlightManager highlightManager = HighlightManager.getInstance(project); final RangeHighlighter[] highlighters = ((HighlightManagerImpl) highlightManager).getHighlighters(editor); for (RangeHighlighter highlighter : highlighters) { final TextAttributes ta = highlighter.getTextAttributes(); if (ta != null && ta instanceof NamedTextAttr && highlighter.getLayer() == HighlighterLayer.SELECTION - 1) { highlightManager.removeSegmentHighlighter(editor, highlighter); } } }
public static PsiElement getHeaderOfValueGroupUnderCaret(@NotNull final Editor editor) { Validate.notNull(editor); final PsiElement psiElementUnderCaret = PsiUtilBase.getElementAtCaret(editor); if (null == psiElementUnderCaret) { return null; } final ImpexValueGroup valueGroup = ImpexPsiUtils.getClosestSelectedValueGroupFromTheSameLine( psiElementUnderCaret); if (null != valueGroup) { final PsiElement header = ImpexPsiUtils.getHeaderForValueGroup(valueGroup); if (null != header) { return header; } } return null; }
public void actionPerformed( AnActionEvent e ) { Editor editor = ( Editor ) e.getDataContext().getData( "editor" ); SelectionModel selectionModel = editor.getSelectionModel(); if ( selectionModel != null ) { String selectedText = selectionModel.getSelectedText(); if ( selectedText != null && selectedText.trim().length() > 0 ) { Project project = ( Project ) e.getDataContext().getData( DataConstants.PROJECT ); String panelid = ( String ) project.getUserData( QuickNotes.KEY_PANELID ); QuickNotesPanel quickNotesPanel = QuickNotesManager.getInstance().getQuickNotesPanel( panelid ); if ( quickNotesPanel != null ) { FileDocumentManager manager = FileDocumentManager.getInstance(); VirtualFile virtualFile = manager.getFile( editor.getDocument() ); quickNotesPanel.addNewNote( "[File: " + virtualFile.getPath() + "]\n" + selectedText ); } } } }
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); }
public GCMStructureViewModel(@NotNull PsiFile psiFile, @NotNull final GCMStructureViewRootElement root, Editor editor) { super(psiFile, root); withSorters(typeSorter, Sorter.ALPHA_SORTER); editor.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void documentChanged(DocumentEvent event) { synchronized (needRefresh) { needRefresh = true; } } }); executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { GCMStructureViewModel.this.refreshView(); } }, 15, 5, TimeUnit.SECONDS); }
private void processSubDec(GCMClassDeclaration o, GCMStructureViewClassElement classElement, Editor editor) { /* for (GCMClassElemDeclaration relDec : o.getClassElemDeclarationList()) { if (relDec.getRelationDeclaration() != null) { GCMStructureViewReferenceElement referenceElement = new GCMStructureViewReferenceElement(relDec.getRelationDeclaration(), editor); classElement.references.add(referenceElement); } else if (relDec.getAttributeDeclaration() != null) { GCMStructureViewAttributeElement attributeElement = new GCMStructureViewAttributeElement(relDec.getAttributeDeclaration(), editor); classElement.attributes.add(attributeElement); } else { System.err.println("Could not find appropriate ClassElem declaration type in processReference for Structure view"); } } */ }
@Override public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { if (!element.isWritable()) return false; boolean isTwigFile = GravFileTemplateUtil.isTwigTemplateFile(element.getContainingFile()) || element.getContainingFile() instanceof HtmlFileImpl; boolean isXmlAttribute = false; if (!isTwigFile) return false; if (element.getParent() instanceof XmlAttributeValueImpl) { XmlAttributeValueImpl parent0 = ((XmlAttributeValueImpl) element.getParent()); boolean hasTwigElement = PsiTreeUtil.findChildOfType(parent0, OuterLanguageElement.class) != null; if (!hasTwigElement && parent0.getParent() instanceof XmlAttributeImpl) { XmlAttributeImpl parent1 = (XmlAttributeImpl) parent0.getParent(); if (parent1.getName().equalsIgnoreCase("href") || parent1.getName().equalsIgnoreCase("src")) isXmlAttribute = true; } } return isXmlAttribute; }
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); } }
/** * 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); }
@Override public Result preprocessEnter( @NotNull PsiFile psiFile, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretOffsetChange, @NotNull DataContext dataContext, @Nullable EditorActionHandler originalHandler) { if (psiFile instanceof SoyFile && isBetweenSiblingTags(psiFile, caretOffset.get())) { if (originalHandler != null) { originalHandler.execute(editor, dataContext); } return Result.Default; } return Result.Continue; }
private static boolean isClearHighlights(@NotNull Editor editor) { if (editor instanceof EditorWindow) { editor = ((EditorWindow) editor).getDelegate(); } final Project project = editor.getProject(); if (project == null) { Log.error("isClearHighlights: editor.getProject() == null"); return false; } int caretOffset = editor.getCaretModel().getOffset(); final RangeHighlighter[] highlighters = ((HighlightManagerImpl) HighlightManager.getInstance(project)).getHighlighters( editor); for (RangeHighlighter highlighter : highlighters) { if (TextRange.create(highlighter).grown(1).contains(caretOffset)) { return true; } } return false; }
@Nullable @Override public PsiElement[] getGotoDeclarationTargets(@Nullable PsiElement psiElement, int i, Editor editor) { if(psiElement == null) { return new PsiElement[0]; } StringLiteralExpression stringLiteral = getStringLiteral(psiElement); if(stringLiteral == null) { return new PsiElement[0]; } return EnvironmentVariablesApi.getKeyDeclarations(psiElement.getProject(), stringLiteral.getContents()); }
private static PsiElement findTargetElement(@NotNull Editor editor, @NotNull PsiFile file) { PsiElement targetElement = TargetElementUtil.findTargetElement(editor, TargetElementUtil.getInstance().getReferenceSearchFlags()); if (targetElement != null && targetElement != file) { if (targetElement instanceof NavigationItem) { targetElement = (targetElement).getNavigationElement(); } if (targetElement instanceof NavigationItem) { return targetElement; } } return null; }
@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); }
private void getTranslation(AnActionEvent event) { Editor mEditor = event.getData(PlatformDataKeys.EDITOR); Project project = event.getData(PlatformDataKeys.PROJECT); String basePath = project.getBasePath(); if (null == mEditor) { return; } SelectionModel model = mEditor.getSelectionModel(); String selectedText = model.getSelectedText(); if (TextUtils.isEmpty(selectedText)) { selectedText = getCurrentWords(mEditor); if (TextUtils.isEmpty(selectedText)) { return; } } String queryText = strip(addBlanks(selectedText)); new Thread(new RequestRunnable(mEditor, queryText,basePath)).start(); }
@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()); } } }
@Override public void actionPerformed(AnActionEvent e) { DataContext dataContext = e.getDataContext(); VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext); Editor editor = CommonDataKeys.EDITOR.getData(dataContext); Project project = CommonDataKeys.PROJECT.getData(dataContext); if (virtualFile == null || project == null || editor == null) { return; } Task task = StudyUtils.getTaskForFile(project, virtualFile); if (task == null) return; if (!(task instanceof TaskWithSubtasks)) { task = convertToTaskWithSubtasks(task, project); } addSubtask((TaskWithSubtasks)task, project); }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor problemDescriptor) { Method method = (Method)methodReference.resolve(); if (method != null) { Parameter[] parameters = method.getParameters(); int paramParameterIndex = ClassUtils.getParamIndex(method, "params"); int conditionParameterIndex = ClassUtils.getParamIndex(method, new String[]{ "condition", "expression", "sql"}); if (paramParameterIndex > -1 && conditionParameterIndex > -1 && conditionParameterIndex == paramParameterIndex - 1 && methodReference.getParameters().length > conditionParameterIndex) { String condition = methodReference.getParameters()[conditionParameterIndex].getText(); String[] conditionParams = DatabaseUtils.extractParamsFromCondition(condition); ArrayCreationExpression array = null; if (methodReference.getParameters().length > paramParameterIndex) { PsiElement paramParameter = methodReference.getParameters()[paramParameterIndex]; if (paramParameter instanceof ArrayCreationExpression) array = (ArrayCreationExpression)paramParameter; paramParameter.delete(); } TemplateManager templateManager = TemplateManager.getInstance(project); Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor == null || methodReference.getParameterList() == null) return; editor.getCaretModel().moveToOffset(methodReference.getParameterList().getLastChild().getTextRange().getEndOffset()); PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument()); Template template = templateManager.createTemplate("", ""); template.setToReformat(true); buildParamArray(template, conditionParams, array, conditionParameterIndex); PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument()); templateManager.startTemplate(editor, template); } } }
@Override public boolean tryToMove(PsiElement element, Project project, DataContext dataContext, @Nullable PsiReference reference, Editor editor) { return CCUtils.isCourseCreator(project); }
@Override public void actionPerformed(AnActionEvent e) { // TODO: insert action logic here PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE); Project project = e.getProject(); Editor editor = e.getData(PlatformDataKeys.EDITOR); TypePickDialog dialog = new TypePickDialog(); dialog.setListener(type -> {build(type, psiFile, project, editor);}); dialog.pack(); dialog.setVisible(true); }
public CCState(@NotNull final TaskFile taskFile, @Nullable final AnswerPlaceholder answerPlaceholder, @NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Project project) { myTaskFile = taskFile; myAnswerPlaceholder = answerPlaceholder; myFile = file; myEditor = editor; myProject = project; }
private PsiClass getPsiClassFromContext(AnActionEvent e) { PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE); Editor editor = e.getData(PlatformDataKeys.EDITOR); if (psiFile == null || editor == null) { return null; } int offset = editor.getCaretModel().getOffset(); PsiElement element = psiFile.findElementAt(offset); return PsiTreeUtil.getParentOfType(element, PsiClass.class); }
private void translate(AnActionEvent e, String sercet, String apiKey) { Editor editor = e.getData(CommonDataKeys.EDITOR); if (editor != null) { String text = editor.getSelectionModel().getSelectedText(); if (text != null) try { text = StringUtil.replace(text, "*", ""); text = StringUtil.replace(text, "\n", ""); text = StringUtil.replace(text, "<tt>", ""); text = StringUtil.replace(text, "</tt>", ""); text = StringUtil.replace(text, "@link", ""); text = StringUtil.replace(text, "{", ""); text = StringUtil.replace(text, "}", ""); String result = HttpClientPool.getHttpClient().get(Constants.genUrl(sercet, apiKey, text)); ApiResult data = gson.fromJson(result, ApiResult.class); if(data.getErrorCode().equals("202")){ Messages.showErrorDialog("请确认setting里面的ApiKey和ApiSecret是否正确","Api验证错误"); }else{ showPop(e, editor, resolveResult(text, data)); } } catch (Exception exception) { onParseError(exception); // if(State.instance().isDebug()){ // Messages.showErrorDialog(exception.toString(),"发生了错误~~"); // } exception.printStackTrace(); } } }
private static void refreshFile(@NotNull final StudyState studyState, @NotNull final Project project) { final Editor editor = studyState.getEditor(); final TaskFile taskFile = studyState.getTaskFile(); final Task task = taskFile.getTask(); if (task instanceof TaskWithSubtasks) { for (AnswerPlaceholder placeholder : taskFile.getActivePlaceholders()) { StudySubtaskUtils.refreshPlaceholder(editor, placeholder); } } else { if (!resetTaskFile(editor.getDocument(), project, taskFile)) { Messages.showInfoMessage("The initial text of task file is unavailable", "Failed to Refresh Task File"); return; } if (task instanceof ChoiceTask) { final StudyToolWindow window = StudyUtils.getStudyToolWindow(project); if (window != null) { window.setBottomComponent(new StudyChoiceVariantsPanel((ChoiceTask)task)); } } } WolfTheProblemSolver.getInstance(project).clearProblems(studyState.getVirtualFile()); taskFile.setHighlightErrors(false); StudyUtils.drawAllAnswerPlaceholders(editor, taskFile); EduAnswerPlaceholderPainter.createGuardedBlocks(editor, taskFile); ApplicationManager.getApplication().invokeLater( () -> IdeFocusManager.getInstance(project).requestFocus(editor.getContentComponent(), true)); StudyNavigator.navigateToFirstAnswerPlaceholder(editor, taskFile); showBalloon(project, MessageType.INFO); }
private static int getWordAtCaretStart( Project project, String filePath ) { Editor[] editor = new Editor[1]; editor[0] = getActiveEditor( project ); if( !(editor[0] instanceof EditorImpl) ) { return -1; } EditorImpl editorImpl = (EditorImpl)editor[0]; if( !editorImpl.getVirtualFile().getPath().equals( filePath ) ) { return -1; } CaretModel cm = editorImpl.getCaretModel(); Document document = editorImpl.getDocument(); int offset = cm.getOffset(); if( offset == 0 ) { return 0; } int lineNumber = cm.getLogicalPosition().line; int newOffset = offset - 1; int minOffset = lineNumber > 0 ? document.getLineEndOffset( lineNumber - 1 ) : 0; for( ; newOffset > minOffset; newOffset-- ) { if( EditorActionUtil.isWordOrLexemeStart( editorImpl, newOffset, false ) ) { break; } } return newOffset; }
public 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])) { Logger.warn("Caret not in a word"); 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; } String ret = new String(chars, start, end-start); Logger.info("Selected words: " + ret); return ret; }
@NotNull private static Result handleTyping(Project project, Editor editor, PsiFile file, boolean showBaloon) { if (!StudyUtils.isStudyProject(project)) { return Result.CONTINUE; } TaskFile taskFile = StudyUtils.getTaskFile(project, file.getVirtualFile()); if (taskFile == null || !(taskFile.getTask() instanceof TaskWithSubtasks)) { return Result.CONTINUE; } int offset = editor.getCaretModel().getOffset(); if (CCUtils.isCourseCreator(project)) { AnswerPlaceholder placeholder = StudyUtils.getAnswerPlaceholder(offset, taskFile.getAnswerPlaceholders()); if (placeholder == null || placeholder.isActive()) { return Result.CONTINUE; } if (showBaloon) { Integer toSubtask = Collections.max(placeholder.getSubtaskInfos().keySet().stream() .filter(k -> k < ((TaskWithSubtasks)taskFile.getTask()).getActiveSubtaskIndex()) .collect(Collectors.toList())); int userVisibleSubtaskNum = toSubtask + 1; String text = String .format("<html>To edit this placeholder <a href=\"%s\">activate</a> it or <a href=\"%s\">switch to subtask %d</a></html>", ACTIVATE, SWITCH, userVisibleSubtaskNum); MyHyperlinkAdapter listener = new MyHyperlinkAdapter(taskFile, placeholder, file, editor, project, toSubtask); Balloon balloon = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(text, null, MessageType.WARNING.getPopupBackground(), listener) .setHideOnLinkClick(true).createBalloon(); balloon.show(JBPopupFactory.getInstance().guessBestPopupLocation(editor), Balloon.Position.below); } return Result.STOP; } boolean insidePlaceholder = taskFile.getAnswerPlaceholder(offset) != null; if (!insidePlaceholder) { HintManager.getInstance().showInformationHint(editor, "Text outside of placeholders is not editable in this task"); } return insidePlaceholder ? Result.CONTINUE : Result.STOP; }
public ImpexTableFormatAction() { super(new ImpexTableActionHandler() { @Override protected Runnable action(Editor editor) { return new FormatTableOperation(new ImpexTableEditor(editor)); } }); }
@NotNull private static Function<PsiLet, LogicalPosition> letExpressionToLogicalPosition(Editor selectedTextEditor) { return letStatement -> { PsiElement letName = letStatement.getNameIdentifier(); if (letName == null) { return null; } int nameOffset = letName.getTextOffset(); return selectedTextEditor.offsetToLogicalPosition(nameOffset); }; }
@Contract protected boolean isAlreadyHighlighted( @NotNull final Editor editor, @Nullable final List<PsiElement> column ) { Validate.notNull(editor); return Objects.equals(cache.getIfPresent(editor), column); }
@Override public void performAnswerPlaceholderAction(@NotNull CCState state) { Editor editor = state.getEditor(); final int offset = editor.getCaretModel().getOffset(); TaskFile taskFile = state.getTaskFile(); final Task task = state.getTaskFile().getTask(); if (!(task instanceof TaskWithSubtasks)) return; int subtaskIndex = ((TaskWithSubtasks)task).getActiveSubtaskIndex(); AnswerPlaceholder existingPlaceholder = StudyUtils.getAnswerPlaceholder(offset, taskFile.getAnswerPlaceholders()); if (existingPlaceholder == null) { return; } AnswerPlaceholderSubtaskInfo info = getInfo(state, subtaskIndex, existingPlaceholder); if (info == null) { return; } EduUtils.runUndoableAction(state.getProject(), getTitle(), new BasicUndoableAction(state.getEditor().getDocument()) { @Override public void undo() throws UnexpectedUndoException { undoAction(existingPlaceholder, subtaskIndex, info); StudyUtils.drawAllAnswerPlaceholders(editor, taskFile); } @Override public void redo() throws UnexpectedUndoException { redoAction(existingPlaceholder, subtaskIndex, info); StudyUtils.drawAllAnswerPlaceholders(editor, taskFile); } }); }
public static void setLine(Editor editor, int line, int column) { if (editor != null) { try { int startOffset = editor.logicalPositionToOffset(new LogicalPosition(line, column)); editor.getCaretModel().moveToOffset(startOffset); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); editor.getSelectionModel().setSelection(startOffset, startOffset); } catch (Exception e) { // do nothing } } }
private static void searchSelection(Editor editor, Project project) { final SelectionModel selectionModel = editor.getSelectionModel(); if (!selectionModel.hasSelection()) { selectionModel.selectWordAtCaret(false); } final String text = selectionModel.getSelectedText(); if (text == null) { return; } if (editor instanceof EditorWindow) { // highlightUsages selection in the whole editor, not injected fragment only editor = ((EditorWindow) editor).getDelegate(); } EditorSearchSession oldSearch = EditorSearchSession.get(editor); if (oldSearch != null) { if (oldSearch.hasMatches()) { String oldText = oldSearch.getTextInField(); if (!oldSearch.getFindModel().isRegularExpressions()) { oldText = StringUtil.escapeToRegexp(oldText); oldSearch.getFindModel().setRegularExpressions(true); } String newText = oldText + '|' + StringUtil.escapeToRegexp(text); oldSearch.setTextInField(newText); return; } } EditorSearchSession.start(editor, project).getFindModel().setRegularExpressions(false); }
public void update(AnActionEvent event) { Project project = getEventProject(event); if (project == null) { this.setStatus(event, false); return; } if (DumbService.isDumb(project)) { this.setStatus(event, false); return; } DataContext dataContext = event.getDataContext(); final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); final PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext); final PhpClass targetClass = editor == null || file == null ? null : PhpCodeEditUtil.findClassAtCaret(editor, file); if (targetClass == null) { setStatus(event, false); return; } if (ExtensionUtility.getExtensionDirectory(event) == null) { this.setStatus(event, false); return; } this.setStatus(event, PhpElementsUtil.hasSuperClass(targetClass, "\\TYPO3\\CMS\\Extbase\\Mvc\\Controller\\AbstractController")); }