@Override public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { IDocument document = viewer.getDocument(); if (document == null) { return null; } String source = document.get(); Set<String> words = simpleWordCompletion.calculate(source, offset); ICompletionProposal[] result = new ICompletionProposal[words.size()]; int i = 0; for (String word : words) { result[i++] = new SimpleWordProposal(document, offset, word); } return result; }
@Override public void apply(IDocument document) { // the proposal shall enter always a space after applyment... String proposal = word; if (isAddingSpaceAtEnd()) { proposal += " "; } int zeroOffset = offset - textBefore.length(); try { document.replace(zeroOffset, textBefore.length(), proposal); nextSelection = zeroOffset + proposal.length(); } catch (BadLocationException e) { BatchEditorUtil.logError("Not able to replace by proposal:" + word +", zero offset:"+zeroOffset+", textBefore:"+textBefore, e); } }
public static HashMap<String, IRegion> getPartitionsInfoByType(IDocument document, String partitionType) { HashMap<String, IRegion> lines = new HashMap<String, IRegion>(); final Scanner scanner = new Scanner(document.get()); int lineNumber = 0; try { while (scanner.hasNextLine()) { final String line = scanner.nextLine(); final int offset = document.getLineOffset(lineNumber); if (document.getPartition(offset).getType().equals(partitionType)) { lines.put(line, document.getLineInformation(lineNumber)); } lineNumber++; } } catch (BadLocationException e) { e.printStackTrace(); } finally { if (scanner != null) scanner.close(); } return lines; }
@Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { initIfNeeded(); IDocument document = viewer.getDocument(); if (fTextViewer == null) { fTextViewer = viewer; } // don't eat if not in preferences, XOR with modifier key 1 (Ctrl) // but: if there is a selection, replace it! Point selection = viewer.getSelectedRange(); fToggleEating = (stateMask & SWT.MOD1) != 0; int newLength = selection.x + selection.y - getReplacementOffset(); if ((insertCompletion() ^ fToggleEating) && newLength >= 0) { setReplacementLength(newLength); } apply(document, trigger, offset); fToggleEating = false; }
@Override public IDocument getDocument(Object element) { IDocument document = super.getDocument(element); if (document == null) { return null; } IDocumentPartitioner formerPartitioner = document.getDocumentPartitioner(); if (formerPartitioner instanceof BatchPartitioner) { return document; } /* installation necessary */ IDocumentPartitioner partitioner = BatchPartionerFactory.create(); partitioner.connect(document); document.setDocumentPartitioner(partitioner); return document; }
public void moveTo(String handlerName) { IEditorPart editor = PlatformUI .getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .getActiveEditor(); if (editor instanceof JscriptTransactionEditor) { JscriptTransactionEditor myEditor = (JscriptTransactionEditor) editor; MyJScriptEditor jsEditor = myEditor.getEditor(); IDocumentProvider provider = jsEditor.getDocumentProvider(); IDocument document = provider.getDocument(editor.getEditorInput()); String content = document.get(); int index = content.indexOf(handlerName); jsEditor.selectAndReveal(index, handlerName.length()); } }
public static String getLineByOffset(IDocument document, int offset) { final Scanner scanner = new Scanner(document.get()); int lineNumber = 0; try { while (scanner.hasNextLine()) { final String line = scanner.nextLine(); if (lineNumber == document.getLineOfOffset(offset)) { return line; } lineNumber++; } } catch (BadLocationException e) { e.printStackTrace(); } finally { if (scanner != null) scanner.close(); } return ""; }
@Override public boolean validate(IDocument document, int offset, DocumentEvent event) { try { String content = document.get(fReplacementPosition.getOffset(), offset - fReplacementPosition.getOffset()); if (fReplacementString.startsWith(content)) { return true; } else if (fReplacementString.length() > 0) { char c = fReplacementString.charAt(0); if ((c == '"' || c == '\'') && fReplacementString.startsWith(c + content)) { return true; } } } catch (BadLocationException e) { // ignore concurrently modified document } return false; }
protected int getOffsetAdjustment(IDocument document, int offset, int length) { if (length == 0 || Math.abs(length) > 1) return 0; try { if (length < 0) { if (isOpeningBracket(document.getChar(offset))) { return 1; } } else { if (isClosingBracket(document.getChar(offset - 1))) { return -1; } } } catch (BadLocationException e) { // do nothing } return 0; }
@Override public void apply(IDocument document) { // the proposal shall enter always a space after applyment... String proposal = word; if (isAddingSpaceAtEnd()) { proposal += " "; } int zeroOffset = offset - textBefore.length(); try { document.replace(zeroOffset, textBefore.length(), proposal); nextSelection = zeroOffset + proposal.length(); } catch (BadLocationException e) { BashEditorUtil.logError("Not able to replace by proposal:" + word +", zero offset:"+zeroOffset+", textBefore:"+textBefore, e); } }
@Override public IDocument getDocument(Object element) { IDocument document = super.getDocument(element); if (document == null) { return null; } IDocumentPartitioner formerPartitioner = document.getDocumentPartitioner(); if (formerPartitioner instanceof BashPartitioner) { return document; } /* installation necessary */ IDocumentPartitioner partitioner = BashPartionerFactory.create(); partitioner.connect(document); document.setDocumentPartitioner(partitioner); return document; }
@Override public void paint(int reason) { IDocument document = textViewer.getDocument(); if (document == null) { deactivate(false); return; } if (!fIsActive) { StyledText styledText = textViewer.getTextWidget(); fIsActive = true; styledText.addPaintListener(this); redrawAll(); } else if (reason == CONFIGURATION || reason == INTERNAL) { redrawAll(); } }
@Override public ICodeLens[] provideSyncCodeLenses(ICodeLensContext context, IProgressMonitor monitor) { ITextViewer textViewer = context.getViewer(); IDocument document = textViewer.getDocument(); List<ICodeLens> lenses = new ArrayList<>(); int lineCount = document.getNumberOfLines(); for (int i = 0; i < lineCount; i++) { String line = getLineText(document, i, false); int index = line.indexOf("class "); if (index != -1) { String className = line.substring(index + "class ".length(), line.length()); index = className.indexOf(" "); if (index != -1) { className = className.substring(0, index); } if (className.length() > 0) { lenses.add(new ClassCodeLens(className, i + 1)); } } } return lenses.toArray(new ICodeLens[0]); }
/** * Save the AST int he Compilation Unit * * @param testInterface * @param rewrite * @throws CoreException */ public static void save(CompilationUnit unit, ASTRewrite rewrite) throws CoreException { ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); IPath path = unit.getJavaElement().getPath(); try { bufferManager.connect(path, null); ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path); IDocument document = textFileBuffer.getDocument(); TextEdit edit = rewrite.rewriteAST(document, null); edit.apply(document); textFileBuffer.commit(null /* ProgressMonitor */, true /* Overwrite */); } catch (Exception e) { ResourceManager.logException(e); } finally { // disconnect the path bufferManager.disconnect(path, null); } }
/** * Similar to {@link IDocument#getLineInformationOfOffset(int)}, but the client can provide a text region instead of * only an offset. If the given region spans multiple lines, all affected lines will be returned, i.e. entire line * containing beginning of region, all lines contained in the region, and entire line containing the end of the * region. */ public static IRegion getLineInformationOfRegion(IDocument doc, int offset, int length, boolean includeLineDelimiterOfLastLine) throws BadLocationException { // get the line containing the beginning of the given text region final int firstLineNo = doc.getLineOfOffset(offset); // get the line containing the end of the given text region // (may be the same line if removal does not span multiple lines) final int lastLineNo = doc.getLineOfOffset(offset + length); // compute result final int startOffset = doc.getLineOffset(firstLineNo); final int endOffset = doc.getLineOffset(lastLineNo) + (includeLineDelimiterOfLastLine ? doc.getLineLength(lastLineNo) // includes line delimiters! : doc.getLineInformation(lastLineNo).getLength()); // does *not* include line delimiters! return new Region( startOffset, endOffset - startOffset); }
@Override public void customizeDocumentCommand(final IDocument document, final DocumentCommand command) { if (command.text.equals("(")) { command.text = "()"; this.configureCaret(command); } else if (command.text.equals("[")) { command.text = "[]"; this.configureCaret(command); } else if (command.text.equals("{")) { command.text = "{}"; this.configureCaret(command); } }
@Override public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { IDocument document = textViewer.getDocument(); /* Extrait le mot courant. */ ITextSelection selection = new TextSelection(document, region.getOffset(), region.getLength()); ITextSelection currentWordSelection = DocumentUtils.findCurrentWord(document, selection, WordSelectionType.CONSTANT_CASE); if (currentWordSelection == null) { return null; // NOSONAR } String currentWord = currentWordSelection.getText(); if (currentWord == null) { return null; // NOSONAR } IRegion targetRegion = new Region(currentWordSelection.getOffset(), currentWordSelection.getLength()); FileRegion fileRegion = new FileRegion(UiUtils.getCurrentEditorFile(), targetRegion.getOffset(), targetRegion.getLength()); /* Cherche un nom de DTO. */ IHyperlink[] hyperlinks = detectDtDefinitionName(currentWord, targetRegion, fileRegion); if (hyperlinks != null) { return hyperlinks; } /* Cherche un nom de Task. */ hyperlinks = detectTaskName(currentWord, targetRegion); if (hyperlinks != null) { return hyperlinks; } /* Cherche une déclaration KSP autre. */ return detectKspName(currentWord, targetRegion, fileRegion); }
private void ensurePositionCategoryRemoved(IDocument document) { if (document.containsPositionCategory(getCategory())) { try { document.removePositionCategory(getCategory()); } catch (BadPositionCategoryException e) { // ignore } document.removePositionUpdater(fUpdater); } }
/** * Method copied from super class with only a minor change: call to "readOnly" changed to "tryReadOnly". */ @Override public IHyperlink[] detectHyperlinks(final ITextViewer textViewer, final IRegion region, final boolean canShowMultipleHyperlinks) { final IDocument xtextDocument = textViewer.getDocument(); if (!(xtextDocument instanceof N4JSDocument)) { return super.detectHyperlinks(textViewer, region, canShowMultipleHyperlinks); } final IHyperlinkHelper helper = getHelper(); return ((N4JSDocument) xtextDocument).tryReadOnly(new IUnitOfWork<IHyperlink[], XtextResource>() { @Override public IHyperlink[] exec(XtextResource resource) throws Exception { if (resource == null) { return null; } if (helper instanceof ISourceViewerAware && textViewer instanceof ISourceViewer) { ((ISourceViewerAware) helper).setSourceViewer((ISourceViewer) textViewer); } return helper.createHyperlinksByOffset(resource, region.getOffset(), canShowMultipleHyperlinks); } }, null); }
/** * All {@link PseudoTokens} are considered to be contained in the default partition except for * {@link PseudoTokens#JS_DOC_TOKEN}. */ @Override public String getPartitionType(int antlrTokenType) { if (antlrTokenType == PseudoTokens.JS_DOC_TOKEN) { return JS_DOC_PARTITION; } if (antlrTokenType >= PseudoTokens.PSEUDO_TOKEN_START) { return IDocument.DEFAULT_CONTENT_TYPE; } return super.getPartitionType(antlrTokenType); }
@Override public boolean isInsertClosingBracket(IDocument doc, int offset) throws BadLocationException { if (offset >= 2) { ITypedRegion prevPartition = doc.getPartition(offset - 1); String prevPartitionType = prevPartition.getType(); if (TerminalsTokenTypeToPartitionMapper.SL_COMMENT_PARTITION.equals(prevPartitionType)) { return false; } if (TokenTypeToPartitionMapper.REG_EX_PARTITION.equals(prevPartitionType)) { return prevPartition.getLength() == 1; } } return SingleLineTerminalsStrategy.DEFAULT.isInsertClosingBracket(doc, offset); }
public static List<String> getPartitionsByType(IDocument document, String partitionType) { List<String> lines = new ArrayList<String>(); final Scanner scanner = new Scanner(document.get()); int lineNumber = 0; try { while (scanner.hasNextLine()) { final String line = scanner.nextLine(); final int offset = document.getLineOffset(lineNumber); if (document.getPartition(offset).getType().equals(partitionType)) { lines.add(line); } lineNumber++; } } catch (BadLocationException e) { e.printStackTrace(); } finally { if (scanner != null) scanner.close(); } return lines; }
@Override public IContentAssistant getContentAssistant(final ISourceViewer sourceViewer) { final ContentAssistant assistant = new ContentAssistant(); assistant.setContentAssistProcessor(new DefaultCompletionProcessor(), IDocument.DEFAULT_CONTENT_TYPE); assistant.setAutoActivationDelay(500); assistant.enableAutoActivation(true); assistant.enableAutoInsert(true); assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY); assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); return assistant; }
private Map<ProjectionAnnotation, Position> getAllSnippetsAnnotations() { Map<ProjectionAnnotation, Position> annotations = new HashMap<ProjectionAnnotation, Position>(); IDocument document = getDocument(); int curOffset = 0; FindReplaceDocumentAdapter frda = new FindReplaceDocumentAdapter(document); try { IRegion startRegion = frda.find(curOffset, "SNIPPET_START", true, false, false, false); //$NON-NLS-1$ while (startRegion != null && startRegion.getOffset() >= curOffset) { int startLine = document.getLineOfOffset(startRegion.getOffset()); int startOffset = document.getLineOffset(startLine); curOffset = startOffset + document.getLineLength(startLine); IRegion endRegion = frda.find(startRegion.getOffset(), "SNIPPET_END", true, false, false, false); //$NON-NLS-1$ if (endRegion != null) { int endLine = document.getLineOfOffset(endRegion.getOffset()); int endOffset = document.getLineOffset(endLine); endOffset += document.getLineLength(endLine); curOffset = endOffset; String text = document.get(startOffset, endOffset - startOffset); ProjectionAnnotation annotation = new ProjectionAnnotation(true); annotation.setText(text); annotation.setRangeIndication(true); annotations.put(annotation, new Position(startOffset, endOffset - startOffset)); } if (curOffset < document.getLength()) { startRegion = frda.find(curOffset, "SNIPPET_START", true, false, false, false); //$NON-NLS-1$ } } } catch (BadLocationException e) { } return annotations; }
private int getMethodLineNumber(IDocument document, VFMethod method) { FindReplaceDocumentAdapter findReplaceDocumentAdapter = new FindReplaceDocumentAdapter(document); try { method.getSootMethod().getBytecodeSignature(); IRegion region = findReplaceDocumentAdapter.find(0, method.getSootMethod().getDeclaration(), true, true, false, false); return document.getLineOfOffset(region.getOffset()); } catch (BadLocationException e) { e.printStackTrace(); } return -1; }
/** * Registers a document manager with an editor. * @param doc the document to be managed * @param st the styled text of the editor * @param dm the document manager */ public static void register(IDocument doc, StyledText st, DocumentManager dm) { if (doc != null) { doc.addDocumentListener(dm); DocumentUndoManagerRegistry.connect(doc); IDocumentUndoManager undoManager = DocumentUndoManagerRegistry.getDocumentUndoManager(doc); if (undoManager != null) { undoManager.addDocumentUndoListener(dm); } } if (st != null) { st.addListener(SWT.KeyDown, dm); st.addListener(SWT.MouseDown, dm); st.addListener(SWT.MouseDoubleClick, dm); } }
/** * Unregisters a document manager with an editor. * @param doc the document to be managed * @param st the styled text of the editor * @param dm the document manager */ public static void unregister(IDocument doc, StyledText st, DocumentManager dm) { if (doc != null) { doc.removeDocumentListener(dm); IDocumentUndoManager undoManager = DocumentUndoManagerRegistry.getDocumentUndoManager(doc); DocumentUndoManagerRegistry.disconnect(doc); if (undoManager != null) { undoManager.removeDocumentUndoListener(dm); } } if (st != null) { st.removeListener(SWT.KeyDown, dm); st.removeListener(SWT.MouseDown, dm); st.removeListener(SWT.MouseDoubleClick, dm); } }
/** * Use only for non-project parsers * @param {@link IFileEditorInput} {@link IResource} or null * @return true if refresh was triggered successfully */ private boolean refreshParser(PgDbParser parser, IResource res, IProgressMonitor monitor) throws InterruptedException, IOException, CoreException { if (res instanceof IFile && res.getProject().hasNature(NATURE.ID)) { parser.getObjFromProjFile((IFile) res, monitor); return true; } IEditorInput in = getEditorInput(); if (in instanceof IURIEditorInput) { IURIEditorInput uri = (IURIEditorInput) in; IDocument document = getDocumentProvider().getDocument(getEditorInput()); InputStream stream = new ByteArrayInputStream(document.get().getBytes(StandardCharsets.UTF_8)); parser.fillRefsFromInputStream(stream, Paths.get(uri.getURI()).toString(), monitor); return true; } return false; }
/** * Obtains the current contents of a file under recording. * @return the contents of source code, or <code>null</code> if source code does not exist */ protected String getCurrentCode() { IDocument doc = EditorUtilities.getDocument(file); if (doc != null) { return doc.get(); } return null; }
private void createJimpleBreakpoint() throws CoreException, BadLocationException { IDocument document = getDocument(); IFile file = getFile(); int lineNumber = getLineNumber(); int offset = document.getLineOffset(lineNumber - 1); int length = document.getLineInformation(lineNumber - 1).getLength(); int charStart = offset; int charEnd = offset + length; try { String unitFqn = getUnitFqn(lineNumber - 1, offset, length); IMarker m = file.createMarker(JIMPLE_BREAKPOINT_MARKER); m.setAttribute(IMarker.LINE_NUMBER, getLineNumber()); m.setAttribute(IMarker.MESSAGE, "Unit breakpoint: " + file.getName() + " [Line "+getLineNumber()+"]"); m.setAttribute("Jimple.file", file.getProjectRelativePath().toPortableString()); m.setAttribute("Jimple.project", file.getProject().getName()); m.setAttribute("Jimple.unit.charStart", charStart); m.setAttribute("Jimple.unit.charEnd", charEnd); m.setAttribute("Jimple.unit.fqn", unitFqn); JimpleBreakpointManager.getInstance().createBreakpoint(m); } catch(UnitNotFoundException e) { String msg = "The selected unit couldn't be found in our Jimple model. This might be a problem related to Jimple optimizations."; MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Breakpoint could not be placed", msg); } }
/** * Obtains the document of a file existing on an editor. * @param editor the editor * @return the document of the file, or <code>null</code> if none */ public static IDocument getDocument(IEditorPart editor) { IFile file = getInputFile(editor); if (file != null) { return getDocument(file); } return null; }
/** * Obtains the contents of source code appearing in an editor. * @param editor the editor * @return the contents of the source code, or <code>null</code> if the source code is not valid */ public static String getSourceCode(IEditorPart editor) { IDocument doc = getDocument(editor); if (doc != null) { return doc.get(); } return null; }
/** * Obtains the contents of source code appearing in an editor. * @param file the file * @return the contents of the source code, or <code>null</code> if the source code is not valid */ public static String getSourceCode(IFile file) { IDocument doc = getDocument(file); if (doc != null) { return doc.get(); } return null; }
@Override protected FileInfo createFileInfo(Object element) throws CoreException{ FileInfo info = super.createFileInfo(element); if(info == null){ info = createEmptyFileInfo(); } IDocument document = info.fTextFileBuffer.getDocument(); if (document != null) { setupDocument(document); } return info; }
@Override public List<KspDeclaration> getItems(FileProvider fileProvider) { IFile file = fileProvider.getFile(); IDocument document = fileProvider.getDocument(); /* Parse le document KSP. */ KspFile kspFile = createKspFile(document, file); /* Récupère toutes les déclarations KSP. */ return kspFile.getKspDeclarations(); }
@Override protected IDocument createDocument(Object element) throws CoreException { IDocument document = super.createDocument(element); if (document != null) { /* installation necessary */ JenkinsPartitioner partitioner = JenkinsPartionerFactory.create(); partitioner.connect(document,true); document.setDocumentPartitioner(partitioner); } return document; }
/** * This function filters the units of a class according to the function name and class name and content. * We need to filter this based on methods, because different function might contain similar lines of code and * hence their contents will be similar. * @param className The name of the class. * @param document The document which the user is currently interacting with * @param content The contents of the document. * @param lineNumber The linenumber on which the user has right-clicked. * @return Map of filtered unit and the function it belongs to. */ private HashMap<VFUnit, VFMethod> getSelectedUnit(String className, IDocument document, String content, int lineNumber) { //Get the VFClass which contains all the VFMethods which inturn contains VFUnits DataModel dataModel = ServiceUtil.getService(DataModel.class); HashMap<VFUnit, VFMethod> map = new HashMap<>(); //Iterate over all classes for (VFClass vfClass : dataModel.listClasses()) { //Filter by the class that is passed. if (vfClass.getSootClass().getName().equals(className)) { //Get all methods of the class. List<VFMethod> vfMethods = vfClass.getMethods(); Map<String, Integer> methodLines = getMethodLineNumbers(document, vfMethods); Collection<Integer> allMethodLines = methodLines.values(); List<Integer> lesserThanCuurent = allMethodLines.stream().filter(x -> x.intValue() < lineNumber).collect(Collectors.toList()); int toBeCompared = lesserThanCuurent.get(lesserThanCuurent.size() - 1); for (VFMethod method : vfMethods) { int methodLine = methodLines.get(method.getSootMethod().getDeclaration()); if (toBeCompared == methodLine) { for (VFUnit unit : method.getUnits()) { if (unit.getUnit().toString().trim().equals(content)) { map.put(unit, method); } } } } } } return map; }
@Override public ICompletionProposal[] computeCompletionProposals(final ITextViewer viewer, final int offset) { final List<ICompletionProposal> proposals = new ArrayList<>(); final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); try { allFiles.clear(); allEcoreFiles.clear(); findAllEMFFiles(root); findAllXMIFiles(root); } catch (final Exception e) { e.printStackTrace(); return null; } final IDocument document = viewer.getDocument(); try { IRegion lineInfo = document.getLineInformationOfOffset(offset); String line = document.get(lineInfo.getOffset(), lineInfo.getLength()); int activationIndex = line.indexOf(activationChar); if (activationIndex != -1) { String prefix = line.substring(line.indexOf("@") + 1); String type = document.getPartition(offset - 1).getType(); int replacementOffset = offset - prefix.length(); addProposals(proposals, prefix, replacementOffset, type); } } catch (BadLocationException e1) { e1.printStackTrace(); } final ICompletionProposal[] result = new ICompletionProposal[proposals.size()]; proposals.toArray(result); return result; }
/** * Get document text - safe way. * * @return string, never <code>null</code> */ String getDocumentText() { IDocument doc = getDocument(); if (doc == null) { return ""; } return doc.get(); }