Java Code Examples for org.eclipse.jface.text.ITextViewer#getDocument()
The following examples show how to use
org.eclipse.jface.text.ITextViewer#getDocument() .
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: AbstractJavaEditorTextHover.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Returns the Java elements at the given hover region. * * @param textViewer the text viewer * @param hoverRegion the hover region * @return the array with the Java elements or <code>null</code> * @since 3.4 */ protected IJavaElement[] getJavaElementsAt(ITextViewer textViewer, IRegion hoverRegion) { /* * The region should be a word region an not of length 0. * This check is needed because codeSelect(...) also finds * the Java element if the offset is behind the word. */ if (hoverRegion.getLength() == 0) return null; IDocument document= textViewer.getDocument(); if (document != null && isInheritDoc(document, hoverRegion)) return null; ICodeAssist resolve= getCodeAssist(); if (resolve != null) { try { return resolve.codeSelect(hoverRegion.getOffset(), hoverRegion.getLength()); } catch (JavaModelException x) { return null; } } return null; }
Example 2
Source File: OverrideMethodCompletionProposal.java From Pydev with Eclipse Public License 1.0 | 6 votes |
@Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { IDocument document = viewer.getDocument(); int finalOffset = applyOnDocument(viewer, document, trigger, stateMask, offset); if (finalOffset >= 0) { try { PySelection ps = new PySelection(document, finalOffset); int firstCharPosition = PySelection.getFirstCharPosition(ps.getLine()); int lineOffset = ps.getLineOffset(); int location = lineOffset + firstCharPosition; int len = finalOffset - location; fCursorPosition = location; fReplacementLength = len; } catch (Exception e) { Log.log(e); } } }
Example 3
Source File: AbstractJsonHyperlinkDetector.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 6 votes |
@Override public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { JsonDocument document = (JsonDocument) textViewer.getDocument(); JsonPointer basePath = document.getPath(region); if (!canDetect(basePath)) { return null; } HyperlinkInfo info = getHyperlinkInfo(textViewer, region); if (info == null) { return null; } return doDetect(document, textViewer, info, basePath); }
Example 4
Source File: ResourceUtils.java From LogViewer with Eclipse Public License 2.0 | 6 votes |
public static IConsole getConsole(IWorkbenchPart part) { if(!(part instanceof IViewPart)){ return null; } IViewPart vp =(IViewPart) part; if (vp instanceof PageBookView) { IPage page = ((PageBookView) vp).getCurrentPage(); ITextViewer viewer = getViewer(page); if (viewer == null || viewer.getDocument() == null) return null; } IConsole con = null; try { con = ((IConsoleView)part).getConsole(); } catch (Exception e) { } return con; }
Example 5
Source File: XtextTemplateProposal.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
@Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { IDocument document = viewer.getDocument(); // ImportsVariableResolver may add imports, so start a rewrite session if possible. // This will compound all document changes in one Undo entry. if (document instanceof IDocumentExtension4) { IDocumentExtension4 docExt4 = (IDocumentExtension4) document; DocumentRewriteSession session = docExt4.startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED); super.apply(viewer, trigger, stateMask, offset); if (session != null) { docExt4.stopRewriteSession(session); } } else { super.apply(viewer, trigger, stateMask, offset); } }
Example 6
Source File: CodeTemplateSourceViewerConfiguration.java From typescript.java with MIT License | 6 votes |
public String getHoverInfo(ITextViewer textViewer, IRegion subject) { try { IDocument doc= textViewer.getDocument(); int offset= subject.getOffset(); if (offset >= 2 && "${".equals(doc.get(offset-2, 2))) { //$NON-NLS-1$ String varName= doc.get(offset, subject.getLength()); TemplateContextType contextType= fProcessor.getContextType(); if (contextType != null) { Iterator iter= contextType.resolvers(); while (iter.hasNext()) { TemplateVariableResolver var= (TemplateVariableResolver) iter.next(); if (varName.equals(var.getType())) { return var.getDescription(); } } } } } catch (BadLocationException e) { } return null; }
Example 7
Source File: SnippetContentAssistProcessor.java From corrosion with Eclipse Public License 2.0 | 5 votes |
@Override public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { IDocument document = viewer.getDocument(); String textToOffset = document.get().substring(0, offset); if (isOffsetInComment(textToOffset)) { return new ICompletionProposal[0]; } Matcher matcher = ENDS_WITH_WORD_PATTERN.matcher(textToOffset.substring(textToOffset.lastIndexOf('\n') + 1)); matcher.matches(); String indent = matcher.group("indent"); //$NON-NLS-1$ String prefix = matcher.group("prefix"); //$NON-NLS-1$ // Use range from selection (if available) to support "surround with" style // completions Range range = getRangeFromSelection(document, viewer).orElseGet(() -> { // no selection available: get range from prefix try { int line = document.getLineOfOffset(offset); int lineOffset = offset - document.getLineOffset(line); Position start = new Position(line, lineOffset - prefix.length()); Position end = new Position(line, lineOffset); return new Range(start, end); } catch (BadLocationException e) { return null; } }); if (range == null) { return new ICompletionProposal[] {}; } Collection<LSPDocumentInfo> infos = LanguageServiceAccessor.getLSPDocumentInfosFor(document, capabilities -> Boolean.TRUE.equals(capabilities.getReferencesProvider())); LSPDocumentInfo docInfo = infos.iterator().next(); ICompletionProposal[] proposals = snippets.stream().filter(s -> s.matchesPrefix(prefix)) .map(s -> s.convertToCompletionProposal(offset, docInfo, prefix, indent, range)) .toArray(ICompletionProposal[]::new); return proposals; }
Example 8
Source File: TMPresentationReconciler.java From tm4e with Eclipse Public License 1.0 | 5 votes |
@Override public void install(ITextViewer viewer) { Assert.isNotNull(viewer); this.viewer = viewer; viewer.addTextInputListener(internalListener); IDocument document = viewer.getDocument(); if (document != null) { internalListener.inputDocumentChanged(null, document); } themeChangeListener = new ThemeChangeListener(); ThemeManager.getInstance().addPreferenceChangeListener(themeChangeListener); }
Example 9
Source File: PyDocumentTemplateContext.java From Pydev with Eclipse Public License 1.0 | 5 votes |
/** * Creates a concrete template context for the given region in the document. This involves finding out which * context type is valid at the given location, and then creating a context of this type. The default implementation * returns a <code>DocumentTemplateContext</code> for the context type at the given location. * * @param contextType the context type for the template. * @param viewer the viewer for which the context is created * @param region the region into <code>document</code> for which the context is created * @return a template context that can handle template insertion at the given location, or <code>null</code> */ public static PyDocumentTemplateContext createContext(final TemplateContextType contextType, final ITextViewer viewer, final IRegion region, String indent) { if (contextType != null) { IDocument document = viewer.getDocument(); final String indentTo = indent; return new PyDocumentTemplateContext(contextType, document, region.getOffset(), region.getLength(), indentTo, viewer); } return null; }
Example 10
Source File: XMLAttributeProposal.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
/** * Special code added to allow tabstop positions so we can easily tab past the quotes for Events/Attributes. */ @Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { super.apply(viewer, trigger, stateMask, offset); // See if there are any positions that should be linked. Last is always exit, first is cursor position if (_positions != null && _positions.length > 0) { IDocument document = viewer.getDocument(); boolean validPrefix = isValidPrefix(getPrefix(document, offset), getDisplayString()); int shift = (validPrefix) ? offset - this._replacementOffset : 0; try { LinkedModeModel.closeAllModels(document); // Exit out of any existing linked mode LinkedModeModel model = new LinkedModeModel(); int i = 0; for (int pos : _positions) { LinkedPositionGroup group = new LinkedPositionGroup(); group.addPosition(new LinkedPosition(document, (offset - shift) + pos, 0, i++)); model.addGroup(group); } model.forceInstall(); LinkedModeUI ui = new LinkedModeUI(model, viewer); ui.setCyclingMode(LinkedModeUI.CYCLE_ALWAYS); ui.setExitPosition(viewer, (offset - shift) + _positions[_positions.length - 1], 0, Integer.MAX_VALUE); ui.enter(); } catch (BadLocationException e) { IdeLog.logError(XMLPlugin.getDefault(), e); } } }
Example 11
Source File: AttributeOrEventProposal.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
/** * Special code added to allow tabstop positions so we can easily tab past the quotes for Events/Attributes. */ @Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { super.apply(viewer, trigger, stateMask, offset); // See if there are any positions that should be linked. Last is always exit, first is cursor position if (_positions != null && _positions.length > 0) { IDocument document = viewer.getDocument(); boolean validPrefix = isValidPrefix(getPrefix(document, offset), getDisplayString()); int shift = (validPrefix) ? offset - this._replacementOffset : 0; try { LinkedModeModel.closeAllModels(document); // Exit out of any existing linked mode LinkedModeModel model = new LinkedModeModel(); int i = 0; for (int pos : _positions) { LinkedPositionGroup group = new LinkedPositionGroup(); group.addPosition(new LinkedPosition(document, (offset - shift) + pos, 0, i++)); model.addGroup(group); } model.forceInstall(); LinkedModeUI ui = new LinkedModeUI(model, viewer); ui.setCyclingMode(LinkedModeUI.CYCLE_ALWAYS); ui.setExitPosition(viewer, (offset - shift) + _positions[_positions.length - 1], 0, Integer.MAX_VALUE); ui.enter(); } catch (BadLocationException e) { IdeLog.logError(HTMLPlugin.getDefault(), e); } } }
Example 12
Source File: ToolboxCompletionProcessor.java From tlaplus with MIT License | 5 votes |
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { final IDocument document = viewer.getDocument(); // get the selection range final Point selectedRange = viewer.getSelectedRange(); final List<ICompletionProposal> propList = new ArrayList<ICompletionProposal>(); try { // The zero-based row index of the caret. final int caretRowIndex = document.getLineOfOffset(offset); // The zero-based column index of the caret. final int carretColumnIndex = offset - document.getLineOffset(caretRowIndex); if (selectedRange.y > 0) { // the range is non-empty final String text = document.get(selectedRange.x, selectedRange.y); computeWordProposals(text, offset, carretColumnIndex, propList); } else { // the range is empty, no selection in the editor // get the region final IRegion wordRegion = DocumentHelper.getRegionExpandedBackwards(document, offset, DocumentHelper.getDefaultWordDetector()); final String word = document.get(wordRegion.getOffset(), wordRegion.getLength()); computeWordProposals(word, offset, carretColumnIndex, propList); } } catch (final BadLocationException ignore) { } return propList.toArray(new ICompletionProposal[propList.size()]); }
Example 13
Source File: ImpexTypeHyperlinkDetector.java From hybris-commerce-eclipse-plugin with Apache License 2.0 | 4 votes |
@Override public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { IDocument document = textViewer.getDocument(); int offset = region.getOffset(); // extract relevant characters IRegion lineRegion; String candidate; try { lineRegion = document.getLineInformationOfOffset(offset); candidate = document.get(lineRegion.getOffset(), lineRegion.getLength()); } catch (BadLocationException ex) { return null; } String upperCandidate = candidate.toUpperCase(Locale.ENGLISH); if (upperCandidate.startsWith("INSERT") || upperCandidate.startsWith("REMOVE") || upperCandidate.startsWith("UPDATE")) { // look for keyword if (allTypeNames == null) { allTypeNames = Activator.getDefault().getAllTypeNames(); } String headerPlusType = candidate.substring(0, candidate.indexOf(";")); String typeName = headerPlusType.substring(candidate.indexOf(" ") + 1, headerPlusType.length()); if (allTypeNames.contains(typeName)) { int index = candidate.indexOf(typeName); if (index != -1) { // detect region containing keyword IRegion targetRegion = new Region(lineRegion.getOffset() + index, typeName.length()); if ((targetRegion.getOffset() <= offset) && ((targetRegion.getOffset() + targetRegion.getLength()) > offset)) { try { return new IHyperlink[] { new ImpexTypeHyperlink(targetRegion, document.get(targetRegion.getOffset(), targetRegion.getLength())) }; } catch (BadLocationException e) { Activator.logError("BadLocationException", e); } } } } } return null; }
Example 14
Source File: PySelectionFromEditor.java From Pydev with Eclipse Public License 1.0 | 4 votes |
public static PySelection createPySelectionFromEditor(ITextViewer viewer, ITextSelection textSelection) { return new PySelection(viewer.getDocument(), new CoreTextSelection( viewer.getDocument(), textSelection.getOffset(), textSelection.getLength())); }
Example 15
Source File: JsonContentAssistProcessor.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 4 votes |
@Override public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { if (!(viewer.getDocument() instanceof JsonDocument)) { return super.computeCompletionProposals(viewer, documentOffset); } maybeSwitchScope(documentOffset); final JsonDocument document = (JsonDocument) viewer.getDocument(); final ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection(); int line = 0, lineOffset = 0, column = 0; try { line = document.getLineOfOffset(documentOffset); lineOffset = document.getLineOffset(line); column = selection.getOffset() - lineOffset; } catch (BadLocationException e) { } final String prefix = extractPrefix(viewer, documentOffset); // we have to remove the length of // the prefix to obtain the correct // column to resolve the path if (!prefix.isEmpty()) { column -= prefix.length(); } currentModel = document.getModel(documentOffset - prefix.length()); currentPath = currentModel.getPath(line, column); isRefCompletion = referenceProposalProvider.canProvideProposal(currentModel, currentPath); Collection<ProposalDescriptor> kaizenProposals; if (isRefCompletion) { updateStatus(); kaizenProposals = referenceProposalProvider.getProposals(currentPath, document, currentScope); } else { clearStatus(); kaizenProposals = proposalProvider.getProposals(currentPath, currentModel, prefix); } final Collection<ICompletionProposal> proposals = getCompletionProposals(kaizenProposals, prefix, documentOffset, selection.getText()); // compute template proposals only if not trying to propose references if (!isRefCompletion) { List<ICompletionProposal> templateProposals = filterTemplateProposals( super.computeCompletionProposals(viewer, documentOffset), prefix); if (!templateProposals.isEmpty()) { proposals.addAll(templateProposals); } } return proposals.toArray(new ICompletionProposal[proposals.size()]); }
Example 16
Source File: TextViewerMoveLinesAction.java From xtext-eclipse with Eclipse Public License 2.0 | 4 votes |
@Override public void runWithEvent(Event event) { ITextViewer viewer = getTextViewer(); if (viewer == null) return; if (!canModifyViewer()) return; // get involved objects IDocument document= viewer.getDocument(); if (document == null) return; StyledText widget= viewer.getTextWidget(); if (widget == null) return; // get selection ITextSelection sel= (ITextSelection) viewer.getSelectionProvider().getSelection(); if (sel.isEmpty()) return; ITextSelection skippedLine= getSkippedLine(document, sel); if (skippedLine == null) return; try { ITextSelection movingArea= getMovingSelection(document, sel, viewer); // if either the skipped line or the moving lines are outside the widget's // visible area, bail out if (!containedByVisibleRegion(movingArea, viewer) || !containedByVisibleRegion(skippedLine, viewer)) return; // get the content to be moved around: the moving (selected) area and the skipped line String moving= movingArea.getText(); String skipped= skippedLine.getText(); if (moving == null || skipped == null || document.getLength() == 0) return; String delim; String insertion; int offset, deviation; if (fUpwards) { delim= document.getLineDelimiter(skippedLine.getEndLine()); if (fCopy) { delim= TextUtilities.getDefaultLineDelimiter(document); insertion= moving + delim; offset= movingArea.getOffset(); deviation= 0; } else { Assert.isNotNull(delim); insertion= moving + delim + skipped; offset= skippedLine.getOffset(); deviation= -skippedLine.getLength() - delim.length(); } } else { delim= document.getLineDelimiter(movingArea.getEndLine()); if (fCopy) { if (delim == null) { delim= TextUtilities.getDefaultLineDelimiter(document); insertion= delim + moving; } else { insertion= moving + delim; } offset= skippedLine.getOffset(); deviation= movingArea.getLength() + delim.length(); } else { Assert.isNotNull(delim); insertion= skipped + delim + moving; offset= movingArea.getOffset(); deviation= skipped.length() + delim.length(); } } // modify the document beginCompoundEdit(); if (fCopy) { document.replace(offset, 0, insertion); } else { document.replace(offset, insertion.length(), insertion); } // move the selection along int selOffset= movingArea.getOffset() + deviation; int selLength= movingArea.getLength() + (fAddDelimiter ? delim.length() : 0); if (! (viewer instanceof ITextViewerExtension5)) selLength= Math.min(selLength, viewer.getVisibleRegion().getOffset() + viewer.getVisibleRegion().getLength() - selOffset); else { // TODO need to check what is necessary in the projection case } selectAndReveal(viewer, selOffset, selLength); } catch (BadLocationException x) { // won't happen without concurrent modification - bail out return; } }
Example 17
Source File: QuotedCompletionProposal.java From APICloud-Studio with GNU General Public License v3.0 | 4 votes |
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { try { IDocument document = viewer.getDocument(); // Handle wrapping in quotes if necessary char prevChar = _replacementOffset > 0 ? document.getChar(_replacementOffset - 1) : ' '; char quote = '"'; switch (prevChar) { case '\'': quote = '\''; break; case '"': // We're fine break; default: if (addLeading) { // Add wrapping quotes _replacementString = "\"" + _replacementString; //$NON-NLS-1$ _cursorPosition++; } break; } if (addTrailing) { // handle adding trailing space if necessary int nextCharIndex = _replacementOffset + _replacementLength; if (nextCharIndex >= document.getLength()) { // Add a close quote when we're against the EOF _replacementString += quote; _cursorPosition++; } else { char nextChar = document.getChar(nextCharIndex); switch (nextChar) { case ' ': case '\t': case '\r': case '\n': case '\f': // add close quote _replacementString += quote; _cursorPosition++; break; default: if (addEndQuote(nextChar)) { // Add a close quote and then a space _replacementString += quote + " "; //$NON-NLS-1$ _cursorPosition += 2; } break; } } } } catch (BadLocationException e) { // ignore } super.apply(viewer, trigger, stateMask, offset); }
Example 18
Source File: HTMLTextHover.java From APICloud-Studio with GNU General Public License v3.0 | 4 votes |
protected BaseElement getMatchingElement(ITextViewer textViewer, IRegion hoverRegion, HTMLElementNode node) { // Hover over start tag? IRange elementNameRange = node.getNameNode().getNameRange(); if (!elementNameRange.contains(hoverRegion.getOffset())) { return null; } // Check if we're hovering over the tag/element name try { IDocument doc = textViewer.getDocument(); String openTagContent = doc.get(elementNameRange.getStartingOffset(), elementNameRange.getLength()); int index = openTagContent.indexOf(node.getName()); IRange tagNameRange = new Range(elementNameRange.getStartingOffset() + index, elementNameRange.getStartingOffset() + index + node.getName().length()); if (tagNameRange.contains(hoverRegion.getOffset())) { return new HTMLIndexQueryHelper().getElement(node.getElementName().toLowerCase()); } } catch (BadLocationException e) { // ignore } // Are we hovering over an attribute? IParseNodeAttribute attr = node.getAttributeAtOffset(hoverRegion.getOffset()); if (attr == null) { return null; } // Are we over the attribute name? IRange nameRange = attr.getNameRange(); if (nameRange != null && nameRange.contains(hoverRegion.getOffset())) { return new HTMLIndexQueryHelper().getAttribute(node.getElementName().toLowerCase(), attr.getName()); } // We must be hovering over empty space, or attribute value, show no hover return null; }
Example 19
Source File: TypeScriptEditor.java From typescript.java with MIT License | 4 votes |
public IStatus run(IProgressMonitor progressMonitor) { fProgressMonitor = progressMonitor; if (isCanceled()) { if (LinkedModeModel.hasInstalledModel(fDocument)) { // Template completion applied, remove occurrences removeOccurrenceAnnotations(); } return Status.CANCEL_STATUS; } ITextViewer textViewer = getViewer(); if (textViewer == null) return Status.CANCEL_STATUS; IDocument document = textViewer.getDocument(); if (document == null) return Status.CANCEL_STATUS; IAnnotationModel annotationModel = getAnnotationModel(); if (annotationModel == null) return Status.CANCEL_STATUS; // Add occurrence annotations int length = fPositions.length; Map annotationMap = new HashMap(length); for (int i = 0; i < length; i++) { if (isCanceled()) return Status.CANCEL_STATUS; String message; Position position = fPositions[i]; // Create & add annotation try { message = document.get(position.offset, position.length); } catch (BadLocationException ex) { // Skip this match continue; } annotationMap.put(new Annotation("org.eclipse.wst.jsdt.ui.occurrences", false, message), //$NON-NLS-1$ position); } if (isCanceled()) return Status.CANCEL_STATUS; synchronized (getLockObject(annotationModel)) { if (annotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap); } else { removeOccurrenceAnnotations(); Iterator iter = annotationMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry mapEntry = (Map.Entry) iter.next(); annotationModel.addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue()); } } fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet() .toArray(new Annotation[annotationMap.keySet().size()]); } return Status.OK_STATUS; }
Example 20
Source File: TestResultHyperlinkDetector.java From n4js with Eclipse Public License 1.0 | 4 votes |
@Override public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { IDocument document = textViewer.getDocument(); int offset = region.getOffset(); // extract relevant characters IRegion lineRegion; String candidate; try { lineRegion = document.getLineInformationOfOffset(offset); candidate = document.get(lineRegion.getOffset(), lineRegion.getLength()); } catch (BadLocationException ex) { return null; } Matcher matcher = JSStackTraceLocationText.JAVASCRIPT_STRACKTRACE_LOCATION_PATTERN.matcher(candidate); List<IHyperlink> links = new ArrayList<>(); while (matcher.find()) { JSStackTraceLocationText generatedLocation = new JSStackTraceLocationText(matcher); IRegion linkRegion = new Region( lineRegion.getOffset() + matcher.start(), matcher.end() - matcher.start()); // generatedLocation.fileName.length()); JSStackTraceLocationText originalLocation = retrieveOriginal(generatedLocation); if (originalLocation != null) { // prefer original location (e.g. n4js) links.add(new TestResultHyperlink(linkRegion, originalLocation)); if (!canShowMultipleHyperlinks) { // and do not show any other in case of single hyper links break; } } links.add(new TestResultHyperlink(linkRegion, generatedLocation)); if (!canShowMultipleHyperlinks) { break; } } if (links.isEmpty()) { return null; } IHyperlink[] hyperlinks = new IHyperlink[links.size()]; links.toArray(hyperlinks); return hyperlinks; }