private String getUnitFqn(int lineNumber, int offset, int length) throws BadLocationException { IDocument document = getDocument(); IFile file = getFile(); String content = document.get(offset, length).trim(); if (content.trim().length() > 0) { String className = file.getName().substring(0, file.getName().lastIndexOf('.')); VFUnit resultantUnit = getSelectedUnit(className, document, content.trim().substring(0, content.length() - 1), lineNumber); if (resultantUnit != null) { return resultantUnit.getFullyQualifiedName(); } } throw new UnitNotFoundException("Couldn't determine fully qualified name for unit"); }
/** * Computes and returns the initial pattern for the type search dialog. * * If no initial pattern can be computed, an empty string is returned. */ private String computeInitialPattern() { IEditorPart activeEditor = HandlerServiceUtils.getActiveEditor().orNull(); if (activeEditor instanceof N4JSEditor) { Point range = ((N4JSEditor) activeEditor).getSourceViewer2().getSelectedRange(); try { String text = ((N4JSEditor) activeEditor).getDocument().get(range.x, range.y); if (N4JSLanguageUtils.isValidIdentifier(text) && !startWithLowercaseLetter(text) && !languageHelper.isReservedIdentifier(text)) { return text; } } catch (BadLocationException e) { LOGGER.error("Failed to infer type search pattern from editor selection.", e); } } return ""; }
private VFUnit getSelectedUnit(String className, IDocument document, String content, int lineNumber) throws BadLocationException { DataModel dataModel = ServiceUtil.getService(DataModel.class); // VFClass // vfClass=dataModel.listClasses().stream().filter(x->x.getSootClass().getName()==className).collect(Collectors.toList()).get(0); for (VFClass vfClass : dataModel.listClasses()) { if (vfClass.getSootClass().getName().equals(className)) { 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)) { return unit; } } } } } } return null; }
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 ""; }
/** * Applies all given changes to the given document. This method assumes that 'changes' contains only changes * intended for the given document; the actual URI stored in the changes is ignored. */ public void applyAllInSameDocument(Collection<? extends IAtomicChange> changes, IDocument document) throws BadLocationException { DocumentRewriteSession rewriteSession = null; try { // prepare if (document instanceof IDocumentExtension4) { rewriteSession = ((IDocumentExtension4) document).startRewriteSession( DocumentRewriteSessionType.UNRESTRICTED); } // perform replacements for (IAtomicChange currRepl : changes) { currRepl.apply(document); } } finally { // cleanup if (rewriteSession != null) ((IDocumentExtension4) document).stopRewriteSession(rewriteSession); } }
/** * Insert the given string as a new line above the line at the given offset. The given string need not contain any * line delimiters and the offset need not point to the beginning of a line. If 'sameIndentation' is set to * <code>true</code>, the new line will be indented as the line at the given offset (i.e. same leading white space). */ public static IChange insertLineAbove(IXtextDocument doc, int offset, String txt, boolean sameIndentation) throws BadLocationException { final String NL = lineDelimiter(doc, offset); final IRegion currLineReg = doc.getLineInformationOfOffset(offset); String indent = ""; if (sameIndentation) { final String currLine = doc.get(currLineReg.getOffset(), currLineReg.getLength()); int idx = 0; while (idx < currLine.length() && Character.isWhitespace(currLine.charAt(idx))) { idx++; } indent = currLine.substring(0, idx); } return new Replacement(getURI(doc), currLineReg.getOffset(), 0, indent + txt + NL); }
/** * Removes text of the given length at the given offset. If 'removeEntireLineIfEmpty' is set to <code>true</code>, * the line containing the given text region will be deleted entirely iff the change would leave the line empty * (i.e. contains only white space) <em>after</em> the removal of the text region. */ public static IChange removeText(IXtextDocument doc, int offset, int length, boolean removeEntireLineIfEmpty) throws BadLocationException { if (!removeEntireLineIfEmpty) { // simple return new Replacement(getURI(doc), offset, length, ""); } else { // get entire line containing the region to be removed // OR in case the region spans multiple lines: get *all* lines affected by the removal final IRegion linesRegion = DocumentUtilN4.getLineInformationOfRegion(doc, offset, length, true); final String lines = doc.get(linesRegion.getOffset(), linesRegion.getLength()); // simulate the removal final int offsetRelative = offset - linesRegion.getOffset(); final String lineAfterRemoval = removeSubstring(lines, offsetRelative, length); final boolean isEmptyAfterRemoval = lineAfterRemoval.trim().isEmpty(); if (isEmptyAfterRemoval) { // remove entire line (or in case the removal spans multiple lines: remove all affected lines entirely) return new Replacement(getURI(doc), linesRegion.getOffset(), linesRegion.getLength(), ""); } else { // just remove the given text region return new Replacement(getURI(doc), offset, length, ""); } } }
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; }
/** * Returns the end offset of the line that contains the specified offset or * if the offset is inside a line delimiter, the end offset of the next * line. * * @param offset * the offset whose line end offset must be computed * @return the line end offset for the given offset * @exception BadLocationException * if offset is invalid in the current document */ protected int endOfLineOf(int offset) throws BadLocationException { IRegion info = fDocument.getLineInformationOfOffset(offset); if (offset <= info.getOffset() + info.getLength()){ return info.getOffset() + info.getLength(); } int line = fDocument.getLineOfOffset(offset); try { info = fDocument.getLineInformation(line + 1); return info.getOffset() + info.getLength(); } catch (BadLocationException x) { return fDocument.getLength(); } }
@Override public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent event, boolean documentPartitioningChanged) { if (!documentPartitioningChanged) { try { IRegion info = fDocument.getLineInformationOfOffset(event.getOffset()); int start = Math.max(partition.getOffset(), info.getOffset()); int end = event.getOffset() + (event.getText() == null ? event.getLength() : event.getText().length()); if (info.getOffset() <= end && end <= info.getOffset() + info.getLength()) { // optimize the case of the same line end = info.getOffset() + info.getLength(); } else{ end = endOfLineOf(end); } end = Math.min(partition.getOffset() + partition.getLength(), end); return new Region(start, end - start); } catch (BadLocationException x) { } } return partition; }
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); } }
private void addErrorMarkers(BashScriptModel model, int severity) { if (model == null) { return; } IDocument document = getDocument(); if (document == null) { return; } Collection<BashError> errors = model.getErrors(); for (BashError error : errors) { int startPos = error.getStart(); int line; try { line = document.getLineOfOffset(startPos); } catch (BadLocationException e) { EclipseUtil.logError("Cannot get line offset for " + startPos, e); line = 0; } BashEditorUtil.addScriptError(this, line, error, severity); } }
/** * Performs global post-processing of synthesized code: * - Adds import declarations * * @param ast the owner of the document * @param env environment that was used for synthesis * @param document draft program document * @throws BadLocationException if an error occurred when rewriting document */ private void postprocessGlobal(AST ast, Environment env, Document document) throws BadLocationException { /* add imports */ ASTRewrite rewriter = ASTRewrite.create(ast); ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY); Set<Class> toImport = new HashSet<>(env.imports); toImport.addAll(sketch.exceptionsThrown()); // add all catch(...) types to imports for (Class cls : toImport) { while (cls.isArray()) cls = cls.getComponentType(); if (cls.isPrimitive() || cls.getPackage().getName().equals("java.lang")) continue; ImportDeclaration impDecl = cu.getAST().newImportDeclaration(); String className = cls.getName().replaceAll("\\$", "\\."); impDecl.setName(cu.getAST().newName(className.split("\\."))); lrw.insertLast(impDecl, null); } rewriter.rewriteAST(document, null).apply(document); }
/** * Parse le document. * * @return Fichier KSP. */ public KspFile parse() { /* Parcourt les lignes du document. */ for (int lineIdx = 0; lineIdx < document.getNumberOfLines(); lineIdx++) { try { /* Lit la ligne courante. */ readLine(lineIdx); /* Extrait le package. */ parsePackage(); /* Extrait une déclaration KSP */ parseKspDeclaration(); /* Extrait un attribut de déclaration KSP. */ parseKspDeclarationAttribute(); } catch (BadLocationException e) { ErrorUtils.handle(e); } } /* Créé le fichier KSP. */ return new KspFile(file, packageName, kspDeclarations); }
private void updateMarker(IResource resource, String message, int start, int end, int severity, IMarker marker) { try { marker.setAttribute(IMarker.MESSAGE, message); marker.setAttribute(IMarker.SEVERITY, severity); if (resource.getType() != IResource.FILE) { return; } IFile file = (IFile) resource; ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager(); ITextFileBuffer textFileBuffer = manager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE); if (textFileBuffer == null) { manager.connect(file.getFullPath(), LocationKind.IFILE, new NullProgressMonitor()); textFileBuffer = manager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE); } IDocument document = textFileBuffer.getDocument(); marker.setAttribute(IMarker.CHAR_START, start); marker.setAttribute(IMarker.CHAR_END, end); marker.setAttribute(IMarker.LINE_NUMBER, document.getLineOfOffset(start) + 1); } catch (CoreException | BadLocationException e) { e.printStackTrace(); } }
private void findWordEnd() { /* On se place à la fin de la sélection initiale. */ int offset = selection.getOffset() + selection.getLength() - 1; /* On parcourt les caractères vers la droite. */ while (true) { // NOSONAR offset++; try { /* Obtention du caractère. */ String currentChar = document.get(offset, 1); if (wordTest.test(currentChar)) { /* Test ok : on l'insert à la fin du mot courant. */ builder.append(currentChar); /* On met à jour les coordonnées du mot courant. */ currentLength++; } else { /* Test ko : la fin du mot est atteint. */ break; } } catch (BadLocationException e) { // NOSONAR break; } } }
/** * Validate 'insert_final_newline' if needed and update the given set of marker. * * @param document * the document to validate * @param remainingMarkers * set of markers to update. * @throws BadLocationException */ private void validateInsertFinalNewline(IDocument document, Set<IMarker> remainingMarkers) throws BadLocationException { boolean insertFinalNewline = preferenceStore.getBoolean(EDITOR_INSERT_FINAL_NEWLINE); if (!insertFinalNewline) { return; } // Check if there are an empty line at the end of the document. if (document.getLength() == 0) { return; } int line = document.getNumberOfLines() - 1; IRegion region = document.getLineInformation(line); if (region.getLength() > 0) { int end = region.getOffset() + region.getLength(); int start = end - 1; addOrUpdateMarker(start, end, insertFinalNewlineType, document, remainingMarkers); } }
@Override public void initialReconcile() { if (this.document == null) { return; } Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { RelationModelReconcilingStrategy.this.manager = new SynchronizationManager(RelationModelReconcilingStrategy.this.document); } catch (final BadLocationException e) { e.printStackTrace(); } } }); }
public static HashMap<String, Integer> getPartitionsLinesByType(IDocument document, String partitionType) { HashMap<String, Integer> lines = new HashMap<String, Integer>(); 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, lineNumber); } lineNumber++; } } catch (BadLocationException e) { e.printStackTrace(); } finally { if (scanner != null) scanner.close(); } return lines; }
private ITypedRegion getPartition(final String partitionContentType) { final IDocumentExtension3 extension = (IDocumentExtension3) this.document; ITypedRegion[] computePartitioning = null; try { computePartitioning = extension.computePartitioning(IDocumentExtension3.DEFAULT_PARTITIONING, 0, this.document.getLength(), false); } catch (BadLocationException | BadPartitioningException e) { e.printStackTrace(); } for (final ITypedRegion iTypedRegion : computePartitioning) { if (iTypedRegion.getType().equals(partitionContentType)) { return iTypedRegion; } } return null; }
@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; }
/** * This method returns the line numbers of all the methods passed to it. * @param document The document with which the user is interacting. * @param vfMethods The list of methods for which the line numbers are required. * @return Map containing method names and their starting line numbers. */ private Map<String, Integer> getMethodLineNumbers(IDocument document, List<VFMethod> vfMethods) { FindReplaceDocumentAdapter findReplaceDocumentAdapter = new FindReplaceDocumentAdapter(document); TreeMap<String, Integer> result = new TreeMap<String, Integer>(); for (VFMethod method : vfMethods) { try { method.getSootMethod().getBytecodeSignature(); IRegion region = findReplaceDocumentAdapter.find(0, method.getSootMethod().getDeclaration().substring(0, method.getSootMethod().getDeclaration().indexOf('(')), true, true, false, false); if (region != null) { result.put(method.getSootMethod().getDeclaration(), document.getLineOfOffset(region.getOffset())); } } catch (BadLocationException e) { e.printStackTrace(); } } return MapUtil.sortByValue(result); }
/** * We add new error annotation related to error which alloy parser is giving us. * * @param e the exception which is parse operation occurred */ private void addNewAnnotation(final Err e) { final int line = e.pos.y; int offset = 0; final int length = e.pos.x2 - e.pos.x + 1; final String message = e.getLocalizedMessage(); try { offset = this.document.getLineOffset(line - 1) + e.pos.x - 1; } catch (final BadLocationException e1) { e1.printStackTrace(); } final Annotation annotation = new Annotation(this.MME_PARSE_ANNOT_TYPE, true, message); this.annotationModel.connect(this.document); this.annotationModel.addAnnotation(annotation, new Position(offset, length)); this.annotationModel.disconnect(this.document); }
private String getPatternToEmphasizeMatch(IDocument document, int offset) { int start = getPrefixCompletionStart(document, offset); int patternLength = offset - start; String pattern = null; try { pattern = document.get(start, patternLength); } catch (BadLocationException e) { // return null } return pattern; }
/** * Compute changes that will remove all imports. * * @param resource * the resource to modify * @param document * the document connected to the xtextResource, for textual changes. * @return list of changes to the document. */ public static List<IChange> getImportDeletionChanges(XtextResource resource, IXtextDocument document) throws BadLocationException { List<IChange> changes = new ArrayList<>(); List<ScriptElement> elements = XtextResourceUtils.getScript(resource).getScriptElements(); // elements.filter(ImportDeclaration).map[findActualNodeFor(it)].forEach[changes.add(document.removeNodeButKeepComments(it))] for (ScriptElement el : elements) { if (el instanceof ImportDeclaration) { INode nodeToRemove = NodeModelUtils.findActualNodeFor(el); changes.add(removeNodeButKeepComments(document, nodeToRemove)); } } return changes; }
private static IChange removeNodeButKeepComments(IXtextDocument doc, INode importNode) throws BadLocationException { if (importNode == null) return IChange.IDENTITY; int end = importNode.getEndOffset(); int offset = importNode.getOffset(); return ChangeProvider.removeText(doc, offset, end - offset, true); }
/** * This method returns the line numbers of all the methods passed to it. * @param document The document with which the user is interacting. * @param vfMethods The list of methods for which the line numbers are required. * @return Map containing method names and their starting line numbers. */ private Map<String, Integer> getMethodLineNumbers(IDocument document, List<VFMethod> vfMethods) { FindReplaceDocumentAdapter findReplaceDocumentAdapter = new FindReplaceDocumentAdapter(document); TreeMap<String, Integer> result = new TreeMap<>(); for (VFMethod method : vfMethods) { try { method.getSootMethod().getBytecodeSignature(); IRegion region = findReplaceDocumentAdapter.find(0, method.getSootMethod().getDeclaration(), true, true, false, false); result.put(method.getSootMethod().getDeclaration(), document.getLineOfOffset(region.getOffset())); } catch (BadLocationException e) { e.printStackTrace(); } } return MapUtil.sortByValue(result); }
@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; }
/** * Same as {@link #removeText(IXtextDocument, int, int, boolean)}, but the text region to remove can be specified by * providing a semantic object, i.e. AST node. */ public static IChange removeSemanticObject(IXtextDocument doc, EObject obj, boolean removeEntireLineIfEmpty) throws BadLocationException { if (obj == null) return IChange.IDENTITY; return removeNode(doc, NodeModelUtils.findActualNodeFor(obj), removeEntireLineIfEmpty); }
/** * Same as {@link #removeText(IXtextDocument, int, int, boolean)}, but the text region to remove can be specified by * providing a parse tree node. */ public static IChange removeNode(IXtextDocument doc, INode node, boolean removeEntireLineIfEmpty) throws BadLocationException { if (node == null) return IChange.IDENTITY; return removeText(doc, node.getOffset(), node.getLength(), removeEntireLineIfEmpty); }
/** * Delete line containing the given offset (the offset need not point to the beginning of the line). Will do nothing * if 'deleteOnlyIfEmpty' is set to <code>true</code> and the given line is non-empty, i.e. contains characters * other than {@link Character#isWhitespace(char) white space}. */ public static IChange deleteLine(IXtextDocument doc, int offset, boolean deleteOnlyIfEmpty) throws BadLocationException { if (deleteOnlyIfEmpty && !DocumentUtilN4.getLine(doc, offset).trim().isEmpty()) return IChange.IDENTITY; final int lineNo = doc.getLineOfOffset(offset); final int currLineOffset = doc.getLineOffset(lineNo); final int currLineLen = doc.getLineLength(lineNo); // n.b.: includes line delimiter! return new Replacement(getURI(doc), currLineOffset, currLineLen, ""); }
@Fix(IOIJavaValidator.SALARY_TOO_LOW) public void raiseSalary(final Issue issue, IssueResolutionAcceptor acceptor) { acceptor.accept(issue, "Raise Salary", "Raise Salary.", "", new IModification() { public void apply(IModificationContext context) throws BadLocationException { IXtextDocument xtextDocument = context.getXtextDocument(); //String firstLetter = xtextDocument.get(issue.getOffset(), 1); xtextDocument.replace(issue.getOffset(), issue.getLength(), issue.getData()[0]); } }); }
@Fix(IOIJavaValidator.SALARY_TOO_HIGH) public void cutSalary(final Issue issue, IssueResolutionAcceptor acceptor) { acceptor.accept(issue, "Cut Salary", "Cut Salary.", "", new IModification() { public void apply(IModificationContext context) throws BadLocationException { IXtextDocument xtextDocument = context.getXtextDocument(); //String firstLetter = xtextDocument.get(issue.getOffset(), 1); xtextDocument.replace(issue.getOffset(), issue.getLength(), issue.getData()[0]); } }); }
@Override public void keyReleased(KeyEvent e) { InsertClosingBracketsSupport insertClosingBracketsSupport = getInsertionSupport(e); if (insertClosingBracketsSupport == null) { return; } /* * do not use last caret start - because the listener ordering could be * different */ ISelectionProvider selectionProvider = this.batchEditor.getSelectionProvider(); if (selectionProvider == null) { return; } ISelection selection = selectionProvider.getSelection(); if (!(selection instanceof ITextSelection)) { return; } boolean enabled = getPreferences().getBooleanPreference(P_EDITOR_AUTO_CREATE_END_BRACKETSY); if (!enabled) { return; } ITextSelection textSelection = (ITextSelection) selection; int offset = textSelection.getOffset(); try { IDocument document = this.batchEditor.getDocument(); if (document == null) { return; } insertClosingBracketsSupport.insertClosingBrackets(document, selectionProvider, offset); } catch (BadLocationException e1) { /* ignore */ return; } }