/**
   * Creates a style range for the text viewer.
   *
   * @param viewer the text viewer
   * @return the new style range for the text viewer or <code>null</code>
   */
  private StyleRange createStyleRange(ITextViewer viewer) {
    StyledText text = viewer.getTextWidget();
    if (text == null || text.isDisposed()) {
      return null;
    }

    int widgetCaret = text.getCaretOffset();

    int modelCaret = 0;
    if (viewer instanceof ITextViewerExtension5) {
      ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
      modelCaret = extension.widgetOffset2ModelOffset(widgetCaret);
    } else {
      IRegion visibleRegion = viewer.getVisibleRegion();
      modelCaret = widgetCaret + visibleRegion.getOffset();
    }

    if (modelCaret >= getReplacementOffset() + getReplacementLength()) {
      return null;
    }

    int length = getReplacementOffset() + getReplacementLength() - modelCaret;

    Color foreground = getForegroundColor();
    Color background = getBackgroundColor();

    return new StyleRange(modelCaret, length, foreground, background);
  }
 private void restorePosition() {
   if (fPosition != null && !fPosition.isDeleted() && fViewer.getDocument() != null) {
     fViewer.setSelectedRange(fPosition.offset, fPosition.length);
     fViewer.revealRange(fPosition.offset, fPosition.length);
   }
   fPosition = null;
 }
  /** Select the word at the current selection. */
  protected void selectWord() {
    if (matchWord()) {

      if (fStartPos == fEndPos) fText.setSelectedRange(fStartPos, 0);
      else fText.setSelectedRange(fStartPos + 1, fEndPos - fStartPos - 1);
    }
  }
  /**
   * Compute completion proposals.
   *
   * @param viewer the viewer
   * @param documentOffset the document offset
   * @return the i completion proposal[]
   */
  @Override
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    String text;
    String prefix = "";
    PropertyLabelLexer lexer = null;
    PropertyLabelParser parser = null;
    Collection<ICompletionProposal> result = null;
    int selectionRange = 0;

    try {
      text = viewer.getDocument().get(0, documentOffset);
      lexer = new PropertyLabelLexer(new ANTLRStringStream(text));
      CommonTokenStream tokens = new CommonTokenStream(lexer);

      parser = new PropertyLabelParser(tokens, property, new SimpleStringErrorReporter());
      parser.setValidation(true);
      selectionRange = viewer.getSelectedRange().y;
      parser.label();
      modifiersUsed = parser.getModifiersUsed();
      result = computeCompletions(viewer, parser.getContext(), documentOffset, selectionRange);
    } catch (BadLocationException e) {
      e.printStackTrace();
    } catch (RuntimeException e) {
      modifiersUsed = parser.getModifiersUsed();
      prefix = getPrefix(viewer, documentOffset);
      result = computeCompletions(viewer, parser.getContext(), documentOffset, selectionRange);
    } catch (RecognitionException e) {
      modifiersUsed = parser.getModifiersUsed();
      prefix = getPrefix(viewer, documentOffset);
      result = computeCompletions(viewer, parser.getContext(), documentOffset, selectionRange);
    }

    return result.toArray(new ICompletionProposal[] {});
  }
示例#5
0
  /**
   * Implementation of the <code>IAction</code> prototype. Checks if the selected lines are all
   * commented or not and uncomments/comments them respectively.
   */
  @Override
  public void run() {
    if (fOperationTarget == null || fDocumentPartitioning == null || fPrefixesMap == null) return;

    final int operationCode;
    if (isSelectionCommented(fViewer.getSelectionProvider().getSelection()))
      operationCode = ITextOperationTarget.STRIP_PREFIX;
    else operationCode = ITextOperationTarget.PREFIX;

    Shell shell = fViewer.getTextWidget().getShell();
    if (!fOperationTarget.canDoOperation(operationCode)) {
      if (shell != null)
        MessageDialog.openError(
            shell,
            "An error occured",
            "ToggleComment_error_message=An error occurred while toggling comments."); //$NON-NLS-1$//$NON-NLS-2$
      return;
    }

    Display display = null;
    if (shell != null && !shell.isDisposed()) display = shell.getDisplay();

    BusyIndicator.showWhile(
        display,
        new Runnable() {
          public void run() {
            fOperationTarget.doOperation(operationCode);
          }
        });
  }
  /**
   * Show completions at caret position. If current position does not contain quick fixes look for
   * next quick fix on same line by moving from left to right and restarting at end of line if the
   * beginning of the line is reached.
   *
   * @see org.eclipse.jface.text.quickassist.IQuickAssistAssistant#showPossibleQuickAssists()
   */
  public String showPossibleQuickAssists() {
    fPosition = null;
    fCurrentAnnotations = null;

    if (fViewer == null || fViewer.getDocument() == null)
      // Let superclass deal with this
      return super.showPossibleQuickAssists();

    ArrayList resultingAnnotations = new ArrayList(20);
    try {
      Point selectedRange = fViewer.getSelectedRange();
      int currOffset = selectedRange.x;
      int currLength = selectedRange.y;
      boolean goToClosest = (currLength == 0);

      int newOffset =
          collectQuickFixableAnnotations(fEditor, currOffset, goToClosest, resultingAnnotations);
      if (newOffset != currOffset) {
        storePosition(currOffset, currLength);
        fViewer.setSelectedRange(newOffset, 0);
        fViewer.revealRange(newOffset, 0);
      }
    } catch (BadLocationException e) {
      JavaScriptPlugin.log(e);
    }
    fCurrentAnnotations =
        (Annotation[]) resultingAnnotations.toArray(new Annotation[resultingAnnotations.size()]);

    return super.showPossibleQuickAssists();
  }
示例#7
0
  /**
   * Inspects the context of the compilation unit around <code>completionPosition</code> and feeds
   * the collector with proposals.
   *
   * @param viewer the text viewer
   * @param completionPosition the context position in the document of the text viewer
   * @param compilationUnit the compilation unit (may be <code>null</code>)
   */
  public void complete(ITextViewer viewer, int completionPosition, IRubyScript compilationUnit) {
    IDocument document = viewer.getDocument();

    if (!(fContextType instanceof RubyScriptContextType)) return;

    Point selection = viewer.getSelectedRange();

    // remember selected text
    String selectedText = null;
    if (selection.y != 0) {
      try {
        selectedText = document.get(selection.x, selection.y);
      } catch (BadLocationException e) {
      }
    }

    RubyScriptContext context =
        ((RubyScriptContextType) fContextType)
            .createContext(document, completionPosition, selection.y, compilationUnit);
    context.setVariable("selection", selectedText); // $NON-NLS-1$
    int start = context.getStart();
    int end = context.getEnd();
    IRegion region = new Region(start, end - start);

    Template[] templates = RubyPlugin.getDefault().getTemplateStore().getTemplates();

    if (selection.y == 0) {
      for (int i = 0; i != templates.length; i++)
        if (context.canEvaluate(templates[i]))
          fProposals.add(
              new TemplateProposal(
                  templates[i],
                  context,
                  region,
                  RubyPluginImages.get(RubyPluginImages.IMG_OBJS_TEMPLATE)));

    } else {

      if (context.getKey().length() == 0) context.setForceEvaluation(true);

      boolean multipleLinesSelected = areMultipleLinesSelected(viewer);

      for (int i = 0; i != templates.length; i++) {
        Template template = templates[i];
        if (context.canEvaluate(template)
            && template.getContextTypeId().equals(context.getContextType().getId())
            && (!multipleLinesSelected && template.getPattern().indexOf($_WORD_SELECTION) != -1
                || (multipleLinesSelected
                    && template.getPattern().indexOf($_LINE_SELECTION) != -1))) {
          fProposals.add(
              new TemplateProposal(
                  templates[i],
                  context,
                  region,
                  RubyPluginImages.get(RubyPluginImages.IMG_OBJS_TEMPLATE)));
        }
      }
    }
  }
  /**
   * Select the area between the selected bracket and the closing bracket. Return true if
   * successful.
   */
  protected boolean selectBracketBlock() {
    if (matchBracketsAt()) {

      if (fStartPos == fEndPos) fText.setSelectedRange(fStartPos, 0);
      else fText.setSelectedRange(fStartPos + 1, fEndPos - fStartPos - 1);

      return true;
    }
    return false;
  }
  /**
   * Returns the difference between the baseline of the widget and the baseline as specified by the
   * font for <code>gc</code>. When drawing line numbers, the returned bias should be added to
   * obtain text lined up on the correct base line of the text widget.
   *
   * @param gc the {@code GC} to get the font metrics from
   * @param widgetLine the widget line
   * @return the baseline bias to use when drawing text that is lined up with the text widget.
   */
  private int getBaselineBias(GC gc, int widgetLine) {
    ITextViewer textViewer = getParentRuler().getTextViewer();
    int offset = textViewer.getTextWidget().getOffsetAtLine(widgetLine);
    int widgetBaseline = textViewer.getTextWidget().getBaseline(offset);

    FontMetrics fm = gc.getFontMetrics();
    int fontBaseline = fm.getAscent() + fm.getLeading();
    int baselineBias = widgetBaseline - fontBaseline;
    return Math.max(0, baselineBias);
  }
  protected boolean selectComment(int caretPos) {
    IDocument doc = fText.getDocument();
    int startPos, endPos;

    try {
      int pos = caretPos;
      char c = ' ';

      while (pos >= 0) {
        c = doc.getChar(pos);
        if (c == '\\') {
          pos -= 2;
          continue;
        }
        if (c == Character.LINE_SEPARATOR || c == '\"') {
          break;
        }
        --pos;
      }

      if (c != '\"') {
        return false;
      }

      startPos = pos;

      pos = caretPos;
      int length = doc.getLength();
      c = ' ';

      while (pos < length) {
        c = doc.getChar(pos);
        if (c == Character.LINE_SEPARATOR || c == '\"') {
          break;
        }
        ++pos;
      }
      if (c != '\"') {
        return false;
      }

      endPos = pos;

      int offset = startPos + 1;
      int len = endPos - offset;
      fText.setSelectedRange(offset, len);
      return true;
    } catch (BadLocationException x) {
    }

    return false;
  }
  private static void applyProposal(
      ICompletionProposal proposal,
      ITextViewer viewer,
      char trigger,
      int stateMask,
      final int offset) {
    Assert.isTrue(proposal instanceof ICompletionProposalExtension2);

    IRewriteTarget target = null;
    IEditingSupportRegistry registry = null;
    IEditingSupport helper =
        new IEditingSupport() {

          public boolean isOriginator(DocumentEvent event, IRegion focus) {
            return focus.getOffset() <= offset && focus.getOffset() + focus.getLength() >= offset;
          }

          public boolean ownsFocusShell() {
            return false;
          }
        };

    try {
      IDocument document = viewer.getDocument();

      if (viewer instanceof ITextViewerExtension) {
        ITextViewerExtension extension = (ITextViewerExtension) viewer;
        target = extension.getRewriteTarget();
      }

      if (target != null) target.beginCompoundChange();

      if (viewer instanceof IEditingSupportRegistry) {
        registry = (IEditingSupportRegistry) viewer;
        registry.register(helper);
      }

      ((ICompletionProposalExtension2) proposal).apply(viewer, trigger, stateMask, offset);

      Point selection = proposal.getSelection(document);
      if (selection != null) {
        viewer.setSelectedRange(selection.x, selection.y);
        viewer.revealRange(selection.x, selection.y);
      }
    } finally {
      if (target != null) target.endCompoundChange();

      if (registry != null) registry.unregister(helper);
    }
  }
  /**
   * Returns the closest IStructuredDocumentRegion for the offest and viewer.
   *
   * @param viewer
   * @param documentOffset
   * @return the closest IStructuredDocumentRegion for the offest and viewer.
   */
  public static IStructuredDocumentRegion getStructuredDocumentRegion(
      ITextViewer viewer, int documentOffset) {
    IStructuredDocumentRegion sdRegion = null;
    if (viewer == null || viewer.getDocument() == null) return null;

    int lastOffset = documentOffset;
    IStructuredDocument doc = (IStructuredDocument) viewer.getDocument();
    sdRegion = doc.getRegionAtCharacterOffset(documentOffset);
    while (sdRegion == null && lastOffset >= 0) {
      lastOffset--;
      sdRegion = doc.getRegionAtCharacterOffset(lastOffset);
    }
    return sdRegion;
  }
  public static IJavaProject findJavaProject(ITextViewer viewer) {

    if (viewer == null) return null;

    IStructuredModel existingModelForRead =
        StructuredModelManager.getModelManager().getExistingModelForRead(viewer.getDocument());

    if (existingModelForRead == null) return null;

    IJavaProject javaProject = null;
    try {
      String baseLocation = existingModelForRead.getBaseLocation();
      // 20041129 (pa) the base location changed for XML model
      // because of FileBuffers, so this code had to be updated
      // https://bugs.eclipse.org/bugs/show_bug.cgi?id=79686
      IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
      IPath filePath = new Path(baseLocation);
      IProject project = null;
      if (filePath.segmentCount() > 0) {
        project = root.getProject(filePath.segment(0));
      }
      if (project != null) {
        javaProject = JavaCore.create(project);
      }
    } catch (Exception ex) {
      MapperPlugin.getDefault().logException(ex);
    }
    return javaProject;
  }
 /*
  * @see org.eclipse.jface.text.IPainter#paint(int)
  */
 public void paint(int reason) {
   IDocument document = fTextViewer.getDocument();
   if (document == null) {
     deactivate(false);
     return;
   }
   if (!fIsActive) {
     fIsActive = true;
     fTextWidget.addPaintListener(this);
     redrawAll();
   } else if (reason == CONFIGURATION || reason == INTERNAL) {
     redrawAll();
   } else if (reason == TEXT_CHANGE) {
     // redraw current line only
     try {
       IRegion lineRegion =
           document.getLineInformationOfOffset(getDocumentOffset(fTextWidget.getCaretOffset()));
       int widgetOffset = getWidgetOffset(lineRegion.getOffset());
       int charCount = fTextWidget.getCharCount();
       int redrawLength = Math.min(lineRegion.getLength(), charCount - widgetOffset);
       if (widgetOffset >= 0 && redrawLength > 0) {
         fTextWidget.redrawRange(widgetOffset, redrawLength, true);
       }
     } catch (BadLocationException e) {
       // ignore
     }
   }
 }
  /* (non-Javadoc)
   * @see org.eclipse.jface.text.ITextHoverExtension2#getHoverInfo2(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
   */
  public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
    IJavaScriptStackFrame frame = getFrame();
    if (frame != null) {
      IDocument document = textViewer.getDocument();
      if (document != null) {
        try {
          String variableName = document.get(hoverRegion.getOffset(), hoverRegion.getLength());
          IVariable var = findLocalVariable(frame, variableName);
          if (var != null) {
            return var;
          }

          // might be in 'this'
          var = frame.getThisObject();
          try {
            IValue val = var == null ? null : var.getValue();
            if (val != null) {
              IVariable[] vars = val.getVariables();
              for (int i = 0; i < vars.length; i++) {
                if (vars[i].getName().equals(variableName)) {
                  return vars[i];
                }
              }
            }
          } catch (DebugException de) {
            return null;
          }

        } catch (BadLocationException e) {
          return null;
        }
      }
    }
    return null;
  }
示例#16
0
 /**
  * Convert mouse screen coordinates to a <code>StyledText</code> offset.
  *
  * @param x screen X-coordinate
  * @param y screen Y-coordinate
  * @param absolute if <code>true</code>, coordinates are expected to be absolute screen
  *     coordinates
  * @return text offset
  * @see StyledText#getOffsetAtLocation()
  */
 private int getOffsetAtLocation(int x, int y, boolean absolute) {
   StyledText textWidget = fViewer.getTextWidget();
   StyledTextContent content = textWidget.getContent();
   Point location;
   if (absolute) {
     location = textWidget.toControl(x, y);
   } else {
     location = new Point(x, y);
   }
   int line = (textWidget.getTopPixel() + location.y) / textWidget.getLineHeight();
   if (line >= content.getLineCount()) {
     return content.getCharCount();
   }
   int lineOffset = content.getOffsetAtLine(line);
   String lineText = content.getLine(line);
   Point endOfLine = textWidget.getLocationAtOffset(lineOffset + lineText.length());
   if (location.x >= endOfLine.x) {
     return lineOffset + lineText.length();
   }
   try {
     return textWidget.getOffsetAtLocation(location);
   } catch (IllegalArgumentException iae) {
     // we are expecting this
     return -1;
   }
 }
  protected List<IRegion> getAttributeValueRegions(ITextViewer viewer) {
    List<IRegion> regions = new ArrayList<IRegion>();
    IDocument document = viewer.getDocument();
    int startOffset = 0;
    int endOffset = document.getLength();

    IStructuredDocumentRegion sdRegion = null;

    while (startOffset < endOffset
        && (sdRegion = ContentAssistUtils.getStructuredDocumentRegion(viewer, startOffset))
            != null) {
      ITextRegionList list = sdRegion.getRegions();

      for (int i = 0; list != null && i < list.size(); i++) {
        ITextRegion region = list.get(i);
        if (region.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) {

          final int regionOffset = sdRegion.getStartOffset() + region.getStart();
          final int regionLength = region.getTextLength();

          regions.add(new Region(regionOffset, regionLength));
        }
      }
      startOffset += sdRegion.getLength();
    }

    return regions;
  }
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    List<ICompletionProposal> result = new ArrayList<ICompletionProposal>();

    try {
      IDocument document = viewer.getDocument();
      ITypedRegion partition = document.getPartition(offset);
      if (isOffsetValidForProposal(document, offset, partition.getOffset())) {
        result.add(
            new CompletionProposal("1 ", offset, 0, 2, null, "1 Heading level 1", null, null));
        result.add(
            new CompletionProposal("1.1 ", offset, 0, 4, null, "1.1 Heading level 2", null, null));
        result.add(
            new CompletionProposal(
                "1.1.1 ", offset, 0, 6, null, "1.1.1 Heading level 3", null, null));
        result.add(
            new CompletionProposal(
                "1.1.1.1 ", offset, 0, 8, null, "1.1.1.1 Heading level 4", null, null));
        result.add(
            new CompletionProposal(
                "1.1.1.1.1 ", offset, 0, 10, null, "1.1.1.1.1 Heading level 5", null, null));
        result.add(
            new CompletionProposal(
                "1.1.1.1.1.1 ", offset, 0, 12, null, "1.1.1.1.1.1 Heading level 6", null, null));
      }
    } catch (BadLocationException e) {
      CoreLog.logError("Content assist error", e);
    }

    if (result.size() > 0) {
      return result.toArray(new ICompletionProposal[result.size()]);
    }

    return null;
  }
示例#19
0
 public SpellingHelper(ISpellingSupport support, ITextViewer viewer) {
   this.support = support;
   this.viewer = viewer;
   this.control = viewer.getTextWidget();
   this.contentAdapter = new StyledTextContentAdapter();
   init(viewer);
 }
  /** Select the word at the current selection. Return true if successful, false otherwise. */
  protected boolean matchWord() {

    IDocument doc = fText.getDocument();

    try {

      int pos = fPos;
      char c;

      while (pos >= 0) {
        c = doc.getChar(pos);
        if (!Character.isJavaIdentifierPart(c)) break;
        --pos;
      }

      fStartPos = pos;

      pos = fPos;
      int length = doc.getLength();

      while (pos < length) {
        c = doc.getChar(pos);
        if (!Character.isJavaIdentifierPart(c)) break;
        ++pos;
      }

      fEndPos = pos;

      return true;

    } catch (BadLocationException x) {
    }

    return false;
  }
  private IHyperlink openModule(Node current, ITextViewer textViewer, int offset) {
    while (current != null && !(current instanceof Element)) {
      current = current.getParentNode();
    }
    if (current == null) {
      return null;
    }
    String pathUp = XmlUtils.pathUp(current, 2);
    if (!"modules/module".equals(pathUp)) { // $NON-NLS-1$
      // just in case we are in some random plugin configuration snippet..
      return null;
    }

    ITextFileBuffer buf =
        FileBuffers.getTextFileBufferManager().getTextFileBuffer(textViewer.getDocument());
    if (buf == null) {
      // for repository based poms..
      return null;
    }
    IFileStore folder = buf.getFileStore().getParent();

    String path = XmlUtils.getTextValue(current);
    final String fPath = path;
    // construct IPath for the child pom file, handle relative paths..
    while (folder != null && path.startsWith("../")) { // $NON-NLS-1$
      folder = folder.getParent();
      path = path.substring("../".length()); // $NON-NLS-1$
    }
    if (folder == null) {
      return null;
    }
    IFileStore modulePom = folder.getChild(path);
    if (!modulePom.getName().endsWith("xml")) { // $NON-NLS-1$
      modulePom = modulePom.getChild("pom.xml"); // $NON-NLS-1$
    }
    final IFileStore fileStore = modulePom;
    if (!fileStore.fetchInfo().exists()) {
      return null;
    }
    assert current instanceof IndexedRegion;
    final IndexedRegion region = (IndexedRegion) current;

    return new IHyperlink() {
      public IRegion getHyperlinkRegion() {
        return new Region(region.getStartOffset(), region.getEndOffset() - region.getStartOffset());
      }

      public String getHyperlinkText() {
        return NLS.bind(Messages.PomHyperlinkDetector_open_module, fPath);
      }

      public String getTypeLabel() {
        return "pom-module"; //$NON-NLS-1$
      }

      public void open() {
        openXmlEditor(fileStore);
      }
    };
  }
示例#22
0
 /**
  * Use hyperlink detectors to find a text viewer's hyperlinks and return the style ranges to
  * render them.
  *
  * @param textViewer
  * @param hyperlinkDetectors
  * @return the style ranges to render the detected hyperlinks
  */
 public static StyleRange[] getHyperlinkDetectorStyleRanges(
     ITextViewer textViewer, IHyperlinkDetector[] hyperlinkDetectors) {
   List<StyleRange> styleRangeList = new ArrayList<StyleRange>();
   if (hyperlinkDetectors != null && hyperlinkDetectors.length > 0) {
     for (int i = 0; i < textViewer.getTextWidget().getText().length(); i++) {
       IRegion region = new Region(i, 0);
       for (IHyperlinkDetector hyperLinkDetector : hyperlinkDetectors) {
         IHyperlink[] hyperlinks = hyperLinkDetector.detectHyperlinks(textViewer, region, true);
         if (hyperlinks != null) {
           for (IHyperlink hyperlink : hyperlinks) {
             StyleRange hyperlinkStyleRange =
                 new StyleRange(
                     hyperlink.getHyperlinkRegion().getOffset(),
                     hyperlink.getHyperlinkRegion().getLength(),
                     Display.getDefault().getSystemColor(SWT.COLOR_BLUE),
                     Display.getDefault().getSystemColor(SWT.COLOR_WHITE));
             hyperlinkStyleRange.underline = true;
             styleRangeList.add(hyperlinkStyleRange);
           }
         }
       }
     }
   }
   StyleRange[] styleRangeArray = new StyleRange[styleRangeList.size()];
   styleRangeList.toArray(styleRangeArray);
   return styleRangeArray;
 }
  @Override
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    ICompletionProposal[] allProposals = super.computeCompletionProposals(viewer, offset);
    List<ICompletionProposal> validProposals =
        new ArrayList<ICompletionProposal>(allProposals.length);
    for (ICompletionProposal proposal : allProposals) {
      if (proposal instanceof ICompletionProposalExtension2) {
        if (!((ICompletionProposalExtension2) proposal)
            .validate(viewer.getDocument(), offset, null)) {
          continue;
        }
      }
      validProposals.add(proposal);
    }
    Collections.sort(
        validProposals,
        new Comparator<ICompletionProposal>() {

          public int compare(ICompletionProposal o1, ICompletionProposal o2) {
            return String.CASE_INSENSITIVE_ORDER.compare(
                o1.getDisplayString(), o2.getDisplayString());
          }
        });
    return validProposals.toArray(new ICompletionProposal[validProposals.size()]);
  }
示例#24
0
  /* (non-Javadoc)
   * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
   */
  public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    ScriptStackFrame frame = getFrame();
    if (frame == null) {
      return null;
    }
    IDocument document = textViewer.getDocument();
    if (document == null) {
      return null;
    }
    try {
      String str =
          TextUtilities.getContentType(
              document,
              IDocumentExtension3.DEFAULT_PARTITIONING,
              hoverRegion.getOffset() + 1,
              true);

      String variableName = document.get(hoverRegion.getOffset(), hoverRegion.getLength());

      if (JSPartitionScanner.JS_KEYWORD.equals(str) && !"this".equals(variableName)) // $NON-NLS-1$
      {
        return null;
      }
      ScriptValue var = ((ScriptDebugTarget) frame.getDebugTarget()).evaluate(frame, variableName);
      if (var != null) {
        return getVariableText(var);
      }
    } catch (BadLocationException e) {
      return null;
    }
    return null;
  }
  // similar to
  // org.eclipse.jdt.internal.ui.text.correction.ModifierCorrectionSubProcessor.removeOverrideAnnotationProposal(..)
  public void removeDeprecatedAnnotation(
      IDocument document, ICompilationUnit cu, BodyDeclaration decl) {
    Annotation annot = findAnnotation(decl.modifiers());
    if (annot != null) {
      ASTRewrite rewrite = ASTRewrite.create(annot.getAST());
      rewrite.remove(annot, null);

      callASTRewriteCorrectionProposal(getDisplayString(), cu, rewrite, 6, getImage(), document);

      ITextViewer viewer = getViewer(JavaPlugin.getActivePage().getActiveEditor());
      ITrackedNodePosition trackPos = rewrite.track(decl);
      if (trackPos != null && viewer != null) {
        viewer.setSelectedRange(trackPos.getStartPosition(), 0);
      }
    }
  }
 /*
  * @see org.eclipse.ui.texteditor.AbstractTextEditor#isVisible(ISourceViewer, int, int)
  */
 private /*static*/ final boolean isVisible(ITextViewer viewer, int offset, int length) {
   if (viewer instanceof ITextViewerExtension5) {
     ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
     IRegion overlap = extension.modelRange2WidgetRange(new Region(offset, length));
     return overlap != null;
   }
   return viewer.overlapsWithVisibleRegion(offset, length);
 }
 /**
  * @param textViewer check to see if this viewer is empty
  * @return <code>true</code> if there is no text or it's all white space, <code>false</code>
  *     otherwise
  */
 public static boolean isViewerEmpty(ITextViewer textViewer) {
   boolean isEmpty = false;
   String text = textViewer.getTextWidget().getText();
   if ((text == null) || ((text != null) && text.trim().equals(""))) { // $NON-NLS-1$
     isEmpty = true;
   }
   return isEmpty;
 }
示例#28
0
 public void uninstall() {
   if (isInstalled) {
     textViewer.removeTextInputListener(textInputListener);
     isInstalled = false;
     if (documentListener != null) {
       if (textViewer instanceof ISourceViewerExtension4) {
         ContentAssistantFacade facade =
             ((ISourceViewerExtension4) textViewer).getContentAssistantFacade();
         facade.removeCompletionListener(documentListener);
       }
       if (textViewer.getDocument() instanceof IXtextDocument) {
         ((IXtextDocument) textViewer.getDocument())
             .removeXtextDocumentContentObserver(documentListener);
       }
     }
   }
 }
 @SuppressWarnings("unchecked")
 private List<ScriptVariable> getScriptVariables(final ITextViewer viewer) {
   final List<ScriptVariable> result = new ArrayList<ScriptVariable>();
   final List<ScriptVariable> nodes =
       (List<ScriptVariable>)
           viewer.getTextWidget().getData(GroovyViewer.PROCESS_VARIABLES_DATA_KEY);
   if (nodes != null) {
     result.addAll(nodes);
   }
   final List<ScriptVariable> providedScriptVariables =
       (List<ScriptVariable>)
           viewer.getTextWidget().getData(GroovyViewer.BONITA_KEYWORDS_DATA_KEY);
   if (providedScriptVariables != null) {
     result.addAll(providedScriptVariables);
   }
   return result;
 }
示例#30
0
  /**
   * Returns <code>true</code> if one line is completely selected or if multiple lines are selected.
   * Being completely selected means that all characters except the new line characters are
   * selected.
   *
   * @return <code>true</code> if one or multiple lines are selected
   * @since 2.1
   */
  private boolean areMultipleLinesSelected(ITextViewer viewer) {
    if (viewer == null) return false;

    Point s = viewer.getSelectedRange();
    if (s.y == 0) return false;

    try {

      IDocument document = viewer.getDocument();
      int startLine = document.getLineOfOffset(s.x);
      int endLine = document.getLineOfOffset(s.x + s.y);
      IRegion line = document.getLineInformation(startLine);
      return startLine != endLine || (s.x == line.getOffset() && s.y == line.getLength());

    } catch (BadLocationException x) {
      return false;
    }
  }