/** * This method makes sure that no changes are applied (no dirty state), if there are no changes. This fixes bug * GHOLD-272 */ @Override public void format(IDocument document, IRegion region) { IXtextDocument doc = (IXtextDocument) document; TextEdit e = doc.priorityReadOnly(new FormattingUnitOfWork(doc, region)); if (e == null) return; if (e instanceof ReplaceEdit) { ReplaceEdit r = (ReplaceEdit) e; if ((r.getOffset() == 0) && (r.getLength() == 0) && (r.getText().isEmpty())) { return; } } try { e.apply(document); } catch (BadLocationException ex) { throw new RuntimeException(ex); } }
/** * 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, ""); } } }
/** * 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; }
@Override public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { SQLEditor editor = getAdapter(SQLEditor.class); PgDbParser parser = editor.getParser(); int offset = region.getOffset(); List<PgObjLocation> refs = parser.getObjsForEditor(editor.getEditorInput()); for (PgObjLocation obj : refs) { if (offset > obj.getOffset() && offset < (obj.getOffset() + obj.getObjLength())) { IHyperlink[] links = parser.getDefinitionsForObj(obj) .map(def -> new SQLEditorHyperLink( new Region(def.getOffset(), def.getObjLength()), new Region(obj.getOffset(), obj.getObjLength()), obj.getObjName(), def.getFilePath(), def.getLineNumber())) .toArray(IHyperlink[]::new); if (links.length != 0) { return links; } } } return null; }
@Override public IRegion getHoverRegion(ITextViewer textViewer, int offset) { PgDbParser parser = editor.getParser(); List<PgObjLocation> refs = parser.getObjsForEditor(editor.getEditorInput()); for (PgObjLocation obj : refs) { if (offset > obj.getOffset() && offset < (obj.getOffset() + obj.getObjLength())) { Optional<PgObjLocation> loc = parser.getDefinitionsForObj(obj).findAny(); if (loc.isPresent()) { SQLEditorMyRegion region = new SQLEditorMyRegion(obj.getOffset(), obj.getObjLength()); region.setComment(loc.get().getComment()); return region; } } } return new Region(offset, 0); }
@Override public IRegion getHoverRegion(ITextViewer textViewer, int offset) { IDocument document = textViewer.getDocument(); /* Vérifie qu'on est dans une String de KSP */ boolean isSqlString = DocumentUtils.isContentType(document, offset, KspRegionType.STRING); if (!isSqlString) { return null; } /* Extrait le mot courant. */ ITextSelection selection = new TextSelection(document, offset, 0); ITextSelection currentWordSelection = DocumentUtils.findCurrentWord(document, selection, WordSelectionType.SNAKE_CASE); if (currentWordSelection == null) { return null; } String currentWord = currentWordSelection.getText(); if (currentWord == null) { return null; } /* Renvoie la région du mot. */ return new Region(currentWordSelection.getOffset(), currentWordSelection.getLength()); }
@Override public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { /* Extrait le mot de la région. */ String currentWord = getSelectedWord(textViewer, hoverRegion); /* Extrait un nom de DTO : Calcul le nom en PascalCase */ String javaName = StringUtils.toPascalCase(currentWord); /* Cherche le fichier Java du DTO. */ DtoFile dtoFile = DtoManager.getInstance().findDtoFile(javaName); if (dtoFile == null) { return null; } /* Renvoie le nom Java. Le texte complet sera généré par KspInformationPresenter. */ return javaName; }
private IHyperlink[] detectKspName(String currentWord, IRegion targetRegion, FileRegion fileRegion) { /* Cherche la déclaration. */ KspDeclaration kspDeclaration = KspManager.getInstance().findKspDeclarationByConstantCaseName(currentWord); if (kspDeclaration == null) { return null; // NOSONAR } /* Vérifie que le focus n'est pas déjà sur la déclaration. */ if (fileRegion.equals(kspDeclaration.getFileRegion())) { return null; // NOSONAR } /* Renvoie un lien vers la déclaration. */ return new IHyperlink[] { new KspDeclarationHyperLink(targetRegion, kspDeclaration) }; }
@Override public void reconcile(final IRegion partition) { if (this.document == null) { return; } try { final ITypedRegion[] partitionRegions = this.document.computePartitioning(partition.getOffset(), partition.getLength()); for (int i = 0; i < partitionRegions.length; i++) { if (partitionRegions[i].getType().equals(MetaModelPartitionScanner.META_MODEL_REASON)) { this.reconcile(null, partitionRegions[i]); } } } catch (final BadLocationException e) { e.printStackTrace(); } }
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; }
/** * 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); } }
/** * 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); }
@Override protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException { try { String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document); final IJavaProject project= getCompilationUnit().getJavaProject(); IRegion region= document.getLineInformationOfOffset(fInsertPosition); String lineContent= document.get(region.getOffset(), region.getLength()); String indentString= Strings.getIndentString(lineContent, project); String str= Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter); InsertEdit edit= new InsertEdit(fInsertPosition, str); rootEdit.addChild(edit); if (fComment.charAt(fComment.length() - 1) != '\n') { rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter)); rootEdit.addChild(new InsertEdit(fInsertPosition, indentString)); } } catch (BadLocationException e) { throw new CoreException(StatusFactory.newErrorStatus("Invalid edit", e)); } }
/** * Find the IDs in the given text and return the array of * regions pointing to those or an empty array, if no IDs were found. * An ID is scheme_timestamp, created by {@link ModelWriter#getValidIdentifier(String)} e.G. next_125195338522638000 * @param text text containing IDs (error text) * @return array of regions or empty array */ public static IRegion[] findIds(String text) { if (text == null || text.length() == 0) { return new IRegion[0]; } Matcher matcher = ModelWriter.ID_MATCHER.matcher(text); Vector<Region> regions = new Vector<Region>(); while (matcher.find()) { regions.add(new Region(matcher.start(), matcher.end() - matcher.start())); } return regions.toArray(new IRegion[regions.size()]); }
/** * Finds for an \end{env} the matching \begin{env}. * @param input * @param envName Name of the environment, e.g. "itemize" * @param beginIndex Must be at the start of \end{env} * @return The region of the \begin{env} command or null if the end was not found */ public static IRegion findMatchingBeginEnvironment(String input, String envName, int beginIndex) { int pos = beginIndex; IRegion nextEnd, nextBegin; int level = 0; do { nextEnd = findLastEnvironment(input, envName, "\\end", pos); nextBegin = findLastEnvironment(input, envName, "\\begin", pos); if (nextBegin == null) return null; if (nextEnd == null) { level--; pos = nextBegin.getOffset(); } else { if (nextEnd.getOffset() > nextBegin.getOffset()) level++; else level--; pos = nextEnd.getOffset(); } } while (level >= 0); return nextBegin; }
private void insertMultiLiner(BracketInsertion data, ISelectionProvider selectionProvider, int offset, IDocument document) throws BadLocationException { IRegion region = document.getLineInformationOfOffset(offset); if (region == null) { return; } int length = region.getLength(); String textBeforeColumn = document.get(offset - length, length-1); //-1 to get not he bracket itself String relevantColumnsBefore = TextUtil.trimRightWhitespaces(textBeforeColumn); InsertionData result = support.prepareInsertionString( data.createMultiLineTemplate(SourceCodeInsertionSupport.CURSOR_VARIABLE), relevantColumnsBefore); document.replace(offset - 1, 1, result.getSourceCode()); selectionProvider.setSelection(new TextSelection(offset + result.getCursorOffset() - 1, 0)); }
private static IRegion findLastEnvironment(String input, String envName, String command, int fromIndex) { int pos = input.lastIndexOf("{" + envName + "}", fromIndex); while (pos != -1) { int end = pos + envName.length() + 2; // Search for the command int beginStart = findLastCommand(input, command, pos); if (beginStart != -1 && beginStart <= fromIndex) { // Check for whitespaces between \command and {...} while (pos != beginStart + command.length() && Character.isWhitespace(input.charAt(--pos))) ; if (pos == beginStart + command.length()) { return new Region(beginStart, end - beginStart); } } pos = input.lastIndexOf("{" + envName + "}", pos-1); } return null; }
public String getHoverInfo( ITextViewer textViewer, IRegion hoverRegion){ int offset = hoverRegion.getOffset(); if (hoverRegion != null) { try { if (hoverRegion.getLength() > -1) { IDocument doc = textViewer.getDocument(); // String key = textViewer.getDocument().get(offset, hoverRegion.getLength()); // ITypedRegion region = doc.getPartition(offset); ITypedRegion partitionType = textViewer.getDocument().getPartition(offset); IRegion reg2 = doc.getLineInformationOfOffset(offset); String lineText = doc.get(reg2.getOffset(), reg2.getLength()); // if(BaseUtils.isEmpty(key)){ // key = BaseUtils.getKeyFromLine(lineText); // return HAssistInfoMap.getInfo(key); // } String key = DocumentUtils.getKeyFromLine(lineText); return LazyObjects.getInfoMap("Headers").getInfo(key); } } catch (BadLocationException x) { } } return "JavaEditorMessages.getString(MyTextHover.emptySelection)"; }
private IHyperlink[] handleFileLink(IRegion lineInfo, GradleHyperLinkResult result) { try { File folder = editorFile.getParentFile(); String fileName = result.linkContent; File target = new File(folder, fileName); if (!target.exists()) { target = new File(fileName); } if (!target.exists()) { return null; } IFileStore fileStore = EFS.getLocalFileSystem().getStore(target.toURI()); if (fileStore==null){ return null; } IRegion urlRegion = new Region(lineInfo.getOffset() + result.linkOffsetInLine, result.linkLength); GradleFileHyperlink gradleFileHyperlink = new GradleFileHyperlink(urlRegion, fileStore); return new IHyperlink[] { gradleFileHyperlink }; } catch (RuntimeException e) { return null; } }
@Override public void reconcile(DirtyRegion dirty, IRegion partition) { try { IProblemRequestorExtension e = getProblemRequestorExtension(); if (e != null) { try { e.beginReportingSequence(); doReconcile(dirty, partition); } finally { e.endReportingSequence(); } } else { doReconcile(dirty, partition); } } finally { ((FluentMkEditor) editor).reconciled(); } }
private int getFirstCompleteLineOfRegion(IRegion region, IDocument document) { try { final int startLine = document.getLineOfOffset(region.getOffset()); int offset = document.getLineOffset(startLine); if (offset >= region.getOffset()) { return startLine; } final int nextLine = startLine + 1; if (nextLine == document.getNumberOfLines()) { return -1; } offset = document.getLineOffset(nextLine); return (offset > region.getOffset() + region.getLength() ? -1 : nextLine); } catch (BadLocationException x) { // should not happen } return -1; }
/** * Sets beginCommentOffset, endCommentOffset, indent, and margin * * @throws org.eclipse.jface.text.BadLocationException */ private void setCommentFields() throws org.eclipse.jface.text.BadLocationException { // Following code modified by LL on 13 Apr 2011 so that it // finds the correct beginning and end of the comment if // if the cursor is at right after the "(" or right before // the ")" that bracket the comment. int searchOffset = offset; if ((offset > 0) && text.charAt(offset - 1) == '(') { searchOffset++; } beginCommentOffset = text.lastIndexOf("(*", searchOffset); searchOffset = offset; if (text.charAt(offset) == ')') { searchOffset--; } endCommentOffset = text.indexOf("*)", searchOffset) + 2; IRegion beginCommentLineInfo = doc .getLineInformationOfOffset(beginCommentOffset); indent = beginCommentOffset - beginCommentLineInfo.getOffset(); margin = Math.max(RightMargin, indent + 4); }
/** * ����Ŀ��������ļ��в��Ҹ����Ĺؼ��� */ public void findInAllFiles(String word, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean showAll, boolean regularExpressions) { if (b.projectFile != null) { File dir = new File(b.projectFile.getParent() + "\\Files"); String[] files = dir.list(); for (String file : files) { File f = new File(dir + "\\" + file); ioThread io = new ioThread(b, f, 0, null, null, null); b.getDisplay().syncExec(io); ArrayList<IRegion> al = findwordInAllFiles(io.doc, word, forwardSearch, caseSensitive, wholeWord, regularExpressions); if (al != null && al.size() > 0) { TreeItem ti = b.addFindResultToTree( b.fileInfo.getProperty(f.getName(), f.getName()) + " " + al.size() + "�����"); ti.setData("file", f); ti.setData("iregions", al); } } } }
private boolean isBlockCommented(int startLine, int endLine, String[] prefixes, IDocument document) { try { // check for occurrences of prefixes in the given lines for (int i = startLine; i <= endLine; i++) { IRegion line = document.getLineInformation(i); String text = document.get(line.getOffset(), line.getLength()); int[] found = TextUtilities.indexOf(prefixes, text, 0); if (found[0] == -1) { // found a line which is not commented return false; } String s = document.get(line.getOffset(), found[0]); s = s.trim(); if (s.length() != 0) { // found a line which is not commented return false; } } return true; } catch (BadLocationException x) { // should not happen } return false; }
/** * Finds the locations in the given text and return the array of * regions pointing to those or an empty array, if no location were found. * A location is a pointer in the TLA file, e.G. "line 11, col 8 to line 14, col 26 of module Foo" * @param text text containing locations (error text) * @return array of regions or empty array */ public static IRegion[] findLocations(String text) { if (text == null || text.length() == 0) { return new IRegion[0]; } Matcher matcher = Location.LOCATION_MATCHER.matcher(text); Vector<IRegion> regions = new Vector<IRegion>(); while (matcher.find()) { regions.add(new Region(matcher.start(), matcher.end() - matcher.start())); } // look for this pattern also // this pattern appears when there // is an error evaluating a nested expression matcher = Location.LOCATION_MATCHER4.matcher(text); while (matcher.find()) { regions.add(new Region(matcher.start(), matcher.end() - matcher.start())); } return regions.toArray(new IRegion[regions.size()]); }
/** * Recalculate region in a document to four-int-coordinates * @param document * @param region * @param singleLine true, if the region covers one line only * @return four ints: begin line, begin column, end line, end column * @throws BadLocationException */ public static int[] regionToLocation(IDocument document, IRegion region, boolean singleLine) throws BadLocationException { if (!singleLine) { throw new IllegalArgumentException("Not implemented"); } int[] coordinates = new int[4]; // location of the id found in the provided document int offset = region.getOffset(); int length = region.getLength(); // since the id is written as one word, we are in the same line coordinates[0] = document.getLineOfOffset(offset) + 1; // begin line coordinates[2] = document.getLineOfOffset(offset) + 1; // end line // the columns are relative to the offset of the line IRegion line = document.getLineInformationOfOffset(offset); coordinates[1] = offset - line.getOffset(); // begin column coordinates[3] = coordinates[1] + length; // end column // return the coordinates return coordinates; }
/** * Decides if a "\begin{...}" needs a "\end{...}" * @param environment Name of the environment (...) * @param document The document as String * @param coffset The starting offset (just at the beginning of * the "\begin{...}" * @return true, if it needs an end, else false */ public static boolean needsEnd(String environment, String docString, int coffset) { int counter = 1; int offset = coffset; while (counter > 0) { IRegion end = LatexParserUtils.findEndEnvironment(docString, environment, offset + 5); if (end == null) { return true; } IRegion start = LatexParserUtils.findBeginEnvironment(docString, environment, offset + 7); if (start == null) { counter--; offset = end.getOffset(); } else if (end.getOffset() > start.getOffset()) { counter++; offset = start.getOffset(); } else { counter--; offset = end.getOffset(); } } return false; }
/** * 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); }
/** * Returns indentation, i.e. leading white space characters, of the line at the given region. Argument for * 'lineRegion' must cover the entire line excluding any line delimiters (i.e. exactly as returned by * {@link IDocument#getLineInformationOfOffset(int)}. */ public static String getIndent(IDocument doc, IRegion lineRegion) throws BadLocationException { final String currLine = doc.get(lineRegion.getOffset(), lineRegion.getLength()); int idx = 0; while (idx < currLine.length() && Character.isWhitespace(currLine.charAt(idx))) { idx++; } return currLine.substring(0, idx); }
/** * 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); }