org.eclipse.jface.text.IRegion Java Examples
The following examples show how to use
org.eclipse.jface.text.IRegion.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TMPresentationReconciler.java From tm4e with Eclipse Public License 1.0 | 6 votes |
private void colorize(ModelTokensChangedEvent event) { IDocument document = viewer.getDocument(); if (document == null) { return; } ITMModel model = event.model; if (! (model instanceof TMDocumentModel)) { return; } TMDocumentModel docModel = (TMDocumentModel) model; for (Range range : event.ranges) { try { int length = document.getLineOffset(range.toLineNumber - 1) + document.getLineLength(range.toLineNumber - 1) - document.getLineOffset(range.fromLineNumber - 1); IRegion region = new Region(document.getLineOffset(range.fromLineNumber -1), length); TMPresentationReconciler.this.colorize(region, docModel); } catch (BadLocationException ex) { TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, ex.getMessage(), ex)); } } }
Example #2
Source File: MissingSwitchDefaultQuickfix.java From eclipse-cs with GNU Lesser General Public License v2.1 | 6 votes |
/** * {@inheritDoc} */ @Override protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo, final int markerStartOffset) { return new ASTVisitor() { @SuppressWarnings("unchecked") @Override public boolean visit(SwitchStatement node) { if (containsPosition(lineInfo, node.getStartPosition())) { SwitchCase defNode = node.getAST().newSwitchCase(); defNode.setExpression(null); node.statements().add(defNode); node.statements().add(node.getAST().newBreakStatement()); } return true; // also visit children } }; }
Example #3
Source File: DeleteWhitespaceHandler.java From e4macs with Eclipse Public License 1.0 | 6 votes |
/** * Delete the whitespace at the end of each line from the bottom up * * @param lastLine last line in the region * @param firstLine first line in the region * @param maxOffset when narrowed, this is the last offset on the last line * @param document the model * @throws BadLocationException */ private void deleteWhitepace(int lastLine, int firstLine, int maxOffset, IDocument document) throws BadLocationException { // bottoms up for (int i= lastLine; i >= firstLine; i--) { IRegion line= document.getLineInformation(i); if (line.getLength() == 0) continue; int lineStart= line.getOffset(); int lineLen = line.getLength(); int lineEnd = lineStart + lineLen; if (lineEnd > maxOffset) { lineLen -= (lineEnd - maxOffset) - 1; lineEnd = maxOffset; } else { lineEnd--; } int j= lineEnd; // String t = document.get(lineStart,line.getLength()); while (j >= lineStart && Character.isWhitespace(document.getChar(j))) --j; if (j < lineEnd) { String newText = document.get(lineStart,(j - lineStart)+1); updateText(document,lineStart,lineLen ,newText); } } }
Example #4
Source File: UiBinderUtilities.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
/** * Finds the EL expressions's contents in the given text. * * @param in the text containing EL expressions. * @return a non-null list of regions of the contents of EL expressions */ public static List<IRegion> getElExpressionRegions(String in) { final Pattern braces = Pattern.compile("[{]([^}]*)[}]"); final Pattern legalFirstChar = Pattern.compile("^[$_a-zA-Z].*"); final List<IRegion> list = new ArrayList<IRegion>(); int nextFindStart = 0; Matcher m = braces.matcher(in); while (m.find(nextFindStart)) { String fieldReference = m.group(1); if (!legalFirstChar.matcher(fieldReference).matches()) { nextFindStart = m.start() + 2; continue; } list.add(new Region(m.start(1), m.end(1) - m.start(1))); nextFindStart = m.end(); } return list; }
Example #5
Source File: RenameAnalyzeUtil.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private static boolean existsInNewOccurrences(SearchMatch searchResult, SearchResultGroup[] newOccurrences, TextChangeManager manager) { SearchResultGroup newGroup= findOccurrenceGroup(searchResult.getResource(), newOccurrences); if (newGroup == null) { return false; } IRegion oldEditRange= getCorrespondingEditChangeRange(searchResult, manager); if (oldEditRange == null) { return false; } SearchMatch[] newSearchResults= newGroup.getSearchResults(); int oldRangeOffset = oldEditRange.getOffset(); for (int i= 0; i < newSearchResults.length; i++) { if (newSearchResults[i].getOffset() == oldRangeOffset) { return true; } } return false; }
Example #6
Source File: LatexParserUtils.java From texlipse with Eclipse Public License 1.0 | 6 votes |
/** * Finds for a \begin{env} the matching \end{env}. * @param input * @param envName Name of the environment, e.g. "itemize" * @param beginIndex Must be at the start or inside of \begin{env} * @return The region of the \end{env} command or null if the end was not found */ public static IRegion findMatchingEndEnvironment(String input, String envName, int beginIndex) { int pos = beginIndex + 1; IRegion nextEnd, nextBegin; int level = 0; do { nextEnd = findEndEnvironment(input, envName, pos); nextBegin = findBeginEnvironment(input, envName, pos); if (nextEnd == null) return null; if (nextBegin == null) { level--; pos = nextEnd.getOffset() + envName.length() + 6; } else { if (nextBegin.getOffset() > nextEnd.getOffset()) level--; else level++; pos = nextBegin.getOffset() + envName.length() + 8; } } while (level >= 0); return nextEnd; }
Example #7
Source File: SelectNextOccurrenceHandler.java From eclipse-multicursor with Eclipse Public License 1.0 | 6 votes |
private void startLinkedEdit(List<IRegion> selections, ITextViewer viewer, Point originalSelection) throws BadLocationException { final LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup(); for (IRegion selection : selections) { linkedPositionGroup.addPosition(new LinkedPosition(viewer.getDocument(), selection.getOffset(), selection .getLength())); } LinkedModeModel model = new LinkedModeModel(); model.addGroup(linkedPositionGroup); model.forceInstall(); //FIXME can add a listener here to listen for the end of linked mode //model.addLinkingListener(null); LinkedModeUI ui = new EditorLinkedModeUI(model, viewer); ui.setExitPolicy(new DeleteBlockingExitPolicy(viewer.getDocument())); ui.enter(); // by default the text being edited is selected so restore original selection viewer.setSelectedRange(originalSelection.x, originalSelection.y); }
Example #8
Source File: FinalParametersQuickfix.java From eclipse-cs with GNU Lesser General Public License v2.1 | 6 votes |
/** * {@inheritDoc} */ @Override protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo, final int markerStartOffset) { return new ASTVisitor() { @SuppressWarnings("unchecked") @Override public boolean visit(SingleVariableDeclaration node) { if (containsPosition(node, markerStartOffset) && !Modifier.isFinal(node.getModifiers())) { if (!Modifier.isFinal(node.getModifiers())) { Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD); node.modifiers().add(finalModifier); } } return true; } }; }
Example #9
Source File: ScopeSelectionAction.java From Pydev with Eclipse Public License 1.0 | 6 votes |
public void deselect(BaseEditor editor) { FastStack<IRegion> stack = ScopeSelectionAction.getCache(editor); ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection(); Region region = new Region(selection.getOffset(), selection.getLength()); Iterator<IRegion> it = stack.topDownIterator(); while (it.hasNext()) { IRegion iRegion = it.next(); stack.pop(); //After getting the latest, pop it. if (iRegion.equals(region)) { if (stack.size() > 0) { IRegion peek = stack.peek(); editor.setSelection(peek.getOffset(), peek.getLength()); } break; } } }
Example #10
Source File: MarkerPlacementStrategy.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
private IMarker createMarker(IResource resource, IDocument document, IRegion position, String msg, int severity) throws CoreException { if (isDuplicate(resource, position, msg)) { return null; } IMarker marker = MarkerUtilities.createMarker(markerId, resource, msg, severity); marker.setAttribute(IMarker.CHAR_START, position.getOffset()); marker.setAttribute(IMarker.CHAR_END, position.getOffset() + position.getLength()); try { // +1 since the attribute is 1-relative but document.getLineOfOffset is // 0-relative marker.setAttribute(IMarker.LINE_NUMBER, document.getLineOfOffset(position.getOffset()) + 1); } catch (BadLocationException e) { GWTPluginLog.logWarning(e, "Unexpected bad location when getting line number for marker."); } return marker; }
Example #11
Source File: ToggleCommentHandler.java From xds-ide with Eclipse Public License 1.0 | 6 votes |
protected boolean isSelectionCommented(IDocument document, ITextSelection selection, String commentPrefix) { try { for (int lineNum = selection.getStartLine(); lineNum <= selection.getEndLine(); ++lineNum) { IRegion r = document.getLineInformation(lineNum); String str = document.get(r.getOffset(), r.getLength()).trim(); if (!str.startsWith(commentPrefix)) { return false; } } return true; } catch (Exception x) { } return false; }
Example #12
Source File: N4JSStackTraceHyperlink.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** * Returns this link's text * * @return the complete text of the link, never <code>null</code> * @exception CoreException * if unable to retrieve the text */ protected String getLinkText() throws CoreException { try { IDocument document = getConsole().getDocument(); IRegion region = getConsole().getRegion(this); int regionOffset = region.getOffset(); int lineNumber = document.getLineOfOffset(regionOffset); IRegion lineInformation = document.getLineInformation(lineNumber); int lineOffset = lineInformation.getOffset(); String line = document.get(lineOffset, lineInformation.getLength()); int regionOffsetInLine = regionOffset - lineOffset; int linkEnd = line.indexOf(')', regionOffsetInLine); int linkStart = line.lastIndexOf(' ', regionOffsetInLine); return line.substring(linkStart == -1 ? 0 : linkStart + 1, linkEnd + 1); } catch (BadLocationException e) { IStatus status = new Status(IStatus.ERROR, N4JSActivator.PLUGIN_ID, 0, ConsoleMessages.msgUnableToParseLinkText(), e); throw new CoreException(status); } }
Example #13
Source File: UpperEllQuickFix.java From vscode-checkstyle with GNU Lesser General Public License v3.0 | 6 votes |
@Override public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) { return new ASTVisitor() { @Override public boolean visit(NumberLiteral node) { if (containsPosition(node, markerStartOffset)) { String token = node.getToken(); if (token.endsWith("l")) { //$NON-NLS-1$ token = token.replace('l', 'L'); node.setToken(token); } } return true; } }; }
Example #14
Source File: ModulaEditorTextHover.java From xds-ide with Eclipse Public License 1.0 | 6 votes |
/** * {@inheritDoc} */ @Override public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { // Check through the contributed hover providers. for (ITextHover hoverContributer : hoverContributors) { @SuppressWarnings("deprecation") String hoverText = hoverContributer.getHoverInfo(textViewer, hoverRegion); if (hoverText != null) { lastReturnedHover = hoverContributer; return hoverText; } } return String.valueOf(getHoverInfo2(textViewer, hoverRegion)); }
Example #15
Source File: OpenAction.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@Override public void run(ITextSelection selection) { if (!checkEnabled(selection)) return; IRegion region= new Region(selection.getOffset(), selection.getLength()); PropertyKeyHyperlinkDetector detector= new PropertyKeyHyperlinkDetector(); detector.setContext(fEditor); IHyperlink[]hyperlinks= detector.detectHyperlinks(fEditor.internalGetSourceViewer(), region, false); if (hyperlinks != null && hyperlinks.length == 1) hyperlinks[0].open(); }
Example #16
Source File: EmbeddedEditorModelAccess.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
public String getEditablePart() { IDocument doc = this.viewer.getDocument(); IRegion visible = this.viewer.getVisibleRegion(); try { return doc.get(visible.getOffset(), visible.getLength()); } catch (BadLocationException e) { return ""; //$NON-NLS-1$ } }
Example #17
Source File: JSDocEditStrategy.java From n4js with Eclipse Public License 1.0 | 5 votes |
/** * Expects the cursor to be in the same line as the start terminal puts any text between start terminal and cursor * into a separate newline before the cursor. puts any text between cursor and end terminal into a separate newline * after the cursor. puts the closing terminal into a separate line at the end. adds a closing terminal if not * existent. If the next astElement is a method with parameters or return the JSDoc-tags will be added as an * addition. */ @Override protected CommandInfo handleCursorInFirstLine(IDocument document, DocumentCommand command, IRegion startTerminal, IRegion stopTerminal) throws BadLocationException { CommandInfo newC = new CommandInfo(); List<String> returnTypeAndParameterNames = getReturnTypeAndParameterNames(document, startTerminal); String paramString = ""; String returnString = ""; if ((returnTypeAndParameterNames.size() > 0) && returnTypeAndParameterNames.get(0).equals("return")) { returnString = INDENTATION_STR + RETURN_STR + command.text; } if (returnTypeAndParameterNames.size() > 1) { for (int i = 1; i < returnTypeAndParameterNames.size(); i += 1) { paramString += command.text + INDENTATION_STR + PARAM_STR + returnTypeAndParameterNames.get(i); } } newC.isChange = true; newC.offset = command.offset; newC.text += command.text + INDENTATION_STR; newC.cursorOffset = command.offset + newC.text.length(); if (stopTerminal == null && atEndOfLineInput(document, command.offset)) { newC.text += command.text + getRightTerminal(); } if (stopTerminal != null && stopTerminal.getOffset() >= command.offset && util.isSameLine(document, stopTerminal.getOffset(), command.offset)) { String string = document.get(command.offset, stopTerminal.getOffset() - command.offset); if (string.trim().length() > 0) newC.text += string.trim(); if (!(returnTypeAndParameterNames.size() == 0)) { newC.text += paramString + command.text + returnString; } else { newC.text += command.text; } newC.length += string.length(); } return newC; }
Example #18
Source File: XtextInformationProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * Just for compatibility reasons * {@link org.eclipse.jface.text.information.IInformationProvider#getInformation(ITextViewer, IRegion)} */ @Override @Deprecated public String getInformation(ITextViewer textViewer, IRegion subject) { if(hover instanceof ITextHoverExtension2){ Object hoverInfo2 = ((ITextHoverExtension2) hover).getHoverInfo2(textViewer, subject); return hoverInfo2!= null ? hoverInfo2.toString():null; } return null; }
Example #19
Source File: JavaDocContext.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Returns the indentation level at the position of code completion. * * @return the indentation level at the position of the code completion */ private int getIndentation() { int start= getStart(); IDocument document= getDocument(); try { IRegion region= document.getLineInformationOfOffset(start); String lineContent= document.get(region.getOffset(), region.getLength()); IJavaProject project= getJavaProject(); return Strings.computeIndentUnits(lineContent, project); } catch (BadLocationException e) { return 0; } }
Example #20
Source File: TypeScriptSourceValidator.java From typescript.java with MIT License | 5 votes |
@Override public void validate(IRegion dirtyRegion, IValidationContext helper, IReporter reporter) { // Never called, because TypeScriptSourceValidator is declared as // "total" (and // not "partial") in the plugin.xml // "org.eclipse.wst.sse.ui.sourcevalidation" extension point. }
Example #21
Source File: AddImportOnSelectionAction.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private IEditingSupport createViewerHelper(final ITextSelection selection, final SelectTypeQuery query) { return new IEditingSupport() { public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) { return subjectRegion.getOffset() <= selection.getOffset() + selection.getLength() && selection.getOffset() <= subjectRegion.getOffset() + subjectRegion.getLength(); } public boolean ownsFocusShell() { return query.isShowing(); } }; }
Example #22
Source File: SnippetsCompletionProcessor.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
@Override protected ICompletionProposal createProposal(Template template, TemplateContext context, IRegion region, int relevance) { if (template instanceof SnippetTemplate) { return new SnippetTemplateProposal(template, context, region, getImage(template), relevance); } return new CommandProposal(template, context, region, getImage(template), relevance); }
Example #23
Source File: JsniParserTest.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
public void testParseMethodDeclaration() { // Have JDT parse the compilation unit ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(getTestProject()); parser.setResolveBindings(false); parser.setSource(testClass.getCompilationUnit()); CompilationUnit root = (CompilationUnit) parser.createAST(null); // Find the JSNI method and parse it TypeDeclaration typeDecl = (TypeDeclaration) root.types().get(0); MethodDeclaration jsniMethod = typeDecl.getMethods()[0]; JavaValidationResult result = JsniParser.parse(jsniMethod); // Verify the Java refs List<JsniJavaRef> refs = result.getJavaRefs(); assertEquals(3, refs.size()); assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.A$B::getNumber()"))); assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.JsniParserTest::getSum(II)"))); assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.JsniParserTest::counter"))); // Verify the problems List<GWTJavaProblem> problems = result.getProblems(); assertEquals(1, problems.size()); GWTJavaProblem problem = problems.get(0); assertEquals(GWTProblemType.JSNI_JAVA_REF_UNRESOLVED_TYPE, problem.getProblemType()); IRegion expectedProblemRegion = RegionConverter.convertWindowsRegion(184, 0, testClass.getContents()); assertEquals(expectedProblemRegion.getOffset(), problem.getSourceStart()); }
Example #24
Source File: DotHtmlLabelDoubleClickStrategy.java From gef with Eclipse Public License 2.0 | 5 votes |
private IRegion findExtendedSelectionHtml( ITextDoubleClickStrategy doubleClickStrategy, IDocument htmlDocument, int htmlLabelClickOffset) { Method findExtendedSelection = findExtendedDoubleClickSelectionMethod( doubleClickStrategy.getClass()); return invokeMethodOn(findExtendedSelection, doubleClickStrategy, htmlDocument, htmlLabelClickOffset); }
Example #25
Source File: ModulaInformationProvider.java From xds-ide with Eclipse Public License 1.0 | 5 votes |
public IRegion getSubject(ITextViewer textViewer, int offset) { createHover(textViewer); if (hover != null) { return hover.getHoverRegion(textViewer, offset); } return null; }
Example #26
Source File: DefaultSpellingEngine.java From xds-ide with Eclipse Public License 1.0 | 5 votes |
@Override public void check(IDocument document, IRegion[] regions, SpellingContext context, ISpellingProblemCollector collector, IProgressMonitor monitor) { ISpellingEngine engine = getEngine(context.getContentType()); if (engine == null){ engine = getEngine(TEXT_CONTENT_TYPE); } if (engine != null){ engine.check(document, regions, context, collector, monitor); } }
Example #27
Source File: PresentationDamager.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * @return <code>true</code> only if the lastDamage is encloses the affected text of the given DocumentEvent. */ protected boolean isEventMatchingLastDamage(DocumentEvent e, IRegion lastDamage) { int eventStart = e.getOffset(); int eventEnd = eventStart+e.getText().length(); int damageStart = lastDamage.getOffset(); int damageEnd = damageStart+lastDamage.getLength(); boolean result = damageStart<=eventStart && damageEnd>=eventEnd; return result; }
Example #28
Source File: HierarchyInformationPresenter.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected IRegion modelRange2WidgetRange(IRegion region) { if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; return extension.modelRange2WidgetRange(region); } IRegion visibleRegion = sourceViewer.getVisibleRegion(); int start = region.getOffset() - visibleRegion.getOffset(); int end = start + region.getLength(); if (end > visibleRegion.getLength()) end = visibleRegion.getLength(); return new Region(start, end - start); }
Example #29
Source File: TextSelectionUtils.java From Pydev with Eclipse Public License 1.0 | 5 votes |
/** * @return if the region passed is composed of a single line */ public static boolean endsInSameLine(IDocument document, IRegion region) { try { int startLine = document.getLineOfOffset(region.getOffset()); int end = region.getOffset() + region.getLength(); int endLine = document.getLineOfOffset(end); return startLine == endLine; } catch (BadLocationException e) { return false; } }
Example #30
Source File: CSSElementSelectorHover.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) { try { IParseNode activeNode = getActiveNode(textViewer, hoverRegion.getOffset()); if (!(activeNode instanceof CSSSimpleSelectorNode)) { return null; } CSSSimpleSelectorNode node = (CSSSimpleSelectorNode) activeNode; ElementElement element = new HTMLIndexQueryHelper().getElement(node.getTypeSelector().toLowerCase()); // To avoid duplicating work, we generate the header and documentation together here // and then getHeader and getDocumentation just return the values. if (element != null) { fHeader = HTMLModelFormatter.TEXT_HOVER.getHeader(element); fDocs = HTMLModelFormatter.TEXT_HOVER.getDocumentation(element); return getHoverInfo(element, isBrowserControlAvailable(textViewer), null, getEditor(textViewer), hoverRegion); } return null; } finally { fHeader = null; fDocs = null; } }